code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def area2lonlat(dataarray):
area = dataarray.attrs['area']
lons, lats = area.get_lonlats_dask()
lons = xr.DataArray(lons, dims=['y', 'x'],
attrs={'name': "longitude",
'standard_name': "longitude",
'units': 'degrees_east'},
name='longitude')
lats = xr.DataArray(lats, dims=['y', 'x'],
attrs={'name': "latitude",
'standard_name': "latitude",
'units': 'degrees_north'},
name='latitude')
dataarray.attrs['coordinates'] = 'longitude latitude'
return [dataarray, lons, lats] | Convert an area to longitudes and latitudes. |
def explorev2(self, datasource_type, datasource_id):
return redirect(url_for(
'Superset.explore',
datasource_type=datasource_type,
datasource_id=datasource_id,
**request.args)) | Deprecated endpoint, here for backward compatibility of urls |
def force_single_imports(self):
for import_stmt in self.imports[:]:
import_info = import_stmt.import_info
if import_info.is_empty() or import_stmt.readonly:
continue
if len(import_info.names_and_aliases) > 1:
for name_and_alias in import_info.names_and_aliases:
if hasattr(import_info, "module_name"):
new_import = importinfo.FromImport(
import_info.module_name, import_info.level,
[name_and_alias])
else:
new_import = importinfo.NormalImport([name_and_alias])
self.add_import(new_import)
import_stmt.empty_import() | force a single import per statement |
def update_ticket(self, ticket_id, **kwargs):
url = 'tickets/%d' % ticket_id
ticket = self._api._put(url, data=json.dumps(kwargs))
return Ticket(**ticket) | Updates a ticket from a given ticket ID |
def subset(data, sel0, sel1):
data = np.asarray(data)
if data.ndim < 2:
raise ValueError('data must have 2 or more dimensions')
sel0 = asarray_ndim(sel0, 1, allow_none=True)
sel1 = asarray_ndim(sel1, 1, allow_none=True)
if sel0 is not None and sel0.dtype.kind == 'b':
sel0, = np.nonzero(sel0)
if sel1 is not None and sel1.dtype.kind == 'b':
sel1, = np.nonzero(sel1)
if sel0 is not None and sel1 is not None:
sel0 = sel0[:, np.newaxis]
if sel0 is None:
sel0 = _total_slice
if sel1 is None:
sel1 = _total_slice
return data[sel0, sel1] | Apply selections on first and second axes. |
def _dismiss_worker(self, worker):
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True | Dismiss ``worker`` unless it is still required |
def get(self, thread_uuid, uuid):
members = (v for v in self.list(thread_uuid) if v.get('userUuid') == uuid)
for i in members:
self.log.debug(i)
return i
return None | Get one thread member. |
def crashlog_clean(name, timestamp, size, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action('crashlog:clean', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'size': size,
'timestamp': timestamp,
}) | For application NAME leave SIZE crashlogs or remove all crashlogs with timestamp > TIMESTAMP. |
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. |
def _extract_germline(in_file, data):
out_file = "%s-germline.vcf" % utils.splitext_plus(in_file)[0]
if not utils.file_uptodate(out_file, in_file) and not utils.file_uptodate(out_file + ".gz", in_file):
with file_transaction(data, out_file) as tx_out_file:
reader = cyvcf2.VCF(str(in_file))
reader.add_filter_to_header({'ID': 'Somatic', 'Description': 'Variant called as Somatic'})
with open(tx_out_file, "w") as out_handle:
out_handle.write(reader.raw_header)
for rec in reader:
rec = _update_germline_filters(rec)
out_handle.write(str(rec))
return out_file | Extract germline calls non-somatic, non-filtered calls. |
def _attach_config(mfg_event, record):
if 'config' not in record.metadata:
return
attachment = mfg_event.attachment.add()
attachment.name = 'config'
attachment.value_binary = _convert_object_to_json(record.metadata['config'])
attachment.type = test_runs_pb2.TEXT_UTF8 | Attaches the OpenHTF config file as JSON. |
def OnTextSize(self, event):
try:
size = int(event.GetString())
except Exception:
size = get_default_font().GetPointSize()
post_command_event(self, self.FontSizeMsg, size=size) | Text size combo text event handler |
def find_silent_exception(node):
return (
isinstance(node, ast.ExceptHandler)
and node.type is None
and len(node.body) == 1
and isinstance(node.body[0], ast.Pass)
) | Finds silent generic exceptions |
def timeit(output):
b = time.time()
yield
print output, 'time used: %.3fs' % (time.time()-b) | If output is string, then print the string and also time used |
def percent(self, value: float) -> 'Size':
raise_not_number(value)
self.maximum = '{}%'.format(value)
return self | Set the percentage of free space to use. |
def register_class(cls):
if cls.appname in LinkFactory._class_dict:
return
LinkFactory.register(cls.appname, cls) | Regsiter this class in the `LinkFactory` |
def sendTemplate(mailer, sender, recipient, template, context, hook=_nop):
headers, parts = template.evaluate(context)
headers["From"] = sender
headers["To"] = recipient
hook(headers, parts)
content = mime.buildMessage(headers, parts)
return mailer.send(sender, recipient, content) | Simple case for sending some e-mail using a template. |
def index(self, alias):
clone = self._clone()
clone._index = alias
return clone | Selects which database this QuerySet should execute its query against. |
def page_response(self, title='', body=''):
f = StringIO()
f.write('<!DOCTYPE html>\n')
f.write('<html>\n')
f.write('<head><title>{}</title><head>\n'.format(title))
f.write('<body>\n<h2>{}</h2>\n'.format(title))
f.write('<div class="content">{}</div>\n'.format(body))
f.write('</body>\n</html>\n')
length = f.tell()
f.seek(0)
self.send_response(200)
encoding = sys.getfilesystemencoding()
self.send_header("Content-type", "text/html; charset=%s" % encoding)
self.send_header("Content-Length", str(length))
self.end_headers()
self.copyfile(f, self.wfile)
f.close() | Helper to render an html page with dynamic content |
def _copy_source_to_target(self):
if self.source and self.target:
for k, v in self.source.items('config'):
self.target.set_input(k, v) | copy source user configuration to target |
def fasta_cmd_get_seqs(acc_list,
blast_db=None,
is_protein=None,
out_filename=None,
params={},
WorkingDir=tempfile.gettempdir(),
SuppressStderr=None,
SuppressStdout=None):
if is_protein is None:
params["-p"] = 'G'
elif is_protein:
params["-p"] = 'T'
else:
params["-p"] = 'F'
if blast_db:
params["-d"] = blast_db
if out_filename:
params["-o"] = out_filename
params["-a"] = "F"
fasta_cmd = FastaCmd(params=params,
InputHandler='_input_as_string',
WorkingDir=WorkingDir,
SuppressStderr=SuppressStderr,
SuppressStdout=SuppressStdout)
return fasta_cmd("\"%s\"" % ','.join(acc_list)) | Retrieve sequences for list of accessions |
def check_bbox(bbox):
for name, value in zip(['x_min', 'y_min', 'x_max', 'y_max'], bbox[:4]):
if not 0 <= value <= 1:
raise ValueError(
'Expected {name} for bbox {bbox} '
'to be in the range [0.0, 1.0], got {value}.'.format(
bbox=bbox,
name=name,
value=value,
)
)
x_min, y_min, x_max, y_max = bbox[:4]
if x_max <= x_min:
raise ValueError('x_max is less than or equal to x_min for bbox {bbox}.'.format(
bbox=bbox,
))
if y_max <= y_min:
raise ValueError('y_max is less than or equal to y_min for bbox {bbox}.'.format(
bbox=bbox,
)) | Check if bbox boundaries are in range 0, 1 and minimums are lesser then maximums |
def compliance(self, value):
if (self.api_version < '2.0'):
self.profile = value
else:
try:
self.profile[0] = value
except AttributeError:
self.profile = [value] | Set the compliance profile URI. |
def _needs_elements(self, f):
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.elements == None:
self.getelements()
return f(self, *args, **kwargs)
return wrapper | Decorator used to make sure that there are elements prior to running the task. |
def _delete_chars(self, value):
value = int(value)
if value <= 0:
value = 1
for i in range(value):
self._cursor.deleteChar()
self._text_edit.setTextCursor(self._cursor)
self._last_cursor_pos = self._cursor.position() | Deletes the specified number of charachters. |
def _transform_coefficients(self, NN, HHw, CCw, ffparm, polycf,
any_pwl, npol, nw):
nnw = any_pwl + npol + nw
M = csr_matrix((ffparm[:, 3], (range(nnw), range(nnw))))
MR = M * ffparm[:, 2]
HMR = HHw * MR
MN = M * NN
HH = MN.T * HHw * MN
CC = MN.T * (CCw - HMR)
C0 = 1./2. * MR.T * HMR + sum(polycf[:, 2])
return HH, CC, C0[0] | Transforms quadratic coefficients for w into coefficients for x. |
def generate_route(self, route):
self.emit('')
self.emit('route %s (%s, %s, %s)' % (
route.name,
self.format_data_type(route.arg_data_type),
self.format_data_type(route.result_data_type),
self.format_data_type(route.error_data_type)
))
with self.indent():
if route.doc is not None:
self.emit(self.format_string(route.doc)) | Output a route definition. |
def _refresh_path(self):
if os.path.exists(self.path):
try:
i = open(self.path, 'r')
i.close()
juicer.utils.Log.log_debug("Successfully read item at: %s" % self.path)
except:
raise IOError("Error while attempting to access item at path: %s" % self.path)
else:
raise IOError("Could not locate item at path: %s" % self.path) | Does it exist? Can we read it? Is it an RPM? |
def __create_xml_request(self, text):
soap_root = ET.Element('soap:Envelope', {
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:soap': 'http://schemas.xmlsoap.org/soap/envelope/', })
body = ET.SubElement(soap_root, 'soap:Body')
process_text = ET.SubElement(body, 'ProcessText', {
'xmlns': 'http://typograf.artlebedev.ru/webservices/', })
ET.SubElement(process_text, 'text').text = text
ET.SubElement(process_text, 'entityType').text = str(self._entityType)
ET.SubElement(process_text, 'useBr').text = str(self._useBr)
ET.SubElement(process_text, 'useP').text = str(self._useP)
ET.SubElement(process_text, 'maxNobr').text = str(self._maxNobr)
string = Container()
soap = ET.ElementTree(soap_root)
soap.write(string, encoding=self._encoding, xml_declaration=True)
if PY3:
return string.getvalue().decode(self._encoding)
return string.getvalue() | make xml content from given text |
def register_single(key, value, param=None):
get_current_scope().container.register(key, lambda: value, param) | Generates resolver to return singleton value and adds it to global container |
def apply_filters(df, filters):
idx = pd.Series([True]*df.shape[0])
for k, v in list(filters.items()):
if k not in df.columns:
continue
idx &= (df[k] == v)
return df.loc[idx] | Basic filtering for a dataframe. |
def setdefault(obj, field, default):
setattr(obj, field, getattr(obj, field, default)) | Set an object's field to default if it doesn't have a value |
def _check_descendant(self, item):
children = self.get_children(item)
for iid in children:
self.change_state(iid, "checked")
self._check_descendant(iid) | Check the boxes of item's descendants. |
def _dataChanged(self, item):
index = self.items.index(item)
qindex = self.createIndex(index, 0)
self.dataChanged.emit(qindex, qindex) | Explicitly emit dataChanged upon item changing |
def copy_abiext(self, inext, outext):
infile = self.has_abiext(inext)
if not infile:
raise RuntimeError('no file with extension %s in %s' % (inext, self))
for i in range(len(infile) - 1, -1, -1):
if infile[i] == '_':
break
else:
raise RuntimeError('Extension %s could not be detected in file %s' % (inext, infile))
outfile = infile[:i] + '_' + outext
shutil.copy(infile, outfile)
return 0 | Copy the Abinit file with extension inext to a new file withw extension outext |
def add_empty_fields(untl_dict):
for element in UNTL_XML_ORDER:
if element not in untl_dict:
try:
py_object = PYUNTL_DISPATCH[element](
content='',
qualifier='',
)
except:
try:
py_object = PYUNTL_DISPATCH[element](content='')
except:
try:
py_object = PYUNTL_DISPATCH[element]()
except:
raise PyuntlException(
'Could not add empty element field.'
)
else:
untl_dict[element] = [{'content': {}}]
else:
if not py_object.contained_children:
untl_dict[element] = [{'content': ''}]
else:
untl_dict[element] = [{'content': {}}]
else:
if not py_object.contained_children:
untl_dict[element] = [{'content': '', 'qualifier': ''}]
else:
untl_dict[element] = [{'content': {}, 'qualifier': ''}]
for child in py_object.contained_children:
untl_dict[element][0].setdefault('content', {})
untl_dict[element][0]['content'][child] = ''
return untl_dict | Add empty values if UNTL fields don't have values. |
def product_path(cls, project, location, product):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/products/{product}",
project=project,
location=location,
product=product,
) | Return a fully-qualified product string. |
def save_image(self, image_file):
self.ensure_pyplot()
command = 'plt.gcf().savefig("%s")'%image_file
self.process_input_line('bookmark ipy_thisdir', store_history=False)
self.process_input_line('cd -b ipy_savedir', store_history=False)
self.process_input_line(command, store_history=False)
self.process_input_line('cd -b ipy_thisdir', store_history=False)
self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
self.clear_cout() | Saves the image file to disk. |
def status(self, verbose=False):
try:
response=api(url=self.__url, method="GET", verbose=verbose)
except Exception as e:
print('Could not get status from CyREST:\n\n' + str(e))
else:
print('CyREST online!') | Checks the status of your CyREST server. |
def binary_report(self, sha256sum, apikey):
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, data=params)
if response.status_code == self.HTTP_OK:
json_response = response.json()
response_code = json_response['response_code']
return json_response
elif response.status_code == self.HTTP_RATE_EXCEEDED:
time.sleep(20)
else:
self.logger.warning("retrieve report: %s, HTTP code: %d", os.path.basename(filename), response.status_code) | retrieve report from file scan |
def _format_list_objects(result):
all_keys = set()
for item in result:
all_keys = all_keys.union(item.keys())
all_keys = sorted(all_keys)
table = Table(all_keys)
for item in result:
values = []
for key in all_keys:
value = iter_to_table(item.get(key))
values.append(value)
table.add_row(values)
return table | Format list of objects into a table. |
def delete(self, *args, **kwargs):
source_cache = self.get_source_cache()
self.delete_thumbnails(source_cache)
super(ThumbnailerFieldFile, self).delete(*args, **kwargs)
if source_cache and source_cache.pk is not None:
source_cache.delete() | Delete the image, along with any generated thumbnails. |
def config_value_changed(option):
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved is None:
return False
return current != saved | Determine if config value changed since last call to this function. |
def range_r(self):
return self.radius - self.dr, self.radius + self.dr | Current interpolation range of radius |
def compute_message_authenticator(radius_packet, packed_req_authenticator,
shared_secret):
data = prepare_packed_data(radius_packet, packed_req_authenticator)
radius_hmac = hmac.new(shared_secret, data, hashlib.md5)
return radius_hmac.digest() | Computes the "Message-Authenticator" of a given RADIUS packet. |
def printSequence(x, formatString="%d"):
numElements = len(x)
s = ""
for j in range(numElements):
s += formatString % x[j]
print s | Compact print a list or numpy array. |
def deep_encode(s, encoding='utf-8', errors='strict'):
s = deep_encode(s)
if sys.version_info.major < 3 and isinstance(s, unicode):
return s.encode(encoding, errors)
if isinstance(s, (list, tuple)):
return [deep_encode(i, encoding=encoding, errors=errors) for i in s]
if isinstance(s, dict):
return dict([
(
deep_encode(key, encoding=encoding, errors=errors),
deep_encode(s[key], encoding=encoding, errors=errors)
) for key in s
])
return s | Encode "DEEP" S using the codec registered for encoding. |
def create_order(self, order_deets):
request = self._post('transactions/orders', order_deets)
return self.responder(request) | Creates a new order transaction. |
def on_get(self, req, resp):
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
try:
containers = docker.from_env()
except Exception as e:
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
container_list = []
try:
for c in containers.containers.list(all=True):
if c.attrs['Config']['Image'] == \
'cyberreboot/vent-ncapture:master':
if 'core' not in c.attrs['Config']['Labels']['vent.groups']:
lst = {}
lst['id'] = c.attrs['Id'][:12]
lst['status'] = c.attrs['State']['Status']
lst['args'] = c.attrs['Args']
container_list.append(lst)
except Exception as e:
resp.body = "(False, 'Failure because: " + str(e) + "')"
return
resp.body = json.dumps(container_list)
return | Send a GET request to get the list of all of the filter containers |
def _process_open(self):
click.launch(self._format_issue_url())
if not click.confirm('Did it work?', default=True):
click.echo()
self._process_print()
click.secho(
'\nOpen the line manually and copy the text above\n',
fg='yellow'
)
click.secho(
' ' + self.REPO_URL + self.ISSUE_SUFFIX + '\n', bold=True
) | Open link in a browser. |
def _prepare_if_args(stmt):
args = stmt['args']
if args and args[0].startswith('(') and args[-1].endswith(')'):
args[0] = args[0][1:].lstrip()
args[-1] = args[-1][:-1].rstrip()
start = int(not args[0])
end = len(args) - int(not args[-1])
args[:] = args[start:end] | Removes parentheses from an "if" directive's arguments |
def commit(self):
if self.session is not None:
logger.info("committing transaction in %s" % self)
tmp = self.stable
self.stable, self.session = self.session, None
self.istable = 1 - self.istable
self.write_istable()
tmp.close()
self.lock_update.release()
else:
logger.warning("commit called but there's no open session in %s" % self) | Commit changes made by the latest session. |
def eigenvalues_(self):
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist() | The eigenvalues associated with each principal component. |
def tokhex(length=10, urlsafe=False):
if urlsafe is True:
return secrets.token_urlsafe(length)
return secrets.token_hex(length) | Return a random string in hexadecimal |
def breaks(self, frame, no_remove=False):
for breakpoint in set(self.breakpoints):
if breakpoint.breaks(frame):
if breakpoint.temporary and not no_remove:
self.breakpoints.remove(breakpoint)
return True
return False | Return True if there's a breakpoint at frame |
def compute(cls, observation, prediction):
assert isinstance(observation, dict)
try:
p_value = prediction['mean']
except (TypeError, KeyError, IndexError):
try:
p_value = prediction['value']
except (TypeError, IndexError):
p_value = prediction
o_mean = observation['mean']
o_std = observation['std']
value = (p_value - o_mean)/o_std
value = utils.assert_dimensionless(value)
if np.isnan(value):
score = InsufficientDataScore('One of the input values was NaN')
else:
score = ZScore(value)
return score | Compute a z-score from an observation and a prediction. |
def run_forecast(self):
self.prepare_hmet()
self.prepare_gag()
self.rapid_to_gssha()
self.hotstart()
return self.run() | Updates card & runs for RAPID to GSSHA & LSM to GSSHA |
def load_jupyter_server_extension(nbapp):
here = PACKAGE_DIR
nbapp.log.info('nteract extension loaded from %s' % here)
app_dir = here
web_app = nbapp.web_app
config = NteractConfig(parent=nbapp)
config.assets_dir = app_dir
config.page_url = '/nteract'
config.dev_mode = False
core_mode = ''
if hasattr(nbapp, 'core_mode'):
core_mode = nbapp.core_mode
if app_dir == here or app_dir == os.path.join(here, 'build'):
core_mode = True
config.settings_dir = ''
web_app.settings.setdefault('page_config_data', dict())
web_app.settings['page_config_data']['token'] = nbapp.token
web_app.settings['page_config_data']['ga_code'] = config.ga_code
web_app.settings['page_config_data']['asset_url'] = config.asset_url
web_app.settings['nteract_config'] = config
add_handlers(web_app, config) | Load the server extension. |
def browse(self):
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open('file://' + path) | Save response in temporary file and open it in GUI browser. |
def visit_Name(self, node):
return self.add(node, self.result[node.id]) | Get range for parameters for examples or false branching. |
def text(self):
txBody = self.txBody
if txBody is None:
return ''
return '\n'.join([p.text for p in txBody.p_lst]) | str text contained in cell |
def read_variant(variant):
result = 0
cnt = 0
for data in variant:
result |= (data & 0x7f) << (7 * cnt)
cnt += 1
if not data & 0x80:
return result, variant[cnt:]
raise Exception('invalid variant') | Read and parse a binary protobuf variant value. |
def patch_tree(actions, tree):
patcher = patch.Patcher()
return patcher.patch(actions, tree) | Takes an lxml root element or element tree, and a list of actions |
def cache(cls, id):
sampler = {'unit': 'days', 'value': 1, 'function': 'sum'}
query = 'webacc.requests.cache.all'
metrics = Metric.query(id, 60 * 60 * 24, query, 'paas', sampler)
cache = {'hit': 0, 'miss': 0, 'not': 0, 'pass': 0}
for metric in metrics:
what = metric['cache'].pop()
for point in metric['points']:
value = point.get('value', 0)
cache[what] += value
return cache | return the number of query cache for the last 24H |
async def _async_get_sshable_ips(self, ip_addresses):
async def _async_ping(ip_address):
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(ip_address, 22), timeout=5)
except (OSError, TimeoutError):
return None
try:
line = await reader.readline()
finally:
writer.close()
if line.startswith(b'SSH-'):
return ip_address
ssh_ips = await asyncio.gather(*[
_async_ping(ip_address)
for ip_address in ip_addresses
])
return [
ip_address
for ip_address in ssh_ips
if ip_address is not None
] | Return list of all IP address that could be pinged. |
def gray2int(graystr):
num = bin2int(graystr)
num ^= (num >> 8)
num ^= (num >> 4)
num ^= (num >> 2)
num ^= (num >> 1)
return num | Convert greycode to binary |
def reset_experiment(experiment):
redis = _get_redis_connection()
experiment = Experiment.find(redis, experiment)
if experiment:
experiment.reset()
return redirect(url_for('.index')) | Delete all data for an experiment. |
def to_filter(self, query, arg):
return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_) | Json-server filter using the _or_ operator. |
def purge_old_event_logs(delete_before_days=7):
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = EventLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | Purges old event logs from the database table |
def start_stop_video(self):
if self.parent.info.dataset is None:
self.parent.statusBar().showMessage('No Dataset Loaded')
return
if 'Start' in self.idx_button.text().replace('&', ''):
try:
self.update_video()
except IndexError as er:
lg.debug(er)
self.idx_button.setText('Not Available / Start')
return
except OSError as er:
lg.debug(er)
self.idx_button.setText('NO VIDEO for this dataset')
return
self.idx_button.setText('Stop')
elif 'Stop' in self.idx_button.text():
self.idx_button.setText('Start')
self.medialistplayer.stop()
self.t.stop() | Start and stop the video, and change the button. |
def clear_cache(self):
super(HyperparameterTuningJobAnalytics, self).clear_cache()
self._tuning_job_describe_result = None
self._training_job_summaries = None | Clear the object of all local caches of API methods. |
def getPhotos(self):
method = 'flickr.photosets.getPhotos'
data = _doget(method, photoset_id=self.id)
photos = data.rsp.photoset.photo
p = []
for photo in photos:
p.append(Photo(photo.id, title=photo.title, secret=photo.secret, \
server=photo.server))
return p | Returns list of Photos. |
def _find_entity_in_records_by_class_name(self, entity_name):
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
if len(records) > 1:
raise ConfigurationError(
f'Entity with name {entity_name} has been registered twice. '
f'Please use fully qualified Entity name to specify the exact Entity.')
elif len(records) == 1:
return next(iter(records.values()))
else:
raise AssertionError(f'No Entity registered with name {entity_name}') | Fetch by Entity Name in values |
def _readuntil(f, end=_TYPE_END):
buf = bytearray()
byte = f.read(1)
while byte != end:
if byte == b'':
raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))
buf += byte
byte = f.read(1)
return buf | Helper function to read bytes until a certain end byte is hit |
def rejectEdit(self):
if self._lineEdit:
self._lineEdit.hide()
self.editingCancelled.emit() | Cancels the edit for this label. |
def from_mapping(cls, mapping):
group = cls()
for name, value in mapping.items():
if name.startswith('_'):
continue
group[name] = Parameter(
name=name,
value=value,
constraint=Parameter.constraint_from_type(value),
)
return group | Produces a set of parameters from a mapping |
def keys(self) -> Iterator[str]:
if self.param:
yield self.param_name
yield from self.paths.keys() | return all possible paths one can take from this ApiNode |
def save(self, expires=None):
if expires is None:
expires = self.expires
s = self.serialize()
key = self._key(self._all_keys())
_cache.set(key, s, expires) | Save a copy of the object into the cache. |
def loadedfields(self):
if self._loadedfields is None:
for field in self._meta.scalarfields:
yield field
else:
fields = self._meta.dfields
processed = set()
for name in self._loadedfields:
if name in processed:
continue
if name in fields:
processed.add(name)
yield fields[name]
else:
name = name.split(JSPLITTER)[0]
if name in fields and name not in processed:
field = fields[name]
if field.type == 'json object':
processed.add(name)
yield field | Generator of fields loaded from database |
def archive_namespace(self):
try:
for ns_prefix, url in self.feed.namespaces.items():
if url == 'http://purl.org/syndication/history/1.0':
return ns_prefix
except AttributeError:
pass
return None | Returns the known namespace of the RFC5005 extension, if any |
def load_schema(path):
with open(path) as json_data:
schema = json.load(json_data)
return schema | Loads a JSON schema file. |
def _get_perf(text, msg_id):
msg = KQMLPerformative('REQUEST')
msg.set('receiver', 'READER')
content = KQMLList('run-text')
content.sets('text', text)
msg.set('content', content)
msg.set('reply-with', msg_id)
return msg | Return a request message for a given text. |
def add_complex(self, **kwargs):
self.check_developer()
self.post('developers/%s/complexes/' % self.developer, data=kwargs) | Add a new complex to the rumetr db |
def _make_info(self, name, stat_result, namespaces):
info = {
'basic': {
'name': name,
'is_dir': stat.S_ISDIR(stat_result.st_mode)
}
}
if 'details' in namespaces:
info['details'] = self._make_details_from_stat(stat_result)
if 'stat' in namespaces:
info['stat'] = {
k: getattr(stat_result, k)
for k in dir(stat_result) if k.startswith('st_')
}
if 'access' in namespaces:
info['access'] = self._make_access_from_stat(stat_result)
return Info(info) | Create an `Info` object from a stat result. |
def _row_resized(self, row, old_height, new_height):
self.dataTable.setRowHeight(row, new_height)
self._update_layout() | Update the row height. |
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None):
fileobj = filething.fileobj
iff_file = IFFFile(fileobj)
if u'ID3' not in iff_file:
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
try:
data = self._prepare_data(
fileobj, chunk.data_offset, chunk.data_size, v2_version,
v23_sep, padding)
except ID3Error as e:
reraise(error, e, sys.exc_info()[2])
new_size = len(data)
new_size += new_size % 2
assert new_size % 2 == 0
chunk.resize(new_size)
data += (new_size - len(data)) * b'\x00'
assert new_size == len(data)
chunk.write(data) | Save ID3v2 data to the AIFF file |
def indented(text, level, indent=2):
return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines()) | Take a multiline text and indent it as a block |
def read_args_tool(toolkey, example_parameters, tool_add_args=None):
import scanpy as sc
p = default_tool_argparser(help(toolkey), example_parameters)
if tool_add_args is None:
p = add_args(p)
else:
p = tool_add_args(p)
args = vars(p.parse_args())
args = settings.process_args(args)
return args | Read args for single tool. |
def validate(self):
for name, field in self:
try:
field.validate_for_object(self)
except ValidationError as error:
raise ValidationError(
"Error for field '{name}'.".format(name=name),
error,
) | Explicitly validate all the fields. |
def on_load(self, event):
dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*', wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.settings.load(dlg.GetPath())
for label in self.setting_map.keys():
setting = self.setting_map[label]
ctrl = self.controls[label]
value = ctrl.GetValue()
if isinstance(value, str) or isinstance(value, unicode):
ctrl.SetValue(str(setting.value))
else:
ctrl.SetValue(setting.value) | called on load button |
def _correct_dims(data):
if not hasattr(data, 'dims'):
raise TypeError("Data must have a 'dims' attribute.")
data = data.copy()
if 'y' not in data.dims or 'x' not in data.dims:
if data.ndim != 2:
raise ValueError("Data must have a 'y' and 'x' dimension")
if 'y' not in data.dims:
old_dim = [d for d in data.dims if d != 'x'][0]
data = data.rename({old_dim: 'y'})
if 'x' not in data.dims:
old_dim = [d for d in data.dims if d != 'y'][0]
data = data.rename({old_dim: 'x'})
if "bands" not in data.dims:
if data.ndim <= 2:
data = data.expand_dims('bands')
data['bands'] = ['L']
else:
raise ValueError("No 'bands' dimension provided.")
return data | Standardize dimensions to bands, y, and x. |
def __send_command(self, command, args=[]):
self.ws.send(json.dumps({"op": command, "args": args})) | Send a raw command. |
def period(self):
return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu)) | Period of the orbit as a timedelta |
def min_freq(self):
i = np.unravel_index(np.argmin(self.bands), self.bands.shape)
return self.qpoints[i[1]], self.bands[i] | Returns the point where the minimum frequency is reached and its value |
def sqlvm_group_list(
client,
resource_group_name=None):
if resource_group_name:
return client.list_by_resource_group(resource_group_name=resource_group_name)
return client.list() | Lists all SQL virtual machine groups in a resource group or subscription. |
def export_datasources(print_stdout, datasource_file,
back_references, include_defaults):
data = dict_import_export.export_to_dict(
session=db.session,
recursive=True,
back_references=back_references,
include_defaults=include_defaults)
if print_stdout or not datasource_file:
yaml.safe_dump(data, stdout, default_flow_style=False)
if datasource_file:
logging.info('Exporting datasources to %s', datasource_file)
with open(datasource_file, 'w') as data_stream:
yaml.safe_dump(data, data_stream, default_flow_style=False) | Export datasources to YAML |
def exclude_data_files(self, package, src_dir, files):
files = list(files)
patterns = self._get_platform_patterns(
self.exclude_package_data,
package,
src_dir,
)
match_groups = (
fnmatch.filter(files, pattern)
for pattern in patterns
)
matches = itertools.chain.from_iterable(match_groups)
bad = set(matches)
keepers = (
fn
for fn in files
if fn not in bad
)
return list(_unique_everseen(keepers)) | Filter filenames for package's data files in 'src_dir |
def write_config(configfile, content):
with open(configfile, 'w+') as ymlfile:
yaml.dump(
content,
ymlfile,
default_flow_style=False,
) | Write dict to a file in yaml format |
def write(self, data):
self.backingStream.write(data)
for listener in self.writeListeners:
listener(len(data)) | Write the given data to the file. |
def read_string_from_file(path, encoding="utf8"):
with codecs.open(path, "rb", encoding=encoding) as f:
value = f.read()
return value | Read entire contents of file into a string. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.