_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q41500 | ValidateS3UploadForm._generate_processed_key_name | train | def _generate_processed_key_name(process_to, upload_name):
"""Returns a key name to use after processing based on timestamp and
upload key name."""
timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
name, extension = os.path.splitext(upload_name)
digest = md5(''.join([timestam... | python | {
"resource": ""
} |
q41501 | ValidateS3UploadForm.clean_bucket_name | train | def clean_bucket_name(self):
"""Validates that the bucket name in the provided data matches the
bucket name from the storage backend."""
bucket_name = self.cleaned_data['bucket_name']
if not bucket_name == self.get_bucket_name():
raise forms.ValidationError('Bucket name does ... | python | {
"resource": ""
} |
q41502 | ValidateS3UploadForm.clean_key_name | train | def clean_key_name(self):
"""Validates that the key in the provided data starts with the
required prefix, and that it exists in the bucket."""
key = self.cleaned_data['key_name']
# Ensure key starts with prefix
if not key.startswith(self.get_key_prefix()):
raise forms... | python | {
"resource": ""
} |
q41503 | ValidateS3UploadForm.get_processed_key_name | train | def get_processed_key_name(self):
"""Return the full path to use for the processed file."""
if not hasattr(self, '_processed_key_name'):
path, upload_name = os.path.split(self.get_upload_key().name)
key_name = self._generate_processed_key_name(
self.process_to, up... | python | {
"resource": ""
} |
q41504 | ValidateS3UploadForm.get_processed_path | train | def get_processed_path(self):
"""Returns the processed file path from the storage backend.
:returns: File path from the storage backend.
:rtype: :py:class:`unicode`
"""
location = self.get_storage().location
return self.get_processed_key_name()[len(location):] | python | {
"resource": ""
} |
q41505 | ValidateS3UploadForm.process_upload | train | def process_upload(self, set_content_type=True):
"""Process the uploaded file."""
metadata = self.get_upload_key_metadata()
if set_content_type:
content_type = self.get_upload_content_type()
metadata.update({b'Content-Type': b'{0}'.format(content_type)})
upload_... | python | {
"resource": ""
} |
q41506 | ValidateS3UploadForm.get_upload_content_type | train | def get_upload_content_type(self):
"""Determine the actual content type of the upload."""
if not hasattr(self, '_upload_content_type'):
with self.get_storage().open(self.get_upload_path()) as upload:
content_type = Magic(mime=True).from_buffer(upload.read(1024))
s... | python | {
"resource": ""
} |
q41507 | ValidateS3UploadForm.get_upload_key | train | def get_upload_key(self):
"""Get the `Key` from the S3 bucket for the uploaded file.
:returns: Key (object) of the uploaded file.
:rtype: :py:class:`boto.s3.key.Key`
"""
if not hasattr(self, '_upload_key'):
self._upload_key = self.get_storage().bucket.get_key(
... | python | {
"resource": ""
} |
q41508 | ValidateS3UploadForm.get_upload_key_metadata | train | def get_upload_key_metadata(self):
"""Generate metadata dictionary from a bucket key."""
key = self.get_upload_key()
metadata = key.metadata.copy()
# Some http header properties which are stored on the key need to be
# copied to the metadata when updating
headers = {
... | python | {
"resource": ""
} |
q41509 | ValidateS3UploadForm.get_upload_path | train | def get_upload_path(self):
"""Returns the uploaded file path from the storage backend.
:returns: File path from the storage backend.
:rtype: :py:class:`unicode`
"""
location = self.get_storage().location
return self.cleaned_data['key_name'][len(location):] | python | {
"resource": ""
} |
q41510 | ask | train | def ask(question, escape=True):
"Return the answer"
answer = raw_input(question)
if escape:
answer.replace('"', '\\"')
return answer.decode('utf') | python | {
"resource": ""
} |
q41511 | Sesame.update_state | train | def update_state(self, cache=True):
"""Update the internal state of the Sesame."""
self.use_cached_state = cache
endpoint = API_SESAME_ENDPOINT.format(self._device_id)
response = self.account.request('GET', endpoint)
if response is None or response.status_code != 200:
... | python | {
"resource": ""
} |
q41512 | Sesame.lock | train | def lock(self):
"""Lock the Sesame. Return True on success, else False."""
endpoint = API_SESAME_CONTROL_ENDPOINT.format(self.device_id)
payload = {'type': 'lock'}
response = self.account.request('POST', endpoint, payload=payload)
if response is None:
return False
... | python | {
"resource": ""
} |
q41513 | PyPiRC.save | train | def save(self):
"""Saves pypirc file with new configuration information."""
for server, conf in self.servers.iteritems():
self._add_index_server()
for conf_k, conf_v in conf.iteritems():
if not self.conf.has_section(server):
self.conf.add_secti... | python | {
"resource": ""
} |
q41514 | PyPiRC._get_index_servers | train | def _get_index_servers(self):
"""Gets index-servers current configured in pypirc."""
idx_srvs = []
if 'index-servers' in self.conf.options('distutils'):
idx = self.conf.get('distutils', 'index-servers')
idx_srvs = [srv.strip() for srv in idx.split('\n') if srv.strip()]
... | python | {
"resource": ""
} |
q41515 | PyPiRC._add_index_server | train | def _add_index_server(self):
"""Adds index-server to 'distutil's 'index-servers' param."""
index_servers = '\n\t'.join(self.servers.keys())
self.conf.set('distutils', 'index-servers', index_servers) | python | {
"resource": ""
} |
q41516 | OutputMapper.outputmap | train | def outputmap(self, data):
""" Internal function used to traverse a data structure and map the contents onto python-friendly objects inplace.
This uses recursion, so try not to pass in anything that's over 255 objects deep.
:param data: data structure
:type data: any
... | python | {
"resource": ""
} |
q41517 | get_lux_count | train | def get_lux_count(lux_byte):
""" Method to convert data from the TSL2550D lux sensor
into more easily usable ADC count values.
"""
LUX_VALID_MASK = 0b10000000
LUX_CHORD_MASK = 0b01110000
LUX_STEP_MASK = 0b00001111
valid = lux_byte & LUX_VALID_MASK
if valid != 0:
step_n... | python | {
"resource": ""
} |
q41518 | SensorCluster.update_lux | train | def update_lux(self, extend=0):
""" Communicates with the TSL2550D light sensor and returns a
lux value.
Note that this method contains approximately 1 second of total delay.
This delay is necessary in order to obtain full resolution
compensated lux values.
... | python | {
"resource": ""
} |
q41519 | SensorCluster.update_humidity_temp | train | def update_humidity_temp(self):
""" This method utilizes the HIH7xxx sensor to read
humidity and temperature in one call.
"""
# Create mask for STATUS (first two bits of 64 bit wide result)
STATUS = 0b11 << 6
TCA_select(SensorCluster.bus, self.mux_addr, Senso... | python | {
"resource": ""
} |
q41520 | SensorCluster.sensor_values | train | def sensor_values(self):
"""
Returns the values of all sensors for this cluster
"""
self.update_instance_sensors(opt="all")
return {
"light": self.lux,
"water": self.soil_moisture,
"humidity": self.humidity,
"temperature": ... | python | {
"resource": ""
} |
q41521 | SensorCluster.get_water_level | train | def get_water_level(cls):
""" This method uses the ADC on the control module to measure
the current water tank level and returns the water volume
remaining in the tank.
For this method, it is assumed that a simple voltage divider
is used to interface the se... | python | {
"resource": ""
} |
q41522 | _imported_symbol | train | def _imported_symbol(import_path):
"""Resolve a dotted path into a symbol, and return that.
For example...
>>> _imported_symbol('django.db.models.Model')
<class 'django.db.models.base.Model'>
Raise ImportError if there's no such module, AttributeError if no
such symbol.
"""
module_na... | python | {
"resource": ""
} |
q41523 | Param | train | def Param(name, value=None, unit=None, ucd=None, dataType=None, utype=None,
ac=True):
"""
'Parameter', used as a general purpose key-value entry in the 'What' section.
May be assembled into a :class:`Group`.
NB ``name`` is not mandated by schema, but *is* mandated in full spec.
Args:
... | python | {
"resource": ""
} |
q41524 | Group | train | def Group(params, name=None, type=None):
"""Groups together Params for adding under the 'What' section.
Args:
params(list of :func:`Param`): Parameter elements to go in this group.
name(str): Group name. NB ``None`` is valid, since the group may be
best identified by its type.
... | python | {
"resource": ""
} |
q41525 | Reference | train | def Reference(uri, meaning=None):
"""
Represents external information, typically original obs data and metadata.
Args:
uri(str): Uniform resource identifier for external data, e.g. FITS file.
meaning(str): The nature of the document referenced, e.g. what
instrument and filter wa... | python | {
"resource": ""
} |
q41526 | EventIvorn | train | def EventIvorn(ivorn, cite_type):
"""
Used to cite earlier VOEvents.
Use in conjunction with :func:`.add_citations`
Args:
ivorn(str): It is assumed this will be copied verbatim from elsewhere,
and so these should have any prefix (e.g. 'ivo://','http://')
already in plac... | python | {
"resource": ""
} |
q41527 | Odp.batch | train | def batch(self, source_id, data):
""" Upload data to the given soruce
:param source_id: The ID of the source to upload to
:type source_id: str
:param data: The data to upload to the source
:type data: list
:return: dict of REST API output with headers... | python | {
"resource": ""
} |
q41528 | create_package_version | train | def create_package_version(requirement):
"""Create a new PackageVersion from a requirement. Handles errors."""
try:
PackageVersion(requirement=requirement).save()
logger.info("Package '%s' added.", requirement.name) # noqa
except IntegrityError:
logger.info("Package '%s' already exi... | python | {
"resource": ""
} |
q41529 | local | train | def local():
"""Load local requirements file."""
logger.info("Loading requirements from local file.")
with open(REQUIREMENTS_FILE, 'r') as f:
requirements = parse(f)
for r in requirements:
logger.debug("Creating new package: %r", r)
create_package_version(r) | python | {
"resource": ""
} |
q41530 | remote | train | def remote():
"""Update package info from PyPI."""
logger.info("Fetching latest data from PyPI.")
results = defaultdict(list)
packages = PackageVersion.objects.exclude(is_editable=True)
for pv in packages:
pv.update_from_pypi()
results[pv.diff_status].append(pv)
logger.debug(... | python | {
"resource": ""
} |
q41531 | Command.handle | train | def handle(self, *args, **options):
"""Run the managemement command."""
if options['clean']:
clean()
if options['local']:
local()
if options['remote']:
results = remote()
render = lambda t: render_to_string(t, results)
if opti... | python | {
"resource": ""
} |
q41532 | HistoricsPreview.create | train | def create(self, stream, start, parameters, sources, end=None):
""" Create a hitorics preview job.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/previewcreate
:param stream: hash of the CSDL filter to create the job for
:type stream: str
... | python | {
"resource": ""
} |
q41533 | HistoricsPreview.get | train | def get(self, preview_id):
""" Retrieve a Historics preview job.
Warning: previews expire after 24 hours.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/previewget
:param preview_id: historics preview job hash of the job to retrieve
... | python | {
"resource": ""
} |
q41534 | Historics.prepare | train | def prepare(self, hash, start, end, name, sources, sample=None):
""" Prepare a historics query which can later be started.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsprepare
:param hash: The hash of a CSDL create the query for
:type ... | python | {
"resource": ""
} |
q41535 | Historics.start | train | def start(self, historics_id):
""" Start the historics job with the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart
:param historics_id: hash of the job to start
:type historics_id: str
:return: dict of REST AP... | python | {
"resource": ""
} |
q41536 | Historics.update | train | def update(self, historics_id, name):
""" Update the name of the given Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsupdate
:param historics_id: playback id of the job to start
:type historics_id: str
:param... | python | {
"resource": ""
} |
q41537 | Historics.stop | train | def stop(self, historics_id, reason=''):
""" Stop an existing Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstop
:param historics_id: playback id of the job to stop
:type historics_id: str
:param reason: opt... | python | {
"resource": ""
} |
q41538 | Historics.status | train | def status(self, start, end, sources=None):
""" Check the data coverage in the Historics archive for a given interval.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstatus
:param start: Unix timestamp for the start time
:type start: int... | python | {
"resource": ""
} |
q41539 | Historics.delete | train | def delete(self, historics_id):
""" Delete one specified playback query. If the query is currently running, stop it.
status_code is set to 204 on success
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete
:param historics_id: playbac... | python | {
"resource": ""
} |
q41540 | Historics.get_for | train | def get_for(self, historics_id, with_estimate=None):
""" Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: str
:return... | python | {
"resource": ""
} |
q41541 | Historics.get | train | def get(self, historics_id=None, maximum=None, page=None, with_estimate=None):
""" Get the historics query with the given ID, if no ID is provided then get a list of historics queries.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param histor... | python | {
"resource": ""
} |
q41542 | Historics.pause | train | def pause(self, historics_id, reason=""):
""" Pause an existing Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicspause
:param historics_id: id of the job to pause
:type historics_id: str
:param reason: optional... | python | {
"resource": ""
} |
q41543 | Historics.resume | train | def resume(self, historics_id):
""" Resume a paused Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsresume
:param historics_id: id of the job to resume
:type historics_id: str
:return: dict of REST API output ... | python | {
"resource": ""
} |
q41544 | Resource.remove | train | def remove(self, source_id, resource_ids):
""" Remove one or more resources from a Managed Source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceresourceremove
:param source_id: target Source ID
:type source_id: str
:param resou... | python | {
"resource": ""
} |
q41545 | Auth.add | train | def add(self, source_id, auth, validate=True):
""" Add one or more sets of authorization credentials to a Managed Source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceauthadd
:param source_id: target Source ID
:type source_id: str
... | python | {
"resource": ""
} |
q41546 | Auth.remove | train | def remove(self, source_id, auth_ids):
""" Remove one or more sets of authorization credentials from a Managed Source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceauthremove
:param source_id: target Source ID
:type source_id: str
... | python | {
"resource": ""
} |
q41547 | ManagedSources.create | train | def create(self, source_type, name, resources, auth=None, parameters=None, validate=True):
""" Create a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcecreate
:param source_type: data source name e.g. facebook_page, googleplus, instagram,... | python | {
"resource": ""
} |
q41548 | ManagedSources.update | train | def update(self, source_id, source_type, name, resources, auth, parameters=None, validate=True):
""" Update a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceupdate
:param source_type: data source name e.g. facebook_page, googleplus, inst... | python | {
"resource": ""
} |
q41549 | ManagedSources.log | train | def log(self, source_id, page=None, per_page=None):
""" Get the log for a specific Managed Source.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcelog
:param source_id: target Source ID
:type source_id: str
:param page: (optional... | python | {
"resource": ""
} |
q41550 | ManagedSources.get | train | def get(self, source_id=None, source_type=None, page=None, per_page=None):
""" Get a specific managed source or a list of them.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceget
:param source_id: (optional) target Source ID
:type source_id... | python | {
"resource": ""
} |
q41551 | Laplacian.apply | train | def apply(self, localArray):
"""
Apply Laplacian stencil to data
@param localArray local array
@return new array on local proc
"""
# input dist array
inp = gdaZeros(localArray.shape, localArray.dtype, numGhosts=1)
# output array
out = numpy.zeros(... | python | {
"resource": ""
} |
q41552 | ndrive.login | train | def login(self, user_id, password, svctype = "Android NDrive App ver", auth = 0):
"""Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
... | python | {
"resource": ""
} |
q41553 | set_mysql | train | def set_mysql(host, user, password, db, charset):
"""Set the SQLAlchemy connection string with MySQL settings"""
manager.database.set_mysql_connection(
host=host,
user=user,
password=password,
db=db,
charset=charset
) | python | {
"resource": ""
} |
q41554 | quantile_gaussianize | train | def quantile_gaussianize(x):
"""Normalize a sequence of values via rank and Normal c.d.f.
Args:
x (array_like): sequence of values.
Returns:
Gaussian-normalized values.
Example:
.. doctest::
>>> from scipy_sugar.stats import quantile_gaussianize
>>> print(quantil... | python | {
"resource": ""
} |
q41555 | Peak.apply_noise | train | def apply_noise(self, noise_generator, split_idx, ndigits=6):
"""Apply noise to dimensions within a peak.
:param noise_generator: Noise generator object.
:param int split_idx: Index specifying which peak list split parameters to use.
:return: None
:rtype: :py:obj:`None`
... | python | {
"resource": ""
} |
q41556 | SequenceSite.is_sequential | train | def is_sequential(self):
"""Check if residues that sequence site is composed of are in sequential order.
:return: If sequence site is in valid sequential order (True) or not (False).
:rtype: :py:obj:`True` or :py:obj:`False`
"""
seq_ids = tuple(int(residue["Seq_ID"]) for residue... | python | {
"resource": ""
} |
q41557 | PeakDescription.create_dimension_groups | train | def create_dimension_groups(dimension_positions):
"""Create list of dimension groups.
:param zip dimension_positions: List of tuples describing dimension and its position within sequence site.
:return: List of dimension groups.
:rtype: :py:class:`list`
"""
dimension_grou... | python | {
"resource": ""
} |
q41558 | Spectrum.peak_templates | train | def peak_templates(self):
"""Create a list of concrete peak templates from a list of general peak descriptions.
:return: List of peak templates.
:rtype: :py:class:`list`
"""
peak_templates = []
for peak_descr in self:
expanded_dims = [dim_group.dimensions for... | python | {
"resource": ""
} |
q41559 | Spectrum.seq_site_length | train | def seq_site_length(self):
"""Calculate length of a single sequence site based upon relative positions specified in peak descriptions.
:return: Length of sequence site.
:rtype: :py:class:`int`
"""
relative_positions_set = set()
for peak_descr in self:
relativ... | python | {
"resource": ""
} |
q41560 | StarFileToPeakList.create_spectrum | train | def create_spectrum(spectrum_name):
"""Initialize spectrum and peak descriptions.
:param str spectrum_name: Name of the spectrum from which peak list will be simulated.
:return: Spectrum object.
:rtype: :class:`~nmrstarlib.plsimulator.Spectrum`
"""
try:
spect... | python | {
"resource": ""
} |
q41561 | StarFileToPeakList.create_sequence_sites | train | def create_sequence_sites(chain, seq_site_length):
"""Create sequence sites using sequence ids.
:param dict chain: Chain object that contains chemical shift values and assignment information.
:param int seq_site_length: Length of a single sequence site.
:return: List of sequence sites.
... | python | {
"resource": ""
} |
q41562 | StarFileToPeakList.calculate_intervals | train | def calculate_intervals(chunk_sizes):
"""Calculate intervals for a given chunk sizes.
:param list chunk_sizes: List of chunk sizes.
:return: Tuple of intervals.
:rtype: :py:class:`tuple`
"""
start_indexes = [sum(chunk_sizes[:i]) for i in range(0, len(chunk_sizes))]
... | python | {
"resource": ""
} |
q41563 | StarFileToPeakList.split_by_percent | train | def split_by_percent(self, spin_systems_list):
"""Split list of spin systems by specified percentages.
:param list spin_systems_list: List of spin systems.
:return: List of spin systems divided into sub-lists corresponding to specified split percentages.
:rtype: :py:class:`list`
... | python | {
"resource": ""
} |
q41564 | StarFileToPeakList.create_peaklist | train | def create_peaklist(self, spectrum, chain, chain_idx, source):
"""Create peak list file.
:param spectrum: Spectrum object instance.
:type spectrum: :class:`~nmrstarlib.plsimulator.Spectrum`
:param dict chain: Chain object that contains chemical shift values and assignment information.
... | python | {
"resource": ""
} |
q41565 | daArray | train | def daArray(arry, dtype=numpy.float):
"""
Array constructor for numpy distributed array
@param arry numpy-like array
"""
a = numpy.array(arry, dtype)
res = DistArray(a.shape, a.dtype)
res[:] = a
return res | python | {
"resource": ""
} |
q41566 | daZeros | train | def daZeros(shap, dtype=numpy.float):
"""
Zero constructor for numpy distributed array
@param shap the shape of the array
@param dtype the numpy data type
"""
res = DistArray(shap, dtype)
res[:] = 0
return res | python | {
"resource": ""
} |
q41567 | daOnes | train | def daOnes(shap, dtype=numpy.float):
"""
One constructor for numpy distributed array
@param shap the shape of the array
@param dtype the numpy data type
"""
res = DistArray(shap, dtype)
res[:] = 1
return res | python | {
"resource": ""
} |
q41568 | mdaArray | train | def mdaArray(arry, dtype=numpy.float, mask=None):
"""
Array constructor for masked distributed array
@param arry numpy-like array
@param mask mask array (or None if all data elements are valid)
"""
a = numpy.array(arry, dtype)
res = MaskedDistArray(a.shape, a.dtype)
res[:] = a
res.ma... | python | {
"resource": ""
} |
q41569 | mdaZeros | train | def mdaZeros(shap, dtype=numpy.float, mask=None):
"""
Zero constructor for masked distributed array
@param shap the shape of the array
@param dtype the numpy data type
@param mask mask array (or None if all data elements are valid)
"""
res = MaskedDistArray(shap, dtype)
res[:] = 0
re... | python | {
"resource": ""
} |
q41570 | mdaOnes | train | def mdaOnes(shap, dtype=numpy.float, mask=None):
"""
One constructor for masked distributed array
@param shap the shape of the array
@param dtype the numpy data type
@param mask mask array (or None if all data elements are valid)
"""
res = MaskedDistArray(shap, dtype)
res[:] = 1
res.... | python | {
"resource": ""
} |
q41571 | UploadForm.stash | train | def stash(self, storage, url):
"""Stores the uploaded file in a temporary storage location."""
result = {}
if self.is_valid():
upload = self.cleaned_data['upload']
name = storage.save(upload.name, upload)
result['filename'] = os.path.basename(name)
... | python | {
"resource": ""
} |
q41572 | CandyHouseAccount.login | train | def login(self, email=None, password=None, timeout=5):
"""Log in to CANDY HOUSE account. Return True on success."""
if email is not None:
self.email = email
if password is not None:
self.password = password
url = self.api_url + API_LOGIN_ENDPOINT
data = j... | python | {
"resource": ""
} |
q41573 | CandyHouseAccount.request | train | def request(self, method, endpoint, payload=None, timeout=5):
"""Send request to API."""
url = self.api_url + endpoint
data = None
headers = {}
if payload is not None:
data = json.dumps(payload)
headers['Content-Type'] = 'application/json'
try:
... | python | {
"resource": ""
} |
q41574 | CandyHouseAccount.sesames | train | def sesames(self):
"""Return list of Sesames."""
response = self.request('GET', API_SESAME_LIST_ENDPOINT)
if response is not None and response.status_code == 200:
return json.loads(response.text)['sesames']
_LOGGER.warning("Unable to list Sesames")
return [] | python | {
"resource": ""
} |
q41575 | get_api | train | def get_api(
profile=None,
config_file=None,
requirements=None):
'''
Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config fi... | python | {
"resource": ""
} |
q41576 | check_requirements | train | def check_requirements(to_populate, prompts, helper=False):
'''
Iterates through required values, checking to_populate for required values
If a key in prompts is missing in to_populate and ``helper==True``,
prompts the user using the values in to_populate. Otherwise, raises an
error.
Parameter... | python | {
"resource": ""
} |
q41577 | UploadView.post | train | def post(self, *args, **kwargs):
"""Save file and return saved info or report errors."""
if self.upload_allowed():
form = self.get_upload_form()
result = {}
if form.is_valid():
storage = self.get_storage()
result['is_valid'] = True
... | python | {
"resource": ""
} |
q41578 | UploadView.get_upload_form | train | def get_upload_form(self):
"""Construct form for accepting file upload."""
return self.form_class(self.request.POST, self.request.FILES) | python | {
"resource": ""
} |
q41579 | from_url | train | def from_url(location):
""" HTTP request for page at location returned as string
malformed url returns ValueError
nonexistant IP returns URLError
wrong subnet IP return URLError
reachable IP, no HTTP server returns URLError
reachable IP, HTTP, wrong page returns HTTPError
"""
req = urll... | python | {
"resource": ""
} |
q41580 | parse_description_xml | train | def parse_description_xml(location):
""" Extract serial number, base ip, and img url from description.xml
missing data from XML returns AttributeError
malformed XML returns ParseError
Refer to included example for URLBase and serialNumber elements
"""
class _URLBase(str):
""" Convenien... | python | {
"resource": ""
} |
q41581 | _build_from | train | def _build_from(baseip):
""" Build URL for description.xml from ip """
from ipaddress import ip_address
try:
ip_address(baseip)
except ValueError:
# """attempt to construct url but the ip format has changed"""
# logger.warning("Format of internalipaddress changed: %s", baseip)
... | python | {
"resource": ""
} |
q41582 | via_upnp | train | def via_upnp():
""" Use SSDP as described by the Philips guide """
ssdp_list = ssdp_discover("ssdp:all", timeout=5)
#import pickle
#with open("ssdp.pickle", "wb") as f:
#pickle.dump(ssdp_list,f)
bridges_from_ssdp = [u for u in ssdp_list if 'IpBridge' in u.server]
logger.info('SSDP return... | python | {
"resource": ""
} |
q41583 | via_nupnp | train | def via_nupnp():
""" Use method 2 as described by the Philips guide """
bridges_from_portal = parse_portal_json()
logger.info('Portal returned %d Hue bridges(s).',
len(bridges_from_portal))
# Confirm Portal gave an accessible bridge device by reading from the returned
# location. S... | python | {
"resource": ""
} |
q41584 | via_scan | train | def via_scan():
""" IP scan - now implemented """
import socket
import ipaddress
import httpfind
bridges_from_scan = []
hosts = socket.gethostbyname_ex(socket.gethostname())[2]
for host in hosts:
bridges_from_scan += httpfind.survey(
# TODO: how do we determine subnet con... | python | {
"resource": ""
} |
q41585 | find_bridges | train | def find_bridges(prior_bridges=None):
""" Confirm or locate IP addresses of Philips Hue bridges.
`prior_bridges` -- optional list of bridge serial numbers
* omitted - all discovered bridges returned as dictionary
* single string - returns IP as string or None
* dictionary - validate provided ip's b... | python | {
"resource": ""
} |
q41586 | ByPackage.matches | train | def matches(self, a, b, **config):
""" The message must match by package """
package_a = self.processor._u2p(a['msg']['update']['title'])[0]
package_b = self.processor._u2p(b['msg']['update']['title'])[0]
if package_a != package_b:
return False
return True | python | {
"resource": ""
} |
q41587 | PackageVersion.update_from_pypi | train | def update_from_pypi(self):
"""Call get_latest_version and then save the object."""
package = pypi.Package(self.package_name)
self.licence = package.licence()
if self.is_parseable:
self.latest_version = package.latest_version()
self.next_version = package.next_ver... | python | {
"resource": ""
} |
q41588 | Connector.sendfile | train | def sendfile(self, data, zlib_compress=None, compress_level=6):
"""Send data from a file object"""
if hasattr(data, 'seek'):
data.seek(0)
chunk_size = CHUNK_SIZE
if zlib_compress:
chunk_size = BLOCK_SIZE
compressor = compressobj(compress_level)
... | python | {
"resource": ""
} |
q41589 | ghostedDistArrayFactory | train | def ghostedDistArrayFactory(BaseClass):
"""
Returns a ghosted distributed array class that derives from BaseClass
@param BaseClass base class, e.g. DistArray or MaskedDistArray
@return ghosted dist array class
"""
class GhostedDistArrayAny(BaseClass):
"""
Ghosted distributed arr... | python | {
"resource": ""
} |
q41590 | serialize_upload | train | def serialize_upload(name, storage, url):
"""
Serialize uploaded file by name and storage. Namespaced by the upload url.
"""
if isinstance(storage, LazyObject):
# Unwrap lazy storage class
storage._setup()
cls = storage._wrapped.__class__
else:
cls = storage.__class__... | python | {
"resource": ""
} |
q41591 | deserialize_upload | train | def deserialize_upload(value, url):
"""
Restore file and name and storage from serialized value and the upload url.
"""
result = {'name': None, 'storage': None}
try:
result = signing.loads(value, salt=url)
except signing.BadSignature:
# TODO: Log invalid signature
pass
... | python | {
"resource": ""
} |
q41592 | open_stored_file | train | def open_stored_file(value, url):
"""
Deserialize value for a given upload url and return open file.
Returns None if deserialization fails.
"""
upload = None
result = deserialize_upload(value, url)
filename = result['name']
storage_class = result['storage']
if storage_class and filen... | python | {
"resource": ""
} |
q41593 | _check_action | train | def _check_action(action):
"""check for invalid actions"""
if isinstance(action, types.StringTypes):
action = action.lower()
if action not in ['learn', 'forget', 'report', 'revoke']:
raise SpamCError('The action option is invalid')
return action | python | {
"resource": ""
} |
q41594 | get_response | train | def get_response(cmd, conn):
"""Return a response"""
resp = conn.socket().makefile('rb', -1)
resp_dict = dict(
code=0,
message='',
isspam=False,
score=0.0,
basescore=0.0,
report=[],
symbols=[],
headers={},
)
if cmd == 'TELL':
r... | python | {
"resource": ""
} |
q41595 | SpamC.get_headers | train | def get_headers(self, cmd, msg_length, extra_headers):
"""Returns the headers string based on command to execute"""
cmd_header = "%s %s" % (cmd, PROTOCOL_VERSION)
len_header = "Content-length: %s" % msg_length
headers = [cmd_header, len_header]
if self.user:
user_head... | python | {
"resource": ""
} |
q41596 | SpamC.perform | train | def perform(self, cmd, msg='', extra_headers=None):
"""Perform the call"""
tries = 0
while 1:
conn = None
try:
conn = self.get_connection()
if hasattr(msg, 'read') and hasattr(msg, 'fileno'):
msg_length = str(os.fstat(ms... | python | {
"resource": ""
} |
q41597 | generate_key | train | def generate_key(filepath):
''' generates a new, random secret key at the given location on the
filesystem and returns its path
'''
fs = path.abspath(path.expanduser(filepath))
with open(fs, 'wb') as outfile:
outfile.write(Fernet.generate_key())
chmod(fs, 0o400)
return fs | python | {
"resource": ""
} |
q41598 | get_key | train | def get_key(key=None, keyfile=None):
""" returns a key given either its value, a path to it on the filesystem
or as last resort it checks the environment variable CRYPTOYAML_SECRET
"""
if key is None:
if keyfile is None:
key = environ.get('CRYPTOYAML_SECRET')
if key is No... | python | {
"resource": ""
} |
q41599 | CryptoYAML.read | train | def read(self):
""" Reads and decrypts data from the filesystem """
if path.exists(self.filepath):
with open(self.filepath, 'rb') as infile:
self.data = yaml.load(
self.fernet.decrypt(infile.read()))
else:
self.data = dict() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.