code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def mme_nodes(mme_base_url, token):
"""Return the available MatchMaker nodes
Args:
mme_base_url(str): base URL of MME service
token(str): MME server authorization token
Returns:
nodes(list): a list of node disctionaries
"""
nodes = []
if not mme_base_url or not token:
... | Return the available MatchMaker nodes
Args:
mme_base_url(str): base URL of MME service
token(str): MME server authorization token
Returns:
nodes(list): a list of node disctionaries |
def _to_json(uniq):
"""
Serializes a MOC to the JSON format.
Parameters
----------
uniq : `~numpy.ndarray`
The array of HEALPix cells representing the MOC to serialize.
Returns
-------
result_json : {str : [int]}
A dictionary of H... | Serializes a MOC to the JSON format.
Parameters
----------
uniq : `~numpy.ndarray`
The array of HEALPix cells representing the MOC to serialize.
Returns
-------
result_json : {str : [int]}
A dictionary of HEALPix cell lists indexed by their depth... |
def pad_to_aspect_ratio(self, aspect_ratio, mode="constant", cval=0.0, return_pad_amounts=False):
"""
Pad the segmentation map on its sides so that its matches a target aspect ratio.
Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or t... | Pad the segmentation map on its sides so that its matches a target aspect ratio.
Depending on which dimension is smaller (height or width), only the corresponding
sides (left/right or top/bottom) will be padded. In each case, both of the sides will
be padded equally.
Parameters
... |
def eight_schools_joint_log_prob(
treatment_effects, treatment_stddevs,
avg_effect, avg_stddev, school_effects_standard):
"""Eight-schools joint log-prob."""
rv_avg_effect = tfd.Normal(loc=0., scale=10.)
rv_avg_stddev = tfd.Normal(loc=5., scale=1.)
rv_school_effects_standard = mvn(
loc=tf.zeros_li... | Eight-schools joint log-prob. |
def _float_oper(op1, op2=None):
''' Returns pop sequence for floating point operands
1st operand in A DE BC, 2nd operand remains in the stack
Unlike 8bit and 16bit version, this does not supports
operands inversion. Since many of the instructions are implemented
as functions, they must support this... | Returns pop sequence for floating point operands
1st operand in A DE BC, 2nd operand remains in the stack
Unlike 8bit and 16bit version, this does not supports
operands inversion. Since many of the instructions are implemented
as functions, they must support this.
However, if 1st operand is a numb... |
def update_extent(self, extent):
# type: (int) -> None
'''
Update the extent for this CE record.
Parameters:
extent - The new extent for this CE record.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibIn... | Update the extent for this CE record.
Parameters:
extent - The new extent for this CE record.
Returns:
Nothing. |
def _load_from_file_object(self, f):
"""Load from a file object.
Args:
f: File object to load vocabulary from
"""
subtoken_strings = []
for line in f:
s = line.strip()
# Some vocab files wrap words in single quotes, but others don't
if ((s.startswith("'") and s.endswith("'")... | Load from a file object.
Args:
f: File object to load vocabulary from |
def _from_base_type(self, value):
"""Converts our stored JSON string back to the desired type.
Args:
value: A value from the datastore to be converted to the
desired type.
Returns:
A deserialized Credentials (or subclass) object, else None if
... | Converts our stored JSON string back to the desired type.
Args:
value: A value from the datastore to be converted to the
desired type.
Returns:
A deserialized Credentials (or subclass) object, else None if
the value can't be parsed. |
def convex_conj(self):
"""Convex conjugate functional of IndicatorLpUnitBall.
Returns
-------
convex_conj : GroupL1Norm
The convex conjugate is the the group L1-norm.
"""
conj_exp = conj_exponent(self.pointwise_norm.exponent)
return GroupL1Norm(self.d... | Convex conjugate functional of IndicatorLpUnitBall.
Returns
-------
convex_conj : GroupL1Norm
The convex conjugate is the the group L1-norm. |
def read(self):
"""
Read object from artifactory. Fill object if exist
:return:
True if object exist,
False else
"""
logging.debug('Read {x.__class__.__name__} [{x.name}]'.format(x=self))
request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format... | Read object from artifactory. Fill object if exist
:return:
True if object exist,
False else |
def _assert_all_loadable_terms_specialized_to(self, domain):
"""Make sure that we've specialized all loadable terms in the graph.
"""
for term in self.graph.node:
if isinstance(term, LoadableTerm):
assert term.domain is domain | Make sure that we've specialized all loadable terms in the graph. |
def calculate(self, **state):
"""
Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g. \
{'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25}
:returns: [Pa.s]... | Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g. \
{'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25}
:returns: [Pa.s] dynamic viscosity
The **state parameter ... |
def get_catalog_hierarchy_design_session(self, proxy):
"""Gets the catalog hierarchy design session.
arg: proxy (osid.proxy.Proxy): proxy
return: (osid.cataloging.CatalogHierarchyDesignSession) - a
``CatalogHierarchyDesignSession``
raise: NullArgument - ``proxy`` is ... | Gets the catalog hierarchy design session.
arg: proxy (osid.proxy.Proxy): proxy
return: (osid.cataloging.CatalogHierarchyDesignSession) - a
``CatalogHierarchyDesignSession``
raise: NullArgument - ``proxy`` is null
raise: OperationFailed - unable to complete request
... |
def ip_address(self,
container: Container
) -> Union[IPv4Address, IPv6Address]:
"""
The IP address used by a given container, or None if no IP address has
been assigned to that container.
"""
r = self.__api.get('containers/{}/ip'.format(conta... | The IP address used by a given container, or None if no IP address has
been assigned to that container. |
def just_load_srno(srno, prm_filename=None):
"""Simply load an dataset based on serial number (srno).
This convenience function reads a dataset based on a serial number. This
serial number (srno) must then be defined in your database. It is mainly
used to check that things are set up correctly.
Ar... | Simply load an dataset based on serial number (srno).
This convenience function reads a dataset based on a serial number. This
serial number (srno) must then be defined in your database. It is mainly
used to check that things are set up correctly.
Args:
prm_filename: name of parameter file (op... |
def force_to_string(unknown):
"""
converts and unknown type to string for display purposes.
"""
result = ''
if type(unknown) is str:
result = unknown
if type(unknown) is int:
result = str(unknown)
if type(unknown) is float:
result = str(unknown)
if type(unkno... | converts and unknown type to string for display purposes. |
def get_internal_registry_ip():
"""
Search for `docker-registry` IP
:return: str, ip address
"""
with conu.backend.origin.backend.OpenshiftBackend() as origin_backend:
services = origin_backend.list_services()
for service in services:
if service.name == 'docker-registry':... | Search for `docker-registry` IP
:return: str, ip address |
def _comports():
'''
Returns
-------
pandas.DataFrame
Table containing descriptor, and hardware ID of each available COM
port, indexed by port (e.g., "COM4").
'''
return (pd.DataFrame(list(map(list, serial.tools.list_ports.comports())),
columns=['port', '... | Returns
-------
pandas.DataFrame
Table containing descriptor, and hardware ID of each available COM
port, indexed by port (e.g., "COM4"). |
def emitDataChanged(self, regItem):
""" Emits the dataChagned signal for the regItem
"""
leftIndex = self.indexFromItem(regItem, col=0)
rightIndex = self.indexFromItem(regItem, col=-1)
logger.debug("Data changed: {} ...{}".format(self.data(leftIndex), self.data(rightIndex)))
... | Emits the dataChagned signal for the regItem |
def find_console_handler(logger):
"""Return a stream handler, if it exists."""
for handler in logger.handlers:
if (isinstance(handler, logging.StreamHandler) and
handler.stream == sys.stderr):
return handler | Return a stream handler, if it exists. |
def list_groups(self, scope_descriptor=None, subject_types=None, continuation_token=None):
"""ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for g... | ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subject_types: A comma separated list of user subject subtypes to reduce t... |
def get_preferred_submodules():
"""
Get all submodules of the main scientific modules and others of our
interest
"""
# Path to the modules database
modules_path = get_conf_path('db')
# Modules database
modules_db = PickleShareDB(modules_path)
if 'submodules' in modules_d... | Get all submodules of the main scientific modules and others of our
interest |
def hashi(self, key, replica=0):
"""Returns a ketama compatible hash from the given key.
"""
dh = self._listbytes(md5(str(key).encode('utf-8')).digest())
rd = replica * 4
return (
(dh[3 + rd] << 24) | (dh[2 + rd] << 16) |
(dh[1 + rd] << 8) | dh[0 + rd]) | Returns a ketama compatible hash from the given key. |
def get_by_name(self, name):
""" returns an object Project which matches name """
for p in self.project_list:
if p.nme == name:
return p
return None | returns an object Project which matches name |
def set(self, name, valu):
'''
Set a name in the SlabDict.
Args:
name (str): The key name.
valu (obj): A msgpack compatible value.
Returns:
None
'''
byts = s_msgpack.en(valu)
lkey = self.pref + name.encode('utf8')
self... | Set a name in the SlabDict.
Args:
name (str): The key name.
valu (obj): A msgpack compatible value.
Returns:
None |
def process_link(self, env, refnode, has_explicit_title, title, target):
"""This handles some special cases for reference links in .NET
First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```,
where a reference to ``Link`` is created with title ``Title``, causes
problems f... | This handles some special cases for reference links in .NET
First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```,
where a reference to ``Link`` is created with title ``Title``, causes
problems for the generic .NET syntax of ``:dn:cls:`FooBar<T>```. So, here
we assume th... |
def build_eval_session(module_spec, class_count):
"""Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottlen... | Builds an restored eval session without train operations for exporting.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: Number of classes
Returns:
Eval session containing the restored eval graph.
The bottleneck input, ground truth, eval step, and prediction tens... |
def arma2psd(A=None, B=None, rho=1., T=1., NFFT=4096, sides='default',
norm=False):
r"""Computes power spectral density given ARMA values.
This function computes the power spectral density values
given the ARMA parameters of an ARMA model. It assumes that
the driving sequence is a white noise p... | r"""Computes power spectral density given ARMA values.
This function computes the power spectral density values
given the ARMA parameters of an ARMA model. It assumes that
the driving sequence is a white noise process of zero mean and
variance :math:`\rho_w`. The sampling frequency and noise variance a... |
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2):
"""
Accumulate the various inputs.
"""
dx = xt - xt1
dy = yt - yt1
if self.numPoints < self.maxPoints:
self.dxValues[self.numPoints,0] = dx
self.dxValues[self.numPoints,1] = dy
self.thetaValues[self.numP... | Accumulate the various inputs. |
def set_gid(self):
"""Change the group of the running process"""
if self.group:
gid = getgrnam(self.group).gr_gid
try:
os.setgid(gid)
except Exception:
message = ("Unable to switch ownership to {0}:{1}. " +
"D... | Change the group of the running process |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_interface(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
... | Auto Generated Code |
def find_saas_endurance_tier_price(package, tier_level):
"""Find the SaaS storage tier level price for the specified tier level
:param package: The Storage As A Service product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or a... | Find the SaaS storage tier level price for the specified tier level
:param package: The Storage As A Service product package
:param tier_level: The endurance tier for which a price is desired
:return: Returns the price for the given tier, or an error if not found |
def samblaster_dedup_sort(data, tx_out_file, tx_sr_file, tx_disc_file):
"""Deduplicate and sort with samblaster, produces split read and discordant pair files.
"""
samblaster = config_utils.get_program("samblaster", data["config"])
samtools = config_utils.get_program("samtools", data["config"])
tmp_... | Deduplicate and sort with samblaster, produces split read and discordant pair files. |
def show_report(self, session, *levels):
"""
Shows the report that has been generated
"""
if levels:
self.make_report(session, *levels)
if self.__report:
session.write_line(self.to_json(self.__report))
else:
session.write_line("No repo... | Shows the report that has been generated |
def plot_pointings(self, pointings=None):
"""Plot pointings on canavs"""
if pointings is None:
pointings = self.pointings
i = 0
for pointing in pointings:
items = []
i = i + 1
label = {}
label['text'] = pointing['label']['text... | Plot pointings on canavs |
def nfa_nonemptiness_check(nfa: dict) -> bool:
""" Checks if the input NFA reads any language other than the
empty one, returning True/False.
The language L(A) recognized by the automaton A is nonempty iff
there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that
t is connected to s.
Thus, a... | Checks if the input NFA reads any language other than the
empty one, returning True/False.
The language L(A) recognized by the automaton A is nonempty iff
there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that
t is connected to s.
Thus, automata nonemptiness is equivalent to graph reachabilit... |
def _get_translation(self, field, code):
"""
Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange ef... | Gets the translation of a specific field for a specific language code.
This raises ObjectDoesNotExist if the lookup was unsuccesful. As of
today, this stuff is cached. As the cache is rather aggressive it
might cause rather strange effects. However, we would see the same
effects when an... |
def cdx_resolve_revisits(cdx_iter):
"""
resolve revisits.
this filter adds three fields to CDX: ``orig.length``, ``orig.offset``,
and ``orig.filename``. for revisit records, these fields have corresponding
field values in previous non-revisit (original) CDX record.
They are all ``"-"`` for non-... | resolve revisits.
this filter adds three fields to CDX: ``orig.length``, ``orig.offset``,
and ``orig.filename``. for revisit records, these fields have corresponding
field values in previous non-revisit (original) CDX record.
They are all ``"-"`` for non-revisit records. |
def send(self, wallet, source, destination, amount, work=None, id=None):
"""
Send **amount** from **source** in **wallet** to **destination**
.. enable_control required
:param wallet: Wallet of account used to send funds
:type wallet: str
:param source: Account to send... | Send **amount** from **source** in **wallet** to **destination**
.. enable_control required
:param wallet: Wallet of account used to send funds
:type wallet: str
:param source: Account to send funds from
:type source: str
:param destination: Account to send funds to
... |
def cdf(self, x_data):
"""
Cumulative distribution function.
Note that chaospy only supports cumulative distribution functions for
stochastically independent distributions.
Args:
x_data (numpy.ndarray):
Location for the distribution function. Assumes... | Cumulative distribution function.
Note that chaospy only supports cumulative distribution functions for
stochastically independent distributions.
Args:
x_data (numpy.ndarray):
Location for the distribution function. Assumes that
``len(x_data) == len(... |
def get_function_spec(name):
"""Return a dictionary with the specification of a function:
parameter names and defaults (value, bounds, scale, etc.).
Returns
-------
par_names : list
List of parameter names for this function.
norm_par : str
Name of normalization parameter.
... | Return a dictionary with the specification of a function:
parameter names and defaults (value, bounds, scale, etc.).
Returns
-------
par_names : list
List of parameter names for this function.
norm_par : str
Name of normalization parameter.
default : dict
Parameter def... |
def run_fatcat(structure_path_1, structure_path_2, fatcat_sh, outdir='', silent=False, print_cmd=False, force_rerun=False):
"""Run FATCAT on two PDB files, and return the path of the XML result file.
Args:
structure_path_1 (str): Path to PDB file
structure_path_2 (str): Path to PDB file
... | Run FATCAT on two PDB files, and return the path of the XML result file.
Args:
structure_path_1 (str): Path to PDB file
structure_path_2 (str): Path to PDB file
fatcat_sh (str): Path to "runFATCAT.sh" executable script
outdir (str): Path to where FATCAT XML output files will b... |
def set_state_from_file(self, filename):
"""Sets the state of the sampler back to the instance saved in a file.
"""
with self.io(filename, 'r') as fp:
rstate = fp.read_random_state()
# set the numpy random state
numpy.random.set_state(rstate)
# set emcee's gen... | Sets the state of the sampler back to the instance saved in a file. |
def distorted_inputs(data_dir, batch_size):
"""Construct distorted input for CIFAR training using the Reader ops.
Args:
data_dir: Path to the CIFAR-10 data directory.
batch_size: Number of images per batch.
Returns:
images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
label... | Construct distorted input for CIFAR training using the Reader ops.
Args:
data_dir: Path to the CIFAR-10 data directory.
batch_size: Number of images per batch.
Returns:
images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
labels: Labels. 1D tensor of [batch_size] size. |
def cublasStpmv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Matrix-vector product for real triangular-packed matrix.
"""
status = _libcublas.cublasStpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
... | Matrix-vector product for real triangular-packed matrix. |
def Zabransky_cubic_integral_over_T(T, a1, a2, a3, a4):
r'''Calculates the integral of liquid heat capacity over T using the model
developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a4 : float
Coefficients
Returns
-------
S : float
Differ... | r'''Calculates the integral of liquid heat capacity over T using the model
developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a4 : float
Coefficients
Returns
-------
S : float
Difference in entropy from 0 K, [J/mol/K]
Notes
-----
... |
def get_bookmark_tags(self, bookmark_id):
"""
Retrieve tags that have been applied to a bookmark.
The requested bookmark must belong to the current user.
:param bookmark_id: ID of the bookmark to delete.
"""
url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_... | Retrieve tags that have been applied to a bookmark.
The requested bookmark must belong to the current user.
:param bookmark_id: ID of the bookmark to delete. |
def _filter_dict(input_dict, search_key, search_value):
'''
Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the lea... | Filters a dictionary of dictionaries by a key-value pair.
:param input_dict: is a dictionary whose values are lists of dictionaries
:param search_key: is the key in the leaf dictionaries
:param search_values: is the value in the leaf dictionaries
:return: filtered dictionary |
def ipi_name_number(name=None):
"""
IPI Name Number field.
An IPI Name Number is composed of eleven digits.
So, for example, an IPI Name Number code field can contain 00014107338.
:param name: name for the field
:return: a parser for the IPI Name Number field
"""
if name is None:
... | IPI Name Number field.
An IPI Name Number is composed of eleven digits.
So, for example, an IPI Name Number code field can contain 00014107338.
:param name: name for the field
:return: a parser for the IPI Name Number field |
def stationary_distributions(self, max_iter=200, tol=1e-5):
r"""
Compute the moments of the stationary distributions of :math:`x_t` and
:math:`y_t` if possible. Computation is by iteration, starting from
the initial conditions self.mu_0 and self.Sigma_0
Parameters
-----... | r"""
Compute the moments of the stationary distributions of :math:`x_t` and
:math:`y_t` if possible. Computation is by iteration, starting from
the initial conditions self.mu_0 and self.Sigma_0
Parameters
----------
max_iter : scalar(int), optional(default=200)
... |
def lag_matrix(blk, max_lag=None):
"""
Finds the lag matrix for a given 1-D block sequence.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
max_lag :
The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``,
the... | Finds the lag matrix for a given 1-D block sequence.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
max_lag :
The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``,
the maximum lag that doesn't create fully zero... |
def get_queryset(self, request):
"""
Filter the change list by currently logged in user if not a
superuser. We also skip filtering if the model for this admin
class has been added to the sequence in the setting
``OWNABLE_MODELS_ALL_EDITABLE``, which contains models in the
... | Filter the change list by currently logged in user if not a
superuser. We also skip filtering if the model for this admin
class has been added to the sequence in the setting
``OWNABLE_MODELS_ALL_EDITABLE``, which contains models in the
format ``app_label.object_name``, and allows models ... |
def uncertain_inputs_sparse_regression(max_iters=200, optimize=True, plot=True):
"""Run a 1D example of a sparse GP regression with uncertain inputs."""
fig, axes = pb.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True)
# sample inputs and outputs
S = np.ones((20, 1))
X = np.random.uniform(-3... | Run a 1D example of a sparse GP regression with uncertain inputs. |
def toc_html(self, depth=6, lowest_level=6):
"""
Get TOC of currently fed HTML string in form of HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: an HTML string
"""
toc = self.toc(depth=depth, lowest... | Get TOC of currently fed HTML string in form of HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: an HTML string |
def PopupGetFile(message, title=None, default_path='', default_extension='', save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anyw... | Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon... |
def parseBranches(self, descendants):
"""
Parse top level of latex
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects
>>> toc = TOC.fromLatex(r'\section{h1}\subsection{subh1}\section{h2}\
... \subsection{subh2}')
>>> toc... | Parse top level of latex
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects
>>> toc = TOC.fromLatex(r'\section{h1}\subsection{subh1}\section{h2}\
... \subsection{subh2}')
>>> toc.parseTopDepth(toc.descendants)
1
>>> toc.... |
def load_environment_vars(self):
"""
Looks for any MACH9_ prefixed environment variables and applies
them to the configuration if present.
"""
for k, v in os.environ.items():
if k.startswith(MACH9_PREFIX):
_, config_key = k.split(MACH9_PREFIX, 1)
... | Looks for any MACH9_ prefixed environment variables and applies
them to the configuration if present. |
def replace_activities(self):
"""Replace ative flags with Agent states when possible."""
logger.debug('Running PySB Preassembler replace activities')
# TODO: handle activity hierarchies
new_stmts = []
def has_agent_activity(stmt):
"""Return True if any agents in the ... | Replace ative flags with Agent states when possible. |
def main(argv=sys.argv):
"""Populate database with 30 users."""
if len(argv) < 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
engine = engine_from_config(settings, "sqlalchemy.")
DBSession.configure(bind=engine)
Base.met... | Populate database with 30 users. |
def _get_hidden_forum_ids(self, forums, user):
""" Given a set of forums and a user, returns the list of forums that are not visible by
this user.
"""
visible_forums = self._get_forums_for_user(
user, ['can_see_forum', 'can_read_forum', ], use_tree_hierarchy=True,
... | Given a set of forums and a user, returns the list of forums that are not visible by
this user. |
def query(self, xri, service_types):
"""Resolve some services for an XRI.
Note: I don't implement any service endpoint selection beyond what
the resolver I'm querying does, so the Services I return may well
include Services that were not of the types you asked for.
May raise fe... | Resolve some services for an XRI.
Note: I don't implement any service endpoint selection beyond what
the resolver I'm querying does, so the Services I return may well
include Services that were not of the types you asked for.
May raise fetchers.HTTPFetchingError or L{etxrd.XRDSError} i... |
def _handle_changed_fields(self, old_data):
"""
Looks for changed relation fields between new and old data (before/after save).
Creates back_link references for updated fields.
Args:
old_data: Object's data before save.
"""
for link in self.get_links(is_set=F... | Looks for changed relation fields between new and old data (before/after save).
Creates back_link references for updated fields.
Args:
old_data: Object's data before save. |
def sort_by_key(self, keys=None):
"""
:param keys: list of str to sort by, if name starts with -
reverse order
:return: None
"""
keys = keys or self.key_on
keys = keys if isinstance(keys, (list, tuple)) else [keys]
for key in reversed(keys):
... | :param keys: list of str to sort by, if name starts with -
reverse order
:return: None |
def login(session, username, password, class_name=None):
"""
Login on coursera.org with the given credentials.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag
"""
logging.debug('Initiating login.')
try:
session.cookies.clear('.course... | Login on coursera.org with the given credentials.
This adds the following cookies to the session:
sessionid, maestro_login, maestro_login_flag |
def tagged(*tags: Tags) -> Callable:
global GREENSIM_TAG_ATTRIBUTE
"""
Decorator for adding a label to the process.
These labels are applied to any child Processes produced by event
"""
def hook(event: Callable):
def wrapper(*args, **kwargs):
event(*args, **kwargs)
se... | Decorator for adding a label to the process.
These labels are applied to any child Processes produced by event |
def calculate_fuzzy_chi(alpha, square_map, right_eigenvectors):
"""Calculate the membership matrix (chi) from parameters alpha.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
square_map : ndarray
Mapping from square indices (i,j) to flat in... | Calculate the membership matrix (chi) from parameters alpha.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
right_eigenvectors : ndarray
The right eigenvect... |
def on_startup(self):
"""
Defines the slot triggered on Framework startup.
"""
LOGGER.debug("> Calling '{0}' Component Framework 'on_startup' method.".format(self.__class__.__name__))
if self.Autostart_TCP_Server_checkBox.isChecked():
if not self.__tcp_server.online... | Defines the slot triggered on Framework startup. |
def list_subnets(self, tag_values=None):
'''
a method to discover the list of subnets on AWS EC2
:param tag_values: [optional] list of tag values
:return: list of strings with subnet ids
'''
title = '%s.list_subnets' % self.__class__.__name__
# validate inputs... | a method to discover the list of subnets on AWS EC2
:param tag_values: [optional] list of tag values
:return: list of strings with subnet ids |
def new_object(cls, state, type_, symbolic=False, init_object=False):
"""
Creates a new object reference.
:param state: State associated to the object.
:param type_: Class of the object.
:param init_object: Whether the objects initializer method should be run.
:return: Re... | Creates a new object reference.
:param state: State associated to the object.
:param type_: Class of the object.
:param init_object: Whether the objects initializer method should be run.
:return: Reference to the new object. |
def create(self, subid, params=None):
''' /v1/snapshot/create
POST - account
Create a snapshot from an existing virtual machine.
The virtual machine does not need to be stopped.
Link: https://www.vultr.com/api/#snapshot_create
'''
params = update_params(params, {... | /v1/snapshot/create
POST - account
Create a snapshot from an existing virtual machine.
The virtual machine does not need to be stopped.
Link: https://www.vultr.com/api/#snapshot_create |
def effective_sample_size(states,
filter_threshold=0.,
filter_beyond_lag=None,
name=None):
"""Estimate a lower bound on effective sample size for each independent chain.
Roughly speaking, "effective sample size" (ESS) is the size of an i... | Estimate a lower bound on effective sample size for each independent chain.
Roughly speaking, "effective sample size" (ESS) is the size of an iid sample
with the same variance as `state`.
More precisely, given a stationary sequence of possibly correlated random
variables `X_1, X_2,...,X_N`, each identically d... |
def load_state(self, state_id, delete=True):
"""
Load a state from storage identified by `state_id`.
:param state_id: The state reference of what to load
:return: The deserialized state
:rtype: State
"""
return self._store.load_state(f'{self._prefix}{state_id:08x... | Load a state from storage identified by `state_id`.
:param state_id: The state reference of what to load
:return: The deserialized state
:rtype: State |
def mtz2tw(n,c,e,l):
"""mtz: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting ... | mtz: model for the traveling salesman problem with time windows
(based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
- e[i]: earliest date for visiting node i
- l[i]: lates... |
def runGenome(bfile, options):
"""Runs the genome command from plink.
:param bfile: the input file prefix.
:param options: the options.
:type bfile: str
:type options: argparse.Namespace
:returns: the name of the ``genome`` file.
Runs Plink with the ``genome`` option. If the user asks fo... | Runs the genome command from plink.
:param bfile: the input file prefix.
:param options: the options.
:type bfile: str
:type options: argparse.Namespace
:returns: the name of the ``genome`` file.
Runs Plink with the ``genome`` option. If the user asks for SGE
(``options.sge`` is True), a... |
def set_nb_theme(name):
"""Set theme from within notebook """
from IPython.core.display import HTML
styles_dir = os.path.join(package_dir, 'styles/compiled/')
css_path = glob('{0}/{1}.css'.format(styles_dir, name))[0]
customcss = open(css_path, "r").read()
return HTML(''.join(['<style> ', custo... | Set theme from within notebook |
def run_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env='base'):
r'''
Compile a DSC Configuration in the form of a PowerShell script (.ps1) and
ap... | r'''
Compile a DSC Configuration in the form of a PowerShell script (.ps1) and
apply it. The PowerShell script can be cached from the master using the
``source`` option. If there is more than one config within the PowerShell
script, the desired configuration can be applied by passing the name in the
... |
def add_mimetype(mimedb, mimetype, extension):
"""Add or replace a mimetype to be used with the given extension."""
# If extension is already a common type, strict=True must be used.
strict = extension in mimedb.types_map[True]
mimedb.add_type(mimetype, extension, strict=strict) | Add or replace a mimetype to be used with the given extension. |
def send_message(self, fakeid, content):
"""
主动发送文本消息
:param fakeid: 用户的 UID (即 fakeid )
:param content: 发送的内容
:raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据
:raises ValueError: 参数出错, 具体内容有 ``fake id not exist``
"""
url = 'https://mp.weixin.qq.... | 主动发送文本消息
:param fakeid: 用户的 UID (即 fakeid )
:param content: 发送的内容
:raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据
:raises ValueError: 参数出错, 具体内容有 ``fake id not exist`` |
def view_help(self):
"""Return a help message describing all the statically configured keys.
"""
def format_desc(desc):
return "%s (Type: %s, Default: %s)\n%s" % (
desc.name,
desc.validator.__name__.replace('validate_', ''),
... | Return a help message describing all the statically configured keys. |
def build_transgenic_lines(self):
"""
init class | "transgenic_line_source_name":"stock_number" a Class
add superClass | rdfs:subClassOf ilxtr:transgenicLine
add *order* | ilxtr:useObjectProperty ilxtr:<order>
add name | rdfs:label "name"
add def |... | init class | "transgenic_line_source_name":"stock_number" a Class
add superClass | rdfs:subClassOf ilxtr:transgenicLine
add *order* | ilxtr:useObjectProperty ilxtr:<order>
add name | rdfs:label "name"
add def | definition: "description"
add transtype | ... |
def decode(self, packet):
'''
Decode a PUBLISH control packet.
'''
self.encoded = packet
lenLen = 1
while packet[lenLen] & 0x80:
lenLen += 1
packet_remaining = packet[lenLen+1:]
self.dup = (packet[0] & 0x08) == 0x08
self.qos = (p... | Decode a PUBLISH control packet. |
def stop(self):
"""Stop the progress bar."""
if self._progressing:
self._progressing = False
self._thread.join() | Stop the progress bar. |
def transpose(self):
"""Return the transpose of the QuantumChannel."""
return SuperOp(
np.transpose(self._data),
input_dims=self.output_dims(),
output_dims=self.input_dims()) | Return the transpose of the QuantumChannel. |
def stream(self, limit=None, page_size=None):
"""
Streams KeyInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory effici... | Streams KeyInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of reco... |
def prune_by_ngram_count_per_work(self, minimum=None, maximum=None,
label=None):
"""Removes results rows if the n-gram count for all works bearing that
n-gram is outside the range specified by `minimum` and
`maximum`.
That is, if a single witness of... | Removes results rows if the n-gram count for all works bearing that
n-gram is outside the range specified by `minimum` and
`maximum`.
That is, if a single witness of a single work has an n-gram
count that falls within the specified range, all result rows
for that n-gram are kept... |
def ingest(self):
"""ingest the veron catalogue into the catalogues database
See class docstring for usage.
"""
self.log.debug('starting the ``get`` method')
dictList = self._create_dictionary_of_veron()
tableName = self.dbTableName
createStatement = """
CR... | ingest the veron catalogue into the catalogues database
See class docstring for usage. |
def get_authorization_url(self,
signin_with_twitter=False,
access_type=None):
"""Get the authorization URL to redirect the user"""
try:
if signin_with_twitter:
url = self._get_oauth_url('authenticate')
... | Get the authorization URL to redirect the user |
def make_response(status, headers, payload, environ):
"""This function generates an appropriate response object for this async
mode.
"""
return Response(body=payload, status=int(status.split()[0]),
headers=headers) | This function generates an appropriate response object for this async
mode. |
def BOUND(self):
"""BOUND state."""
logger.debug('In state: BOUND')
logger.info('(%s) state changed %s -> bound', self.client.iface,
STATES2NAMES[self.current_state])
self.current_state = STATE_BOUND
self.client.lease.info_lease()
if self.script is not... | BOUND state. |
def get_reservations(**kwargs):
"""
Return a list of reservations matching the passed filter.
Supported kwargs are listed at
http://knowledge25.collegenet.com/display/WSW/reservations.xml
"""
kwargs["scope"] = "extended"
url = "/r25ws/servlet/wrd/run/reservations.xml"
if len(kwargs):
... | Return a list of reservations matching the passed filter.
Supported kwargs are listed at
http://knowledge25.collegenet.com/display/WSW/reservations.xml |
def with_options(self, codec_options=None, read_preference=None,
write_concern=None, read_concern=None):
"""Get a clone of this database changing the specified settings.
>>> db1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> db2... | Get a clone of this database changing the specified settings.
>>> db1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> db2 = db1.with_options(read_preference=ReadPreference.SECONDARY)
>>> db1.read_preference
Primary()
>>> db2.rea... |
def parse(self, inputstring, document):
"""Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser.
"""
link = json.loads(inputstring)
env = document.settings.env
source_dir = os.path.dirname... | Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser. |
def is_parent_of_vault(self, id_, vault_id):
"""Tests if an ``Id`` is a direct parent of a vault.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if this ``id`` is a parent of
``vault_id,`` ``false`` o... | Tests if an ``Id`` is a direct parent of a vault.
arg: id (osid.id.Id): an ``Id``
arg: vault_id (osid.id.Id): the ``Id`` of a vault
return: (boolean) - ``true`` if this ``id`` is a parent of
``vault_id,`` ``false`` otherwise
raise: NotFound - ``vault_id`` is not ... |
def frmnam(frcode, lenout=_default_len_out):
"""
Retrieve the name of a reference frame associated with a SPICE ID code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frmnam_c.html
:param frcode: an integer code for a reference frame
:type frcode: int
:param lenout: Maximum length of... | Retrieve the name of a reference frame associated with a SPICE ID code.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frmnam_c.html
:param frcode: an integer code for a reference frame
:type frcode: int
:param lenout: Maximum length of output string.
:type lenout: int
:return: the na... |
def ReadFlagsFromFiles(self, argv, force_gnu=True):
"""Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Note that the name of t... | Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Note that the name of the program (sys.argv[0]) should be omitted.
force_gnu... |
def choices(self):
"""
Returns the filter list as a tuple. Useful for model choices.
"""
choice_list = getattr(
settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES
)
return [(f, self._get_filter_title(f)) for f in choice_list] | Returns the filter list as a tuple. Useful for model choices. |
def authenticate_search_bind(self, username, password):
"""
Performs a search bind to authenticate a user. This is
required when a the login attribute is not the same
as the RDN, since we cannot string together their DN on
the fly, instead we have to find it in the LDAP, then att... | Performs a search bind to authenticate a user. This is
required when a the login attribute is not the same
as the RDN, since we cannot string together their DN on
the fly, instead we have to find it in the LDAP, then attempt
to bind with their credentials.
Args:
user... |
def LogMsg(msg):
""" Writes a formatted log message with a timestamp to stdout. """
global headerlogged
if headerlogged == 0:
print("{0:<8} {1:<90} {2}".format(
"Time",
"MainThread",
"UpdateSNMPObjsThread"
))
print("{0:-^120}".format("-"))
headerlogged = 1
threadname = threading.currentThread().... | Writes a formatted log message with a timestamp to stdout. |
def _tree_stat(self, mode, infostr, stat):
""" update stat regarding to tree generating process,
e.g. show_tree()
"""
action_str = mode.upper()
info_str = infostr
if stat == 'OK':
self.action_st_panel.SetBackgroundColour('#00FF00')
else: # ERR
... | update stat regarding to tree generating process,
e.g. show_tree() |
def string_get(self, ypos, xpos, length):
"""
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
... | Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.