Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
384,100 | def _refresh(self, session, stopping=False):
s current state.
This must be called under the registryt raise if the work unit is finished
:raises rejester.exceptions.LostLease: if this worker is
no longer doing this work unit
work unit is already finishedwork unit has already ... | Get this task's current state.
This must be called under the registry's lock. It updates
the :attr:`finished` and :attr:`failed` flags and the
:attr:`data` dictionary based on the current state in the
registry.
In the normal case, nothing will change and this function
... |
384,101 | def this_week_day(base_date, weekday):
day_of_week = base_date.weekday()
if day_of_week > weekday:
return next_week_day(base_date, weekday)
start_of_this_week = base_date - timedelta(days=day_of_week + 1)
day = start_of_this_week + timedelta(days=1)
while day.weekday() != week... | Finds coming weekday |
384,102 | def clear_vdp_vsi(self, port_uuid):
try:
LOG.debug("Clearing VDP VSI MAC %(mac)s UUID %(uuid)s",
{: self.vdp_vif_map[port_uuid].get(),
: self.vdp_vif_map[port_uuid].get()})
del self.vdp_vif_map[port_uuid]
except Exception:
... | Stores the vNIC specific info for VDP Refresh.
:param uuid: vNIC UUID |
384,103 | def verify_jwt_in_request_optional():
try:
if request.method not in config.exempt_methods:
jwt_data = _decode_jwt_from_request(request_type=)
ctx_stack.top.jwt = jwt_data
verify_token_claims(jwt_data)
_load_user(jwt_data[config.identity_claim_key])
ex... | Optionally check if this request has a valid access token. If an access
token in present in the request, :func:`~flask_jwt_extended.get_jwt_identity`
will return the identity of the access token. If no access token is
present in the request, this simply returns, and
:func:`~flask_jwt_extended.get_jwt_... |
384,104 | def info(self, category_id, store_view=None, attributes=None):
return self.call(
, [category_id, store_view, attributes]
) | Retrieve Category details
:param category_id: ID of category to retrieve
:param store_view: Store view ID or code
:param attributes: Return the fields specified
:return: Dictionary of data |
384,105 | def process_delivery(message, notification):
mail = message[]
delivery = message[]
if in delivery:
delivered_datetime = clean_time(delivery[])
else:
delivered_datetime = None
deliveries = []
for eachrecipient in delivery[]:
deliveries += [Delivery.objects... | Function to process a delivery notification |
384,106 | def _ns_query(self, session):
return session.query(ORMJob).filter(ORMJob.app == self.app,
ORMJob.namespace == self.namespace) | Return a SQLAlchemy query that is already namespaced by the app and namespace given to this backend
during initialization.
Returns: a SQLAlchemy query object |
384,107 | def parse_alert(output):
for x in output.splitlines():
match = ALERT_PATTERN.match(x)
if match:
rec = {: datetime.strptime(match.group(),
),
: int(match.group()),
: int(match.group()),
... | Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
:param output: A string containing... |
384,108 | def ping(self):
status, _, body = self._request(, self.ping_path())
return(status is not None) and (bytes_to_str(body) == ) | Check server is alive over HTTP |
384,109 | def CompleteHuntIfExpirationTimeReached(hunt_obj):
if (hunt_obj.hunt_state not in [
rdf_hunt_objects.Hunt.HuntState.STOPPED,
rdf_hunt_objects.Hunt.HuntState.COMPLETED
] and hunt_obj.expired):
StopHunt(hunt_obj.hunt_id, reason="Hunt completed.")
data_store.REL_DB.UpdateHuntObject(
... | Marks the hunt as complete if it's past its expiry time. |
384,110 | def parse(self, data):
graph = self._init_graph()
for link in data.get_inner_links():
if link.status != libcnml.libcnml.Status.WORKING:
continue
interface_a, interface_b = link.getLinkedInterfaces()
source = interface_a.ipv4
... | Converts a CNML structure to a NetworkX Graph object
which is then returned. |
384,111 | def authorize(self, email, permission_type=, cloud=None, api_key=None, version=None, **kwargs):
kwargs[] = permission_type
kwargs[] = email
url_params = {"batch": False, "api_key": api_key, "version": version, "method": "authorize"}
return self._api_handler(None, cloud=cloud, ap... | This API endpoint allows you to authorize another user to access your model in a read or write capacity.
Before calling authorize, you must first make sure your model has been registered.
Inputs:
email - String: The email of the user you would like to share access with.
permission_type ... |
384,112 | def keyEvent(self, key, down=1):
self.transport.write(pack("!BBxxI", 4, down, key)) | For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants. |
384,113 | def roc_curve(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8),
xlabel="Probability of False Detection",
ylabel="Probability of Detection",
title="ROC Curve", ticks=np.arange(0, 1.1, 0.1), dpi=300,
legend_params=None, bootstrap_sets=None, ci=(2.5, 9... | Plots a set receiver/relative operating characteristic (ROC) curves from DistributedROC objects.
The ROC curve shows how well a forecast discriminates between two outcomes over a series of thresholds. It
features Probability of Detection (True Positive Rate) on the y-axis and Probability of False Detection
... |
384,114 | def should_expand(self, tag):
return self.indentation is not None and tag and (
not self.previous_indent or (
tag.serializer ==
and tag.subtype.serializer in (, , )
) or (
tag.serializer ==
)
) | Return whether the specified tag should be expanded. |
384,115 | def get_undefined_namespace_names(graph: BELGraph, namespace: str) -> Set[str]:
return {
exc.name
for _, exc, _ in graph.warnings
if isinstance(exc, UndefinedNamespaceWarning) and exc.namespace == namespace
} | Get the names from a namespace that wasn't actually defined.
:return: The set of all names from the undefined namespace |
384,116 | def _train_lbfgs(self, X_feat_train, X_seq_train, y_train,
X_feat_valid, X_seq_valid, y_valid,
graph, var, other_var,
early_stop_patience=None,
n_cores=3):
tic = time.time()
n_epochs = self._param["n_ep... | Train the model actual model
Updates weights / variables, computes and returns the training and validation accuracy |
384,117 | def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], no_cache=None, access_mode=CacheMode.no_cache, **kwargs):
if no_cache is not None:
warnings.warn("The no-cache option has been deprecated and will not be used in future versions of... | Get a cutout from the volume service.
Note that access_mode=no_cache is desirable when reading large amounts of
data at once. In these cases, the data is not first read into the
cache, but instead, is sent directly from the data store to the
requester.
Args... |
384,118 | def label_position(self):
reg_sizes = [(r.size(), r) for r in self.pieces]
reg_sizes.sort()
return reg_sizes[-1][1].label_position() | Find the largest region and position the label in that. |
384,119 | def get_function_for_cognito_trigger(self, trigger):
print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger))
return self.settings.COGNITO_TRIGGER_MAPPING.get(trigger) | Get the associated function to execute for a cognito trigger |
384,120 | def add_job(self, idx):
self.loads[idx] += 1
for lis in (self.targets, self.loads):
lis.append(lis.pop(idx)) | Called after self.targets[idx] just got the job with header.
Override with subclasses. The default ordering is simple LRU.
The default loads are the number of outstanding jobs. |
384,121 | def read(self, source = None, **options):
message = self.read_header(source)
message.data = self.read_data(message.size, message.is_compressed, **options)
return message | Reads and optionally parses a single message.
:Parameters:
- `source` - optional data buffer to be read, if not specified data is
read from the wrapped stream
:Options:
- `raw` (`boolean`) - indicates whether read data should parsed or
returned in raw b... |
384,122 | def dbg_print_irsb(self, irsb_addr, project=None):
if project is None:
project = self._project
if project is None:
raise Exception("Dict addr_to_run is empty. " + \
"Give me a project, and I')
statements[i].pp() | Pretty-print an IRSB with whitelist information |
384,123 | def pass_to_pipeline_if_article(
self,
response,
source_domain,
original_url,
rss_title=None
):
if self.helper.heuristics.is_article(response, original_url):
return self.pass_to_pipeline(
response, source_domain... | Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param ... |
384,124 | def plot_correlated_groups(self, group=None, n_genes=5, **kwargs):
geneID_groups = self.adata.uns[]
if(group is None):
for i in range(len(geneID_groups)):
self.show_gene_expression(geneID_groups[i][0], **kwargs)
else:
for i in range(n_genes):
... | Plots orthogonal expression patterns.
In the default mode, plots orthogonal gene expression patterns. A
specific correlated group of genes can be specified to plot gene
expression patterns within that group.
Parameters
----------
group - int, optional, default None
... |
384,125 | def _should_retry(exc):
if not hasattr(exc, "errors"):
return False
if len(exc.errors) == 0:
return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES)
reason = exc.errors[0]["reason"]
return reason in _RETRYABLE_REASONS | Predicate for determining when to retry.
We retry if and only if the 'reason' is 'backendError'
or 'rateLimitExceeded'. |
384,126 | def scp_file(dest_path, contents=None, kwargs=None, local_file=None):
file_to_upload = None
try:
if contents is not None:
try:
tmpfd, file_to_upload = tempfile.mkstemp()
os.write(tmpfd, contents)
finally:
try:
... | Use scp or sftp to copy a file to a server |
384,127 | def iter_multi_items(mapping):
if isinstance(mapping, MultiDict):
for item in iteritems(mapping, multi=True):
yield item
elif isinstance(mapping, dict):
for key, value in iteritems(mapping):
if isinstance(value, (tuple, list)):
for value in value:
... | Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures. |
384,128 | def save(self, fname, compression=):
egg = {
: df2list(self.pres),
: df2list(self.rec),
: self.dist_funcs,
: self.subjgroup,
: self.subjname,
: self.listgroup,
: self.listname,
: self.date_... | Save method for the Egg object
The data will be saved as a 'egg' file, which is a dictionary containing
the elements of a Egg saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
A name for the file. If the file extension (.egg) is n... |
384,129 | def build(self, construct):
if lib.EnvBuild(self._env, construct.encode()) != 1:
raise CLIPSError(self._env) | Build a single construct in CLIPS.
The Python equivalent of the CLIPS build command. |
384,130 | def rename(self, newpath):
"Move folder to a new name, possibly a whole new path"
params = {: % (self.jfs.username, newpath)}
r = self.jfs.post(self.path,
extra_headers={:},
params=params)
return r | Move folder to a new name, possibly a whole new path |
384,131 | def make_energy_funnel_data(self, cores=1):
if not self.parameter_log:
raise AttributeError(
)
model_cls = self._params[]
gen_tagged = []
for gen, models in enumerate(self.parameter_log):
for model in models:
... | Compares models created during the minimisation to the best model.
Returns
-------
energy_rmsd_gen: [(float, float, int)]
A list of triples containing the BUFF score, RMSD to the
top model and generation of a model generated during the
minimisation. |
384,132 | def precmd(self, line):
if not line.strip():
return line
args = line.split()
while args[0] in self.aliases:
line = self.aliases[args[0]]
ii = 1
for tmpArg in args[1:]:
line = line.replace("%" + str(ii),
... | Handle alias expansion and ';;' separator. |
384,133 | def getCandScoresMap(self, profile):
elecType = profile.getElecType()
if elecType != "soc" and elecType != "toc":
print("ERROR: unsupported election type")
exit()
copelandScores = dict()
for cand in profile.candMap.keys():
... | Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile. |
384,134 | def part_sum(x, i=0):
if i == len(x):
yield 0
else:
for s in part_sum(x, i + 1):
yield s
yield s + x[i] | All subsetsums from x[i:]
:param x: table of values
:param int i: index defining suffix of x to be considered
:iterates: over all values, in arbitrary order
:complexity: :math:`O(2^{len(x)-i})` |
384,135 | def iter_auth_hashes(user, purpose, minutes_valid):
now = timezone.now().replace(microsecond=0, second=0)
for minute in range(minutes_valid + 1):
yield hashlib.sha1(
% (
now - datetime.timedelta(minutes=minute),
user.password,
purpose,
... | Generate auth tokens tied to user and specified purpose.
The hash expires at midnight on the minute of now + minutes_valid, such
that when minutes_valid=1 you get *at least* 1 minute to use the token. |
384,136 | def remove(self, safe=None):
self._session.remove(self, safe=None)
self._session.flush() | Removes the document itself from database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete. |
384,137 | def images(self):
CREATED7 days agoTAGlatestIMAGE ID2298fbaac143VIRTUAL SIZE302.7 MBREPOSITORYtest1
sys_command =
sys_output = self.command(sys_command)
image_list = self._images(sys_output)
return image_list | a method to list the local docker images
:return: list of dictionaries with available image fields
[ {
'CREATED': '7 days ago',
'TAG': 'latest',
'IMAGE ID': '2298fbaac143',
'VIRTUAL SIZE': '302.7 MB',
'REPOSITORY': 'test1... |
384,138 | def start_notebook(self, name, context: dict, fg=False):
assert context
assert type(context) == dict
assert "context_hash" in context
assert type(context["context_hash"]) == int
http_port = self.pick_port()
assert http_port
context = context.copy()
... | Start new IPython Notebook daemon.
:param name: The owner of the Notebook will be *name*. He/she gets a new Notebook content folder created where all files are placed.
:param context: Extra context information passed to the started Notebook. This must contain {context_hash:int} parameter used to ident... |
384,139 | def dafopw(fname):
fname = stypes.stringToCharP(fname)
handle = ctypes.c_int()
libspice.dafopw_c(fname, ctypes.byref(handle))
return handle.value | Open a DAF for subsequent write requests.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafopw_c.html
:param fname: Name of DAF to be opened.
:type fname: str
:return: Handle assigned to DAF.
:rtype: int |
384,140 | def visit_attribute(self, node):
if self._uses_mandatory_method_param(node):
self._accessed.set_accessed(node)
return
if not self.linter.is_message_enabled("protected-access"):
return
self._check_protected_attribute_access(node) | check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods) |
384,141 | def get_logger(name=None, level=logging.DEBUG, stream=None):
logger = logging.getLogger(name)
colored = colorize_logger(logger, stream=stream, level=level)
return colored | returns a colorized logger. This function can be used just like
:py:func:`logging.getLogger` except you can set the level right
away. |
384,142 | def __reorganize_chron_header(line):
d = {}
m = re.split(re_tab_split, line)
if m:
for s in m:
m2 = re.match(re_var_w_units, s)
if m2:
if... | Reorganize the list of variables. If there are units given, log them.
:param str line:
:return dict: key: variable, val: units (optional) |
384,143 | def is_special_string(obj):
import bs4
return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction)) | Is special string. |
384,144 | def _set_row_label(self, value):
"Set the row label format string (empty to hide)"
if not value:
self.wx_obj.SetRowLabelSize(0)
else:
self.wx_obj._table._row_label = value | Set the row label format string (empty to hide) |
384,145 | def get_body(self):
raw_body = yield get_arg(self, 2)
if not self.serializer:
raise tornado.gen.Return(raw_body)
else:
body = self.serializer.deserialize_body(raw_body)
raise tornado.gen.Return(body) | Get the body value from the response.
:return: a future contains the deserialized value of body |
384,146 | def potential_cloud_layer(self, pcp, water, tlow, land_cloud_prob, land_threshold,
water_cloud_prob, water_threshold=0.5):
part1 = (pcp & water & (water_cloud_prob > water_threshold))
part2 = (pcp & ~water & (land_cloud_prob > land_threshold))
temptest = se... | Final step of determining potential cloud layer
Equation 18 (Zhu and Woodcock, 2012)
Saturation (green or red) test is not in the algorithm
Parameters
----------
pcps: ndarray
potential cloud pixels
water: ndarray
water mask
... |
384,147 | def highlight_multiline_block(self, block, start_pattern, end_pattern, state, format):
if self.previousBlockState() == state:
start = 0
extend = 0
else:
start = start_pattern.indexIn(block)
extend = start_pattern.matchedLength()
while st... | Highlights given multiline text block.
:param block: Text block.
:type block: QString
:param pattern: Start regex pattern.
:type pattern: QRegExp
:param pattern: End regex pattern.
:type pattern: QRegExp
:param format: Format.
:type format: QTextCharForma... |
384,148 | def _set_default_configuration_options(app):
app.config.setdefault(, (,))
app.config.setdefault(, )
app.config.setdefault(, )
app.config.setdefault(, )
app.config.setdefault(, )
app.config.setdefault(, )
app.config.s... | Sets the default configuration options used by this extension |
384,149 | def get_registration(self, path):
if not self.is_registered(path):
raise NotRegistered("Email template not registered")
return self._registry[path] | Returns registration item for specified path.
If an email template is not registered, this will raise NotRegistered. |
384,150 | def get_pixel(framebuf, x, y):
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
return (framebuf.buf[index] >> offset) & 0x01 | Get the color of a given pixel |
384,151 | def create_CreateProcessWarnMultiproc(original_name):
def new_CreateProcess(*args):
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
warn_multiproc()
return getattr(_subprocess, original_name)(*args)
return new_CreateProcess | CreateProcess(*args, **kwargs) |
384,152 | def length_range(string, minimum, maximum):
int_range(len(string), minimum, maximum)
return string | Requires values' length to be in a certain range.
:param string: Value to validate
:param minimum: Minimum length to accept
:param maximum: Maximum length to accept
:type string: str
:type minimum: int
:type maximum: int |
384,153 | def check_oscntab(oscntab, ccdamp, xsize, ysize, leading, trailing):
tab = Table.read(oscntab)
ccdamp = ccdamp.lower().rstrip()
for row in tab:
if (row[].lower().rstrip() in ccdamp and
row[] == xsize and row[] == ysize and
row[] == leading and row[] == trailing):... | Check if the supplied parameters are in the
``OSCNTAB`` reference file.
.. note:: Even if an entry does not exist in ``OSCNTAB``,
as long as the subarray does not have any overscan,
it should not be a problem for CALACS.
.. note:: This function does not check the virtual bias r... |
384,154 | def get_playlists(self, search, start=0, max_items=100):
return self.get_music_service_information(, search, start,
max_items) | Search for playlists.
See get_music_service_information for details on the arguments.
Note:
Un-intuitively this method returns MSAlbumList items. See
note in class doc string for details. |
384,155 | def filter_and_save(raw, symbol_ids, destination_path):
logging.info()
new_hw_ds = []
for el in raw[]:
if el[] in symbol_ids:
el[] = symbol_ids[el[]]
el[].formula_id = symbol_ids[el[]]
new_hw_ds.append(el)
raw[] = new_hw_ds
logging.info(, len(ne... | Parameters
----------
raw : dict
with key 'handwriting_datasets'
symbol_ids : dict
Maps LaTeX to write-math.com id
destination_path : str
Path where the filtered dict 'raw' will be saved |
384,156 | def get_source(self, source_id=None, source_name=None):
if not (bool(source_id) ^ bool(source_name)):
raise ValueError()
if source_id:
try:
source_id = int(source_id)
except (ValueError, TypeError):
raise ValueError(
... | Returns a dict with keys ['id', 'name', 'description'] or None if
no match. The ``id`` field is guaranteed to be an int that
exists in table source. Requires exactly one of ``source_id``
or ``source_name``. A new source corresponding to
``source_name`` is created if necessary. |
384,157 | def remove_all_timers(self):
with self.lock:
if self.rtimer is not None:
self.rtimer.cancel()
self.timers = {}
self.heap = []
self.rtimer = None
self.expiring = False | Remove all waiting timers and terminate any blocking threads. |
384,158 | def conversations_setTopic(
self, *, channel: str, topic: str, **kwargs
) -> SlackResponse:
kwargs.update({"channel": channel, "topic": topic})
return self.api_call("conversations.setTopic", json=kwargs) | Sets the topic for a conversation.
Args:
channel (str): The channel id. e.g. 'C1234567890'
topic (str): The new topic for the channel. e.g. 'My Topic' |
384,159 | def rm_eltorito(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInvalidInput()
if self.eltorito_boot_catalog is None:
raise pycdlibexception.PyCdlibInvalidInput()
for brindex, br in enumerate(self.brs):
if br.boot_system_iden... | Remove the El Torito boot record (and Boot Catalog) from the ISO.
Parameters:
None.
Returns:
Nothing. |
384,160 | def ping(self, endpoint=):
r = requests.get(self.url() + "/" + endpoint)
return r.status_code | Ping the server to make sure that you can access the base URL.
Arguments:
None
Returns:
`boolean` Successful access of server (or status code) |
384,161 | def respond_to_contact_info(self, message):
contacts = self.load("contact_info", {})
context = {
"contacts": contacts,
}
contact_html = rendered_template("contact_info.html", context)
self.say(contact_html, message=message) | contact info: Show everyone's emergency contact info. |
384,162 | def path(self):
if len(self.heads) == 1:
return _fmt_mfs_path(self.heads.keys()[0], self.heads.values()[0])
else:
return "(" + "|".join(
_fmt_mfs_path(k, v) for (k, v) in self.heads.items()
) + ")" | The path attribute returns a stringified, concise representation of
the MultiFieldSelector. It can be reversed by the ``from_path``
constructor. |
384,163 | def detrend(x, deg=1):
t=range(len(x))
p = np.polyfit(t, x, deg)
residual = x - np.polyval(p, t)
return residual | remove polynomial from data.
used by autocorr_noise_id()
Parameters
----------
x: numpy.array
time-series
deg: int
degree of polynomial to remove from x
Returns
-------
x_detrended: numpy.array
detrended time-series |
384,164 | def _find_executables(self):
if len(self.needs) > 0:
return
for execname, executable in list(self.module.executables.items()):
skip = False
if any([p.direction == "" for p in executable.ordered_parameters]):
msg.warn("Som... | Finds the list of executables that pass the requirements necessary to have
a wrapper created for them. |
384,165 | def _setup_chassis(self):
self._create_slots(2)
self._slots[0] = self.integrated_adapters[self._chassis]() | Sets up the router with the corresponding chassis
(create slots and insert default adapters). |
384,166 | async def get_chat(self):
if (self._chat is None or getattr(self._chat, , None))\
and await self.get_input_chat():
try:
self._chat =\
await self._client.get_entity(self._input_chat)
except ValueError:
a... | Returns `chat`, but will make an API call to find the
chat unless it's already cached. |
384,167 | def unindent(self):
if self.tab_always_indent:
cursor = self.editor.textCursor()
if not cursor.hasSelection():
cursor.select(cursor.LineUnderCursor)
self.unindent_selection(cursor)
else:
super(PyIndenterMode, self).unindent() | Performs an un-indentation |
384,168 | def addContainer(self, query):
self.setUpdatesEnabled(False)
self.blockSignals(True)
container = XOrbQueryContainer(self)
container.setShowBack(self.count() > 0)
container.enterCompoundRequested.connect(self.enterContainer)
... | Creates a new query container widget object and slides it into
the frame.
:return <XOrbQueryContainer> |
384,169 | def dlopen(ffi, *names):
for name in names:
for lib_name in (name, + name):
try:
path = ctypes.util.find_library(lib_name)
lib = ffi.dlopen(path or lib_name)
if lib:
return lib
except OSError:
p... | Try various names for the same library, for different platforms. |
384,170 | def autocommit(data_access):
if not data_access.autocommit:
data_access.commit()
old_autocommit = data_access.autocommit
data_access.autocommit = True
try:
yield data_access
finally:
data_access.autocommit = old_autocommit | Make statements autocommit.
:param data_access: a DataAccess instance |
384,171 | def match_replace(cls, ops, kwargs):
expr = ProtoExpr(ops, kwargs)
if LOG:
logger = logging.getLogger()
for key, rule in cls._rules.items():
pat, replacement = rule
match_dict = match_pattern(pat, expr)
if match_dict:
try:
replaced = replaceme... | Match and replace a full operand specification to a function that
provides a replacement for the whole expression
or raises a :exc:`.CannotSimplify` exception.
E.g.
First define an operation::
>>> class Invert(Operation):
... _rules = OrderedDict()
... simplifications =... |
384,172 | def handle_modifier_up(self, modifier):
_logger.debug("%s released", modifier)
if modifier not in (Key.CAPSLOCK, Key.NUMLOCK):
self.modifiers[modifier] = False | Updates the state of the given modifier key to 'released'. |
384,173 | def estimate(self, X, **params):
return super(TRAM, self).estimate(X, **params) | Parameters
----------
X : tuple of (ttrajs, dtrajs, btrajs)
Simulation trajectories. ttrajs contain the indices of the thermodynamic state, dtrajs
contains the indices of the configurational states and btrajs contain the biases.
ttrajs : list of numpy.ndarray(X_i, dt... |
384,174 | def edge_tuple(self, vertex0_id, vertex1_id):
pw0 = self.__getitem__(vertex0_id)
pw1 = self.__getitem__(vertex1_id)
if not pw0 or not pw1:
return None
if pw0 < pw1:
return (vertex0_id, vertex1_id)
elif pw0 > pw1:
return (vertex1_id, v... | To avoid duplicate edges where the vertex ids are reversed,
we maintain that the vertex ids are ordered so that the corresponding
pathway names are alphabetical.
Parameters
-----------
vertex0_id : int
one vertex in the edge
vertex1_id : int
the other... |
384,175 | def add(self, key, value):
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(value) | Add an entry to a list preference
Add `value` to the list of entries for the `key` preference. |
384,176 | def interpret(self, config_dict):
value = config_dict.get(self.name)
if value is None:
if self.default is None:
raise RuntimeError( + self.name)
else:
warnings.warn("Using default {!r} for ".format(self.default, self.name),
... | Converts the config_parser output into the proper type,
supplies defaults if available and needed, and checks for some errors. |
384,177 | def all(user, groupby=, summary=, network=False,
split_week=False, split_day=False, filter_empty=True, attributes=True,
flatten=False):
scalar_type = if groupby is not None else
summary_type = if groupby is not None else
number_of_interactions_in = partial(bc.individual.number_of_i... | Returns a dictionary containing all bandicoot indicators for the user,
as well as reporting variables.
Relevant indicators are defined in the 'individual', and 'spatial' modules.
=================================== =======================================================================
Reporting varia... |
384,178 | def comments(self):
if self._comments is None:
self.assert_bind_client()
if self.comment_count > 0:
self._comments = self.bind_client.get_activity_comments(self.id)
else:
self._comments = []
return self._commen... | Iterator of :class:`stravalib.model.ActivityComment` objects for this activity. |
384,179 | def fftlog(fEM, time, freq, ftarg):
r
_, _, q, mu, tcalc, dlnr, kr, rk = ftarg
if mu > 0:
a = -fEM.imag
else:
a = fEM.real
n = a.size
ln2kr = np.log(2.0/kr)
d = np.pi/(n*dlnr)
m = np.arange(1, (n+1)/2)
y = m*d
if q == 0:
zp = speci... | r"""Fourier Transform using FFTLog.
FFTLog is the logarithmic analogue to the Fast Fourier Transform FFT.
FFTLog was presented in Appendix B of [Hami00]_ and published at
<http://casa.colorado.edu/~ajsh/FFTLog>.
This function uses a simplified version of ``pyfftlog``, which is a
python-version of ... |
384,180 | def update_service(self, stack, service, args):
url = .format(self.host, stack, service)
return self.__post(url, args) | 更新服务
更新指定名称服务的配置如容器镜像等参数,容器被重新部署后生效。
如果指定manualUpdate参数,则需要额外调用 部署服务 接口并指定参数进行部署;处于人工升级模式的服务禁止执行其他修改操作。
如果不指定manualUpdate参数,平台会自动完成部署。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
- args: 服务具体描述请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/
... |
384,181 | def insert_instance(self, block):
embed_type = block.get(, None)
data = block.get(, {})
serializer = self.serializers.get(embed_type, None)
if serializer is None:
return block
try:
instance_id = serializer.get_id(data)
instance = se... | Insert a fetched instance into embed block. |
384,182 | def radialvelocity(self, rf=, v0=, off=None):
loc = {: "radialvelocity",
: rf,
: dq.quantity(v0)}
if is_measure(off):
if not off[] == "radialvelocity":
raise TypeError()
loc["offset"] = off
return self.measure(loc, rf... | Defines a radialvelocity measure. It has to specify a reference
code, radialvelocity quantity value (see introduction for the action
on a scalar quantity with either a vector or scalar value, and when
a vector of quantities is given), and optionally it can specify an
offset, which in its... |
384,183 | def save(self):
if hasattr(self, ):
self.pre_save()
database, collection = self._collection_key.split()
self.validate()
_id = current()[database][collection].save(dict(self))
if _id: self._id = _id
if hasattr(self, ):
self.post_save() | Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
validated against it after ... |
384,184 | def _construct_version(self, function, intrinsics_resolver):
code_dict = function.Code
if not code_dict:
raise ValueError("Lambda function code must be a valid non-empty dictionary")
if not intrinsics_resolver:
raise ValueError("intrinsics_resolver is required f... | Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
Old versions will not be deleted without a direct reference from the CloudFormation template.
:param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version
... |
384,185 | def parse_prototype(prototype):
val = .join(prototype.splitlines())
f = match(func_pat, val)
if f is None:
raise Exception(.format(val))
ftp, pointer, name, arg = [v.strip() for v in f.groups()]
args = []
if arg.strip():
for item in split(arg_split_pat, arg):
... | Returns a :attr:`FunctionSpec` instance from the input. |
384,186 | def get_config():
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser(), ))
try:
token = config[][]
path = config[][]
except:
logger.error()
logger.error()
sys.exit()
if os.path.exists(path):
os.chdir(... | Reads the music download filepath from scdl.cfg |
384,187 | def validate_lang(ctx, param, lang):
if ctx.params[]:
return lang
try:
if lang not in tts_langs():
raise click.UsageError(
" not in list of supported languages.\n"
"Use --all to list languages or "
"add --nocheck to disable langua... | Validation callback for the <lang> option.
Ensures <lang> is a supported language unless the <nocheck> flag is set |
384,188 | def compute(cls, observation, prediction):
assert isinstance(observation, dict)
try:
p_value = prediction[]
try:
p_value = prediction[]
p_value = prediction
o_mean = observation[]
o_std = observation[]
value =... | Compute a z-score from an observation and a prediction. |
384,189 | def parse_raml(self):
if utils.is_url(self.ramlfile):
raml = utils.download_file(self.ramlfile)
else:
with codecs.open(self.ramlfile, "rb", encoding="utf-8") as raml_f:
raml = raml_f.read()
loader = ramlfications.loads(raml)
config = raml... | Parse RAML file |
384,190 | def main(args):
of = sys.stdout
if args.output and args.output[-4:] == :
cmd = +args.output
pof = Popen(cmd.split(),stdin=PIPE)
of = pof.stdin
elif args.output:
of = open(args.output,)
header = None
if args.HQ:
cmd = +args.HQ
sys.stderr.write(cmd+"\n")
header = Popen(cmd.split(... | Use the valid input file to get the header information. |
384,191 | def process_into(self, node, obj):
if isinstance(node, BeautifulSoup.NavigableString):
text = self.process_text(node)
if text:
obj.append(text)
return
if node.name == :
new_obj = document.Paragraph()
obj.ap... | Process a BeautifulSoup node and fill its elements into a pyth
base object. |
384,192 | def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
if root is None:
root = {}
root[] =
container = root
container[] = dataset.GetSpacing()
container[] = dataset.GetOrigin()
container[] = dataset.GetExtent()
dump_all_arrays(dataset... | Dump image data object to vtkjs |
384,193 | def afterglow(self, src=None, event=None, dst=None, **kargs):
if src is None:
src = lambda x: x[].src
if event is None:
event = lambda x: x[].dport
if dst is None:
dst = lambda x: x[].dst
sl = {}
el = {}
dl = {}
for i i... | Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst |
384,194 | def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs):
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
... | Auto Generated Code |
384,195 | def get_ccle_mutations():
if request.method == :
return {}
response = request.body.read().decode()
body = json.loads(response)
gene_list = body.get()
cell_lines = body.get()
mutations = cbio_client.get_ccle_mutations(gene_list, cell_lines)
res = {: mutations}
return res | Get CCLE mutations
returns the amino acid changes for a given list of genes and cell lines |
384,196 | def get_mean(self, col, row):
return javabridge.call(self.jobject, "getMean", "(II)D", col, row) | Returns the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the mean
:rtype: float |
384,197 | def gen_textfiles_from_filenames(
filenames: Iterable[str]) -> Generator[TextIO, None, None]:
for filename in filenames:
with open(filename) as f:
yield f | Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object |
384,198 | def subdomain(self, index, value=None):
if value is not None:
subdomains = self.subdomains()
subdomains[index] = value
return URL._mutate(self, host=.join(subdomains))
return self.subdomains()[index] | Return a subdomain or set a new value and return a new :class:`URL`
instance.
:param integer index: 0-indexed subdomain
:param string value: New subdomain |
384,199 | def find_stack_elements(self, module, module_name="", _visited_modules=None):
from types import ModuleType
if _visited_modules is None: _visited_modules = []
_visited_modules.append(module)
elements = []
for el_name in dir(module):
the_el = module.__... | This function goes through the given container and returns the stack elements. Each stack
element is represented by a tuple:
( container_name, element_name, stack_element)
The tuples are returned in an array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.