Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
362,100 | def on_yaml_imported(self, yaml):
def represent_ordereddict(dumper, data):
values = []
for (key, value) in data.items():
values.append(
(dumper.represent_data(key), dumper.represent_data(value))
)
ret... | The `pyyaml <https://pypi.org/project/pyyaml/>`_ import hook.
:param module yaml: The ``yaml`` module |
362,101 | def extract_tree_with(self, labels, suppress_unifurcations=True):
return self.extract_tree(labels, False, suppress_unifurcations) | Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels``
Args:
``leaves`` (``set``): Set of leaf labels to include.
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
Tree: Copy o... |
362,102 | def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
_ = stderr, time_taken, args, knowledge_base
self.CheckReturn(cmd, return_val)
plist = biplist.readPlist(io.BytesIO(stdout))
if len(plist) > 1:
raise parser.ParseError("SPHardwareDataType plist... | Parse the system profiler output. We get it in the form of a plist. |
362,103 | def _get_struct_shapewithstyle(self, shape_number):
obj = _make_object("ShapeWithStyle")
obj.FillStyles = self._get_struct_fillstylearray(shape_number)
obj.LineStyles = self._get_struct_linestylearray(shape_number)
bc = BitConsumer(self._src)
obj.NumFillBits = n_fill_bit... | Get the values for the SHAPEWITHSTYLE record. |
362,104 | def on_message(self, msg):
self.log(, msg)
"%s", msg.get_msg_class())
return False | When a message with an already known traversal_id is received,
we try to build a duplication message and send it in to a protocol
dependent recipient. This is used in contracts traversing
the graph, when the contract has reached again the same shard.
This message is necessary, as silentl... |
362,105 | def is_valid_state(self):
return self.is_valid_country and self.country.upper() in STATES and \
self.state is not None and \
self.state.upper() in STATES[self.country.upper()] | A bool value that indicates whether the object's state is a valid
state code. |
362,106 | def infix(tokens, operator_table):
operator, matched_tokens = operator_table.infix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) | Match an infix of an operator. |
362,107 | def refresh(self):
import re
if re.match(r"^1\.2\.[0-9]*$", self.identifier):
account = self.blockchain.rpc.get_objects([self.identifier])[0]
else:
account = self.blockchain.rpc.lookup_account_names([self.identifier])[0]
if not account:
raise... | Refresh/Obtain an account's data from the API server |
362,108 | def get_bounding_box_list(input_doc_fname, input_doc, full_page_box_list,
set_of_page_nums_to_crop, argparse_args, chosen_PdfFileWriter):
global args, page_nums_to_crop, PdfFileWriter
args = argparse_args
page_nums_to_crop = set_of_page_nums_to_crop
PdfFileWriter = chosen_P... | Calculate a bounding box for each page in the document. The first
argument is the filename of the document's original PDF file, the second is
the PdfFileReader for the document. The argument full_page_box_list is a list
of the full-page-size boxes (which is used to correct for any nonzero origins
in t... |
362,109 | def username_enable(self, **kwargs):
config = ET.Element("config")
username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
name_key = ET.SubElement(username, "name")
name_key.text = kwargs.pop()
enable = ET.SubElement(username, "enable")
... | Auto Generated Code |
362,110 | def set_shipping(self, *args, **kwargs):
Encomenda normal (PAC).SEDEXTipo de frete não especificado.BRA
self.shipping = {}
for arg, value in kwargs.iteritems():
self.shipping[arg] = value
shipping_schema(self.shipping) | Define os atributos do frete
Args:
type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).',
2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.'
cost (float): (opcional) Valor total do frete. Deve ser maior que 0.00 e menor ou ... |
362,111 | def assert_partial_link_text(self, partial_link_text,
timeout=settings.SMALL_TIMEOUT):
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.wait_for_partial_link_text(partial_link_text, time... | Similar to wait_for_partial_link_text(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT. |
362,112 | def connect(self):
self._connection = StrictRedis(
host=self._host,
port=self._port,
db=self._database,
password=self._password) | Connects to the redis database. |
362,113 | def positional(max_positional_args):
def positional_decorator(wrapped):
@functools.wraps(wrapped)
def positional_wrapper(*args, **kwargs):
if len(args) > max_positional_args:
plural_s =
if max_positional_args != 1:
plural_s =
... | A decorator to declare that only the first N arguments my be positional.
This decorator makes it easy to support Python 3 style keyword-only
parameters. For example, in Python 3 it is possible to write::
def fn(pos1, *, kwonly1=None, kwonly1=None):
...
All named parameters after ``*``... |
362,114 | def get_property(self, filename):
with open(self.filepath(filename)) as f:
return f.read().strip() | Opens the file and reads the value |
362,115 | def _canonical_dir(self, morf):
return os.path.split(CodeUnit(morf, self.file_locator).filename)[0] | Return the canonical directory of the module or file `morf`. |
362,116 | def _get_call_params(self, method, **kwargs):
payload = {: method,
: self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload[] = self.config.API_USERNAME
payload[] = self.config.API_PASSWORD
... | Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters |
362,117 | def dir_empty(d):
flist = glob.glob(os.path.join(d,))
return (len(flist) == 0) | Return True if given directory is empty, false otherwise. |
362,118 | def logical_definitions(self, nid):
ldefs = self.all_logical_definitions
if ldefs is not None:
return [x for x in ldefs if x.class_id == nid]
else:
return [] | Retrieves logical definitions for a class id
Arguments
---------
nid : str
Node identifier for entity to be queried
Returns
-------
LogicalDefinition |
362,119 | def create_pull_from_issue(self, issue, base, head):
if int(issue) > 0:
data = {: issue, : base, : head}
return self._create_pull(data)
return None | Create a pull request from issue #``issue``.
:param int issue: (required), issue number
:param str base: (required), e.g., 'master'
:param str head: (required), e.g., 'username:branch'
:returns: :class:`PullRequest <github3.pulls.PullRequest>` if
successful, else None |
362,120 | def checkIPFromAlias(alias=None):
headers = {
"Content-type": "text/html",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding": " gzip, deflate",
"Accept-Language": " es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
"Connection": "keep-alive",
"DNT": "1",... | Method that checks if the given alias is currently connected to Skype and returns its IP address.
:param alias: Alias to be searched.
:return: Python structure for the Json received. It has the following structure:
{
"type": "i3visio.ip",
"value": "1.1.1.1",
"at... |
362,121 | def numdiff2(f, x0, dv=1e-8):
dd = x0.shape
f0 = f(x0)
nobs = f0.shape[-1]
f_shape = f0.shape[:-1]
out_shape = f_shape + dd + (nobs,)
ret = np.zeros(out_shape)
for ind in product( *[range(i) for i in dd] ):
x = x0.copy()
x[ind] += dv
x2 = x0.copy()
x2... | Returns the derivative of f w.r.t. to multidimensional vector x0
If x0 is of dimension R1 x ... x Rd dimension of f is assumed to be
in the form S1 x ... x Sf x Rn. The last dimension corresponds to various
observations. The value returned is of dimension :
S1 x ... x Sf x R1 x ... x Rd x Rn |
362,122 | def _create_B_direct(self):
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
Z = self._create_Z(Y)
return np.dot(np.dot(Y,np.transpose(Z)),np.linalg.inv(np.dot(Z,np.transpose(Z)))) | Creates OLS coefficient matrix (calculates Y within - for OLS fitting)
Returns
----------
The coefficient matrix B |
362,123 | def use_gdbs(self, gdbs=True, port=2345):
self.gdbs = gdbs
self.gdbs_port = port | Set gdbs use for process.
:param gdbs: Boolean, default is True
:param port: Port number for gdbserver |
362,124 | def ReadList(self, *branches, **kwargs):
branches = map(lambda x: E.Read(x) if isinstance(x, str) else x, branches)
return self.List(*branches, **kwargs) | Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`. |
362,125 | def PrepareMergeTaskStorage(self, task):
if self._storage_type != definitions.STORAGE_TYPE_SESSION:
raise IOError()
merge_storage_file_path = self._GetMergeTaskStorageFilePath(task)
processed_storage_file_path = self._GetProcessedStorageFilePath(task)
task.storage_file_size = os.path.getsiz... | Prepares a task storage for merging.
Moves the task storage file from the processed directory to the merge
directory.
Args:
task (Task): task.
Raises:
IOError: if the storage type is not supported or
if the storage file cannot be renamed.
OSError: if the storage type is no... |
362,126 | def parse(self, string, parent):
result = {}
for member in self.RE_MEMBERS.finditer(string):
mems = self._process_member(member, parent, string)
for onemem in mems:
result[onemem.name.lower()] = onemem
re... | Parses all the value code elements from the specified string. |
362,127 | def _stat(self, path):
s parent to already be deref()
if path not in self.entries:
return OverlayStat(*self.originals[](path)[:10], st_overlay=0)
st = self.entries[path].stat
if stat.S_ISLNK(st.st_mode):
return self._stat(self.deref(path))
return st | IMPORTANT: expects `path`'s parent to already be deref()'erenced. |
362,128 | def reply(self, msg, router=None, **kwargs):
if not isinstance(msg, Message):
msg = Message.pickled(msg)
msg.dst_id = self.src_id
msg.handle = self.reply_to
vars(msg).update(kwargs)
if msg.handle:
(self.router or router).route(msg)
else:
... | Compose a reply to this message and send it using :attr:`router`, or
`router` is :attr:`router` is :data:`None`.
:param obj:
Either a :class:`Message`, or an object to be serialized in order
to construct a new message.
:param router:
Optional router to use if... |
362,129 | def npm(package_json, output_file, pinned_file):
amd_build_deprecation_warning()
try:
version = get_distribution(current_app.name).version
except DistributionNotFound:
version =
output = {
: current_app.name,
: make_semver(version) if version else version,
... | Generate a package.json file. |
362,130 | def auth_aws_iam(self, access_key, secret_key, session_token=None, header_value=None, mount_point=, role=, use_token=True, region=):
request = aws_utils.generate_sigv4_auth_request(header_value=header_value)
auth = aws_utils.SigV4Auth(access_key, secret_key, session_token, region)
auth... | POST /auth/<mount point>/login
:param access_key: AWS IAM access key ID
:type access_key: str
:param secret_key: AWS IAM secret access key
:type secret_key: str
:param session_token: Optional AWS IAM session token retrieved via a GetSessionToken AWS API request.
see:... |
362,131 | def extract_vars(template):
keys = set()
for match in re.finditer(r"\{\{ (?P<key>\w+) \}\}", template.getvalue()):
keys.add(match.groups()[0])
return sorted(list(keys)) | Extract variables from template. Variables are enclosed in
double curly braces. |
362,132 | def _SetPath(self, path):
old_path = self._path
if old_path and not io_wrapper.IsCloudPath(old_path):
try:
self._path = path
self._loader = self._loader_factory(path) | Sets the current path to watch for new events.
This also records the size of the old path, if any. If the size can't be
found, an error is logged.
Args:
path: The full path of the file to watch. |
362,133 | def statsd_metric(name, count, elapsed):
with statsd.pipeline() as pipe:
pipe.incr(name, count)
pipe.timing(name, int(round(1000 * elapsed))) | Metric that records to statsd & graphite |
362,134 | def _render_full_resource(self, instance, include, fields):
api_type = instance.__jsonapi_type__
orm_desc_keys = instance.__mapper__.all_orm_descriptors.keys()
to_ret = {
: instance.id,
: api_type,
: {},
: {},
: {}
}
... | Generate a representation of a full resource to match JSON API spec.
:param instance: The instance to serialize
:param include: Dictionary of relationships to include
:param fields: Dictionary of fields to filter |
362,135 | def caches(self, options={}):
query = urllib.urlencode(options)
url = "caches"
if query != "":
url = "%s?%s" % (url, query)
result = self.client.get(url)
return [cache["name"] for cache in result["body"]] | Query the server for a list of caches, parse the JSON response, and
return the result.
Keyword arguments:
options -- a dict of arguments to send with the request. See
http://dev.iron.io/cache/reference/api/#list_caches for more
information on defaults and p... |
362,136 | def _processLostJobs(self):
if ((time.time() - self.timeSinceJobsLastRescued) >= self.config.rescueJobsFrequency):
self.reissueOverLongJobs()
logger.info("Reissued any over long jobs")
hasNoMissingJobs = ... | Process jobs that have gone awry |
362,137 | def clean(self, value):
if isinstance(value, numpy.ndarray):
return value
elif isinstance(value, (list, tuple)):
return numpy.array(value)
raise ParameterNotValidError | Cleans and returns the given value, or raises a ParameterNotValidError exception |
362,138 | def set_geometry(self, geom):
(self.thet0, self.thet, self.phi0, self.phi, self.alpha,
self.beta) = geom | A convenience function to set the geometry variables.
Args:
geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta).
See the Scatterer class documentation for a description of these
angles. |
362,139 | def inheritance_diagram_directive(name, arguments, options, content, lineno,
content_offset, block_text, state,
state_machine):
node = inheritance_diagram()
class_names = arguments
graph = InheritanceGraph(class_names)
... | Run when the inheritance_diagram directive is first encountered. |
362,140 | def postorder(self):
if not self:
return
if self.left:
for x in self.left.postorder():
yield x
if self.right:
for x in self.right.postorder():
yield x
yield self | iterator for nodes: left, right, root |
362,141 | def wait_for_ssh(ip):
for _ in range(12):
with safe_socket() as s:
try:
s.connect((ip, 22))
return True
except socket.timeout:
pass
time.sleep(10)
return False | Wait for SSH to be available at given IP address. |
362,142 | def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs):
from .bases import ContainerProperty
from .dataspec import DataSpec
name = self.name
if name in new_class_attrs:
raise RuntimeError("Two property generat... | ``MetaHasProps`` calls this during class creation as it iterates
over properties to add, to update its registry of new properties.
The parameters passed in are mutable and this function is expected to
update them accordingly.
Args:
class_name (str) :
name of... |
362,143 | def get_supported_versions(self):
if not hasattr(self, ):
try:
self._versions = [self.send_apdu(INS_GET_VERSION).decode()]
except exc.APDUError as e:
return self._versions | Gets a list of supported U2F versions from the device. |
362,144 | def list_public_images(self, guid=None, name=None, **kwargs):
if not in kwargs:
kwargs[] = IMAGE_MASK
_filter = utils.NestedDict(kwargs.get() or {})
if name:
_filter[] = utils.query_filter(name)
if guid:
_filter[] = utils.query_filter(guid)... | List all public images.
:param string guid: filter based on GUID
:param string name: filter based on name
:param dict \\*\\*kwargs: response-level options (mask, limit, etc.) |
362,145 | def attribute_is_public(self, permission):
try:
parent = getattr(self, "parent_{}".format(permission))
student = getattr(self, "self_{}".format(permission))
return (parent and student)
except Exception:
logger.error("Could not retrieve permissions... | Checks if attribute is visible to public (regardless of admins status) |
362,146 | def reverse_dictionary(d):
rev_d = {}
[rev_d.update({v:k}) for k, v in d.items()]
return rev_d | Reverses the key value pairs for a given dictionary.
Parameters
----------
d : :obj:`dict`
dictionary to reverse
Returns
-------
:obj:`dict`
dictionary with keys and values swapped |
362,147 | def media_new_callbacks(self, open_cb, read_cb, seek_cb, close_cb, opaque):
return libvlc_media_new_callbacks(self, open_cb, read_cb, seek_cb, close_cb, opaque) | Create a media with custom callbacks to read the data from.
@param open_cb: callback to open the custom bitstream input media.
@param read_cb: callback to read data (must not be NULL).
@param seek_cb: callback to seek, or NULL if seeking is not supported.
@param close_cb: callback to clo... |
362,148 | def open(self):
self._tryfinallys = []
self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0) | initialize visit variables and statistics |
362,149 | def _wrapped_signed_div(a, b):
bits = max(a.bits, b.bits)
divisor_lb = b.lower_bound
divisor_ub = b.upper_bound
uninit_flag = a.uninitialized | b.uninitialized
if divisor_lb == 0:
if divisor_ub == 0:
return StridedInte... | Perform wrapped unsigned division on two StridedIntervals.
:param a: The dividend (StridedInterval)
:param b: The divisor (StridedInterval)
:return: The quotient |
362,150 | def tpot_driver(args):
if args.VERBOSITY >= 2:
_print_args(args)
input_data = _read_data_file(args)
features = input_data.drop(args.TARGET_NAME, axis=1)
training_features, testing_features, training_target, testing_target = \
train_test_split(features, input_data[args.TARGET_NAME]... | Perform a TPOT run. |
362,151 | def compile(definition, handlers={}):
resolver, code_generator = _factory(definition, handlers)
global_state = code_generator.global_state
exec(code_generator.func_code, global_state)
return global_state[resolver.get_scope_name()] | Generates validation function for validating JSON schema passed in ``definition``.
Example:
.. code-block:: python
import fastjsonschema
validate = fastjsonschema.compile({'type': 'string'})
validate('hello')
This implementation support keyword ``default``:
.. code-block:: p... |
362,152 | def payload(self, value):
if isinstance(value, tuple):
content_type, payload = value
self.content_type = content_type
self._payload = payload
else:
self._payload = value | Sets the payload of the message and eventually the Content-Type
:param value: the payload |
362,153 | def addRecord(self, record):
if self._destroyed:
return
if not self.uiRecordBTN.isChecked():
return
self._queue.append(record) | Adds the inputed record to this logger tree widget.
:param record | <logging.LogRecord> |
362,154 | def start(self):
if rospy.get_name() == :
raise ValueError()
if not self._connect_to_sensor():
self._running = False
return False
self._color_im_sub = rospy.Subscriber(, ImageMessage, self._color_im_callback)
self._depth_im... | Start the sensor. |
362,155 | def put(self, uri_relative, request_bytes, custom_headers):
return self._request(
self._METHOD_PUT,
uri_relative,
request_bytes,
{},
custom_headers
) | :type uri_relative: str
:type request_bytes: bytes
:type custom_headers: dict[str, str]
:rtype: BunqResponseRaw |
362,156 | def googleRetryPredicate(e):
if isinstance(e, GoogleAPICallError) and e.code == 429:
return True
if isinstance(e, InternalServerError) or isinstance(e, ServiceUnavailable):
return True
return False | necessary because under heavy load google may throw
TooManyRequests: 429
The project exceeded the rate limit for creating and deleting buckets.
or numerous other server errors which need to be retried. |
362,157 | def to_scales(val):
res = []
for i in val:
if len(i) == 3:
res.append((i[0], type(i[2])))
else:
try:
res.append((i[0], i[3].dtype, i[2]))
except AttributeError:
res.append((i[0], type(i[3]), i[2]))
dtype = np.dtype(res... | Parse *val* to return an array of scale factors. |
362,158 | def ellipsoid_phantom(space, ellipsoids, min_pt=None, max_pt=None):
if space.ndim == 2:
_phantom = _ellipse_phantom_2d
elif space.ndim == 3:
_phantom = _ellipsoid_phantom_3d
else:
raise ValueError()
if min_pt is None and max_pt is None:
return _phantom(space, ellips... | Return a phantom given by ellipsoids.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created, must be 2- or
3-dimensional. If ``space.shape`` is 1 in an axis, a corresponding
slice of the phantom is created (instead of squashing the whole
pha... |
362,159 | def single(window, config):
cordx = round(config.get(, 0))
color = config.get(, red)
icon = config.get(, )
align = config.get(, )
term = window.term
width = round(config.get(, window.width))
title = config.get(, )
header = term.center(title, width, icon)
header = header.split(... | Single theme
===== Header =====
= items =
================== |
362,160 | def get_gain(self, attr_name):
subset_entropy = 0.0
for value in iterkeys(self._attr_value_counts[attr_name]):
value_prob = self.get_value_prob(attr_name, value)
e = self.get_entropy(attr_name, value)
subset_entropy += value_prob * e
return (self.main... | Calculates the information gain from splitting on the given attribute. |
362,161 | def regress(self, method = ):
if method is :
self.betas, residuals_sum, rank, s = LA.lstsq(self.design_matrix.T, self.resampled_signal.T)
self.residuals = self.resampled_signal - self.predict_from_design_matrix(self.design_matrix)
elif method is :
import sta... | regress performs linear least squares regression of the designmatrix on the data.
:param method: method, or backend to be used for the regression analysis.
:type method: string, one of ['lstsq', 'sm_ols']
:returns: instance variables 'betas' (nr_betas x nr_signals) and 'residuals' ... |
362,162 | def get_relaxation_options(self):
domain = self.get_domain()
for upper_value in self.upper:
for suc in domain.predecessors(upper_value):
yield suc | Returns possible generalizations for the upper values in the taxonomy |
362,163 | def _Viscosity(rho, T, fase=None, drho=None):
Tr = T/Tc
Dr = rho/rhoc
H = [1.67752, 2.20462, 0.6366564, -0.241605]
mu0 = 100*Tr**0.5/sum([Hi/Tr**i for i, Hi in enumerate(H)])
I = [0, 1, 2, 3, 0, 1, 2, 3, 5, 0, 1, 2, 3, 4, 0, 1, 0, 3, 4, 3, 5]
J = [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2... | Equation for the Viscosity
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
fase: dict, optional for calculate critical enhancement
phase properties
drho: float, optional for calculate critical enhancement
[∂ρ/∂P]T at reference state,... |
362,164 | def remove_ignore(path, use_sudo=False, force=False):
which = sudo if use_sudo else run
which(rm(path, recursive=True, force=force), warn_only=True) | Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for temporary
files that can be assumed to be cleaned up at a later point.
:param path: Path to file or directory to remove.
:type path: unicode
:param use_sudo: Use the `sudo` command.
:type use_sudo: ... |
362,165 | def _build_path(self):
if not self.path:
self.path =
if self.uri_parameters:
self.path = self.path + + requote_uri(self.uri_parameters)
if self.query:
self.path = (self.path + + self.query)
if self.params:
try:
... | Constructs the actual request URL with accompanying query if any.
Returns:
None: But does modify self.path, which contains the final
request path sent to the server. |
362,166 | def _globals(self):
globbies = dict(_n.__dict__)
globbies.update(_special.__dict__)
globbies.update({:self.h, :self.c, :self, :self})
globbies.update(self.extra_globals)
return globbies | Returns the globals needed for eval() statements. |
362,167 | def value_error(self, key, bad_value):
msg = ERROR_MESSAGES[key].format(bad_value)
self.logger.log(msg)
self.error = True | Reports a value error using ERROR_MESSAGES dict.
key - key to use for ERROR_MESSAGES.
bad_value - is passed to format which is called on what key maps to
in ERROR_MESSAGES. |
362,168 | def _check_auth(self, username: str, password: str) -> bool:
try:
return self.credentials[username] == password
except KeyError:
return False | Check if a username/password combination is valid. |
362,169 | def get_queryset(self):
try:
date = ElectionDay.objects.get(date=self.kwargs[])
except Exception:
raise APIException(
.format(self.kwargs[])
)
body_ids = []
for election in date.elections.all():
body = election.race... | Returns a queryset of all bodies holding an election on a date. |
362,170 | def multipart_to_singleparts(geom):
if isinstance(geom, base.BaseGeometry):
if hasattr(geom, "geoms"):
for subgeom in geom:
yield subgeom
else:
yield geom | Yield single part geometries if geom is multipart, otherwise yield geom.
Parameters:
-----------
geom : shapely geometry
Returns:
--------
shapely single part geometries |
362,171 | def code(self):
code = getattr(self, , None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | the http status code to return to the client, by default, 200 if a body is present otherwise 204 |
362,172 | def provisioning_configuration(
self, body, custom_headers=None, raw=False, **operation_config):
url =
query_parameters = {}
if self.api_version:
query_parameters["api-version"] = self.api_version
header_parameters = {}
... | ProvisioningConfiguration.
:param body:
:type body: :class:`ContinuousDeploymentConfiguration
<vsts_info_provider.models.ContinuousDeploymentConfiguration>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongs... |
362,173 | def create_namespace(self, name, ignore_errors=False):
if not self.has_namespace(name):
self.namespaces[name] = ConjunctiveGraph()
return True
elif ignore_errors:
return True
else:
raise RuntimeError("namespace already exists" % n... | creates a namespace if it does not exist
args:
name: the name of the namespace
ignore_errors(bool): Will ignore if a namespace already exists or
there is an error creating the namespace
returns:
True if created
False if not c... |
362,174 | def to_dir_path_url(url_info: URLInfo) -> str:
dir_name = posixpath.dirname(url_info.path)
if not dir_name.endswith():
url_template =
else:
url_template =
return url_template.format(url_info.hostname_with_port, dir_name) | Return URL string with the path replaced with directory only. |
362,175 | def _init_special(self):
self._special_del = {}
self._special_del[] = _del_SCANNERS
self._special_set = {}
for key in reserved_construction_var_names:
self._special_set[key] = _set_reserved
for key in future_reserved_construction_var_names:
self.... | Initial the dispatch tables for special handling of
special construction variables. |
362,176 | def closeContentsWidget( self ):
widget = self.currentContentsWidget()
if ( not widget ):
return
widget.close()
widget.setParent(None)
widget.deleteLater() | Closes the current contents widget. |
362,177 | def normalized(self, document, schema=None, always_return_document=False):
self.__init_processing(document, schema)
self.__normalize_mapping(self.document, self.schema)
self.error_handler.end(self)
if self._errors and not always_return_document:
return None
e... | Returns the document normalized according to the specified rules
of a schema.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Defaults to :obj:`None`. If not
provided here, the schema must have ... |
362,178 | def put(self, x):
if self._num_serial > 0 or len(self._threads) == 0:
self._num_serial -= 1
out = self._parallizable.forward_backward(x)
self._out_queue.put(out)
else:
self._in_queue.put(x) | Assign input `x` to an available worker and invoke
`parallizable.forward_backward` with x. |
362,179 | def guild_details(guild_id=None, name=None):
if guild_id and name:
warnings.warn("both guild_id and name are specified, "
"name will be ignored")
if guild_id:
params = {"guild_id": guild_id}
cache_name = "guild_details.%s.json" % guild_id
elif name:
... | This resource returns details about a guild.
:param guild_id: The guild id to query for.
:param name: The guild name to query for.
*Note: Only one parameter is required; if both are set, the guild Id takes
precedence and a warning will be logged.*
The response is a dictionary with the following k... |
362,180 | def upload_panel(store, institute_id, case_name, stream):
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
raw_symbols = [line.strip().split()[0] for line in stream if
line and not line.startswith()]
hgnc_symbols = []
for raw_symbol in raw_symbols... | Parse out HGNC symbols from a stream. |
362,181 | def scaleToBoxParam(quad, shape):
x0 = 0.5*(quad[0][0]+quad[1][0])
x1 = 0.5*(quad[2][0]+quad[3][0])
y0 = 0.5*(quad[0][1]+quad[3][1])
y1 = 0.5*(quad[1][1]+quad[2][1])
cx = (x0*shape[0]) / (x0-x1+shape[0])
cy = (y0*shape[1]) / (y0-y1+shape[1])
fx = abs(cx/(x0-cx))
... | so, you have a [quad] ((x0,y0),,,) inside a box [shape](width,height)
this function gives you center [x,y], and scale factor [x,y]
you would need to apply to [quad] in order to scale it to the same shape as the box
!quad corners needs to be sorted like in example |
362,182 | def _format_unhashed_feature(name, hl_spaces, sep=):
return sep.join(
format_signed(n, _format_single_feature, hl_spaces=hl_spaces)
for n in name) | Format feature name for hashed features. |
362,183 | def continuous_periods(self):
result = []
start_date = self.start_date
for gap in self.pot_data_gaps:
end_date = gap.start_date - timedelta(days=1)
result.append(PotPeriod(start_date, end_date))
start_date = gap.end_date + timed... | Return a list of continuous data periods by removing the data gaps from the overall record. |
362,184 | def validate_sort_fields(sort_fields):
descending = set()
def sort_order_filter(name):
"Helper to remove flag and memoize sort order"
if name.startswith():
name = name[1:]
descending.add(name)
return name
sort_fields = validate_field_list(sort_... | Make sure the fields in the given list exist, and return sorting key.
If field names are prefixed with '-', sort order is reversed for that field (descending). |
362,185 | def matrixToMathTransform(matrix):
if isinstance(matrix, ShallowTransform):
return matrix
off, scl, rot = MathTransform(matrix).decompose()
return ShallowTransform(off, scl, rot) | Take a 6-tuple and return a ShallowTransform object. |
362,186 | def file_find(self, load):
path = load.get()
if not path:
return {: ,
: }
tgt_env = load.get(, )
return self.find_file(path, tgt_env) | Convenience function for calls made using the LocalClient |
362,187 | def query_radecl(ra,
decl,
filtersystem=,
field_deg2=1.0,
usebinaries=True,
extinction_sigma=0.1,
magnitude_limit=26.0,
maglim_filtercol=4,
trilegal_version=1.6,
extra... | This runs the TRILEGAL query for decimal equatorial coordinates.
Parameters
----------
ra,decl : float
These are the center equatorial coordinates in decimal degrees
filtersystem : str
This is a key in the TRILEGAL_FILTER_SYSTEMS dict. Use the function
:py:func:`astrobase.serv... |
362,188 | def clean_start_time(self):
start = self.cleaned_data.get()
if not start:
return start
active_entries = self.user.timepiece_entries.filter(
start_time__gte=start, end_time__isnull=True)
for entry in active_entries:
output = (
... | Make sure that the start time doesn't come before the active entry |
362,189 | def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
if isinstance(connection_info, basestring):
if tunnel.try_passwordless_ssh(sshserver, sshkey):
password=False
else:
password = getpass("SSH Password for %s: "%sshserver)
for lp,rp in zip(lports, rports... | tunnel connections to a kernel via ssh
This will open four SSH tunnels from localhost on this machine to the
ports associated with the kernel. They can be either direct
localhost-localhost tunnels, or if an intermediate server is necessary,
the kernel must be listening on a public IP.
Par... |
362,190 | def write(self, filename=):
if filename == :
filename = self.filename
if not filename.endswith():
filename +=
with open(filename, ) as out:
out.write(self.__str__()) | write object to an ENVI header file |
362,191 | def compute_node_colors(self):
data = [self.graph.node[n][self.node_color] for n in self.nodes]
if self.group_order == "alphabetically":
data_reduced = sorted(list(set(data)))
elif self.group_order == "default":
data_reduced = list(unique_everseen(data))
... | Compute the node colors. Also computes the colorbar. |
362,192 | def allsplit(self, x, mesh_axis, split_axis, which=None):
if which is None:
which = self.laid_out_pcoord(mesh_axis)
num_splits = self.shape[mesh_axis].size
def my_fn(x, which):
slice_begin = [
dimsize // num_splits * which if i == split_axis else 0
for i, dimsize in enum... | Inverse of allconcat - split each slice and keep only one piece of it.
The number of ways to split is the number of processors in the group.
The part that is kept corresponds to the processor's index in the group.
Args:
x: LaidOutTensor.
mesh_axis: int, the mesh axis along which to split.
... |
362,193 | def _get_rar_version(xfile):
buf = xfile.read(len(RAR5_ID))
if buf.startswith(RAR_ID):
return 3
elif buf.startswith(RAR5_ID):
xfile.read(1)
return 5
return 0 | Check quickly whether file is rar archive. |
362,194 | def populateFromFile(self, dataUrl, indexFile=None):
self._dataUrl = dataUrl
self._indexFile = indexFile
if indexFile is None:
self._indexFile = dataUrl + ".bai"
samFile = self.getFileHandle(self._dataUrl)
self._setHeaderFields(samFile)
if not in sam... | Populates the instance variables of this ReadGroupSet from the
specified dataUrl and indexFile. If indexFile is not specified
guess usual form. |
362,195 | def _generate_id_maps(self, unique_stmts, poolsize=None,
size_cutoff=100, split_idx=None):
if poolsize is None:
logger.debug(
)
use_mp = False
elif sys.version_info[0] >= 3 and sys.version_info[1] >= 4:
... | Connect statements using their refinement relationships. |
362,196 | def addStormCmd(self, ctor):
if not s_syntax.isCmdName(ctor.name):
raise s_exc.BadCmdName(name=ctor.name)
self.stormcmds[ctor.name] = ctor | Add a synapse.lib.storm.Cmd class to the cortex. |
362,197 | def inception_v3_arg_scope(weight_decay=0.00004,
stddev=0.1,
batch_norm_var_collection=):
batch_norm_params = {
: 0.9997,
: 0.001,
: tf.GraphKeys.UPDATE_OPS,
: {
: None,
: None,
:... | Defines the default InceptionV3 arg scope.
Args:
weight_decay: The weight decay to use for regularizing the model.
stddev: The standard deviation of the trunctated normal weight initializer.
batch_norm_var_collection: The name of the collection for the batch norm
variables.
Returns:
An `arg_... |
362,198 | def make_link_node(rawtext, app, type, slug, options):
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith():
base +=
except AttributeError as err:
raise ValueError( % str(err))
ref = base + type + ... | Create a link to a github resource.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param type: Link type (issues, changeset, etc.)
:param slug: ID of the thing to link to
:param options: Options dictionary passed to role func. |
362,199 | def read_archive(archive, fname):
zfile = zipfile.ZipFile(archive)
contents = zfile.open(fname, )
fobj = io.TextIOWrapper(contents)
seen = set()
for line in fobj:
line = line.rstrip()
if line not in seen:
yield line.split()
seen.add(line) | Return an iterator of unique rows from a zip archive.
* archive - path to the zip archive.
* fname - name of the compressed file within the archive. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.