Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
348,300 | def load(self, **kwargs):
self._is_version_supported_method()
newinst = self._stamp_out_core()
newinst._refresh(**kwargs)
return newinst | Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here |
348,301 | def on_update_enabled(self, conf_evt):
enabled = conf_evt.value
if enabled:
LOG.info(, self)
if self._protocol and self._protocol.started:
LOG.error()
else:
self.state.bgp_state = const.BGP_FSM_CONNECT
... | Implements neighbor configuration change listener. |
348,302 | def getTCPportConnCount(self, ipv4=True, ipv6=True, resolve_ports=False,
**kwargs):
port_dict = {}
result = self.getStats(tcp=True, udp=False,
include_listen=False, ipv4=ipv4,
ipv6=ipv6, resolve_ports=re... | Returns TCP connection counts for each local port.
@param ipv4: Include IPv4 ports in output if True.
@param ipv6: Include IPv6 ports in output if True.
@param resolve_ports: Resolve numeric ports to names if True.
@param **kwargs: Keyword variables are us... |
348,303 | def main(server):
if in os.environ:
start_cgi(server)
stdin_sock = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
try:
stdin_sock.getpeername()
except socket.error as e:
if e.errno == errno.ENOTCONN:
start_fcgi(server)
start_standalone(server) | A convenience ``main`` method for running WSGI-compatible HTTP
application as CGI, FCGI or standalone (with auto-detection). |
348,304 | def format_dictfield_nodes(field_name, field, field_id, state, lineno):
valuetype_item = nodes.definition_list_item()
valuetype_item = nodes.term(text=)
valuetype_def = nodes.definition()
valuetype_def += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_name... | Create a section node that documents a DictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.DictField``
A configuration field.
field_id : `str`
Unique i... |
348,305 | def _load_general(data, targets, major_axis):
for d_src, d_targets, axis in zip(data, targets, major_axis):
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
elif isinstance(d_src, (list, tuple)):
for src, dst in zip(d_src, d_targets):
src.co... | Load a list of arrays into a list of arrays specified by slices. |
348,306 | def RgbToHsv(r, g, b):
v = float(max(r, g, b))
d = v - min(r, g, b)
if d==0: return (0.0, 0.0, v)
s = d / v
dr, dg, db = [(v - val) / d for val in (r, g, b)]
if r==v:
h = db - dg
elif g==v:
h = 2.0 + dr - db
else:
h = 4.0 + dg - dr
... | Convert the color from RGB coordinates to HSV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, v) tuple in the range:
h[0...360],
s[0...1],
... |
348,307 | def delta(self):
completed_date = parse_api_datetime(self.batch["CompletedDate"])
created_date = parse_api_datetime(self.batch["CreatedDate"])
td = completed_date - created_date
return td.total_seconds() | returns the time (in seconds) that the batch took, if complete |
348,308 | def parse_config_section(config_section, section_schema):
storage = {}
for name, param in select_params_from_section_schema(section_schema):
value = config_section.get(name, None)
if value is None:
if param.default is None:
continue
value = param.defa... | Parse a config file section (INI file) by using its schema/description.
.. sourcecode::
import configparser # -- NOTE: Use backport for Python2
import click
from click_configfile import SectionSchema, Param, parse_config_section
class ConfigSectionSchema(object):
c... |
348,309 | def digicam_control_encode(self, target_system, target_component, session, zoom_pos, zoom_step, focus_lock, shot, command_id, extra_param, extra_value):
s absolute position (0 means ignore) (uint8_t)
zoom_step : -100 to 100 //Zooming step value to offset zoom from the cur... | Control on-board Camera Control System to take shots.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
session : 0: stop, 1: start or keep it up //Session control e.g. show/hide lens (uint8_t)
... |
348,310 | def evaluate_rpn(rpn):
vals_stack = []
for item in rpn:
if item in _ALL_OPS:
v2 = vals_stack.pop()
if item in _UNARY_OPS:
res = _UNARY_OPS[item](v2)
elif item in _BIN_OPS:
v1 = vals_stack.pop()
res ... | Evaluates the RPN form produced my map2rpn.
Returns:
bool |
348,311 | def get_items_from_uuid(uuid, enrich_backend, ocean_backend):
uuid_fields = enrich_backend.get_fields_uuid()
terms = ""
for field in uuid_fields:
terms += % (field, uuid)
terms += ","
terms = terms[:-1]
query = % (terms)
url_search = enrich_backend.elastic.... | Get all items that include uuid |
348,312 | def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
request.client = request.client or self._clientgetter(client_id)
redirect_uri = request.client.default_redirect_uri
log.debug(, redirect_uri)
return redirect_uri | Default redirect_uri for the given client. |
348,313 | def psetex(self, key, milliseconds, value):
if not isinstance(milliseconds, int):
raise TypeError("milliseconds argument must be int")
fut = self.execute(b, key, milliseconds, value)
return wait_ok(fut) | Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int |
348,314 | def godot_options(self, info):
if info.initialized:
self.edit_traits( parent = info.ui.control,
kind = "livemodal",
view = "options_view" ) | Handles display of the options menu. |
348,315 | def build_trees(self):
"Build an unrooted consensus tree from filtered clade counts."
nodes = {}
idxarr = np.arange(len(self.fclade_counts[0][0]))
queue = []
countdict = defaultdict(int)
for clade, count in self.fclade_counts:
mask = np.int... | Build an unrooted consensus tree from filtered clade counts. |
348,316 | def reassemble(self, blueprint, fields, documents):
blueprint.reset()
for document in documents:
blueprint.reassemble(fields, document) | Reassemble the given set of fields for a list of pre-assembed documents.
NOTE: Reassembly is done in place, since the data you send the method
should be JSON type safe, if you need to retain the existing document
it is recommended that you copy them using `copy.deepcopy`. |
348,317 | def GetHostMemUnmappedMB(self):
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetHostMemUnmappedMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | Undocumented. |
348,318 | def run(self):
while not self._stopped.is_set():
try:
message = self.q.get(timeout=0.1)
except Empty:
continue
dtype, data, ts = message
if dtype in (, , , , ):
try:
self._response_handl... | Main routine.
:return: |
348,319 | def evict(self, urls):
if isinstance(urls, six.string_types):
urls = (urls,)
return self.handler.evict(urls) | Evict url(s) from the cache.
:param urls: An iterable containing normalized urls.
:returns: The number of items removed from the cache. |
348,320 | def operation_list(uploader):
files = uploader.file_list()
for f in files:
log.info("{file:30s} {size}".format(file=f[0], size=f[1])) | List file on target |
348,321 | def camel_to_snake_case(camel_input):
res = camel_input[0].lower()
for i, letter in enumerate(camel_input[1:], 1):
if letter.isupper():
if camel_input[i-1].islower() or (i != len(camel_input)-1 and camel_input[i+1].islower()):
res +=
res += letter.lower()
re... | Converts camelCase (or CamelCase) to snake_case.
From https://codereview.stackexchange.com/questions/185966/functions-to-convert-camelcase-strings-to-snake-case
:param str camel_input: The camelcase or CamelCase string to convert to snake_case
:return str |
348,322 | def _check_not_hanging(self):
checks = []
if self._ensure_unique:
checks.append((
_CONF.FIELD.ENSURE_UNIQUE,
self._ensure_unique,
lambda g: len(set(g)) != len(g),
,
... | Rough check that generate() will not hang or be very slow.
Raises ConfigurationError if generate() spends too much time in retry loop.
Issues a warning.warn() if there is a risk of slowdown. |
348,323 | def mojo_predict_csv(input_csv_path, mojo_zip_path, output_csv_path=None, genmodel_jar_path=None, classpath=None, java_options=None, verbose=False):
default_java_options =
prediction_output_file =
java = H2OLocalServer._find_java()
H2OLocalServer._check_java(java=java, verbose=verbose)
... | MOJO scoring function to take a CSV file and use MOJO model as zip file to score.
:param input_csv_path: Path to input CSV file.
:param mojo_zip_path: Path to MOJO zip downloaded from H2O.
:param output_csv_path: Optional, name of the output CSV file with computed predictions. If None (default), then
... |
348,324 | def get_actions_permission_description(view, method):
action = getattr(view, , None)
if action is None:
return
if hasattr(view, action + ):
permission_types = (action,)
elif method in SAFE_METHODS:
permission_types = (, % action)
else:
permission_types = (, %... | Returns actions permissions description in format:
* permission1 name
* permission1 docstring
* permission2 name
* permission2 docstring |
348,325 | def get_band_structure_dict(self):
if self._band_structure is None:
msg = ("run_band_structure has to be done.")
raise RuntimeError(msg)
retdict = {: self._band_structure.qpoints,
: self._band_structure.distances,
: self._band_stru... | Returns calclated band structures
Returns
-------
dict
keys: qpoints, distances, frequencies, eigenvectors, and
group_velocities
Each dict value is a list containing properties on number of paths.
The number of q-points on one path can be di... |
348,326 | def insert_comment(event):
buff = event.current_buffer
if event.arg != 1:
def change(line):
return line[1:] if line.startswith() else line
else:
def change(line):
return + line
buff.document = Document(
text=.join(map(change, buff.text.splitli... | Without numeric argument, comment all lines.
With numeric argument, uncomment all lines.
In any case accept the input. |
348,327 | def ceil(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_rint_ceil,
(BigFloat._implicit_convert(x),),
context,
) | Return the next higher or equal integer to x.
If the result is not exactly representable, it will be rounded according to
the current context. Note that the rounding step means that it's possible
for the result to be smaller than ``x``. For example::
>>> x = 2**100 + 1
>>> ceil(2**100 + ... |
348,328 | def find_prompt(self, delay_factor=1):
delay_factor = self.select_delay_factor(delay_factor)
self.clear_buffer()
self.write_channel(self.RETURN)
time.sleep(delay_factor * 0.1)
prompt = self.read_channel()
if self.ansi_escape_codes:
prompt = ... | Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int |
348,329 | def format_error(e):
if isinstance(e, PyMacaronException):
return e.to_model()
if isinstance(e, PyMacaronCoreException) and e.__class__.__name__ == :
return ValidationError(str(e)).to_model()
return UnhandledServerError(str(e)).to_model() | Take an exception caught within pymacaron_core and turn it into a
bravado-core Error instance |
348,330 | def get_all_incoming_properties(self, params=None):
if not params:
params = {}
return self._iterate_through_pages(
self.get_incoming_properties_per_page,
resource=INCOMING_PROPERTIES,
**{: params}
) | Get all incoming properties
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list |
348,331 | def index(self, item):
k = self._key(item)
i = bisect_left(self._keys, k)
j = bisect_right(self._keys, k)
return self._items[i:j].index(item) + i | Find the position of an item. Raise ValueError if not found. |
348,332 | def from_arrays(cls, name, verts, normals, n_verts=3):
wavefront_str = "o {name}\n".format(name=name)
for vert in verts:
wavefront_str += "v {0} {1} {2}\n".format(*vert)
wavefront_str += "vt 1.0 1.0\n"
for norm in normals:
... | Returns a wavefront .obj string using pre-triangulated vertex dict and normal dict as reference. |
348,333 | def is_likely_inline(link):
file_type = mimetypes.guess_type(link, strict=False)[0]
if file_type:
top_level_type, subtype = file_type.split(, 1)
return top_level_type in (, , ) or subtype == | Return whether the link is likely to be inline. |
348,334 | def libvlc_video_set_scale(p_mi, f_factor):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,), (1,),), None,
None, MediaPlayer, ctypes.c_float)
return f(p_mi, f_factor) | Set the video scaling factor. That is the ratio of the number of pixels on
screen to the number of pixels in the original decoded video in each
dimension. Zero is a special value; it will adjust the video to the output
window/drawable (in windowed mode) or the entire screen.
Note that not all video outp... |
348,335 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.document is not None:
_dict[] = self.document._to_dict()
if hasattr(self, ) and self.model_id is not None:
_dict[] = self.model_id
if hasattr(self, ) and self.model_version is not None:
... | Return a json dictionary representing this model. |
348,336 | def fix_all(override_debug=False, override_all=False):
fix_base(True)
fix_builtins(override_debug)
fix_subprocess(override_debug, override_all)
return True | Activate the full compatibility. |
348,337 | def to_motor_velocity_acceleration(self, va):
if isinstance(va, collections.Iterable):
return [(x * self._va_to_motor) for x in va]
else:
return va * self._va_to_motor | Convert velocities/accelerations to motor units.
Converts velocity/ies and/or acceleration/s to units of motor
pitch per second (or second squared), which is what the drive
requires when given move instructions.
Parameters
----------
va : int, float, or iterable of ints... |
348,338 | def add(self, cls_or_branch, *args, **kwargs):
if isinstance(cls_or_branch, Branch):
self.tasks.append(cls_or_branch)
else:
self.__validate_task(cls_or_branch, , args, kwargs)
self.tasks.append({: cls_or_branch, : args, : kwargs})
... | Adds a task or branch to the lane.
Parameters
----------
cls_or_branch : Class
*args
Variable length argument list to be passed to `cls_or_branch` during instantiation
**kwargs
Variable length keyword arguments to be passed to `cls_or_branch` during insta... |
348,339 | def fit_cosine_function(wind):
wind_daily = wind.groupby(wind.index.date).mean()
wind_daily_hourly = pd.Series(index=wind.index, data=wind_daily.loc[wind.index.date].values)
df = pd.DataFrame(data=dict(daily=wind_daily_hourly, hourly=wind)).dropna(how=)
x = np.array([df.daily, df.index.hour])
... | fits a cosine function to observed hourly windspeed data
Args:
wind: observed hourly windspeed data
Returns:
parameters needed to generate diurnal features of windspeed using a cosine function |
348,340 | def _read_tags_for_revset(self, spec):
cmd = [
, , , , ,
, spec]
res = self._invoke(*cmd)
header_pattern = re.compile(r)
match_res = map(header_pattern.match, res.splitlines())
matched_lines = filter(None, match_res)
matches = (match.groupdict() for match in matched_lines)
for match in matches:
... | Return TaggedRevision for each tag/rev combination in the revset spec |
348,341 | def signup(request, **kwargs):
if not ALLAUTH:
return http.HttpResponse(_())
if request.method == "POST" and in request.POST:
form_class = LoginForm
form = form_class(request.POST)
redirect_field_name = "next"
success_url = get_default_redirect(request, redirect_fie... | Overrides allauth.account.views.signup |
348,342 | def norm_nuclear(X):
r
return np.sum(np.linalg.svd(sl.promote16(X), compute_uv=False)) | r"""Compute the nuclear norm
.. math::
\| X \|_* = \sum_i \sigma_i
where :math:`\sigma_i` are the singular values of matrix :math:`X`.
Parameters
----------
X : array_like
Input array :math:`X`
Returns
-------
nncl : float
Nuclear norm of `X` |
348,343 | def do_status(self, args):
work_spec_name = self._get_work_spec_name(args)
status = self.task_master.status(work_spec_name)
self.stdout.write(json.dumps(status, indent=4, sort_keys=True) +
) | print the number of work units in an existing work spec |
348,344 | def mixture_from_any(ID):
-R512AR512AairAir
if type(ID) == list:
if len(ID) == 1:
ID = ID[0]
else:
raise Exception()
ID = ID.lower().strip()
ID2 = ID.replace(, )
ID3 = ID.replace(, )
for i in [ID, ID2, ID3]:
if i in _MixtureDictLookup:
... | Looks up a string which may represent a mixture in the database of
thermo to determine the key by which the composition of that mixture can
be obtained in the dictionary `_MixtureDict`.
Parameters
----------
ID : str
A string or 1-element list containing the name which may represent a
... |
348,345 | def save(self):
if self.views:
if self.get(, None) != QUERY_LANGUAGE:
for view_name, view in self.iterviews():
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(104, view_name)
else:
... | Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updated remotely. In
either ... |
348,346 | def getWindowByPID(self, pid, order=0):
for w in self._get_window_list():
if "kCGWindowOwnerPID" in w and w["kCGWindowOwnerPID"] == pid:
if order == 0:
return w["kCGWindowNumber"]
else:
order -= 1
... | Returns a handle for the first window that matches the provided PID |
348,347 | def stop(self, _exc_type=None, _exc_value=None, _exc_traceback=None):
if self.do_pop_attrs:
self.get_tracer().pop_zipkin_attrs()
end_timestamp = time.time()
if self.duration:
duration = self.duration
else:
... | Exit the span context. Zipkin attrs are pushed onto the
threadlocal stack regardless of sampling, so they always need to be
popped off. The actual logging of spans depends on sampling and that
the logging was correctly set up. |
348,348 | def _fill_col_borders(self):
first = True
last = True
if self.col_indices[0] == self.hcol_indices[0]:
first = False
if self.col_indices[-1] == self.hcol_indices[-1]:
last = False
for num, data in enumerate(self.tie_data):
self.tie_dat... | Add the first and last column to the data by extrapolation. |
348,349 | def get_lookup():
lookup = dict()
version_file = os.path.join(, )
with open(version_file) as filey:
exec(filey.read(), lookup)
return lookup | get version by way of sregistry.version, returns a
lookup dictionary with several global variables without
needing to import singularity |
348,350 | def _send_trace(self, chunk=None):
self._trace_sm_running = True
if chunk is None:
chunk = self._next_tracing_chunk(20)
if chunk is None or len(chunk) == 0:
self._trace_sm_running = False
return
try:
self._send_notifica... | Stream tracing data to the ble client in 20 byte chunks
Args:
chunk (bytearray): A chunk that should be sent instead of requesting a
new chunk from the pending reports. |
348,351 | def _InitSSLContext(self, cafile=None,
disable_ssl_certificate_validation=False):
try:
if disable_ssl_certificate_validation:
ssl._create_default_https_context = ssl._create_unverified_context
ssl_context = ssl.create_default_context()
else:
s... | Creates a ssl.SSLContext with the given settings.
Args:
cafile: A str identifying the resolved path to the cafile. If not set,
this will use the system default cafile.
disable_ssl_certificate_validation: A boolean indicating whether
certificate verification is disabled. For security pur... |
348,352 | def edit_reals(
self,
id_vip,
method_bal,
reals,
reals_prioritys,
reals_weights,
alter_priority=0):
if not is_valid_int_param(id_vip):
raise InvalidParameterError(
u)
vip_map = dict... | Execute the script 'gerador_vips' several times with options -real, -add and -del to adjust vip request reals.
:param id_vip: Identifier of the VIP. Integer value and greater than zero.
:param method_bal: method_bal.
:param reals: List of reals. Ex: [{'real_name':'Teste1', 'real_ip':'10.10.10.1'... |
348,353 | def set_pwm(self, values):
if len(values) != len(self._pins):
raise ValueError(
)
if not all(0 <= v <= 1 for v in values):
raise ValueError()
for tries in range(self.IO_TRIES):
try:
self._set_pwm(self._to_... | Set pwm values on the controlled pins.
:param values: Values to set (0.0-1.0).
:return: |
348,354 | def fetch_additional_posts(self, uid):
cats = MPost2Catalog.query_by_entity_uid(uid, kind=self.kind)
cat_uid_arr = []
for cat_rec in cats:
cat_uid = cat_rec.tag_id
cat_uid_arr.append(cat_uid)
logger.info(.format(cat_uid_arr))
rel_recs = MRelation.... | fetch the rel_recs, and random recs when view the post. |
348,355 | def writeTypes(self, fd):
print >>fd, *50
print >>fd, %self.getTypesModuleName()
print >>fd,
print >>fd, %self.__class__
print >>fd, %.join(sys.argv)
print >>fd,
print >>fd, *50
print >>fd, TypesHeaderContainer()
se... | write out types module to file descriptor. |
348,356 | def add(self, parent, obj_type, **attributes):
response = self.post(self.server_url + parent.ref + + obj_type, attributes)
return self._get_href(response.json()) | IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: STC object reference. |
348,357 | def save_shortcuts(self):
self.check_shortcuts()
for shortcut in self.source_model.shortcuts:
shortcut.save() | Save shortcuts from table model. |
348,358 | def update_session_entity_type(
self,
session_entity_type,
update_mask=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
if not in self._inner_api_calls:... | Updates the specified session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.SessionEntityTypesClient()
>>>
>>> # TODO: Initialize ``session_entity_type``:
>>> session_entity_type = {}
>>>
... |
348,359 | def positions(self, key, value):
email_addresses = self.get("email_addresses", [])
current = None
record = None
recid_or_status = force_list(value.get())
for el in recid_or_status:
if el.lower() == :
current = True if value.get() else None
else:
record =... | Populate the positions field.
Also populates the email_addresses field by side effect. |
348,360 | def all_inspections(obj):
for name, callback in INSPECTIONS:
result = callback(obj)
if result:
yield name, result | Generator to iterate all current Jishaku inspections. |
348,361 | def to_map_projection(arg, hemi=Ellipsis, chirality=Ellipsis,
center=Ellipsis, center_right=Ellipsis, radius=Ellipsis,
method=Ellipsis, registration=Ellipsis, sphere_radius=Ellipsis,
pre_affine=Ellipsis, post_affine=Ellipsis, meta_data=Ellipsis):
<na... | to_map_projection(mp) yields mp if mp is a map projection object.
to_map_projection((name, hemi)) is equivalent to map_projection(name, chirality=hemi).
to_map_projection((name, opts)) uses the given options dictionary as options to map_projection;
(name, hemi, opts) is also allowed as input.
to_map_p... |
348,362 | def reverseCommit(self):
print(self.after == self.before)
pos = self.qteWidget.textCursor().position()
self.qteWidget.setHtml(self.before)
self.placeCursor(pos) | Reverse the document to the original state. |
348,363 | def complete(self):
if self.scan_limit is not None and self.scan_limit == 0:
return True
if self.item_limit is not None and self.item_limit == 0:
return True
return False | Return True if the limit has been reached |
348,364 | def clean_en_xx_pairs(en_xx_pairs):
for s1, s2 in en_xx_pairs:
if _regex_filter(s1):
continue
s1_list, s2_list = _split_sentences(s1, s2)
if len(s1_list) != len(s2_list):
continue
elif len(s1_list) == 1:
yield s1, s2
else:
for s1_subsentence, s2_subsentence in itertool... | Generates a cleaned-up stream of (English, other) translation pairs.
Cleaning includes both filtering and simplistic sentence splitting, with
minimal assumptions on the non-English pair member: (1) All filtering is
done based on the English member of the pair, and (2) sentence splitting
assumes only that sente... |
348,365 | def fromSuccessResponse(cls, success_response, signed_only=True):
self = cls()
self.ns_uri = self._getSRegNS(success_response.message)
if signed_only:
args = success_response.getSignedNS(self.ns_uri)
else:
args = success_response.message.getArgs(self.ns_u... | Create a C{L{SRegResponse}} object from a successful OpenID
library response
(C{L{openid.consumer.consumer.SuccessResponse}}) response
message
@param success_response: A SuccessResponse from consumer.complete()
@type success_response: C{L{openid.consumer.consumer.SuccessResponse... |
348,366 | def _muaprocessnew(self):
foldername = self._foldername("new")
files = self.filesystem.listdir(foldername)
for filename in files:
if filename == "":
continue
curfilename = self._foldername(joinpath("new", filename))
newfilename = joinp... | Moves all 'new' files into cur, correctly flagging |
348,367 | def destroy(self, request, *args, **kwargs):
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._destroy_many(bulk_payload)
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg not in kwargs:
... | Either delete a single or many model instances in bulk
DELETE /dogs/
{
"dogs": [
{"id": 1},
{"id": 2}
]
}
DELETE /dogs/
[
{"id": 1},
{"id": 2}
] |
348,368 | def get_live_id(self, username):
params = {
"flags": "live_onair"
}
api_user_videos = USER_INFO_URL.format(username) + "/videos"
try:
res = self.session.http.get(api_user_videos.format(username),
params=params)
except Ex... | Get the livestream videoid from a username.
https://developer.dailymotion.com/tools/apiexplorer#/user/videos/list |
348,369 | def pool_create(self, name, description, category):
params = {
: name,
: description,
: category
}
return self._get(, params, method=, auth=True) | Function to create a pool (Requires login) (UNTESTED).
Parameters:
name (str): Pool name.
description (str): Pool description.
category (str): Can be: series, collection. |
348,370 | def add(self, key, value):
self.configfile.add(self.name, key, value) | Add a new value for a key.
This differs from __setitem__ in adding a new value instead of updating
the list of values, thus avoiding the need to fetch the previous list of
values. |
348,371 | def _curve(x1, y1, x2, y2, hunit = HUNIT, vunit = VUNIT):
ax1, ax2, axm = x1 * hunit, x2 * hunit, (x1 + x2) * hunit / 2
ay1, ay2 = y1 * vunit, y2 * vunit
return pyx.path.curve(ax1, ay1, axm, ay1, axm, ay2, ax2, ay2) | Return a PyX curved path from (x1, y1) to (x2, y2),
such that the slope at either end is zero. |
348,372 | def _output_file_data(self, outfp, blocksize, ino):
log_block_size = self.pvd.logical_block_size()
outfp.seek(ino.extent_location() * log_block_size)
tmp_start = outfp.tell()
with inode.InodeOpenData(ino, log_block_size) as (data_fp, data_len):
utils.copy_d... | Internal method to write a directory record entry out.
Parameters:
outfp - The file object to write the data to.
blocksize - The blocksize to use when writing the data out.
ino - The Inode to write.
Returns:
The total number of bytes written out. |
348,373 | def get_medium_attachments_of_controller(self, name):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
medium_attachments = self._call("getMediumAttachmentsOfController",
in_p=[name])
medium_attachme... | Returns an array of medium attachments which are attached to the
the controller with the given name.
in name of type str
return medium_attachments of type :class:`IMediumAttachment`
raises :class:`VBoxErrorObjectNotFound`
A storage controller with given name doesn't exist. |
348,374 | def assert_bool(dist, attr, value):
if bool(value) != value:
raise DistutilsSetupError(
"%r must be a boolean value (got %r)" % (attr,value)
) | Verify that value is True, False, 0, or 1 |
348,375 | def deserialize_from_headers(headers):
return create_exception_by_name(
_get_header(headers, ),
_get_header(headers, ),
_get_header(headers, ),
_get_header(headers, ),
_get_header(headers, ),
_get_header(headers, ),
) | Deserialize a DataONE Exception that is stored in a map of HTTP headers (used in
responses to HTTP HEAD requests). |
348,376 | def apply_inheritance(self):
self.hosts.apply_inheritance()
self.contacts.apply_inheritance()
self.services.apply_inheritance()
self.servicedependencies.apply_inheritance()
self.hostdependencies.apply_inheritance()
self.timeperiods.apply_inherit... | Apply inheritance over templates
Template can be used in the following objects::
* hosts
* contacts
* services
* servicedependencies
* hostdependencies
* timeperiods
* hostsextinfo
* servicesextinfo
* serviceescalations
* hostescal... |
348,377 | def new_dir(self, name):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
self._new(name, 0) | A method to create a new Path Table Record.
Parameters:
name - The name for this Path Table Record.
Returns:
Nothing. |
348,378 | def per_country_data(self):
ret = {}
for cache_date in self.cache_dates:
data = self._cache_get(cache_date)
ret[cache_date] = {}
for cc, count in data[].items():
k = % (self._alpha2_to_country(cc), cc)
ret[cache_date][k] = cou... | Return download data by country.
:return: dict of cache data; keys are datetime objects, values are
dict of country (str) to count (int)
:rtype: dict |
348,379 | def addTag( self, tag ):
if ( not (tag and self.isTagValid(tag)) ):
return False
self.blockSignals(True)
create_item = self.createItem()
if create_item:
self.insertItem(self.row(create_item), XMultiTagItem(tag, self))
create_... | Adds a new tag to the edit.
:param tag | <str>
:return <bool> |
348,380 | def get_eni_id(self, interface=1):
log = logging.getLogger(self.cls_logger + )
if self.instance_id is None:
msg =
log.error(msg)
raise OSError(msg)
log.info(.format(i=self.instance_id))
log.debug()
try:
response... | Given an interface number, gets the AWS elastic network
interface associated with the interface.
:param interface: Integer associated to the interface/device number
:return: String Elastic Network Interface ID or None if not found
:raises OSError, AWSAPIError, EC2UtilError |
348,381 | def set_sum_w2(self, w, ix, iy=0, iz=0):
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = self.nbins(axis=0, overflow=True)
yl = self.nbins(axis=1, overflow=True)
... | Sets the true number of entries in the bin weighted by w^2 |
348,382 | def iter_search_nodes(self, **conditions):
for n in self.traverse():
conditions_passed = 0
for key, value in six.iteritems(conditions):
if hasattr(n, key) and getattr(n, key) == value:
conditions_passed +=1
if conditions_passed == ... | Search nodes in an interative way. Matches are being yield as
they are being found. This avoids to scan the full tree
topology before returning the first matches. Useful when
dealing with huge trees. |
348,383 | def queue_size(self):
response = self._request("tasks/list")
tasks = json.loads(response.content.decode())["tasks"]
return len([t for t in tasks if t[] == ]) | Determine Cuckoo sandbox queue length
There isn't a built in way to do this like with Joe
:rtype: int
:return: Number of submissions in sandbox queue. |
348,384 | def get_revision(self, id, rev, **kwargs):
kwargs[] = True
if kwargs.get():
return self.get_revision_with_http_info(id, rev, **kwargs)
else:
(data) = self.get_revision_with_http_info(id, rev, **kwargs)
return data | Get specific audited revision of this build configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>... |
348,385 | def del_downtime(self, downtime_id):
if downtime_id in self.downtimes:
self.downtimes[downtime_id].can_be_deleted = True
del self.downtimes[downtime_id] | Delete a downtime in this object
:param downtime_id: id of the downtime to delete
:type downtime_id: int
:return: None |
348,386 | def clustdealer(pairdealer, optim):
ccnt = 0
chunk = []
while ccnt < optim:
try:
taker = itertools.takewhile(lambda x: x[0] != "//\n", pairdealer)
oneclust = ["".join(taker.next())]
except StopIteration:
return 1, chunk
... | return optim clusters given iterators, and whether it got all or not |
348,387 | def get_var_count(self):
n = c_int()
self.library.get_var_count.argtypes = [POINTER(c_int)]
self.library.get_var_count(byref(n))
return n.value | Return number of variables |
348,388 | def assert_single_selected(self, option_name, select_name):
option = find_option(world.browser, select_name, option_name)
assert option.is_selected(), "Option should be selected." | Assert the given option is selected from the select with label
(recommended), name or id.
If multiple selections are supported other options may be selected. |
348,389 | def create_account(self, email_address, password=None, client_id=None, client_secret=None):
request = self._get_request()
params = {
: email_address
}
if client_id:
params[] = client_id
params[] = client_secret
response = request.pos... | Create a new account.
If the account is created via an app, then Account.oauth will contain the
OAuth data that can be used to execute actions on behalf of the newly created account.
Args:
email_address (str): Email address of the new account to create
passw... |
348,390 | def new_transfer_transaction(self, asset: str, b58_from_address: str, b58_to_address: str, amount: int,
b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction:
if not isinstance(b58_from_address, str) or not isinstance(b58_to_address, str) or not isinsta... | This interface is used to generate a Transaction object for transfer.
:param asset: a string which is used to indicate which asset we want to transfer.
:param b58_from_address: a base58 encode address which indicate where the asset from.
:param b58_to_address: a base58 encode address which indi... |
348,391 | def toggleDrawingSensitive(self, drawing=True):
self.actions.editMode.setEnabled(not drawing)
if not drawing and self.beginner():
print()
self.canvas.setEditing(True)
self.canvas.restoreCursor()
self.actions.create.setEnabled(True) | In the middle of drawing, toggling between modes should be disabled. |
348,392 | def compare_two(data1, data2, test=StatTests.ks):
results = getattr(_st, get_test(test))(data1, data2)
Stats = namedtuple(, [, ])
return Stats(*results) | Compares two distributions of data
and assess two scores: a distance between them
and a probability they are drawn from the same
distribution.
Parameters:
data1: numpy array of dataset 1
data2: numpy array of dataset 2
test: Stat_tests\
Defines the statistic... |
348,393 | def get_library_barcode_sequence_hash(self, inverse=False):
action = os.path.join(self.record_url, "get_library_barcode_sequence_hash")
res = requests.get(url=action, headers=HEADERS, verify=False)
res.raise_for_status()
res_json = res.json()
new_res = {}
... | Calls the SequencingRequest's get_library_barcode_sequence_hash server-side endpoint to
create a hash of the form {LibraryID -> barcode_sequence} for all Libraries on the
SequencingRequest.
Args:
inverse: `bool`. True means to inverse the key and value pairs such that the barcode
... |
348,394 | def safe_makedirs(path):
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
raise | A safe function for creating a directory tree. |
348,395 | def nunique(self, dropna=True):
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except TypeError:
msg = .format(val.dtype)
assert val.dtype == object, msg
val, _ = algorithms... | Return number of unique elements in the group. |
348,396 | def remove_mapping(agent, prefix, ip):
return _broadcast(agent, RemoveMappingManager,
RecordType.record_A, prefix, ip) | Removes a mapping with a contract.
It has high latency but gives some kind of guarantee. |
348,397 | def manifest(request, form):
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
line_items = (
Q(lineitem__product__in=products) |
Q(lineitem__product__category__in=categories)
)
invoices = commerce.Invoice.objects.filter(
line_items,
... | Produces the registration manifest for people with the given product
type. |
348,398 | def make_python_xref_nodes(py_typestr, state, hide_namespace=False):
if hide_namespace:
template =
else:
template =
xref_text = template.format(py_typestr)
return parse_rst_content(xref_text, state) | Make docutils nodes containing a cross-reference to a Python object.
Parameters
----------
py_typestr : `str`
Name of the Python object. For example
``'mypackage.mymodule.MyClass'``. If you have the object itself, or
its type, use the `make_python_xref_nodes_for_type` function inste... |
348,399 | def Lehrer(m, Dtank, Djacket, H, Dinlet, rho, Cp, k, mu, muw=None,
isobaric_expansion=None, dT=None, inlettype=,
inletlocation=):
rtangentialradialtopbottomautoradial
delta = (Djacket-Dtank)/2.
Q = m/rho
Pr = Cp*mu/k
vs = Q/H/delta
vo = Q/(pi/4*Dinlet**2)
if dT and isob... | r'''Calculates average heat transfer coefficient for a jacket around a
vessel according to [1]_ as described in [2]_.
.. math::
Nu_{S,L} = \left[\frac{0.03Re_S^{0.75}Pr}{1 + \frac{1.74(Pr-1)}
{Re_S^{0.125}}}\right]\left(\frac{\mu}{\mu_w}\right)^{0.14}
d_g = \left(\frac{8}{3}\right)^{0.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.