Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
9,300 | def timeseries_reactive(self):
if self._timeseries_reactive is None:
if self.grid.network.timeseries.load_reactive_power is not None:
self.power_factor =
self.reactive_power_mode =
ts_total... | Reactive power time series in kvar.
Parameters
-----------
timeseries_reactive : :pandas:`pandas.Seriese<series>`
Series containing reactive power in kvar.
Returns
-------
:pandas:`pandas.Series<series>` or None
Series containing reactive power t... |
9,301 | def usearch61_smallmem_cluster(intermediate_fasta,
percent_id=0.97,
minlen=64,
rev=False,
output_dir=".",
remove_usearch_logs=False,
w... | Performs usearch61 de novo clustering via cluster_smallmem option
Only supposed to be used with length sorted data (and performs length
sorting automatically) and does not support reverse strand matching
intermediate_fasta: fasta filepath to be clustered with usearch61
percent_id: percentage id to c... |
9,302 | def display(self, image):
assert(image.mode == self.mode)
assert(image.size == self.size)
self._last_image = image.copy()
sz = image.width * image.height * 4
buf = bytearray(sz * 3)
m = self._mapping
for idx, (r, g, b, a) in enumerate(image.get... | Takes a 32-bit RGBA :py:mod:`PIL.Image` and dumps it to the daisy-chained
APA102 neopixels. If a pixel is not fully opaque, the alpha channel
value is used to set the brightness of the respective RGB LED. |
9,303 | def dfa_word_acceptance(dfa: dict, word: list) -> bool:
current_state = dfa[]
for action in word:
if (current_state, action) in dfa[]:
current_state = dfa[][current_state, action]
else:
return False
if current_state in dfa[]:
return True
else:
... | Checks if a given **word** is accepted by a DFA,
returning True/false.
The word w is accepted by a DFA if DFA has an accepting run
on w. Since A is deterministic,
:math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` .
:param dict dfa: input DFA;
:param list word: list of actions ∈ dfa['alpha... |
9,304 | def start_request(self, headers, *, end_stream=False):
yield from _wait_for_events(self._resumed, self._stream_creatable)
stream_id = self._conn.get_next_available_stream_id()
self._priority.insert_stream(stream_id)
self._priority.block(stream_id)
self._conn.send_headers... | Start a request by sending given headers on a new stream, and return
the ID of the new stream.
This may block until the underlying transport becomes writable, and
the number of concurrent outbound requests (open outbound streams) is
less than the value of peer config MAX_CONCURRENT_STRE... |
9,305 | def check_database_connected(db):
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
errors = []
try:
with db.engine.connect() as connection:
connection.execute()
except DBAPIError as e:
msg = .format(e)
errors.append(Error(msg, id=health.ERROR_DB_API_EXCEPT... | A built-in check to see if connecting to the configured default
database backend succeeds.
It's automatically added to the list of Dockerflow checks if a
:class:`~flask_sqlalchemy.SQLAlchemy` object is passed
to the :class:`~dockerflow.flask.app.Dockerflow` class during
instantiation, e.g.::
... |
9,306 | def reverse(self):
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i] | S.reverse() -- reverse *IN PLACE* |
9,307 | def _set_cpu_queue_info_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=cpu_queue_info_state.cpu_queue_info_state, is_container=, presence=False, yang_name="cpu-queue-info-state", rest_name="cpu-queue-info-state", parent=self, path_helper=self._... | Setter method for cpu_queue_info_state, mapped from YANG variable /cpu_queue_info_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cpu_queue_info_state is considered as a private
method. Backends looking to populate this variable should
do so via calling... |
9,308 | def get_data(self):
result = {}
for field in self.fields:
result[field.name] = self.data.get(field.name)
return result | Returns data from each field. |
9,309 | def button(self):
if self.type != EventType.TABLET_TOOL_BUTTON:
raise AttributeError(_wrong_prop.format(self.type))
return self._libinput.libinput_event_tablet_tool_get_button(
self._handle) | The button that triggered this event.
For events that are not of type
:attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property
raises :exc:`AttributeError`.
Returns:
int: The button triggering this event. |
9,310 | def list_nodes_full(call=None):
response = _query(, )
ret = {}
for item in response[]:
name = item[]
ret[name] = item
ret[name][] = item[]
ret[name][] = item[][]
ret[name][] = item[][]
ret[name][] = [item[][]]
ret[name][] = []
ret[name][... | List nodes, with all available information
CLI Example:
.. code-block:: bash
salt-cloud -F |
9,311 | def _finalCleanup(self):
for conn in self._connections.values():
conn.releaseConnectionResources()
assert not self._connections | Clean up all of our connections by issuing application-level close and
stop notifications, sending hail-mary final FIN packets (which may not
reach the other end, but nevertheless can be useful) when possible. |
9,312 | def gps_message_arrived(self, m):
gps_week = getattr(m, , None)
gps_timems = getattr(m, , None)
if gps_week is None:
gps_week = getattr(m, , None)
gps_timems = getattr(m, , None)
if gps_week is None:
if getattr(m,... | adjust time base from GPS message |
9,313 | def move_identity(session, identity, uidentity):
if identity.uuid == uidentity.uuid:
return False
old_uidentity = identity.uidentity
identity.uidentity = uidentity
last_modified = datetime.datetime.utcnow()
old_uidentity.last_modified = last_modified
uidentity.last_modified = las... | Move an identity to a unique identity.
Shifts `identity` to the unique identity given in
`uidentity`. The function returns whether the operation
was executed successfully.
When `uidentity` is the unique identity currently related
to `identity`, this operation does not have any effect and
`Fals... |
9,314 | def inquire_property(name, doc=None):
def inquire_property(self):
if not self._started:
msg = ("Cannot read {0} from a security context whose "
"establishment has not yet been started.")
raise AttributeError(msg)
return getattr(self._inquire(**{name:... | Creates a property based on an inquire result
This method creates a property that calls the
:python:`_inquire` method, and return the value of the
requested information.
Args:
name (str): the name of the 'inquire' result information
Returns:
property: the created property |
9,315 | def reverse_transform(self, col):
output = pd.DataFrame(index=col.index)
output[self.col_name] = col.apply(self.safe_round, axis=1)
if self.subtype == :
output[self.col_name] = output[self.col_name].astype(int)
return output | Converts data back into original format.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame |
9,316 | def delete(name):
with Session() as session:
try:
session.VFolder(name).delete()
print_done()
except Exception as e:
print_error(e)
sys.exit(1) | Delete the given virtual folder. This operation is irreversible!
NAME: Name of a virtual folder. |
9,317 | def autoconf(self):
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
return (serverInfo is not None) | Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise. |
9,318 | def stream_events(signals: Sequence[Signal], filter: Callable[[T_Event], bool] = None, *,
max_queue_size: int = 0) -> AsyncIterator[T_Event]:
@async_generator
async def streamer():
try:
while True:
event = await queue.get()
if filter is ... | Return an async generator that yields events from the given signals.
Only events that pass the filter callable (if one has been given) are returned.
If no filter function was given, all events are yielded from the generator.
:param signals: the signals to get events from
:param filter: a callable that... |
9,319 | def from_array(filename, data, iline=189,
xline=193,
format=SegySampleFormat.IBM_FLOAT_4_BYTE,
dt=4000,
delrt=0):
dt = int(dt)
delrt = int(delrt)
data = np.asarray(data)
dim... | Create a new SEGY file from an n-dimentional array. Create a structured
SEGY file with defaulted headers from a 2-, 3- or 4-dimensional array.
ilines, xlines, offsets and samples are inferred from the size of the
array. Please refer to the documentation for functions from_array2D,
from_array3D and from_... |
9,320 | def send(msg_type, send_async=False, *args, **kwargs):
message = message_factory(msg_type, *args, **kwargs)
try:
if send_async:
message.send_async()
else:
message.send()
except MessageSendError as e:
err_exit("Unable to send message: ", e) | Constructs a message class and sends the message.
Defaults to sending synchronously. Set send_async=True to send
asynchronously.
Args:
:msg_type: (str) the type of message to send, i.e. 'Email'
:send_async: (bool) default is False, set True to send asynchronously.
:kwargs: (dict) k... |
9,321 | def shift_coordinate_grid(self, x_shift, y_shift, pixel_unit=False):
if pixel_unit is True:
ra_shift, dec_shift = self.map_pix2coord(x_shift, y_shift)
else:
ra_shift, dec_shift = x_shift, y_shift
self._ra_at_xy_0 += ra_shift
self._dec_at_xy_0 += dec_shift... | shifts the coordinate system
:param x_shif: shift in x (or RA)
:param y_shift: shift in y (or DEC)
:param pixel_unit: bool, if True, units of pixels in input, otherwise RA/DEC
:return: updated data class with change in coordinate system |
9,322 | def triangulize(image, tile_size):
if isinstance(image, basestring) or hasattr(image, ):
image = Image.open(image)
assert isinstance(tile_size, int)
image = prep_image(image, tile_size)
logging.info(, image.size)
pix = image.load()
draw = ImageDraw.Draw(image)
... | Processes the given image by breaking it down into tiles of the given
size and applying a triangular effect to each tile. Returns the processed
image as a PIL Image object.
The image can be given as anything suitable for passing to `Image.open`
(ie, the path to an image or as a file-like object contain... |
9,323 | def search(self, index_name, query):
try:
results = self.els_search.search(index=index_name, body=query)
return results
except Exception, error:
error_str = % str(error)
error_str +=
print error_str
raise RuntimeError(er... | Search the given index_name with the given ELS query.
Args:
index_name: Name of the Index
query: The string to be searched.
Returns:
List of results.
Raises:
RuntimeError: When the search query fails. |
9,324 | def searchForGroups(self, name, limit=10):
params = {"search": name, "limit": limit}
j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_GROUP, params=params))
return [Group._from_graphql(node) for node in j["viewer"]["groups"]["nodes"]] | Find and get group thread by its name
:param name: Name of the group thread
:param limit: The max. amount of groups to fetch
:return: :class:`models.Group` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed |
9,325 | def avail_platforms():
ret = {}
for platform in CMD_MAP:
ret[platform] = True
for cmd in CMD_MAP[platform]:
if not salt.utils.path.which(cmd):
ret[platform] = False
return ret | Return which platforms are available
CLI Example:
.. code-block:: bash
salt myminion genesis.avail_platforms |
9,326 | def add_intercept_term(self, x):
nr_x,nr_f = x.shape
intercept = np.ones([nr_x,1])
x = np.hstack((intercept,x))
return x | Adds a column of ones to estimate the intercept term for
separation boundary |
9,327 | def create_collection(self, name, codec_options=None,
read_preference=None, write_concern=None,
read_concern=None, **kwargs):
if name in self.collection_names():
raise CollectionInvalid("collection %s already exists" % name)
retur... | Create a new :class:`~pymongo.collection.Collection` in this
database.
Normally collection creation is automatic. This method should
only be used to specify options on
creation. :class:`~pymongo.errors.CollectionInvalid` will be
raised if the collection already exists.
... |
9,328 | def walk_dir(path, args, state):
if args.debug:
sys.stderr.write("Walking %s\n" % path)
for root, _dirs, files in os.walk(path):
if not safe_process_files(root, files, args, state):
return False
if state.should_quit():
return False
return True | Check all files in `path' to see if there is any requests that
we should send out on the bus. |
9,329 | def as_dict(self):
bson_nb_voro_list2 = self.to_bson_voronoi_list2()
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"bson_nb_voro_list2": bson_nb_voro_list2,
"structure": self.structure.as_dict(),... | Bson-serializable dict representation of the VoronoiContainer.
:return: dictionary that is BSON-encodable |
9,330 | def add_model(self, *args, **kwargs):
if self.category != Category.MODEL:
raise APIError("Part should be of category MODEL")
return self._client.create_model(self, *args, **kwargs) | Add a new child model to this model.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
additional keyword=value argument to this method. This will improve performance of the backend
against a trade-off that someone looking at the frontend won't no... |
9,331 | def fill_subparser(subparser):
subparser.add_argument(
"--shuffle-seed", help="Seed to use for randomizing order of the "
"training set on disk.",
default=config.default_seed, type=int, required=False)
return convert_ilsvrc2012 | Sets up a subparser to convert the ILSVRC2012 dataset files.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `ilsvrc2012` command. |
9,332 | def parse_ns_headers(ns_headers):
known_attrs = ("expires", "domain", "path", "secure",
"version", "port", "max-age")
result = []
for ns_header in ns_headers:
pairs = []
version_set = False
for ii, param in enumerate(re.split(r";\s*", ns_h... | Ad-hoc parser for Netscape protocol cookie-attributes.
The old Netscape cookie format for Set-Cookie can for instance contain
an unquoted "," in the expires field, so we have to use this ad-hoc
parser instead of split_header_words.
XXX This may not make the best possible effort to parse all the crap
... |
9,333 | def rearrange_jupytext_metadata(metadata):
for key in [, ]:
if key in metadata:
metadata[key.replace(, )] = metadata.pop(key)
jupytext_metadata = metadata.pop(, {})
if in metadata:
jupytext_metadata[] = metadata.pop()
if in metadata:
jupytext_metadata[]... | Convert the jupytext_formats metadata entry to jupytext/formats, etc. See #91 |
9,334 | def _lookup_identity_names(self):
id_batch_size = 100
ac = get_auth_client()
self._resolved_map = {}
for i in range(0, len(self.identity_ids), id_batch_size):
chunk = self.identity_ids[i : i + id_batch_size]
resolved_result = ac.get_identities(i... | Batch resolve identities to usernames.
Returns a dict mapping IDs to Usernames |
9,335 | def remote_tags(url):
tags = []
remote_git = Git()
for line in remote_git.ls_remote(, , url).split():
hash_ref = line.split()
tags.append(hash_ref[1][10:].replace(,))
return natsorted(tags) | List all available remote tags naturally sorted as version strings
:rtype: list
:param url: Remote URL of the repository
:return: list of available tags |
9,336 | def add_size_info (self):
maxbytes = self.aggregate.config["maxfilesizedownload"]
if self.size > maxbytes:
self.add_warning(
_("Content size %(size)s is larger than %(maxbytes)s.") %
dict(size=strformat.strsize(self.size),
maxby... | Set size of URL content (if any)..
Should be overridden in subclasses. |
9,337 | def start(self):
self.stop()
self.initialize()
self.handle = self.loop.call_at(self.get_next(), self.call_next) | Start scheduling |
9,338 | def should_filter(items):
return (vcfutils.get_paired(items) is not None and
any("damage_filter" in dd.get_tools_on(d) for d in items)) | Check if we should do damage filtering on somatic calling with low frequency events. |
9,339 | def _update_digital_forms(self, **update_props):
digital_forms = wrap_value(update_props[])
xpath_map = self._data_structures[update_props[]]
dist_format_props = (, , , )
dist_format_xroot = self._data_map[]
dist_format_xmap = {prop: xpath_map[prop] for prop... | Update operation for ISO Digital Forms metadata
:see: gis_metadata.utils._complex_definitions[DIGITAL_FORMS] |
9,340 | def compute_K_numerical(dataframe, settings=None, keep_dir=None):
inversion_code = reda.rcParams.get(, )
if inversion_code == :
import reda.utils.geom_fac_crtomo as geom_fac_crtomo
if keep_dir is not None:
keep_dir = os.path.abspath(keep_dir)
K = geom_fac_crtomo.compute_... | Use a finite-element modeling code to infer geometric factors for meshes
with topography or irregular electrode spacings.
Parameters
----------
dataframe : pandas.DataFrame
the data frame that contains the data
settings : dict
The settings required to compute the geometric factors. ... |
9,341 | def pdf_extract_text(path, pdfbox_path, pwd=, timeout=120):
if not os.path.isfile(path):
raise IOError()
if not os.path.isfile(pdfbox_path):
raise IOError()
import subprocess
for p in os.environ[].split():
if os.path.isfile(os.path.join(p, )):
brea... | Utility to use PDFBox from pdfbox.apache.org to extract Text from a PDF
Parameters
----------
path : str
Path to source pdf-file
pdfbox_path : str
Path to pdfbox-app-x.y.z.jar
pwd : str, optional
Password for protected pdf files
timeout : int, optional
Second... |
9,342 | def asarray(self, out=None, squeeze=True, lock=None, reopen=True,
maxsize=None, maxworkers=None, validate=True):
fh = self.parent.filehandle
byteorder = self.parent.tiff.byteorder
offsets, bytecounts = self._offsetscounts
self_ = self
self = self... | Read image data from file and return as numpy array.
Raise ValueError if format is unsupported.
Parameters
----------
out : numpy.ndarray, str, or file-like object
Buffer where image data will be saved.
If None (default), a new array will be created.
... |
9,343 | def commissionerUnregister(self):
print % self.port
cmd =
print cmd
return self.__sendCommand(cmd)[0] == | stop commissioner
Returns:
True: successful to stop commissioner
False: fail to stop commissioner |
9,344 | def _get(self, url,
param_dict={},
securityHandler=None,
additional_headers=[],
handlers=[],
proxy_url=None,
proxy_port=None,
compress=True,
custom_handlers=[],
out_folder=None,
file_name=No... | Performs a GET operation
Inputs:
Output:
returns dictionary, string or None |
9,345 | def set_default_init_cli_cmds(self):
init_cli_cmds = []
init_cli_cmds.append("set --retcode true")
init_cli_cmds.append("echo off")
init_cli_cmds.append("set --vt100 off")
init_cli_cmds.append(+self.name+)
init_cli_cmds.append([ + self.testcase + , True... | Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name>
and set testcase <tc name>
:return: List of default cli initialization commands. |
9,346 | def _check_callback(callback):
if inspect.isclass(callback):
callback_object = callback()
if not callable(callback_object):
raise ValueError(
"Callback must be a class that implements __call__ or a function."
)
elif callable(callback):
ca... | Turns a callback that is potentially a class into a callable object.
Args:
callback (object): An object that might be a class, method, or function.
if the object is a class, this creates an instance of it.
Raises:
ValueError: If an instance can't be created or it isn't a callable objec... |
9,347 | def loop(self, max_seconds=None):
loop_started = datetime.datetime.now()
self._is_running = True
while self._is_running:
self.process_error_queue(self.q_error)
if max_seconds is not None:
if (datetime.datetime.now() - loop_started).total_second... | Main loop for the process. This will run continuously until maxiter |
9,348 | def ReadVarString(self, max=sys.maxsize):
length = self.ReadVarInt(max)
return self.unpack(str(length) + , length) | Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator.
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes: |
9,349 | def make_posthook(self):
print(id(self.posthook), self.posthook)
print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook)
import ipdb;ipdb.set_trace()
if self.posthook:
os.chdir(self.project_name)
self.posthook() | Run the post hook into the project directory. |
9,350 | def en004(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
.format(value))
self._en004 = value | Corresponds to IDD Field `en004`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `en004`
Unit: kJ/kg
if `value` is None it will not be checked ag... |
9,351 | def console(self):
while True:
if six.PY2:
code = raw_input()
else:
code = input()
try:
print(self.eval(code))
except KeyboardInterrupt:
break
except Exception as e:
... | starts to interact (starts interactive console) Something like code.InteractiveConsole |
9,352 | def set_attributes(self, cell_renderer, **attributes):
Gtk.CellLayout.clear_attributes(self, cell_renderer)
for (name, value) in attributes.items():
Gtk.CellLayout.add_attribute(self, cell_renderer, name, value) | :param cell_renderer: the :obj:`Gtk.CellRenderer` we're setting the attributes of
:type cell_renderer: :obj:`Gtk.CellRenderer`
{{ docs }} |
9,353 | def creep_kill(self, target, timestamp):
self.creep_kill_types[target] += 1
matched = False
for k, v in self.creep_types.iteritems():
if target.startswith(k):
matched = True
setattr(self, v, getattr(self, v) + 1)
break
... | A creep was tragically killed. Need to split this into radiant/dire
and neutrals |
9,354 | def update(self, data_and_metadata: DataAndMetadata.DataAndMetadata, state: str, sub_area, view_id) -> None:
self.__state = state
self.__sub_area = sub_area
hardware_source_id = self.__hardware_source.hardware_source_id
channel_index = self.index
channel_id = self.chann... | Called from hardware source when new data arrives. |
9,355 | def set_chat_photo(self, chat_id, photo):
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(photo, InputFile, parameter_name="photo")
result = self.d... | Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Note: In regular groups (non-supergroups), this method will only work if the ‘A... |
9,356 | def resolve_variables(self, provided_variables):
self.resolved_variables = {}
defined_variables = self.defined_variables()
variable_dict = dict((var.name, var) for var in provided_variables)
for var_name, var_def in defined_variables.items():
value = resolve_variable... | Resolve the values of the blueprint variables.
This will resolve the values of the `VARIABLES` with values from the
env file, the config, and any lookups resolved.
Args:
provided_variables (list of :class:`stacker.variables.Variable`):
list of provided variables |
9,357 | def prt_results(self, goea_results):
if self.args.outfile is None:
self._prt_results(goea_results)
else:
outfiles = self.args.outfile.split(",")
grpwr = self.prepgrp.get_objgrpwr(goea_results) if self.prepgrp else None
if grp... | Print GOEA results to the screen or to a file. |
9,358 | def get_serializer(self, *args, **kwargs):
action = kwargs.pop(, None)
serializer_class = self.get_serializer_class(action)
kwargs[] = self.get_serializer_context()
return serializer_class(*args, **kwargs) | Returns the serializer instance that should be used to the
given action.
If any action was given, returns the serializer_class |
9,359 | def iter_directory(directory):
for path, dir, files in os.walk(directory):
for f in files:
filepath = os.path.join(path, f)
key = os.path.relpath(filepath, directory)
yield (filepath, key) | Given a directory, yield all files recursivley as a two-tuple (filepath, s3key) |
9,360 | def pop(self):
if self._count == 0:
raise StreamEmptyError("Pop called on buffered stream walker without any data", selector=self.selector)
while True:
curr = self.engine.get(self.storage_type, self.offset)
self.offset += 1
stream = DataStream.... | Pop a reading off of this stream and return it. |
9,361 | def get_tokens_by_code(self, code, state):
params = dict(oxd_id=self.oxd_id, code=code, state=state)
logger.debug("Sending command `get_tokens_by_code` with params %s",
params)
response = self.msgr.request("get_tokens_by_code", **params)
logger.debug("Recei... | Function to get access code for getting the user details from the
OP. It is called after the user authorizes by visiting the auth URL.
Parameters:
* **code (string):** code, parse from the callback URL querystring
* **state (string):** state value parsed from the callback URL
... |
9,362 | def _merge_mappings(*args):
dct = {}
for arg in args:
if isinstance(arg, dict):
merge = arg
else:
assert isinstance(arg, tuple)
keys, value = arg
merge = dict(zip(keys, [value]*len(keys)))
dct.update(merge)
return dct | Merges a sequence of dictionaries and/or tuples into a single dictionary.
If a given argument is a tuple, it must have two elements, the first of which is a sequence of keys and the second
of which is a single value, which will be mapped to from each of the keys in the sequence. |
9,363 | def AddPoly(self, poly, smart_duplicate_handling=True):
inserted_name = poly.GetName()
if poly.GetName() in self._name_to_shape:
if not smart_duplicate_handling:
raise ShapeError("Duplicate shape found: " + poly.GetName())
print ("Warning: duplicate shape id being added to collection: ... | Adds a new polyline to the collection. |
9,364 | def get_genes_for_hgnc_id(self, hgnc_symbol):
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/xrefs/symbol/homo_sapiens/{}".format(hgnc_symbol)
r = self.ensembl_request(ext, headers)
genes = []
... | obtain the ensembl gene IDs that correspond to a HGNC symbol |
9,365 | def main_nonexecutable_region_limbos_contain(self, addr, tolerance_before=64, tolerance_after=64):
closest_region = None
least_limbo = None
for start, end in self.main_nonexecutable_regions:
if start - tolerance_before <= addr < start:
if least_limbo is Non... | Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes
after the beginning of the section. We take care of that here.
:param int addr: The address to check.
:return: A 2-tuple of (bool, the closest base address)
:rtype: tuple |
9,366 | def create_node(hostname, username, password, name, address):
ret = {: name, : {}, : False, : }
if __opts__[]:
return _test_output(ret, , params={
: hostname,
: username,
: password,
: name,
: address
}
)
existi... | Create a new node if it does not already exist.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to create
address
The address of the node |
9,367 | def ReadSerializableArray(self, class_name, max=sys.maxsize):
module = .join(class_name.split()[:-1])
klassname = class_name.split()[-1]
klass = getattr(importlib.import_module(module), klassname)
length = self.ReadVarInt(max=max)
items = []
try:
... | Deserialize a stream into the object specific by `class_name`.
Args:
class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block'
max (int): (Optional) maximum number of bytes to read.
Returns:
list: list of `class_name` objects de... |
9,368 | def get_vnetwork_portgroups_output_vnetwork_pgs_vlan(self, **kwargs):
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
output = ET.SubElement(get_vnetwork_portgroups, "output")
vnetwork_pgs = E... | Auto Generated Code |
9,369 | def _convert_pflags(self, pflags):
if (pflags & SFTP_FLAG_READ) and (pflags & SFTP_FLAG_WRITE):
flags = os.O_RDWR
elif pflags & SFTP_FLAG_WRITE:
flags = os.O_WRONLY
else:
flags = os.O_RDONLY
if pflags & SFTP_FLAG_APPEND:
flags |= o... | convert SFTP-style open() flags to Python's os.open() flags |
9,370 | def get_requires(self, profile=None):
out = []
for req in self.requires:
if ((req.profile and not profile) or
(req.profile and profile and req.profile != profile)):
continue
out.append(req)
return out | Get filtered list of Require objects in this Feature
:param str profile: Return Require objects with this profile or None
to return all Require objects.
:return: list of Require objects |
9,371 | def get_relavent_units(self):
relavent_units = {}
for location,unit in self.units.items():
if self.unit_is_related(location, self.worksheet):
relavent_units[location] = unit
return relavent_units | Retrieves the relevant units for this data block.
Returns:
All flags related to this block. |
9,372 | def get_annotation_data_before_time(self, id_tier, time):
if self.tiers[id_tier][1]:
return self.get_ref_annotation_before_time(id_tier, time)
befores = self.get_annotation_data_between_times(id_tier, 0, time)
if befores:
return [max(befores, key=lambda x: x[0])]... | Give the annotation before a given time. When the tier contains
reference annotations this will be returned, check
:func:`get_ref_annotation_data_before_time` for the format. If an
annotation overlaps with ``time`` that annotation will be returned.
:param str id_tier: Name of the tier.
... |
9,373 | def apply_index(self, i):
if type(self) is not DateOffset:
raise NotImplementedError("DateOffset subclass {name} "
"does not have a vectorized "
"implementation".format(
na... | Vectorized apply of DateOffset to DatetimeIndex,
raises NotImplentedError for offsets without a
vectorized implementation.
Parameters
----------
i : DatetimeIndex
Returns
-------
y : DatetimeIndex |
9,374 | def _draw_box(self, parent_node, quartiles, outliers, box_index, metadata):
width = (self.view.x(1) - self.view.x(0)) / self._order
series_margin = width * self._series_margin
left_edge = self.view.x(0) + width * box_index + series_margin
width -= 2 * series_margin
... | Return the center of a bounding box defined by a box plot.
Draws a box plot on self.svg. |
9,375 | def pkgPath(root, path, rpath="/"):
global data_files
if not os.path.exists(path):
return
files = []
for spath in os.listdir(path):
if spath == :
continue
subpath = os.path.join(path, spath)
spath = os.path.join(rpath, spath)
if os.path.i... | Package up a path recursively |
9,376 | def fit_labels_to_mask(label_image, mask):
r
label_image = scipy.asarray(label_image)
mask = scipy.asarray(mask, dtype=scipy.bool_)
if label_image.shape != mask.shape:
raise ValueError()
labels = scipy.unique(label_image)
collection = {}
for label in labels:
collec... | r"""
Reduces a label images by overlaying it with a binary mask and assign the labels
either to the mask or to the background. The resulting binary mask is the nearest
expression the label image can form of the supplied binary mask.
Parameters
----------
label_image : array_like
A n... |
9,377 | def root_item_selected(self, item):
if self.show_all_files:
return
for root_item in self.get_top_level_items():
if root_item is item:
self.expandItem(root_item)
else:
self.collapseItem(root_item) | Root item has been selected: expanding it and collapsing others |
9,378 | def _filter_modules(self, plugins, names):
if self.module_plugin_filters:
original_length_plugins = len(plugins)
module_plugins = set()
for module_filter in self.module_plugin_filters:
module_plugins.update(module_filter(plugins, names))
... | Internal helper method to parse all of the plugins and names
through each of the module filters |
9,379 | def _wait_and_except_if_failed(self, event, timeout=None):
event.wait(timeout or self.__sync_timeout)
self._except_if_failed(event) | Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured
sync_timeout is used. |
9,380 | def get_version():
if not in sys.platform:
return NO_WIN
win_ver = sys.getwindowsversion()
try:
major, minor, build = win_ver.platform_version
except AttributeError:
if sys.version_info < (3, 0):
from platform import _get... | Get the Windows OS version running on the machine.
Params:
None
Returns:
The Windows OS version running on the machine (comparables with the values list in the class). |
9,381 | def redraw(self, whence=0):
with self._defer_lock:
whence = min(self._defer_whence, whence)
if not self.defer_redraw:
if self._hold_redraw_cnt == 0:
self._defer_whence = self._defer_whence_reset
self.redraw_now(whence=when... | Redraw the canvas.
Parameters
----------
whence
See :meth:`get_rgb_object`. |
9,382 | def set_mode_px4(self, mode, custom_mode, custom_sub_mode):
if isinstance(mode, str):
mode_map = self.mode_mapping()
if mode_map is None or mode not in mode_map:
print("Unknown mode " % mode)
return
mode, custom_mode, cust... | enter arbitrary mode |
9,383 | def updateStatus(self, dataset, is_dataset_valid):
if( dataset == "" ):
dbsExceptionHandler("dbsException-invalid-input", "DBSDataset/updateStatus. dataset is required.")
conn = self.dbi.connection()
trans = conn.begin()
try:
self.updatestatus.execute(c... | Used to toggle the status of a dataset is_dataset_valid=0/1 (invalid/valid) |
9,384 | def Kdiag(self, X):
vyt = self.variance_Yt
vyx = self.variance_Yx
lyt = 1./(2*self.lengthscale_Yt)
lyx = 1./(2*self.lengthscale_Yx)
a = self.a
b = self.b
c = self.c
k3 = ( 4*3*lyx**2 )*vyt*vyx
Kdiag = np.zeros(X.shape[0])
... | Compute the diagonal of the covariance matrix associated to X. |
9,385 | def collect(context=None, style=None, palette=None, **kwargs):
params = {}
if context:
params.update(get(context, , **kwargs))
if style:
params.update(get(style, , **kwargs))
if palette:
params.update(get(palette, , **kwargs))
return params | Returns the merged rcParams dict of the specified context, style, and palette.
Parameters
----------
context: str
style: str
palette: str
kwargs:
-
Returns
-------
rcParams: dict
The merged parameter dicts of the specified context, style, and palette.
Notes
... |
9,386 | def open_file(self, file_):
with open(file_, , encoding=) as file:
text =
for line in file:
text += line
return text | Receives a file path has input and returns a
string with the contents of the file |
9,387 | def happens(intervals: Iterable[float], name: Optional[str] = None) -> Callable:
def hook(event: Callable):
def make_happen(*args_event: Any, **kwargs_event: Any) -> None:
if name is not None:
local.name = cast(str, name)
for interval in intervals:
... | Decorator used to set up a process that adds a new instance of another process at intervals dictated by the given
sequence (which may be infinite).
Example: the following program runs process named `my_process` 5 times, each time spaced by 2.0 time units.
```
from itertools import repeat
sim = Si... |
9,388 | def last_archive(self):
archives = {}
for archive in self.archives():
archives[int(archive.split()[0].split()[-1])] = archive
return archives and archives[max(archives)] or None | Get the last available archive
:return: |
9,389 | def _make_image_to_vec_tito(feature_name, tmp_dir=None, checkpoint=None):
def _image_to_vec(image_str_tensor):
def _decode_and_resize(image_tensor):
f_out.write(f_in.read())
with tf.Session() as sess:
saver.restore(sess, checkpoint_tmp)
output_graph_def = ... | Creates a tensor-in-tensor-out function that produces embeddings from image bytes.
Image to embedding is implemented with Tensorflow's inception v3 model and a pretrained
checkpoint. It returns 1x2048 'PreLogits' embeddings for each image.
Args:
feature_name: The name of the feature. Used only to identify t... |
9,390 | def get_hints(self, plugin):
hints = []
for hint_name in getattr(plugin, , []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,... | Return plugin hints from ``plugin``. |
9,391 | def _get_instance(self):
try:
instance = self.compute_driver.ex_get_node(
self.running_instance_id,
zone=self.region
)
except ResourceNotFoundError as e:
raise GCECloudException(
.format(
id=... | Retrieve instance matching instance_id. |
9,392 | def intersection(self, other, ignore_conflicts=False):
result = self.copy()
result.intersection_update(other, ignore_conflicts)
return result | Return a new definition from the intersection of the definitions. |
9,393 | def _assign_method(self, resource_class, method_type):
method_name = resource_class.get_method_name(
resource_class, method_type)
valid_status_codes = getattr(
resource_class.Meta,
,
DEFAULT_VALID_STATUS_CODES
)
@self._ca... | Exactly the same code as the original except:
- uid is now first parameter (after self). Therefore, no need to explicitly call 'uid='
- Ignored the other http methods besides GET (as they are not needed for the pokeapi.co API)
- Added cache wrapping function
- Added a way to list all get... |
9,394 | def clean_metric_name(self, metric_name):
if not self._clean_metric_name:
return metric_name
metric_name = str(metric_name)
for _from, _to in self.cleaning_replacement_list:
metric_name = metric_name.replace(_from, _to)
return metric_name | Make sure the metric is free of control chars, spaces, tabs, etc. |
9,395 | def pm(client, event, channel, nick, rest):
if rest:
rest = rest.strip()
Karma.store.change(rest, 2)
rcpt = rest
else:
rcpt = channel
if random.random() > 0.95:
return f"Arrggh ye be doin good work, {rcpt}!" | Arggh matey |
9,396 | def from_description(cls, description, attrs):
hash_key = None
range_key = None
index_type = description["Projection"]["ProjectionType"]
includes = description["Projection"].get("NonKeyAttributes")
for data in description["KeySchema"]:
name = data["AttributeN... | Create an object from a dynamo3 response |
9,397 | def facts(self):
fact = lib.EnvGetNextFact(self._env, ffi.NULL)
while fact != ffi.NULL:
yield new_fact(self._env, fact)
fact = lib.EnvGetNextFact(self._env, fact) | Iterate over the asserted Facts. |
9,398 | def create_base_logger(config=None, parallel=None):
if parallel is None: parallel = {}
parallel_type = parallel.get("type", "local")
cores = parallel.get("cores", 1)
if parallel_type == "ipython":
from bcbio.log import logbook_zmqpush
fqdn_ip = socket.gethostbyname(socket.getfqdn())... | Setup base logging configuration, also handling remote logging.
Correctly sets up for local, multiprocessing and distributed runs.
Creates subscribers for non-local runs that will be references from
local logging.
Retrieves IP address using tips from http://stackoverflow.com/a/1267524/252589 |
9,399 | def pre_serialize(self, raw, pkt, i):
self.length = len(raw) + OpenflowHeader._MINLEN | Set length of the header based on |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.