code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def serveUpcoming(self, request): """Upcoming events list view.""" myurl = self.get_url(request) today = timezone.localdate() monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[today.year, today.month]) weekNum = gregor...
Upcoming events list view.
def consumer(self, fn): """Consumer decorator :param fn: coroutine consumer function Example: >>> api = StreamingAPI('my_service_key') >>> stream = api.get_stream() >>> @stream.consumer >>> @asyncio.coroutine >>> def handle_event(payload): >>> ...
Consumer decorator :param fn: coroutine consumer function Example: >>> api = StreamingAPI('my_service_key') >>> stream = api.get_stream() >>> @stream.consumer >>> @asyncio.coroutine >>> def handle_event(payload): >>> print(payload)
def new_mapping(self, lineup, station, channel, channelMinor, validFrom, validTo, onAirFrom, onAirTo): """Callback run for each new mapping within a lineup""" if self.__v_mapping: # [Mapping: FL09567:X, 11097, 45, None, 2010-06-29 00:00:00.00, None, None, None] ...
Callback run for each new mapping within a lineup
def register_token(self, *args, **kwargs): """ Register token Accepts: - token_name [string] - contract_address [hex string] - blockchain [string] token's blockchain (QTUMTEST, ETH) Returns dictionary with following fields: - success [Boo...
Register token Accepts: - token_name [string] - contract_address [hex string] - blockchain [string] token's blockchain (QTUMTEST, ETH) Returns dictionary with following fields: - success [Bool]
def safe_remove_file(filename, app): """ Removes a given resource file from builder resources. Needed mostly during test, if multiple sphinx-build are started. During these tests js/cass-files are not cleaned, so a css_file from run A is still registered in run B. :param filename: filename to remov...
Removes a given resource file from builder resources. Needed mostly during test, if multiple sphinx-build are started. During these tests js/cass-files are not cleaned, so a css_file from run A is still registered in run B. :param filename: filename to remove :param app: app object :return: None
def ParseLines(lines, message, allow_unknown_extension=False, allow_field_number=False): """Parses an text representation of a protocol message into a message. Args: lines: An iterable of lines of a message's text representation. message: A protocol buffer message to merge into. allow_un...
Parses an text representation of a protocol message into a message. Args: lines: An iterable of lines of a message's text representation. message: A protocol buffer message to merge into. allow_unknown_extension: if True, skip over missing extensions and keep parsing allow_field_number: if True...
async def read(cls, node): """Get list of `Bcache`'s for `node`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" ...
Get list of `Bcache`'s for `node`.
def get_dev_vlans(auth, url, devid=None, devip=None): """Function takes input of devID to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devi...
Function takes input of devID to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devId as the only input parameter :param...
def check_docker_access(self): """ Creates a :class:`DockerClient <docker.client.DockerClient>` for the instance and checks the connection. :raise BuildError: If docker isn't accessible by the current user. """ try: if self.client is None: self.client = docke...
Creates a :class:`DockerClient <docker.client.DockerClient>` for the instance and checks the connection. :raise BuildError: If docker isn't accessible by the current user.
def _register_endpoints(self, providers): """ See super class satosa.frontends.base.FrontendModule#register_endpoints :type providers: list[str] :rtype list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))] | list[(str, (satosa.context.Context) -> s...
See super class satosa.frontends.base.FrontendModule#register_endpoints :type providers: list[str] :rtype list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))] | list[(str, (satosa.context.Context) -> satosa.response.Response)] :param providers: A list wit...
def p_joinx(self,t): # todo: support join types http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html#QUERIES-JOIN """joinx : fromtable jointype fromtable | fromtable jointype fromtable kw_on expression | fromtable jointype fromtable kw_using '(' namelist ')' """...
joinx : fromtable jointype fromtable | fromtable jointype fromtable kw_on expression | fromtable jointype fromtable kw_using '(' namelist ')'
def prob(self, comparison_vectors, return_type=None): """Compute the probabilities for each record pair. For each pair of records, estimate the probability of being a match. Parameters ---------- comparison_vectors : pandas.DataFrame The dataframe with comparison ve...
Compute the probabilities for each record pair. For each pair of records, estimate the probability of being a match. Parameters ---------- comparison_vectors : pandas.DataFrame The dataframe with comparison vectors. return_type : str Deprecated. (default...
def del_layer(self, layer_num): """ Delete mesh layer """ del self.layer_stack[layer_num] # Adjust current layer if needed if layer_num < self.current_layer(): self.set_current_layer(self.current_layer() - 1) return None
Delete mesh layer
def create(cls, statement_format, date_start, date_end, monetary_account_id=None, regional_format=None, custom_headers=None): """ :type user_id: int :type monetary_account_id: int :param statement_format: The format type of statement. Allowed values: ...
:type user_id: int :type monetary_account_id: int :param statement_format: The format type of statement. Allowed values: MT940, CSV, PDF. :type statement_format: str :param date_start: The start date for making statements. :type date_start: str :param date_end: Th...
def fetch(self, url): """ Get the feed content using 'requests' """ try: r = requests.get(url, timeout=self.timeout) except requests.exceptions.Timeout: if not self.safe: raise else: return None ...
Get the feed content using 'requests'
def doParseXMLData( self ): """This function parses the XML output of FileMaker.""" parser = xml2obj.Xml2Obj() # Not valid document comming from FMServer if self.data[-6:] == '</COL>': self.data += '</ROW></RESULTSET></FMPXMLRESULT>' xobj = parser.ParseString( self.data ) try: el = xobj.getElemen...
This function parses the XML output of FileMaker.
def getTaskInfos(self): """ .. note:: Experimental Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage, ordered by partition ID. .. versionadded:: 2.4.0 """ if self._port is None or self._secret is None: raise Exception("Not supporte...
.. note:: Experimental Returns :class:`BarrierTaskInfo` for all tasks in this barrier stage, ordered by partition ID. .. versionadded:: 2.4.0
def spawn(self, actor, aid=None, **params): '''Spawn a new actor from ``actor``. ''' aid = aid or create_aid() future = actor.send('arbiter', 'spawn', aid=aid, **params) return actor_proxy_future(aid, future)
Spawn a new actor from ``actor``.
def from_str(cls, s): """Construct an import object from a string.""" ast_obj = ast.parse(s).body[0] if not isinstance(ast_obj, cls._expected_ast_type): raise AssertionError( 'Expected ast of type {!r} but got {!r}'.format( cls._expected_ast_type, ...
Construct an import object from a string.
def lower_folded_coerce_types_into_filter_blocks(folded_ir_blocks): """Lower CoerceType blocks into "INSTANCEOF" Filter blocks. Indended for folded IR blocks.""" new_folded_ir_blocks = [] for block in folded_ir_blocks: if isinstance(block, CoerceType): new_block = convert_coerce_type_to_...
Lower CoerceType blocks into "INSTANCEOF" Filter blocks. Indended for folded IR blocks.
def is_builtin_name(name): """For example, __foo__ or __bar__.""" if name.startswith('__') and name.endswith('__'): return ALL_LOWER_CASE_RE.match(name[2:-2]) is not None return False
For example, __foo__ or __bar__.
def serialized_task(self, task: Task) -> Tuple[str, str]: """ Returns the name of the task definition file and its contents. """ return f"{task.hash}.json", task.json
Returns the name of the task definition file and its contents.
def price(usr, item, searches = 2, method = "AVERAGE", deduct = 0): """ Searches the shop wizard for given item and determines price with given method Searches the shop wizard x times (x being number given in searches) for the given item and collects the lowest price from each result. U...
Searches the shop wizard for given item and determines price with given method Searches the shop wizard x times (x being number given in searches) for the given item and collects the lowest price from each result. Uses the given pricing method to determine and return the price of the it...
def calculate_width_and_height(url_parts, options): '''Appends width and height information to url''' width = options.get('width', 0) has_width = width height = options.get('height', 0) has_height = height flip = options.get('flip', False) flop = options.get('flop', False) if flip: ...
Appends width and height information to url
def SLOAD(self, offset): """Load word from storage""" storage_address = self.address self._publish('will_evm_read_storage', storage_address, offset) value = self.world.get_storage_data(storage_address, offset) self._publish('did_evm_read_storage', storage_address, offset, value) ...
Load word from storage
def expect_keyword(lexer: Lexer, value: str) -> Token: """Expect the next token to be a given keyword. If the next token is a given keyword, return that token after advancing the lexer. Otherwise, do not change the parser state and throw an error. """ token = lexer.token if token.kind == TokenK...
Expect the next token to be a given keyword. If the next token is a given keyword, return that token after advancing the lexer. Otherwise, do not change the parser state and throw an error.
def start_instance(self, instance): """ Starts a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'running'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
Starts a single instance. :param str instance: A Yamcs instance name.
def main(port=4118, parentpid=None): """Main entry point. Parse command line options and start up a server.""" if "LDTP_DEBUG" in os.environ: _ldtp_debug = True else: _ldtp_debug = False _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None) if _ldtp_debug: print("Parent ...
Main entry point. Parse command line options and start up a server.
def get_user_by_key(app, key): """ An SQLAlchemy User getting function. Get a user by public key. :param str key: the public key the user belongs to """ user = ses.query(um.User).join(um.UserKey).filter(um.UserKey.key==key).first() return user
An SQLAlchemy User getting function. Get a user by public key. :param str key: the public key the user belongs to
def step_size(self, t0, t1=None): ''' Return the time in seconds for each step. Requires that we know a time relative to which we should calculate to account for variable length intervals (e.g. February) ''' tb0 = self.to_bucket( t0 ) if t1: tb1 = self.to_bucket( t1, steps=1 ) # NOTE: ...
Return the time in seconds for each step. Requires that we know a time relative to which we should calculate to account for variable length intervals (e.g. February)
def findXScreens(self): qapp = QtCore.QCoreApplication.instance() if not qapp: # QApplication has not been started return screens = qapp.screens() """ let's find out which screens are virtual screen, siblings: One big virtual desktop: ...
let's find out which screens are virtual screen, siblings: One big virtual desktop: A [A, B, C] B [A, B, C] C [A, B, C] A & B in one xscreen, C in another: A [A, B] B [A, B] C [C]
def do_edit(self, line): """edit FILE Copies the file locally, launches an editor to edit the file. When the editor exits, if the file was modified then its copied back. You can specify the editor used with the --editor command line option when you start ...
edit FILE Copies the file locally, launches an editor to edit the file. When the editor exits, if the file was modified then its copied back. You can specify the editor used with the --editor command line option when you start rshell, or by using the VISUAL or ED...
def _escaped_token_to_subtoken_strings(self, escaped_token): """ Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings. """ # NOTE: This algor...
Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings.
def InitFromApiFlow(self, f, cron_job_id=None): """Shortcut method for easy legacy cron jobs support.""" if f.flow_id: self.run_id = f.flow_id elif f.urn: self.run_id = f.urn.Basename() self.started_at = f.started_at self.cron_job_id = cron_job_id flow_state_enum = api_plugins_flow....
Shortcut method for easy legacy cron jobs support.
def get_approval_by_id(self, issue_id_or_key, approval_id): """ Get an approval for a given approval ID :param issue_id_or_key: str :param approval_id: str :return: """ url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_key, approval_id) ...
Get an approval for a given approval ID :param issue_id_or_key: str :param approval_id: str :return:
def _transition(self, duration, hue=None, brightness=None): """ Transition. :param duration: Time to transition. :param hue: Transition to this hue. :param brightness: Transition to this brightness. """ # Calculate brightness steps. b_steps = 0 if brightn...
Transition. :param duration: Time to transition. :param hue: Transition to this hue. :param brightness: Transition to this brightness.
def apply_T12(word): '''There is a syllable boundary within a VV sequence of two nonidentical vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].''' WORD = word offset = 0 for vv in new_vv(WORD): # import pdb; pdb.set_trace() seq = vv.group(1) if not is_diph...
There is a syllable boundary within a VV sequence of two nonidentical vowels that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].
def _type_priority(ifo, ftype, trend=None): """Prioritise the given GWF type based on its name or trend status. This is essentially an ad-hoc ordering function based on internal knowledge of how LIGO does GWF type naming. """ # if looking for a trend channel, prioritise the matching type for tr...
Prioritise the given GWF type based on its name or trend status. This is essentially an ad-hoc ordering function based on internal knowledge of how LIGO does GWF type naming.
def app_to_context(self, context): """Return a context encoded tag.""" if self.tagClass != Tag.applicationTagClass: raise ValueError("application tag required") # application tagged boolean now has data if (self.tagNumber == Tag.booleanAppTag): return ContextTag(...
Return a context encoded tag.
def reserve_position(fp, fmt='I'): """ Reserves the current position for write. Use with `write_position`. :param fp: file-like object :param fmt: format of the reserved position :return: the position """ position = fp.tell() fp.seek(struct.calcsize(str('>' + fmt)), 1) return p...
Reserves the current position for write. Use with `write_position`. :param fp: file-like object :param fmt: format of the reserved position :return: the position
def save_token(self, user, token): """Save the token on the config file.""" self.config.set('auth', 'user', user) self.config.set('auth', 'token', token) # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser(allow_no_value=True) ...
Save the token on the config file.
def group(self): """ Returns the periodic table group of the element. """ z = self.Z if z == 1: return 1 if z == 2: return 18 if 3 <= z <= 18: if (z - 2) % 8 == 0: return 18 elif (z - 2) % 8 <= 2: ...
Returns the periodic table group of the element.
def cosh(x): """ Hyperbolic cosine """ if isinstance(x, UncertainFunction): mcpts = np.cosh(x._mcpts) return UncertainFunction(mcpts) else: return np.cosh(x)
Hyperbolic cosine
def _get_precision_scale(self, number): """ :param number: :return: tuple(precision, scale, decimal_number) """ try: decimal_num = Decimal(number) except InvalidOperation: raise Invalid(self.msg or 'Value must be a number enclosed with string') ...
:param number: :return: tuple(precision, scale, decimal_number)
def get_nearest_successors(self, type_measurement): """! @brief Find pair of nearest successors of the node in line with measurement type. @param[in] type_measurement (measurement_type): Measurement type that is used for obtaining nearest successors. @return (list...
! @brief Find pair of nearest successors of the node in line with measurement type. @param[in] type_measurement (measurement_type): Measurement type that is used for obtaining nearest successors. @return (list) Pair of nearest successors represented by list.
def _configure_using_fluent_definition(self): """ Configure the console command using a fluent definition. """ definition = Parser.parse(self.signature) self._config.set_name(definition["name"]) for name, flags, description, default in definition["arguments"]: ...
Configure the console command using a fluent definition.
def _listify(collection): """This is a workaround where Collections are no longer iterable when using JPype.""" new_list = [] for index in range(len(collection)): new_list.append(collection[index]) return new_list
This is a workaround where Collections are no longer iterable when using JPype.
def override_locale(self, locale: str = locales.EN, ) -> Generator['BaseDataProvider', None, None]: """Context manager which allows overriding current locale. Temporarily overrides current locale for locale-dependent providers. :param locale: Locale. :re...
Context manager which allows overriding current locale. Temporarily overrides current locale for locale-dependent providers. :param locale: Locale. :return: Provider with overridden locale.
def filter_params(self, src_mod): """ Remove params uneeded by source_model """ # point and area related params STRIKE_PARAMS[src_mod.num_np:] = [] DIP_PARAMS[src_mod.num_np:] = [] RAKE_PARAMS[src_mod.num_np:] = [] NPW_PARAMS[src_mod.num_np:] = [] ...
Remove params uneeded by source_model
def _getMetadata(self, key): """_getMetadata(self, key) -> char *""" if self.isClosed: raise ValueError("operation illegal for closed doc") return _fitz.Document__getMetadata(self, key)
_getMetadata(self, key) -> char *
def _unicode(self): '''This returns a printable representation of the screen as a unicode string (which, under Python 3.x, is the same as 'str'). The end of each screen line is terminated by a newline.''' return u'\n'.join ([ u''.join(c) for c in self.w ])
This returns a printable representation of the screen as a unicode string (which, under Python 3.x, is the same as 'str'). The end of each screen line is terminated by a newline.
def getInferenceTypeFromLabel(cls, label): """ Extracts the PredictionKind (temporal vs. nontemporal) from the given metric label. :param label: (string) for a metric spec generated by :meth:`getMetricLabel` :returns: (:class:`~nupic.frameworks.opf.opf_utils.InferenceType`) """ ...
Extracts the PredictionKind (temporal vs. nontemporal) from the given metric label. :param label: (string) for a metric spec generated by :meth:`getMetricLabel` :returns: (:class:`~nupic.frameworks.opf.opf_utils.InferenceType`)
def scale_back_batch(self, bboxes_in, scores_in): """ Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox """ if bboxes_in.device == torch.device("cpu"): self.dboxes = self.dboxes.cpu() self.dboxes_xywh = self.d...
Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox
def predict(self, X): """Returns predictions of input test cases.""" return self.__cost(self.__unroll(self.__thetas), 0, np.matrix(X))
Returns predictions of input test cases.
def _get_image_size(self, image_path): """Return disk size in bytes""" command = 'du -b %s' % image_path (rc, output) = zvmutils.execute(command) if rc: msg = ("Error happened when executing command du -b with" "reason: %s" % output) LOG.error(m...
Return disk size in bytes
def retrieve_approver_email_list(self, domain, product_id): """Retrieve the list of allowed approver email addresses.""" response = self.request(E.retrieveApproverEmailListSslCertRequest( E.domain(domain), E.productId(product_id) )) return [str(i) for i in respo...
Retrieve the list of allowed approver email addresses.
def standard_kinetics(target, quantity, prefactor, exponent): r""" """ X = target[quantity] A = target[prefactor] b = target[exponent] r = A*(X**b) S1 = A*b*(X**(b - 1)) S2 = A*(1 - b)*(X**b) values = {'S1': S1, 'S2': S2, 'rate': r} return values
r"""
def update_geometry(self): """ Updates the Widget geometry. :return: Method success. :rtype: bool """ self.setGeometry(self.__editor.contentsRect().left(), self.__editor.contentsRect().top(), self.get_width(), ...
Updates the Widget geometry. :return: Method success. :rtype: bool
def returner(ret): ''' Insert minion return data into the sqlite3 database ''' log.debug('sqlite3 returner <returner> called with data: %s', ret) conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, id, fun_args, date, full_ret, success) ...
Insert minion return data into the sqlite3 database
def make_call_positionals(stack_builders, count): """ Make the args entry for an ast.Call node. """ out = [make_expr(stack_builders) for _ in range(count)] out.reverse() return out
Make the args entry for an ast.Call node.
def lock_access(repository_path, callback): """ Synchronise access to the user file between processes, this specifies which user is allowed write access at the current time """ with open(cpjoin(repository_path, 'lock_file'), 'w') as fd: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB...
Synchronise access to the user file between processes, this specifies which user is allowed write access at the current time
def _load_from_file(self, filename): """Find filename in tar, and load it""" if filename in self.fdata: return self.fdata[filename] else: filepath = find_in_tarball(self.tarloc, filename) return read_from_tarball(self.tarloc, filepath)
Find filename in tar, and load it
def get_weekly_chart_dates(self): """Returns a list of From and To tuples for the available charts.""" doc = self._request(self.ws_prefix + ".getWeeklyChartList", True) seq = [] for node in doc.getElementsByTagName("chart"): seq.append((node.getAttribute("from"), node.getAt...
Returns a list of From and To tuples for the available charts.
def off(self): """Send an OFF message to device group.""" off_command = ExtendedSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00, self._udata) off_command.set_checksum() self._send_method(off_command, self._off_message_...
Send an OFF message to device group.
def bqsr_table(data): """Generate recalibration tables as inputs to BQSR. """ in_file = dd.get_align_bam(data) out_file = "%s-recal-table.txt" % utils.splitext_plus(in_file)[0] if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: as...
Generate recalibration tables as inputs to BQSR.
def p_empty_statement(self, p): """empty_statement : SEMI""" p[0] = self.asttypes.EmptyStatement(p[1]) p[0].setpos(p)
empty_statement : SEMI
def write_json_document(title, body): """ `title` - Name of the file to write. `body` - Python datastructure representing the document. This method handles transforming the body into a proper json string, and then writing the file to disk. """ if not title.endswith('.json'): title +...
`title` - Name of the file to write. `body` - Python datastructure representing the document. This method handles transforming the body into a proper json string, and then writing the file to disk.
def securityHandler(self, value): """ sets the security handler """ if isinstance(value, BaseSecurityHandler): if isinstance(value, security.AGOLTokenSecurityHandler): self._securityHandler = value elif isinstance(value, security.OAuthSecurityHandler): ...
sets the security handler
def Ax(self): """Compute a stack of skew-symmetric matrices which can be multiplied by 'b' to get the cross product. See: http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication """ # 0 -self.a3 self.a2 # self.a3 0 -self.a1 ...
Compute a stack of skew-symmetric matrices which can be multiplied by 'b' to get the cross product. See: http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication
def get_comments(self) -> Iterator[PostComment]: r"""Iterate over all comments of the post. Each comment is represented by a PostComment namedtuple with fields text (string), created_at (datetime), id (int), owner (:class:`Profile`) and answers (:class:`~typing.Iterator`\ [:class:`PostCommentAn...
r"""Iterate over all comments of the post. Each comment is represented by a PostComment namedtuple with fields text (string), created_at (datetime), id (int), owner (:class:`Profile`) and answers (:class:`~typing.Iterator`\ [:class:`PostCommentAnswer`]) if available.
def _note_reply_pending(self, option, state): """Record the status of requested Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].reply_pending = state
Record the status of requested Telnet options.
def new(params, event_shape=(), dtype=None, validate_args=False, name=None): """Create the distribution instance from a `params` vector.""" with tf.compat.v1.name_scope(name, 'IndependentBernoulli', [params, event_shape]): params = tf.convert_to_tensor(value=params, name='...
Create the distribution instance from a `params` vector.
def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
Verifies the value is between 1 and 9 inclusively.
def get_config(self): """ Currently only contains the "config" member, which is a string containing the config file as loaded by i3 most recently. :rtype: ConfigReply """ data = self.message(MessageType.GET_CONFIG, '') return json.loads(data, object_hook=ConfigRe...
Currently only contains the "config" member, which is a string containing the config file as loaded by i3 most recently. :rtype: ConfigReply
def excute_query(query, db=None, flags=None, use_sudo=False, **kwargs): """Execute remote psql query.""" flags = flags or u'' if db: flags = u"%s -d %s" % (flags, db) command = u'psql %s -c "%s"' % (flags, query) if use_sudo: sudo(command, user='postgres', **kwargs) else: ...
Execute remote psql query.
def get_serializer_class(self, view, method_func): """ Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class """ if hasattr(method_func, 'request_serializer'): return getattr(method_f...
Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevan...
Return a json dictionary representing this model.
def get_basis(name, elements=None, version=None, fmt=None, uncontract_general=False, uncontract_spdf=False, uncontract_segmented=False, make_general=False, optimize_general=False, data_dir=None,...
Obtain a basis set This is the main function for getting basis set information. This function reads in all the basis data and returns it either as a string or as a python dictionary. Parameters ---------- name : str Name of the basis set. This is not case sensitive. elements : str ...
def get_file_contents_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Returns the string contents of a file, or of a BLOB. """ binary_contents = get_file_contents(filename=filename, blob=blob) # 1. Try the encoding the user ...
Returns the string contents of a file, or of a BLOB.
def get_type(mime=None, ext=None): """ Returns the file type instance searching by MIME type or file extension. Args: ext: file extension string. E.g: jpg, png, mp4, mp3 mime: MIME string. E.g: image/jpeg, video/mpeg Returns: The matched file type instance. Otherwise None. ...
Returns the file type instance searching by MIME type or file extension. Args: ext: file extension string. E.g: jpg, png, mp4, mp3 mime: MIME string. E.g: image/jpeg, video/mpeg Returns: The matched file type instance. Otherwise None.
def publ(name, cfg): """ Create a Flask app and configure it for use with Publ """ config.setup(cfg) app = _PublApp(name, template_folder=config.template_folder, static_folder=config.static_folder, static_url_path=config.static_url_path) for ro...
Create a Flask app and configure it for use with Publ
def file_modified_time(file_name) -> pd.Timestamp: """ File modified time in python Args: file_name: file name Returns: pd.Timestamp """ return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name)))
File modified time in python Args: file_name: file name Returns: pd.Timestamp
def get_default_task(self): """ Returns the default task if there is only one """ default_tasks = list(filter(lambda task: task.default, self.values())) if len(default_tasks) == 1: return default_tasks[0]
Returns the default task if there is only one
def get_map_url(self, mapsource, grid_coords): """ Get URL to a map region. """ return self.get_abs_url( "/maps/{}/{}/{}/{}.kml".format(mapsource.id, grid_coords.zoom, grid_coords.x, grid_coords.y))
Get URL to a map region.
def has_in_watched(self, watched): """ :calls: `GET /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: bool """ assert isinstance(watched, github.Repository.Repository), watch...
:calls: `GET /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: bool
def _set_name(self, v, load=False): """ Setter method for name, mapped from YANG variable /rbridge_id/event_handler/activate/name (list) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable...
Setter method for name, mapped from YANG variable /rbridge_id/event_handler/activate/name (list) If this variable is read-only (config: false) in the source YANG file, then _set_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_name(...
def uncache(self): """ Disable in-memory caching (Spark only). """ if self.mode == 'spark': self.values.unpersist() return self else: notsupported(self.mode)
Disable in-memory caching (Spark only).
def _last_commit(self): """ Retrieve the most recent commit message (with ``svn log -l1``) Returns: tuple: (datestr, (revno, user, None, desc)) :: $ svn log -l1 ------------------------------------------------------------------------ r25701 | bhendrix | 2010-08-02 12:14:25 ...
Retrieve the most recent commit message (with ``svn log -l1``) Returns: tuple: (datestr, (revno, user, None, desc)) :: $ svn log -l1 ------------------------------------------------------------------------ r25701 | bhendrix | 2010-08-02 12:14:25 -0500 (Mon, 02 Aug 2010) | 1 line added sel...
def sub(self, repl): """ Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") ...
Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") print(make_html.transformString("h1:ma...
def append_responder(self, matcher, *args, **kwargs): """Add a responder of last resort. Like `.autoresponds`, but instead of adding a responder to the top of the stack, add it to the bottom. This responder will be called if no others match. """ return self._insert_respo...
Add a responder of last resort. Like `.autoresponds`, but instead of adding a responder to the top of the stack, add it to the bottom. This responder will be called if no others match.
def parse_dis_tree(self, dis_tree, indent=0): """parse a *.dis ParentedTree into this document graph""" tree_type = get_tree_type(dis_tree) assert tree_type in SUBTREE_TYPES if tree_type == 'Root': # replace generic root node with tree root old_root_id = self.root...
parse a *.dis ParentedTree into this document graph
def get_mining_contracts(): """ Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., '...
Get all the mining contracts information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining contracts data is available: coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ..., 'B...
def del_alias(self, alias): """ Delete an alias from the registry. The blobs it points to won't be deleted. Use :meth:`del_blob` for that. .. Note:: On private registry, garbage collection might need to be run manually; see: https://docs.docker.com/registry/garbage-collect...
Delete an alias from the registry. The blobs it points to won't be deleted. Use :meth:`del_blob` for that. .. Note:: On private registry, garbage collection might need to be run manually; see: https://docs.docker.com/registry/garbage-collection/ :param alias: Alias name. ...
def oracle_eval(command): """ Retrieve password from the given command """ p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() if p.returncode == 0: return p.stdout.readline().strip().decode('utf-8') else: die( "Erro...
Retrieve password from the given command
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): """ The how well do the features plus a constant base rate sum up to the model output. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_t...
The how well do the features plus a constant base rate sum up to the model output.
def get_real_data(self): """ Grab actual data from the system """ ret = [] username = os.environ.get('USER') if username: ret.append(username) editor = os.environ.get('EDITOR') if editor: editor = editor.split('/')[-1] ...
Grab actual data from the system
async def service_observer(self, limit) -> int: """ Service the observer's inBox and outBox :return: the number of messages successfully serviced """ if not self.isReady(): return 0 return await self._observer.serviceQueues(limit)
Service the observer's inBox and outBox :return: the number of messages successfully serviced
def FromBinary(cls, record_data, record_count=1): """Create an UpdateRecord subclass from binary record data. This should be called with a binary record blob (NOT including the record type header) and it will decode it into a SetConstantRecord. Args: record_data (bytearray)...
Create an UpdateRecord subclass from binary record data. This should be called with a binary record blob (NOT including the record type header) and it will decode it into a SetConstantRecord. Args: record_data (bytearray): The raw record data that we wish to parse i...
def get(self, request, bot_id, hook_id, id, format=None): """ Get recipient by id --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated """ bot = self.get_bot(bot_id, request.user) ho...
Get recipient by id --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated
def modifyBits(inputVal, maxChanges): """ Modifies up to maxChanges number of bits in the inputVal """ changes = np.random.random_integers(0, maxChanges, 1)[0] if changes == 0: return inputVal inputWidth = len(inputVal) whatToChange = np.random.random_integers(0, 41, changes) runningIndex = -1 n...
Modifies up to maxChanges number of bits in the inputVal