Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
338,400 | def egg2dist(self, egginfo_path, distinfo_path):
def adios(p):
if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):
shutil.rmtree(p)
elif os.path.exists(p):
os.unlink(p)
adios(distinfo_path)
if not os... | Convert an .egg-info directory into a .dist-info directory |
338,401 | def create_parser(self, prog_name, subcommand):
parser = OptionParser(prog=prog_name,
usage=self.usage(subcommand),
option_list=self.option_list)
return parser | Create an OptionParser
prog_name - Name of a command
subcommand - Name of a subcommand |
338,402 | def getResultsRangeDict(self):
specs = {}
subfields = self.Schema()[].subfields
for spec in self.getResultsRange():
keyword = spec[]
specs[keyword] = {}
for key in subfields:
if key not in [, ]:
specs[keyword][key] ... | Return a dictionary with the specification fields for each
service. The keys of the dictionary are the keywords of each
analysis service. Each service contains a dictionary in which
each key is the name of the spec field:
specs['keyword'] = {'min': value,
... |
338,403 | def gpg_export_key( appname, key_id, config_dir=None, include_private=False ):
assert is_valid_appname(appname)
config_dir = get_config_dir( config_dir )
keydir = get_gpg_home( appname, config_dir=config_dir )
gpg = gnupg.GPG( homedir=keydir )
keydat = gpg.export_keys( [key_id], secret=include... | Get the ASCII-armored key, given the ID |
338,404 | def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS,
packet_size=PACKET_SIZE, path_finder=False):
myStats = MyStats()
mySeqNumber = 0
try:
destIP = socket.gethostbyname(hostname)
except socket.gaierror as e:
return 0,0,0,0
myStats.thisIP = destIP
... | Same as verbose_ping, but the results are returned as tuple |
338,405 | def canChiNgay(nn, tt, nnnn, duongLich=True, timeZone=7, thangNhuan=False):
if duongLich is False:
[nn, tt, nnnn] = L2S(nn, tt, nnnn, thangNhuan, timeZone)
jd = jdFromDate(nn, tt, nnnn)
canNgay = (jd + 9) % 10 + 1
chiNgay = (jd + 1) % 12 + 1
return [canNgay, chiNgay] | Summary
Args:
nn (int): ngày
tt (int): tháng
nnnn (int): năm
duongLich (bool, optional): True nếu là dương lịch, False âm lịch
timeZone (int, optional): Múi giờ
thangNhuan (bool, optional): Có phải là tháng nhuận không?
Returns:
TYPE: Description |
338,406 | def find_file(path, saltenv=, **kwargs):
if in kwargs:
kwargs.pop()
fnd = {: None,
: None}
metadata = _init()
if not metadata or saltenv not in metadata:
return fnd
env_files = _find_files(metadata[saltenv])
if not _is_env_per_bucket():
path ... | Look through the buckets cache file for a match.
If the field is found, it is retrieved from S3 only if its cached version
is missing, or if the MD5 does not match. |
338,407 | def year(self, value=None):
if value is None:
return self.day() / 365
else:
self.millisecond(self.day(value * 365)) | We do *NOT* know for what year we are converting so lets assume the
year has 365 days. |
338,408 | def _generate_paragraphs(package, subpackages):
for subpackage in _iter_subpackages(package, subpackages):
subpackage_name = subpackage.__name__
yield "
yield _doc(_import_module(subpackage_name))
for func in _iter_functions(subpackage):
yi... | Generate the paragraphs of the API documentation. |
338,409 | def sample_rows(total, data, replace=True, accounting_column=None,
max_iterations=50, prob_column=None, return_status=False):
if not data.index.is_unique:
raise ValueError()
if accounting_column is None:
if replace is False and total > len(data.index.values):
... | Samples and returns rows from a data frame while matching a desired control total. The total may
represent a simple row count or may attempt to match a sum/quantity from an accounting column.
Parameters
----------
total : int
The control total the sampled rows will attempt to match.
data: p... |
338,410 | def get_image(self, float_key="floats", to_chw=True):
tensors = callBigDlFunc(self.bigdl_type,
"localImageFrameToImageTensor", self.value, float_key, to_chw)
return map(lambda tensor: tensor.to_ndarray(), tensors) | get image list from ImageFrame |
338,411 | def verify(self, data, signature=None, keyrings=None, homedir=None):
if isinstance(data, six.text_type):
data = data.encode()
tmpdir = tempfile.mkdtemp()
data_file, data_path = tempfile.mkstemp(dir=tmpdir)
data_file = os.fdopen(data_file, )
data_file.write(... | `data` <string> the data to verify.
`signature` <string> The signature, if detached from the data.
`keyrings` <list of string> Additional keyrings to search in.
`homedir` <string> Override the configured homedir. |
338,412 | def add_choice(self, choice, name=, identifier=None):
if not isinstance(choice, DisplayText):
raise InvalidArgument()
if identifier is None:
identifier = str(ObjectId())
current_identifiers = [c[] for c in self.my_osid_object_form._my_map[]]
if identifier... | stub |
338,413 | def program(self, prog, offset = 0):
for addr, word in enumerate(prog):
self.program_word(offset + addr, word) | .. _program:
Write the content of the iterable ``prog`` starting with the optional offset ``offset``
to the device.
Invokes program_word_. |
338,414 | def if_then_else(cls,
condition: ,
true_case: ,
false_case: ) -> :
t have same shape.
'
true = TensorFluent.constant(True, tf.bool)
false = TensorFluent.constant(False, tf.bool)
ite = (condition == true) * true_case + (condition == false) * fal... | Returns a TensorFluent for the control op if-then-else.
Args:
condition: Boolean fluent for the if condition.
true_case: Fluent returned in the true clause.
false_case: Fluent returned in the false clause.
Returns:
A TensorFluent wrapping the if-then-els... |
338,415 | def hapmap3(data_set=):
try:
from pandas import read_pickle, DataFrame
from sys import stdout
import bz2
except ImportError as i:
raise i("Need pandas for hapmap dataset, make sure to install pandas (http://pandas.pydata.org/) before loading the hapmap dataset")
dir_pat... | The HapMap phase three SNP dataset - 1184 samples out of 11 populations.
SNP_matrix (A) encoding [see Paschou et all. 2007 (PCA-Correlated SNPs...)]:
Let (B1,B2) be the alphabetically sorted bases, which occur in the j-th SNP, then
/ 1, iff SNPij==(B1,B1)
Aij = | 0, iff SNPij==(B1,B2)
... |
338,416 | def update(self, entries = {}, *args, **kwargs):
if isinstance(entries, dict):
entries = self._reject_reserved_keys(entries)
for key, value in dict(entries, *args, **kwargs).items():
if isinstance(value, dict):
self.__dict__[key] = AttributeDict(value)
... | Update dictionary.
@example:
object.update({'foo': {'bar': 1}}) |
338,417 | def old_values(self):
def get_old_values_and_key(item):
values = item.old_values
values.update({self._key: item.past_dict[self._key]})
return values
return [get_old_values_and_key(el)
for el in self._get_recursive_difference()
... | Returns the old values from the diff |
338,418 | def present(name, filename, section, value, parameter=None):
if parameter is None:
parameter = name
ret = {: name,
: {},
: False,
: }
try:
old_value = __salt__[](filename=filename,
section=section,
... | Ensure a value is set in an OpenStack configuration file.
filename
The full path to the configuration file
section
The section in which the parameter will be set
parameter (optional)
The parameter to change. If the parameter is not supplied, the name will be used as the parameter... |
338,419 | def get(*args, **kwargs):
from invenio.modules.communities.models import FeaturedCommunity
q = FeaturedCommunity.query
return q.count(), q.all() | Get communities. |
338,420 | def is_member(self, rtc):
s
instance name. Component objects are more reliable.
Returns False if the given component is not a member of this
composition.
Raises NotCompositeError if this component is not a composition.
'
if not self.is_composite:
ra... | Is the given component a member of this composition?
rtc may be a Component object or a string containing a component's
instance name. Component objects are more reliable.
Returns False if the given component is not a member of this
composition.
Raises NotCompositeError if thi... |
338,421 | def search_next_results(self):
if not self.__next_max_id:
raise TwitterSearchException(1011)
self.send_search(
"%s&max_id=%i" % (self._start_url, self.__next_max_id)
)
return True | Triggers the search for more results using the Twitter API. \
Raises exception if no further results can be found. \
See `Advanced usage <advanced_usage.html>`_ for example
:returns: ``True`` if there are more results available \
within the Twitter Search API
:raises: TwitterSea... |
338,422 | def timetz(self):
"Return the time part, with same tzinfo."
return time(self.hour, self.minute, self.second, self.microsecond,
self._tzinfo) | Return the time part, with same tzinfo. |
338,423 | def init(library: typing.Union[str, types.ModuleType]) -> None:
if isinstance(library, types.ModuleType):
library = library.__name__
if library not in manager._handlers:
raise ValueError("Possible values are <{}>, not <{}>".format(manager._handlers.keys(),
... | Must be called at some point after import and before your event loop
is run.
Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.
The supported libraries at the moment are:
- curio
- trio
Args:
library (str or module): Either the m... |
338,424 | def _nested_convert_to_tensor(struct, dtype=None, name=None):
if dtype is not None or not tf.nest.is_nested(struct):
return tf.convert_to_tensor(struct, dtype=dtype)
if _maybe_convertible_to_tensor(struct):
try:
return tf.convert_to_tensor(value=struct, name=name)
except (ValueError, Ty... | Eagerly converts struct to Tensor, recursing upon failure. |
338,425 | def _new_java_obj(sc, java_class, *args):
java_obj = _jvm()
for name in java_class.split("."):
java_obj = getattr(java_obj, name)
java_args = [_py2java(sc, arg) for arg in args]
return java_obj(*java_args) | Construct a new Java object. |
338,426 | def get_gradebook_column_query_session(self, proxy):
if not self.supports_gradebook_column_query():
raise errors.Unimplemented()
return sessions.GradebookColumnQuerySession(proxy=proxy, runtime=self._runtime) | Gets the ``OsidSession`` associated with the gradebook column query service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookColumnQuerySession) - a
``GradebookColumnQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFai... |
338,427 | def DeleteInstance(self, context, ports):
resource_details = self._parse_remote_model(context)
res = self.command_wrapper.execute_command_with_connection(
context,
self.destroy_virtual_machine_command.DeleteInstance,
resource_details.vm_uuid,
... | Destroy Vm Command, will only destroy the vm and will not remove the resource
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! |
338,428 | def set_font(self, font):
self.setFont(font)
self.set_pythonshell_font(font)
cursor = self.textCursor()
cursor.select(QTextCursor.Document)
charformat = QTextCharFormat()
charformat.setFontFamily(font.family())
charformat.setFontPointSize(font.poi... | Set shell styles font |
338,429 | def load_pointings(self):
import os,re,ephem
import tkFileDialog,tkMessageBox
filename=tkFileDialog.askopenfilename()
if filename is None:
return
f=open(filename)
lines=f.readlines()
f.close()
points=[]
if lines[0][0:5]=="<?xml":
for i in range... | Load some pointings |
338,430 | def compress(self, condition, axis=0, out=None):
return compress_haplotype_array(self, condition, axis=axis, cls=type(self),
compress=np.compress, out=out) | Return selected slices of an array along given axis.
Parameters
----------
condition : array_like, bool
Array that selects which entries to return. N.B., if len(condition)
is less than the size of the given axis, then output is truncated to the length
of the ... |
338,431 | def command_long_send(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7, force_mavlink1=False):
return self.send(self.command_long_encode(target_system, target_component, command, confirmation, param1, param2, param3, pa... | Send a command with up to seven parameters to the MAV
target_system : System which should execute the command (uint8_t)
target_component : Component which should execute the command, 0 for all components (uint8_t)
command : Command ... |
338,432 | def colors_to_materials(colors, count=None):
rgba = to_rgba(colors)
if util.is_shape(rgba, (4,)) and count is not None:
diffuse = rgba.reshape((-1, 4))
index = np.zeros(count, dtype=np.int)
elif util.is_shape(rgba, (-1, 4)):
unique, index = grouping... | Convert a list of colors into a list of unique materials
and material indexes.
Parameters
-----------
colors : (n, 3) or (n, 4) float
RGB or RGBA colors
count : int
Number of entities to apply color to
Returns
-----------
diffuse : (m, 4) int
Colors
index : (count... |
338,433 | def set_ttl(self, ttl):
if self._client._session_timeout != ttl:
self._client._session_timeout = ttl
self._client.restart()
return True | It is not possible to change ttl (session_timeout) in zookeeper without
destroying old session and creating the new one. This method returns `!True`
if session_timeout has been changed (`restart()` has been called). |
338,434 | def _conv(self,v):
if isinstance(v,str):
return %v.replace(""%s""%s"' %self.db_module.Date(v.year,v.month,v.day)
else:
return v | Convert Python values to MySQL values |
338,435 | def from_dict(self, graph_dict):
self.reset_graph()
for new_node in six.iterkeys(graph_dict):
self.add_node(new_node)
for ind_node, dep_nodes in six.iteritems(graph_dict):
if not isinstance(dep_nodes, list):
raise TypeError()
for dep_... | Reset the graph and build it from the passed dictionary.
The dictionary takes the form of {node_name: [directed edges]} |
338,436 | def hash_tuple(val, encoding=, hash_key=None):
hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key)
for v in val)
h = _combine_hash_arrays(hashes, len(val))[0]
return h | Hash a single tuple efficiently
Parameters
----------
val : single tuple
encoding : string, default 'utf8'
hash_key : string key to encode, default to _default_hash_key
Returns
-------
hash |
338,437 | def request_headers(self):
headers = CIMultiDict()
for k in self.environ:
if k.startswith():
head = k[5:].replace(, )
headers[head] = self.environ[k]
for head in ENVIRON_HEADERS:
k = head.replace(, ).upper()
v = self.en... | Fill request headers from the environ dictionary and
modify them via the list of :attr:`headers_middleware`.
The returned headers will be sent to the target uri. |
338,438 | def set_dir(self, dir_):
self.__lock_set_dir(dir_)
self.__lock_auto_load()
self.__lock_update_table()
self.__update_info()
self.__update_window_title() | Sets directory, auto-loads, updates all GUI contents. |
338,439 | def fromdict(dict):
self = Proof()
self.mu = dict["mu"]
self.sigma = dict["sigma"]
return self | Takes a dictionary as an argument and returns a new Proof object
from the dictionary.
:param dict: the dictionary to convert |
338,440 | def add_handler(self, fn, handle=None, persist=True,
policy=None, respondent=None,
overwrite=False):
handle = handle or next(self._last_handle)
_vv and IOLOG.debug(, self, fn, handle, persist)
if handle in self._handle_map and not overwrite:
... | Invoke `fn(msg)` on the :class:`Broker` thread for each Message sent to
`handle` from this context. Unregister after one invocation if
`persist` is :data:`False`. If `handle` is :data:`None`, a new handle
is allocated and returned.
:param int handle:
If not :data:`None`, an ... |
338,441 | def asset_create_asset(self, *args, **kwargs):
if not self.cur_asset:
return
asset = self.create_asset(project=self.cur_asset.project, asset=self.cur_asset)
if not asset:
return
atypes = {}
for c in self.asset_asset_model.root.childItems:
... | Create a new asset
:returns: None
:rtype: None
:raises: None |
338,442 | def mute():
if system.get_name() == :
pass
elif system.get_name() == :
sp.Popen([, , ]).wait()
else:
if unix_is_pulseaudio_server():
sp.Popen([, , , , ,
, ]).wait()
else:
sp.Popen([, , , , ]).wait() | Mute the volume.
Mutes the volume. |
338,443 | def get(self, stat_name=None):
if stat_name is None:
return self._thresholds
if stat_name in self._thresholds:
return self._thresholds[stat_name]
else:
return {} | Return the threshold dict.
If stat_name is None, return the threshold for all plugins (dict of Threshold*)
Else return the Threshold* instance for the given plugin |
338,444 | def loads(self, s):
f = io.BytesIO(s)
return VaultUnpickler(self, f).load() | Deserializes a string representation of the object.
:param s: the string |
338,445 | def global_hook(handler):
if not hasattr(handler, "__call__"):
raise TypeError("trace hooks must be callable")
log.info("setting a new global hook callback")
state.global_hooks.append(weakref.ref(handler))
return handler | add a callback to run in every switch between coroutines
:param handler:
the callback function, must be a function taking 2 arguments:
- the greenlet being switched from
- the greenlet being switched to
be aware that only a weak reference to this function will be held.
:type h... |
338,446 | def bspline_to_nurbs(obj):
if isinstance(obj, BSpline.Curve):
return _convert.convert_curve(obj, NURBS)
elif isinstance(obj, BSpline.Surface):
return _convert.convert_surface(obj, NURBS)
elif isinstance(obj, BSpline.Volume):
return _convert.convert_volume(obj, NURBS)
el... | Converts non-rational parametric shapes to rational ones.
:param obj: B-Spline shape
:type obj: BSpline.Curve, BSpline.Surface or BSpline.Volume
:return: NURBS shape
:rtype: NURBS.Curve, NURBS.Surface or NURBS.Volume
:raises: TypeError |
338,447 | def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
data = data.asnumpy().transpose((0, 2, 3, 1))
datanp = np.clip(
(data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
x_dim = min(8, batch_size)
y_dim = int(math.ceil(float(batch_size... | save image |
338,448 | def _should_use_fr_error_handler(self):
adapter = current_app.create_url_adapter(request)
try:
adapter.match()
except MethodNotAllowed as e:
valid_route_method = e.valid_methods[0]
rule, _ = adapter.match(method=valid_route_method, retur... | Determine if error should be handled with FR or default Flask
The goal is to return Flask error handlers for non-FR-related routes,
and FR errors (with the correct media type) for FR endpoints. This
method currently handles 404 and 405 errors.
:return: bool |
338,449 | def get_all_connections(self, id, connection_name, **args):
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
re... | Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items. |
338,450 | def is_subset(reference_set
):
def is_subset_of(x):
missing = x - reference_set
if len(missing) == 0:
return True
else:
raise NotSubset(wrong_value=x, reference_set=reference_set, unsupported=missing)
is... | 'Is subset' validation_function generator.
Returns a validation_function to check that x is a subset of reference_set
:param reference_set: the reference set
:return: |
338,451 | def report_run():
build = g.build
release, run = _get_or_create_run(build)
db.session.refresh(run, lockmode=)
current_url = request.form.get(, type=str)
current_image = request.form.get(, type=str)
current_log = request.form.get(, type=str)
current_config = request.form.get(, type=str... | Reports data for a run for a release candidate. |
338,452 | def add_item(self, item, field_name=None):
field_name = self._choose_field_name(field_name)
related_manager = getattr(item, field_name)
related_manager.add(self) | Add the item to the specified section.
Intended for use with items of settings.ARMSTRONG_SECTION_ITEM_MODEL.
Behavior on other items is undefined. |
338,453 | def majority_value(data, class_attr):
if is_continuous(data[0][class_attr]):
return CDist(seq=[record[class_attr] for record in data])
else:
return most_frequent([record[class_attr] for record in data]) | Creates a list of all values in the target attribute for each record
in the data list object, and returns the value that appears in this list
the most frequently. |
338,454 | def __get_stack_id(self, value, values, height):
def step(values, height):
step_range = max(values) - min(values)
return (((step_range / float((len(self.__list) * height) - 1)))
or 1)
step_value = step(values, height)
return int(round((value... | Returns the index of the column representation of the given value
▁ ▂ ▃ ▄ ▅ ▆ ▇' ...
▁ ▂ ▃ ▄ ▅ ▆ ▇' ▇ ▇ ▇ ▇ ▇ ▇ ▇ ...
▁ ▂ ▃ ▄ ▅ ▆ ▇' ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ▇ ...
0 1 2 3 4 5 6 ... |
338,455 | def distribute_batches(self, indices):
assert len(indices) == self.num_samples
indices = indices.view(-1, self.batch_size)
indices = indices[self.rank::self.world_size].contiguous()
indices = indices.view(-1)
indices = indices.tolist()
assert len(indices) == se... | Assigns batches to workers.
Consecutive ranks are getting consecutive batches.
:param indices: torch.tensor with batch indices |
338,456 | def add(self, p_src):
todos = self.add_list([p_src])
return todos[0] if len(todos) else None | Given a todo string, parse it and put it to the end of the list. |
338,457 | def daemonize(enable_stdio_inheritance=False,
auto_close_fds=True,
keep_fds=None):
if os.fork():
os._exit(0)
os.setsid()
if os.fork():
os._exit(0)
os.umask(0o22)
if not enable_stdio_inheritance:
... | \
Standard daemonization of a process.
http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16 |
338,458 | def PopupGetFile(message, title=None, default_path=, default_extension=, save_as=False, file_types=(("ALL Files", "*"),),
no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None,
icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere... | Display popup with text entry field and browse button. Browse for file
:param message:
:param default_path:
:param default_extension:
:param save_as:
:param file_types:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon... |
338,459 | def redeem(ctx, htlc_id, secret, account):
print_tx(ctx.blockchain.htlc_redeem(htlc_id, secret, account=account)) | Redeem an HTLC contract |
338,460 | def run_hooks(self, name, event=None, context=None):
hooks = {
"pre:setup": lambda p: p.pre_setup(self),
"post:setup": lambda p: p.post_setup(self),
"pre:invoke": lambda p: p.pre_invoke(event, context),
"post:invoke": lambda p: p.post_invoke(event, contex... | Runs plugin hooks for each registered plugin. |
338,461 | def _make_result(self,
trans_input: TranslatorInput,
translation: Translation) -> TranslatorOutput:
target_ids = translation.target_ids
target_tokens = [self.vocab_target_inv[target_id] for target_id in target_ids]
target_string = C.TOKEN_SEPARA... | Returns a translator result from generated target-side word ids, attention matrices and scores.
Strips stop ids from translation string.
:param trans_input: Translator input.
:param translation: The translation + attention and score.
:return: TranslatorOutput. |
338,462 | def accept(self, request, uuid=None):
invitation = self.get_object()
if invitation.state != models.Invitation.State.PENDING:
raise ValidationError(_())
elif invitation.civil_number and invitation.civil_number != request.user.civil_number:
raise ValidationError(_... | Accept invitation for current user.
To replace user's email with email from invitation - add parameter
'replace_email' to request POST body. |
338,463 | def _related_field_data(field, obj):
data = _basic_field_data(field, obj)
relation_info = {
Field.REL_DB_TABLE: field.rel.to._meta.db_table,
Field.REL_APP: field.rel.to._meta.app_label,
Field.REL_MODEL: field.rel.to.__name__
}
data[Field.TYPE] = FieldType.REL
data[Field.... | Returns relation ``field`` as a dict.
Dict contains related pk info and some meta information
for reconstructing objects. |
338,464 | def deactivate_mfa_device(self, user_name, serial_number):
user = self.get_user(user_name)
if serial_number not in user.mfa_devices:
raise IAMNotFoundException(
"Device {0} not found".format(serial_number)
)
user.deactivate_mfa_device(serial_numb... | Deactivate and detach MFA Device from user if device exists. |
338,465 | def verify_abort(func, *args, **kwargs):
expected_exception = kwargs.pop("expected_exception", runez.system.AbortException)
with CaptureOutput() as logged:
try:
value = func(*args, **kwargs)
assert False, "%s did not raise, but returned %s" % (func, value)
except ex... | Convenient wrapper around functions that should exit or raise an exception
Example:
assert "Can't create folder" in verify_abort(ensure_folder, "/dev/null/not-there")
Args:
func (callable): Function to execute
*args: Args to pass to 'func'
**kwargs: Named args to pass to 'func'... |
338,466 | def step(self, observation, argmax_sampling=False):
policy_params, q = self(observation)
actions = self.action_head.sample(policy_params, argmax_sampling=argmax_sampling)
logprobs = self.action_head.logprob(actions, policy_params)
return {
: actions,
... | Select actions based on model's output |
338,467 | def update_shot_browser(self, project, releasetype):
if project is None:
self.shotbrws.set_model(None)
return
shotmodel = self.create_shot_model(project, releasetype)
self.shotbrws.set_model(shotmodel) | Update the shot browser to the given project
:param releasetype: the releasetype for the model
:type releasetype: :data:`djadapter.RELEASETYPES`
:param project: the project of the shots
:type project: :class:`djadapter.models.Project`
:returns: None
:rtype: None
... |
338,468 | def evaluate_course(self, kcdm, jxbh,
r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1,
r201=3, r202=3, advice=):
return self.query(EvaluateCourse(
kcdm, jxbh,
r101, r102, r103, r104, r105, r106, r107, r108, r... | 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r... |
338,469 | def load_cobra_model(path, notifications):
doc = libsbml.readSBML(path)
fbc = doc.getPlugin("fbc")
sbml_ver = doc.getLevel(), doc.getVersion(), fbc if fbc is None else \
fbc.getVersion()
with catch_warnings(record=True) as warnings:
simplefilter("always")
try:
mo... | Load a COBRA model with meta information from an SBML document. |
338,470 | def animate_phase_matrix(sync_output_dynamic, grid_width = None, grid_height = None, animation_velocity = 75, colormap = , save_movie = None):
figure = plt.figure();
def init_frame():
return frame_generation(0);
def frame_generation(index_... | !
@brief Shows animation of phase matrix between oscillators during simulation on 2D stage.
@details If grid_width or grid_height are not specified than phase matrix size will by calculated automatically by square root.
@param[in] sync_output_dynamic (sync_dynamic): Output dynamic o... |
338,471 | def workon(ctx, issue_id, new, base_branch):
lancet = ctx.obj
if not issue_id and not new:
raise click.UsageError("Provide either an issue ID or the --new flag.")
elif issue_id and new:
raise click.UsageError(
"Provide either an issue ID or the --new flag, but not both."
... | Start work on a given issue.
This command retrieves the issue from the issue tracker, creates and checks
out a new aptly-named branch, puts the issue in the configured active,
status, assigns it to you and starts a correctly linked Harvest timer.
If a branch with the same name as the one to be created... |
338,472 | def CopyToDateTimeString(self):
if self._timestamp is None:
return None
number_of_days, hours, minutes, seconds = self._GetTimeValues(
int(self._timestamp))
year, month, day_of_month = self._GetDateValuesWithEpoch(
number_of_days, self._EPOCH)
microseconds = int(
(s... | Copies the Cocoa timestamp to a date and time string.
Returns:
str: date and time value formatted as: YYYY-MM-DD hh:mm:ss.###### or
None if the timestamp cannot be copied to a date and time string. |
338,473 | def create_project(self,
project_name,
dataset_name,
hostname,
is_public,
s3backend=0,
kvserver=,
kvengine=,
mdengine=,
... | Creates a project with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Dataset name project is based on
hostname (str): Hostname
s3backend (str): S3 region to save the data in
is_public (int): 1 is public. 0 is no... |
338,474 | def post_parse(self):
if self.result:
out = []
for pu in self.result:
try:
out.append(pu.parse(self.scope))
except SyntaxError as e:
self.handle_error(e, 0)
self.result = list(utility.flatten(out... | Post parse cycle. nodejs version allows calls to mixins
not yet defined or known to the parser. We defer all calls
to mixins until after first cycle when all names are known. |
338,475 | def hdfs_path(ctx, path):
HADOOP_SCHEMES = [,
,
,
,
,
,
,
,
,
]
if (any(path.startswith(scheme) for scheme in HADOOP_SCHEMES)):
... | Convenience function to create a Tensorflow-compatible absolute HDFS path from relative paths
Args:
:ctx: TFNodeContext containing the metadata specific to this node in the cluster.
:path: path to convert
Returns:
An absolute path prefixed with the correct filesystem scheme. |
338,476 | def listen(self, callback=None):
self._running = True
self.loop.create_task(self._async_listen(callback)) | Start the &listen long poll and return immediately. |
338,477 | def create(self):
self.service.create()
predix.config.set_env_value(self.use_class, , self._get_uri())
predix.config.set_env_value(self.use_class, ,
self._get_zone_id()) | Create an instance of the Access Control Service with the typical
starting settings. |
338,478 | def where_cross(data,threshold):
Is=np.where(data>threshold)[0]
Is=np.concatenate(([0],Is))
Ds=Is[:-1]-Is[1:]+1
return Is[np.where(Ds)[0]+1] | return a list of Is where the data first crosses above threshold. |
338,479 | def stream(self, entity, callback):
with self._lock:
self._stream(entity, callback) | Stream out all eligible children of the input entity.
:param entity: The target entity to be streamed.
:param callback: The function that takes the node and
actually send it out. |
338,480 | def create_networks(self, ids, id_vlan):
network_map = dict()
network_map[] = ids
network_map[] = id_vlan
code, xml = self.submit(
{: network_map}, , )
return self.response(code, xml) | Set column 'active = 1' in tables redeipv4 and redeipv6]
:param ids: ID for NetworkIPv4 and/or NetworkIPv6
:return: Nothing |
338,481 | def partition_master(incoming=True, outgoing=True):
echo(.format(incoming, outgoing))
network.save_iptables(shakedown.master_ip())
network.flush_all_rules(shakedown.master_ip())
network.allow_all_traffic(shakedown.master_ip())
if incoming and outgoing:
network.run_iptables(shakedown.... | Partition master's port alone. To keep DC/OS cluster running.
:param incoming: Partition incoming traffic to master process. Default True.
:param outgoing: Partition outgoing traffic from master process. Default True. |
338,482 | def is_masked(self, column):
column = _ensure_string_from_expression(column)
if column in self.columns:
return np.ma.isMaskedArray(self.columns[column])
return False | Return if a column is a masked (numpy.ma) column. |
338,483 | def get(self, reg, ty):
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
if offset == self.irsb_c.irsb.arch.ip_offset:
return self.constant(self.addr, ty)
rdt = self.irsb_c.rdreg(offset, ty)
return VexValue(self.irsb_c, rdt) | Load a value from a machine register into a VEX temporary register.
All values must be loaded out of registers before they can be used with operations, etc
and stored back into them when the instruction is over. See Put().
:param reg: Register number as an integer, or register string name
... |
338,484 | def writeDword(self, dword):
self.data.write(pack(self.endianness + ("L" if not self.signed else "l"), dword)) | Writes a dword value into the L{WriteData} stream object.
@type dword: int
@param dword: Dword value to write into the stream. |
338,485 | def open(self, serial_no=None, ip_addr=None):
func = enums.JLinkFunctions.UNSECURE_HOOK_PROTOTYPE(unsecure_hook)
self._dll.JLINK_SetHookUnsecureDialog(func)
return None | Connects to the J-Link emulator (defaults to USB).
If ``serial_no`` and ``ip_addr`` are both given, this function will
connect to the J-Link over TCP/IP.
Args:
self (JLink): the ``JLink`` instance
serial_no (int): serial number of the J-Link
ip_addr (str): IP addr... |
338,486 | def Read(self):
encoded_string = self._file_object.readline()
if isinstance(encoded_string, py2to3.UNICODE_TYPE):
return encoded_string
try:
string = codecs.decode(encoded_string, self._encoding, self._errors)
except UnicodeDecodeError:
if self._errors == :
logger.error(... | Reads a string from the input.
Returns:
str: input. |
338,487 | def makeCoreValuesSubqueryCondition(engine, column, values: List[Union[int, str]]):
if isPostGreSQLDialect(engine):
return column.in_(values)
if not isMssqlDialect(engine):
raise NotImplementedError()
sql = _createMssqlSqlText(values)
return column.in_(sql) | Make Core Values Subquery
:param engine: The database engine, used to determine the dialect
:param column: The column, eg TableItem.__table__.c.colName
:param values: A list of string or int values |
338,488 | def parse_argv(tokens, options, options_first=False):
parsed = []
while tokens.current() is not None:
if tokens.current() == :
return parsed + [Argument(None, v) for v in tokens]
elif tokens.current().startswith():
parsed += parse_long(tokens, options)
elif t... | Parse command-line argument vector.
If options_first:
argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else:
argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; |
338,489 | def viewbox_mouse_event(self, event):
if event.handled or not self.interactive:
return
BaseCamera.viewbox_mouse_event(self, event)
if event.type == :
center = self._scene_transform.imap(event.pos)
self.zoom((1 + self.zoom_factor) ** (-event... | The SubScene received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event. |
338,490 | def add_list_members(self, screen_name=None, user_id=None, slug=None,
list_id=None, owner_id=None, owner_screen_name=None):
return self._add_list_members(list_to_csv(screen_name),
list_to_csv(user_id),
... | Perform bulk add of list members from user ID or screenname |
338,491 | def compute_ranges(self, obj, key, ranges):
all_table = all(isinstance(el, Table) for el in obj.traverse(lambda x: x, [Element]))
if obj is None or not self.normalize or all_table:
return OrderedDict()
ranges = self.ranges if ranges is None else dict(ranges)
... | Given an object, a specific key, and the normalization options,
this method will find the specified normalization options on
the appropriate OptionTree, group the elements according to
the selected normalization option (i.e. either per frame or
over the whole animation) and finally compu... |
338,492 | async def terminal(self, device):
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not opening terminal {0}: not mounted", device))
return False
if not self._terminal:
self._log.error(_("not opening terminal {0}: no prog... | Launch terminal on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched. |
338,493 | def createInstance(self, codec=None):
if type(self.klass) is type:
return self.klass.__new__(self.klass)
return self.klass() | Creates an instance of the klass.
@return: Instance of C{self.klass}. |
338,494 | def store_mo(self, state, new_mo, overwrite=True):
start, end = self._resolve_range(new_mo)
if overwrite:
self.store_overwrite(state, new_mo, start, end)
else:
self.store_underwrite(state, new_mo, start, end) | Stores a memory object.
:param new_mo: the memory object
:param overwrite: whether to overwrite objects already in memory (if false, just fill in the holes) |
338,495 | def smoothWSinc(self, niter=15, passBand=0.1, edgeAngle=15, featureAngle=60):
poly = self.poly
cl = vtk.vtkCleanPolyData()
cl.SetInputData(poly)
cl.Update()
smoothFilter = vtk.vtkWindowedSincPolyDataFilter()
smoothFilter.SetInputData(cl.GetOutput())
smoot... | Adjust mesh point positions using the `Windowed Sinc` function interpolation kernel.
:param int niter: number of iterations.
:param float passBand: set the passband value for the windowed sinc filter.
:param float edgeAngle: edge angle to control smoothing along edges (either interior or bounda... |
338,496 | def update_case_task(self, task):
req = self.url + "/api/case/task/{}".format(task.id)
update_keys = [
, , , , , , ,
]
data = {k: v for k, v in task.__dict__.items() if k in update_keys}
try:
return requests.patch(req, headers={: }, j... | :Updates TheHive Task
:param case: The task to update. The task's `id` determines which Task to update.
:return: |
338,497 | def _get_function(self, name: str):
f = mapped.get(name)
if f is None:
raise MissingPipelineFunctionError(.format(name))
if name in universe_map and name in in_place_map:
return self._wrap_in_place(self._wrap_universe(f))
if name in universe_map:
... | Wrap a function with the universe and in-place.
:param name: The name of the function
:rtype: types.FunctionType
:raises MissingPipelineFunctionError: If the functions is not registered |
338,498 | def skill_show(self, skill_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/skills
api_path = "/api/v2/skills/{skill_id}"
api_path = api_path.format(skill_id=skill_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/skills#get-skill-by-id |
338,499 | def add_http_basic_auth(url,
user=None,
password=None,
https_only=False):
if user is None and password is None:
return url
else:
urltuple = urlparse(url)
if https_only and urltuple.scheme != :
raise ... | Return a string with http basic auth incorporated into it |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.