Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
9,000 | def _list(self, request, start_response):
configs = []
generator = directory_list_generator.DirectoryListGenerator(request)
for config in self._config_manager.configs.itervalues():
if config != self.API_CONFIG:
configs.append(config)
directory = generator.pretty_print_config_to_json(c... | Sends HTTP response containing the API directory.
This calls start_response and returns the response body.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defined in PEP-333.
Returns:
A string containing the resp... |
9,001 | def undoable(generator):
descriptive text
def inner(*args, **kwargs):
action = _Action(generator, args, kwargs)
ret = action.do()
stack().append(action)
if isinstance(ret, tuple):
if len(ret) == 1:
return ret[0]
elif len(ret) == ... | Decorator which creates a new undoable action type.
This decorator should be used on a generator of the following format::
@undoable
def operation(*args):
do_operation_code
yield 'descriptive text'
undo_operator_code |
9,002 | def from_arg_kinds(cls, arch, fp_args, ret_fp=False, sizes=None, sp_delta=None, func_ty=None):
basic = cls(arch, sp_delta=sp_delta, func_ty=func_ty)
basic.args = basic.arg_locs(fp_args, sizes)
basic.ret_val = basic.fp_return_val if ret_fp else basic.return_val
return basic | Get an instance of the class that will extract floating-point/integral args correctly.
:param arch: The Archinfo arch for this CC
:param fp_args: A list, with one entry for each argument the function can take. True if the argument is fp,
false if it is integral.
... |
9,003 | def output_default(paragraphs, fp=sys.stdout, no_boilerplate=True):
for paragraph in paragraphs:
if paragraph.class_type == :
if paragraph.heading:
tag =
else:
tag =
elif no_boilerplate:
continue
else:
tag... | Outputs the paragraphs as:
<tag> text of the first paragraph
<tag> text of the second paragraph
...
where <tag> is <p>, <h> or <b> which indicates
standard paragraph, heading or boilerplate respecitvely. |
9,004 | def do_command(self):
method = self.args[0]
raw_args = self.args[1:]
if in method:
if raw_args:
self.parser.error("Please don=,')
self.execute(self.open(), method, self.cooked(raw_args)) | Call a single command with arguments. |
9,005 | def hpre(*content, sep=):
return _md(quote_html(_join(*content, sep=sep)), symbols=MD_SYMBOLS[7]) | Make mono-width text block (HTML)
:param content:
:param sep:
:return: |
9,006 | def format_docstring(elt, arg_comments:dict={}, alt_doc_string:str=, ignore_warn:bool=False)->str:
"Merge and format the docstring definition with `arg_comments` and `alt_doc_string`."
parsed = ""
doc = parse_docstring(inspect.getdoc(elt))
description = alt_doc_string or f"{doc[]} {doc[]}"
if descri... | Merge and format the docstring definition with `arg_comments` and `alt_doc_string`. |
9,007 | def ReadClientLastPings(self,
min_last_ping=None,
max_last_ping=None,
fleetspeak_enabled=None,
cursor=None):
query = "SELECT client_id, UNIX_TIMESTAMP(last_ping) FROM clients "
query_values = []
wher... | Reads client ids for all clients in the database. |
9,008 | def get_model_choices():
result = []
for ct in ContentType.objects.order_by(, ):
try:
if issubclass(ct.model_class(), TranslatableModel):
result.append(
(.format(ct.app_label, ct.model.lower()),
.format(ct.app_label.capitalize(), ... | Get the select options for the model selector
:return: |
9,009 | def repr_failure(self, excinfo):
exc = excinfo.value
cc = self.colors
if isinstance(exc, NbCellError):
msg_items = [
cc.FAIL + "Notebook cell execution failed" + cc.ENDC]
formatstring = (
cc.OKBLUE + "Cell %d: %s\n\n" +
... | called when self.runtest() raises an exception. |
9,010 | def text_to_qcolor(text):
color = QColor()
if not is_string(text):
text = str(text)
if not is_text_string(text):
return color
if text.startswith() and len(text)==7:
correct =
for char in text:
if char.lower() not in correct:
return color... | Create a QColor from specified string
Avoid warning from Qt when an invalid QColor is instantiated |
9,011 | def lookup(self, subcmd_prefix):
for subcmd_name in list(self.subcmds.keys()):
if subcmd_name.startswith(subcmd_prefix) \
and len(subcmd_prefix) >= \
self.subcmds[subcmd_name].__class__.min_abbrev:
return self.subcmds[subcmd_name]
pa... | Find subcmd in self.subcmds |
9,012 | def is_empty_shape(sh: ShExJ.Shape) -> bool:
return sh.closed is None and sh.expression is None and sh.extra is None and \
sh.semActs is None | Determine whether sh has any value |
9,013 | def scan_temperature_old(self, measure, temperature, rate, delay=1):
self.activity =
self.sweep_table.clear()
current_temperature = self.control_temperature
sweep_time = abs((temperature - current_temperature) / rate)
self.sweep_table[0] = t... | Performs a temperature scan.
Measures until the target temperature is reached.
:param measure: A callable called repeatedly until stability at target
temperature is reached.
:param temperature: The target temperature in kelvin.
:param rate: The sweep rate in kelvin per minu... |
9,014 | def clean_ticker(ticker):
pattern = re.compile()
res = pattern.sub(, ticker.split()[0])
return res.lower() | Cleans a ticker for easier use throughout MoneyTree
Splits by space and only keeps first bit. Also removes
any characters that are not letters. Returns as lowercase.
>>> clean_ticker('^VIX')
'vix'
>>> clean_ticker('SPX Index')
'spx' |
9,015 | def _elements(self, IDs, func, aspList):
res = []
for asp in aspList:
if (asp in [0, 180]):
if func == self.N:
res.extend([func(ID, asp) for ID in IDs])
else:
res.extend([func(ID) for ID in IDs]... | Returns the IDs as objects considering the
aspList and the function. |
9,016 | def load_agents(self, config_file=None):
if config_file is not None:
self.overall_config = config_file
self.agents.clear()
num_participants = get_num_players(self.overall_config)
try:
for i in range(num_participants):
self.load_agent(i)
... | Loads all agents for this team from the rlbot.cfg
:param config_file: A config file that is similar to rlbot.cfg |
9,017 | def pre_calc(self, x, y, beta, n_order, center_x, center_y):
x_ = x - center_x
y_ = y - center_y
n = len(np.atleast_1d(x))
H_x = np.empty((n_order+1, n))
H_y = np.empty((n_order+1, n))
if n_order > 170:
raise ValueError(, n_order)
for n in ran... | calculates the H_n(x) and H_n(y) for a given x-array and y-array
:param x:
:param y:
:param amp:
:param beta:
:param n_order:
:param center_x:
:param center_y:
:return: list of H_n(x) and H_n(y) |
9,018 | def htmldiff_tokens(html1_tokens, html2_tokens):
result = cleanup_delete(result)
return result | Does a diff on the tokens themselves, returning a list of text
chunks (not tokens). |
9,019 | def _set_mstp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=mstp.mstp, is_container=, presence=True, yang_name="mstp", rest_name="mstp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u: {u:... | Setter method for mstp, mapped from YANG variable /protocol/spanning_tree/mstp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mstp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mstp() dire... |
9,020 | def _get_input_for_run(args, executable, preset_inputs=None, input_name_prefix=None):
exec_inputs = try_call(ExecutableInputs,
executable,
input_name_prefix=input_name_prefix,
active_region=args.region)
if args... | Returns an input dictionary that can be passed to executable.run() |
9,021 | def _file_filter(cls, filename, include_patterns, exclude_patterns):
logger.debug(.format(filename))
for exclude_pattern in exclude_patterns:
if exclude_pattern.match(filename):
return False
if include_patterns:
found = False
for include_pattern in include_patterns:
if... | :returns: `True` if the file should be allowed through the filter. |
9,022 | def _update_roster(self):
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.fopen(roster_file, ) as roster_fp:
roster_fp.write(
... | Update default flat roster with the passed in information.
:return: |
9,023 | def files(self):
self._printer()
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
if not path.startswith():
self.fil... | Return list of files in root directory |
9,024 | def _moments_central(data, center=None, order=1):
data = np.asarray(data).astype(float)
if data.ndim != 2:
raise ValueError()
if center is None:
from ..centroids import centroid_com
center = centroid_com(data)
indices = np.ogrid[[slice(0, i) for i in data.shape]]
ypo... | Calculate the central image moments up to the specified order.
Parameters
----------
data : 2D array-like
The input 2D array.
center : tuple of two floats or `None`, optional
The ``(x, y)`` center position. If `None` it will calculated as
the "center of mass" of the input ``da... |
9,025 | def layer_tagger_mapping(self):
return {
PARAGRAPHS: self.tokenize_paragraphs,
SENTENCES: self.tokenize_sentences,
WORDS: self.tokenize_words,
ANALYSIS: self.tag_analysis,
TIMEXES: self.tag_timexes,
NAMED_ENTITIES: self.tag_named_e... | Dictionary that maps layer names to taggers that can create that layer. |
9,026 | def verifies( self, hash, signature ):
G = self.generator
n = G.order()
r = signature.r
s = signature.s
if r < 1 or r > n-1: return False
if s < 1 or s > n-1: return False
c = numbertheory.inverse_mod( s, n )
u1 = ( hash * c ) % n
u2 = ( r * c ) % n
xy = u1 * G + u2 *... | Verify that signature is a valid signature of hash.
Return True if the signature is valid. |
9,027 | def decode_response(client_message, to_object=None):
parameters = dict(response=None)
response_size = client_message.read_int()
response = []
for _ in range(0, response_size):
response_item = client_message.read_data()
response.append(response_item)
parameters[] = ImmutableLazyD... | Decode response from client message |
9,028 | def check_version(component, expected_version):
comp = comp_names[component]
compath = os.path.realpath(os.path.abspath(comp.path))
sys.path.insert(0, compath)
import version
if version.version != expected_version:
raise EnvironmentError("Version mismatch during release, expected={}... | Make sure the package version in setuptools matches what we expect it to be |
9,029 | def parse_xml_jtl(self, granularity):
data = defaultdict(list)
processed_data = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
for input_file in self.infile_list:
logger.info(, input_file)
timestamp_format = None
tree = ElementTree.parse(input_file)
samples = tree.f... | Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics
:param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second'
:return: status of the metric parse |
9,030 | def copy(a):
shared = anonymousmemmap(a.shape, dtype=a.dtype)
shared[:] = a[:]
return shared | Copy an array to the shared memory.
Notes
-----
copy is not always necessary because the private memory is always copy-on-write.
Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory |
9,031 | def notUnique(iterable, reportMax=INF):
hash = {}
n=0
if reportMax < 1:
raise ValueError("`reportMax` must be >= 1 and is %r" % reportMax)
for item in iterable:
count = hash[item] = hash.get(item, 0) + 1
if count > 1:
yield item
n += 1
if ... | Returns the elements in `iterable` that aren't unique; stops after it found
`reportMax` non-unique elements.
Examples:
>>> list(notUnique([1,1,2,2,3,3]))
[1, 2, 3]
>>> list(notUnique([1,1,2,2,3,3], 1))
[1] |
9,032 | def expand(self, other):
if not isinstance(other, Result):
raise ValueError("Provided argument has to be instance of overpy:Result()")
other_collection_map = {Node: other.nodes, Way: other.ways, Relation: other.relations, Area: other.areas}
for element_type, own_collection ... | Add all elements from an other result to the list of elements of this result object.
It is used by the auto resolve feature.
:param other: Expand the result with the elements from this result.
:type other: overpy.Result
:raises ValueError: If provided parameter is not instance of :clas... |
9,033 | def print_about(self):
filepath = os.path.join(self.suite_path, "bin", self.tool_name)
print "Tool: %s" % self.tool_name
print "Path: %s" % filepath
print "Suite: %s" % self.suite_path
msg = "%s (%r)" % (self.context.load_path, self.context_name)
prin... | Print an info message about the tool. |
9,034 | def star(self, **args):
if in args:
self.gist_name = args[]
self.gist_id = self.getMyID(self.gist_name)
elif in args:
self.gist_id = args[]
else:
raise Exception(s Unambigious Gistname or any unique Gistid to be starred%s/gists/%s/staridGist can\) | star any gist by providing gistID or gistname(for authenticated user) |
9,035 | def wallet_republish(self, wallet, count):
wallet = self._process_value(wallet, )
count = self._process_value(count, )
payload = {"wallet": wallet, "count": count}
resp = self.call(, payload)
return resp.get() or [] | Rebroadcast blocks for accounts from **wallet** starting at frontier
down to **count** to the network
.. enable_control required
.. version 8.0 required
:param wallet: Wallet to rebroadcast blocks for
:type wallet: str
:param count: Max amount of blocks to rebroadcast ... |
9,036 | def UnpackItems(*items, fields=None, defaults=None):
defaults = defaults or {}
@use_context
@use_raw_input
def _UnpackItems(context, bag):
nonlocal fields, items, defaults
if fields is None:
fields = ()
for item in items:
fields += tuple(bag... | >>> UnpackItems(0)
:param items:
:param fields:
:param defaults:
:return: callable |
9,037 | def get_abstracts(self, refresh=True):
return [ScopusAbstract(eid, refresh=refresh)
for eid in self.get_document_eids(refresh=refresh)] | Return a list of ScopusAbstract objects using ScopusSearch. |
9,038 | def deframesig(frames, siglen, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,))):
frame_len = round_half_up(frame_len)
frame_step = round_half_up(frame_step)
numframes = numpy.shape(frames)[0]
assert numpy.shape(frames)[1] == frame_len,
indices = numpy.tile(numpy.arange(0, frame_len)... | Does overlap-add procedure to undo the action of framesig.
:param frames: the array of frames.
:param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples.
:param frame_len: length of each frame measured in samples.
:param frame_step: number of samples ... |
9,039 | def localize(dt, tz):
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
return tz.localize(dt) | Given a naive datetime object this method will return a localized
datetime object |
9,040 | def extract_bag_of_words_from_corpus_parallel(corpus, lemmatizing="wordnet"):
pool = Pool(processes=get_threads_number()*2,)
partitioned_corpus = chunks(corpus, len(corpus) / get_threads_number())
list_of_bags_of_words, list_of_lemma_to_keywordset_maps = pool.map(partial... | This extracts one bag-of-words from a list of strings. The documents are mapped to parallel processes.
Inputs: - corpus: A list of strings.
- lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet".
Output: - bag_of_words: This is a bag-of-words in python dictionar... |
9,041 | def get_keys(self, lst):
pk_name = self.get_pk_name()
return [getattr(item, pk_name) for item in lst] | return a list of pk values from object list |
9,042 | def _broadcast_item(self, row_lookup, col_lookup, item, to_shape):
if isinstance(item, (pandas.Series, pandas.DataFrame, DataFrame)):
if not all(idx in item.index for idx in row_lookup):
raise ValueError(
"Must have equal len keys and va... | Use numpy to broadcast or reshape item.
Notes:
- Numpy is memory efficient, there shouldn't be performance issue. |
9,043 | def fromfilenames(filenames, coltype = int):
pattern = re.compile(r"-([\d.]+)-([\d.]+)\.[\w_+
l = segments.segmentlist()
for name in filenames:
[(s, d)] = pattern.findall(name.strip().rstrip(".gz"))
s = coltype(s)
d = coltype(d)
l.append(segments.segment(s, s + d))
return l | Return a segmentlist describing the intervals spanned by the files
whose names are given in the list filenames. The segmentlist is
constructed by parsing the file names, and the boundaries of each
segment are coerced to type coltype.
The file names are parsed using a generalization of the format
described in Tec... |
9,044 | def get_assigned_licenses(service_instance, entity_ref=None, entity_name=None,
license_assignment_manager=None):
if not license_assignment_manager:
license_assignment_manager = \
get_license_assignment_manager(service_instance)
if not entity_name:
r... | Returns the licenses assigned to an entity. If entity ref is not provided,
then entity_name is assumed to be the vcenter. This is later checked if
the entity name is provided.
service_instance
The Service Instance Object from which to obtain the licenses.
entity_ref
VMware entity to ge... |
9,045 | def calculate_squared_differences(image_tile_dict, transformed_array, template, sq_diff_tolerance=0.1):
template_norm_squared = np.sum(template**2)
image_norms_squared = {(x,y):np.sum(image_tile_dict[(x,y)]**2) for (x,y) in image_tile_dict.keys()}
match_points = image_tile_dict.keys()
h, w = t... | As above, but for when the squared differences matching method is used |
9,046 | def component_activated(self, component):
component.env = self
super(Environment, self).component_activated(component) | Initialize additional member variables for components.
Every component activated through the `Environment` object
gets an additional member variable: `env` (the environment object) |
9,047 | def load_table_from_uri(
self,
source_uris,
destination,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
job_config=None,
retry=DEFAULT_RETRY,
):
job_id = _make_job_id(job_id, job_id_prefix)
if project is... | Starts a job for loading data into a table from CloudStorage.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load
Arguments:
source_uris (Union[str, Sequence[str]]):
URIs of data files to be loaded; in format
``gs://<... |
9,048 | def _deriv_growth(z, **cosmo):
inv_h = (cosmo[]*(1 + z)**3 + cosmo[])**(-0.5)
fz = (1 + z) * inv_h**3
deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) *\
1.5 * cosmo[] * (1 + z)**2 -\
fz * growthfactor(z, norm=True, **cosmo)/_int_growth(z, **cosmo)
return(deriv_g) | Returns derivative of the linear growth factor at z
for a given cosmology **cosmo |
9,049 | def Advertise(port, stype="SCOOP", sname="Broker", advertisername="Broker",
location=""):
scoop.logger.info("Launching advertiser...")
service = minusconf.Service(stype, port, sname, location)
advertiser = minusconf.ThreadAdvertiser([service], advertisername)
advertiser.start()
sc... | stype = always SCOOP
port = comma separated ports
sname = broker unique name
location = routable location (ip or dns) |
9,050 | def stream(identifier=None, priority=LOG_INFO, level_prefix=False):
r
if identifier is None:
if not _sys.argv or not _sys.argv[0] or _sys.argv[0] == :
identifier =
else:
identifier = _sys.argv[0]
fd = stream_fd(identifier, priority, level_prefix)
return _os.fdo... | r"""Return a file object wrapping a stream to journal.
Log messages written to this file as simple newline sepearted text strings
are written to the journal.
The file will be line buffered, so messages are actually sent after a
newline character is written.
>>> from systemd import journal
>>>... |
9,051 | def _HandleLegacy(self, args, token=None):
generic_hunt_args = rdf_hunts.GenericHuntArgs()
generic_hunt_args.flow_runner_args.flow_name = args.flow_name
generic_hunt_args.flow_args = args.flow_args
if args.original_hunt:
ref = rdf_hunts.FlowLikeObjectReference.FromHuntId... | Creates a new hunt. |
9,052 | def ftr_get_config(website_url, exact_host_match=False):
def check_requests_result(result):
return (
u in result.headers.get()
and u not in result.text
and u not in result.text
and u not in result.text
)
repositories = [
x.strip() fo... | Download the Five Filters config from centralized repositories.
Repositories can be local if you need to override siteconfigs.
The first entry found is returned. If no configuration is found,
`None` is returned. If :mod:`cacheops` is installed, the result will
be cached with a default expiration delay... |
9,053 | def gdf_to_geojson(gdf, date_format=, properties=None, filename=None):
gdf = convert_date_columns(gdf, date_format)
gdf_out = gdf[[] + properties or []]
geojson_str = gdf_out.to_json()
if filename:
with codecs.open(filename, "w", "utf-8-sig") as f:
f.write(geojson_str)
... | Serialize a GeoPandas dataframe to a geojson format Python dictionary / file |
9,054 | def event_filter_type(self, event_filter_type):
allowed_values = ["BYCHART", "AUTOMATIC", "ALL", "NONE", "BYDASHBOARD", "BYCHARTANDDASHBOARD"]
if event_filter_type not in allowed_values:
raise ValueError(
"Invalid value for `event_filter_type` ({0}), must be one of... | Sets the event_filter_type of this Dashboard.
How charts belonging to this dashboard should display events. BYCHART is default if unspecified # noqa: E501
:param event_filter_type: The event_filter_type of this Dashboard. # noqa: E501
:type: str |
9,055 | def compile_insert_get_id(self, query, values, sequence=None):
if sequence is None:
sequence = "id"
return "%s RETURNING %s" % (
self.compile_insert(query, values),
self.wrap(sequence),
) | Compile an insert and get ID statement into SQL.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The values to insert
:type values: dict
:param sequence: The id sequence
:type sequence: str
:return: The compiled statement
... |
9,056 | def import_from_string(value):
value = value.replace(, )
try:
module_path, class_name = value.rsplit(, 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) as ex:
raise ImportError("Could not import . {}: {}.".for... | Copy of rest_framework.settings.import_from_string |
9,057 | def delete(self, url: StrOrURL, **kwargs: Any) -> :
return _RequestContextManager(
self._request(hdrs.METH_DELETE, url,
**kwargs)) | Perform HTTP DELETE request. |
9,058 | def packetToDict(pkt):
d = {
: pkt[4],
: xl320.InstrToStr[pkt[7]],
: (pkt[6] << 8) + pkt[5],
: pkt[8:-2],
: pkt[-2:]
}
return d | Given a packet, this turns it into a dictionary ... is this useful?
in: packet, array of numbers
out: dictionary (key, value) |
9,059 | def rpc_get_pydoc_documentation(self, symbol):
try:
docstring = pydoc.render_doc(str(symbol),
"Elpy Pydoc Documentation for %s",
False)
except (ImportError, pydoc.ErrorDuringImport):
return... | Get the Pydoc documentation for the given symbol.
Uses pydoc and can return a string with backspace characters
for bold highlighting. |
9,060 | def get_most_recent_event(self, originator_id, lt=None, lte=None):
events = self.get_domain_events(originator_id=originator_id, lt=lt, lte=lte, limit=1, is_ascending=False)
events = list(events)
try:
return events[0]
except IndexError:
pass | Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: get highest at or before this position
:return: domain event |
9,061 | def _subclass_must_implement(self, fn):
m = "Missing function implementation in {}: {}".format(type(self), fn)
return NotImplementedError(m) | Returns a NotImplementedError for a function that should be implemented.
:param fn: name of the function |
9,062 | def load(source, triples=False, cls=PENMANCodec, **kwargs):
decode = cls(**kwargs).iterdecode
if hasattr(source, ):
return list(decode(source.read()))
else:
with open(source) as fh:
return list(decode(fh.read())) | Deserialize a list of PENMAN-encoded graphs from *source*.
Args:
source: a filename or file-like object to read from
triples: if True, read graphs as triples instead of as PENMAN
cls: serialization codec class
kwargs: keyword arguments passed to the constructor of *cls*
Returns:... |
9,063 | def send(self, data, room=None, skip_sid=None, namespace=None,
callback=None):
return self.client.send(data, namespace=namespace or self.namespace,
callback=callback) | Send a message to the server.
The only difference with the :func:`socketio.Client.send` method is
that when the ``namespace`` argument is not given the namespace
associated with the class is used. |
9,064 | def groups_moderators(self, room_id=None, group=None, **kwargs):
if room_id:
return self.__call_api_get(, roomId=room_id, kwargs=kwargs)
elif group:
return self.__call_api_get(, roomName=group, kwargs=kwargs)
else:
raise RocketMissingParamException() | Lists all moderators of a group. |
9,065 | def create_user(self, user):
data = self._create_user_dict(user=user)
response = self._perform_request(
url=,
method=,
data=json.dumps(data))
return response | Creates a new user.
:param user: The user object to be created.
:type user: ``dict`` |
9,066 | def instantiate_by_name_with_default(self, object_name, default_value=None):
if object_name not in self.instances:
if object_name not in self.environment:
return default_value
else:
instance = self.instantiate_from_data(self.environment[object_nam... | Instantiate object from the environment, possibly giving some extra arguments |
9,067 | def importSNPs(name) :
path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name)
PS.importSNPs(path) | Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. |
9,068 | def extract_path_info(
environ_or_baseurl,
path_or_url,
charset="utf-8",
errors="werkzeug.url_quote",
collapse_http_schemes=True,
):
def _normalize_netloc(scheme, netloc):
parts = netloc.split(u"@", 1)[-1].split(u":", 1)
if len(parts) == 2:
netloc, port = parts
... | Extracts the path info from the given URL (or WSGI environment) and
path. The path info returned is a unicode string, not a bytestring
suitable for a WSGI environment. The URLs might also be IRIs.
If the path info could not be determined, `None` is returned.
Some examples:
>>> extract_path_info... |
9,069 | def deactivate_user(query):
user = _query_to_user(query)
if click.confirm(f):
user.active = False
user_manager.save(user, commit=True)
click.echo(f)
else:
click.echo() | Deactivate a user. |
9,070 | def dynamize_attribute_updates(self, pending_updates):
d = {}
for attr_name in pending_updates:
action, value = pending_updates[attr_name]
if value is None:
d[attr_name] = {"Action": action}
else:
d[attr_name] ... | Convert a set of pending item updates into the structure
required by Layer1. |
9,071 | def query_raw(self, metric, **kwargs):
kwargs[] = True
if kwargs.get():
return self.query_raw_with_http_info(metric, **kwargs)
else:
(data) = self.query_raw_with_http_info(metric, **kwargs)
return data | Perform a raw data query against Wavefront servers that returns second granularity points grouped by tags # noqa: E501
An API to check if ingested points are as expected. Points ingested within a single second are averaged when returned. # noqa: E501
This method makes a synchronous HTTP request by d... |
9,072 | def load_interfaces(self, interfaces_dict):
if interfaces_dict.get(, {}).get(, None) is None:
raise ValueError("Invalid response for GetSupportedAPIList")
interfaces = interfaces_dict[][]
if len(interfaces) == 0:
raise ValueError("API returned not interfaces; pr... | Populates the namespace under the instance |
9,073 | def to_dict(self, index=0):
index += 1
rep = {}
rep["index"] = index
rep["leaf"] = len(self.children) == 0
rep["depth"] = self.udepth
rep["scoreDistr"] = [0.0] * len(LabeledTree.SCORE_MAPPING)
if self.label is not None:
rep["scoreDist... | Dict format for use in Javascript / Jason Chuang's display technology. |
9,074 | def featureCounts_chart (self):
config = {
: ,
: ,
: ,
:
}
return bargraph.plot(self.featurecounts_data, self.featurecounts_keys, config) | Make the featureCounts assignment rates plot |
9,075 | def _run_server(self, multiprocessing):
if not self._flag_m:
raise UnsupportedCall(f"Extractor(engine={self._exeng})_run_serverExtractor(engine=pipeline)fout={self._ofnm}mpfrmmprsmmpbufmpkitstartmpkitmpbufmpfdp': self._mpfdp[self._frnum]}
)
... | Use server multiprocessing to extract PCAP files. |
9,076 | def pop(h):
n = h.size() - 1
h.swap(0, n)
down(h, 0, n)
return h.pop() | Pop the heap value from the heap. |
9,077 | def on_tab_close_clicked(self, event, state_m):
[page, state_identifier] = self.find_page_of_state_m(state_m)
if page:
self.close_page(state_identifier, delete=False) | Triggered when the states-editor close button is clicked
Closes the tab.
:param state_m: The desired state model (the selected state) |
9,078 | def lfprob (dfnum, dfden, F):
p = betai(0.5*dfden, 0.5*dfnum, dfden/float(dfden+dfnum*F))
return p | Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn |
9,079 | def apply(self, key, value, prompt=None,
on_load=lambda a: a, on_save=lambda a: a):
if value == :
value = None
if key and self.data.has_key(key): del self.data[key]
if value is not None:
value = on_load(value)
if key: s... | Applies a setting value to a key, if the value is not `None`.
Returns without prompting if either of the following:
* `value` is not `None`
* already present in the dictionary
Args:
prompt:
May either be a string to prompt via `raw_input` or a
... |
9,080 | def execute(self, progress_fn, print_verbose_info=None):
assert_is_type(progress_fn, FunctionType, GeneratorType, MethodType)
if isinstance(progress_fn, GeneratorType):
progress_fn = (lambda g: lambda: next(g))(progress_fn)
self._next_poll_time = 0
... | Start the progress bar, and return only when the progress reaches 100%.
:param progress_fn: the executor function (or a generator). This function should take no arguments
and return either a single number -- the current progress level, or a tuple (progress level, delay),
where delay is ... |
9,081 | def _get_default_iface_linux():
data = _read_file()
if data is not None and len(data) > 1:
for line in data.split()[1:-1]:
iface_name, dest = line.split()[:2]
if dest == :
return iface_name
return None | Get the default interface by reading /proc/net/route.
This is the same source as the `route` command, however it's much
faster to read this file than to call `route`. If it fails for whatever
reason, we can fall back on the system commands (e.g for a platform
that has a route command, but maybe doesn't... |
9,082 | def js_distance(p, q):
js_dist = np.sqrt(js_divergence(p, q))
return js_dist | Compute the Jensen-Shannon distance between two discrete distributions.
NOTE: JS divergence is not a metric but the sqrt of JS divergence is a
metric and is called the JS distance.
Parameters
----------
p : np.array
probability mass array (sums to 1)
q : np.array
probability ma... |
9,083 | def play(self, **kwargs):
path = % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path) | Trigger a job explicitly.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobPlayError: If the job could not be triggered |
9,084 | def clear_cached_data(self):
adapter.RemoveDevice(device._device.object_path) | Clear any internally cached BLE device data. Necessary in some cases
to prevent issues with stale device data getting cached by the OS. |
9,085 | def get_theming_attribute(self, mode, name, part=None):
colours = int(self._config.get())
return self._theme.get_attribute(colours, mode, name, part) | looks up theming attribute
:param mode: ui-mode (e.g. `search`,`thread`...)
:type mode: str
:param name: identifier of the atttribute
:type name: str
:rtype: urwid.AttrSpec |
9,086 | def getLogger(name):
log = logging.getLogger(name=name)
for handler in log.handlers:
if name == handler.name:
return log
else:
return LogSetup().default_logger(name=name.split()[0]) | Return a logger from a given name.
If the name does not have a log handler, this will create one for it based
on the module name which will log everything to a log file in a location
the executing user will have access to.
:param name: ``str``
:return: ``object`` |
9,087 | def build_network_settings(**settings):
*
changes = []
current_network_settings = _parse_current_network_settings()
opts = _parse_network_settings(settings, current_network_settings)
skip_etc_default_networking = (
__grains__[] == and
int(__grains__[].spl... | Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings> |
9,088 | def get_library_citation():
all_ref_data = api.get_reference_data()
lib_refs_data = {k: all_ref_data[k] for k in _lib_refs}
return (_lib_refs_desc, lib_refs_data) | Return a descriptive string and reference data for what users of the library should cite |
9,089 | def parse_field(self, field_data, index=0):
field = {
: index,
}
if isinstance(field_data, str):
field.update(self.parse_string_field(field_data))
elif isinstance(field_data, dict):
field.update(field_data)
else:
raise Typ... | Parse field and add missing options |
9,090 | def grant_permissions(self, proxy_model):
ContentType = apps.get_model(, )
try:
Permission = apps.get_model(, )
except LookupError:
return
))
permissions = [
Permission(codename=codename, name=name, content_type=ctype)
... | Create the default permissions for the just added proxy model |
9,091 | def default_image_loader(filename, flags, **kwargs):
def load(rect=None, flags=None):
return filename, rect, flags
return load | This default image loader just returns filename, rect, and any flags |
9,092 | def script(self, sql_script, split_algo=, prep_statements=True, dump_fails=True):
return Execute(sql_script, split_algo, prep_statements, dump_fails, self) | Wrapper method providing access to the SQLScript class's methods and properties. |
9,093 | def run_radia(job, bams, univ_options, radia_options, chrom):
job.fileStore.logToMaster( %(univ_options[], chrom))
work_dir = job.fileStore.getLocalTempDir()
input_files = {
: bams[],
: bams[],
: bams[],
: bams[],
: bams[],
: bams[],
: radia_optio... | This module will run radia on the RNA and DNA bams
ARGUMENTS
1. bams: Dict of bams and their indexes
bams
|- 'tumor_rna': <JSid>
|- 'tumor_rnai': <JSid>
|- 'tumor_dna': <JSid>
|- 'tumor_dnai': <JSid>
|- 'normal_dna': <JSid>
+- 'normal_dnai': <JSid>
... |
9,094 | def coverage_region_detailed_stats(target_name, bed_file, data, out_dir):
if bed_file and utils.file_exists(bed_file):
ready_depth = tz.get_in(["depth", target_name], data)
if ready_depth:
cov_file = ready_depth["regions"]
dist_file = ready_depth["dist"]
thre... | Calculate coverage at different completeness cutoff
for region in coverage option. |
9,095 | def create_dset_to3d(prefix,file_list,file_order=,num_slices=None,num_reps=None,TR=None,slice_order=,only_dicoms=True,sort_filenames=False):
tags = {
: (0x0028,0x0010),
: (0x0020,0x0105),
: (0x0018,0x0080)
}
with nl.notify( % prefix):
if os.path.exists(prefix):
... | manually create dataset by specifying everything (not recommended, but necessary when autocreation fails)
If `num_slices` or `num_reps` is omitted, it will be inferred by the number of images. If both are omitted,
it assumes that this it not a time-dependent dataset
:only_dicoms: filter the given li... |
9,096 | def configure_sessionmaker(graph):
engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy)
if engine_routing_strategy.supports_multiple_binds:
ScopedFactory.infect(graph, "postgres")
class RoutingSession(Session):
def get_bind(self, mapper=... | Create the SQLAlchemy session class. |
9,097 | def generate_variants(unresolved_spec):
for resolved_vars, spec in _generate_variants(unresolved_spec):
assert not _unresolved_values(spec)
yield format_vars(resolved_vars), spec | Generates variants from a spec (dict) with unresolved values.
There are two types of unresolved values:
Grid search: These define a grid search over values. For example, the
following grid search values in a spec will produce six distinct
variants in combination:
"activation":... |
9,098 | def _create_opt_rule(self, rulename):
optname = rulename +
def optrule(self, p):
p[0] = p[1]
optrule.__doc__ = % (optname, rulename)
optrule.__name__ = % optname
setattr(self.__class__, optrule.__name__, optrule) | Given a rule name, creates an optional ply.yacc rule
for it. The name of the optional rule is
<rulename>_opt |
9,099 | def view_set(method_name):
def view_set(value, context, **_params):
method = getattr(context["view"], method_name)
return _set(method, context["key"], value, (), {})
return view_set | Creates a setter that will call the view method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the view.
@type method_name: str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.