Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,400 | def _execute_command(self, command, *args):
try:
command(*args)
except libvirt.libvirtError as error:
raise RuntimeError("Unable to execute command. %s" % error) | Execute the state transition command. |
346,401 | def shelli(ndim, array):
array = stypes.toIntVector(array)
ndim = ctypes.c_int(ndim)
libspice.shelli_c(ndim, ctypes.cast(array, ctypes.POINTER(ctypes.c_int)))
return stypes.cVectorToPython(array) | Sort an integer array using the Shell Sort algorithm.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/shelli_c.html
:param ndim: Dimension of the array.
:type ndim: int
:param array: The array to be sorted.
:type array: Array of ints
:return: The sorted array.
:rtype: Array of ints |
346,402 | def tag_verb_chains(self):
if not self.is_tagged(CLAUSES):
self.tag_clauses()
if self.__verbchain_detector is None:
self.__verbchain_detector = load_default_verbchain_detector()
sentences = self.divide()
verbchains = []
for sentence in sentences:
... | Create ``verb_chains`` layer.
Depends on ``clauses`` layer. |
346,403 | def as_quat_array(a):
a = np.asarray(a, dtype=np.double)
if a.shape == (4,):
return quaternion(a[0], a[1], a[2], a[3])
if not a.flags[] or a.strides[-1] != a.itemsize:
a = a.copy(order=)
try:
av = a.view(np.quaternion)
except ValueError as e:
message ... | View a float array as an array of quaternions
The input array must have a final dimension whose size is
divisible by four (or better yet *is* 4), because successive
indices in that last dimension will be considered successive
components of the output quaternion.
This function is usually fast (of o... |
346,404 | def printJobChildren(self):
for job in self.jobsToReport:
children = "CHILDREN_OF_JOB:%s " % job
for level, jobList in enumerate(job.stack):
for childJob in jobList:
children += "\t(CHILD_JOB:%s,PRECEDENCE:%i)" % (childJob, level)
... | Takes a list of jobs, and prints their successors. |
346,405 | def charge(self, amount):
try:
result = Transaction.sale(
{
: amount.quantize(Decimal()),
: self.vault_id,
"options": {
"submit_for_settlement": True
}
}
... | Charges the users credit card, with he passed $amount, if they are in the vault. Returns the payment_log instance
or None (if charge fails etc.) |
346,406 | def mcscanq(args):
p = OptionParser(mcscanq.__doc__)
p.add_option("--color", help="Add color highlight, used in plotting")
p.add_option("--invert", default=False, action="store_true",
help="Invert query and subject [default: %default]")
opts, args = p.parse_args(args)
if len(a... | %prog mcscanq query.ids blocksfile
Query multiple synteny blocks to get the closest alignment feature. Mostly
used for 'highlighting' the lines in the synteny plot, drawn by
graphics.karyotype and graphics.synteny. |
346,407 | def show_system_monitor_output_switch_status_port_status_port_name(self, **kwargs):
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
switch_status = ET... | Auto Generated Code |
346,408 | def transform(self, transform, desc=None):
if desc is None:
desc = u.format(getattr(transform, , ))
return self.replace(
transforms=self.transforms + [transform],
desc_stack=self.desc_stack + [desc]
) | Create a copy of this query, transformed by `transform`.
Args:
transform (callable): Callable that takes an iterable of values and
returns an iterable of transformed values.
Keyword Args:
desc (str): A description of the transform, to use in log messages.
... |
346,409 | def all_package_versions(package):
info = PyPI.package_info(package)
return info and sorted(info[].keys(), key=lambda x: x.split(), reverse=True) or [] | All versions for package |
346,410 | def atom_criteria(*params):
result = {}
for index, param in enumerate(params):
if param is None:
continue
elif isinstance(param, int):
result[index] = HasAtomNumber(param)
else:
result[index] = param
return result | An auxiliary function to construct a dictionary of Criteria |
346,411 | def fit(
self, frequency, recency, T, weights=None, initial_params=None, verbose=False, tol=1e-7, index=None, **kwargs
):
frequency = np.asarray(frequency).astype(int)
recency = np.asarray(recency)
T = np.asarray(T)
_check_inputs(frequency, recency, T)
if we... | Fit a dataset to the BG/NBD model.
Parameters
----------
frequency: array_like
the frequency vector of customers' purchases
(denoted x in literature).
recency: array_like
the recency vector of customers' purchases
(denoted t_x in literatur... |
346,412 | def set_seq2(self, b):
if b is self.b and hasattr(self, ):
return
self.b = b
if not isinstance(self.a, list):
self.a = list(self.a)
if not isinstance(self.b, list):
self.b = list(self.b)
[hash(x) for x in self.a]
... | Same as SequenceMatcher.set_seq2, but uses the c chainb
implementation. |
346,413 | def target_to_ipv6_cidr(target):
splitted = target.split()
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
block = int(splitted[1])
except (socket.error, ValueError):
return None
if block <= 0 or block > 126:
... | Attempt to return a IPv6 CIDR list from a target string. |
346,414 | def init_layout(self):
super(AndroidListView, self).init_layout()
d = self.declaration
w = self.widget
adapter = self.adapter = BridgedRecyclerAdapter(w)
adapter.setRecyleListener(adapter.getId())
adapter.onRecycleView.connect(self.on_recycle_... | Initialize the underlying widget. |
346,415 | def _maybe_null_out(result, axis, mask, min_count=1):
if hasattr(axis, ):
raise ValueError(
)
if axis is not None and getattr(result, , False):
null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0
if null_mask.any():
dtype, fill_val... | xarray version of pandas.core.nanops._maybe_null_out |
346,416 | def print_exception(exception, secret_values=None):
print(brief_exception_text(exception, secret_values), file=sys.stderr) | Prints the exception message and the name of the exception class to stderr.
:param exception: The exception to print
:param secret_values: Values to hide in output |
346,417 | def capfirst(x):
x = to_string(x).strip()
if x:
return x[0].upper() + x[1:].lower()
else:
return x | Capitalise the first letter of ``x``. |
346,418 | def write_edge (self, node):
self.writeln(u" edge [")
self.writeln(u % node["edge"])
self.writeln(u" source %d" % self.nodes[node["parent_url"]]["id"])
self.writeln(u" target %d" % node["id"])
if self.has_part("result"):
self.writeln(u" valid %d" %... | Write one edge. |
346,419 | def clean(self, value):
if self._type == :
pass
elif self._type == :
elif self._type == :
elif isinstance(value, basestring):
pass
else:
value = str(value)
if isinstance(value, datetime.datetime):
value = value.strftime()
elif isinstance(value, datetime.... | Clean
Cleans and returns the new value
Arguments:
value {mixed} -- The value to clean
Returns:
mixed |
346,420 | def list(context, sort, limit, offset, where, verbose):
result = user.list(
context,
sort=sort,
limit=limit,
offset=offset,
where=where
)
utils.format_output(result, context.format, verbose=verbose) | list(context, sort, limit, offset, where, verbose)
List all users.
>>> dcictl user-list
:param string sort: Field to apply sort
:param integer limit: Max number of rows to return
:param integer offset: Offset associated with the limit
:param string where: An optional filter criteria
:para... |
346,421 | def render_json_tree(tree, indent):
tree = sorted_tree(tree)
branch_keys = set(r.key for r in flatten(tree.values()))
nodes = [p for p in tree.keys() if p.key not in branch_keys]
key_tree = dict((k.key, v) for k, v in tree.items())
get_children = lambda n: key_tree.get(n.key, [])
def aux(n... | Converts the tree into a nested json representation.
The json repr will be a list of hashes, each hash having the following fields:
- package_name
- key
- required_version
- installed_version
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int in... |
346,422 | def get_instruments(self):
url = "{0}/{1}/instruments".format(self.domain, self.API_VERSION)
params = {"accountId": self.account_id}
try:
response = self._Client__call(uri=url, params=params)
assert len(response) > 0
return response
except Req... | See more:
http://developer.oanda.com/rest-live/rates/#getInstrumentList |
346,423 | def securityEventSSE(symbols=None, on_data=None, token=, version=):
return _runSSE(, symbols, on_data, token, version) | The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
token (stri... |
346,424 | def K_to_F(self, K, method=):
A1 = self.A + dot(self.C, K)
B1 = self.B
Q1 = self.Q
R1 = self.R - self.beta * self.theta * dot(K.T, K)
lq = LQ(Q1, R1, A1, B1, beta=self.beta)
P, F, d = lq.stationary_values(method=method)
return F, P | Compute agent 1's best value-maximizing response F, given K.
Parameters
----------
K : array_like(float, ndim=2)
A j x n array
method : str, optional(default='doubling')
Solution method used in solving the associated Riccati
equation, str in {'doublin... |
346,425 | def trigger_replication_schedule(self, schedule_id, dry_run=False):
return self._post("replications/%s/run" % schedule_id, ApiCommand,
params=dict(dryRun=dry_run),
api_version=3) | Trigger replication immediately. Start and end dates on the schedule will be
ignored.
@param schedule_id: The id of the schedule to trigger.
@param dry_run: Whether to execute a dry run.
@return: The command corresponding to the replication job.
@since: API v3 |
346,426 | def p_lvalue_pointer(self, p):
p[0] = Lvalue(p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | lvalue : lpointer |
346,427 | def create_status(self, state, target_url=github.GithubObject.NotSet, description=github.GithubObject.NotSet, context=github.GithubObject.NotSet):
assert isinstance(state, (str, unicode)), state
assert target_url is github.GithubObject.NotSet or isinstance(target_url, (str, unicode)), target_ur... | :calls: `POST /repos/:owner/:repo/statuses/:sha <http://developer.github.com/v3/repos/statuses>`_
:param state: string
:param target_url: string
:param description: string
:param context: string
:rtype: :class:`github.CommitStatus.CommitStatus` |
346,428 | def update(self, document):
if not in document:
return self.insert(document)
copy = document.copy()
del copy[]
self.db.execute( % self.name, (json.dumps(copy), document[]))
return document | Updates a document stored in this collection. If the document does not
already have an '_id' value, it will be created |
346,429 | async def close(self):
if self._connection is None:
return
if self._transaction is not None:
await self._transaction.rollback()
self._transaction = None
self._engine.release(self)
self._connection = None
self._engine... | Close this SAConnection.
This results in a release of the underlying database
resources, that is, the underlying connection referenced
internally. The underlying connection is typically restored
back to the connection-holding Pool referenced by the Engine
that produced this SACo... |
346,430 | def _rr_line(self, section):
deleting = None
token = self.tok.get(want_leading = True)
if not token.is_whitespace():
self.last_name = dns.name.from_text(token.value, None)
name = self.last_name
token = self.tok.get()
if not token.is_identifi... | Process one line from the text format answer, authority, or
additional data sections. |
346,431 | def _write_to_zip(self, path, contents):
if isinstance(path, list):
path = os.path.sep.join(path)
self.zf.writestr(path, contents) | _write_to_zip: Write file to zip
Args:
path: (str) where in zip to write file
contents: (str) contents of file to write
Returns: None |
346,432 | def channel(self, channel_id=None, synchronous=False):
if channel_id is None:
if len(self._channels) - 1 >= self._channel_max:
raise Connection.TooManyChannels(
"%d channels already open, max %d",
len(self._channels) - 1,
... | Fetch a Channel object identified by the numeric channel_id, or
create that object if it doesn't already exist. If channel_id is not
None but no channel exists for that id, will raise InvalidChannel. If
there are already too many channels open, will raise TooManyChannels.
If synchrono... |
346,433 | def setDebug( self, flag=True ):
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self | Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
... |
346,434 | def import_wd_atmcof(self, plfile, atmfile, wdidx, Nabun=19, Nlogg=11, Npb=25, Nints=4):
self.wd_data = libphoebe.wd_readdata(plfile, atmfile)
self.extern_wd_idx = wdidx
atmtab = np.reshape(self.wd_data[], (Nabu... | Parses WD's atmcof and reads in all Legendre polynomials for the
given passband.
@plfile: path and filename of atmcofplanck.dat
@atmfile: path and filename of atmcof.dat
@wdidx: WD index of the passed passband. This can be automated
but it's not a high priority.
... |
346,435 | def _normalize_tz(val):
match = _TZ_RE.match(val)
if match:
ts, tz = match.groups()
if len(tz) == 5:
return ts + tz
if len(tz) == 6:
return ts + tz[:3] + tz[4:]
if tz == "Z" or tz == "z":
return ts + "+0000"
else:
return ts + t... | Normalizes all valid ISO8601 time zone variants to the one python will
parse.
:val: a timestamp string without a timezone, or with a timezone in one of the ISO8601 accepted
formats. |
346,436 | def _merge_files(windows, nb_cpu):
windows = iter(windows)
merged = next(windows)
for chromosome_dfs in windows:
merged = merge_same_files(merged, chromosome_dfs, nb_cpu)
return merged | Merge lists of chromosome bin df chromosome-wise.
windows is an OrderedDict where the keys are files, the values are lists of
dfs, one per chromosome.
Returns a list of dataframes, one per chromosome, with the collective count
per bin for all files.
TODO: is it faster to merge all in one command? |
346,437 | def set_colors(self, text=, background=):
if self._multiline: self._widget.setStyleSheet("QTextEdit {background-color: "+str(background)+"; color: "+str(text)+"}")
else: self._widget.setStyleSheet("QLineEdit {background-color: "+str(background)+"; color: "+str(text)+"}") | Sets the colors of the text area. |
346,438 | def enable_gui(self, gui=None, app=None):
if gui in (None, GUI_NONE):
return self.disable_gui()
if gui in self.aliases:
return self.enable_gui(self.aliases[gui], app)
try:
gui_hook = self.guihooks[gui]
except KeyError:
... | Switch amongst GUI input hooks by name.
This is a higher level method than :meth:`set_inputhook` - it uses the
GUI name to look up a registered object which enables the input hook
for that GUI.
Parameters
----------
gui : optional, string or None
If None (or '... |
346,439 | def read_wwln(file):
tmp = pd.read_csv(file, parse_dates=True, header=None,
names=[, , , , , ])
list_dts = []
for dvals, tvals, in zip(tmp[], tmp[]):
list_dts.append(gen_datetime(dvals, tvals))
dtdf = pd.DataFrame(list_dts, columns=[])
result = pd.concat([dtdf... | Read WWLN file |
346,440 | def cli(ctx, group, user):
return ctx.gi.users.add_to_group(group, user) | Add a user to a group
Output:
an empty dictionary |
346,441 | def getImage(self):
self.lock.acquire()
image = self.data
self.lock.release()
return image | Returns last Image.
@return last JdeRobotTypes Image saved |
346,442 | def request_search(self, txt=None):
if self.checkBoxRegex.isChecked():
try:
re.compile(self.lineEditSearch.text(), re.DOTALL)
except sre_constants.error as e:
self._show_error(e)
return
else:
self._show_... | Requests a search operation.
:param txt: The text to replace. If None, the content of lineEditSearch
is used instead. |
346,443 | def create_from_binary(cls, binary_view):
attr_type, attr_len, non_resident, name_len, name_offset, flags, attr_id, \
content_len, content_offset, indexed_flag = cls._REPR.unpack(binary_view[:cls._REPR.size])
if name_len:
name = binary_view[name_offset:name_offset+(2*name_l... | Creates a new object AttributeHeader from a binary stream. The binary
stream can be represented by a byte string, bytearray or a memoryview of the
bytearray.
Args:
binary_view (memoryview of bytearray) - A binary stream with the
information of the attribute
... |
346,444 | def extract_variants(pattern):
v1, v2 = pattern.find(), pattern.find()
if v1 > -1 and v2 > v1:
variations = pattern[v1+1:v2].split()
variants = [pattern[:v1] + v + pattern[v2+1:] for v in variations]
else:
variants = [pattern]
return list(_deduplicate(variants)) | Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz). |
346,445 | def get_user_data(self):
settings = self.request.session.get()
saved_searches = self.request.session.get()
load_new_settings = False
if settings:
... | Extracts user data, either from user session or from
database (for each User, an InfoObject is used to
store data of a certain kind (e.g., user customization,
saved searches, etc.). If for a given user,
no InfoObject exists for a given type of user-specific data,
the default data... |
346,446 | def _get_application(self, subdomain):
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_application(subdomain=subdomain)
self.instances[subdomain] = app
return app | Return a WSGI application for subdomain. The subdomain is
passed to the create_application constructor as a keyword argument.
:param subdomain: Subdomain to get or create an application with |
346,447 | def start(self, attempts=5, timeout=2):
if not self.alive():
with LogTask( % self.name()):
net = self.libvirt_con.networkCreateXML(self._libvirt_xml())
if net is None:
raise RuntimeError(
%
... | Start the network, will check if the network is active ``attempts``
times, waiting ``timeout`` between each attempt.
Args:
attempts (int): number of attempts to check the network is active
timeout (int): timeout for each attempt
Returns:
None
Raise... |
346,448 | def attachFile(self, CorpNum, ItemCode, MgtKey, FilePath, UserID=None):
if MgtKey == None or MgtKey == "":
raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")
if FilePath == None or FilePath == "":
raise PopbillException(-99999999, "파일경로가 입력되지 않았습니다.")
i... | 파일 첨부
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
FilePath : 첨부파일의 경로
UserID :... |
346,449 | def has_no_jumps(neuron, max_distance=30.0, axis=):
bad_ids = []
axis = {: COLS.X, : COLS.Y, : COLS.Z, }[axis.lower()]
for neurite in iter_neurites(neuron):
section_segment = ((sec, seg) for sec in iter_sections(neurite)
for seg in iter_segments(sec))
for sec,... | Check if there are jumps (large movements in the `axis`)
Arguments:
neuron(Neuron): The neuron object to test
max_distance(float): value above which consecutive z-values are
considered a jump
axis(str): one of x/y/z, which axis to check for jumps
Returns:
CheckResult wi... |
346,450 | def cost_normalization(C, norm=None):
if norm == "median":
C /= float(np.median(C))
elif norm == "max":
C /= float(np.max(C))
elif norm == "log":
C = np.log(1 + C)
elif norm == "loglog":
C = np.log(1 + np.log(1 + C))
return C | Apply normalization to the loss matrix
Parameters
----------
C : np.array (n1, n2)
The cost matrix to normalize.
norm : str
type of normalization from 'median','max','log','loglog'. Any other
value do not normalize.
Returns
-------
C : np.array (n1, n2)
T... |
346,451 | def set_throttle_params(self, level=None, level_max=None):
self._set(, level)
self._set(, level_max)
return self._section | Throttling options.
* http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#throttling
* http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#loyalty
:param int level: Set throttling level (in milliseconds) for bad behaving vassals. Default: 1000.
:param int level_max: Set maximu... |
346,452 | def add_noFill_bgPr(self):
xml = (
% nsdecls(, )
)
bgPr = parse_xml(xml)
self._insert_bgPr(bgPr)
return bgPr | Return a new `p:bgPr` element with noFill properties. |
346,453 | def get_public_trades(self, time_frame=):
self._log()
return self._rest_client.get(
endpoint=,
params={: self.name, : time_frame}
) | Return public trades that were completed recently.
:param time_frame: Time frame. Allowed values are "minute" for trades
in the last minute, or "hour" for trades in the last hour (default:
"hour").
:type time_frame: str | unicode
:return: Public trades completed recently... |
346,454 | def trimmed_mean(self, p1, p2):
if not (p1 < p2):
raise ValueError("p1 must be between 0 and 100 and less than p2.")
min_count = p1 / 100. * self.n
max_count = p2 / 100. * self.n
trimmed_sum = trimmed_count = curr_count = 0
for i, c in enumerate(self.C.valu... | Computes the mean of the distribution between the two percentiles p1 and p2.
This is a modified algorithm than the one presented in the original t-Digest paper. |
346,455 | def translateprotocolmask(protocol):
pcscprotocol = 0
if None != protocol:
if CardConnection.T0_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T0
if CardConnection.T1_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T1
if CardConnection.RAW_protocol &... | Translate CardConnection protocol mask into PCSC protocol mask. |
346,456 | def build_document(html_content, base_href=None):
assert html_content is not None
if isinstance(html_content, unicode):
html_content = html_content.encode("utf8", "xmlcharrefreplace")
try:
document = document_fromstring(html_content, parser=UTF8_PARSER)
except (ParserError, XMLSyn... | Requires that the `html_content` not be None |
346,457 | def main_dump(paths, directory, dry_run):
table_map = get_table_map(paths)
for conn_name, conn_info in table_map.items():
inter = conn_info["interface"]
conn = inter.connection_config
table_names = conn_info["table_names"]
cmd = get_base_cmd("backup", inter, directory)
... | dump all or part of the prom data, currently only works on Postgres databases
basically just a wrapper around `dump backup` https://github.com/Jaymon/dump |
346,458 | def save(self, folder_path=, configuration_type=, vrf_management_name=None, return_artifact=False):
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(conf... | Backup 'startup-config' or 'running-config' from device to provided file_system [ftp|tftp]
Also possible to backup config to localhost
:param folder_path: tftp/ftp server where file be saved
:param configuration_type: type of configuration that will be saved (StartUp or Running)
:param ... |
346,459 | def model_counts_spectrum(self, name, logemin=None, logemax=None,
summed=False, weighted=False):
if logemin is None:
logemin = self.log_energies[0]
if logemax is None:
logemax = self.log_energies[-1]
if summed:
cs = np.... | Return the predicted number of model counts versus energy
for a given source and energy range. If summed=True return
the counts spectrum summed over all components otherwise
return a list of model spectra. If weighted=True return
the weighted version of the counts spectrum |
346,460 | def _add_bearer_token(self, uri, http_method=, body=None,
headers=None, token_placement=None):
if token_placement == AUTH_HEADER:
headers = tokens.prepare_bearer_headers(self.access_token, headers)
elif token_placement == URI_QUERY:
uri = token... | Add a bearer token to the request uri, body or authorization header. |
346,461 | def create_port_channel(self, nexus_host, vpc_nbr):
starttime = time.time()
vpc_str = str(vpc_nbr)
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_ADD_PORT_CH % (vpc_str, vpc_str, vpc_str)
self.send_edit_string(nexus_host, path_snip, body_snip)
self._apply_... | Creates port channel n on Nexus switch. |
346,462 | def format_iso_datetime(datetime_obj):
datetime_obj = localize_datetime(datetime_obj, pytz.utc)
if datetime_obj < MIN_DATE:
datetime_obj = MIN_DATE
elif datetime_obj > MAX_DATE:
datetime_obj = MAX_DATE
return datetime_obj.replace(tzinfo=None).strftime()[:-3] + | Formats the given datetime as a UTC-zoned ISO 8601 date string.
:param datetime_obj: The datetime object.
:type datetime_obj: datetime
:return: The datetime object in 8601 string form.
:rtype: datetime |
346,463 | def rmi(*names, **kwargs):
pre_images = images(all=True)
pre_tags = list_tags()
force = kwargs.get(, False)
noprune = not kwargs.get(, True)
errors = []
for name in names:
image_id = inspect_image(name)[]
try:
_client_wrapper(,
image_... | Removes an image
name
Name (in ``repo:tag`` notation) or ID of image.
force : False
If ``True``, the image will be removed even if the Minion has
containers created from that image
prune : True
If ``True``, untagged parent image layers will be removed as well, set
... |
346,464 | def write(self,
equities=None,
futures=None,
exchanges=None,
root_symbols=None,
equity_supplementary_mappings=None,
chunk_size=DEFAULT_CHUNK_SIZE):
if exchanges is None:
exchange_names = [
df... | Write asset metadata to a sqlite database.
Parameters
----------
equities : pd.DataFrame, optional
The equity metadata. The columns for this dataframe are:
symbol : str
The ticker symbol for this equity.
asset_name : str
... |
346,465 | def add_and_get(self, delta):
with self._reference.get_lock():
self._reference.value += delta
return self._reference.value | Atomically adds `delta` to the current value.
:param delta: The delta to add. |
346,466 | def update_delivery_note_item(self, delivery_note_item_id, delivery_note_item_dict):
return self._create_put_request(
resource=DELIVERY_NOTE_ITEMS,
billomat_id=delivery_note_item_id,
send_data=delivery_note_item_dict
) | Updates a delivery note item
:param delivery_note_item_id: delivery note item id
:param delivery_note_item_dict: dict
:return: dict |
346,467 | def configExternalRouter(self, P_Prefix, P_stable, R_Preference=0):
print % self.port
print P_Prefix
stable =
prefix = self.__convertIp6PrefixStringToIp6Address(str(P_Prefix))
try:
if R_Preference == 1:
prf =
elif R_Preference =... | configure border router with a given external route prefix entry
Args:
P_Prefix: IPv6 prefix for the route
P_Stable: is true if the external route prefix is stable network data
R_Preference: a two-bit signed integer indicating Router preference
1: h... |
346,468 | def __make_request_headers(self, teststep_dict, entry_json):
teststep_headers = {}
for header in entry_json["request"].get("headers", []):
if header["name"].lower() in IGNORE_REQUEST_HEADERS:
continue
teststep_headers[header["name"]] = header["value"]
... | parse HAR entry request headers, and make teststep headers.
header in IGNORE_REQUEST_HEADERS will be ignored.
Args:
entry_json (dict):
{
"request": {
"headers": [
{"name": "Host", "value": "httprunne... |
346,469 | def doblob(morphed, blobdet, img, anno=True):
keypoints = blobdet.detect(morphed)
nkey = len(keypoints)
kpsize = asarray([k.size for k in keypoints])
final = img.copy()
final = cv2.drawKeypoints(img, keypoints, outImage=final,
flags=cv2.DRAW_MATCHES_FLAGS_DRAW_R... | img: can be RGB (MxNx3) or gray (MxN)
http://docs.opencv.org/master/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html
http://docs.opencv.org/trunk/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html |
346,470 | def add_error(name=None, code=None, status=None):
if not name or not status or not code:
raise Exception("Can't create Exception class %s: you must set both name, status and code" % name)
myexception = type(name, (PyMacaronException, ), {"code": code, "status": status})
globals()[name] = myexce... | Create a new Exception class |
346,471 | def update_short(self, **kwargs):
for key, val in six.iteritems(kwargs):
self.update_arg(key, short=val) | Update the short optional arguments (those with one leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinis... |
346,472 | def users_list(self, permission_set=None, role=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users
api_path = "/api/v2/users.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
del kwargs["query"]
if per... | https://developer.zendesk.com/rest_api/docs/core/users#list-users |
346,473 | def fit_from_cfg(cls, choosers, chosen_fname, alternatives, cfgname, outcfgname=None):
logger.debug(.format(cfgname))
lcm = cls.from_yaml(str_or_buffer=cfgname)
lcm.fit(choosers, alternatives, choosers[chosen_fname])
for k, v in lcm._group.models.items():
print("LCM ... | Parameters
----------
choosers : DataFrame
A dataframe of rows of agents that have made choices.
chosen_fname : string
A string indicating the column in the choosers dataframe which
gives which alternative the choosers have chosen.
alternatives : DataF... |
346,474 | def plot(self, pcs=[1, 2], ax=None, cmap=None, cdict=None, legend=True, title=None, outfile=None):
pc1 = pcs[0] - 1
pc2 = pcs[1] - 1
if pc1 < 0 or pc2 > self.ncomponents - 1:
raise IPyradError("PCs are 1-indexed. 1 is min & {} is max".format(self.ncomponents))
... | Do the PCA and plot it.
Parameters
---------
pcs: list of ints
...
ax: matplotlib axis
...
cmap: matplotlib colormap
...
cdict: dictionary mapping pop names to colors
...
legend: boolean, whether or not to show the legend |
346,475 | def get_mors_with_properties(service_instance, object_type, property_list=None,
container_ref=None, traversal_spec=None,
local_properties=False):
content_args = [service_instance, object_type]
content_kwargs = {: property_list,
... | Returns a list containing properties and managed object references for the managed object.
service_instance
The Service Instance from which to obtain managed object references.
object_type
The type of content for which to obtain managed object references.
property_list
An optional... |
346,476 | def revision(directory, message, autogenerate, sql, head, splice, branch_label,
version_path, rev_id):
_revision(directory, message, autogenerate, sql, head, splice,
branch_label, version_path, rev_id) | Create a new revision file. |
346,477 | def clean(self, value):
if isinstance(value, six.string_types):
return value
elif isinstance(value, numbers.Number):
return str(value)
raise ParameterNotValidError | Cleans and returns the given value, or raises a ParameterNotValidError exception |
346,478 | def node_field_stats(self, nodes=None):
parts = [, , ]
if nodes:
paths = [, ",".join(nodes), , ]
path = make_path(*parts)
return self.conn._send_request(, path) | Retrieve field stats per node(s) or cluster wide
:ref:`nodes info <es-guide-reference-api-admin-cluster-nodes-stats>` API allows to retrieve one or more (or all)
the cluster nodes info about field data memory usage |
346,479 | def get_RaDecOffsets(ra1_deg, dec1_deg, ra2_deg, dec2_deg):
delta_ra_deg = ra1_deg - ra2_deg
adj = math.cos(math.radians(dec2_deg))
if delta_ra_deg > 180.0:
delta_ra_deg = (delta_ra_deg - 360.0) * adj
elif delta_ra_deg < -180.0:
delta_ra_deg = (delta_ra_deg + 360.0) * adj
else:
... | Calculate offset. |
346,480 | def set_value(self, name, value, PY2_frontend):
import cloudpickle
ns = self._get_reference_namespace(name)
svalue = value[0]
if PY2_frontend and not PY2:
svalue = bytes(svalue, )
dvalue = cloudpickle.l... | Set the value of a variable |
346,481 | def formatText(self, text):
format = self.inputFormat()
if format == XLineEdit.InputFormat.Normal:
return text
text = projex.text.nativestring(text)
if format == XLineEdit.InputFormat.CamelHump:
return projex.text.camelHump(text)
... | Formats the inputed text based on the input format assigned to this
line edit.
:param text | <str>
:return <str> | frormatted text |
346,482 | def summary(args):
p = OptionParser(summary.__doc__)
p.add_option("--strict", default=False, action="store_true",
help="Strict mode. Exclude gaps from covered base.")
p.add_option("--tabular", default=False, action="store_true",
help="Print succint tabular output")
... | %prog summary blastfile
Provide summary on id% and cov%, for both query and reference. Often used in
comparing genomes (based on NUCMER results). |
346,483 | def prune(self, var, value, removals):
"Rule out var=value."
self.curr_domains[var].remove(value)
if removals is not None: removals.append((var, value)) | Rule out var=value. |
346,484 | def post(url: str, *args, **kwargs) -> tuple:
return RequestsHelper.request(url, "post", *args, **kwargs) | Send a POST request. Returns a dict or :class:`requests.Response <Response>` |
346,485 | def setColumns(self, columns):
self.__columns = {}
for name, column in columns.items():
self.__columns[name] = column
column.setSchema(self) | Sets the columns that this schema uses.
:param columns | [<orb.Column>, ..] |
346,486 | def establish_ssh_connection(ip,
ssh_private_key_file,
ssh_user,
port,
attempts=5,
timeout=None):
client = paramiko.SSHClient()
client.set_missing_host_key_policy... | Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts. |
346,487 | def _encrypt(key_data, derived_key_information):
iv = os.urandom(16)
symmetric_key = derived_key_information[]
encryptor = Cipher(algorithms.AES(symmetric_key), modes.CTR(iv),
backend=default_backend()).encryptor()
ciphertext = encryptor.update(key_data.encode())... | Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm.
'derived_key_information' should contain a key strengthened by PBKDF2. The
key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode).
The HMAC of the ciphertext is generated to ensure the ciphertext has not been
... |
346,488 | def sample_row_keys(self):
data_client = self._instance._client.table_data_client
response_iterator = data_client.sample_row_keys(
self.name, app_profile_id=self._app_profile_id
)
return response_iterator | Read a sample of row keys in the table.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_sample_row_keys]
:end-before: [END bigtable_sample_row_keys]
The returned row keys will delimit contiguous sections of the table of
approxim... |
346,489 | def get(self, **kwargs):
old_state = self.state.copy()
self.merge_dict(kwargs)
result = rendering.InputRenderer.render_nomenclative(self)
self.merge_dict(old_state)
return result | Gets the string of the current name of the object
Returns (string): the name of the object |
346,490 | def uniform_pdf():
norm_const = 1.0
def pdf(x):
return norm_const * np.sin(np.pi/180.0 * x)
norm_dev = quad(pdf, 0.0, 180.0)[0]
norm_const /= norm_dev
return pdf | Uniform PDF for orientation averaging.
Returns:
pdf(x), a function that returns the value of the spherical Jacobian-
normalized uniform PDF. It is normalized for the interval [0, 180]. |
346,491 | def get_backend_router_id_from_hostname(self, hostname):
results = self.client.call(, )
return [result[] for result in results if result[] == hostname.lower()] | Finds the backend router Id that matches the hostname given
No way to use an objectFilter to find a backendRouter, so we have to search the hard way. |
346,492 | def runBrain(self, f):
if self.error:
self.error.value = ""
def wrapper():
self.brain_running.set()
try:
f()
except KeyboardInterrupt:
pass
except Exception as e:
if self... | Run a brain program in the background. |
346,493 | def total_return(self):
pxend = self.close
pxstart = pxend.shift(1).bfill()
return (1. + (pxend - pxstart + self.dvds.fillna(0)) / pxstart).cumprod() - 1 | http://en.wikipedia.org/wiki/Total_shareholder_return - mimics bloomberg total return |
346,494 | def edit(name, connection_uri, id_file="", o=[], config=None):
storm_ = get_storm_instance(config)
try:
if in name:
name = " ".join(name.split(","))
user, host, port = parse(
connection_uri,
user=get_default("user", storm_.defaults),
port=g... | Edits the related entry in ssh config. |
346,495 | def pore_diameter(elements, coordinates, com=None):
if com is None:
com = center_of_mass(elements, coordinates)
atom_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
dist_matrix = euclidean_distances(coordinates, com.reshape(1, -1))
re_dist_matrix = dist_matrix - atom_vdw
... | Return pore diameter of a molecule. |
346,496 | def connect(self, protocol=None):
if protocol is not None:
port = self.PORT_MAP[protocol]
else:
port = DAPAccess.PORT.DEFAULT
try:
self._link.connect(port)
except DAPAccess.Error as exc:
six.raise_from(self._conve... | Initialize DAP IO pins for JTAG or SWD |
346,497 | def Analyze(self, data):
if not self._rules:
return
try:
self._matches = self._rules.match(data=data, timeout=self._MATCH_TIMEOUT)
except yara.YaraTimeoutError:
logger.error(.format(
self._MATCH_TIMEOUT))
except yara.YaraError as exception:
logger.error(.format(
... | Analyzes a block of data, attempting to match Yara rules to it.
Args:
data(bytes): a block of data. |
346,498 | def category(soup):
category = []
tags = raw_parser.category(soup)
for tag in tags:
category.append(node_text(tag))
return category | Find the category from subject areas |
346,499 | def color_ramp(self, size):
color = PALETTE.get(self.option.palette, {})
color = color.get(self.term.colors, None)
color_ramp = []
if color is not None:
ratio = len(color) / float(size)
for i in range(int(size)):
color_ramp.append(self.ter... | Generate a color ramp for the current screen height. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.