Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
14,300 | def read_mnist_images(filename, dtype=None):
with gzip.open(filename, ) as f:
magic, number, rows, cols = struct.unpack(, f.read(16))
if magic != MNIST_IMAGE_MAGIC:
raise ValueError("Wrong magic number reading MNIST image file")
array = numpy.frombuffer(f.read(), dtype=)
... | Read MNIST images from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read images.
dtype : 'float32', 'float64', or 'bool'
If unspecified, images will be returned in their original
unsigned byte format.
Returns
-------
... |
14,301 | def get_user_id(self):
if self._user_id is None:
self._user_id = self.get_user_data()[]
return self._user_id | Returns "id" of a OneDrive user. |
14,302 | def register(self, model, handler=None):
from permission.handlers import PermissionHandler
if model._meta.abstract:
raise ImproperlyConfigured(
% model)
if model in self._registry:
raise KeyError("A permission handler cla... | Register a permission handler to the model
Parameters
----------
model : django model class
A django model class
handler : permission handler class, string, or None
A permission handler class or a dotted path
Raises
------
ImproperlyConfi... |
14,303 | def action_is_satisfied(action):
num_consumed_args = _num_consumed_args.get(action, 0)
if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]:
return True
if action.nargs == ONE_OR_MORE:
return num_consumed_args >= 1
if action.nargs == PARSER:
return False... | Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise. |
14,304 | def _update_solution_data(self, s):
x = s["x"]
Va = x[self._Va.i1:self._Va.iN + 1]
Vm = x[self._Vm.i1:self._Vm.iN + 1]
Pg = x[self._Pg.i1:self._Pg.iN + 1]
Qg = x[self._Qg.i1:self._Qg.iN + 1]
return Va, Vm, Pg, Qg | Returns the voltage angle and generator set-point vectors. |
14,305 | def split(self, verbose=None, end_in_new_line=None):
elapsed_time = self.get_elapsed_time()
self.split_elapsed_time.append(elapsed_time)
self._cumulative_elapsed_time += elapsed_time
self._elapsed_time = datetime.timedelta()
if verbose is None:
verbose = self... | Save the elapsed time of the current split and restart the stopwatch.
The current elapsed time will be appended to :attr:`split_elapsed_time`.
If the stopwatch is paused, then it will remain paused.
Otherwise, it will continue running.
Parameters
----------
verbose : Op... |
14,306 | def update_timestamps(self, chan_id, ts):
try:
self.last_update[chan_id] = ts
except KeyError:
self.log.warning("Attempted ts update of channel %s, but channel "
"not present anymore.",
self.channel_directory[chan... | Updates the timestamp for the given channel id.
:param chan_id:
:param ts:
:return: |
14,307 | def _create_tokens_for_next_line_dent(self, newline_token):
indent_delta = self._get_next_line_indent_delta(newline_token)
if indent_delta is None or indent_delta == 0:
return None
dent_type = if indent_delta > 0 else
dent_token = _create... | Starting from a newline token that isn't followed by another newline
token, returns any indent or dedent tokens that immediately follow.
If indentation doesn't change, returns None. |
14,308 | def best_match(self, seqs, scan_rc=True):
self.set_threshold(threshold=0.0)
for matches in self.scan(seqs, 1, scan_rc):
yield [m[0] for m in matches] | give the best match of each motif in each sequence
returns an iterator of nested lists containing tuples:
(score, position, strand) |
14,309 | def zip(*args, **kwargs):
args = [list(iterable) for iterable in args]
n = max(map(len, args))
v = kwargs.get("default", None)
return _zip(*[i + [v] * (n - len(i)) for i in args]) | Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables (or default if too short). |
14,310 | def check_stops(
feed: "Feed", *, as_df: bool = False, include_warnings: bool = False
) -> List:
table = "stops"
problems = []
if feed.stops is None:
problems.append(["error", "Missing table", table, []])
else:
f = feed.stops.copy()
problems = check_for_required_co... | Analog of :func:`check_agency` for ``feed.stops``. |
14,311 | def init_app(self, app):
if app.config.MONGO_URIS and isinstance(app.config.MONGO_URIS, dict):
self.MONGO_URIS = app.config.MONGO_URIS
self.app = app
else:
raise ValueError(
"nonstandard sanic config MONGO_URIS,MONGO_URIS must be a Dict[dbnam... | 绑定app |
14,312 | def paginate_queryset(self, queryset, request, view=None):
result = super(MultipleModelLimitOffsetPagination, self).paginate_queryset(queryset, request, view)
try:
if self.max_count < self.count:
self.max_count = self.count
except AttributeError:
... | adds `max_count` as a running tally of the largest table size. Used for calculating
next/previous links later |
14,313 | def is_interface_up(interface):
if sys.platform.startswith("linux"):
if interface not in psutil.net_if_addrs():
return False
import fcntl
SIOCGIFFLAGS = 0x8913
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
result = fc... | Checks if an interface is up.
:param interface: interface name
:returns: boolean |
14,314 | def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post):
filehash = sha1sum(filename)
files = {: open(filename, )}
payload = {
: filehash,
: os.path.basename(filename),
: token,
: nonce,
}
return method("%s/sign/%s" % (baseurl, form... | Uploads file (given by `filename`) to server at `baseurl`.
`sesson_key` and `nonce` are string values that get passed as POST
parameters. |
14,315 | def _get_magnitude_term(self, C, mag):
if mag >= self.CONSTS["Mh"]:
return C["e1"] + C["b3"] * (mag - self.CONSTS["Mh"])
else:
return C["e1"] + (C["b1"] * (mag - self.CONSTS["Mh"])) +\
(C["b2"] * (mag - self.CONSTS["Mh"]) ** 2.) | Returns the magnitude scaling term - equation 3 |
14,316 | def post(self, object_type, object_id):
if object_id == 0:
return Response(status=404)
tagged_objects = []
for name in request.get_json(force=True):
if in name:
type_name = name.split(, 1)[0]
type_ = TagTypes[type_name]
... | Add new tags to an object. |
14,317 | def express_route_ports_locations(self):
api_version = self._get_api_version()
if api_version == :
from .v2018_08_01.operations import ExpressRoutePortsLocationsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(a... | Instance depends on the API version:
* 2018-08-01: :class:`ExpressRoutePortsLocationsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRoutePortsLocationsOperations>` |
14,318 | def render(self, doc, context=None, math_option=False, img_path=,
css_path=CSS_PATH):
if self.wait():
self.doc = doc
self.context = context
self.math_option = math_option
self.img_path = img_path
self.css_path ... | Start thread to render a given documentation |
14,319 | def get_z(self, var, coords=None):
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, , coords)
if coord is not None:
return coord
zname = self.get_zname(var)
if zname is not None:
return coords.get(zname)
return None | Get the vertical (z-) coordinate of a variable
This method searches for the z-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Z', otherwise it looks whether there is an intersection
between the :attr:`z` attribute and... |
14,320 | def add_label(self, query_params=None):
list_json = self.fetch_json(
uri_path=self.base_uri + ,
http_method=,
query_params=query_params or {}
)
return self.create_label(list_json) | Create a label for a board. Returns a new Label object. |
14,321 | def time_series(
self,
start_date=,
end_date=,
precision=None,
distrib=None,
tzinfo=None):
start_date = self._parse_date_time(start_date, tzinfo=tzinfo)
end_date = self._parse_date_time(end_date, tzinfo=tzinfo)
if ... | Returns a generator yielding tuples of ``(<datetime>, <value>)``.
The data points will start at ``start_date``, and be at every time interval specified by
``precision``.
``distrib`` is a callable that accepts ``<datetime>`` and returns ``<value>`` |
14,322 | def from_sites(cls, sites, charge=None, validate_proximity=False,
to_unit_cell=False):
if len(sites) < 1:
raise ValueError("You need at least one site to construct a %s" %
cls)
prop_keys = []
props = {}
lattice = None
... | Convenience constructor to make a Structure from a list of sites.
Args:
sites: Sequence of PeriodicSites. Sites must have the same
lattice.
validate_proximity (bool): Whether to check if there are sites
that are less than 0.01 Ang apart. Defaults to False... |
14,323 | def _terminalSymbolsGenerator(self):
py2 = sys.version[0] <
UPPAs = list(list(range(0xE000,0xF8FF+1)) + list(range(0xF0000,0xFFFFD+1)) + list(range(0x100000, 0x10FFFD+1)))
for i in UPPAs:
if py2:
yield(unichr(i))
else:
yield(chr(i... | Generator of unique terminal symbols used for building the Generalized Suffix Tree.
Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols
are not part of the input string. |
14,324 | def stream_url(self, item, *, device_id=None, quality=, session_token=None):
if device_id is None:
device_id = self.device_id
if in item:
response = self._call(
mc_calls.PodcastEpisodeStreamURL,
item[],
quality=quality,
device_id=device_id
)
elif in item:
response = self._ca... | Get a URL to stream a podcast episode, library song, station_song, or store song.
Note:
Streaming requires a ``device_id`` from a valid, linked mobile device.
Parameters:
item (str): A podcast episode, library song, station_song, or store song.
A Google Music subscription is required to stream store son... |
14,325 | def get_filename(self, task, default_ext):
url_path = urlparse(task[])[2]
extension = url_path.split()[-1] if in url_path else default_ext
file_idx = self.fetched_num + self.file_idx_offset
return .format(file_idx, extension) | Set the path where the image will be saved.
The default strategy is to use an increasing 6-digit number as
the filename. You can override this method if you want to set custom
naming rules. The file extension is kept if it can be obtained from
the url, otherwise ``default_ext`` is used ... |
14,326 | def get_consistent_resource(self):
http_client = HttpClient()
response, _ = http_client.get(routes.url(routes.PAYMENT_RESOURCE, resource_id=self.id))
return Payment(**response) | :return a payment that you can trust.
:rtype Payment |
14,327 | def write_grid_tpl(name, tpl_file, suffix, zn_array=None, shape=None,
spatial_reference=None,longnames=False):
if shape is None and zn_array is None:
raise Exception("must pass either zn_array or shape")
elif shape is None:
shape = zn_array.shape
parnme, x, y = [], ... | write a grid-based template file
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write - include path
zn_array : numpy.ndarray
an array used to skip inactive cells
Returns
-------
df : pandas.DataFrame
a datafr... |
14,328 | def abs_timedelta(delta):
if delta.days < 0:
now = _now()
return now - (now + delta)
return delta | Returns an "absolute" value for a timedelta, always representing a
time distance. |
14,329 | def attributes_js(cls, attributes):
assign_template =
conditional_template =
code =
for key, attr_path in sorted(attributes.items()):
data_assign = .format(key=key)
attrs = attr_path.split()
obj_name = attrs[0]
attr_getters = .j... | Generates JS code to look up attributes on JS objects from
an attributes specification dictionary. If the specification
references a plotting particular plotting handle it will also
generate JS code to get the ID of the object.
Simple example (when referencing cb_data or cb_obj):
... |
14,330 | def linspace(start, stop, num, decimals=18):
start = float(start)
stop = float(stop)
if abs(start - stop) <= 10e-8:
return [start]
num = int(num)
if num > 1:
div = num - 1
delta = stop - start
return [float(("{:." + str(decimals) + "f}").format((start + (float(x)... | Returns a list of evenly spaced numbers over a specified interval.
Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py
:param start: starting value
:type start: float
:param stop: end value
:type stop: float
:param num: number of samp... |
14,331 | def setup_signals(self, ):
self.duplicate_tb.clicked.connect(self.duplicate)
self.delete_tb.clicked.connect(self.delete)
self.load_tb.clicked.connect(self.load)
self.unload_tb.clicked.connect(self.unload)
self.reference_tb.clicked.connect(self.reference)
self.imp... | Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None |
14,332 | def _get_stddevs(self, C, stddev_types, num_sites, mag):
stddevs = []
sigma = (C[] + C[] * mag) if mag < 7.2 else C[]
vals = sigma * np.ones((num_sites))
for _ in stddev_types:
stddevs.append(vals)
return stddevs | Returns standard deviation as defined in equation 23, page 2291
(Tavakoli and Pezeshk, 2005) |
14,333 | def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, verbose=True):
if iface is None:
iface = conf.iface
argv = [conf.prog.tcpreplay, "--intf1=%s" % iface ]
if pps is not None:
argv.append("--pps=%i" % pps)
elif mbps is not None:
argv.ap... | Send packets at layer 2 using tcpreplay for performance
pps: packets per second
mpbs: MBits per second
realtime: use packet's timestamp, bending time with realtime value
loop: number of times to process the packet list
file_cache: cache packets in RAM instead of reading from disk at each iteration
... |
14,334 | def extract_common_fields(self, data):
email = None
for curr_email in data.get("emails", []):
email = email or curr_email.get("email")
if curr_email.get("verified", False) and \
curr_email.get("primary", False):
email = curr_email.get(... | Extract fields from a basic user query. |
14,335 | def sphere_pos(self, x):
c = 0.0
if x[0] < c:
return np.nan
return -c**2 + sum((x + 0)**2) | Sphere (squared norm) test objective function |
14,336 | def get_location(self,callb=None):
if self.location is None:
mypartial=partial(self.resp_set_location)
if callb:
mycallb=lambda x,y:(mypartial(y),callb(x,y))
else:
mycallb=lambda x,y:mypartial(y)
response = self.req_with_re... | Convenience method to request the location from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that callb be executed when a response is received.... |
14,337 | def get_host_lock(url):
hostname = get_hostname(url)
return host_locks.setdefault(hostname, threading.Lock()) | Get lock object for given URL host. |
14,338 | def merge(self, conflicted, tables=[], diff_only=True):
if os.path.isfile(conflicted):
con, master, reassign = Database(conflicted), self.list("PRAGMA database_list").fetchall()[0][2], {}
con.modify("ATTACH DATABASE AS m".format(master), verbose=False)
... | Merges specific **tables** or all tables of **conflicted** database into the master database.
Parameters
----------
conflicted: str
The path of the SQL database to be merged into the master.
tables: list (optional)
The list of tables to merge. If None, all tables... |
14,339 | def validate_data_table(data_table, sed=None):
if isinstance(data_table, Table) or isinstance(data_table, QTable):
data_table = [data_table]
try:
for dt in data_table:
if not isinstance(dt, Table) and not isinstance(dt, QTable):
raise TypeError(
... | Validate all columns of a data table. If a list of tables is passed, all
tables will be validated and then concatenated
Parameters
----------
data_table : `astropy.table.Table` or list of `astropy.table.Table`.
sed : bool, optional
Whether to convert the fluxes to SED. If unset, all data ... |
14,340 | def render_footer(self, ctx, data):
if self.staticContent is None:
return ctx.tag
header = self.staticContent.getFooter()
if header is not None:
return ctx.tag[header]
else:
return ctx.tag | Render any required static content in the footer, from the C{staticContent}
attribute of this page. |
14,341 | def id_lookup(paper_id, idtype):
if idtype not in (, , ):
raise ValueError("Invalid idtype %s; must be , , "
"or ." % idtype)
ids = {: None, : None, : None}
pmc_id_results = pmc_client.id_lookup(paper_id, idtype)
ids[] = pmc_id_results.get()
ids[] = p... | Take an ID of type PMID, PMCID, or DOI and lookup the other IDs.
If the DOI is not found in Pubmed, try to obtain the DOI by doing a
reverse-lookup of the DOI in CrossRef using article metadata.
Parameters
----------
paper_id : str
ID of the article.
idtype : str
Type of the ID... |
14,342 | def get_mime_message(subject, text):
message = MIMEText(
"<html>" +
str(text).replace("\n", "<br>") +
"</html>", "html"
)
message["subject"] = str(subject)
return message | Creates MIME message
:param subject: Subject of email
:param text: Email content
:return: Email formatted as HTML ready to be sent |
14,343 | def get_cache_key(brain_or_object):
key = [
get_portal_type(brain_or_object),
get_id(brain_or_object),
get_uid(brain_or_object),
get_url(brain_or_object),
get_modification_date(brain_or_object).micros(),
]
return "-".join(map(lambda x: str(x), k... | Generate a cache key for a common brain or object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Cache Key
:rtype: str |
14,344 | def new_portfolio(self, portfolio_cookie=None):
_portfolio = QA_Portfolio(
user_cookie=self.user_cookie,
portfolio_cookie=portfolio_cookie
)
if _portfolio.portfolio_cookie not in self.portfolio_list.keys():
self.portfolio_list[_portfolio.portfolio_coo... | 根据 self.user_cookie 创建一个 portfolio
:return:
如果存在 返回 新建的 QA_Portfolio
如果已经存在 返回 这个portfolio |
14,345 | def _api_handler(self, *args, **kwargs):
keyword_arguments = {}
keyword_arguments.update(self.keywords)
keyword_arguments.update(kwargs)
return api_handler(*args, **keyword_arguments) | Thin wrapper around api_handler from `indicoio.utils.api` to add in stored keyword argument to the JSON body |
14,346 | def display_grid_scores(grid_scores, top=None):
grid_scores = sorted(grid_scores, key=lambda x: x[1], reverse=True)
if top is not None:
grid_scores = grid_scores[:top]
_, best_mean, best_scores = grid_scores[0]
threshold = best_mean - 2 * sem(best_scores)
for params, ... | Helper function to format a report on a grid of scores |
14,347 | def _get_nameservers(domain):
nameservers = []
rdtypes_ns = [, ]
rdtypes_ip = [, ]
for rdtype_ns in rdtypes_ns:
for rdata_ns in Provider._dns_lookup(domain, rdtype_ns):
for rdtype_ip in rdtypes_ip:
for rdata_ip in Provider._dns_loo... | Looks for domain nameservers and returns the IPs of the nameservers as a list.
The list is empty, if no nameservers were found. Needed associated domain zone
name for lookup. |
14,348 | def get_fastq_files(directory, lane, fc_name):
files = glob.glob(os.path.join(directory, "%s_*%s*txt*" % (lane, fc_name)))
files.sort()
if len(files) > 2 or len(files) == 0:
raise ValueError("Did not find correct files for %s %s %s %s" %
(directory, lane, fc_name, files))
re... | Retrieve fastq files for the given lane, ready to process. |
14,349 | def visit_tryfinally(self, node, parent):
newnode = nodes.TryFinally(node.lineno, node.col_offset, parent)
newnode.postinit(
[self.visit(child, newnode) for child in node.body],
[self.visit(n, newnode) for n in node.finalbody],
)
return newnode | visit a TryFinally node by returning a fresh instance of it |
14,350 | def _set_prior(self, prior):
if prior is None:
self._prior = None
else:
try:
_ = prior(self.value)
except:
raise NotCallableOrErrorInCall("Could not call the provided prior. " +
... | Set prior for this parameter. The prior must be a function accepting the current value of the parameter
as input and giving the probability density as output. |
14,351 | def consecutiveness(password, consecutive_length=3):
consec = 0
for i in range(len(password) - consecutive_length):
if all([char.islower() for char in password[i:i+consecutive_length]]):
consec += 1
elif all([char.islower() for char in password[i:i+consec... | Consecutiveness is the enemy of entropy, but makes it easier to remember.
:param str password:
:param int consecutive_length: length of the segment to be uniform to consider loss of entropy
:param int base_length: usual length of the password
:return int: in range 0-1
>>> Complex... |
14,352 | def parse_root(raw):
"Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary."
if sys.version < :
fp = StringIO(raw)
else:
fp = BytesIO(raw.encode())
for event, element in etree.iterparse(fp, events=(,)):
retu... | Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary. |
14,353 | def taxids(self):
r = self.session.query(distinct(models.Entry.taxid)).all()
return [x[0] for x in r] | Distinct NCBI taxonomy identifiers (``taxid``) in :class:`.models.Entry`
:return: NCBI taxonomy identifiers
:rtype: list[int] |
14,354 | def typed_encode(self, r):
try:
value = r.get()
if "json" in r:
value = json2value(r["json"])
elif is_data(value) or value != None:
pass
else:
from mo_logs import Log
raise Log.error("Expecti... | :param record: expecting id and value properties
:return: dict with id and json properties |
14,355 | def exception_handler(job, *exc_info):
job_info = job.to_dict()
rollbar.report_exc_info(exc_info, extra_data=extra_data, payload_data=payload_data)
return True | Called by RQ when there is a failure in a worker.
NOTE: Make sure that in your RQ worker process, rollbar.init() has been called with
handler='blocking'. The default handler, 'thread', does not work from inside an RQ worker. |
14,356 | def validate(nanopub: dict, error_level: str = "WARNING") -> Tuple[str, str, str]:
v = []
bel_version = config["bel"]["lang"]["default_bel_version"]
try:
if not isinstance(nanopub["nanopub"]["assertions"], list):
msg = "Assertions must be a list/array"
v.app... | Validate Nanopub
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
The validation result is a list of objects containing
{
'level': 'Warning|Error',
'section': 'Assertion|Annotation|Structure',
... |
14,357 | def createKeyboardTab(self):
_keyboardList = [
, , , , , , , ,
, ,
, , , , , , , ,
, ,
, , , , , , , ,
,
, , , , , , , ,
, ,
]
for keyboard in _keyboardList:
_cpb = ControlPanel... | KEYBOARD |
14,358 | def stage_http_response2(self, payload):
if not self._http_response_version and not payload:
return
if self.enabled and self.http_detail_level is not None and \
self.httplogger.isEnabledFor(logging.DEBUG):
if self._http_response_headers... | Log complete http response, including response1 and payload |
14,359 | def copy_format(self):
row, col, tab = self.grid.actions.cursor
code_array = self.grid.code_array
new_cell_attributes = []
selection = self.get_selection()
if not selection:
selection = Selection([], [], [], [], [(row, col)])
... | Copies the format of the selected cells to the Clipboard
Cells are shifted so that the top left bbox corner is at 0,0 |
14,360 | def handle_fail_rcs(self, req):
try:
logger.debug("HTTP Status Code: %s", req.status_code)
logger.debug("HTTP Response Text: %s", req.text)
logger.debug("HTTP Response Reason: %s", req.reason)
logger.debug("HTTP Response Content: %s", req.content)
... | Bail out if we get a 401 and leave a message |
14,361 | def _to_dict(self):
_dict = {}
if hasattr(self,
) and self.document_retrieval_strategy is not None:
_dict[
] = self.document_retrieval_strategy
return _dict | Return a json dictionary representing this model. |
14,362 | def create(self, message, mid=None, age=60, force=True):
with self.session_lock:
if not hasattr(message, "id"):
message.__setattr__("id", "event-%s" % (uuid.uuid4().hex,))
if self.session_list.get(message.id, None) is not None:
if force is False:
... | create session
force if you pass `force = False`, it may raise SessionError
due to duplicate message id |
14,363 | def restore_gc_state():
old_isenabled = gc.isenabled()
old_flags = gc.get_debug()
try:
yield
finally:
gc.set_debug(old_flags)
(gc.enable if old_isenabled else gc.disable)() | Restore the garbage collector state on leaving the with block. |
14,364 | def _get_axis_data(self, bunch, dim, cluster_id=None, load_all=None):
if dim in self.attributes:
return self.attributes[dim](cluster_id, load_all=load_all)
masks = bunch.get(, None)
assert dim not in self.attributes
s =
c_rel = int(dim[:-1])
... | Extract the points from the data on a given dimension.
bunch is returned by the features() function.
dim is the string specifying the dimensions to extract for the data. |
14,365 | def distb(self, tb=None, file=None):
if tb is None:
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError("no last traceback to disassemble")
while tb.tb_next: tb = tb.tb_next
self.disassemble(tb.tb_frame.f_cod... | Disassemble a traceback (default: last traceback). |
14,366 | def plot_magseries(times,
mags,
magsarefluxes=False,
errs=None,
out=None,
sigclip=30.0,
normto=,
normmingap=4.0,
timebin=None,
yrange=None,
... | This plots a magnitude/flux time-series.
Parameters
----------
times,mags : np.array
The mag/flux time-series to plot as a function of time.
magsarefluxes : bool
Indicates if the input `mags` array is actually an array of flux
measurements instead of magnitude measurements. If... |
14,367 | def frequency_psd_from_qd(self, tau0=1.0):
a = self.b + 2.0
return self.qd*2.0*pow(2.0*np.pi, a)*pow(tau0, a-1.0) | return frequency power spectral density coefficient h_a
for the noise type defined by (qd, b, tau0)
Colored noise generated with (qd, b, tau0) parameters will
show a frequency power spectral density of
S_y(f) = Frequency_PSD(f) = h_a * f^a
where the slope a ... |
14,368 | def positionToIntensityUncertainty(image, sx, sy, kernelSize=None):
psf_is_const = not isinstance(sx, np.ndarray)
if not psf_is_const:
assert image.shape == sx.shape == sy.shape, \
"Image and position uncertainty maps need to have same size"
if kernelSize is None:
... | calculates the estimated standard deviation map from the changes
of neighbouring pixels from a center pixel within a point spread function
defined by a std.dev. in x and y taken from the (sx, sy) maps
sx,sy -> either 2d array of same shape as [image]
of single values |
14,369 | def get_env_credential(env=):
url = .join([API_URL, , env])
credential_response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
assert credential_response.ok,
credential = credential_response.json()
LOG.debug(, credential)
return credential | Get Account Credential from Spinnaker for *env*.
Args:
env (str): Environment name to find credentials for.
Returns:
dict: Complete credentials for *env*::
{
'accountId': '123098123',
'accountType': 'dev',
'assumeRole': 'role/spinnak... |
14,370 | def references(self, env, object_name, model, assoc_class,
result_class_name, role, result_role, keys_only):
pass | Instrument Associations.
All four association-related operations (Associators, AssociatorNames,
References, ReferenceNames) are mapped to this method.
This method is a python generator
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
object_n... |
14,371 | def nvm_primer():
print( +
cyan())
print( +
cyan() + +
cyan() + +
cyan() +
+
cyan() +
)
print( +
cyan())
print( +
cyan())
print() | Getting started with nvm (cf. https://github.com/creationix/nvm#usage). |
14,372 | def _create_keywords_wizard_action(self):
icon = resources_path(, , )
self.action_keywords_wizard = QAction(
QIcon(icon),
self.tr(),
self.iface.mainWindow())
self.action_keywords_wizard.setStatusTip(self.tr(
))
self.action_keywords... | Create action for keywords creation wizard. |
14,373 | def clean_videos(self):
if self.videos:
self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)] | Validates that all values in the video list are integer ids and removes all None values. |
14,374 | def _sweep(self):
while self.running:
for am in list(self.activeMeasurements):
now = datetime.datetime.utcnow()
recordingDeviceCount = len(am.recordingDevices)
if recordingDeviceCount > 0:
if all(entry[] ==... | Checks the state of each measurement and verifies their state, if an active measurement is now complete then
passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts.
:return: |
14,375 | def getFreeEnergyDifferences(self, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False):
f_i = np.matrix(self.f_k)
Deltaf_ij = f_i - f_i.transpose()
self._zerosamestates(Deltaf_ij)
returns = []
returns.append... | Get the dimensionless free energy differences and uncertainties among all thermodynamic states.
Parameters
----------
compute_uncertainty : bool, optional
If False, the uncertainties will not be computed (default: True)
uncertainty_method : string, optional
Choi... |
14,376 | def emit(self, record):
try:
if self.max_messages:
p = self.redis_client.pipeline()
p.rpush(self.key, self.format(record))
p.ltrim(self.key, -self.max_messages, -1)
p.execute()
else:
self.redis_clien... | Publish record to redis logging list |
14,377 | def monkey_patch():
ozmq = __import__()
ozmq.Socket = zmq.Socket
ozmq.Context = zmq.Context
ozmq.Poller = zmq.Poller
ioloop = __import__()
ioloop.Poller = zmq.Poller | Monkey patches `zmq.Context` and `zmq.Socket`
If test_suite is True, the pyzmq test suite will be patched for
compatibility as well. |
14,378 | def advance_job_status(namespace: str, job: Job, duration: float,
err: Optional[Exception]):
duration = human_duration(duration)
if not err:
job.status = JobStatus.SUCCEEDED
logger.info(, job, duration)
return
if job.should_retry:
job.status = Job... | Advance the status of a job depending on its execution.
This function is called after a job has been executed. It calculates its
next status and calls the appropriate signals. |
14,379 | def insert(self):
self.default_val = 0
return self.interface.insert(
self.schema,
self.fields
)
return self.interface.insert(self.schema, self.fields) | persist the .fields |
14,380 | def _get_leftMargin(self):
bounds = self.bounds
if bounds is None:
return None
xMin, yMin, xMax, yMax = bounds
return xMin | This must return an int or float.
If the glyph has no outlines, this must return `None`.
Subclasses may override this method. |
14,381 | def cbday_roll(self):
cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)
if self._prefix.endswith():
roll_func = cbday.rollforward
else:
roll_func = cbday.rollback
return roll_func | Define default roll function to be called in apply method. |
14,382 | def colored_level_name(self, levelname):
if self.colors_disabled:
return self.plain_levelname_format.format(levelname)
else:
return self.colored_levelname_format.format(self.color_map[levelname], levelname) | Colors the logging level in the logging record |
14,383 | def create_port(self, context, network_id, port_id, **kwargs):
LOG.info("create_port %s %s %s" % (context.tenant_id, network_id,
port_id))
if not kwargs.get():
raise IronicException(msg=)
base_net_driver = kwargs[]
... | Create a port.
:param context: neutron api request context.
:param network_id: neutron network id.
:param port_id: neutron port id.
:param kwargs:
required keys - device_id: neutron port device_id (instance_id)
instance_node_id: nova hypervisor ho... |
14,384 | def series_to_yaml_safe(series, ordered=False):
index = series.index.to_native_types(quoting=True)
values = series.values.tolist()
if ordered:
return OrderedDict(
tuple((k, v)) for k, v in zip(index, values))
else:
return {i: v for i, v in zip(index, values)} | Convert a pandas Series to a dict that will survive YAML serialization
and re-conversion back to a Series.
Parameters
----------
series : pandas.Series
ordered: bool, optional, default False
If True, an OrderedDict is returned.
Returns
-------
safe : dict or OrderedDict |
14,385 | def drawItem(self, item, painter, option):
dataset = item.dataset()
painter.save()
painter.setRenderHint(painter.Antialiasing)
pen = QPen(dataset.color())
pen.setWidth(0.75)
painter.setPen(pen)
for path in item.buildD... | Draws the inputed item as a bar graph.
:param item | <XChartDatasetItem>
painter | <QPainter>
option | <QStyleOptionGraphicsItem> |
14,386 | def negative_gradient(self, y, y_pred, sample_weight=None, **kwargs):
pred_time = y[] - y_pred.ravel()
mask = (pred_time > 0) | y[]
ret = numpy.zeros(y[].shape[0])
ret[mask] = pred_time.compress(mask, axis=0)
if sample_weight is not None:
ret *= sample_weight... | Negative gradient of partial likelihood
Parameters
---------
y : tuple, len = 2
First element is boolean event indicator and second element survival/censoring time.
y_pred : np.ndarray, shape=(n,):
The predictions. |
14,387 | def firmware_manifest_retrieve(self, manifest_id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.firmware_manifest_retrieve_with_http_info(manifest_id, **kwargs)
else:
(data) = self.firmware_manifest_retrieve_with_http_info(manifest_id, **kwargs)
... | Get a manifest # noqa: E501
Retrieve a firmware manifest. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.firmware_manifest_retrieve(manifest_id, asynchronous=True)
>>> r... |
14,388 | def validate(self, input_string):
parsed_url = urlparse(url=input_string)
return bool(parsed_url.scheme and parsed_url.netloc) | Validate url
:return: True if match / False otherwise |
14,389 | def approve(group_id, user_id):
membership = Membership.query.get_or_404((user_id, group_id))
group = membership.group
if group.can_edit(current_user):
try:
membership.accept()
except Exception as e:
flash(str(e), )
return redirect(url_for(, group_id... | Approve a user. |
14,390 | def pattern_match(pattern, string):
def backtrack(pattern, string, dic):
if len(pattern) == 0 and len(string) > 0:
return False
if len(pattern) == len(string) == 0:
return True
for end in range(1, len(string)-len(pattern)+2):
if pattern[0] not in d... | :type pattern: str
:type string: str
:rtype: bool |
14,391 | async def _get_packet_from_stream(self, stream, existing_data, got_first_packet=True, psml_structure=None):
if self.use_json:
packet, existing_data = self._extract_packet_json_from_data(existing_data,
got_first... | A coroutine which returns a single packet if it can be read from the given StreamReader.
:return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data to create
a packet. remaining_data is the leftover data which was not enough to create a packet from.
:r... |
14,392 | def dev_parameters_vs_axis(dnaRef, dnaSubj, parameter, bp, axis=, bp_range=True, windows=10, err_type=, tool=):
RefParam, ref_bp_idx = dnaRef.get_parameters(parameter, bp, bp_range)
RefAxis, dummy = dnaRef.get_parameters(
.format(axis), bp, bp_range)
SubjParam, subj_bp_idx = dnaSubj.get_parame... | To calculate deviation in the given parameters of a Subject DNA to Reference DNA along the given axis.
.. note:: Deviation = Reference_DNA(parameter) - Subject_DNA(parameter)
.. warning::
To calculate errors by using ``error = 'acf'`` or ``error = 'block'``,
GROMACS tool ``g_analyze`` ... |
14,393 | def apply(self, func, axis=0, subset=None, **kwargs):
self._todo.append((lambda instance: getattr(instance, ),
(func, axis, subset), kwargs))
return self | Apply a function column-wise, row-wise, or table-wise,
updating the HTML representation with the result.
Parameters
----------
func : function
``func`` should take a Series or DataFrame (depending
on ``axis``), and return an object with the same shape.
... |
14,394 | def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None):
assert amount >= 0
return self.post(amount, credit_account, description, self_memo=debit_memo, other_memo=credit_memo, datetime=datetime) | Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively.
note amount must be non-negative. |
14,395 | def masked_rec_array_to_mgr(data, index, columns, dtype, copy):
fill_value = data.fill_value
fdata = ma.getdata(data)
if index is None:
index = get_names_from_index(fdata)
if index is None:
index = ibase.default_index(len(data))
index = ensure_index(index)
if ... | Extract from a masked rec array and create the manager. |
14,396 | def find_card_bundles(provider: Provider, deck: Deck) -> Optional[Iterator]:
if isinstance(provider, RpcNode):
if deck.id is None:
raise Exception("deck.id required to listtransactions")
p2th_account = provider.getaccount(deck.p2th_address)
batch_data = [(, [i["txid"], 1])... | each blockchain transaction can contain multiple cards,
wrapped in bundles. This method finds and returns those bundles. |
14,397 | def Synchronized(f):
@functools.wraps(f)
def NewFunction(self, *args, **kw):
with self.lock:
return f(self, *args, **kw)
return NewFunction | Synchronization decorator. |
14,398 | def compare_dicts(old=None, new=None):
ret = {}
for key in set((new or {})).union((old or {})):
if key not in old:
ret[key] = {: ,
: new[key]}
elif key not in new:
ret[key] = {: ,
: old[key]}
... | Compare before and after results from various salt functions, returning a
dict describing the changes that were made. |
14,399 | def imbtree(ntips, treeheight=1.0):
rtree = toytree.tree()
rtree.treenode.add_child(name="0")
rtree.treenode.add_child(name="1")
for i in range(2, ntips):
cherry = toytree.tree()
cherry.treenode.add_child(name=str(i))
... | Return an imbalanced (comb-like) tree topology. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.