code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def getLocation(self):
method =
try:
data = _doget(method, photo_id=self.id)
except FlickrError:
return None
loc = data.rsp.photo.location
return [loc.latitude, loc.longitude] | Return the latitude+longitutde of the picture.
Returns None if no location given for this pic. |
def from_numpy_vectors(cls, linear, quadratic, offset, vartype, variable_order=None):
try:
heads, tails, values = quadratic
except ValueError:
raise ValueError("quadratic should be a 3-tuple")
if not len(heads) == len(tails) == len(values):
raise Va... | Create a binary quadratic model from vectors.
Args:
linear (array_like):
A 1D array-like iterable of linear biases.
quadratic (tuple[array_like, array_like, array_like]):
A 3-tuple of 1D array_like vectors of the form (row, col, bias).
offse... |
def mask(self):
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None` |
def create_node(self, network, participant):
if network.role == "practice" or network.role == "catch":
return RogersAgentFounder(network=network, participant=participant)
elif network.size(type=Agent) < network.generation_size:
return RogersAgentFounder(network=network, ... | Make a new node for participants. |
def select_site_view(self, request, form_url=):
if not self.has_add_permission(request):
raise PermissionDenied
extra_qs =
if request.META[]:
extra_qs = + request.META[]
site_choices = self.get_site_choices()
if len(site_choices) == 1:
... | Display a choice form to select which site to add settings. |
def get_json_files(p):
f = [os.path.join(p, x) for x in os.listdir(p) if x.endswith(".json")]
return sorted(f) | Scan the provided policy directory for all JSON policy files. |
def failover_to_replicant(self, volume_id, replicant_id, immediate=False):
return self.client.call(, ,
replicant_id, immediate, id=volume_id) | Failover to a volume replicant.
:param integer volume_id: The id of the volume
:param integer replicant_id: ID of replicant to failover to
:param boolean immediate: Flag indicating if failover is immediate
:return: Returns whether failover was successful or not |
def get_argument_role(self):
try:
return self.get_argument(constants.PARAM_ROLE, default=None)
except tornado.web.MissingArgumentError as e:
raise Exception(e.log_message) | Helper function to get request argument.
Raises exception if argument is missing.
Returns the role argument. |
def get_clumpp_table(self, kvalues, max_var_multiple=0, quiet=False):
if max_var_multiple:
if max_var_multiple < 1:
raise ValueError()
if isinstance(kvalues, int):
return _get_clumpp_table(self, kvalues, max_var_multiple, quiet)
else:
... | Returns a dictionary of results tables for making structure barplots.
This calls the same functions used in get_evanno_table() to call
CLUMPP to permute replicates.
Parameters:
-----------
kvalues : list or int
A kvalue or list of kvalues to run CLUMPP on and return... |
def inspiral_range(psd, snr=8, mass1=1.4, mass2=1.4, fmin=None, fmax=None,
horizon=False):
mass1 = units.Quantity(mass1, ).to()
mass2 = units.Quantity(mass2, ).to()
mtotal = mass1 + mass2
fisco = (constants.c ** 3 / (constants.G * 6**1.5 * pi * mtotal)).to()
fmax ... | Calculate the inspiral sensitive distance from a GW strain PSD
The method returns the distance (in megaparsecs) to which an compact
binary inspiral with the given component masses would be detectable
given the instrumental PSD. The calculation is as defined in:
https://dcc.ligo.org/LIGO-T030276/public... |
def create_namespaced_cron_job(self, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.create_namespaced_cron_job_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_cron_job_with_http_info(namespace, body, **kwa... | create a CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_cron_job(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ... |
def topDownCompute(self, encoded):
if self._prevAbsolute==None or self._prevDelta==None:
return [EncoderResult(value=0, scalar=0,
encoding=numpy.zeros(self.n))]
ret = self._adaptiveScalarEnc.topDownCompute(encoded)
if self._prevAbsolute != None:
ret = [Enc... | [ScalarEncoder class method override] |
def log_task(
task, logger=logging, level=, propagate_fail=True, uuid=None
):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with LogTask(
task,
logger=logger,
level=level,
propagate_fail=propagate... | Parameterized decorator to wrap a function in a log task
Example:
>>> @log_task('mytask')
... def do_something():
... pass |
def rightAt(self, offset=0):
return Location(self.getX() + self.getW() + offset, self.getY() + (self.getH() / 2)) | Returns point in the center of the region's right side (offset to the right
by ``offset``) |
def execute_ccm_remotely(remote_options, ccm_args):
if not PARAMIKO_IS_AVAILABLE:
logging.warn("Paramiko is not Availble: Skipping remote execution of CCM command")
return None, None
ssh_client = SSHClient(remote_options.ssh_host, remote_options.ssh_port,
re... | Execute CCM operation(s) remotely
:return A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script
:raises Exception if invalid options are passed for `--dse-... |
def save(self, *args, **kwargs):
self.slug = self.create_slug()
super(Slugable, self).save(*args, **kwargs) | Overrides the save method |
def update_endtime(jid, time):
jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__[])
try:
if not os.path.exists(jid_dir):
os.makedirs(jid_dir)
with salt.utils.files.fopen(os.path.join(jid_dir, ENDTIME), ) as etfile:
etfile.write(salt.utils.stringutils.to_str(... | Update (or store) the end time for a given job
Endtime is stored as a plain text string |
def create_destination_id(client, container, name):
path = str(pathlib.PurePath(name))
return .join((client.primary_endpoint, container, path)) | Create a unique destination id
:param azure.storage.StorageClient client: storage client
:param str container: container name
:param str name: entity name
:rtype: str
:return: unique id for the destination |
def run(self):
self.logger.info("Running with Python %s", sys.version.replace("\n", ""))
self.logger.info("Running on platform %s", platform.platform())
self.logger.info("Current cpu count is %d", multiprocessing.cpu_count())
configuration = self.load_configuration()
pa... | Processing the pipeline. |
def save_item(self, item_form, *args, **kwargs):
if item_form.is_for_update():
return self.update_item(item_form, *args, **kwargs)
else:
return self.create_item(item_form, *args, **kwargs) | Pass through to provider ItemAdminSession.update_item |
def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT):
self.ws_client.send(data, opcode) | Send message to server.
data: message to send. If you set opcode to OPCODE_TEXT,
data must be utf-8 string or unicode.
opcode: operation code of data. default is OPCODE_TEXT. |
def _update_dPrxy(self):
super(ExpCM_empirical_phi_divpressure, self)._update_dPrxy()
if in self.freeparams:
with scipy.errstate(divide=, under=, over=,
invalid=):
scipy.copyto(self.dPrxy[], -self.ln_piAx_piAy_beta
... | Update `dPrxy`, accounting for dependence of `Prxy` on `omega2`. |
def intersectingPoint(self, p):
if p == self.data.mid:
return self.data.ends
if p > self.data.mid:
endAfterP = [r for r in self.data.ends
if (r.end >= p and not self.openEnded) or
(r.end > p and self.openEnded)]
if self.righ... | given a point, get intervals in the tree that are intersected.
:param p: intersection point
:return: the list of intersected intervals |
def check(self, data):
if isinstance(data, Iterable):
data = "".join(str(x) for x in data)
try:
data = str(data)
except UnicodeDecodeError:
return False
return bool(data and self.__regexp.match(data)) | returns True if any match any regexp |
def get_url(self, version=None):
if self.fixed_bundle_url:
return self.fixed_bundle_url
return % (os.path.join(self.bundle_url_root, self.bundle_filename), version or self.get_version(), self.bundle_type) | Return the filename of the bundled bundle |
def scroll(self, clicks):
target = self._target
ratio = 0.90
mult = 1.0
if clicks > 0:
mult = ratio**clicks
elif clicks < 0:
mult = (1.0 / ratio)**abs(clicks)
z_axis = self._n_pose[:3, 2].flatten()
eye = self._n_pose[:3, 3].flatt... | Zoom using a mouse scroll wheel motion.
Parameters
----------
clicks : int
The number of clicks. Positive numbers indicate forward wheel
movement. |
def _update_targets(vesseldicts, environment_dict):
nodelist = []
for vesseldict in vesseldicts:
nodeip_port = vesseldict[]++str(vesseldict[])
if not nodeip_port in nodelist:
nodelist.append(nodeip_port)
seash_global_variables.targets[] = []
print nodelist
retdict = seash_helper... | <Purpose>
Connects to the nodes in the vesseldicts and adds them to the list
of valid targets.
<Arguments>
vesseldicts:
A list of vesseldicts obtained through
SeattleClearinghouseClient calls.
<Side Effects>
All valid targets that the user can access on the specified nodes
are ... |
def trim(self):
if 0 < self.cutoff <= 0.5:
pscore = self.raw_data[]
keep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff)
Y_trimmed = self.raw_data[][keep]
D_trimmed = self.raw_data[][keep]
X_trimmed = self.raw_data[][keep]
self.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed)
self.raw_... | Trims data based on propensity score to create a subsample with
better covariate balance.
The default cutoff value is set to 0.1. To set a custom cutoff
value, modify the object attribute named cutoff directly.
This method should only be executed after the propensity score
has been estimated. |
def count_hom_ref(self, axis=None):
b = self.is_hom_ref()
return np.sum(b, axis=axis) | Count homozygous reference genotypes.
Parameters
----------
axis : int, optional
Axis over which to count, or None to perform overall count. |
def get_device_name(self):
command = const.CMD_OPTIONS_RRQ
command_string = b
response_size = 1024
cmd_response = self.__send_command(command, command_string, response_size)
if cmd_response.get():
device = self.__data.split(b, 1)[-1].split(b)[0]
... | return the device name
:return: str |
def open_channel(self):
if self._closing:
raise ConnectionClosed("Closed by application")
if self.closed.done():
raise self.closed.exception()
channel = yield from self.channel_factory.open()
return channel | Open a new channel on this connection.
This method is a :ref:`coroutine <coroutine>`.
:return: The new :class:`Channel` object. |
def checkTikaServer(scheme="http", serverHost=ServerHost, port=Port, tikaServerJar=TikaServerJar, classpath=None, config_path=None):
if classpath is None:
classpath = TikaServerClasspath
if port is None:
port = if scheme == else
urlp = urlparse(tikaServerJar)
serverEndpoint = %... | Check that tika-server is running. If not, download JAR file and start it up.
:param scheme: e.g. http or https
:param serverHost:
:param port:
:param tikaServerJar:
:param classpath:
:return: |
def quality(self, tests, alias=None):
this_tests =\
tests.get(, [])+tests.get(, [])+tests.get(, [])\
+ tests.get(self.mnemonic, [])\
+ utils.flatten_list([tests.get(a) for a in self.get_alias(alias=alias)])
this_tests = filter(None,... | Run a series of tests and return the corresponding results.
Args:
tests (list): a list of functions.
alias (dict): a dictionary mapping mnemonics to lists of mnemonics.
Returns:
list. The results. Stick to booleans (True = pass) or ints. |
def discovery_redis(self):
self.context.install_bundle("pelix.remote.discovery.redis").start()
with use_waiting_list(self.context) as ipopo:
ipopo.add(
rs.FACTORY_DISCOVERY_REDIS,
"pelix-discovery-redis",
{
... | Installs the Redis discovery bundles and instantiates components |
def associate_route_table(self, route_table_id, subnet_id):
params = {
: route_table_id,
: subnet_id
}
result = self.get_object(, params, ResultSet)
return result.associationId | Associates a route table with a specific subnet.
:type route_table_id: str
:param route_table_id: The ID of the route table to associate.
:type subnet_id: str
:param subnet_id: The ID of the subnet to associate with.
:rtype: str
:return: The ID of the association creat... |
def _init_values(self, context=None):
if context is None:
context = self.env.context
basic_fields = []
for field_name in self._columns:
field = self._columns[field_name]
if not getattr(field, , False):
basic_fields.append(fiel... | Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made. |
def disambiguate_fname(files_path_list, filename):
fname = os.path.basename(filename)
same_name_files = get_same_name_files(files_path_list, fname)
if len(same_name_files) > 1:
compare_path = shortest_path(same_name_files)
if compare_path == filename:
same_name_files.... | Get tab title without ambiguation. |
def dial(self, target):
if not target:
return None, "target network must be specified with -t or --target"
url = get_url(self.config, target)
try:
if url.startswith():
self.w3 = Web3(WebsocketProvider(url))
elif url.startswith():
... | connects to a node
:param url: string (optional) - resource in which to connect.
if not provided, will use default for the stage
:returns: provider, error |
def _make_server(self):
app = application.standard_tensorboard_wsgi(self.flags,
self.plugin_loaders,
self.assets_zip_provider)
return self.server_class(app, self.flags) | Constructs the TensorBoard WSGI app and instantiates the server. |
def threshold(self, value, inclusive=False):
if inclusive:
def function(x, y):
return True if x >= y else False
else:
def function(x, y):
return True if x > y else False
return self.operation(value, function) | Return True if > than treshold value (or >= threshold value if
inclusive=True). |
def sapm_aoi_loss(aoi, module, upper=None):
aoi_coeff = [module[], module[], module[], module[],
module[], module[]]
aoi_loss = np.polyval(aoi_coeff, aoi)
aoi_loss = np.clip(aoi_loss, 0, upper)
aoi_lt_0 = np.full_like(aoi, False, dtype=)
np.less(aoi, 0, where=~np.isnan(a... | Calculates the SAPM angle of incidence loss coefficient, F2.
Parameters
----------
aoi : numeric
Angle of incidence in degrees. Negative input angles will return
zeros.
module : dict-like
A dict, Series, or DataFrame defining the SAPM performance
parameters. See the :py... |
def span_case(self, i, case):
if self.span_stack:
self.span_stack.pop()
if self.single_stack:
self.single_stack.pop()
self.span_stack.append(case)
count = len(self.span_stack)
self.end_found = False
try:
while not sel... | Uppercase or lowercase the next range of characters until end marker is found. |
def fetch_max(self, cluster, metric, topology, component, instance, timerange, environ=None):
components = [component] if component != "*" else (yield get_comps(cluster, environ, topology))
result = {}
futures = []
for comp in components:
query = self.get_query(metric, comp, instance)
... | :param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param environ:
:return: |
def get_page_name(id):
data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
return data["title"] | Return name of a page based on passed page id.
Parameters:
- id: id of a Confluence page. |
def mtf_bitransformer_tiny():
hparams = mtf_bitransformer_base()
hparams.batch_size = 2
hparams.mesh_shape = ""
hparams.d_model = 128
hparams.encoder_layers = ["self_att", "drd"] * 2
hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2
hparams.num_heads = 4
hparams.d_ff = 512
return hparams | Small encoder-decoder model for testing. |
async def _registration_completed(self, message):
if not self.registered:
self.registered = True
self.connection.throttle = True
target = message.params[0]
fakemsg = self._create_message(, target, source=self.nickname)
await self... | We're connected and registered. Receive proper nickname and emit fake NICK message. |
def get_flag_variables(ds):
flag_variables = []
for name, ncvar in ds.variables.items():
standard_name = getattr(ncvar, , None)
if isinstance(standard_name, basestring) and in standard_name:
flag_variables.append(name)
elif hasattr(ncvar, ):
flag_variables.a... | Returns a list of variables that are defined as flag variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset |
def clean_file(c_source, virtualenv_dirname):
with open(c_source, "r") as file_obj:
contents = file_obj.read().rstrip()
py_version = "python{}.{}".format(*sys.version_info[:2])
lib_path = os.path.join(
".nox", virtualenv_dirname, "lib", py_version, "site-packages", ""
)
con... | Strip trailing whitespace and clean up "local" names in C source.
These source files are autogenerated from the ``cython`` CLI.
Args:
c_source (str): Path to a ``.c`` source file.
virtualenv_dirname (str): The name of the ``virtualenv``
directory where Cython is installed (this is ... |
def __set_buffer_watch(self, pid, address, size, action, bOneShot):
bset = set()
nset = set()
cset = set()
page_addr = base
pageSize = MemoryAddresses.pageSize
while page_addr < limit:
... | Used by L{watch_buffer} and L{stalk_buffer}.
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@param size: Size in bytes of buffer to watch.
@type action: function
@... |
def LL(n):
if (n<=0):return Context()
else:
LL1=LL(n-1)
r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1
r2 = LL1 - LL1 - LL1
return r1 + r2 | constructs the LL context |
def merge_wgts(em_sz, wgts, itos_pre, itos_new):
vocab_size = len(itos_new)
enc_wgts = wgts["0.encoder.weight"].numpy()
row_m = enc_wgts.mean(0)
stoi_pre = collections.defaultdict(
lambda: -1, {v: k for k, v in enumerate(itos_pre)}
)
new_w = np.zeros((vocab_size, em_sz),... | :meth: `merge_wgts` insert pretrained weights and vocab into a new set of weights and vocab;
use average if vocab not in pretrained vocab
:param int em_sz: embedding size
:param wgts: torch model weights
:param list itos_pre: pretrained list of vocab
:param list itos_new: list of new vocab
:retu... |
def _resetWidgets(self):
self._filenameLineEdit.setText()
self._encodingComboBox.setCurrentIndex(0)
self._delimiterBox.reset()
self._headerCheckBox.setChecked(False)
self._statusBar.showMessage()
self._previewTableView.setModel(None)
self._datatypeTableVi... | Resets all widgets of this dialog to its inital state. |
def register(self, bug: Bug) -> None:
path = "bugs/{}".format(bug.name)
payload = bug.to_dict()
r = self.__api.put(path, json=payload)
if r.status_code != 204:
self.__api.handle_erroneous_response(r) | Dynamically registers a given bug with the server. Note that the
registration will not persist beyond the lifetime of the server.
(I.e., when the server is closed, the bug will be deregistered.)
Raises:
BugAlreadyExists: if there is already a bug registered on the
se... |
def compose_telegram(body):
msg = [b"A8"] + body + [checksum_bytes(body)] + [b"A3"]
return str.encode("".join([x.decode() for x in msg])) | Compose a SCS message
body: list containing the body of the message.
returns: full telegram expressed (bytes instance) |
def dump_json_file(json_data, pwd_dir_path, dump_file_name):
class PythonObjectEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(self, obj)
except TypeError:
return str(obj)
logs_dir_path = os.path.join(pwd_dir_pa... | dump json data to file |
def search_datasets(self):
request = protocol.SearchDatasetsRequest()
request.page_size = pb.int(self._page_size)
return self._run_search_request(
request, "datasets", protocol.SearchDatasetsResponse) | Returns an iterator over the Datasets on the server.
:return: An iterator over the :class:`ga4gh.protocol.Dataset`
objects on the server. |
def ensure_specifier_exists(db_spec):
local_match = LOCAL_RE.match(db_spec)
remote_match = REMOTE_RE.match(db_spec)
plain_match = PLAIN_RE.match(db_spec)
if local_match:
db_name = local_match.groupdict().get()
server = shortcuts.get_server()
if db_name not in server:
... | Make sure a DB specifier exists, creating it if necessary. |
def RecursiveMultiListChildren(self, urns, limit=None, age=NEWEST_TIME):
checked_urns = set()
urns_to_check = urns
while True:
found_children = []
for subject, values in self.MultiListChildren(
urns_to_check, limit=limit, age=age):
found_children.extend(values)
... | Recursively lists bunch of directories.
Args:
urns: List of urns to list children.
limit: Max number of children to list (NOTE: this is per urn).
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Yields:
(subject<->children urns) tuples... |
def gather_positions(tree):
pos = {: ,
: ,
: ,
: ,
: ,
: ,
: ,
: False
}
steps = 0
default_movement = True
for step in tree.findall():
steps += 1
for key in POSITION_ATTRIBS:
value... | Makes a list of positions and position commands from the tree |
def findclass(self, name):
refnum = _C.Vfindclass(self._hdf_inst._id, name)
if not refnum:
raise HDF4Error("vgroup not found")
return refnum | Find a vgroup given its class name, returning its reference
number if found.
Args::
name class name of the vgroup to find
Returns::
vgroup reference number
An exception is raised if the vgroup is not found.
C library equivalent: Vfind |
def select_by_index(self, index):
match = str(index)
for opt in self.options:
if opt.get_attribute("index") == match:
self._setSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index) | Select the option at the given index. This is done by examing the "index" attribute of an
element, and not merely by counting.
:Args:
- index - The option at this index will be selected
throws NoSuchElementException If there is no option with specified index in SELECT |
def path_is_empty(p: tcod.path.AStar) -> bool:
return bool(lib.TCOD_path_is_empty(p._path_c)) | Return True if a path is empty.
Args:
p (AStar): An AStar instance.
Returns:
bool: True if a path is empty. Otherwise False. |
def dt_weekofyear(x):
import pandas as pd
return pd.Series(x).dt.weekofyear.values | Returns the week ordinal of the year.
:returns: an expression containing the week ordinal of the year, extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
... |
def tuple_arg(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
args = map(tuplefy, args)
return fn(*args, **kwargs)
return wrapped | fun(1,2) -> fun((1,), (2,))로
f(1,2,3) => f((1,), (2,), (3,))
:param fn:
:return: |
def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
if not is_bytes(data):
raise TypeError("The `data` value must be of bytes type. Got {0}".format(type(data)))
decoders = [
self._registry.get_decoder(type_str)
for type_str i... | Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string representations of the ABI types that
will be used for decoding e.g. ``('uint256', 'bytes... |
def get_query_tokens(query):
query = preprocess_query(query)
parsed = sqlparse.parse(query)
if not parsed:
return []
tokens = TokenList(parsed[0].tokens).flatten()
return [token for token in tokens if token.ttype is not Whitespace] | :type query str
:rtype: list[sqlparse.sql.Token] |
def cmdloop(self, intro=None):
self.preloop()
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_... | Override the command loop to handle Ctrl-C. |
def _logger_api(self):
from .tcex_logger import TcExLogHandler, TcExLogFormatter
api = TcExLogHandler(self.session)
api.set_name()
api.setLevel(logging.DEBUG)
api.setFormatter(TcExLogFormatter())
self.log.addHandler(api) | Add API logging handler. |
def desc(self):
return .format(
self.name, self.device_id, self.type, self.status) | Get a short description of the device. |
def retry_connect(self):
with self.lock:
if self._funds_remaining > 0 and not self._leaving_state:
self._open_channels() | Will be called when new channels in the token network are detected.
If the minimum number of channels was not yet established, it will try
to open new channels.
If the connection manager has no funds, this is a noop. |
def spacing_file(path):
with open(os.path.abspath(path)) as f:
return spacing_text(f.read()) | Perform paranoid text spacing from file. |
def load(self, require=True, *args, **kwargs):
if not require or args or kwargs:
warnings.warn(
"Parameters to load are deprecated. Call .resolve and "
".require separately.",
PkgResourcesDeprecationWarning,
stacklevel=2,
... | Require packages for this EntryPoint, then resolve it. |
def main():
sender = PulsarSender()
args = parse_command_line()
_log = _init_log(level=logging.DEBUG if args.verbose else logging.INFO)
_log.info(, args.config_file.name)
_config = json.load(args.config_file)
if args.print_settings:
_log.debug(, json.dumps(_co... | Main script function |
def find_file(name, directory):
path_bits = directory.split(os.sep)
for i in range(0, len(path_bits) - 1):
check_path = path_bits[0:len(path_bits) - i]
check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name)
if os.path.exists(check_file):
return abspath(check_fil... | Searches up from a directory looking for a file |
def send_document(self, peer: Peer, document: str, reply: int=None, on_success: callable=None,
reply_markup: botapi.ReplyMarkup=None):
if isinstance(reply, Message):
reply = reply.id
document = botapi.InputFile(, botapi.InputFileInfo(document, open(document, )... | Send document to peer.
:param peer: Peer to send message to.
:param document: File path to document to send.
:param reply: Message object or message_id to reply to.
:param on_success: Callback to call when call is complete.
:type reply: int or Message |
def _twofilter_smoothing_ON2(self, t, ti, info, phi, lwinfo):
sp, sw = 0., 0.
upb = lwinfo.max() + self.wgt[t].lw.max()
if hasattr(self.model, ):
upb += self.model.upper_bound_trans(t + 1)
for n in range(self.N):
omegan = np.exp(lwinfo + self.wgt... | O(N^2) version of two-filter smoothing.
This method should not be called directly, see twofilter_smoothing. |
def gates_close(gate0: Gate, gate1: Gate,
tolerance: float = TOLERANCE) -> bool:
return vectors_close(gate0.vec, gate1.vec, tolerance) | Returns: True if gates are almost identical.
Closeness is measured with the gate angle. |
def channelRelease(BaRange_presence=0, GroupChannelDescription_presence=0,
GroupCipherKeyNumber_presence=0, GprsResumption_presence=0,
BaListPref_presence=0):
a = TpPd(pd=0x6)
b = MessageType(mesType=0xD)
c = RrCause()
packet = a / b / c
if BaRange_presen... | CHANNEL RELEASE Section 9.1.7 |
def _add_childTnLst(self):
self.remove(self.get_or_add_timing())
timing = parse_xml(self._childTnLst_timing_xml())
self._insert_timing(timing)
return timing.xpath()[0] | Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Any existing `p:timing` child element is ruthlessly removed and
replaced. |
def clean_params(self):
result = self.params.copy()
if self.cog is not None:
result.popitem(last=False)
try:
result.popitem(last=False)
except Exception:
raise ValueError() from None
return result | Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature. |
def _get_full_paths(fastq_dir, config, config_file):
if fastq_dir:
fastq_dir = utils.add_full_path(fastq_dir)
config_dir = utils.add_full_path(os.path.dirname(config_file))
galaxy_config_file = utils.add_full_path(config.get("galaxy_config", "universe_wsgi.ini"),
... | Retrieve full paths for directories in the case of relative locations. |
def get_crypt_class(self):
crypt_type = getattr(settings, , )
if crypt_type == :
crypt_class_name =
elif crypt_type == :
crypt_class_name =
else:
raise ImproperlyConfigured(
% crypt_type)
return geta... | Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to Keyczar.
Returns:
keyczar.... |
def movie(self, cycles, plotstyle=,movname=,fps=12,**kwargs):
from matplotlib import animation
iso_abundabu_chartplotiso_abundabu_chartplotplotxlimsylimsxlabelylabellegendlocbestintervalt want to wait for port to do it) check out
these binaries:
http://stackoverflow.com/questions... | Make an interactive movie in the matplotlib window for a number of
different plot types:
Plot types
----------
'iso_abund' : abundance distribution a la se.iso_abund()
'abu_chart' : abundance chart a la se.abu_chart()
'plot' : plot any number... |
def P1(self, value):
if value < self.P2:
self._P1 = value
else:
raise InvalidFirstDisparityChangePenaltyError("P1 must be less "
"than P2.")
self._replace_bm() | Set private ``_P1`` and reset ``_block_matcher``. |
def reset(self):
for i in range(len(self.values)):
self.values[i].delete(0, tk.END)
if self.defaults[i] is not None:
self.values[i].insert(0, self.defaults[i]) | Clears all entries.
:return: None |
def _get_subnets_table(subnets):
table = formatting.Table([,
,
,
])
for subnet in subnets:
table.add_row([subnet.get(, ),
subnet.get(, ),
subnet.get(, ),
... | Yields a formatted table to print subnet details.
:param List[dict] subnets: List of subnets.
:return Table: Formatted for subnet output. |
def print_results(results):
if not isinstance(results, list):
results = [results]
for r in results:
try:
r.log()
except AttributeError:
raise ValueError(
) | Print `results` (the results of validation) to stdout.
Args:
results: A list of FileValidationResults or ObjectValidationResults
instances. |
def coerceType(self, ftype, value):
if value is None:
return None
if ftype == :
return str(value)
elif ftype == :
return str(value)
elif ftype == :
try:
v = int(value)
return str(v)
excep... | Returns unicode(value) after trying to coerce it into the SOLR field type.
@param ftype(string) The SOLR field type for the value
@param value(any) The value that is to be represented as Unicode text. |
def icanhaz(parser, token):
bits = token.contents.split()
if len(bits) not in [2, 3]:
raise template.TemplateSyntaxError(
" tag takes one argument: the name/id of the template")
return ICanHazNode(bits[1]) | Finds the ICanHaz template for the given name and renders it surrounded by
the requisite ICanHaz <script> tags. |
def strip_cdata(text):
if not is_cdata(text):
return text
xml = "<e>{0}</e>".format(text)
node = etree.fromstring(xml)
return node.text | Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped string with CDATA block qualifier... |
async def uint(self, elem, elem_type, params=None):
if self.writing:
return IntegerModel(elem, elem_type.WIDTH) if self.modelize else elem
else:
return elem.val if isinstance(elem, IModel) else elem | Integer types
:param elem:
:param elem_type:
:param params:
:return: |
def filter(self, versions, key=lambda x: x):
return [x for x in versions if self.check(key(x))] | Filter all of the versions in an iterable that match this version range
Args:
versions (iterable): An iterable of SemanticVersion objects
Returns:
list: A list of the SemanticVersion objects that matched this range |
def deserialize(cls, value, trusted=False, strict=False,
assert_valid=False, **kwargs):
if not isinstance(value, dict):
raise ValueError()
identifier = value.pop(, value.get())
if identifier is None:
raise ValueError()
if identifier in... | Create a Singleton instance from a serialized dictionary.
This behaves identically to HasProperties.deserialize, except if
the singleton is already found in the singleton registry the existing
value is used.
.. note::
If property values differ from the existing singleton a... |
def postprocess(self):
for path in self.neb_dirs:
for f in VASP_NEB_OUTPUT_SUB_FILES:
f = os.path.join(path, f)
if os.path.exists(f):
if self.final and self.suffix != "":
shutil.move(f, "{}{}".format(f, sel... | Postprocessing includes renaming and gzipping where necessary. |
def recover_devices(cls):
if "_devices" in globals():
return
global _devices
confs_dir = os.path.abspath(os.path.normpath(cfg.CONF.dhcp_confs))
for netid in os.listdir(confs_dir):
conf_dir = os.path.join(confs_dir, netid)
intf_filename = os.... | Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system. |
def _parse_hosts_contents(self, hosts_contents):
sections = []
cur_section = {
: ,
: None,
: []
}
for line in hosts_contents:
line = line.strip()
if line.startswith() or not line:
continue
e... | Parse the inventory contents. This returns a list of sections found in
the inventory, which can then be used to figure out which hosts belong
to which groups and such. Each section has a name, a type ('hosts',
'children', 'vars') and a list of entries for that section. Entries
consist of... |
def out_format(data, out=, opts=None, **kwargs):
*keyvalue
if not opts:
opts = __opts__
return salt.output.out_format(data, out, opts=opts, **kwargs) | Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default: ``__opts__``.
kwargs
Arguments ... |
def execute(self, sensor_graph, scope_stack):
if self.subtract_stream.stream_type != DataStream.ConstantType:
raise SensorGraphSemanticError("You can only subtract a constant value currently", stream=self.subtract_stream)
parent = scope_stack[-1]
alloc = parent.allocator
... | Execute this statement on the sensor_graph given the current scope tree.
This adds a single node to the sensor graph with subtract as the function
so that the current scope's trigger stream has the subtract_stream's value
subtracted from it.
Args:
sensor_graph (SensorGraph)... |
def authenticate(self, *args, **kwargs):
username = kwargs.get("username", None)
password = kwargs.get("password", None)
authorization = self.ldap_link(username, password, mode=)
if authorization:
user = self.get_or_create_user(usern... | Authenticate the user agains LDAP |
def serve(self, host=, port=8888, limit=100, **kwargs):
if limit <= 0:
raise ValueError(
)
self._server = Server(
host=host,
port=port,
proxies=self._proxies,
timeout=sel... | Start a local proxy server.
The server distributes incoming requests to a pool of found proxies.
When the server receives an incoming request, it chooses the optimal
proxy (based on the percentage of errors and average response time)
and passes to it the incoming request.
In a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.