Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
362,700 | def label_from_instance(self, obj):
return % (self.level_indicator * getattr(obj, obj._mptt_meta.level_attr), obj) | Creates labels which represent the tree level of each node when
generating option labels. |
362,701 | def nvrtcDestroyProgram(self, prog):
code = self._lib.nvrtcDestroyProgram(byref(prog))
self._throw_on_error(code)
return | Destroys the given NVRTC program object. |
362,702 | def add_button(self, name, button_class=wtf_fields.SubmitField, **options):
self._buttons[name] = button_class(**options) | Adds a button to the form. |
362,703 | def send_xapi_statements(self, lrs_configuration, days):
for course_enrollment in self.get_course_enrollments(lrs_configuration.enterprise_customer, days):
try:
send_course_enrollment_statement(lrs_configuration, course_enrollment)
except ClientError:
... | Send xAPI analytics data of the enterprise learners to the given LRS.
Arguments:
lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations
of the LRS where to send xAPI learner analytics.
days (int): Include course enrollment of this n... |
362,704 | def _make_client_with_token(self, token):
cached_clients = getattr(self, , None)
hashed_token = _hash_token(self, token)
if cached_clients and hashed_token in cached_clients:
return cached_clients[hashed_token]
client = self.make_client(token)
if cached_c... | Uses cached client or create new one with specific token. |
362,705 | def create_key_translating_dot_dict(
new_class_name,
translation_tuples,
base_class=DotDict
):
class DotDictWithKeyTranslations(base_class):
def __init__(self, *args, **kwargs):
self.__dict__[] = translation_tuples
super(DotDictWithKeyTranslations, self).__init... | this function will generate a DotDict derivative class that has key
translation built in. If the key is not found, translations (as specified
by the translation_tuples) are performed on the key and the lookup is
tried again. Only on failure of this second lookup will the KeyError
exception be raised.
... |
362,706 | def delete_files(self, ids):
self.check_owner()
if not isinstance(ids, list):
raise TypeError("You must specify list of files to delete!")
self.conn.make_call("deleteFiles", ids) | Remove one or more files |
362,707 | def prox_unity(X, step, axis=0):
return X / np.sum(X, axis=axis, keepdims=True) | Projection onto sum=1 along an axis |
362,708 | def lorem(anon, obj, field, val):
return .join(anon.faker.sentences(field=field)) | Generates a paragraph of lorem ipsum text |
362,709 | def get_composition_notification_session_for_repository(self,
composition_receiver=None,
repository_id=None,
proxy=None):
... | Gets the composition notification session for the given repository.
arg: composition_receiver
(osid.repository.CompositionReceiver): the notification
callback
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a ... |
362,710 | def get_native_default_args():
native_default_args = dict(max_jobs=500,
time_per_cycle=15,
jobs_per_cycle=20,
max_job_age=90,
no_batch=False)
return native_default_args.copy() | Get the correct set of batch jobs arguments. |
362,711 | def luhn_checksum(num: str) -> str:
check = 0
for i, s in enumerate(reversed(num)):
sx = int(s)
sx = sx * 2 if i % 2 == 0 else sx
sx = sx - 9 if sx > 9 else sx
check += sx
return str(check * 9 % 10) | Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number. |
362,712 | def bucket_create(self, name, bucket_type=,
bucket_password=, replicas=0, ram_quota=1024,
flush_enabled=False):
params = {
: name,
: bucket_type,
: ,
: bucket_password if bucket_password else ,
: int... | Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bucket to create. This
can either be `couchbase` to create a couchbase style
bucket (which persists data and supports replication) or
`memcached` (which is... |
362,713 | def clean(self, text, **kwargs):
text = stringify(text)
if text is not None:
return self.clean_text(text, **kwargs) | Create a more clean, but still user-facing version of an
instance of the type. |
362,714 | def calc_neg_log_likelihood_and_neg_gradient(beta,
design_3d,
alt_IDs,
rows_to_obs,
rows_to_alts,
... | Parameters
----------
beta : 1D ndarray.
All elements should by ints, floats, or longs. Should have 1 element
for each utility coefficient being estimated (i.e. num_features +
num_coefs_being_mixed).
design_3d : 3D ndarray.
All elements should be ints, floats, or longs. Shou... |
362,715 | def log(fn):
def func(*args, **kwargs):
arg_string = ""
for i in range(0, len(args)):
var_name = fn.__code__.co_varnames[i]
if var_name != "self":
arg_string += var_name + ":" + str(args[i]) + ","
arg_string = arg_string[0:len(arg_string) - 1]
... | logs parameters and result - takes no arguments |
362,716 | def demote(self, mode):
mode_control = {
: dict(stop=, checkpoint=False, release=False, offline=True, async_req=False),
: dict(stop=, checkpoint=True, release=True, offline=False, async_req=False),
: dict(stop=, checkpoint=False, release=True,... | Demote PostgreSQL running as master.
:param mode: One of offline, graceful or immediate.
offline is used when connection to DCS is not available.
graceful is used when failing over to another node due to user request. May only be called running async.
immediate is used when ... |
362,717 | def morphy_stem(word, pos=None):
word = word.lower()
if pos is not None:
if pos.startswith():
pos =
elif pos.startswith():
pos =
elif pos.startswith():
pos =
elif pos.startswith():
pos =
if pos is None and word.endswith... | Get the most likely stem for a word. If a part of speech is supplied,
the stem will be more accurate.
Valid parts of speech are:
- 'n' or 'NN' for nouns
- 'v' or 'VB' for verbs
- 'a' or 'JJ' for adjectives
- 'r' or 'RB' for adverbs
Any other part of speech will be treated as unknown. |
362,718 | def _parse_version_reply(self):
"waiting for a version reply"
if len(self._data) >= 2:
reply = self._data[:2]
self._data = self._data[2:]
(version, method) = struct.unpack(, reply)
if version == 5 and method in [0x00, 0x02]:
self.version_re... | waiting for a version reply |
362,719 | def get_default_runner(udf_class, input_col_delim=, null_indicator=, stdin=None):
proto = udf.get_annotation(udf_class)
in_types, out_types = parse_proto(proto)
stdin = stdin or sys.stdin
arg_parser = ArgParser(in_types, stdin, input_col_delim, null_indicator)
stdin_feed = make_feed(arg_parser)... | Create a default runner with specified udf class. |
362,720 | def walk_transitive_dependency_graph(self,
addresses,
work,
predicate=None,
postorder=False,
dep_predicate=None,
... | Given a work function, walks the transitive dependency closure of `addresses` using DFS.
:API: public
:param list<Address> addresses: The closure of `addresses` will be walked.
:param function work: The function that will be called on every target in the closure using
the specified traversal order.
... |
362,721 | def init_write_line(self):
format_list = self._format_list
output_info = self.gen_output_fmt(format_list)
self._output_fmt = "".join([sub[0] for sub in output_info])
self._out_gen_fmt = [sub[1] for sub in output_info if sub[1] is not None]
self._out_widths = [sub[2] for ... | init_write_line() initializes fields relevant to output generation |
362,722 | def lub(self, other):
return self.__class__(
[
max(self.lower, other.lower),
max(self.upper, other.upper),
],
lower_inc=self.lower_inc if self < other else other.lower_inc,
upper_inc=self.upper_inc if self > other else othe... | Return the least upper bound for given intervals.
:param other: AbstractInterval instance |
362,723 | def get_digest(self):
hashes_per_fragment = FRAGMENT_LENGTH // Hash.LEN
key_fragments = self.iter_chunks(FRAGMENT_LENGTH)
digest = [0] * HASH_LENGTH * len(key_fragments)
for i, fragment in enumerate(key_fragments):
fragment_trits = fragm... | Generates the digest used to do the actual signing.
Signing keys can have variable length and tend to be quite long,
which makes them not-well-suited for use in crypto algorithms.
The digest is essentially the result of running the signing key
through a PBKDF, yielding a constant-lengt... |
362,724 | def set_keyvault_secret(access_token, vault_uri, secret_name, secret_value):
endpoint = .join([vault_uri,
, secret_name,
, ])
current_time = datetime.datetime.now().isoformat()
attributes = {: current_time,
: True,
: None,
... | Adds a secret to a key vault using the key vault URI.
Creates a new version if the secret already exists.
Args:
access_token (str): A valid Azure authentication token.
vault_uri (str): Vault URI e.g. https://myvault.vault.azure.net.
secret_name (str): Name of the secret to add.
... |
362,725 | def create(resource_path, previous_version=None, package=):
pkg, obj = resource_path.rsplit(, 1)
module = importlib.import_module(pkg)
resource = getattr(module, obj)
version = uuid4().hex
target_module = importlib.import_module(package)
target_dir = os.path.dirname(target_module.__file__)
... | Create a new migration |
362,726 | def visit_Set(self, node):
demodef foo(a, b): return {a, b}|a||b|
if node.elts:
elts_aliases = {ContainerOf(alias)
for elt in node.elts
for alias in self.visit(elt)}
else:
elts_aliases = None
return self.add(... | A set is abstracted as an unordered container of its elements
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {a, b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Set)
... |
362,727 | def has_style(node):
elements = [, , , , , , , , , , ]
return any([True for elem in elements if elem in node.rpr]) | Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False |
362,728 | def overwrite_source_file(self, lines_to_write):
tmp_filename = .format(self.input_file)
ok = False
try:
with open(tmp_filename, ) as fh:
fh.writelines(lines_to_write)
ok = True
finally:
if ok:
if platform.syste... | overwrite the file with line_to_write
:param lines_to_write: lines to write to the file - they should be \n terminated
:type lines_to_write: List[str]
:return: None |
362,729 | def complete_file(self, text, line, *_):
leading = line[len("file ") :]
curpath = os.path.join(os.path.curdir, leading)
def isdql(parent, filename):
return not filename.startswith(".") and (
os.path.isdir(os.path.join(parent, filename))
... | Autocomplete DQL file lookup |
362,730 | def upload(clk_json, project, apikey, server, output, verbose):
if verbose:
log("Uploading CLK data from {}".format(clk_json.name))
log("To Entity Matching Server: {}".format(server))
log("Project ID: {}".format(project))
log("Uploading CLK data to the server")
response = p... | Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin. |
362,731 | def search_point(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None):
WORLDVIEW01QUICKBIRD02
searchAreaWkt = "POLYGON ((%s %s, %s %s, %s %s, %s %s, %s %s))" % (lng, lat,lng,lat,lng,lat,lng,lat,lng,lat)
return self.search(searchAreaWkt=searchAreaWkt, filters=filters... | Perform a catalog search over a specific point, specified by lat,lng
Args:
lat: latitude
lng: longitude
filters: Array of filters. Optional. Example:
[
"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')",
... |
362,732 | def set_itunes_categories(self):
self.itunes_categories = []
temp_categories = self.soup.findAll()
for category in temp_categories:
category_text = category.get()
self.itunes_categories.append(category_text) | Parses and set itunes categories |
362,733 | def get_predictions(genes):
data = {
: [],
: [],
: [],
: []
}
for gene_obj in genes:
for pred_key in data:
gene_key = pred_key[:-1]
if len(genes) == 1:
value = gene_obj.get(gene_key, )
else:
gene... | Get sift predictions from genes. |
362,734 | def list(self, count=None, **kwargs):
return list(self.iter(count=count, **kwargs)) | Retrieves a list of entities in this collection.
The entire collection is loaded at once and is returned as a list. This
function makes a single roundtrip to the server, plus at most two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
There is no caching--every ca... |
362,735 | def full(self, asvector=False):
sz = self.n.copy()
if self.r[0] > 1:
sz = _np.concatenate(([self.r[0]], sz))
if self.r[self.d] > 1:
sz = _np.concatenate(([self.r[self.d]], sz))
if (_np.iscomplex(self.core).any()):
a = _tt_f90.tt_f90.z... | Returns full array (uncompressed).
.. warning::
TT compression allows to keep in memory tensors much larger than ones PC can handle in
raw format. Therefore this function is quite unsafe; use it at your own risk.
:returns: numpy.ndarray -- full tensor. |
362,736 | def hist(self, breaks="sturges", plot=True, **kwargs):
server = kwargs.pop("server") if "server" in kwargs else False
assert_is_type(breaks, int, [numeric], Enum("sturges", "rice", "sqrt", "doane", "fd", "scott"))
assert_is_type(plot, bool)
assert_is_type(server, bool)
i... | Compute a histogram over a numeric column.
:param breaks: Can be one of ``"sturges"``, ``"rice"``, ``"sqrt"``, ``"doane"``, ``"fd"``, ``"scott"``;
or a single number for the number of breaks; or a list containing the split points, e.g:
``[-50, 213.2123, 9324834]``. If breaks is "fd", th... |
362,737 | def accounts(self, id=None):
return Account.load(self, id) if id else Account.all(self) | Returns a collection of advertiser :class:`Accounts` available to
the current access token. |
362,738 | def search_browser(self, text):
self.impl.get(self.base_url)
search_div = self.impl.find_element_by_id("search")
search_term = search_div.find_element_by_id("term")
search_term.send_keys(text)
search_div.find_element_by_id("submit").click()
e = self.impl.find_element_by_css_selector("table... | do a slow search via the website and return the first match |
362,739 | def pack(fmt, *args):
formatdef, endianness, i = getmode(fmt)
args = list(args)
n_args = len(args)
result = []
while i < len(fmt):
num, i = getNum(fmt, i)
cur = fmt[i]
try:
format = formatdef[cur]
except KeyError:
raise StructError("%s is not a valid format" % cur)
if num ==... | pack(fmt, v1, v2, ...) -> string
Return string containing values v1, v2, ... packed according to fmt.
See struct.__doc__ for more on format strings. |
362,740 | def colormapper(value, lower=0, upper=1, cmap=None):
cmap = get_cmap(cmap)
if upper - lower == 0:
rgba = cmap(0)
else:
rgba = cmap((value - lower) / float(upper - lower))
hex_ = rgb2hex(rgba)
return hex_ | Maps values to colors by normalizing within [a,b], obtaining rgba from the
given matplotlib color map for heatmap polygon coloring.
Parameters
----------
value: float
The value to be colormapped
lower: float
Lower bound of colors
upper: float
Upper bound of colors
cm... |
362,741 | def call_method(self, method, *args):
message = self._version.create_request(method, args)
msgid = message[]
try:
with switch_back(self._timeout) as switcher:
self._method_calls[msgid] = switcher
self.send_message(message)
args... | Call a JSON-RPC method and wait for its result.
The *method* is called with positional arguments *args*.
On success, the ``result`` field from the JSON-RPC response is
returned. On error, a :class:`JsonRpcError` is raised, which you can
use to access the ``error`` field of the JSON-RP... |
362,742 | async def waitfini(self, timeout=None):
if self.isfini:
return True
if self.finievt is None:
self.finievt = asyncio.Event()
return await s_coro.event_wait(self.finievt, timeout) | Wait for the base to fini()
Returns:
None if timed out, True if fini happened
Example:
base.waitfini(timeout=30) |
362,743 | def _periodic_callback(self):
try:
self.notify(self._state)
except Exception:
self._error_callback(*sys.exc_info())
if self._subscriptions:
self._call_later_handle = \
self._loop.call_later(self._interval, self._perio... | Will be started on first emit |
362,744 | def _extract_links_from_asset_tags_in_text(self, text):
asset_tags_map = self._extract_asset_tags(text)
ids = list(iterkeys(asset_tags_map))
if not ids:
return {}
asset_urls = self._extract_asset_urls(ids)
supplement_links = {}
... | Scan the text and extract asset tags and links to corresponding
files.
@param text: Page text.
@type text: str
@return: @see CourseraOnDemand._extract_links_from_text |
362,745 | def _readline(self, timeout=1):
line = self.port.readline(timeout=timeout)
return strip_escape(line.strip()) if line is not None else line | Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None |
362,746 | def wash_html_id(dirty):
import re
if not dirty[0].isalpha():
dirty = + dirty
non_word = re.compile(r)
return non_word.sub(, dirty) | Strip non-alphabetic or newline characters from a given string.
It can be used as a HTML element ID (also with jQuery and in all browsers).
:param dirty: the string to wash
:returns: the HTML ID ready string |
362,747 | def _api_call(self, method_name, *args, **kwargs):
params = kwargs.setdefault(, {})
params.update({: self._apikey})
if self._token is not None:
params.update({: self._token})
http_method = getattr(requests, method_name)
return http_method(TRELLO_URL + self._... | Makes the HTTP request. |
362,748 | def _auditpol_cmd(cmd):
ret = salt.modules.cmdmod.run_all(cmd=.format(cmd),
python_shell=True)
if ret[] == 0:
return ret[].splitlines()
msg = .format(cmd)
msg += .join(ret[])
raise CommandExecutionError(msg) | Helper function for running the auditpol command
Args:
cmd (str): the auditpol command to run
Returns:
list: A list containing each line of the return (splitlines)
Raises:
CommandExecutionError: If the command encounters an error |
362,749 | def missingDataValue(self):
value = dataSetMissingValue(self._h5Dataset)
fieldNames = self._h5Dataset.dtype.names
if hasattr(value, ) and len(value) == len(fieldNames):
idx = fieldNames.index(self.nodeName)
return value[idx]
else:
... | Returns the value to indicate missing data. None if no missing-data value is specified. |
362,750 | def extract_asset_tags(dstore, tagname):
tagcol = dstore[]
if tagname:
yield tagname, barray(tagcol.gen_tags(tagname))
for tagname in tagcol.tagnames:
yield tagname, barray(tagcol.gen_tags(tagname)) | Extract an array of asset tags for the given tagname. Use it as
/extract/asset_tags or /extract/asset_tags/taxonomy |
362,751 | def add_permission_by_name(self, code, save=False):
if not save:
return ["%s | %s" % (p.name, p.code) for p in
Permission.objects.filter(code__contains=code)]
for p in Permission.objects.filter(code__contains=code):
if p not in self.Permissions:
... | Adds a permission with given name.
Args:
code (str): Code name of the permission.
save (bool): If False, does nothing. |
362,752 | def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True,
a=1.0, alpha=0.602, c=1.0, gamma=0.101,
disp=False, callback=None):
A = 0.01 * niter
if bounds is not None:
bounds = np.asarray(bounds)
project = lambda x: np.clip(x, bounds[:, 0], bo... | Minimization of an objective function by a simultaneous perturbation
stochastic approximation algorithm.
This algorithm approximates the gradient of the function by finite differences
along stochastic directions Deltak. The elements of Deltak are drawn from
+- 1 with probability one half. The gradient ... |
362,753 | def get_hline():
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl(, token=Token.Line)) | gets a horiztonal line |
362,754 | def _serialization_helper(self, ray_forking):
if ray_forking:
actor_handle_id = compute_actor_handle_id(
self._ray_actor_handle_id, self._ray_actor_forks)
else:
actor_handle_id = self._ray_actor_handle_id
state = {
"... | This is defined in order to make pickling work.
Args:
ray_forking: True if this is being called because Ray is forking
the actor handle and false if it is being called by pickling.
Returns:
A dictionary of the information needed to reconstruct the object. |
362,755 | def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter,
ytol=None, full_output=False, disp=True):
s C bisect routine.
'
fa = f(a, *args)
fb = f(b, *args)
if fa*fb > 0.0:
raise ValueError("f(a) and f(b) must have different signs")
elif fa == 0.0:
retu... | Port of SciPy's C bisect routine. |
362,756 | def declare_var(self, key, val):
if val is not None:
line = "export " + key + + str(val)
else:
line = "unset " + key
self._add(line) | Declare a env variable. If val is None the variable is unset. |
362,757 | def out_nbrs(self, node):
l = map(self.tail, self.out_edges(node))
return l | List of nodes connected by outgoing edges |
362,758 | def resolve(self, event_handler, *custom_filters, **full_config
) -> typing.List[typing.Union[typing.Callable, AbstractFilter]]:
filters_set = []
filters_set.extend(self._resolve_registered(event_handler,
{k: v for k, v in full... | Resolve filters to filters-set
:param event_handler:
:param custom_filters:
:param full_config:
:return: |
362,759 | def MultiDeleteAttributes(self,
subjects,
attributes,
start=None,
end=None,
sync=True):
for subject in subjects:
self.DeleteAttributes(
subject, attributes... | Remove all specified attributes from a list of subjects.
Args:
subjects: The list of subjects that will have these attributes removed.
attributes: A list of attributes.
start: A timestamp, attributes older than start will not be deleted.
end: A timestamp, attributes newer than end will not ... |
362,760 | def get_remote_console_url(self, ip=None):
uri = "{}/remoteConsoleUrl".format(self.data["uri"])
if ip:
uri = "{}?ip={}".format(uri, ip)
return self._helper.do_get(uri) | Generates a Single Sign-On (SSO) session for the iLO Integrated Remote Console Application (IRC) and returns the
URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the
IRC application will prompt for credentials. Use of this URL requires a previo... |
362,761 | def __get_all_scrapers_modules(self):
modules = []
file = os.path.realpath(__file__)
folder = os.path.dirname(file)
for filename in os.listdir(folder + "/../scrapers"):
if filename.endswith("Scraper.py") and not filename.startswith("Base"):
modules... | Find all available scraper modules.
Returns:
list(obj): The scraper modules. |
362,762 | def create_subscription_in_enrollment_account(
self, enrollment_account_name, body, custom_headers=None, raw=False, polling=True, **operation_config):
raw_result = self._create_subscription_in_enrollment_account_initial(
enrollment_account_name=enrollment_account_name,
... | Creates an Azure subscription.
:param enrollment_account_name: The name of the enrollment account to
which the subscription will be billed.
:type enrollment_account_name: str
:param body: The subscription creation parameters.
:type body:
~azure.mgmt.subscription.models... |
362,763 | def onion_study(in_conn, out_conn, data_source):
onion = OnionStudy(in_connector=in_conn, out_connector=out_conn, data_source=data_source)
ndocs = onion.analyze()
return ndocs | Build and index for onion from a given Git index.
:param in_conn: ESPandasConnector to read from.
:param out_conn: ESPandasConnector to write to.
:param data_source: name of the date source to generate onion from.
:return: number of documents written in ElasticSearch enriched index. |
362,764 | def read_units(self, fid):
lin = self.read_line(fid)
while lin[0] != :
parts = lin.split()
if parts[0]==:
self.mass = float(parts[1])
elif parts[0]==:
self.length = float(parts[1])
elif parts[0]==... | Read units from an acclaim skeleton file stream. |
362,765 | def getMaxRow(self, login, tableName, auths, startRow, startInclusive, endRow, endInclusive):
self.send_getMaxRow(login, tableName, auths, startRow, startInclusive, endRow, endInclusive)
return self.recv_getMaxRow() | Parameters:
- login
- tableName
- auths
- startRow
- startInclusive
- endRow
- endInclusive |
362,766 | def create(configs):
objs = []
for c in configs:
sniffer_type = c["Type"]
sniffer_subtype = c["SubType"]
interface = c["Interface"]
base_configs = c["BaseConfigs"]
module_name = "mobly.controllers.sniffer_lib.{}.{}".format(
sniffer_type, sniffer_subtype)
... | Initializes the sniffer structures based on the JSON configuration. The
expected keys are:
* Type: A first-level type of sniffer. Planned to be 'local' for
sniffers running on the local machine, or 'remote' for sniffers
running remotely.
* SubType: The specific sniffer type ... |
362,767 | def p_duration_duration_unit(self, p):
logger.debug(, p[1])
p[0] = Duration.from_quantity_unit(1, p[1]) | duration : DURATION_UNIT |
362,768 | def detect_model_name(string):
match = re.match(MODEL_NAME_REGEX, string)
if match:
return match.group()
return None | Takes a string related to a model name and extract its model name.
For example:
'000000-bootstrap.index' => '000000-bootstrap' |
362,769 | def init_camera(
self, feature_dimensions, map_size, camera_width_world_units):
if not map_size or not camera_width_world_units:
raise ValueError(
"Either pass the game_info with raw enabled, or map_size and "
"camera_width_world_units in order to use feature_units or camera"
... | Initialize the camera (especially for feature_units).
This is called in the constructor and may be called repeatedly after
`Features` is constructed, since it deals with rescaling coordinates and not
changing environment/action specs.
Args:
feature_dimensions: See the documentation in `AgentInte... |
362,770 | def fill_rect(setter, x, y, w, h, color=None, aa=False):
for i in range(x, x + w):
_draw_fast_vline(setter, i, y, h, color, aa) | Draw solid rectangle with top-left corner at x,y, width w and height h |
362,771 | def f2tc(f,base=25):
try:
f = int(f)
except:
return "--:--:--:--"
hh = int((f / base) / 3600)
mm = int(((f / base) / 60) - (hh*60))
ss = int((f/base) - (hh*3600) - (mm*60))
ff = int(f - (hh*3600*base) - (mm*60*base) - (ss*base))
return "{:02d}:{:02d}:{:02d}:{:02d}".forma... | Converts frames to timecode |
362,772 | async def update_group_memory(self, memory_id, mode, name, slaves, codectype=0x0040, bitrate=0x0003):
act = self.service.action("X_UpdateGroupMemory")
res = await act.async_call(MemoryID=memory_id,
GroupMode=mode,
GroupName=n... | Update existing memory? Can be used to create new ones, too? |
362,773 | def AsRegEx(self):
parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value)
result = u"".join(self._ReplaceRegExPart(p) for p in parts)
return rdf_standard.RegularExpression(u"(?i)\\A%s\\Z" % result) | Return the current glob as a simple regex.
Note: No interpolation is performed.
Returns:
A RegularExpression() object. |
362,774 | def add_surface(self, name, surface):
assert surface is not None
if hasattr(self.module, name):
raise ThriftCompilerError(
% name
)
setattr(self.module, name, surface) | Adds a top-level attribute with the given name to the module. |
362,775 | def sporco_cupy_patch_module(name, attrib=None):
pname = re.sub(, , name)
if attrib is None:
attrib = {}
attrib.update({: cp})
mod = patch_module(name, pname, pfile=, attrib=attrib)
mod.__spec__.has_location = False
return mod | Create a copy of the named sporco module, patch it to replace
numpy with cupy, and register it in ``sys.modules``.
Parameters
----------
name : string
Name of source module
attrib : dict or None, optional (default None)
Dict of attribute names and values to assign to patched module
... |
362,776 | def computeSaturationLevels(outputs, outputsShape, sparseForm=False):
if not sparseForm:
outputs = outputs.reshape(outputsShape)
spOut = SM32(outputs)
else:
if len(outputs) > 0:
assert (outputs.max() < outputsShape[0] * outputsShape[1])
spOut = SM32(1, outputsShape[0] * outputsShape[1])... | Compute the saturation for a continuous level. This breaks the level into
multiple regions and computes the saturation level for each region.
Parameters:
--------------------------------------------
outputs: output of the level. If sparseForm is True, this is a list of
the non-zeros. If ... |
362,777 | def dict(self):
from collections import OrderedDict
d = OrderedDict(
[(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in (,)])
if in self.data:
d[] = len(self.data[])
else:
d[] = None
if self.data:
... | A dict that holds key/values for all of the properties in the
object.
:return: |
362,778 | def create_travis_config(self):
test_runner = self.config["options_test_runner"]
role_url = "{0}".format(os.path.join(self.config["scm_host"],
self.config["scm_user"],
self.config["scm_repo_prefix"] +
... | Create a travis test setup. |
362,779 | def delete_items(self, url, container, container_object=None):
headers, container_uri = self._return_base_data(
url=url,
container=container,
container_object=container_object
)
return self._deleter(uri=container_uri, headers=headers) | Deletes an objects in a container.
:param url:
:param container: |
362,780 | def recordsDF(token=, version=):
df = pd.DataFrame(records(token, version))
_toDatetime(df)
return df | https://iexcloud.io/docs/api/#stats-records
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result |
362,781 | def GetSubkeyByPath(self, key_path):
pyregf_key = self._pyregf_key.get_sub_key_by_path(key_path)
if not pyregf_key:
return None
key_path = key_paths.JoinKeyPath([self._key_path, key_path])
return REGFWinRegistryKey(pyregf_key, key_path=key_path) | Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. |
362,782 | def _big_endian_int(bits: np.ndarray) -> int:
result = 0
for e in bits:
result <<= 1
if e:
result |= 1
return result | Returns the big-endian integer specified by the given bits.
For example, [True, False, False, True, False] becomes binary 10010 which
is 18 in decimal.
Args:
bits: Descending bits of the integer, with the 1s bit at the end.
Returns:
The integer. |
362,783 | def chop_sequence(sequence, limit_length):
return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)] | Input sequence is divided on smaller non-overlapping sequences with set length. |
362,784 | def is_touched(self, pin):
assert pin >= 0 and pin < 12,
t = self.touched()
return (t & (1 << pin)) > 0 | Return True if the specified pin is being touched, otherwise returns
False. |
362,785 | def find(self, name):
for i, nm in enumerate(self.data):
if nm[-1] == name:
return i
return -1 | Return the index of the toc entry with name NAME.
Return -1 for failure. |
362,786 | def parse_jupytext_args(args=None):
parser = argparse.ArgumentParser(
description=,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(,
help=,
nargs=)
parser.add_argument(,
dest=,
... | Command line parser for jupytext |
362,787 | def image_mapped(name):
try:
out = check_output([, ])
if six.PY3:
out = out.decode()
except CalledProcessError:
return False
return name in out | Determine whether a RADOS block device is mapped locally. |
362,788 | def listener(cls, name=None):
if name is not None and not isinstance(name, str):
raise TypeError(.format(name))
def decorator(func):
actual = func
if isinstance(actual, staticmethod):
actual = actual.__func__
if not inspect.iscor... | A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`.Bot.listen`.
Parameters
------------
name: :class:`str`
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
-... |
362,789 | def get_unstresses(stresses: List[int], count: int) -> List[int]:
return list(set(range(count)) - set(stresses)) | Given a list of stressed positions, and count of possible positions, return a list of
the unstressed positions.
:param stresses: a list of stressed positions
:param count: the number of possible positions
:return: a list of unstressed positions
>>> get_unstresses([0, 3, 6, 9, 12, 15], 17)
[1, ... |
362,790 | def edit(self,
name,
description=None,
homepage=None,
private=None,
has_issues=None,
has_wiki=None,
has_downloads=None,
default_branch=None):
edit = {: name, : description, : homepage,
... | Edit this repository.
:param str name: (required), name of the repository
:param str description: (optional), If not ``None``, change the
description for this repository. API default: ``None`` - leave
value unchanged.
:param str homepage: (optional), If not ``None``, cha... |
362,791 | def label_count(self, label_list_ids=None):
count = collections.defaultdict(int)
for utterance in self.utterances.values():
for label_value, utt_count in utterance.label_count(label_list_ids=label_list_ids).items():
count[label_value] += utt_count
return co... | Return a dictionary containing the number of times, every label-value in this corpus is occurring.
Args:
label_list_ids (list): If not None, only labels from label-lists with an id contained in this list
are considered.
Returns:
dict: A dictio... |
362,792 | def request(self,message,message_type):
if message_type == MULTIPART:
raise Exception("Unsupported request type")
super(Requestor,self).send(message,message_type) | Send a request message of the given type
Args:
- message: the message to publish
- message_type: the type of message being sent |
362,793 | def variants_of(
graph: BELGraph,
node: Protein,
modifications: Optional[Set[str]] = None,
) -> Set[Protein]:
if modifications:
return _get_filtered_variants_of(graph, node, modifications)
return {
v
for u, v, key, data in graph.edges(keys=True, data=True)
... | Returns all variants of the given node. |
362,794 | def log_weights(self):
m = self.kernel.feature_log_prob_[self._match_class_pos()]
u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]
return self._prob_inverse_transform(m - u) | Log weights as described in the FS framework. |
362,795 | def _get_softmax_name(self):
for layer in self.model.layers:
cfg = layer.get_config()
if in cfg and cfg[] == :
return layer.name
raise Exception("No softmax layers found") | Looks for the name of the softmax layer.
:return: Softmax layer name |
362,796 | def _fetch(self):
while True:
url = self._to_fetch.get()
try:
if url:
page = self.get_page(url)
if page is None:
continue
for link, rel in page.links:
... | Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread. |
362,797 | def tile_overlap(inner, outer, norm=False):
div = 1.0/inner.volume if norm else 1.0
return div*(inner.volume - util.Tile.intersection(inner, outer).volume) | How much of inner is in outer by volume |
362,798 | def cli(obj, customer, match, delete):
client = obj[]
if delete:
client.delete_customer(delete)
else:
if not customer:
raise click.UsageError()
if not match:
raise click.UsageError()
try:
customer = client.create_customer(customer, mat... | Add group/org/domain/role-to-customer or delete lookup entry. |
362,799 | def print_hex(data):
hex_msg = ""
for c in data:
hex_msg += "\\x" + format(c, "02x")
_LOGGER.debug(hex_msg) | Debugging method to print out frames in hex. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.