text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _retrieve_output_mode(self):
"""Save the state of the output mode so it can be reset at the end of the session."""
reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n")
output = self.send_command("get system console")
result_mode_re = reg_mode.search(output)
if result_mode... | 0.00616 |
def numericallySortFilenames(names):
"""
Sort (ascending) a list of file names by their numerical prefixes.
The number sorted on is the numeric prefix of the basename of
the given filename. E.g., '../output/1.json.bz2' will sort before
'../output/10.json.bz2'.
@param: A C{list} of file names, e... | 0.000961 |
def _ensure_filepath(filename):
"""
Ensure that the directory exists before trying to write to the file.
"""
filepath = os.path.dirname(filename)
if not os.path.exists(filepath):
os.makedirs(filepath) | 0.007905 |
def create_actor_delaunay(pts, color, **kwargs):
""" Creates a VTK actor for rendering triangulated plots using Delaunay triangulation.
Keyword Arguments:
* ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False*
:param pts: points
:type pts: vtkFloat... | 0.002939 |
def units(self):
"""
Tuple of the units for length, time and mass. Can be set in any order, and strings are not case-sensitive. See ipython_examples/Units.ipynb for more information. You can check the units' exact values and add Additional units in rebound/rebound/units.py. Units should be set befor... | 0.007203 |
def dispatch_request(self, *args, **kwargs):
"""Dispatch the request.
Its the actual ``view`` flask will use.
"""
if request.method in ('POST', 'PUT'):
return_url, context = self.post(*args, **kwargs)
if return_url is not None:
return redirect(retu... | 0.004149 |
def _download(url, dest):
"""
Downloads a URL to a directory
:param url:
The URL to download
:param dest:
The path to the directory to save the file in
:return:
The filesystem path to the saved file
"""
print('Downloading %s' % url)
filename = os.path.basename... | 0.004619 |
def new_filename(prefix, extension=None, flag_minimal=True):
"""returns a file name that does not exist yet, e.g. prefix.0001.extension
Args:
prefix:
extension: examples: "dat", ".dat" (leading dot will be detected, does not repeat dot in name)
flag_minimal:
- True: w... | 0.003839 |
def finish(self):
"""
Respond to nsqd that you’ve processed this message successfully
(or would like to silently discard it).
"""
if self._has_responded:
raise NSQException('already responded')
self._has_responded = True
self.on_finish.send(self) | 0.006369 |
def format(self, format_str):
"""Returns a formatted version of format_str.
The only named replacement fields supported by this method and
their corresponding API calls are:
* {num} group_num
* {name} group_name
* {symbol} group_symbol
*... | 0.001668 |
def replace_launch_config(self, scaling_group, launch_config_type,
server_name, image, flavor, disk_config=None, metadata=None,
personality=None, networks=None, load_balancers=None,
key_name=None):
"""
Replace an existing launch configuration. All of the attributes mu... | 0.011905 |
def write_otu_file(otu_ids, fp):
"""
Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file.
"""
... | 0.001828 |
def update_lipd_v1_1(d):
"""
Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:pa... | 0.003115 |
def json_error_response(error, response, status_code=400):
"""
Formats an error as a response containing a JSON body.
"""
msg = {"error": error.error, "error_description": error.explanation}
response.status_code = status_code
response.add_header("Content-Type", "application/json")
response.... | 0.002755 |
def init_app(self, app=None, blueprint=None, additional_blueprints=None):
"""Update flask application with our api
:param Application app: a flask application
"""
if app is not None:
self.app = app
if blueprint is not None:
self.blueprint = blueprint
... | 0.002331 |
def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT and fetch one."""
return select(table, cols, where, group, order, limit, **kwargs).fetchone() | 0.008811 |
def pair(self):
""" Return tuple (address, port), where address is a string (empty string if self.address() is None) and
port is an integer (zero if self.port() is None). Mainly, this tuple is used with python socket module
(like in bind method)
:return: 2 value tuple of str and int.
"""
address = str(self... | 0.026549 |
def dbRestore(self, db_value, context=None):
"""
Converts a stored database value to Python.
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant>
"""
if db_value is None:
return None
elif isinstance(db_value, (str, unic... | 0.006012 |
def validate(self):
"""Iterate over all triples in the graph and validate each one
appropriately
"""
log.info("{}\nValidating against {}"
.format("-" * 100, self.schema_def.__class__.__name__))
if not self.schema_def:
raise ValueError("No schema ... | 0.002064 |
def remove_flow_controller(cls, name):
"""
Removes a flow controller.
Args:
name (string): Name of the controller to remove.
Raises:
KeyError: If the controller to remove was not registered.
"""
if name not in cls.registered_controllers:
... | 0.004751 |
def det_to_src(self, angle, dparam):
"""Direction from a detector location to the source.
The direction vector is computed as follows::
dir = rotation_matrix(angle).dot(detector.surface_normal(dparam))
Note that for flat detectors, ``surface_normal`` does not depend
on the... | 0.000367 |
def fit(self, X):
"""Fit the PyNNDescent transformer to build KNN graphs with
neighbors given by the dataset X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Sample data
Returns
-------
transformer : PyNNDescentTransform... | 0.001988 |
def market_open(self, session, mins) -> Session:
"""
Time intervals for market open
Args:
session: [allday, day, am, pm, night]
mins: mintues after open
Returns:
Session of start_time and end_time
"""
if session not in self.exch: retu... | 0.006787 |
def put(self, local_path, destination_s3_path, **kwargs):
"""
Put an object stored locally to an S3 path.
:param local_path: Path to source local file
:param destination_s3_path: URL for target S3 location
:param kwargs: Keyword arguments are passed to the boto function `put_obje... | 0.006263 |
def scrub(value, scrub_text=_keep_whitespace, scrub_number=_scrub_number):
"""
REMOVE/REPLACE VALUES THAT CAN NOT BE JSON-IZED
"""
return _scrub(value, set(), [], scrub_text=scrub_text, scrub_number=scrub_number) | 0.008772 |
def run(self):
"""Start the recurring task."""
if self.init_sec:
sleep(self.init_sec)
self._functime = time()
while self._running:
start = time()
self._func()
self._functime += self.interval_sec
if self._functime - start > 0:
... | 0.00551 |
def api_endpoints(obj):
"""Iterator over all API endpoint names and callbacks."""
for name in dir(obj):
attr = getattr(obj, name)
api_path = getattr(attr, 'api_path', None)
if api_path:
yield (
'%s%s' % (obj.api_path_prefix, api_path),
attr,
... | 0.002137 |
def at(self, for_time, counter_offset=0):
"""
Accepts either a Unix timestamp integer or a Time object.
Time objects will be adjusted to UTC automatically
@param [Time/Integer] time the time to generate an OTP for
@param [Integer] counter_offset an amount of ticks to add to the t... | 0.005515 |
def _get_git_tracked_files(rootdir='.'):
"""Parsing .gitignore rules is hard.
However, a way we can get around this problem by just listing all
currently tracked git files, and start our search from there.
After all, if it isn't in the git repo, we're not concerned about
it, because secrets aren't ... | 0.001067 |
def grandparent_path(self):
""" return grandparent's path string """
return os.path.basename(os.path.join(self.path, '../..')) | 0.014085 |
def __insert_represented_points(self, cluster):
"""!
@brief Insert representation points to the k-d tree.
@param[in] cluster (cure_cluster): Cluster whose representation points should be inserted.
"""
for point in cluster.rep:
self.... | 0.017192 |
def _get_dirint_coeffs():
"""
Here be a large multi-dimensional matrix of dirint coefficients.
Returns:
Array with shape ``(6, 6, 7, 5)``.
Ordering is ``[kt_prime_bin, zenith_bin, delta_kt_prime_bin, w_bin]``
"""
coeffs = [[0 for i in range(6)] for j in range(6)]
coeffs[0][0] =... | 0.000062 |
def _get(url, profile):
'''Get a specific dashboard.'''
request_url = "{0}/api/dashboards/{1}".format(profile.get('grafana_url'),
url)
response = requests.get(
request_url,
headers={
"Accept": "application/json",
"Auth... | 0.001613 |
def remove_unreachable_symbols(grammar, inplace=False):
# type: (Grammar, bool) -> Grammar
"""
Remove unreachable symbols from the gramar
:param grammar: Grammar where to symbols remove
:param inplace: True if transformation should be performed in place. False by default.
:return: Grammar withou... | 0.001198 |
def get_encoded_query_params(self):
"""Return encoded query params to be used in proxied request"""
get_data = encode_items(self.request.GET.lists())
return urlencode(get_data) | 0.01 |
def on_evaluate_request(self, py_db, request):
'''
:param EvaluateRequest request:
'''
# : :type arguments: EvaluateArguments
arguments = request.arguments
thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference(
arguments.frameId)
... | 0.007426 |
def from_PyCMDS(filepath, name=None, parent=None, verbose=True) -> Data:
"""Create a data object from a single PyCMDS output file.
Parameters
----------
filepath : path-like
Path to the .data file
Can be either a local or remote file (http/ftp).
Can be compressed with gz/bz2, de... | 0.00141 |
def get_credential_cache():
'''if the user has specified settings to provide a cache for credentials
files, initialize it. The root for the folder is created if it doesn't
exist. The path for the specific client is returned, and it's
not assumed to be either a folder or a file (this is up to th... | 0.005868 |
def validate_event_type(sender, event, created):
"""Verify that the Event's code is a valid one."""
if event.code not in sender.event_codes():
raise ValueError("The Event.code '{}' is not a valid Event "
"code.".format(event.code)) | 0.003676 |
def set_property_value(self, name, value, dry_run=False):
"""Set a property value or remove a property.
value == None means 'remove property'.
Raise HTTP_FORBIDDEN if property is read-only, or not supported.
When dry_run is True, this function should raise errors, as in a real
... | 0.002806 |
def __clean_and_tokenize(self, doc_list):
"""Method to clean and tokenize the document list.
:param doc_list: Document list to clean and tokenize.
:return: Cleaned and tokenized document list.
"""
# Some repositories fill entire documentation in description. We ignore
# ... | 0.001362 |
def get_attachment_model():
"""
Returns the Attachment model that is active in this project.
"""
try:
from .models import AbstractAttachment
klass = apps.get_model(config["attachment_model"])
if not issubclass(klass, AbstractAttachment):
raise ImproperlyConfigured(
... | 0.005599 |
def save_features(paths: List[str], datas: List[np.ndarray],
compressed: bool = False) -> List:
"""
Save features specified with absolute paths.
:param paths: List of files specified with paths.
:param datas: List of numpy ndarrays to save into the respective files
:param compress... | 0.001845 |
def _check_peptide_inputs(self, peptides):
"""
Check peptide sequences to make sure they are valid for this predictor.
"""
require_iterable_of(peptides, string_types)
check_X = not self.allow_X_in_peptides
check_lower = not self.allow_lowercase_in_peptides
check_m... | 0.002972 |
def receiveData(self, connection, data):
"""
Receives some data for the given protocol.
"""
try:
protocol = self._protocols[connection]
except KeyError:
raise NoSuchConnection()
protocol.dataReceived(data)
return {} | 0.006757 |
def import_lv_stations(self, session):
"""
Import lv_stations within the given load_area
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
Returns
-------
lv_stations: :pandas:`pandas.DataFrame<dataframe>`
... | 0.004425 |
def is_metal(self, efermi_tol=1e-4):
"""
Check if the band structure indicates a metal by looking if the fermi
level crosses a band.
Returns:
True if a metal, False if not
"""
for spin, values in self.bands.items():
for i in range(self.nb_bands):
... | 0.003854 |
def batch_watch(parameterized, run=True):
"""
Context manager to batch watcher events on a parameterized object.
The context manager will queue any events triggered by setting a
parameter on the supplied parameterized object and dispatch them
all at once when the context manager exits. If run=False ... | 0.001473 |
def docstring_section_lines(docstring, section_name):
"""
Return a section of a numpydoc string
Paramters
---------
docstring : str
Docstring
section_name : str
Name of section to return
Returns
-------
section : str
Section minus the header
"""
line... | 0.001099 |
def set_active_scheme(self,scheme,case_sensitive=0):
"""Set the currently active scheme.
Names are by default compared in a case-insensitive way, but this can
be changed by setting the parameter case_sensitive to true."""
scheme_names = self.keys()
if case_sensitive:
... | 0.006903 |
def list_leases(self, uuid=None):
"""
List current subnet leases
Args:
uuid(str): Filter the leases by uuid
Returns:
list of :class:~Lease: current leases
"""
try:
lease_files = os.listdir(self.path)
except OSError as e:
... | 0.002663 |
def calculate_bearing(
place_geometry,
latitude,
longitude,
earthquake_hazard=None,
place_exposure=None
):
"""Simple postprocessor where we compute the bearing angle between two
points.
:param place_geometry: Geometry of place.
:type place_geometry: QgsGeometry
... | 0.001135 |
def _set_relative_pythonpath(self, value):
"""Set PYTHONPATH list relative paths"""
self.pythonpath = [osp.abspath(osp.join(self.root_path, path))
for path in value] | 0.009479 |
def traverse(self, root="ROOT", indent="", transform=None, stream=sys.stdout):
'''
Traverses the C{View} tree and prints its nodes.
The nodes are printed converting them to string but other transformations can be specified
by providing a method name as the C{transform} parameter.
... | 0.004916 |
def remove_graphic(self, graphic: Graphics.Graphic, *, safe: bool=False) -> typing.Optional[typing.Sequence]:
"""Remove a graphic, but do it through the container, so dependencies can be tracked."""
return self.remove_model_item(self, "graphics", graphic, safe=safe) | 0.021277 |
def _compute_anom_score_between_two_windows(self, i):
"""
Compute distance difference between two windows' chunk frequencies,
which is then marked as the anomaly score of the data point on the window boundary in the middle.
:param int i: index of the data point between two windows.
... | 0.004175 |
def get_broadcast(cast_name, onto_name):
"""
Get a single broadcast.
Broadcasts are stored data about how to do a Pandas join.
A Broadcast object is a namedtuple with these attributes:
- cast: the name of the table being broadcast
- onto: the name of the table onto which "cast" is broa... | 0.000833 |
def makeRequests(callable_, args_list, callback=None,
exc_callback=_handle_thread_exception):
"""Create several work requests for same callable with different arguments.
Convenience function for creating several work requests for the same
callable where each invocation of the callable rece... | 0.00085 |
def encode(hex):
'''Encode hexadecimal string as base58 (ex: encoding a Monero address).'''
data = _hexToBin(hex)
l_data = len(data)
if l_data == 0:
return ""
full_block_count = l_data // __fullBlockSize
last_block_size = l_data % __fullBlockSize
res_size = full_block_count * __ful... | 0.00486 |
def alias_ip_address(ip_address, interface, aws=False):
"""Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems.
:param ip_address: (str) IP address to set as an alias
:param interface: (str) The interface number or full device name, i... | 0.00283 |
def pprint(arr, columns=('temperature', 'luminosity'),
names=('Temperature (Kelvin)', 'Luminosity (solar units)'),
max_rows=32, precision=2):
"""
Create a pandas DataFrame from a numpy ndarray.
By default use temp and lum with max rows of 32 and precision of 2.
arr - An numpy.nda... | 0.00081 |
def count_scts_in_sct_extension(certificate: cryptography.x509.Certificate) -> Optional[int]:
"""Return the number of Signed Certificate Timestamps (SCTs) embedded in the certificate.
"""
scts_count = 0
try:
# Look for the x509 extension
sct_ext = certificate.exte... | 0.007282 |
def on_client_connect(self, client_conn):
"""Inform client of build state and version on connect.
Parameters
----------
client_conn : ClientConnection object
The client connection that has been successfully established.
Returns
-------
Future that re... | 0.003125 |
def left_sections(self):
"""
The number of sections that touch the left side.
During merging, the cell's text will grow to include other
cells. This property keeps track of the number of sections that
are touching the left side. For example::
+-----+----... | 0.002328 |
def ping(daemon, channel, data=None):
"""
Process the 'ping' control message.
:param daemon: The control daemon; used to get at the
configuration and the database.
:param channel: The publish channel to which to send the
response.
:param data: Optional extra d... | 0.00104 |
def get_time_from_rfc3339(rfc3339):
"""
return time tuple from an RFC 3339-formatted time string
:param rfc3339: str, time in RFC 3339 format
:return: float, seconds since the Epoch
"""
try:
# py 3
dt = dateutil.parser.parse(rfc3339, ignoretz=False)
return dt.timestamp... | 0.001534 |
def file_exists(fname):
"""Check if a file exists and is non-empty.
"""
try:
return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
except OSError:
return False | 0.004831 |
def excepthook(exc_type, exc_value, tracebackobj):
"""
Global function to catch unhandled exceptions.
Parameters
----------
exc_type : str
exception type
exc_value : int
exception value
tracebackobj : traceback
traceback object
"""
separator = "-" * 80
no... | 0.001189 |
def vertex_defects(mesh):
"""
Return the vertex defects, or (2*pi) minus the sum of the angles
of every face that includes that vertex.
If a vertex is only included by coplanar triangles, this
will be zero. For convex regions this is positive, and
concave negative.
Returns
--------
... | 0.001795 |
def register(app, uri, file_or_directory, pattern,
use_modified_since, use_content_range):
# TODO: Though mach9 is not a file server, I feel like we should at least
# make a good effort here. Modified-since is nice, but we could
# also look into etags, expires, and caching
"""
... | 0.000246 |
def setup_address(self, name, address=default, transact={}):
"""
Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method... | 0.003569 |
def _get_input_args(bam_file, data, out_base, background):
"""Retrieve input args, depending on genome build.
VerifyBamID2 only handles GRCh37 (1, 2, 3) not hg19, so need to generate
a pileup for hg19 and fix chromosome naming.
"""
if dd.get_genome_build(data) in ["hg19"]:
return ["--Pileup... | 0.004662 |
def make_cloud_mlengine_request_fn(credentials, model_name, version):
"""Wraps function to make CloudML Engine requests with runtime args."""
def _make_cloud_mlengine_request(examples):
"""Builds and sends requests to Cloud ML Engine."""
api = discovery.build("ml", "v1", credentials=credentials)
parent... | 0.004773 |
def _fits_inside_predicate(self):
"""
Return a function taking an integer point size argument that returns
|True| if the text in this fitter can be wrapped to fit entirely
within its extents when rendered at that point size.
"""
def predicate(point_size):
"""
... | 0.002639 |
def _getAuthHeaders(self):
"""
Get authentication headers. If we have valid header data already,
they immediately return it.
If not, then get new authentication data. If we are currently in
the process of getting the
header data, put this request into a queue to be handle... | 0.000473 |
def load(path):
"""Helper function that tries to load a filepath (or python module notation)
as a python module and on failure `exec` it.
Args:
path (str): Path or module to load
The function tries to import `example.module` when either `example.module`,
`example/module` or `example/module... | 0.003317 |
def _get_rho(self, v):
"""
convert unit-cell volume in A^3 to density in g/cm^3
:param v: unit cell volume in A^3
:return: density in g/cm^3
:note: internal function
"""
v_mol = vol_uc2mol(v, self.z) # in m^3
rho = self.mass / v_mol * 1.e-6 # in g/cm^3... | 0.0059 |
def purge_items(self):
"""Remove purged and overlimit items from the cache.
TODO: optimize somehow.
Leave no more than 75% of `self.max_items` items in the cache."""
self._lock.acquire()
try:
il=self._items_list
num_items = len(il)
need_remov... | 0.00716 |
def _get_stm_with_branches(stm_it):
"""
:return: first statement with rank > 0 or None if iterator empty
"""
last = None
while last is None or last.rank == 0:
try:
last = next(stm_it)
except StopIteration:
last = None
break
return last | 0.003205 |
def flatten(l):
"""Flatten a nested list."""
return sum(map(flatten, l), []) \
if isinstance(l, list) or isinstance(l, tuple) else [l] | 0.013333 |
def server_hardware(self):
"""
Gets the ServerHardware API client.
Returns:
ServerHardware:
"""
if not self.__server_hardware:
self.__server_hardware = ServerHardware(self.__connection)
return self.__server_hardware | 0.006944 |
def unflatten(flat_dict, separator='_'):
"""
Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy
"""
_unflatten_asse... | 0.001418 |
def actionAngleStaeckel_c(pot,delta,R,vR,vT,z,vz,u0=None,order=10):
"""
NAME:
actionAngleStaeckel_c
PURPOSE:
Use C to calculate actions using the Staeckel approximation
INPUT:
pot - Potential or list of such instances
delta - focal length of prolate spheroidal coordinates
... | 0.023831 |
def per_section(it, is_delimiter=lambda x: x.isspace()):
"""
From http://stackoverflow.com/a/25226944/610569
"""
ret = []
for line in it:
if is_delimiter(line):
if ret:
yield ret # OR ''.join(ret)
ret = []
else:
ret.append(lin... | 0.002597 |
def state(self, value):
"""Set device state.
:type value: str
:param value: Future state (either ON or OFF)
"""
if value.upper() == ON:
return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters("1", "true"))
elif value.uppe... | 0.007505 |
def create_data_and_metadata_from_data(self, data: numpy.ndarray, intensity_calibration: CalibrationModule.Calibration=None, dimensional_calibrations: typing.List[CalibrationModule.Calibration]=None, metadata: dict=None, timestamp: str=None) -> DataAndMetadata.DataAndMetadata:
"""Create a data_and_metadata obje... | 0.020031 |
def _check_configs(self):
"""
Reloads the configuration files.
"""
configs = set(self._find_configs())
known_configs = set(self.configs.keys())
new_configs = configs - known_configs
for cfg in (known_configs - configs):
self.log.debug("Compass configur... | 0.003711 |
def main(*argv):
""" main driver of program """
try:
adminUsername = str(argv[0])
adminPassword = str(argv[1])
baseURL = str(argv[2]) #"https://www.arcgis.com/sharing/rest"#
inviteSubject = str(argv[3])
inviteEmail = str(argv[4])
newUserName = argv[5]
firs... | 0.003158 |
def __prepare_histogram(h1, h2):
"""Convert the histograms to scipy.ndarrays if required."""
h1 = h1 if scipy.ndarray == type(h1) else scipy.asarray(h1)
h2 = h2 if scipy.ndarray == type(h2) else scipy.asarray(h2)
if h1.shape != h2.shape or h1.size != h2.size:
raise ValueError('h1 and h2 must be ... | 0.002762 |
def is_static_etcd(self):
'''Determine if we are on a node running etcd'''
return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml")) | 0.0125 |
def top3_full(votes):
"""
Description:
Top m - 1 alternatives q = m(m - 1) + 2m moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
"""
#create array of zeros, length = q
res = np.zeros(2 * len(votes[0]) + (len(votes[0]) * (... | 0.010686 |
def hit_count(self, request, hitcount):
"""
Called with a HttpRequest and HitCount object it will return a
namedtuple:
UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message').
`hit_counted` will be True if the hit was counted and False if it was
not. `'hit_m... | 0.001596 |
def update(self, obj, data):
"""Helper function to update an already existing document
instead of creating a new one.
:param obj: Mongoengine Document to update
:param data: incomming payload to deserialize
:return: an :class UnmarshallResult:
Example: ::
from marshmallow_mongoengi... | 0.001316 |
def subsample(self, factor):
"""
Downsample images by an integer factor.
Parameters
----------
factor : positive int or tuple of positive ints
Stride to use in subsampling. If a single int is passed,
each dimension of the image will be downsampled by this... | 0.004669 |
def get_album_by_mbid(self, mbid):
"""Looks up an album by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "album.getInfo", params).execute(True)
return Album(_extract(doc, "artist"), _extract(doc, "name"), self) | 0.007519 |
def response_from_prediction(self, y_pred, single=True):
"""Turns a model's prediction in *y_pred* into a JSON
response.
"""
result = y_pred.tolist()
if single:
result = result[0]
response = {
'metadata': get_metadata(),
'result': resul... | 0.005025 |
def locate_bar_r(icut, epos):
"""Fine position of the right CSU bar"""
sm = len(icut)
def swap_coor(x):
return sm - 1 - x
def swap_line(tab):
return tab[::-1]
return _locate_bar_gen(icut, epos, transform1=swap_coor,
transform2=swap_line) | 0.0033 |
def writeto(self, filename, **kwargs):
"""
Write the header to a fits file.
:param filename:
:return:
"""
fits.PrimaryHDU(header=self).writeto(filename, output_verify='ignore', **kwargs) | 0.012821 |
def version(self, value):
"""
Save the Site's version from a string or version tuple
@type value: tuple or str
"""
if isinstance(value, tuple):
value = unparse_version(value)
self._version = value | 0.007692 |
def initialize(self,*args,**kwargs):
"""
Only try to parse as JSON if the JSON content type
header is set.
"""
super(JSONHandler,self).initialize(*args,**kwargs)
content_type = self.request.headers.get('Content-Type', '')
if 'application/json' in content_type.lowe... | 0.016216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.