Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,600 | def resize(self, targ_sz, new_path=, resume=True, fn=None):
new_ds = []
dls = [self.trn_dl,self.val_dl,self.fix_dl,self.aug_dl]
if self.test_dl: dls += [self.test_dl, self.test_aug_dl]
else: dls += [None,None]
t = tqdm_notebook(dls)
for dl in t: new_ds.append(sel... | Resizes all the images in the train, valid, test folders to a given size.
Arguments:
targ_sz (int): the target size
new_path (str): the path to save the resized images (default tmp)
resume (bool): if True, check for images in the DataSet that haven't been resized yet (useful if a previo... |
346,601 | def observe_property(self, name, handler):
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode(), MpvFormat.NODE) | Register an observer on the named property. An observer is a function that is called with the new property
value every time the property's value is changed. The basic function signature is ``fun(property_name,
new_value)`` with new_value being the decoded property value as a python object. This function... |
346,602 | def get_body_encoding(self):
assert self.body_encoding != SHORTEST
if self.body_encoding == QP:
return
elif self.body_encoding == BASE64:
return
else:
return encode_7or8bit | Return the content-transfer-encoding used for body encoding.
This is either the string `quoted-printable' or `base64' depending on
the encoding used, or it is a function in which case you should call
the function with a single argument, the Message object being
encoded. The function sh... |
346,603 | def parse_reply(self, data):
if isinstance(data, bytes):
data = data.decode()
try:
rep = json.loads(data)
except Exception as e:
raise InvalidReplyError(e)
for k in rep.keys():
if not k in self._ALLOWED_REPLY_KEYS:
... | Deserializes and validates a response.
Called by the client to reconstruct the serialized :py:class:`JSONRPCResponse`.
:param bytes data: The data stream received by the transport layer containing the
serialized request.
:return: A reconstructed response.
:rtype: :py:class:... |
346,604 | def get_stp_mst_detail_output_cist_port_if_role(self, **kwargs):
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
... | Auto Generated Code |
346,605 | def is_partial(self, filename):
return any((x.startswith("_") for x in filename.split(os.path.sep))) | Check if a file is a partial.
Partial files are not rendered, but they are used in rendering
templates.
A file is considered a partial if it or any of its parent directories
are prefixed with an ``'_'``.
:param filename: the name of the file to check |
346,606 | def normals(self, cells=False):
if cells:
vtknormals = self.polydata(True).GetCellData().GetNormals()
else:
vtknormals = self.polydata(True).GetPointData().GetNormals()
return vtk_to_numpy(vtknormals) | Retrieve vertex normals as a numpy array.
:params bool cells: if `True` return cell normals. |
346,607 | def get_an_int(errmsg, arg, msg_on_error, min_value=None, max_value=None):
ret_value = None
if arg:
try:
ret_value = int(eval(arg))
except (SyntaxError, NameError, ValueError):
if errmsg:
errmsg(msg_on_error)
else... | Another get_int() routine, this one simpler and less stylized
than get_int(). We eval arg return it as an integer value or
None if there was an error in parsing this. |
346,608 | def translate_in_frame_mutation(
transcript,
ref_codon_start_offset,
ref_codon_end_offset,
mutant_codons):
mutant_stop_codon_index = find_first_stop_codon(mutant_codons)
using_three_prime_utr = False
if mutant_stop_codon_index != -1:
mutant_codons = mutant_codo... | Returns:
- mutant amino acid sequence
- offset of first stop codon in the mutant sequence (or -1 if there was none)
- boolean flag indicating whether any codons from the 3' UTR were used
Parameters
----------
transcript : pyensembl.Transcript
Reference transcript to which a ... |
346,609 | async def send_rpc_message(self, message, context):
conn_string = message.get()
rpc_id = message.get()
address = message.get()
timeout = message.get()
payload = message.get()
client_id = context.user_data
self._logger.debug("Calling RPC %d:0x%04X with p... | Handle a send_rpc message.
See :meth:`AbstractDeviceAdapter.send_rpc`. |
346,610 | def load_mode(node):
obs_mode = ObservingMode()
obs_mode.__dict__.update(node)
load_mode_validator(obs_mode, node)
load_mode_builder(obs_mode, node)
load_mode_tagger(obs_mode, node)
return obs_mode | Load one observing mdode |
346,611 | def fetchSpCells(self, nodes, numSyn):
SpCell = []
for size in numSyn:
SpCell.append(np.random.randint(nodes.min(), nodes.max(),
size=size).astype())
return SpCell | For N (nodes count) nestSim-cells draw
POPULATION_SIZE x NTIMES random cell indexes in
the population in nodes and broadcast these as `SpCell`.
The returned argument is a list with len = numSyn.size of np.arrays,
assumes `numSyn` is a list
Parameters
----------
... |
346,612 | async def execute_command(self, command):
self.apply_future = asyncio.Future(loop=self.loop)
entry = self.log.write(self.storage.term, command)
asyncio.ensure_future(self.append_entries(), loop=self.loop)
await self.apply_future | Write to log & send AppendEntries RPC |
346,613 | def find(self):
editorstack = self.get_current_editorstack()
editorstack.find_widget.show()
editorstack.find_widget.search_text.setFocus() | Find slot |
346,614 | def set(self, name, value):
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
self._properties[name] = value | Set a device model property.
Args:
name (str): The name of the property to set
value (int, bool): The value of the property to set |
346,615 | def get_compositions(self):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(self._view_filter()).sort(, DESCENDING)
return objects... | Gets all ``Compositions``.
return: (osid.repository.CompositionList) - a list of
``Compositions``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* |
346,616 | def validate_accept(form, field):
if field.data and form.reject.data:
raise validators.ValidationError(
_("Both reject and accept cannot be set at the same time.")
) | Validate that accept have not been set. |
346,617 | def flushIndexes(self) :
"drops all indexes created by Raba"
for n in self.getIndexes(rabaOnly = True) :
self.dropIndexByName(n[1]) | drops all indexes created by Raba |
346,618 | def filter_only_significant(word):
if not word:
return word
if word.startswith(u) and word.endswith(u):
return filter_only_significant(word[1:-1])
x = len(word)
while x > 0:
x -= 1
c = word[x]
if c == u:
m = INSIGNIFICANT_PARENTHESIS... | Gets a word which removes insignificant letters at the end of the given
word::
>>> pick_significant(u'넥슨(코리아)')
넥슨
>>> pick_significant(u'메이플스토리...')
메이플스토리 |
346,619 | def Acf(poly, dist, N=None, **kws):
if N is None:
N = len(poly)/2 + 1
corr = Corr(poly, dist, **kws)
out = numpy.empty(N)
for n in range(N):
out[n] = numpy.mean(corr.diagonal(n), 0)
return out | Auto-correlation function.
Args:
poly (Poly):
Polynomial of interest. Must have ``len(poly) > N``.
dist (Dist):
Defines the space the correlation is taken on.
N (int):
The number of time steps appart included. If omited set to
``len(poly)/2+1`... |
346,620 | def process_file(self, data, name):
try:
return self.process_file_autodetect(data, name)
except Exception as e:
logger.debug( % (name, e))
self.trace_logger.log(e)
ret = []
logger.debug( % name)
ret.append(self.process_pem(d... | Processes a single file
:param data:
:param name:
:return: |
346,621 | def generate_cert(domain):
*
result = __salt__[](["icinga2", "pki", "new-cert", "--cn", domain, "--key", "{0}{1}.key".format(get_certs_path(), domain), "--cert", "{0}{1}.crt".format(get_certs_path(), domain)], python_shell=False)
return result | Generate an icinga2 client certificate and key.
Returns::
icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt
CLI Example:
.. code-block:: bash
salt '*' icinga2.generate_cert domain.tld |
346,622 | def load_data(filename):
file_root, file_ext = os.path.splitext(filename)
data = None
if file_ext.lower() in COLOR_IMAGE_EXTS:
data = cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB)
elif file_ext == :
data = np.load(filename)
elif file_ext =... | Loads a data matrix from a given file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
Returns
-------
:obj:`numpy.ndarray`
The data array read from the file. |
346,623 | def char_repl(x):
r = ""
for c in x:
if ord(c) > 255:
r += "?"
else:
r += c
return r | A little embarrassing: couldn't figure out how to avoid crashes when
hardcore unicode occurs in description fields ... |
346,624 | def imagesc(data, title=None, fig=, ax=None):
ax = _get_axis(fig, ax, False)
ax.imshow(data, interpolation=, aspect=)
if title:
ax.set_title(title)
return plt.show | Simple alias for a Matlab-like imshow function. |
346,625 | def show_shortcuts(self):
gui_name = self.gui.name
actions_name = self.name
name = (.format(gui_name, actions_name)
if actions_name else gui_name)
_show_shortcuts(self.shortcuts, name) | Print all shortcuts. |
346,626 | def sort_topologically(graph):
levels_by_name = {}
names_by_level = defaultdict(list)
def add_level_to_name(name, level):
levels_by_name[name] = level
names_by_level[level].append(name)
def walk_depth_first(name):
stack = [name]
while(stack):
name = st... | Stackless topological sorting.
graph = {
3: [1],
5: [3],
4: [2],
6: [4],
}
sort_topologically(graph)
[[1, 2], [3, 4], [5, 6]] |
346,627 | def free_param_names(self):
return scipy.concatenate((self.k1.free_param_names, self.k2.free_param_names)) | Returns the names of the free hyperparameters.
Returns
-------
free_param_names : :py:class:`Array`
Array of the names of the free parameters, in order. |
346,628 | def _restore_file(path, delete_backup=True):
backup_base =
backup_path = .join([backup_base,path])
if exists(backup_path):
if delete_backup:
sudo(% (backup_path,path))
else:
sudo(% (backup_path,path)) | Restore a file if it exists and remove the backup |
346,629 | def wait(self, readfds, writefds, timeout):
logger.info("WAIT:")
logger.info("\tProcess %d is going to wait for [ %r %r %r ]", self._current, readfds, writefds, timeout)
logger.info("\tProcess: %r", self.procs)
logger.info("\tRunning: %r", self.running)
logger.info("\tRW... | Wait for filedescriptors or timeout.
Adds the current process to the corresponding waiting list and
yields the cpu to another running process. |
346,630 | def append_stream(self, streamid, stream, encoding=None):
if encoding is None:
readlines = stream.readlines
else:
readlines = decoding_stream(stream, encoding).readlines
try:
self.linesets.append(
LineSet(
streamid,... | append a file to search for similarities |
346,631 | def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id):
param_map = {
: did_to_id(did),
: price,
: Keeper.get_instance().escrow_reward_condition.address,
}
sla_template_path = get_sla_template_path()
... | Build the access service.
:param did: DID, str
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement exp... |
346,632 | def from_model(cls, model, *fields, **named_fields):
d = ModelDict()
if not (fields or named_fields):
fields = [f.attname for f in model._meta.concrete_fields]
not_found = object()
for name, field in chain(zip(fields, fields), named_fields.items()):
... | Work-in-progress constructor,
consuming fields and values from django model instance. |
346,633 | def index(request):
warnings.warn(
"icekit_events.views.index is deprecated and will disappear in a "
"future version. If you need this code, copy it into your project."
, DeprecationWarning
)
occurrences = models.Occurrence.objects.visible()
context = {
: occurrenc... | Listing page for event `Occurrence`s.
:param request: Django request object.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
template such as turning off tracking options or adding
... |
346,634 | def compar(self, x, y):
indX=0
indY=0
a= int(x[0].split()[1])
b= int(y[0].split()[1])
if a>b:
return 1
if a==b:
return 0
if a<b:
return -1 | simple comparator method |
346,635 | def write(self,fileName):
f = open(fileName, )
f.write( % (self.polarisText,
Synset.linebreak)
)
f.close() | Appends synset to Polaris IO file <fileName> |
346,636 | def sendVY(self, vy):
self.lock.acquire()
self.data.vy = vy
self.lock.release() | Sends VY velocity.
@param vy: VY velocity
@type vy: float |
346,637 | def form_invalid(self, form):
LOGGER.debug("Invalid Email Form Submitted")
messages.add_message(self.request, messages.ERROR, _("Invalid Email Address."))
return super(EmailTermsView, self).form_invalid(form) | Override of CreateView method, logs invalid email form submissions. |
346,638 | def load_db_set(self, name, r=None):
r = r or self
db_set = r.genv.db_sets.get(name, {})
r.genv.update(db_set) | Loads database parameters from a specific named set. |
346,639 | def time_to_next_heartbeat(self):
time_since_last_heartbeat = time.time() - max(self.last_send, self.last_reset)
if self.heartbeat_failed:
delay_to_next_heartbeat = self.config[] / 1000
else:
delay_to_next_heartbeat = self.config[] / 1000
return max(0, de... | Returns seconds (float) remaining before next heartbeat should be sent |
346,640 | def treeWithAppliedTxns(self, txns: List, currentTree=None):
currentTree = currentTree or self.tree
tempTree = copy(currentTree)
for txn in txns:
s = self.serialize_for_tree(txn)
tempTree.append(s)
return tempTree | Return a copy of merkle tree after applying the txns
:param txns:
:return: |
346,641 | def doi_to_wos(wosclient, doi):
results = query(wosclient, % doi, , count=1)
return results[0].lstrip() if results else None | Convert DOI to WOS identifier. |
346,642 | def validate_packet(self, data):
expected_length = data[0] + 1
if len(data) != expected_length:
raise InvalidPacketLength(
"Expected packet length to be %s bytes but it was %s bytes"
% (expected_length, len(data))
... | Validate a packet against this packet handler and determine if it
meets the requirements. This is done by checking the following
conditions are true.
- The length of the packet is equal to the first byte.
- The second byte is in the set of defined PACKET_TYPES for this class.
- ... |
346,643 | def _call_vecfield_1(self, vf, out):
vf[0].ufuncs.absolute(out=out)
if self.is_weighted:
out *= self.weights[0]
if len(self.domain) == 1:
return
tmp = self.range.element()
for fi, wi in zip(vf[1:], self.weights[1:]):
fi.ufuncs.absolu... | Implement ``self(vf, out)`` for exponent 1. |
346,644 | def trace_grid_stack_to_next_plane(self):
def minus(grid, deflections):
return grid - deflections
return self.grid_stack.map_function(minus, self.deflection_stack) | Trace this plane's grid_stacks to the next plane, using its deflection angles. |
346,645 | def decorate_disabled(self):
if len(self._tags) == 0:
return False
if self._env_var not in os.environ:
return True
env_tags = os.environ[self._env_var].split(self.__class__.__tags_delimiter__)
if in env_tags:
return False
for tag in self._tags:
if tag in env_tags:
return False
return ... | Return True if this decoration must be omitted, otherwise - False.
This class searches for tags values in environment variable
(:attr:`.Verifier.__environment_var__`), Derived class can implement any logic
:return: bool |
346,646 | def mean(self, *args, **kwargs):
nv.validate_groupby_func(, args, kwargs, [])
try:
return self._cython_agg_general(, **kwargs)
except GroupByError:
raise
except Exception:
with _group_selection_context(self):
f = lambda x: x.... | Compute mean of groups, excluding missing values.
Returns
-------
pandas.Series or pandas.DataFrame
%(see_also)s
Examples
--------
>>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
... 'B': [np.nan, 2, 3, 4, 5],
... ... |
346,647 | def is_corrupted(l, sym, input_v):
input_v = l._versions.find_one({: sym, : input_v}) if isinstance(input_v, int) else input_v
if not _fast_check_corruption(l._collection, sym, input_v,
check_count=True, check_last_segment=True, check_append_safe=False):
try:
... | This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
The VersionStore instance against which ... |
346,648 | def parse_xml_layers(xml_layers):
layers = []
for custom_map_source in xml_layers.getchildren():
layers.append(MapSource.parse_xml_layer(custom_map_source))
return layers | Get the MapLayers from an XML element
Args:
xml_layers (Element): The <layers> tag as XML Element
Returns:
list of MapLayer: |
346,649 | def map(self, func, axis=(0,)):
axes = sorted(tupleize(axis))
key_shape = [self.shape[axis] for axis in axes]
reshaped = self._align(axes, key_shape=key_shape)
mapped = asarray(list(map(func, reshaped)))
elem_shape = mapped[0].shape
linearized_shape_in... | Apply a function across an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may require a transpose/reshape.
Parameters
----------
func : function
Function of a single array to apply
axis : tuple or int, optional, default=(... |
346,650 | def removeFunction(self):
root = self.etree
t_execute = root.find()
try:
root.remove(t_execute)
return True
except (Exception,) as e:
print(e)
return False | Remove function tag |
346,651 | def grad_global_norm(parameters, max_norm):
arrays = []
idx = 0
for p in parameters:
if p.grad_req != :
p_grads = p.list_grad()
arrays.append(p_grads[idx % len(p_grads)])
idx += 1
assert len(arrays) > 0,
def _norm(array):
... | Calculate the 2-norm of gradients of parameters, and how much they should be scaled down
such that their 2-norm does not exceed `max_norm`.
If gradients exist for more than one context for a parameter, user needs to explicitly call
``trainer.allreduce_grads`` so that the gradients are summed first before c... |
346,652 | def iterator_mix(*iterators):
while True:
one_left = False
for it in iterators:
try:
yield it.next()
except StopIteration:
pass
else:
one_left = True
if not one_left:
break | Iterating over list of iterators.
Bit like zip, but zip stops after the
shortest iterator is empty, abd here
we go one until all iterators are empty. |
346,653 | def isVisible(self):
if self._visible and self._inheritVisibility and self._parent:
return self._parent.isVisible()
return self._visible | Returns whether or not this layer is visible. If the inheritVisibility
value is set to True, then this will look up its parent hierarchy to \
ensure it is visible.
:return <bool> |
346,654 | def unregister_hook(self, func):
if func in self.hooks:
self.hooks.remove(func) | Unregisters a hook. For further explanation, please have a look at ``register_hook``. |
346,655 | def conv_to_float(indata, inf_str=):
if indata.strip() == inf_str:
outdata = float()
else:
try:
outdata = float(indata)
except:
raise ValueError(.format(indata))
return outdata | Try to convert an arbitrary string to a float. Specify what will be replaced with "Inf".
Args:
indata (str): String which contains a float
inf_str (str): If string contains something other than a float, and you want to replace it with float("Inf"),
specify that string here.
Re... |
346,656 | def fmt_content(text, width = 0, align = , padding = None, padding_left = None, padding_right = None, padding_char = ):
if padding_left is None:
padding_left = padding
if padding_right is None:
padding_right = padding
if padding_left is not None:
text... | Pad given text with given padding characters, inflate it to given width
and perform horizontal aligning. |
346,657 | def write_table(self):
with self._logger:
self._verify_property()
self._preprocess()
for values in self._table_value_matrix:
self._write_line(json.dumps(values)) | |write_table| with
`Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__
/NDJSON/JSON Lines format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-jsonl-writer` |
346,658 | async def list_keys(request: web.Request) -> web.Response:
keys_dir = CONFIG[]
keys: List[Dict[str, str]] = []
for path in os.listdir(keys_dir):
full_path = os.path.join(keys_dir, path)
if os.path.isdir(full_path):
in_path = os.listdir(full_path)
if len(in_p... | List the key files installed in the system.
This responds with a list of the same objects as key:
```
GET /wifi/keys -> 200 OK
{ keys: [
{
uri: '/wifi/keys/some-hex-digest',
id: 'some-hex-digest',
name: 'keyfile.pem'
},
...
]
}
``... |
346,659 | def _convert_unit(unit):
if unit is None:
return
prefix = None
suffix = None
if unit[:5].lower() == :
prefix =
unit = unit[5:]
elif unit[:5].lower() == :
prefix = mu
unit = unit[5:]
elif unit[:2].lower() == :
prefix = mu
unit = unit... | Convert different names into SI units.
Parameters
----------
unit : str
unit to convert to SI
Returns
-------
str
unit in SI format.
Notes
-----
SI unit such as mV (milliVolt, mVolt), μV (microVolt, muV). |
346,660 | def clear_silence(self, kwargs):
self._request(, , data=json.dumps(kwargs))
return True | Clear a silence entry. |
346,661 | def get_safe_type(self):
product_type = self.product_id.split()[1]
if product_type.startswith():
return EsaSafeType.COMPACT_TYPE
if product_type in [, ]:
return EsaSafeType.OLD_TYPE
raise ValueError(.format(self.product_id)) | Determines the type of ESA product.
In 2016 ESA changed structure and naming of data. Therefore the class must
distinguish between old product type and compact (new) product type.
:return: type of ESA product
:rtype: constants.EsaSafeType
:raises: ValueError |
346,662 | def date_to_long_form_string(dt, locale_ = ):
if locale_:
old_locale = locale.getlocale()
locale.setlocale(locale.LC_ALL, locale_)
v = dt.strftime("%A %B %d %Y")
if locale_:
locale.setlocale(locale.LC_ALL, old_locale)
return v | dt should be a datetime.date object. |
346,663 | def generate_clinamen(self, input_word, list_of_dict_words, swerve):
results = []
selected_list = []
for i in list_of_dict_words:
if len(i) < len(input_word)+1 and len(i) > len(input_word)/2:
if not in i:
selected_list.append(i)
... | Generate a clinamen. Here we
looks for words via the damerau levenshtein distance
with a distance of 2. |
346,664 | def _is_interactive(self):
return not (
self.realworld and (dt.date.today() > self.datetime.date())) | Prevent middlewares and orders to work outside live mode |
346,665 | def _IsPresent(item):
if item[0].label == _FieldDescriptor.LABEL_REPEATED:
return bool(item[1])
elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
return item[1]._is_present_in_parent
else:
return True | Given a (FieldDescriptor, value) tuple from _fields, return true if the
value should be included in the list returned by ListFields(). |
346,666 | def getWeb(url, isFeed):
socket.setdefaulttimeout(300)
loadedWeb = urllib2.build_opener()
loadedWeb.addheaders = getHeaders()
if isFeed:
web = etree.parse(loadedWeb.open(url))
else:
web = html.parse(loadedWeb.open(url))
return web | Download url and parse it with lxml.
If "isFeed" is True returns lxml.etree
else, returns lxml.html |
346,667 | def to_internal_value(self, data):
if "session_event" in data:
data["helper_metadata"]["session_event"] = data["session_event"]
return super(InboundSerializer, self).to_internal_value(data) | Adds extra data to the helper_metadata field. |
346,668 | def get_ancestor_level(self, current_item, depth=1):
if current_item.parent is None:
return current_item
if depth <= 1:
return current_item.parent
return self.get_ancestor_level(current_item.parent, depth=depth-1) | Returns ancestor of level `deep` recursively
:param TreeItemBase current_item:
:param int depth:
:rtype: TreeItemBase |
346,669 | def standard_suggestions(self):
suggestions = BulletedList()
suggestions.add(
)
suggestions.add(
)
suggestions.add(
)
... | Standard generic suggestions.
:return: List of standard suggestions for users who encounter errors.
:rtype: BulletedList |
346,670 | def add_root_vault(self, vault_id):
if self._catalog_session is not None:
return self._catalog_session.add_root_catalog(catalog_id=vault_id)
return self._hierarchy_session.add_root(id_=vault_id) | Adds a root vault.
arg: vault_id (osid.id.Id): the ``Id`` of a vault
raise: AlreadyExists - ``vault_id`` is already in hierarchy
raise: NotFound - ``vault_id`` not found
raise: NullArgument - ``vault_id`` is ``null``
raise: OperationFailed - unable to complete request
... |
346,671 | def startup(self):
log.info("Immediate delivery manager starting.")
log.debug("Initializing transport queue.")
self.transport.startup()
log.info("Immediate delivery manager started.") | Perform startup actions.
This just chains down to the transport layer. |
346,672 | def syntax_check(domain):
if domain and isinstance(domain, str):
load_config(True)
return Check(domain).is_domain_valid()
return None | Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`. |
346,673 | def transform_flask_bare_import(node):
new_names = []
for (name, as_name) in node.names:
match = re.match(r, name)
from_name = match.group(1)
actual_module_name = .format(from_name)
new_names.append((actual_module_name, as_name))
new_node = nodes.Import()
copy_node... | Translates a flask.ext.wtf bare import into a non-magical import.
Translates:
import flask.ext.admin as admin
Into:
import flask_admin as admin |
346,674 | def register_user(self, user):
self.users[user.index] = {: set()}
self.n_user += 1 | For new users, append their information into the dictionaries.
Args:
user (User): User. |
346,675 | def parse_isodate(datestr):
m = isodate_rx.search(datestr)
assert m, + datestr
year, month, day = m.group(, , )
hour, minute, second, fraction = m.group(, , , )
tz, tzhh, tzmm = m.group(, , )
dt = datetime.datetime(int(year), int(month), int(day), int(hour))
if fraction is None:
... | Parse a string that loosely fits ISO 8601 formatted date-time string |
346,676 | def _compute_remote_size(self, options):
size = self.local_path.size
if (self._ase.mode == blobxfer.models.azure.StorageModes.Page and
self.local_path.use_stdin):
if options.stdin_as_page_blob_size == 0:
allocatesize = _MAX_PAGE_BLOB_SIZE
... | Compute total remote file size
:param Descriptor self: this
:param blobxfer.models.options.Upload options: upload options
:rtype: int
:return: remote file size |
346,677 | def add_event(self, key, event):
assert isinstance(key, str)
assert isinstance(event, bytes)
if all([char.isalnum() or char == for char in key]):
safe_key = key
else:
raise ValueError("Key must be alphanumeric or a dash (-):"
... | Add an event and its corresponding key to the store. |
346,678 | def setTargetRange(self, targetRange, padding=None):
self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding,
update=False, disableAutoRange=False) | Sets the range of the target. |
346,679 | def commit(self):
try:
self.__dbapi2_conn.commit()
except Exception, e:
self.reconnect(None)
self.__dbapi2_conn.commit() | As in DBAPI2.0:
Commit any pending transaction to the database. Note that
if the database supports an auto-commit feature, this must
be initially off. An interface method may be provided to
turn it back on.
Database modules that do not support transactions should
impleme... |
346,680 | def get_assessments_offered(self):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find(self._view_filter()).sort(, DESCENDING)
return ... | Gets all ``AssessmentOffered`` elements.
In plenary mode, the returned list contains all known
assessments offered or an error results. Otherwise, the returned
list may contain only those assessments offered that are
accessible through this session.
return: (osid.assessment.Ass... |
346,681 | def service(self):
with self.lock:
for key in list(self.attempts.keys()):
log.debug( % key)
if key in self.attempts:
if self.attempts[key] <= 1:
del self.attempts[key]
else:
... | Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds. |
346,682 | def from_entity(entity, self_user_id):
user_id = UserID(chat_id=entity.id.chat_id,
gaia_id=entity.id.gaia_id)
return User(user_id, entity.properties.display_name,
entity.properties.first_name,
entity.properties.photo_url,
... | Construct user from ``Entity`` message.
Args:
entity: ``Entity`` message.
self_user_id (~hangups.user.UserID or None): The ID of the current
user. If ``None``, assume ``entity`` is the current user.
Returns:
:class:`~hangups.user.User` object. |
346,683 | def import_functions(names, src, dst):
for name in names:
module = importlib.import_module( + src)
setattr(sys.modules[ + dst], name, getattr(module, name)) | Import functions in package from their implementation modules. |
346,684 | def _flush(self):
for consumer in self.consumers:
if not getattr(consumer, "closed", False):
consumer.flush() | Flushes all registered consumer streams. |
346,685 | def find_editor_tab(self, file):
for i in range(self.Script_Editor_tabWidget.count()):
if not self.get_widget(i).file == file:
continue
LOGGER.debug("> File : Tab index .".format(file, i))
return i | Finds the **Script_Editor_tabWidget** Widget tab associated to the given file.
:param file: File to search tab for.
:type file: unicode
:return: Tab index.
:rtype: Editor |
346,686 | def unmarshal(self, v):
if not isinstance(v, date):
v = datetime.strptime(v, "%Y-%m-%d").date()
return v | Convert a date in "2012-12-13" format to a :class:`datetime.date` object. |
346,687 | def get_rest_apis(self, project_name):
all_apis = self.apigateway_client.get_rest_apis(
limit=500
)
for api in all_apis[]:
if api[] != project_name:
continue
yield api | Generator that allows to iterate per every available apis. |
346,688 | def assemble(self, module, *modules, **kwargs):
mgr = AssemblyManager(
vector=self,
modules=[module] + list(modules),
name=kwargs.get("name", "assembly"),
id_=kwargs.get("id", "assembly"),
)
return mgr.assemble() | Assemble the provided modules into the vector.
Arguments:
module (`~moclo.base.modules.AbstractModule`): a module to insert
in the vector.
modules (`~moclo.base.modules.AbstractModule`, optional): additional
modules to insert in the vector. The order of t... |
346,689 | def clean(self, *args, **kwargs):
if self.status != LINK_STATUS.get():
if self.interface_a is None or self.interface_b is None:
raise ValidationError(_())
if (self.interface_a_id == self.interface_b_id) or (self.interface_a == self.interface_b):
... | Custom validation
1. interface_a and interface_b mandatory except for planned links
2. planned links should have at least node_a and node_b filled in
3. dbm and noise fields can be filled only for radio links
4. interface_a and interface_b must differ
5. inter... |
346,690 | def items(cls):
return [
cls.GREEN,
cls.BLACK_AND_WHITE,
cls.CONTRAST_SHIFTED,
cls.CONTRAST_CONTINUOUS
] | All values for this enum
:return: list of str |
346,691 | def from_url(url, format=None):
string = urllib2.urlopen(url).read()
if PY3 is True:
string = string.decode()
if format:
format = format.lower().replace(" ", "_")
func = parse.__getattr__("from_%s" % format)
else:
func = par... | Returns the crs object from a string interpreted as a specified format, located at a given url site.
Arguments:
- *url*: The url where the crs string is to be read from.
- *format* (optional): Which format to parse the crs string as. One of "ogc wkt", "esri wkt", or "proj4".
If None, tries to aut... |
346,692 | def unparse(self, indent_step = 4, max_linelen = 72) :
"returns an XML string description of this Introspection tree."
out = io.StringIO()
def to_string(obj, indent) :
tag_name = obj.tag_name
attrs = []
for attrname in obj.tag_attrs :
attr = ... | returns an XML string description of this Introspection tree. |
346,693 | def stats(self):
nameordered = self.samples.keys()
nameordered.sort()
pd.options.display.max_rows = len(self.samples)
statdat = pd.DataFrame([self.samples[i].stats for i in nameordered],
index=nameordered).dropna(axis=1, how=)
for... | Returns a data frame with Sample data and state. |
346,694 | def _summary(self, name=None):
formatter = self._formatter_func
if len(self) > 0:
index_summary = % (formatter(self[0]),
formatter(self[-1]))
else:
index_summary =
if name is None:
name = type(sel... | Return a summarized representation.
Parameters
----------
name : str
name to use in the summary representation
Returns
-------
String with a summarized representation of the index |
346,695 | def update_value(self,
workspace_id,
entity,
value,
new_value=None,
new_metadata=None,
new_value_type=None,
new_synonyms=None,
new_patterns=None,
... | Update entity value.
Update an existing entity value with new or modified data. You must provide
component objects defining the content of the updated entity value.
This operation is limited to 1000 requests per 30 minutes. For more information,
see **Rate limiting**.
:param st... |
346,696 | def get_snippets(self, *, reference_frames, snippet_len, channel_ids=None):
if isinstance(snippet_len, (tuple, list, np.ndarray)):
snippet_len_before = snippet_len[0]
snippet_len_after = snippet_len[1]
else:
snippet_len_before = int((snippet_len + 1)... | This function returns data snippets from the given channels that
are starting on the given frames and are the length of the given snippet
lengths before and after.
Parameters
----------
snippet_len: int or tuple
If int, the snippet will be centered at the reference f... |
346,697 | def p_statement_continue(p):
if len(p) == 3:
p[0] = ast.Continue(None, lineno=p.lineno(1))
else:
p[0] = ast.Continue(p[2], lineno=p.lineno(1)) | statement : CONTINUE SEMI
| CONTINUE expr SEMI |
346,698 | def upload(args):
base_remote_path, path_dict = Object.validate_full_path(
args.full_path, vault=args.vault, path=args.path)
vault = Vault.get_by_full_path(path_dict[])
if path_dict[] != :
Object.get_by_full_path(base_remote_path, assert_type=)
for local_path in args.lo... | Given a folder or file, upload all the folders and files contained
within it, skipping ones that already exist on the remote. |
346,699 | def execute(self, **minimizer_kwargs):
bound_arguments = self.__signature__.bind(**minimizer_kwargs)
arguments = OrderedDict()
for param in self.__signature__.parameters.values():
if param.name in bound_arguments.arguments:
arguments[param.n... | Execute the chained-minimization. In order to pass options to the
seperate minimizers, they can be passed by using the
names of the minimizers as keywords. For example::
fit = Fit(self.model, self.xx, self.yy, self.ydata,
minimizer=[DifferentialEvolution, BFGS])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.