Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
351,600 | def zoomset_cb(self, setting, value, chviewer, info):
return self.zoomset(chviewer, info.chinfo) | This callback is called when a channel window is zoomed. |
351,601 | def ravel(self, name=None):
nbinsx = self.nbins(0)
nbinsy = self.nbins(1)
left_edge = self.xedgesl(1)
right_edge = self.xedgesh(nbinsx)
out = Hist(nbinsx * nbinsy,
left_edge, nbinsy * (right_edge - left_edge) + left_edge,
type=self.T... | Convert 2D histogram into 1D histogram with the y-axis repeated along
the x-axis, similar to NumPy's ravel(). |
351,602 | def HWProcess(cls, proc: HWProcess, ctx: ResourceContext) -> None:
seen = ctx.seen
for stm in proc.statements:
encl = stm._enclosed_for
full_ev_dep = stm._is_completly_event_dependent
now_ev_dep = stm._now_is_event_dependent
ev_dep = full_ev_dep o... | Gues resource usage by HWProcess |
351,603 | def _connect(self):
if sys.version_info[:2] < (2,6):
self._conn = httplib.HTTPConnection(self._host, self._port)
else:
self._conn = httplib.HTTPConnection(self._host, self._port,
False, defaultTimeout) | Connect to Squid Proxy Manager interface. |
351,604 | def retrieve(self, request, *args, **kwargs):
return super(BaseServiceProjectLinkViewSet, self).retrieve(request, *args, **kwargs) | To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner. |
351,605 | def put_multipart(self, local_path, destination_s3_path, part_size=DEFAULT_PART_SIZE, **kwargs):
self._check_deprecated_argument(**kwargs)
from boto3.s3.transfer import TransferConfig
transfer_config = TransferConfig(multipart_chunksize=part_size)
(bucket, ke... | Put an object stored locally to an S3 path
using S3 multi-part upload (for files > 8Mb).
:param local_path: Path to source local file
:param destination_s3_path: URL for target S3 location
:param part_size: Part size in bytes. Default: 8388608 (8MB)
:param kwargs: Keyword argumen... |
351,606 | def marshal( compoundSignature, variableList, startByte = 0, lendian=True ):
chunks = list()
bstart = startByte
if hasattr(variableList, ):
order = getattr(variableList, )
variableList = [ getattr(variableList, attr_name) for attr_name in order ]
for ct, var in zip(genCompleteType... | Encodes the Python objects in variableList into the DBus wire-format
matching the supplied compoundSignature. This function retuns a list of
binary strings is rather than a single string to simplify the recursive
marshalling algorithm. A single string may be easily obtained from the
result via: ''.join(... |
351,607 | def pick_move(self):
if self.root.position.n >= self.temp_threshold:
fcoord = self.root.best_child()
else:
cdf = self.root.children_as_pi(squash=True).cumsum()
cdf /= cdf[-2]
selection = random.random()
fcoord = cdf.searchsorted(sele... | Picks a move to play, based on MCTS readout statistics.
Highest N is most robust indicator. In the early stage of the game, pick
a move weighted by visit count; later on, pick the absolute max. |
351,608 | def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x):
if geneTree.traversalID.midEnd <= 3:
return (0, 0, geneTree)
checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID)
l = []
def fn(tree):
if tree.traversalID.mid != geneTree.... | Goes through each root possible branch making it the root.
Returns tree that requires the minimum number of duplications. |
351,609 | def append(self, value):
def append_trans(pipe):
self._append_helper(value, pipe)
self._transaction(append_trans) | Add *value* to the right side of the collection. |
351,610 | def try_get_dn_string(subject, shorten=False):
try:
from cryptography.x509.oid import NameOID
from cryptography.x509 import ObjectIdentifier
oid_names = {
getattr(NameOID, , ObjectIdentifier("2.5.4.3")): "CN",
getattr(NameOID, , ObjectIdentifier("2.5.4.6")): "C",... | Returns DN as a string
:param subject:
:param shorten:
:return: |
351,611 | def _check_enum(parameter_name, value, parameter_config):
enum_values = [enum[]
for enum in parameter_config[].values()
if in enum]
if value not in enum_values:
raise errors.EnumRejectionError(parameter_name, value, enum_values) | Checks if an enum value is valid.
This is called by the transform_parameter_value function and shouldn't be
called directly.
This verifies that the value of an enum parameter is valid.
Args:
parameter_name: A string containing the name of the parameter, which is
either just a variable name or the n... |
351,612 | def run(self, react=True, strict=True, roles=1):
try:
folder, index, self.script, self.selection, interlude = self.next(
self.folders, self.ensemble,
strict=strict, roles=roles
)
except TypeError:
raise GeneratorExit
wi... | Select a cast and perform the next scene.
:param bool react: If `True`, then Property directives are executed
at the point they are encountered. Pass `False` to skip them
so they can be enacted later on.
:param bool strict: Only fully-cast scripts to be performed.
:param... |
351,613 | def find_one_sql(table, filter, fields=None):
tblfoobarbazSELECT * FROM tbl WHERE bar=$1 AND foo=$2baztblidfoobarSELECT foo, bar FROM tbl WHERE id=$1
keys, values = _split_dict(filter)
fields = .join(fields) if fields else
where = _pairs(keys)
sql = .format(fields, table, where)
return sql, val... | >>> find_one_sql('tbl', {'foo': 10, 'bar': 'baz'})
('SELECT * FROM tbl WHERE bar=$1 AND foo=$2', ['baz', 10])
>>> find_one_sql('tbl', {'id': 10}, fields=['foo', 'bar'])
('SELECT foo, bar FROM tbl WHERE id=$1', [10]) |
351,614 | def sendUpdate(self, data):
if not self.running:
return
if self.remoteStep:
update = [data, 0]
updates = [update]
d = self.remoteStep.callRemote("update", updates)
d.ad... | This sends the status update to the master-side
L{buildbot.process.step.RemoteCommand} object, giving it a sequence
number in the process. It adds the update to a queue, and asks the
master to acknowledge the update so it can be removed from that
queue. |
351,615 | def dlogpdf_link_dvar(self, link_f, y, Y_metadata=None):
e = y - link_f
s_4 = 1.0/(self.variance**2)
dlik_dsigma = -0.5/self.variance + 0.5*s_4*np.square(e)
return dlik_dsigma | Gradient of the log-likelihood function at y given link(f), w.r.t variance parameter (noise_variance)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\sigma^{2}} = -\\frac{N}{2\\sigma^{2}} + \\frac{(y_{i} - \\lambda(f_{i}))^{2}}{2\\sigma^{4}}
:param link_f: latent variables link(f)
... |
351,616 | def wait_until_complete(self, timeout=None):
timeout_at = None
if timeout:
timeout_at = time.time() + int(timeout)
sequencer = self.get(, )
while True:
cur_test_state = self.get(sequencer, )
if in cur_test_state or in cur_test_state:
... | Wait until sequencer is finished.
This method blocks your application until the sequencer has completed
its operation. It returns once the sequencer has finished.
Arguments:
timeout -- Optional. Seconds to wait for sequencer to finish. If this
time is exceeded, th... |
351,617 | def get_stable_entry_at_u(self, miller_index, delu_dict=None, delu_default=0,
no_doped=False, no_clean=False):
all_delu_dict = self.set_all_variables(delu_dict, delu_default)
def get_coeffs(e):
coeffs = []
for du in all_delu_dict.keys():
... | Returns the entry corresponding to the most stable slab for a particular
facet at a specific chempot. We assume that surface energy is constant
so all free variables must be set with delu_dict, otherwise they are
assumed to be equal to delu_default.
Args:
miller_... |
351,618 | def upload_image(self, subreddit, image_path, name=None,
header=False, upload_as=None):
if name and header:
raise TypeError()
if upload_as not in (None, , ):
raise TypeError("upload_as must be , , or None.")
with open(image_path, ) as image:
... | Upload an image to the subreddit.
:param image_path: A path to the jpg or png image you want to upload.
:param name: The name to provide the image. When None the name will be
filename less any extension.
:param header: When True, upload the image as the subreddit header.
:pa... |
351,619 | def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]:
if isinstance(pt, list):
return pt
return [ast.If(ast.UnaryOp(ast.Not(), pt),
[self.__exit_scope()],
[])] | Normalize a test expression into a statements list.
Statements list are returned as-is.
Expression is packaged as:
if not expr:
return False |
351,620 | def copy_rect(self, x0, y0, x1, y1, dx, dy, destination):
x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1)
dx, dy = force_int(dx, dy)
for x in range(x0, x1 + 1):
for y in range(y0, y1 + 1):
d = destination._offset(dx + x - x0, dy + y - y0)
o... | Copy (blit) a rectangle onto another part of the image |
351,621 | def rename_tables(db, table_mapping, reverse=False):
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_names = connection.introspection.table_names()
for source, destination in table_mapping:
if source in table_names and de... | renames tables from source to destination name, if the source exists and the destination does
not exist yet. |
351,622 | def clone_to_path(https_authenticated_url, folder, branch_or_commit=None):
_LOGGER.info("Cloning repo")
repo = Repo.clone_from(https_authenticated_url, str(folder))
if branch_or_commit:
_LOGGER.info("Checkout branch_or_commit %s", branch_or_commit)
repo.git.checkout(branch_or_... | Clone the given URL to the folder.
:param str branch_or_commit: If specified, switch to this branch. Branch must exist. |
351,623 | def EnumerateQualifiers(self, namespace=None, **extra):
exc = None
qualifiers = None
method_name =
if self._operation_recorders:
self.operation_recorder_reset()
self.operation_recorder_stage_pywbem_args(
method=method_name,
... | Enumerate the qualifier types (= qualifier declarations) in a
namespace.
This method performs the EnumerateQualifiers operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds, this method returns... |
351,624 | def kill(self, container_id=None, sudo=None, signal=None):
sudo = self._get_sudo(sudo)
container_id = self.get_container_id(container_id)
cmd = self._init_command()
cmd.append(container_id)
if signal != None:
cmd = cmd + [, signal]
return self._run_and_retur... | stop (kill) a started OciImage container, if it exists
Equivalent command line example:
singularity oci kill <container_ID>
Parameters
==========
container_id: the id to stop.
signal: signal sent to the container (default SIGTERM)
sudo: Add s... |
351,625 | def is_partial(self, filepath):
path, filename = os.path.split(filepath)
return filename.startswith() | Check if file is a Sass partial source (see
`Sass partials Reference`_).
Args:
filepath (str): A file path. Can be absolute, relative or just a
filename.
Returns:
bool: True if file is a partial source, else False. |
351,626 | def state_call(self, addr, *args, **kwargs):
state = kwargs.pop(, None)
if isinstance(addr, SootAddressDescriptor):
ret_addr = kwargs.pop(, state.addr if state else SootAddressTerminator())
cc = kwargs.pop(, SimCCSoot(self.arch))
... | Create a native or a Java call state.
:param addr: Soot or native addr of the invoke target.
:param args: List of SootArgument values. |
351,627 | def _bootstrap_pacman(
root,
pkg_confs=,
img_format=,
pkgs=None,
exclude_pkgs=None,
):
_make_nodes(root)
if pkgs is None:
pkgs = []
elif isinstance(pkgs, six.string_types):
pkgs = pkgs.split()
default_pkgs = (, , , )
for pkg in defau... | Bootstrap an image using the pacman tools
root
The root of the image to install to. Will be created as a directory if
it does not exist. (e.x.: /root/arch)
pkg_confs
The location of the conf files to copy into the image, to point pacman
to the right repos and configuration.
... |
351,628 | def set_data_location(self, current_extent, start_extent):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
current_assignment = start_extent
for index, desc_unused in enumerate(self.alloc_descs):
self.alloc_descs[index][1] = cu... | A method to set the location of the data that this UDF File Entry
points to.
Parameters:
current_extent - Unused
start_extent - The starting extent for this data location.
Returns:
Nothing. |
351,629 | def write_outxy(self,filename):
f = open(filename,)
f.write("
f.write("
f.write("
for i in range(self.all_radec[0].shape[0]):
f.write(%(self.outxy[i,0],self.outxy[i,1]))
f.close() | Write out the output(transformed) XY catalog for this image to a file. |
351,630 | def sismember(self, name, value):
redis_set = self._get_set(name, )
if not redis_set:
return 0
result = self._encode(value) in redis_set
return 1 if result else 0 | Emulate sismember. |
351,631 | def init_train_args(self, parser):
train
parser.add_argument(, , dest=, default=DEFAULT_USER_CONFIG_PATH,
help=)
parser.add_argument(, , help=)
parser.add_argument(, , help=)
parser.add_argument(, , help=)
parser.add_argument(, , dest=, type=in... | Only invoked conditionally if subcommand is 'train' |
351,632 | def groups(self) -> Set[str]:
return set(opt.group_name for opt in self._options.values()) | The set of option-groups created by ``define``.
.. versionadded:: 3.1 |
351,633 | def get_hostname(config_url=None):
region_string = ""
if config_url:
return urlparse(config_url).hostname
aws_region = os.getenv("AWS_REGION")
if aws_region and aws_region in SUPPORTED_REGIONS:
region_string = ".%s" % aws_region
return "metrics-api%s.iopipe.com" % region_string | Returns the IOpipe collector's hostname. If the `AWS_REGION` environment
variable is not set or unsupported then `us-east-1` will be used by
default. In this case, `us-east-1` is `metrics-api.iopipe.com`.
:param config_url: A optional config URL to use.
:returns: The collector's hostname.
:rtype: ... |
351,634 | def lift_chart(df, col_true=None, col_pred=None, col_scores=None, pos_label=1):
r
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
if not col_scores:
col_scores = get_field_name_by_role(df, FieldRole.PREDICTED_SCORE)
thresh, tp, fn, tn, fp = _run_roc_node... | r"""
Compute life value, true positive rate (TPR) and threshold from predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param pos_label: positive label
:type pos_label: str
:param col_true: true column
... |
351,635 | def _make_sampling_sequence(n):
seq = list(range(5))
i = 50
while len(seq) < n:
seq.append(i)
i += 50
return seq | Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n. |
351,636 | def render(self, text, auth=None):
expected = str if sys.version_info[0] >= 3 else unicode
if not isinstance(text, expected):
raise TypeError(
.format(text))
if self.user_content:
url = .format(self.api_url)
data = {: text,... | Renders the specified markdown content and embedded styles.
Raises TypeError if text is not a Unicode string.
Raises requests.HTTPError if the request fails. |
351,637 | def init():
global sqs, logs, config
if config is None:
with open() as fh:
config = json.load(fh)
if sqs is None:
sqs = boto3.client()
if logs is None:
logs = boto3.client() | Lambda globals cache. |
351,638 | def list_keys(ctx, serials, readers):
if readers:
for reader in list_readers():
click.echo(reader.name)
ctx.exit()
all_descriptors = get_descriptors()
descriptors = [d for d in all_descriptors if d.key_type != YUBIKEY.SKY]
skys = len(all_descriptors) - len(descriptors)
... | List connected YubiKeys. |
351,639 | def update_payment_card_by_id(cls, payment_card_id, payment_card, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._update_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs)
else:
(data) = cls._update_payment_card_by_id_with_http_inf... | Update PaymentCard
Update attributes of PaymentCard
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_payment_card_by_id(payment_card_id, payment_card, async=True)
>>> result = thread.get... |
351,640 | def wrap_fmin_slsqp(fun, guess, opt_kwargs={}):
opt_kwargs = dict(opt_kwargs)
opt_kwargs.pop(, None)
eqcons = []
ieqcons = []
if in opt_kwargs:
if isinstance(opt_kwargs[], dict):
opt_kwargs[] = [opt_kwargs[],]
for con in opt_kwargs.pop():
if con[] == :... | Wrapper for :py:func:`fmin_slsqp` to allow it to be called with :py:func:`minimize`-like syntax.
This is included to enable the code to run with :py:mod:`scipy` versions
older than 0.11.0.
Accepts `opt_kwargs` in the same format as used by
:py:func:`scipy.optimize.minimize`, with the additional precon... |
351,641 | def load(self, filepath):
try:
self._config.read(filepath)
self.long_running_operation_timeout = self._config.getint(
"Azure", "long_running_operation_timeout")
except (ValueError, EnvironmentError, NoOptionError):
msg = "Supplied config file ... | Load configuration from existing file.
:param str filepath: Path to existing config file.
:raises: ValueError if supplied config file is invalid. |
351,642 | def extender(self, edge):
"See what edges can be extended by this edge."
(j, k, B, _, _) = edge
for (i, j, A, alpha, B1b) in self.chart[j]:
if B1b and B == B1b[0]:
self.add_edge([i, k, A, alpha + [edge], B1b[1:]]) | See what edges can be extended by this edge. |
351,643 | def _scan_function_prologues(self, traced_address, function_exits, initial_state):
regexes = set()
for ins_regex in self.project.arch.function_prologs:
r = re.compile(ins_regex)
regexes.add(r)
for start_, bytes_ in self.project.load... | Scan the entire program space for prologues, and start code scanning at those positions
:param traced_address:
:param function_exits:
:param initial_state:
:param next_addr:
:returns: |
351,644 | def strip_headers_footers_pagebreaks(docbody,
page_break_posns,
num_head_lines,
num_foot_lines):
num_breaks = len(page_break_posns)
page_lens = []
for x in xrange(0, num_breaks):
if x ... | Remove page-break lines, header lines, and footer lines from the
document.
@param docbody: (list) of strings, whereby each string in the list is a
line in the document.
@param page_break_posns: (list) of integers, whereby each integer
represents the index in docbody at which a page-... |
351,645 | def create_settings(pkg, repo_dest, db_user, db_name, db_password, db_host,
db_port):
vars = {: pkg,
: db_user,
: db_name,
: db_password or ,
: db_host or ,
: db_port or ,
: datetime.now().strftime(),
: gene... | Creates a local settings file out of the distributed template.
This also fills in database settings and generates a secret key, etc. |
351,646 | def patch_database(self, instance, database, body, project_id=None):
response = self.get_conn().databases().patch(
project=project_id,
instance=instance,
database=database,
body=body
).execute(num_retries=self.num_retries)
operation_name =... | Updates a database resource inside a Cloud SQL instance.
This method supports patch semantics.
See https://cloud.google.com/sql/docs/mysql/admin-api/how-tos/performance#patch.
:param instance: Database instance ID. This does not include the project ID.
:type instance: str
:para... |
351,647 | def create_logger(app: ) -> Logger:
logger = getLogger()
if app.debug and logger.level == NOTSET:
logger.setLevel(DEBUG)
logger.addHandler(default_handler)
return logger | Create a logger for the app based on the app settings.
This creates a logger named quart.app that has a log level based
on the app configuration. |
351,648 | def get_pkg_info(
package_name, additional=("pip", "flit", "pbr", "setuptools", "wheel")
):
dist_index = build_dist_index(pkg_resources.working_set)
root = dist_index[package_name]
tree = construct_tree(dist_index)
dependencies = {pkg.name: pkg.installed_version for pkg in tree[root]}
... | Return build and package dependencies as a dict. |
351,649 | def main():
args = get_command_line_arguments()
return build_toc_tree(args.title,
args.input,
args.output,
args.content_directory) | Starts the Application.
:return: Definition success.
:rtype: bool |
351,650 | def main(arguments=None):
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="DEBUG",
options_first=False,
projectName="HMpTy"
)
arguments, settings, log, dbConn = su.setup()
for arg, val in arguments.iteritems():
if arg[0] =... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* |
351,651 | def get_query_from_request(self, name):
query = self.request.get(name, "{}")
query = json.loads(query)
return self.to_utf8(query) | Returns the query inferred from the request |
351,652 | def get_status_from_resource(self, response):
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
raise BadResponse(
)
status = self._get_provisioning_state(response)
self.status = status or
self.p... | Process the latest status update retrieved from the same URL as
the previous request.
:param requests.Response response: latest REST call response.
:raises: BadResponse if status not 200 or 204. |
351,653 | def get_image(self, source):
buf = StringIO(source.read())
return Image.open(buf) | Given a file-like object, loads it up into a PIL.Image object
and returns it.
:param file source: A file-like object to load the image from.
:rtype: PIL.Image
:returns: The loaded image. |
351,654 | def make_fpfList(options):
user_values = options.fpf
defaults = [, , , ]
if user_values:
for fpf in user_values:
if fpf not in defaults:
defaults.append(fpf)
defaults.sort()
return defaults | aggregate default fpf values and user-defined fpf values where enrichment factor calculations will be attempted.
:param options: SplitInput object
:return defaults: list includes default fpf values & unique user-defined values |
351,655 | def match(self, path_info=None, method=None, return_rule=False,
query_args=None):
self.map.update()
if path_info is None:
path_info = self.path_info
else:
path_info = to_unicode(path_info, self.map.charset)
if query_args is None:
... | The usage is simple: you just pass the match method the current
path info as well as the method (which defaults to `GET`). The
following things can then happen:
- you receive a `NotFound` exception that indicates that no URL is
matching. A `NotFound` exception is also a WSGI applica... |
351,656 | def Logs(loggername, echo=True, debug=False, chatty=False, loglevel=logging.INFO, logfile=None, logpath=None, fileHandler=None):
log = logging.getLogger(loggername)
if fileHandler is None:
if logfile is None:
logFilename = _ourName
else:
logFilename = logfile
... | Initialize logging |
351,657 | def is_solid(regex):
shape = re.sub(r, , regex)
skeleton = shape.replace(, )
if len(shape) <= 1:
return True
if re.match(r, shape):
return True
if re.match(r, shape):
return True
if re.match(r, skeleton):
return True
else:
return False | Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a|b)(c)?')
False |
351,658 | def get_or_add_media_part(self, media):
media_part = self._find_by_sha1(media.sha1)
if media_part is None:
media_part = MediaPart.new(self._package, media)
return media_part | Return a |MediaPart| object containing the media in *media*.
If this package already contains a media part for the same
bytestream, that instance is returned, otherwise a new media part is
created. |
351,659 | def Update(self,name,description=None,location=None):
if not location: location = clc.v2.Account.GetLocation(session=self.session)
payload = {: name}
payload[] = description if description else self.description
r = clc.v2.API.Call(, % (self.alias, location, self.id), payload, session=self.session)
sel... | Updates the attributes of a given Network via PUT.
https://www.ctl.io/api-docs/v2/#networks-update-network
{
"name": "VLAN for Development Servers",
"description": "Development Servers on 11.22.33.0/24"
}
Returns a 204 and no content |
351,660 | def toVector(value):
if isinstance(value, Vector):
return value
elif TypeConverters._can_convert_to_list(value):
value = TypeConverters.toList(value)
if all(map(lambda v: TypeConverters._is_numeric(v), value)):
return DenseVector(value)
... | Convert a value to a MLlib Vector, if possible. |
351,661 | def make_xeditable(instance=None, extra_attrs=[], *args, **kwargs):
if instance is None:
helper = partial(make_xeditable, extra_attrs=extra_attrs, *args, **kwargs)
return helper
data = kwargs.get(, instance)
rich_data = kwargs.get(, data)
default_attr_names = [... | Converts the contents of the column into an ``<a>`` tag with the required DOM attributes to
power the X-Editable UI.
The following keyword arguments are all optional, but may be provided when pre-calling the
helper, to customize the output of the helper once it is run per object record:
* ``type``... |
351,662 | def get_minor_version(module_ident, plpy):
plan = plpy.prepare(, (,))
results = plpy.execute(plan, (module_ident,), 1)
return results[0][] | Retrieve minor version only given module_ident. |
351,663 | def username_matches_request_user(view_fn):
@wraps(view_fn)
def wrapper(request, username, *args, **kwargs):
User = get_user_model()
user = get_object_or_404(User, username=username)
if user != request.user:
return HttpResponseForbidden()
else:
retur... | Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match. |
351,664 | def get_bounds(self):
start, end = None, None
if len(self._weather_series) == 0:
return start, end
for i in (0, -1):
if self.has_tuple_instants:
row = self._weather_series.iloc[i, :]
instant = dt.datetime(row["year"],... | Returns
-------
(start, end)
Datetime instants of beginning and end of data. If no data, will be: (None, None). |
351,665 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.sendable.payments import LabeledPrice
data = {}
data[] = u(array.get())
data[] = u(ar... | Deserialize a new ShippingOption from a given dictionary.
:return: new ShippingOption instance.
:rtype: ShippingOption |
351,666 | def extend(instance, new_class):
instance.__class__ = type(
% (instance.__class__.__name__, new_class.__name__),
(new_class, instance.__class__,),
{}
) | Adds new_class to the ancestors of instance.
:param instance: Instance that will have a new ancestor.
:param new_class: Ancestor. |
351,667 | def describe(df, dtype=None):
if dtype is None:
dtype = {}
print(.format(datapoints=len(df)))
column_info, column_info_meta = _get_column_info(df, dtype)
if len(column_info[]) > 0:
_describe_int(df, column_info)
if len(column_info[]) > 0:
_describe_float(df, column_inf... | Print a description of a Pandas dataframe.
Parameters
----------
df : Pandas.DataFrame
dtype : dict
Maps column names to types |
351,668 | def remove_all_listeners(self, event=None):
if event is None:
self._listeners = collections.defaultdict(list)
self._once = collections.defaultdict(list)
else:
del self._listeners[event]
del self._once[event] | Remove all listeners, or those of the specified *event*.
It's not a good idea to remove listeners that were added elsewhere in
the code, especially when it's on an emitter that you didn't create
(e.g. sockets or file streams). |
351,669 | def make_downloader(url: str, path: str) -> Callable[[bool], str]:
def download_data(force_download: bool = False) -> str:
if os.path.exists(path) and not force_download:
log.info(, path)
else:
log.info(, url, path)
urlretrieve(url, path)
... | Make a function that downloads the data for you, or uses a cached version at the given path.
:param url: The URL of some data
:param path: The path of the cached data, or where data is cached if it does not already exist
:return: A function that downloads the data and returns the path of the data |
351,670 | def is_prime(n, k=64):
if n == 2:
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, 2048):
if n % i == 0:
return False
s = 0
d = n - 1
while True:
q, r = divmod(d, 2)
if r == 1:
break
s += 1
d... | Test whether n is prime probabilisticly.
This uses the Miller-Rabin primality test. If n is composite,
then this test will declare it to be probably prime with a
probability of at most 4**-k.
To be on the safe side, a value of k=64 for integers up to
3072 bits is recommended (error probability = 2... |
351,671 | def _galaxy_association_cuts(
self,
matchedObjects,
catalogueName,
magnitudeLimitFilter,
upperMagnitudeLimit,
lowerMagnitudeLimit):
self.log.debug()
import decimal
decimal.getcontext().prec = 10
g... | *perform a bright star match on the crossmatch results if required by the catalogue search*
**Key Arguments:**
- ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch
- ``catalogueName`` -- the name of the catalogue the crossmatch results from
- ``m... |
351,672 | def getAttribute(self, attribute):
if type(attribute) in (list, tuple):
if len(attribute) != 2:
raise LookupError,
ns_dict = self.attributes.get(attribute[0])
if ns_dict is None:
return None
return ns_dict.get(attribute[... | return requested attribute value or None |
351,673 | def get_legacy_fusion_langauge(identifier: ParserElement, reference: str) -> ParserElement:
break_start = (ppc.integer | ).setParseAction(_fusion_break_handler_wrapper(reference, start=True))
break_end = (ppc.integer | ).setParseAction(_fusion_break_handler_wrapper(reference, start=False))
res = (
... | Build a legacy fusion parser. |
351,674 | def search_dates(text, languages=None, settings=None, add_detected_language=False):
result = _search_with_detection.search_dates(
text=text, languages=languages, settings=settings
)
language, dates = result.get(), result.get()
if dates:
if add_detected_language:
dates = ... | Find all substrings of the given string which represent date and/or time and parse them.
:param text:
A string in a natural language which may contain date and/or time expressions.
:type text: str|unicode
:param languages:
A list of two letters language codes.e.g. ['en'... |
351,675 | def evaluator(self, candidates, args):
fitness = []
if self._use_ants:
for candidate in candidates:
total = 0
for c in candidate:
total += c.value
fitness.append(total)
else:
for candidate in can... | Return the fitness values for the given candidates. |
351,676 | def _guess_quote_and_delimiter(self, data, delimiters):
matches = []
for restr in (])(?P<space> ?)(?P<quote>["\,
]).*?(?P=quote)(?P<delim>[^\w\n"\,
])(?P<space> ?)(?P<quote>["\,
]).*?(?P=quote)(?:$|\n)quotedelimspace\ns a ... | Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,'some text',
The quote with the most wins, same with the delimiter.
If there is no ... |
351,677 | def stream_random_bytes(n):
n = min(n, 100 * 1024)
params = CaseInsensitiveDict(request.args.items())
if "seed" in params:
random.seed(int(params["seed"]))
if "chunk_size" in params:
chunk_size = max(1, int(params["chunk_size"]))
else:
chunk_size = 10 * 1024
def... | Streams n random bytes generated with given seed, at given chunk size per packet.
---
tags:
- Dynamic data
parameters:
- in: path
name: n
type: int
produces:
- application/octet-stream
responses:
200:
description: Bytes. |
351,678 | def get_qpimage_raw(self, idx=0):
name = self._get_experiments()[idx]
with h5py.File(name=self.path, mode="r") as h5:
exp = h5["Experiments"][name]
data = exp["data"][:]
rx = exp["axis-0"].attrs["scale"]
ry = exp["axis-1"... | Return QPImage without background correction |
351,679 | def verbosity(verbosity):
verbosity = int(verbosity)
if verbosity == 0:
return logging.WARNING
if verbosity == 1:
return logging.INFO
if verbosity == 2:
return logging.DEBUG
if verbosity >= 3:
return 0
else:
raise ValueError | Convert the number of times the user specified '-v' on the command-line
into a log level. |
351,680 | def before_request(self, func: Callable) -> Callable:
self.record_once(lambda state: state.app.before_request(func, self.name))
return func | Add a before request function to the Blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_request`. It applies only to requests that
are routed to an endpoint in this blueprint. An example usage,
.. code-block:: python
... |
351,681 | def dispatch(self, event: Any) -> None:
if event.type:
getattr(self, "ev_%s" % (event.type.lower(),))(event) | Send an event to an `ev_*` method.
`*` will be the events type converted to lower-case.
If `event.type` is an empty string or None then it will be ignored. |
351,682 | def _get_str_columns(sf):
return [name for name in sf.column_names() if sf[name].dtype == str] | Returns a list of names of columns that are string type. |
351,683 | def _compute_fans(shape):
if len(shape) < 1:
fan_in = fan_out = 1
elif len(shape) == 1:
fan_in = fan_out = shape[0]
elif len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
else:
receptive_field_size = 1.
for dim in shape[:-2]:
receptive_field_size *= dim
fan_i... | Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out). |
351,684 | def transformed_values(self):
t a success.
Reconstructs the pipeline context to materialize values.
'
if self.success and self.transforms:
with self.reconstruct_context() as context:
values = {
result.step_output_data.output_name: self._ge... | Return dictionary of transformed results, with keys being output names.
Returns None if execution result isn't a success.
Reconstructs the pipeline context to materialize values. |
351,685 | def handle(self):
self.output = PyStratumStyle(self.input, self.output)
config_file = self.input.get_argument()
self.run_command(config_file) | Executes constants command when PyStratumCommand is activated. |
351,686 | def _multiline(self, value, infile, cur_index, maxline):
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)
if mat is not None:
retval = list(mat.grou... | Extract the value, where we are in a multiline situation. |
351,687 | def new_cbuf(self, input, null_if_empty=True):
if not isinstance(input, bytes) and input:
input = input.encode()
if not input and null_if_empty:
return self._ffi.NULL, 0
cbuf = self._ffi.new(, input)
self._bufs.append(cbuf)
return cbuf, len(input... | Converts the input into a raw C buffer
:param input: The input
:param null_if_empty: If the input is empty
:return: A tuple of buffer,length |
351,688 | def blit(
self,
console: tcod.console.Console,
x: float,
y: float,
bg_blend: int,
scale_x: float,
scale_y: float,
angle: float,
) -> None:
lib.TCOD_image_blit(
self.image_c,
_console(console),
x,
... | Blit onto a Console using scaling and rotation.
Args:
console (Console): Blit destination Console.
x (float): Console X position for the center of the Image blit.
y (float): Console Y position for the center of the Image blit.
The Image blit is centered ... |
351,689 | def TerminateStuckRunIfNeeded(self, job):
if job.current_run_id and job.last_run_time and job.lifetime:
now = rdfvalue.RDFDatetime.Now()
expiration_time = (
job.last_run_time + job.lifetime + rdfvalue.Duration("10m"))
if now > expiration_time:
run = data... | Cleans up job state if the last run is stuck. |
351,690 | def copy(self):
other = PackageFilter.__new__(PackageFilter)
other._excludes = self._excludes.copy()
other._includes = self._includes.copy()
return other | Return a shallow copy of the filter.
Adding rules to the copy will not alter the source. |
351,691 | def rowreduce(table, key, reducer, header=None, presorted=False,
buffersize=None, tempdir=None, cache=True):
return RowReduceView(table, key, reducer, header=header,
presorted=presorted,
buffersize=buffersize, tempdir=tempdir, cache=cache) | Group rows under the given key then apply `reducer` to produce a single
output row for each input group of rows. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['a', 3],
... ['a', 7],
... ['b', 2],
... ['b'... |
351,692 | def main(left_path, left_column, right_path, right_column,
outfile, titles, join, minscore, count, warp):
right_file = csv.reader(open(right_path, ))
if titles:
right_header = next(right_file)
index = NGram((tuple(r) for r in right_file),
threshold=minscore,
... | Perform the similarity join |
351,693 | def plot_attention(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], filename: str):
try:
import matplotlib
except ImportError:
raise RuntimeError("Please install matplotlib.")
matplotlib.use("Agg")
import matplotlib.pyplot as plt
assert attention... | Uses matplotlib for creating a visualization of the attention matrix.
:param attention_matrix: The attention matrix.
:param source_tokens: A list of source tokens.
:param target_tokens: A list of target tokens.
:param filename: The file to which the attention visualization will be written to. |
351,694 | def move(name, target, **kwargs):
*
ret = {: [],
: True}
if not name:
ret[] =
ret[] = False
if in kwargs and kwargs[]:
ret[] = .format(name)
else:
opts_schedule = list_(show_all=True, where=, return_yaml=False)
pillar_schedule = list_(show_all=... | Move scheduled job to another minion or minions.
CLI Example:
.. code-block:: bash
salt '*' schedule.move jobname target |
351,695 | def compute_precession(jd_tdb):
eps0 = 84381.406
t = (jd_tdb - T0) / 36525.0
psia = ((((- 0.0000000951 * t
+ 0.000132851 ) * t
- 0.00114045 ) * t
- 1.0790069 ) * t
+ 5038.481507 ) * t
o... | Return the rotation matrices for precessing to an array of epochs.
`jd_tdb` - array of TDB Julian dates
The array returned has the shape `(3, 3, n)` where `n` is the number
of dates that have been provided as input. |
351,696 | def unscheduleFirst(self, runnable):
for evt in self.store.query(TimedEvent, TimedEvent.runnable == runnable, sort=TimedEvent.time.ascending):
evt.deleteFromStore()
break | Remove from given item from the schedule.
If runnable is scheduled to run multiple times, only the temporally first
is removed. |
351,697 | def login_open_sheet(email, password, spreadsheet):
try:
gc = gspread.login(email, password)
worksheet = gc.open(spreadsheet).sheet1
return worksheet
except:
print
sys.exit(1) | Connect to Google Docs spreadsheet and return the first worksheet. |
351,698 | def from_tushare(dataframe, dtype=):
if dtype in []:
return QA_DataStruct_Stock_day(
dataframe.assign(date=pd.to_datetime(dataframe.date)
).set_index([,
],
drop=False),
... | dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description] |
351,699 | def simxSetBooleanParameter(clientID, paramIdentifier, paramValue, operationMode):
return c_SetBooleanParameter(clientID, paramIdentifier, paramValue, operationMode) | Please have a look at the function description/documentation in the V-REP user manual |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.