Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
374,600 | def visualize_explanation(explanation, label=None):
if not sys.version_info[:2] >= (3, 5):
raise IndicoError("Python >= 3.5+ is required for explanation visualization")
try:
from colr import Colr as C
except ImportError:
raise IndicoError("Package colr >= 0.8.1 is required for explan... | Given the output of the explain() endpoint, produces a terminal visual that plots response strength over a sequence |
374,601 | def _writetypesdoc(doc, thing, forceload=0):
try:
object, name = pydoc.resolve(thing, forceload)
name = os.path.join(doc, name + )
except (ImportError, pydoc.ErrorDuringImport), value:
log.debug(str(value))
return
cdict = {}
fdict = {}
elements_dict... | Write HTML documentation to a file in the current directory. |
374,602 | def PublishEvent(cls, event_name, msg, token=None):
cls.PublishMultipleEvents({event_name: [msg]}, token=token) | Publish the message into all listeners of the event.
We send the message to all event handlers which contain this
string in their EVENT static member. This allows the event to be
sent to multiple interested listeners.
Args:
event_name: An event name.
msg: The message to send to the event h... |
374,603 | def openflow_controller_controller_name(self, **kwargs):
config = ET.Element("config")
openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow")
controller_name = ET.SubElement(openflow_controller, "controller-name")
contro... | Auto Generated Code |
374,604 | def _set_default_vrf(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=default_vrf.default_vrf, is_container=, presence=False, yang_name="default-vrf", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths... | Setter method for default_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_default_vrf is considered as a private
method. Backends looking to populate this va... |
374,605 | def _empty_queue(self):
while True:
try:
self.queue.pop()
self.unused += 1
self.nqueue -= 1
except:
self.nqueue = 0
break | Dump all live point proposals currently on the queue. |
374,606 | def _set_ocsp_callback(self, helper, data):
self._ocsp_helper = helper
self._ocsp_callback = helper.callback
if data is None:
self._ocsp_data = _ffi.NULL
else:
self._ocsp_data = _ffi.new_handle(data)
rc = _lib.SSL_CTX_set_tlsext_status_cb(
... | This internal helper does the common work for
``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
almost all of it. |
374,607 | def modified(self, base: pathlib.PurePath = pathlib.PurePath()) \
-> Iterator[str]:
if self.is_modified:
yield str(base / self.right.name) | Find the paths of modified files. There is no option to include
intermediate directories, as all files and directories exist in both
the left and right trees.
:param base: The base directory to recursively append to the right
entity.
:return: An iterable of paths of... |
374,608 | def inverse(self):
if self.scalar == 0.0:
raise ZeroDivisionError(
)
return ScalingOperator(self.domain, 1.0 / self.scalar) | Return the inverse operator.
Examples
--------
>>> r3 = odl.rn(3)
>>> vec = r3.element([1, 2, 3])
>>> op = ScalingOperator(r3, 2.0)
>>> inv = op.inverse
>>> inv(op(vec)) == vec
True
>>> op(inv(vec)) == vec
True |
374,609 | def as_tree(self, visitor=None, children=None):
_parameters = {"node": self}
if visitor is not None:
_parameters["visitor"] = visitor
if children is not None:
_parameters["children"] = children
return self.__class__.objects.node_as_tree(**_parameters) | Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary representation, where the entry
``children`` (by... |
374,610 | def default(self, vid):
command = % vid
return self.configure(command) if isvlan(vid) else False | Defaults the VLAN configuration
.. code-block:: none
default vlan <vlanid>
Args:
vid (str): The VLAN ID to default
Returns:
True if the operation was successful otherwise False |
374,611 | def put(self, transfer_id, amount, created_timestamp, receipt):
return self.connection.put(,
data=dict(transfer_id=transfer_id,
amount=amount,
created_timestamp=created_timestamp... | :param transfer_id: int of the account_id to deposit the money to
:param amount: float of the amount to transfer
:param created_timestamp: str of the validated receipt that money has been received
:param receipt: str of the receipt
:return: ... |
374,612 | def _sort_results(self, results):
parents = []
groups = []
for result in results:
if not self._in_list(parents, result.parent):
parents.append(result.parent)
groups.append([])
groups[len(groups) - 1].append(result)
... | Order the results.
:param results: The disordened results.
:type results: array.bs4.element.Tag
:return: The ordened results.
:rtype: array.bs4.element.Tag |
374,613 | def attach_stream(self, stream):
curr_stream, count, prev = self._allocated_streams[stream]
if count == (self.model.get(u) - 1):
new_stream = self.allocate_stream(curr_stream.stream_type, previous=curr_stream)
copy_desc = u"({} always) => {} using copy_all_a".... | Notify that we would like to attach a node input to this stream.
The return value from this function is the DataStream that should be attached
to since this function may internally allocate a new SGNode that copies the
stream if there is no space in the output list to hold another input.
... |
374,614 | def wait_for_simulation_stop(self, timeout=None):
start = datetime.now()
while self.get_is_sim_running():
sleep(0.5)
if timeout is not None:
if (datetime.now() - start).seconds >= timeout:
ret = None
break
e... | Block until the simulation is done or timeout seconds exceeded.
If the simulation stops before timeout, siminfo is returned. |
374,615 | def read_config_files(self, files):
errors = {}
for _file in files:
config, valid = self.read_config_file(_file)
self.update(config)
if valid is not True:
errors[_file] = valid
return errors or True | Read a list of config files.
:param iterable files: An iterable (e.g. list) of files to read. |
374,616 | def get_active_lines(lines, comment_char="
return list(filter(None, (line.split(comment_char, 1)[0].strip() for line in lines))) | Returns lines, or parts of lines, from content that are not commented out
or completely empty. The resulting lines are all individually stripped.
This is useful for parsing many config files such as ifcfg.
Parameters:
lines (list): List of strings to parse.
comment_char (str): String indi... |
374,617 | def _convert_coordinatelist(input_obj):
cdl = pgmagick.CoordinateList()
for obj in input_obj:
cdl.append(pgmagick.Coordinate(obj[0], obj[1]))
return cdl | convert from 'list' or 'tuple' object to pgmagick.CoordinateList.
:type input_obj: list or tuple |
374,618 | def load_module(self, module):
m_ref = self._modules_map.get(module)
if m_ref is None:
raise LoaderError(.format(module))
mod = importlib.import_module(.format(
.join([elm.split()[0] for elm in m_ref.split(os.path.sep)])))
return mod | Introspect Ansible module.
:param module:
:return: |
374,619 | def name2rgb(name):
try:
import colour
except ImportError:
raise ImportError()
c = colour.Color(name)
color = int(c.red * 255), int(c.green * 255), int(c.blue * 255)
return color | Convert the name of a color into its RGB value |
374,620 | def _mk_connectivity_flats(self, i12, j1, j2, mat_data, flats, elev, mag):
nn, mm = flats.shape
NN = np.prod(flats.shape)
assigned, n_flats = spndi.label(flats, FLATS_KERNEL3)
flat_ids, flat_coords, flat_labelsf = _get_flat_ids(assigned)
flat_j = [None] * n_fla... | Helper function for _mk_adjacency_matrix. This calcualtes the
connectivity for flat regions. Every pixel in the flat will drain
to a random pixel in the flat. This accumulates all the area in the
flat region to a single pixel. All that area is then drained from
that pixel to the surround... |
374,621 | def find_credentials():
return DETAILS[], password
| Cycle through all the possible credentials and return the first one that
works. |
374,622 | def get_config_id(kwargs=None, call=None):
if call == :
raise SaltCloudException(
)
if kwargs is None:
kwargs = {}
name = kwargs.get(, None)
linode_id = kwargs.get(, None)
if name is None and linode_id is None:
raise SaltCloudSystemExit(
... | Returns a config_id for a given linode.
.. versionadded:: 2015.8.0
name
The name of the Linode for which to get the config_id. Can be used instead
of ``linode_id``.h
linode_id
The ID of the Linode for which to get the config_id. Can be used instead
of ``name``.
CLI Ex... |
374,623 | def get_link(self, task_id):
links = [x for x in self.links if x.task_id == task_id]
if len(links) != 1:
raise CoTError("No single Link matches task_id {}!\n{}".format(task_id, self.dependent_task_ids()))
return links[0] | Get a ``LinkOfTrust`` by task id.
Args:
task_id (str): the task id to find.
Returns:
LinkOfTrust: the link matching the task id.
Raises:
CoTError: if no ``LinkOfTrust`` matches. |
374,624 | def catch_config_error(method, app, *args, **kwargs):
try:
return method(app, *args, **kwargs)
except (TraitError, ArgumentError) as e:
app.print_description()
app.print_help()
app.print_examples()
app.log.fatal("Bad config encountered during initialization:")
... | Method decorator for catching invalid config (Trait/ArgumentErrors) during init.
On a TraitError (generally caused by bad config), this will print the trait's
message, and exit the app.
For use on init methods, to prevent invoking excepthook on invalid input. |
374,625 | def remove_all_observers(self):
for weak_observer in self._weak_observers:
observer = weak_observer()
if observer:
self.remove_observer(observer) | Removes all registered observers. |
374,626 | def compose(self, other, qargs=None, front=False):
if qargs is not None:
return Stinespring(
SuperOp(self).compose(other, qargs=qargs, front=front))
if not isinstance(other, Kraus):
other = Kraus(other)
if front and self._input_... | Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel subclass.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compo... |
374,627 | def generate_nodeinfo2_document(**kwargs):
return {
"version": "1.0",
"server": {
"baseUrl": kwargs[][],
"name": kwargs[][],
"software": kwargs[][],
"version": kwargs[][],
},
"organization": {
"name": kwargs.get(, {}).g... | Generate a NodeInfo2 document.
Pass in a dictionary as per NodeInfo2 1.0 schema:
https://github.com/jaywink/nodeinfo2/blob/master/schemas/1.0/schema.json
Minimum required schema:
{server:
baseUrl
name
software
version
}
openRegistrations
... |
374,628 | def configure_stream_logger(logger=, level=None, formatter=):
level = level or logging.WARNING
if isinstance(level, str):
level = getattr(logging, level, None)
if level is None:
raise ValueError( + level)
root_logger = logging.getLogger()
for handler in root_logger.handlers:
root_logger.removeHandler(han... | Configure the default stream handler for logging messages to the console,
remove other logging handlers, and enable capturing warnings.
.. versionadded:: 1.3.0
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specifie... |
374,629 | def parse_request() -> Dict[str, str]:
in_lines = sys.stdin.readlines()
LOGGER.debug(, in_lines)
request = {}
for line in in_lines:
if not line.strip():
continue
parts = line.split(, 1)
assert len(parts) == 2
request[parts[0].strip()] = parts[1... | Parse the request of the git credential API from stdin.
Returns:
A dictionary with all key-value pairs of the request |
374,630 | def verify_leaf_inclusion(self, leaf: bytes, leaf_index: int,
proof: List[bytes], sth: STH):
leaf_hash = self.hasher.hash_leaf(leaf)
return self.verify_leaf_hash_inclusion(leaf_hash, leaf_index, proof,
sth) | Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf: The leaf for which the proof was provided.
leaf_index: Index of the leaf in the tree.
proof: A list of SHA-256 hashes representing the Merkle audit
path... |
374,631 | def dumps(self):
ret_str = []
for item in self._arg_list:
if isinstance(item, TikZUserPath):
ret_str.append(item.dumps())
elif isinstance(item, TikZCoordinate):
ret_str.append(item.dumps())
elif isinstance(item, str):
... | Return representation of the path command. |
374,632 | def transformer_tall_finetune_uniencdec():
hparams = transformer_tall()
hparams.max_input_seq_length = 750
hparams.max_target_seq_length = 100
hparams.optimizer = "true_adam"
hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay")
hparams.learning_rate_decay_steps = 80000
hparams.learning_... | Fine-tune CNN/DM with a unidirectional encoder and decoder. |
374,633 | def has_sources(self, extension=None):
source_paths = self._sources_field.source_paths
if not source_paths:
return False
if not extension:
return True
return any(source.endswith(extension) for source in source_paths) | Return `True` if this target owns sources; optionally of the given `extension`.
:API: public
:param string extension: Optional suffix of filenames to test for.
:return: `True` if the target contains sources that match the optional extension suffix.
:rtype: bool |
374,634 | def get_probmodel_data(model):
if not isinstance(model, BayesianModel):
raise TypeError("Model must an instance of BayesianModel.")
model_data = {: {: , : {}}}
variables = model.nodes()
for var in variables:
model_data[][][var] = model.node[var]
model_data[][] = {}
edges =... | Returns the model_data based on the given model.
Parameters
----------
model: BayesianModel instance
Model to write
Return
------
model_data: dict
dictionary containing model data of the given model.
Examples
--------
>>> model_data = pgmpy.readwrite.get_model_data... |
374,635 | def _merge_tops_merge_all(self, tops):
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
state... | Merge the top files into a single dictionary |
374,636 | def auto_discover_board(self, verbose):
start_time = time.time()
while len(self.analog_mapping_query_results) == 0:
if time.time() - start_time > 30:
return False
self.send_sysex(self.ANALOG_MAPPING_QUERY)
... | This method will allow up to 30 seconds for discovery (communicating with) an Arduino board
and then will determine a pin configuration table for the board.
:return: True if board is successfully discovered or False upon timeout |
374,637 | def _cleanup_temp_dir(self, base_dir):
if self._should_cleanup_temp_dir:
logging.debug(, base_dir)
if self._user is None:
util.rmtree(base_dir, onerror=util.log_rmtree_error)
else:
rm = subprocess.Popen(self._build_cmdline([, , , base_... | Delete given temporary directory and all its contents. |
374,638 | def available_phone_numbers(self):
if self._available_phone_numbers is None:
self._available_phone_numbers = AvailablePhoneNumberCountryList(
self._version,
account_sid=self._solution[],
)
return self._available_phone_numbers | Access the available_phone_numbers
:returns: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList
:rtype: twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryList |
374,639 | def load_stock_quantity(self, symbol: str) -> Decimal(0):
book = self.get_gc_book()
collection = SecuritiesAggregate(book)
sec = collection.get_aggregate_for_symbol(symbol)
quantity = sec.get_quantity()
return quantity | retrieves stock quantity |
374,640 | def _update_alpha(self, event=None):
a = self.alpha.get()
hexa = self.hexa.get()
hexa = hexa[:7] + ("%2.2x" % a).upper()
self.hexa.delete(0, )
self.hexa.insert(0, hexa)
self.alphabar.set(a)
self._update_preview() | Update display after a change in the alpha spinbox. |
374,641 | def _enable_read_access(self):
if not self.algo_inited_for_read:
self.flash.init(self.flash.Operation.VERIFY)
self.algo_inited_for_read = True | ! @brief Ensure flash is accessible by initing the algo for verify.
Not all flash memories are always accessible. For instance, external QSPI. Initing the
flash algo for the VERIFY operation is the canonical way to ensure that the flash is
memory mapped and accessible. |
374,642 | async def process_check_ins(self):
params = {
: 1,
: 1 if AUTO_GET_MATCHES else 0
}
res = await self.connection(, .format(self._id), **params)
self._refresh_from_json(res) | finalize the check in phase
|methcoro|
Warning:
|unstable|
Note:
|from_api| This should be invoked after a tournament's check-in window closes before the tournament is started.
1. Marks participants who have not checked in as inactive.
2. Moves ... |
374,643 | def generate_row_keys(self):
keys = self.key
columns = self.values
if not self._data:
self._data = self.get_data()
for column in columns:
key_prefix = self.cache_key_prefix() + "
self._data[] = self._data[keys].apply(lambda xdf: key_prefix + ... | Method for generating key features at serving time or prediction time
:param data: Pass in the data that is necessary for generating the keys
Example :
Feature : User warehouse searches and conversions
Keys will be of the form 'user_id#warehouse_id#searches=23811676#3'
... |
374,644 | def launch_external_file(filename: str, raise_if_fails: bool = False) -> None:
log.info("Launching external file: {!r}", filename)
try:
if sys.platform.startswith():
cmdargs = ["xdg-open", filename]
subprocess.call(cmdargs)
else:
... | Launches a file using the operating system's standard launcher.
Args:
filename: file to launch
raise_if_fails: raise any exceptions from
``subprocess.call(["xdg-open", filename])`` (Linux)
or ``os.startfile(filename)`` (otherwise)? If not, exceptions
are suppress... |
374,645 | def add_postprocessor(postproc):
def decorator(func):
func = ScriptAdaptor._wrap(func)
func._add_postprocessor(postproc)
return func
return decorator | Define a postprocessor to run after the function is executed, when
running in console script mode.
:param postproc: The callable, which will be passed the Namespace
object generated by argparse and the return
result of the function. The return result of the
... |
374,646 | def matchiter(r, s, flags=0):
if isinstance(r, basestring):
r = re.compile(r, flags)
i = 0
while s:
m = r.match(s)
g = m and m.group(0)
if not m or not g:
raise ValueError("{}: {!r}".format(i, s[:50]))
i += len(g)
s = s[len(g):]
yield ... | Yields contiguous MatchObjects of r in s.
Raises ValueError if r eventually doesn't match contiguously. |
374,647 | def _parse_connection_string(connstr):
res = {}
for item in connstr.split():
item = item.strip()
if not item:
continue
key, value = item.split(, 1)
key = key.strip().lower().replace(, )
value = value.strip()
res[key] = value
return res | MSSQL style connection string parser
Returns normalized dictionary of connection string parameters |
374,648 | def _check_dhcp_server(self, vboxnet):
properties = yield from self._execute("list", ["dhcpservers"])
flag_dhcp_server_found = False
for prop in properties.splitlines():
try:
name, value = prop.split(, 1)
except ValueError:
contin... | Check if the DHCP server associated with a vboxnet is enabled.
:param vboxnet: vboxnet name
:returns: boolean |
374,649 | def _posix_split_name(self, name):
prefix = name[:LENGTH_PREFIX + 1]
while prefix and prefix[-1] != "/":
prefix = prefix[:-1]
name = name[len(prefix):]
prefix = prefix[:-1]
if not prefix or len(name) > LENGTH_NAME:
raise ValueError("name is too ... | Split a name longer than 100 chars into a prefix
and a name part. |
374,650 | def _track_stack_pointers(self):
regs = {self.project.arch.sp_offset}
if hasattr(self.project.arch, ) and self.project.arch.bp_offset is not None:
regs.add(self.project.arch.bp_offset)
spt = self.project.analyses.StackPointerTracker(self.function, regs, track_memory=self._s... | For each instruction, track its stack pointer offset and stack base pointer offset.
:return: None |
374,651 | def results(self):
if self.deriv == 0:
return self.v,
if self.deriv == 1:
return self.v, self.d
if self.deriv == 2:
return self.v, self.d, self.dd | Return the value and optionally derivative and second order derivative |
374,652 | def _compile_pattern(pat, ignore_case=True):
if isinstance(pat, bytes):
pat_str = pat.decode()
res_str = _translate_glob(pat_str)
res = res_str.encode()
else:
res = _translate_glob(pat)
flags = re.IGNORECASE if ignore_case else 0
return re.compile(res, flags=flags).m... | Translate and compile a glob pattern to a regular expression matcher. |
374,653 | def environ_setting(name, default=None, required=True):
if name not in os.environ and default is None:
message = "The {0} ENVVAR is not set.".format(name)
if required:
raise ImproperlyConfigured(message)
else:
warnings.warn(ConfigurationMissing(message))
ret... | Fetch setting from the environment. The bahavior of the setting if it
is not in environment is as follows:
1. If it is required and the default is None, raise Exception
2. If it is requried and a default exists, return default
3. If it is not required and default is None, return None
... |
374,654 | def from_class(cls, target_class):
module_name = target_class.__module__
class_name = target_class.__name__
return cls(module_name, "__init__", class_name) | Create a FunctionDescriptor from a class.
Args:
cls: Current class which is required argument for classmethod.
target_class: the python class used to create the function
descriptor.
Returns:
The FunctionDescriptor instance created according to the cl... |
374,655 | def get_edges_with_citations(self, citations: Iterable[Citation]) -> List[Edge]:
return self.session.query(Edge).join(Evidence).filter(Evidence.citation.in_(citations)).all() | Get edges with one of the given citations. |
374,656 | def Times(self, val):
return Point(self.x * val, self.y * val, self.z * val) | Returns a new point which is pointwise multiplied by val. |
374,657 | def stack_push(self, key, value):
task = Task.current_task()
try:
context = task._context_stack
except AttributeError:
task._context_stack = context = {}
if key not in context:
context[key] = []
context[key].append(value) | Set a value in a task context stack |
374,658 | def wsgi(self, environ, start_response):
request = Request(environ)
ctx = Context(request)
try:
try:
response = self(request, ctx)
ctx._run_callbacks(, (request, response))
response = response.conditional_to(request)
... | Implements the mapper's WSGI interface. |
374,659 | def contributors(self, sr, limit=None):
userlist = self._limit_get(, sr, , , limit=limit)
return _process_userlist(userlist) | Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each contributor, yo... |
374,660 | def STRH(self, params):
Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params)
if self.is_immediate(Rc):
self.check_arguments(low_registers=(Ra, Rb), imm5=(Rc,))
def STRH_func():
for i in range(2):
self.me... | STRH Ra, [Rb, Rc]
STRH Ra, [Rb, #imm6_2]
Store Ra into memory as a half word
Ra, Rb, and Rc must be low registers |
374,661 | def set_values(self,x):
x = numpy.atleast_2d(x)
x = x.real
C_inv = self.__C_inv__
theta = numpy.dot( x, C_inv )
self.theta = theta
return theta | Updates self.theta parameter. No returns values |
374,662 | def ADC(cpu, dest, src):
cpu._ADD(dest, src, carry=True) | Adds with carry.
Adds the destination operand (first operand), the source operand (second operand),
and the carry (CF) flag and stores the result in the destination operand. The state
of the CF flag represents a carry from a previous addition. When an immediate value
is used as an opera... |
374,663 | def show(self):
bytecode._Print("MAP_LIST SIZE", self.size)
for i in self.map_item:
if i.item != self:
i.show() | Print with a pretty display the MapList object |
374,664 | def msg_curse(self, args=None, max_width=None):
ret = []
if not self.stats or self.is_disable():
return ret
msg = .format()
ret.append(self.curse_add_line(msg, "TITLE"))
msg = .format(self.trend_msg(self.get_trend()))
... | Return the dict to display in the curse interface. |
374,665 | def set_current_operation_progress(self, percent):
if not isinstance(percent, baseinteger):
raise TypeError("percent can only be an instance of type baseinteger")
self._call("setCurrentOperationProgress",
in_p=[percent]) | Internal method, not to be called externally.
in percent of type int |
374,666 | def delete_connection(self, **kwargs):
conn = self.find_connection(**kwargs)
if not conn:
return False
self.delete(conn)
return True | Remove a single connection to a provider for the specified user. |
374,667 | def p_genvarlist(self, p):
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | genvarlist : genvarlist COMMA genvar |
374,668 | def _compute_total_chunks(self, chunk_size):
try:
return int(math.ceil(self._ase.size / chunk_size))
except ZeroDivisionError:
return 0 | Compute total number of chunks for entity
:param Descriptor self: this
:param int chunk_size: chunk size
:rtype: int
:return: num chunks |
374,669 | def call_moses_detokenizer(workspace_dir: str, input_fname: str, output_fname: str, lang_code: Optional[str] = None):
detokenizer_fname = os.path.join(workspace_dir,
DIR_THIRD_PARTY,
MOSES_DEST,
"scri... | Call Moses detokenizer.
:param workspace_dir: Workspace third-party directory where Moses
tokenizer is checked out.
:param input_fname: Path of tokenized input file, plain text or gzipped.
:param output_fname: Path of tokenized output file, plain text.
:param lang_code: Langua... |
374,670 | def convert_relational(relational):
rel = relational.rel_op
if rel in [, , ]:
return relational.lhs-relational.rhs
elif rel in [, ]:
return relational.rhs-relational.lhs
else:
raise Exception("The relational operation is not "
"implemented!") | Convert all inequalities to >=0 form. |
374,671 | def window_iterator(data, width):
start = 0
while start < len(data):
yield data[start:start+width]
start += width | Instead of iterating element by element, get a number of elements at each iteration step.
:param data: data to iterate on
:param width: maximum number of elements to get in each iteration step
:return: |
374,672 | def _paged_api_call(self, func, kwargs, item_type=):
page = 1
while True:
LOG.info("Fetching page %s" % page)
kwargs[] = page
rsp = self._load_rsp(func(**kwargs))
if rsp["stat"] == "ok":
plural = item_type +
if plu... | Takes a Flickr API function object and dict of keyword args and calls the
API call repeatedly with an incrementing page value until all contents are exhausted.
Flickr seems to limit to about 500 items. |
374,673 | def get_agile_board(self, board_id):
url = .format(str(board_id))
return self.get(url) | Get agile board info by id
:param board_id:
:return: |
374,674 | def add_boundary_regions(regions=None, faces=[, , ,
, , ]):
r
if faces is not None:
regions = sp.pad(regions, 1, )
if regions.ndim == 3:
regions[:, :, 0] = regions[:, :, 0] + regions.max()
regio... | r"""
Given an image partitioned into regions, pads specified faces with new
regions
Parameters
----------
regions : ND-array
An image of the pore space partitioned into regions and labeled
faces : list of strings
The faces of ``regions`` which should have boundaries added. Opti... |
374,675 | def clone(self, instance):
metaclass = get_metaclass(instance)
metaclass = self.find_metaclass(metaclass.kind)
return metaclass.clone(instance) | Create a shallow clone of an *instance*.
**Note:** the clone and the original instance **does not** have to be
part of the same metaclass. |
374,676 | def channels(self):
def comparator(channel):
return (not isinstance(channel, TextChannel), channel.position)
ret = [c for c in self.guild.channels if c.category_id == self.id]
ret.sort(key=comparator)
return ret | List[:class:`abc.GuildChannel`]: Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels. |
374,677 | def parse_dossier_data(data, ep):
changed = False
doc_changed = False
ref = data[][]
logger.debug(, ref)
with transaction.atomic():
try:
dossier = Dossier.objects.get(reference=ref)
except Dossier.DoesNotExist:
dossier = Dossier(reference=ref)
... | Parse data from parltarck dossier export (1 dossier) Update dossier
if it existed before, this function goal is to import and update a
dossier, not to import all parltrack data |
374,678 | def _compute_a22_factor(self, imt):
if imt.name == :
return 0.0
period = imt.period
if period < 2.0:
return 0.0
else:
return 0.0625 * (period - 2.0) | Compute and return the a22 factor, equation 20, page 80. |
374,679 | def precompile_python_code(context: Context):
from compileall import compile_dir
kwargs = {}
if context.verbosity < 2:
kwargs[] = True
compile_dir(context.app.django_app_name, **kwargs) | Pre-compiles python modules |
374,680 | def try_greyscale(pixels, alpha=False, dirty_alpha=True):
planes = 3 + bool(alpha)
res = list()
apix = list()
for row in pixels:
green = row[1::planes]
if alpha:
apix.append(row[4:planes])
if (green != row[0::planes] or green != row[2::planes]):
retur... | Check if flatboxed RGB `pixels` could be converted to greyscale
If could - return iterator with greyscale pixels,
otherwise return `False` constant |
374,681 | def get_gan_loss(self, true_frames, gen_frames, name):
with tf.variable_scope("%s_discriminator" % name, reuse=tf.AUTO_REUSE):
gan_d_loss, _, fake_logits_stop = self.d_step(
true_frames, gen_frames)
with tf.variable_scope("%s_discriminator" % name, reuse=True):
gan_g_loss_p... | Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be ground truth.
gen_frames: 5-D Tensor of shape (num_steps,... |
374,682 | def read_lock(self):
me = self._current_thread()
if me in self._pending_writers:
raise RuntimeError("Writer %s can not acquire a read lock"
" while waiting for the write lock"
% me)
with self._cond:
wh... | Context manager that grants a read lock.
Will wait until no active or pending writers.
Raises a ``RuntimeError`` if a pending writer tries to acquire
a read lock. |
374,683 | def locate_point(nodes, x_val, y_val):
r
zero1 = _curve_helpers.full_reduce(nodes[[0], :]) - x_val
zero2 = _curve_helpers.full_reduce(nodes[[1], :]) - y_val
if zero1.shape[1] > zero2.shape[1]:
zero1, zero2 = zero2, zero1
zero1, zero2 = zero2, zero1
power_... | r"""Find the parameter corresponding to a point on a curve.
.. note::
This assumes that the curve :math:`B(s, t)` defined by ``nodes``
lives in :math:`\mathbf{R}^2`.
Args:
nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve.
x_val (float): The :math:`x`-coordinate ... |
374,684 | def _get_version_for_class_from_state(state, klass):
names = [_importable_name(klass)]
from .util import class_rename_registry
names.extend(class_rename_registry.old_handled_by(klass))
for n in names:
try:
return state[][n]
... | retrieves the version of the current klass from the state mapping from old locations to new ones. |
374,685 | def get_device_status(host, services=None, zconf=None):
try:
status = _get_status(
host, services, zconf, "/setup/eureka_info?options=detail")
friendly_name = status.get(, "Unknown Chromecast")
model_name = "Unknown model name"
manufacturer = "Unknown manufacturer"... | :param host: Hostname or ip to fetch status from
:type host: str
:return: The device status as a named tuple.
:rtype: pychromecast.dial.DeviceStatus or None |
374,686 | def _create_app(self):
template_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), self.TEMPLATE_FOLDER, self.TEMPLATE_FILENAME
)
new_dir = self._arguments[]
override_destination = self._arguments.get(, None)
if overr... | Method for creating a new Application Template.
USAGE: cloud-harness create <dir_name> [--destination=<path>] |
374,687 | def getValue(self):
dropdown_value = self.widget.GetValue()
if not str(dropdown_value).isdigit():
return
arg = str(self.option_string).replace(, )
repeated_args = arg * int(dropdown_value)
return + repeated_args | Returns
str(option_string * DropDown Value)
e.g.
-vvvvv |
374,688 | def repr_imgs(imgs):
if isinstance(imgs, string_types):
return imgs
if isinstance(imgs, collections.Iterable):
return .format(.join(repr_imgs(img) for img in imgs))
try:
filename = imgs.get_filename()
if filename is not None:
img_str = "{}()".format(im... | Printing of img or imgs |
374,689 | def _add_games_to_schedule(self, schedule):
for item in schedule:
if in str(item) or \
in str(item):
continue
game = Game(item)
self._games.append(game) | Add game information to list of games.
Create a Game instance for the given game in the schedule and add it to
the list of games the team has or will play during the season.
Parameters
----------
schedule : PyQuery object
A PyQuery object pertaining to a team's sche... |
374,690 | def main():
args = parse_arguments()
if args.askpass:
password = getpass.getpass("Password: ")
else:
password = None
if args.asksudopass:
sudo = True
sudo_pass = getpass.getpass("Sudo password[default ssh password]: ")
if len(sudo_pass) == 0:
sud... | Simple examples |
374,691 | def where(self, fieldname, value, negate=False):
if negate:
return self.mask([elem != value
for elem in self[fieldname]])
else:
return self.mask([elem == value
for elem in self[fieldname]]) | Returns a new DataTable with rows only where the value at
`fieldname` == `value`. |
374,692 | def modify_replication_group(ReplicationGroupId=None, ReplicationGroupDescription=None, PrimaryClusterId=None, SnapshottingClusterId=None, AutomaticFailoverEnabled=None, CacheSecurityGroupNames=None, SecurityGroupIds=None, PreferredMaintenanceWindow=None, NotificationTopicArn=None, CacheParameterGroupName=None, Notific... | Modifies the settings for a replication group.
See also: AWS API Documentation
:example: response = client.modify_replication_group(
ReplicationGroupId='string',
ReplicationGroupDescription='string',
PrimaryClusterId='string',
SnapshottingClusterId='string',
Aut... |
374,693 | def parse(self, gff_file, strict=False):
valid_strand = set((, , , ))
valid_phase = set((0, 1, 2))
multi_value_attributes = set((, , , , ))
valid_attribute_target_strand = set((, , ))
reserved_attributes = set((, , , , , , , , , , ))
... | Parse the gff file into the following data structures:
* lines(list of line_data(dict))
- line_index(int): the index in lines
- line_raw(str)
- line_type(str in ['feature', 'directive', 'comment', 'blank', 'unknown'])
- line_errors(list of str): a list of error m... |
374,694 | def _cleanup_and_die(data):
tmpfiles = glob.glob(os.path.join(data.dirs.fastqs, "tmp_*_R*.fastq"))
tmpfiles += glob.glob(os.path.join(data.dirs.fastqs, "tmp_*.p"))
for tmpf in tmpfiles:
os.remove(tmpf) | cleanup func for step 1 |
374,695 | def delete(self, object_id):
obj = self.session.query(self.cls).filter_by(id=object_id).one()
self.session.delete(obj)
return obj | Delete an object by its id
:param object_id: the objects id.
:return: the deleted object
:raises: :class: NoResultFound when the object could not be found |
374,696 | def calculate_bins(array, _=None, *args, **kwargs) -> BinningBase:
if array is not None:
if kwargs.pop("check_nan", True):
if np.any(np.isnan(array)):
raise RuntimeError("Cannot calculate bins in presence of NaN's.")
if kwargs.get("range", None):
array... | Find optimal binning from arguments.
Parameters
----------
array: arraylike
Data from which the bins should be decided (sometimes used, sometimes not)
_: int or str or Callable or arraylike or Iterable or BinningBase
To-be-guessed parameter that specifies what kind of binning should be ... |
374,697 | def mav_to_gpx(infilename, outfilename):
mlog = mavutil.mavlink_connection(infilename)
outf = open(outfilename, mode=)
def process_packet(timestamp, lat, lon, alt, hdg, v):
t = time.localtime(timestamp)
outf.write( % (lat, lon, alt,
time.strftime("%Y-%m-%dT%H:%M:%SZ", t),
... | convert a mavlink log file to a GPX file |
374,698 | def _run_config_cmds(self, commands, server):
command_start = [, ]
command_end = []
full_command = command_start + commands + command_end
self._run_eos_cmds(full_command, server) | Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
:param server: Server endpoint on the Arista switch to be configu... |
374,699 | def plugin(module, *args, **kwargs):
def wrap(f):
m = module(f, *args, **kwargs)
if inspect.isclass(m):
for k, v in m.__dict__.items():
if not k.startswith("__"):
setattr(f, k, v)
elif inspect.isfunction(m):
setattr(f, kls.__na... | Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def my_view(self):
return {}
return MyEx... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.