Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
20,000 | def dock_json_has_plugin_conf(self, plugin_type, plugin_name):
try:
self.dock_json_get_plugin_conf(plugin_type, plugin_name)
return True
except (KeyError, IndexError):
return False | Check whether a plugin is configured. |
20,001 | def add_location_timezone_to_device(self, device_obj, location, timezone):
dictify_device_meta(device_obj)
device_obj[][][][] = location
device_obj[][][][] = location
device_obj[][][][] = timezone
device_obj[][][][] = timezone
return self.update_device(device_obj... | Returns 'device object' with updated location
http://docs.exosite.com/portals/#update-device
http://docs.exosite.com/portals/#device-object |
20,002 | def plate_rate_mc(pole1_plon, pole1_plat, pole1_kappa, pole1_N, pole1_age, pole1_age_error,
pole2_plon, pole2_plat, pole2_kappa, pole2_N, pole2_age, pole2_age_error,
ref_loc_lon, ref_loc_lat, samplesize=10000, random_seed=None, plot=True,
savefig=True, save_director... | Determine the latitudinal motion implied by a pair of poles and utilize
the Monte Carlo sampling method of Swanson-Hysell (2014) to determine the
associated uncertainty.
Parameters:
------------
plon : longitude of pole
plat : latitude of pole
kappa : Fisher precision parameter for VPGs in ... |
20,003 | def get_map_matrix(inputfile, sheet_name):
matrix = read_excel_file(inputfile, sheet_name)
output = [[, , ]]
for row in matrix:
if row[0] and not re.match(r, row[0]):
output.append([row[0], row[1], row[2]])
return output | Return the matrix representation of the genetic map.
:arg inputfile: the path to the input file from which to retrieve the
genetic map.
:arg sheet_name: the excel sheet containing the data on which to
retrieve the genetic map. |
20,004 | def domain_score(self, domains):
warn(
, DeprecationWarning,
)
url_path =
return self._multi_post(url_path, domains) | Calls domain scores endpoint.
This method is deprecated since OpenDNS Investigate API
endpoint is also deprecated. |
20,005 | def calc(args):
from jcvi.formats.fasta import translate
p = OptionParser(calc.__doc__)
p.add_option("--longest", action="store_true",
help="Get longest ORF, only works if no pep file, "\
"e.g. ESTs [default: %default]")
p.add_option("--msa", default="clustal... | %prog calc [prot.fasta] cds.fasta > out.ks
Protein file is optional. If only one file is given, it is assumed to
be CDS sequences with correct frame (frame 0). Results will be written to
stdout. Both protein file and nucleotide file are assumed to be Fasta format,
with adjacent records as the pairs to ... |
20,006 | def bundle_javascript(context: Context):
args = []
if context.verbosity > 0:
args.append()
if not context.use_colour:
args.append()
return context.node_tool(, *args) | Compiles javascript |
20,007 | def construct_variables(self, kwargs):
if isinstance(self.feedable_kwargs, dict):
warnings.warn("Using a dict for `feedable_kwargs is deprecated."
"Switch to using a tuple."
"It is not longer necessary to specify the types "
"of the arguments---... | Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key |
20,008 | def check_response(headers: Headers, key: str) -> None:
connection = sum(
[parse_connection(value) for value in headers.get_all("Connection")], []
)
if not any(value.lower() == "upgrade" for value in connection):
raise InvalidUpgrade("Connection", " ".join(connection))
upgrade = s... | Check a handshake response received from the server.
``key`` comes from :func:`build_request`.
If the handshake is valid, this function returns ``None``.
Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake`
exception.
This function doesn't verify that the response is an HTTP/1.1... |
20,009 | def db_list(**connection_args):
*
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor()
qry =
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = .format(*exc.args)
__context__[] = err
log.error(err)
... | Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list |
20,010 | def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
merged_clusters: List[Set[Tuple[int, int]]] = []
for cluster in clusters.values():
cluster_with_overlapping_mention = None
for mention in cluster:
... | The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans. |
20,011 | def fetch_items(self, category, **kwargs):
from_date = kwargs[]
to_date = kwargs[]
if category == CATEGORY_ISSUE:
items = self.__fetch_issues(from_date, to_date)
elif category == CATEGORY_PULL_REQUEST:
items = self.__fetch_pull_requests(from_date, to_dat... | Fetch the items (issues or pull_requests)
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items |
20,012 | def _chi_lr(self,r, phi, nl,nr,beta):
m=int((nr-nl).real)
n=int((nr+nl).real)
p=int((n-abs(m))/2)
p2=int((n+abs(m))/2)
q=int(abs(m))
if p % 2==0:
prefac=1
else:
prefac=-1
prefactor=prefac/beta**(abs(m)+1)*np.sqrt(math.fact... | computes the generalized polar basis function in the convention of Massey&Refregier eqn 8
:param nl: left basis
:type nl: int
:param nr: right basis
:type nr: int
:param beta: beta --the characteristic scale typically choosen to be close to the size of the object.
:type ... |
20,013 | def _AssertIsLocal(path):
from six.moves.urllib.parse import urlparse
if not _UrlIsLocal(urlparse(path)):
from ._exceptions import NotImplementedForRemotePathError
raise NotImplementedForRemotePathError | Checks if a given path is local, raise an exception if not.
This is used in filesystem functions that do not support remote operations yet.
:param unicode path:
:raises NotImplementedForRemotePathError:
If the given path is not local |
20,014 | def makeCubicxFunc(self,mLvl,pLvl,MedShk,xLvl):
pCount = mLvl.shape[1]
MedCount = mLvl.shape[0]
EndOfPrdvPP = self.DiscFacEff*self.Rfree*self.Rfree*np.sum(self.vPPfuncNext(self.mLvlNext,\
self.pLvlNext)*self.ShkPrbs_temp,axis=0)
EndOfPrdv... | Constructs the (unconstrained) expenditure function for this period using
bilinear interpolation (over permanent income and the medical shock) among
an array of cubic interpolations over market resources.
Parameters
----------
mLvl : np.array
Corresponding market res... |
20,015 | def add(self, username, courseid, taskid, consumer_key, service_url, result_id):
search = {"username": username, "courseid": courseid,
"taskid": taskid, "service_url": service_url,
"consumer_key": consumer_key, "result_id": result_id}
entry = self._database.... | Add a job in the queue
:param username:
:param courseid:
:param taskid:
:param consumer_key:
:param service_url:
:param result_id: |
20,016 | def __alloc_raw_data(self, initial_values=None):
if self.__raw_data == None:
raw_data_type = c_ubyte * self.__raw_report_size
self.__raw_data = raw_data_type()
elif initial_values == self.__raw_data:
return
else:
... | Pre-allocate re-usagle memory |
20,017 | def _next(self, **kwargs):
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_after_entry(query, self._record)
for record in query.order_by(model.Entry.local_date,
... | Get the next item in any particular category |
20,018 | def displayHelp(self):
self.outputStream.write(self.linter.help())
sys.exit(32) | Output help message of twistedchecker. |
20,019 | def install_pip(env, requirements):
try:
installation_source_folder = config.installation_cache_folder()
options = setuptools_install_options(installation_source_folder)
if installation_source_folder is not None:
zip_eggs_in_folder(installation_source_folder)
... | Install pip and its requirements using setuptools. |
20,020 | def unfollow(self, auth_secret, followee_username):
result = {pytwis_constants.ERROR_KEY: None}
loggedin, userid = self._is_loggedin(auth_secret)
if not loggedin:
result[pytwis_constants.ERROR_KEY] = pytwis_constants.ERROR_NOT_LOGGED_IN
return (False, r... | Unfollow a user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
followee_username: str
The username of the followee.
Returns
-------
bool
True if the unfollow is successful, False other... |
20,021 | def simulate():
nest.ResetKernel()
nest.SetKernelStatus({"resolution": dt, "print_time": True,
"overwrite_files": True})
print("Building network")
nest.SetDefaults("iaf_psc_alpha", neuron_params)
nest.SetDefaults("poisson_generator"... | instantiate and execute network simulation |
20,022 | def build(config, services):
filtered_services = {name: service for name, service in services.iteritems() if in service}
_call_output(.format(.join(filtered_services.iterkeys())))
version = _get_version()
for service_name, service_dict in filtered_services.iteritems():
... | Builds images and tags them appropriately.
Where "appropriately" means with the output of:
git describe --tags HEAD
and 'latest' as well (so the "latest" image for each will always be the
most recently built) |
20,023 | def get_credentials(env=None):
environ = env or os.environ
try:
username = environ["TEXTMAGIC_USERNAME"]
token = environ["TEXTMAGIC_AUTH_TOKEN"]
return username, token
except KeyError:
return None, None | Gets the TextMagic credentials from current environment
:param env: environment
:return: username, token |
20,024 | def _delete_file(fileName, n=10):
status = False
count = 0
while not status and count < n:
try:
_os.remove(fileName)
except OSError:
count += 1
_time.sleep(0.2)
else:
status = True
return status | Cleanly deletes a file in `n` attempts (if necessary) |
20,025 | def post_result_data(self, client, check, output, status):
data = {
: client,
: check,
: output,
: status,
}
self._request(, , data=json.dumps(data))
return True | Posts check result data. |
20,026 | def _is_bugged_tarfile(self):
try:
output = subprocess.check_output([, , self.destination]).decode()
return in output and in output
except subprocess.CalledProcessError:
return False | Check for tar file that tarfile library mistakenly reports as invalid.
Happens with tar files created on FAT systems. See:
http://stackoverflow.com/questions/25552162/tarfile-readerror-file-could-not-be-opened-successfully |
20,027 | def rel_path(self, uuid):
_assert_uuid(uuid)
filename = str(uuid)
return Path(filename[0:2], filename[2:4], filename) | Contruct relative path from repository top directory to the file
named after this uuid.
:param:uuid: :class:`UUID` instance |
20,028 | def pipe_split(context, _INPUT, conf, splits, **kwargs):
return Split(context, _INPUT, conf, splits, **kwargs) | An operator that splits a source into identical copies. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : dict
splits : number of copies
Yields
------
_OUTPUT, _OUTPUT2... : copies of all source... |
20,029 | def money_receipts(pronac, dt):
df = verified_repeated_receipts_for_pronac(pronac)
comprovantes_saque = df[df[] == 3.0]
return metric_return(comprovantes_saque) | Checks how many items are in a same receipt when payment type is
withdraw/money
- is_outlier: True if there are any receipts that have more than one
- itens_que_compartilham_comprovantes: List of items that share receipt |
20,030 | def _needs_download(self, f):
@wraps(f)
def wrapper(self, *args, **kwargs):
if not self.isdownloaded():
self.download()
return f(self, *args, **kwargs)
return wrapper | Decorator used to make sure that the downloading happens prior to running the task. |
20,031 | def retrieve_width(self, signum=None, frame=None):
for method_name, args in self.strategies:
method = getattr(self, "from_" + method_name)
width = method(*args)
if width and width > 0:
self.width = width
break
os.environ["COLU... | Stores the terminal width into ``self.width``, if possible.
This function is also the SIGWINCH event handler. |
20,032 | def create_download_specifications(ctx_cli_options, config):
cli_conf = ctx_cli_options[ctx_cli_options[]]
cli_options = cli_conf[]
specs = []
for conf in config[]:
if in conf:
conf_options = conf[]
else:
conf_options = {}
mode = _merge... | Create a list of Download Specification objects from configuration
:param dict ctx_cli_options: cli options
:param dict config: config dict
:rtype: list
:return: list of Download Specification objects |
20,033 | def topology_from_numpy(atoms, bonds=None):
if bonds is None:
bonds = np.zeros((0, 2))
for col in ["name", "element", "resSeq",
"resName", "chainID", "serial"]:
if col not in atoms.dtype.names:
raise ValueError( % col)
if "segmentID" not in atoms.dtype.name... | Create a mdtraj topology from numpy arrays
Parameters
----------
atoms : np.ndarray
The atoms in the topology, represented as a data frame. This data
frame should have columns "serial" (atom index), "name" (atom name),
"element" (atom's element), "resSeq" (index of the residue)
... |
20,034 | def update_dict(self, newdata: dict) -> :
return Language.make(
language=newdata.get(, self.language),
extlangs=newdata.get(, self.extlangs),
script=newdata.get(, self.script),
region=newdata.get(, self.region),
variants=newdata.get(, self.var... | Update the attributes of this Language from a dictionary. |
20,035 | def _is_did(did):
return d1_gmn.app.models.IdNamespace.objects.filter(did=did).exists() | Return True if ``did`` is recorded in a local context.
``did``=None is supported and returns False.
A DID can be classified with classify_identifier(). |
20,036 | def _lrepr_fallback(
o: Any,
human_readable: bool = False,
print_dup: bool = PRINT_DUP,
print_length: PrintCountSetting = PRINT_LENGTH,
print_level: PrintCountSetting = PRINT_LEVEL,
print_meta: bool = PRINT_META,
print_readably: bool = PRINT_READABLY,
) -> str:
kwargs = {
... | Fallback function for lrepr for subclasses of standard types.
The singledispatch used for standard lrepr dispatches using an exact
type match on the first argument, so we will only hit this function
for subclasses of common Python types like strings or lists. |
20,037 | def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
**["foo", "bar"]*["foo", {"bar": "1.2.3-0ubuntu0"}]*[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]<package>old<old-version>new<new-version>
refreshdb = sa... | Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
... |
20,038 | async def purge(self, *, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True):
if check is None:
check = lambda m: True
iterator = self.history(limit=limit, before=before, after=after, oldest_first=oldest_first, around=around)
ret = [... | |coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have the :attr:`~Permissions.manage_messages` permission to
delete messages even if they are y... |
20,039 | def configure(self, *, hwm: int=None, rcvtimeo: int=None, sndtimeo: int=None, linger: int=None) -> :
if hwm is not None:
self.set_hwm(hwm)
if rcvtimeo is not None:
self.setsockopt(zmq.RCVTIMEO, rcvtimeo)
if sndtimeo is not None:
self.setsockopt(zmq.SN... | Allows to configure some common socket options and configurations, while allowing method chaining |
20,040 | def __add_hopscotch_tour_step(self, message, selector=None, name=None,
title=None, alignment=None):
arrow_offset_row = None
if not selector or selector == "html":
selector = "head"
alignment = "bottom"
arrow_offset_row = "arr... | Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attach to.
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.... |
20,041 | def pub_connect(self):
s zmq socket. If a publisher socket
already exists "pub_close" is called before creating and connecting a
new socket.
ipc_modetcptcp://127.0.0.1:{0}tcp_master_publish_pullipc://{0}sock_dirpublish_pull.ipc')
)
log.debug("Connecting to pub ser... | Create and connect this thread's zmq socket. If a publisher socket
already exists "pub_close" is called before creating and connecting a
new socket. |
20,042 | def from_date(cls, date):
try:
date = date.date()
except AttributeError:
pass
return cls(date.year, date.month) | Returns a Month instance from the given datetime.date or
datetime.datetime object |
20,043 | def check_lt(self):
lt_valid = self.request.session.get(, [])
lt_send = self.request.POST.get()
self.gen_lt()
if lt_send not in lt_valid:
return False
else:
self.request.session[].remove(lt_send)
... | Check is the POSTed LoginTicket is valid, if yes invalide it
:return: ``True`` if the LoginTicket is valid, ``False`` otherwise
:rtype: bool |
20,044 | def get_Generic_parameters(tp, generic_supertype):
try:
res = _select_Generic_superclass_parameters(tp, generic_supertype)
except TypeError:
res = None
if res is None:
raise TypeError("%s has no proper parameters defined by %s."%
(type_str(tp), type_str(generic_s... | tp must be a subclass of generic_supertype.
Retrieves the type values from tp that correspond to parameters
defined by generic_supertype.
E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent
to get_Mapping_key_value(tp) except for the error message.
Note that get_Generic_itemtype(tp) is n... |
20,045 | def get_authservers(self, domainid, page=None):
opts = {}
if page:
opts[] = page
return self.api_call(
ENDPOINTS[][],
dict(domainid=domainid), **opts) | Get Authentication servers |
20,046 | def get(self, sid):
return RoomRecordingContext(self._version, room_sid=self._solution[], sid=sid, ) | Constructs a RoomRecordingContext
:param sid: The sid
:returns: twilio.rest.video.v1.room.recording.RoomRecordingContext
:rtype: twilio.rest.video.v1.room.recording.RoomRecordingContext |
20,047 | def _get_name_filter(package, context="decorate", reparse=False):
global name_filters
pkey = (package, context)
if pkey in name_filters and not reparse:
return name_filters[pkey]
from acorn.config import settings
spack = settings(package)
sections = {
"decora... | Makes sure that the name filters for the specified package have been
loaded.
Args:
package (str): name of the package that this method belongs to.
context (str): one of ['decorate', 'time', 'analyze']; specifies which
section of the configuration settings to check. |
20,048 | def count_account(self, domain):
selector = domain.to_selector()
cos_list = self.request_list(, {: selector})
ret = []
for i in cos_list:
count = int(i[])
ret.append((zobjects.ClassOfService.from_dict(i), count))
return list(ret) | Count the number of accounts for a given domain, sorted by cos
:returns: a list of pairs <ClassOfService object>,count |
20,049 | def plot(self, colorbar=True, cb_orientation=,
cb_label=, show=True, **kwargs):
return self.geoid.plot(colorbar=colorbar,
cb_orientation=cb_orientation,
cb_label=cb_label, show=True, **kwargs) | Plot the geoid.
Usage
-----
x.plot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation,
cb_label, show, fname, **kwargs])
Parameters
----------
tick_interval : list or tuple, optional, default = [30, 30]
Intervals to use when plottin... |
20,050 | def allLocales(self):
if self._allLocales:
return self._allLocales
expr = re.compile()
locales = babel.core.localedata.locale_identifiers()
babel_locales = {}
for locale in locales:
if expr.match(locale):
babel_l... | Returns all the locales that are defined within the babel
architecture.
:return [<str>, ..] |
20,051 | def convert_cg3_to_conll( lines, **kwargs ):
\""Rio de JaneiroRio_de_Janeiro
if not isinstance( lines, list ):
raise Exception()
fix_selfrefs = True
fix_open_punct = True
unesc_quotes = True
rep_spaces = False
error_on_unexp = False
for argName, argVal in kwargs.items() :... | Converts the output of VISL_CG3 based syntactic parsing into CONLL format.
Expects that the output has been cleaned ( via method cleanup_lines() ).
Returns a list of CONLL format lines;
Parameters
-----------
lines : list of str
The input text for the pipelin... |
20,052 | def prj_create_atype(self, *args, **kwargs):
if not self.cur_prj:
return
atype = self.create_atype(projects=[self.cur_prj])
if atype:
atypedata = djitemdata.AtypeItemData(atype)
treemodel.TreeItem(atypedata, self.prj_atype_model.root) | Create a new project
:returns: None
:rtype: None
:raises: None |
20,053 | def set_icon(self, icon):
s icon image'
self._icon = icon
return self._listitem.setIconImage(icon) | Sets the listitem's icon image |
20,054 | def close_comments(self, request, queryset):
queryset.update(comment_enabled=False)
self.message_user(
request, _()) | Close the comments for selected entries. |
20,055 | def report_command_error(self, error_dict):
error = dict(error_dict)
error["command"] = self.commands[error_dict["step"]]
error["target"] = self.frame
del error["index"]
del error["step"]
self.errors.append(error) | Report a server error executing a command.
We keep track of the command's position in the command list,
and we add annotation of what the command was, to the error.
:param error_dict: The server's error dict for the error encountered |
20,056 | def get(self, obj, cls):
method = self._cache.get(cls)
if not method:
name = "visit_" + cls.__name__.lower()
method = getattr(obj, name, obj.visit_default)
self._cache[cls] = method
return method | Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,
or `obj.visit_default` if the type-specific method is not found. |
20,057 | def has_parser(self, url_info: URLInfo):
key = self.url_info_key(url_info)
return key in self._parsers | Return whether a parser has been created for the URL. |
20,058 | def min_base_quality(self):
try:
return min(self.base_qualities)
except ValueError:
assert self.offset_start == self.offset_end
adjacent_qualities = [
self.alignment.query_qualities[offset]
for offset in [self.offs... | The minimum of the base qualities. In the case of a deletion, in which
case there are no bases in this PileupElement, the minimum is taken
over the sequenced bases immediately before and after the deletion. |
20,059 | def checkValidCell(self, index):
col = index.column()
row = index.row()
return self.model.isFieldValid(row, self._headers[index.column()]) | Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` |
20,060 | def _add_sj_index_commands(fq1, ref_file, gtf_file):
if _has_sj_index(ref_file):
return ""
else:
rlength = fastq.estimate_maximum_read_length(fq1)
cmd = " --sjdbGTFfile %s " % gtf_file
cmd += " --sjdbOverhang %s " % str(rlength - 1)
return cmd | newer versions of STAR can generate splice junction databases on thephfly
this is preferable since we can tailor it to the read lengths |
20,061 | def _parse_plan(self, match):
expected_tests = int(match.group("expected"))
directive = Directive(match.group("directive"))
if directive.text and not directive.skip:
return Unknown()
return Plan(expected_tests, directive) | Parse a matching plan line. |
20,062 | def _read_stdin():
line = sys.stdin.readline()
while line:
yield line
line = sys.stdin.readline() | Generator for reading from standard input in nonblocking mode.
Other ways of reading from ``stdin`` in python waits, until the buffer is
big enough, or until EOF character is sent.
This functions yields immediately after each line. |
20,063 | def toggle_aggregation_layer_combo(self):
selected_hazard_layer = layer_from_combo(self.hazard_layer_combo)
selected_exposure_layer = layer_from_combo(self.exposure_layer_combo)
if ((self.aggregation_layer_combo.count() > 1)
and (selected_hazard_layer is not No... | Toggle the aggregation combo enabled status.
Whether the combo is toggled on or off will depend on the current dock
status. |
20,064 | def _add_method_setting(self, conn, api_id, stage_name, path, key, value,
op):
logger.debug(,
op, path, str(value))
res = conn.update_stage(
restApiId=api_id,
stageName=stage_name,
patchOperations=[
... | Update a single method setting on the specified stage. This uses the
'add' operation to PATCH the resource.
:param conn: APIGateway API connection
:type conn: :py:class:`botocore:APIGateway.Client`
:param api_id: ReST API ID
:type api_id: str
:param stage_name: stage nam... |
20,065 | def siret_validator():
def _validate_siret(form, field, siret=""):
if field is not None:
siret = (field.data or "").strip()
if len(siret) != 14:
msg = _("SIRET must have exactly 14 characters ({count})").format(
count=len(siret)
)
... | Validate a SIRET: check its length (14), its final code, and pass it
through the Luhn algorithm. |
20,066 | def save_subresource(self, subresource):
data = deepcopy(subresource._resource)
data.pop(, None)
data.pop(self.resource_type + , None)
subresources = getattr(self, subresource.parent_key, {})
subresources[subresource.id] = data
setattr(self, subresource.parent_k... | Save the sub-resource
NOTE: Currently assumes subresources are stored within a dictionary,
keyed with the subresource's ID |
20,067 | def scan(self,
table_name,
index_name=None,
consistent_read=None,
projection_expression=None,
filter_expression=None,
expression_attribute_names=None,
expression_attribute_values=None,
segment=None,
tota... | The `Scan`_ operation returns one or more items and item attributes
by accessing every item in a table or a secondary index.
If the total number of scanned items exceeds the maximum data set size
limit of 1 MB, the scan stops and results are returned to the user as a
``LastEvaluatedKey`... |
20,068 | def run(name,
cmd,
container_type=None,
exec_driver=None,
output=None,
no_start=False,
stdin=None,
python_shell=True,
output_loglevel=,
ignore_retcode=False,
path=None,
use_vt=False,
keep_env=None):
ps aux
valid_outp... | Common logic for running shell commands in containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.run mycontainer 'ps aux' container_type=docker exec_driver=nsenter outp... |
20,069 | def resolve_address(endpoint_type=PUBLIC, override=True):
resolved_address = None
if override:
resolved_address = _get_address_override(endpoint_type)
if resolved_address:
return resolved_address
vips = config()
if vips:
vips = vips.split()
net_type = ADDRE... | Return unit address depending on net config.
If unit is clustered with vip(s) and has net splits defined, return vip on
correct network. If clustered with no nets defined, return primary vip.
If not clustered, return unit address ensuring address is on configured net
split if one is configured, or a J... |
20,070 | def count(self, conn, filters):
pipe, intersect, temp_id = self._prepare(conn, filters)
pipe.zcard(temp_id)
pipe.delete(temp_id)
return pipe.execute()[-2] | Returns the count of the items that match the provided filters.
For the meaning of what the ``filters`` argument means, see the
``.search()`` method docs. |
20,071 | def rank_subgraph_by_node_filter(graph: BELGraph,
node_predicates: Union[NodePredicate, Iterable[NodePredicate]],
annotation: str = ,
reverse: bool = True,
) -> List[Tuple[str, int]]:
... | Rank sub-graphs by which have the most nodes matching an given filter.
A use case for this function would be to identify which subgraphs contain the most differentially expressed
genes.
>>> from pybel import from_pickle
>>> from pybel.constants import GENE
>>> from pybel_tools.integration import o... |
20,072 | def verify2(self, atv_public_key, data):
self._check_initialized()
log_binary(_LOGGER, , PublicSecret=atv_public_key, Data=data)
public = curve25519.Public(atv_public_key)
shared = self._verify_private.get_shared_key(
public, hashfunc=lambda x: x)
... | Last device verification step. |
20,073 | def define_batch_env(constructor, num_agents, env_processes):
with tf.variable_scope():
if env_processes:
envs = [
tools.wrappers.ExternalProcess(constructor)
for _ in range(num_agents)]
else:
envs = [constructor() for _ in range(num_agents)]
batch_env = tools.BatchEnv(e... | Create environments and apply all desired wrappers.
Args:
constructor: Constructor of an OpenAI gym environment.
num_agents: Number of environments to combine in the batch.
env_processes: Whether to step environment in external processes.
Returns:
In-graph environments object. |
20,074 | def p_gate_op_3(self, program):
program[0] = node.CustomUnitary([program[1], program[4]])
self.verify_as_gate(program[1], program[4])
self.verify_bit_list(program[4])
self.verify_distinct([program[4]]) | gate_op : id '(' ')' id_list ';' |
20,075 | def get_operation_ast(
document_ast: DocumentNode, operation_name: Optional[str] = None
) -> Optional[OperationDefinitionNode]:
operation = None
for definition in document_ast.definitions:
if isinstance(definition, OperationDefinitionNode):
if not operation_name:
... | Get operation AST node.
Returns an operation AST given a document AST and optionally an operation
name. If a name is not provided, an operation is only returned if only one
is provided in the document. |
20,076 | def append_to_path (path, directory):
if not os.path.isdir(directory) or directory in path:
return path
if not path.endswith(os.pathsep):
path += os.pathsep
return path + directory | Add a directory to the PATH environment variable, if it is a valid
directory. |
20,077 | def get_iso_time(date_part, time_part):
r
str_date = datetime.datetime.strptime(
date_part, ).strftime()
str_time = datetime.datetime.strptime(
time_part, ).strftime()
return str_date + "T" + str_time + "-7:00" | r"""Combign date and time into an iso datetime. |
20,078 | def shutdown(self):
if not process.proc_alive(self.proc):
return
logger.info("Attempting to connect to %s", self.hostname)
client = self.connection
attempts = 2
for i in range(attempts):
logger.info("Attempting to send s... | Send shutdown command and wait for the process to exit. |
20,079 | def check_environment_temperature(the_session, the_helper, the_snmp_value, the_unit=1):
a_snmp_unit = snmpSessionBaseClass.get_data(
the_session,
apc_oid_environment_temperature_unit,
the_helper)
snmp_units = {
: ,
:
}
a_unit = snmp_units.get(a_snmp_u... | OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1
MIB Excerpt
The current temperature reading from the probe displayed
in the units shown in the 'iemStatusProbeTempUnits' OID
(Celsius or Fahrenheit).
Description of unit OID
OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.5
The temperature scale used to display t... |
20,080 | def ConvertFromWireFormat(self, value, container=None):
result = self.type()
ReadIntoObject(value[2], 0, result)
return result | The wire format is simply a string. |
20,081 | def get_request_token(
cls, consumer_key, redirect_uri=, state=None
):
headers = {
: ,
}
url =
payload = {
: consumer_key,
: redirect_uri,
}
if state:
payload[] = state
return cls._make_reques... | Returns the request token that can be used to fetch the access token |
20,082 | def do_drawing(self, size, frame, cairo_ctx):
if self.get_window() and not self.bot_size:
self.set_size_request(*size)
self.bot_size = size
self.backing_store = BackingStore.get_backingstore(self.width, self.height)
cr = pycairo.Context(self.backing_st... | Update the backing store from a cairo context and
schedule a redraw (expose event)
:param size: width, height in pixels of bot
:param frame: frame # thar was drawn
:param cairo_ctx: cairo context the bot was drawn on |
20,083 | def prefix_fragment(self, nid):
sep=
if nid.startswith():
if in nid:
sep=
else:
sep=
parts = nid.split(sep)
frag = parts.pop()
prefix = sep.join(parts)
return prefix, frag | Return prefix and fragment/localid for a node |
20,084 | def response(request, status, obj):
request.setResponseCode(status)
request.responseHeaders.setRawHeaders(
u"content-type", [u"application/json"],
)
body = dumps_bytes(obj)
return body | Generate a response.
:param IRequest request: The request being responsed to.
:param int status: The response status code to set.
:param obj: Something JSON-dumpable to write into the response body.
:return bytes: The response body to write out. eg, return this from a
*render_* method. |
20,085 | def use_in(ContentHandler):
ContentHandler = table.use_in(ContentHandler)
def startTable(self, parent, attrs, __orig_startTable = ContentHandler.startTable):
name = table.StripTableName(attrs[u"Name"])
if name in TableByName:
return TableByName[name](attrs)
return __orig_startTable(self, parent, attrs)
... | Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table
classes defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHand... |
20,086 | def isOriginalLocation(attr):
sourceModule = inspect.getmodule(attr.load())
if sourceModule is None:
return False
currentModule = attr
while not isinstance(currentModule, PythonModule):
currentModule = currentModule.onObject
return currentModule.name == sourceModule.__name__ | Attempt to discover if this appearance of a PythonAttribute
representing a class refers to the module where that class was
defined. |
20,087 | def next_chunk_boundaries_levels(self, buf, prepend_bytes=0):
boundaries = {}
for level_index, chunker in enumerate(self._chunkers):
boundaries.update(
dict([(boundary, level_index) for boundary in chunker.next_chunk_boundaries(buf, prepend_bytes)]))
return s... | Computes the next chunk boundaries within `buf`.
Similar to :meth:`.next_chunk_boundaries`, but information about which chunker led to a respective boundary is
included in the returned value.
Args:
buf (bytes): The message that is to be chunked.
prepend_bytes (Optional[... |
20,088 | def altitudes_send(self, time_boot_ms, alt_gps, alt_imu, alt_barometric, alt_optical_flow, alt_range_finder, alt_extra, force_mavlink1=False):
return self.send(self.altitudes_encode(time_boot_ms, alt_gps, alt_imu, alt_barometric, alt_optical_flow, alt_range_finder, alt_extra), force_mav... | The altitude measured by sensors and IMU
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
alt_gps : GPS altitude in meters, expressed as * 1000 (millimeters), above MSL (int32_t)
alt_imu : IMU altitude ... |
20,089 | def xml2object(self, content):
r
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options[] else self.parse_full(element)
if not self.__options[]:
node = self.get_node(element)
if not self.__options[]... | r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2 |
20,090 | def newer(new_ver, old_ver, strict=False):
if old_ver == new_ver or old_ver + (0,) == new_ver:
return False
for n, o in zip(new_ver, old_ver):
if not isinstance(n, int):
o = str(o)
if o < n:
return True
elif o > n:
return False
return ... | Determines if the first version tuple is newer than the second.
True if newer, False if older, None if difference is after specified version parts. |
20,091 | def chords(chord_labels, intervals, fs, **kwargs):
util.validate_intervals(intervals)
roots, interval_bitmaps, _ = chord.encode_many(chord_labels)
chromagram = np.array([np.roll(interval_bitmap, root)
for (interval_bitmap, root)
in zip(interva... | Synthesizes chord labels
Parameters
----------
chord_labels : list of str
List of chord label strings.
intervals : np.ndarray, shape=(len(chord_labels), 2)
Start and end times of each chord label
fs : int
Sampling rate to synthesize at
kwargs
Additional keyword a... |
20,092 | def smartplugs(self):
return [SmartPlug(self, plug.get())
for plug in self._state.get(,
{}).get(, [])
if plug.get()] | :return: A list of smartplug objects. |
20,093 | def setHandler(self,handler,cbfn):
async-responsesregistrations-expiredde-registrationsreg-updatesregistrationsnotifications
if handler == "async-responses":
self.async_responses_callback = cbfn
elif handler == "registrations-expired":
self.registrations_expired_callback = cbfn
elif handler == "de-registr... | Register a handler for a particular notification type.
These are the types of notifications that are acceptable.
| 'async-responses'
| 'registrations-expired'
| 'de-registrations'
| 'reg-updates'
| 'registrations'
| 'notifications'
:param str handler: name of the notification type
:param fnptr cb... |
20,094 | def getHelpFileAsString(taskname,taskpath):
pathsplit=os.path.split(taskpath)
else:
helpname = taskname
localdir = pathsplit[0]
if localdir == :
localdir =
helpfile=rglob(localdir,helpname+".help")[0]
if os.access(helpfile,os.R_OK):
fh=open(helpfile,)
... | This functions will return useful help as a string read from a file
in the task's installed directory called "<module>.help".
If no such file can be found, it will simply return an empty string.
Notes
-----
The location of the actual help file will be found under the task's
installed directory... |
20,095 | def OnLineWidth(self, event):
linewidth_combobox = event.GetEventObject()
idx = event.GetInt()
width = int(linewidth_combobox.GetString(idx))
borders = self.bordermap[self.borderstate]
post_command_event(self, self.BorderWidthMsg, width=width,
... | Line width choice event handler |
20,096 | def ogrn(self) -> str:
numbers = []
for _ in range(0, 12):
numbers.append(self.random.randint(1 if _ == 0 else 0, 9))
ogrn = .join([str(x) for x in numbers])
check_sum = str(int(ogrn) % 11 % 10)
return .format(ogrn, check_sum) | Generate random valid ``OGRN``.
:return: OGRN.
:Example:
4715113303725. |
20,097 | def read(self, n=None):
response = ""
while n is None or n > 0:
c = self.stream.read(1)
if c == "":
break
elif c == "<":
c += self.stream.read(1)
if c == "<?":
while True:
... | Read at most *n* characters from this stream.
If *n* is ``None``, return all available characters. |
20,098 | def lmfit_parameters(self):
p0 = []
for param in self.fitting_parameters:
opts = param[].copy() if in param else {}
if in opts: opts[] = prefix_factor(param) * opts[]
if in opts: opts[] = prefix_factor(param) * opts[]
p0.append((prefix_factor(p... | A [`lmfit.Parameters`][1] object built from `scipy_data_fitting.Fit.fitting_parameters`,
see `scipy_data_fitting.Fit.parameters`.
Each parameters is assigned a key of the form `p_00000`, `p_00001`, `p_00002`, etc.
Thus, `sorted(self.lmfit_parameters)` will give the keys in the same
orde... |
20,099 | def make_label_index(self, stream_item):
labels = stream_item.body.labels.get(self.annotator_id)
if not labels:
labels = []
self.label_index = SortedCollection(
[l for l in labels if OffsetType.CHARS in l.offsets],
key=lambda label: label.offsets[Off... | make a sortedcollection on body.labels |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.