code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def pretty_unicode(string):
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return string.decode('Latin-1').encode('unicode_escape').decode("utf8") | Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed. |
def default_endpoint(ctx, param, value):
if ctx.resilient_parsing:
return
config = ctx.obj['config']
endpoint = default_endpoint_from_config(config, option=value)
if endpoint is None:
raise click.UsageError('No default endpoint found.')
return endpoint | Return default endpoint if specified. |
def imethodcallPayload(self, methodname, localnsp, **kwargs):
param_list = [pywbem.IPARAMVALUE(x[0], pywbem.tocimxml(x[1]))
for x in kwargs.items()]
payload = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.IMETHODCALL(
methodname,
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in localnsp.split('/')]),
param_list)),
'1001', '1.0'),
'2.0', '2.0')
return self.xml_header + payload.toxml() | Generate the XML payload for an intrinsic methodcall. |
def _find_value(key, *args):
for arg in args:
v = _get_value(arg, key)
if v is not None:
return v | Find a value for 'key' in any of the objects given as 'args |
def _on_state_changed(self):
raw_state, generation = self.state.raw_state_and_generation
if generation != self._last_generation:
self._last_generation = generation
self._send_update(raw_state, generation) | Invoked when the viewer state changes. |
def write_sampler_metadata(self, sampler):
super(EmceePTFile, self).write_sampler_metadata(sampler)
self[self.sampler_group].attrs["betas"] = sampler.betas | Adds writing betas to MultiTemperedMCMCIO. |
def hostname(self):
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] | Get the hostname that this connection is associated with |
def _make_c_string(string):
if isinstance(string, bytes):
try:
_utf_8_decode(string, None, True)
return string + b"\x00"
except UnicodeError:
raise InvalidStringData("strings in documents must be valid "
"UTF-8: %r" % string)
else:
return _utf_8_encode(string)[0] + b"\x00" | Make a 'C' string. |
def _add_to_checksum(self, checksum, value):
checksum = self._byte_rot_left(checksum, 1)
checksum = checksum + value
if (checksum > 255):
checksum = checksum - 255
self._debug(PROP_LOGLEVEL_TRACE, "C: " + str(checksum) + " V: " + str(value))
return checksum | Add a byte to the checksum. |
def register_builtin_message_types():
from .plain import PlainTextMessage
from .email import EmailTextMessage, EmailHtmlMessage
register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage) | Registers the built-in message types. |
def load(self, rel_path=None):
for k, v in self.layer.iteritems():
self.add(k, v['module'], v.get('package'))
filename = v.get('filename')
path = v.get('path')
if filename:
warnings.warn(DeprecationWarning(SIMFILE_LOAD_WARNING))
if not path:
path = rel_path
else:
path = os.path.join(rel_path, path)
filename = os.path.join(path, filename)
self.open(k, filename) | Add sim_src to layer. |
def rename_page(self, old_slug, new_title):
p = s2page.Page(self, old_slug, isslug=True)
p.rename(new_title) | Load the page corresponding to the slug, and rename it. |
def _ssh_master_cmd(addr, user, command, local_key=None):
ssh_call = ['ssh', '-qNfL%d:127.0.0.1:12042' % find_port(addr, user),
'-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' %
find_port(addr, user),
'-O', command, '%s@%s' % (user, addr,)]
if local_key:
ssh_call.insert(1, local_key)
ssh_call.insert(1, '-i')
return subprocess.call(ssh_call) | Exit or check ssh mux |
def find_by_reference_ids(reference_ids, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
if not isinstance(reference_ids, (list, tuple)):
err = "Video.find_by_reference_ids expects an iterable argument"
raise exceptions.PyBrightcoveError(err)
ids = ','.join(reference_ids)
return connection.ItemResultSet(
'find_videos_by_reference_ids', Video, _connection, page_size,
page_number, sort_by, sort_order, reference_ids=ids) | List all videos identified by a list of reference ids |
def FDMT_params(f_min, f_max, maxDT, inttime):
maxDM = inttime*maxDT/(4.1488e-3 * (1/f_min**2 - 1/f_max**2))
logger.info('Freqs from {0}-{1}, MaxDT {2}, Int time {3} => maxDM {4}'.format(f_min, f_max, maxDT, inttime, maxDM)) | Summarize DM grid and other parameters. |
def cli(env, identifier):
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
instance = vsi.get_instance(vs_id)
table = formatting.Table(['username', 'password'])
for item in instance['operatingSystem']['passwords']:
table.add_row([item['username'], item['password']])
env.fout(table) | List virtual server credentials. |
def middleware(func):
@wraps(func)
def parse(*args, **kwargs):
middleware = copy.deepcopy(kwargs['middleware'])
kwargs.pop('middleware')
if request.method == "OPTIONS":
return JsonResponse(200)
if middleware is None:
return func(*args, **kwargs)
for mware in middleware:
ware = mware()
if ware.status is False:
return ware.response
return func(*args, **kwargs)
return parse | Executes routes.py route middleware |
def format_platforms(cls, platforms):
lines = []
if platforms:
lines.append('This DAP is only supported on the following platforms:')
lines.extend([' * ' + platform for platform in platforms])
return lines | Formats supported platforms in human readable form |
def _load_file(self, f):
try:
with open(f, 'r') as _fo:
_seria_in = seria.load(_fo)
_y = _seria_in.dump('yaml')
except IOError:
raise FiggypyError("could not open configuration file")
self.values.update(yaml.load(_y)) | Get values from config file |
def _init_ca(self):
if not exists(path_join(self.ca_dir, 'ca.cnf')):
with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh:
fh.write(
CA_CONF_TEMPLATE % (self.get_conf_variables()))
if not exists(path_join(self.ca_dir, 'signing.cnf')):
with open(path_join(self.ca_dir, 'signing.cnf'), 'w') as fh:
fh.write(
SIGNING_CONF_TEMPLATE % (self.get_conf_variables()))
if exists(self.ca_cert) or exists(self.ca_key):
raise RuntimeError("Initialized called when CA already exists")
cmd = ['openssl', 'req', '-config', self.ca_conf,
'-x509', '-nodes', '-newkey', 'rsa',
'-days', self.default_ca_expiry,
'-keyout', self.ca_key, '-out', self.ca_cert,
'-outform', 'PEM']
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
log("CA Init:\n %s" % output, level=DEBUG) | Generate the root ca's cert and key. |
def refresh(self):
for cbar in self.colorbars:
cbar.draw_all()
self.canvas.draw() | Refresh the current figure |
def validate_schedule():
all_items = prefetch_schedule_items()
errors = []
for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS:
if validator(all_items):
errors.append(msg)
all_slots = prefetch_slots()
for validator, _type, msg in SLOT_VALIDATORS:
if validator(all_slots):
errors.append(msg)
return errors | Helper routine to report issues with the schedule |
def constant_jump_targets_and_jumpkinds(self):
exits = dict()
if self.exit_statements:
for _, _, stmt_ in self.exit_statements:
exits[stmt_.dst.value] = stmt_.jumpkind
default_target = self.default_exit_target
if default_target is not None:
exits[default_target] = self.jumpkind
return exits | A dict of the static jump targets of the basic block to their jumpkind. |
def cli_main():
SearchContext.commit()
args = parser.parse_args()
firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
with contextlib.closing(firefox_remote):
context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
search = Search(parent=context)
if args.fast:
with context.use(FastSearch, Browser):
main(search, args.query)
else:
with context.use(Browser):
main(search, args.query) | cli entrypoitns, sets up everything needed |
def install_package_command(package_name):
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, shell=True) | install python package from pip |
def _add_comments(
self,
comments: Optional[Sequence[str]],
original_string: str = ""
) -> str:
if self.config['ignore_comments']:
return self._strip_comments(original_string)[0]
if not comments:
return original_string
else:
return "{0}{1} {2}".format(self._strip_comments(original_string)[0],
self.config['comment_prefix'],
"; ".join(comments)) | Returns a string with comments added if ignore_comments is not set. |
def add(self, name, obj=None):
if obj:
text = '\n::\n\n' + indent(str(obj))
else:
text = views.view(name, self.dstore)
if text:
title = self.title[name]
line = '-' * len(title)
self.text += '\n'.join(['\n\n' + title, line, text]) | Add the view named `name` to the report text |
def api_routes(self, callsign: str) -> Tuple[Airport, ...]:
from .. import airports
c = requests.get(
f"https://opensky-network.org/api/routes?callsign={callsign}"
)
if c.status_code == 404:
raise ValueError("Unknown callsign")
if c.status_code != 200:
raise ValueError(c.content.decode())
json = c.json()
return tuple(airports[a] for a in json["route"]) | Returns the route associated to a callsign. |
def getSearch(self):
return Search(self.getColumns(), Sitools2Abstract.getBaseUrl(self) + self.getUri()) | Returns the search capability. |
def logFile(fileName, printFunction=logger.info):
printFunction("Reporting file: %s" % fileName)
shortName = fileName.split("/")[-1]
fileHandle = open(fileName, 'r')
line = fileHandle.readline()
while line != '':
if line[-1] == '\n':
line = line[:-1]
printFunction("%s:\t%s" % (shortName, line))
line = fileHandle.readline()
fileHandle.close() | Writes out a formatted version of the given log file |
def _initialize_logging():
if sys.stdout.isatty() or platform.system() in ("Darwin", "Linux"):
RuntimeGlobals.logging_console_handler = foundations.verbose.get_logging_console_handler()
RuntimeGlobals.logging_formatters = {"Default": foundations.verbose.LOGGING_DEFAULT_FORMATTER,
"Extended": foundations.verbose.LOGGING_EXTENDED_FORMATTER,
"Standard": foundations.verbose.LOGGING_STANDARD_FORMATTER} | Initializes the Application logging. |
def remove(self, list):
xml = SP.DeleteList(SP.listName(list.id))
self.opener.post_soap(LIST_WEBSERVICE, xml,
soapaction='http://schemas.microsoft.com/sharepoint/soap/DeleteList')
self.all_lists.remove(list) | Removes a list from the site. |
def gan_critic(n_channels:int=3, nf:int=128, n_blocks:int=3, p:int=0.15):
"Critic to train a `GAN`."
layers = [
_conv(n_channels, nf, ks=4, stride=2),
nn.Dropout2d(p/2),
res_block(nf, dense=True,**_conv_args)]
nf *= 2
for i in range(n_blocks):
layers += [
nn.Dropout2d(p),
_conv(nf, nf*2, ks=4, stride=2, self_attention=(i==0))]
nf *= 2
layers += [
_conv(nf, 1, ks=4, bias=False, padding=0, use_activ=False),
Flatten()]
return nn.Sequential(*layers) | Critic to train a `GAN`. |
def collection_year(soup):
pub_date = first(raw_parser.pub_date(soup, pub_type="collection"))
if not pub_date:
pub_date = first(raw_parser.pub_date(soup, date_type="collection"))
if not pub_date:
return None
year = None
year_tag = raw_parser.year(pub_date)
if year_tag:
year = int(node_text(year_tag))
return year | Pub date of type collection will hold a year element for VOR articles |
def do_visualize(self, line):
if not self.current:
self._help_noontology()
return
line = line.split()
try:
from ..ontodocs.builder import action_visualize
except:
self._print("This command requires the ontodocs package: `pip install ontodocs`")
return
import webbrowser
url = action_visualize(args=self.current['file'], fromshell=True)
if url:
webbrowser.open(url)
return | Visualize an ontology - ie wrapper for export command |
def _print_bar(self):
self._print('[')
for position in range(self._bar_width):
position_fraction = position / (self._bar_width - 1)
position_bytes = position_fraction * self.max_value
if position_bytes < (self.continue_value or 0):
self._print('+')
elif position_bytes <= (self.continue_value or 0) + self.current_value:
self._print('=')
else:
self._print(' ')
self._print(']') | Print a progress bar. |
def run(self):
luigi.LocalTarget(path=self.fixture).copy(self.output().path) | Just copy the fixture, so we have some output. |
def parse_name(parser):
token = expect(parser, TokenKind.NAME)
return ast.Name(value=token.value, loc=loc(parser, token.start)) | Converts a name lex token into a name parse node. |
def _repr_html_(self, **kwargs):
html = self.render(**kwargs)
html = "data:text/html;charset=utf-8;base64," + base64.b64encode(html.encode('utf8')).decode('utf8')
if self.height is None:
iframe = (
'<div style="width:{width};">'
'<div style="position:relative;width:100%;height:0;padding-bottom:{ratio};">'
'<iframe src="{html}" style="position:absolute;width:100%;height:100%;left:0;top:0;'
'border:none !important;" '
'allowfullscreen webkitallowfullscreen mozallowfullscreen>'
'</iframe>'
'</div></div>').format
iframe = iframe(html=html,
width=self.width,
ratio=self.ratio)
else:
iframe = ('<iframe src="{html}" width="{width}" height="{height}"'
'style="border:none !important;" '
'"allowfullscreen" "webkitallowfullscreen" "mozallowfullscreen">'
'</iframe>').format
iframe = iframe(html=html, width=self.width, height=self.height)
return iframe | Displays the Figure in a Jupyter notebook. |
def attach_method(self, resource_id):
try:
_response = self.client.put_method(
restApiId=self.api_id,
resourceId=resource_id,
httpMethod=self.trigger_settings['method'],
authorizationType="NONE",
apiKeyRequired=False, )
self.log.debug('Response for resource (%s) push authorization: %s', resource_id, _response)
_response = self.client.put_method_response(
restApiId=self.api_id,
resourceId=resource_id,
httpMethod=self.trigger_settings['method'],
statusCode='200')
self.log.debug('Response for resource (%s) no authorization: %s', resource_id, _response)
self.log.info("Successfully attached method: %s", self.trigger_settings['method'])
except botocore.exceptions.ClientError:
self.log.info("Method %s already exists", self.trigger_settings['method']) | Attach the defined method. |
def create_dm_pkg(secret,username):
secret = tools.EncodeString(secret)
username = tools.EncodeString(username)
pkg_format = '>HHHH32sHH32s'
pkg_vals = [
IK_RAD_PKG_VER,
IK_RAD_PKG_AUTH,
IK_RAD_PKG_USR_PWD_TAG,
len(secret),
secret.ljust(32,'\x00'),
IK_RAD_PKG_CMD_ARGS_TAG,
len(username),
username.ljust(32,'\x00')
]
return struct.pack(pkg_format,*pkg_vals) | create ikuai dm message |
def savetofile(self, filelike, sortkey = True):
filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | Save configurations to a file-like object which supports `writelines` |
def secret_key_bytes(self):
if not hasattr(self, '_secret_key_bytes'):
key = self.secret_key()
if key is None:
self._secret_key_bytes = None
else:
self._secret_key_bytes = codecs.encode(key, "utf-8")
return self._secret_key_bytes | Return the secret_key, converted to bytes and cached. |
def _update_method(self, oldmeth, newmeth):
if hasattr(oldmeth, 'im_func') and hasattr(newmeth, 'im_func'):
self._update(None, None, oldmeth.im_func, newmeth.im_func)
elif hasattr(oldmeth, '__func__') and hasattr(newmeth, '__func__'):
self._update(None, None, oldmeth.__func__, newmeth.__func__)
return oldmeth | Update a method object. |
def _load_mol2(self, mol2_lines, mol2_code, columns):
if columns is None:
col_names = COLUMN_NAMES
col_types = COLUMN_TYPES
else:
col_names, col_types = [], []
for i in range(len(columns)):
col_names.append(columns[i][0])
col_types.append(columns[i][1])
try:
self.mol2_text = ''.join(mol2_lines)
self.code = mol2_code
except TypeError:
mol2_lines = [m.decode() for m in mol2_lines]
self.mol2_text = ''.join(mol2_lines)
self.code = mol2_code.decode()
self._df = self._construct_df(mol2_lines, col_names, col_types) | Load mol2 contents into assert_raise_message instance |
def filter_tasks(self, request, context):
_log_request(request, context)
tasks_pattern, tasks_negate = PATTERN_PARAMS_OP(request.tasks_filter)
state_pattern = request.state_pattern
limit, reverse = request.limit, request.reverse
pregex = re.compile(tasks_pattern)
sregex = re.compile(state_pattern)
def pcondition(task):
return accepts(pregex, tasks_negate, task.name, task.routing_key)
def scondition(task):
return accepts(sregex, tasks_negate, task.state)
found_tasks = (task for _, task in
self.listener.memory.tasks_by_time(limit=limit or None,
reverse=reverse)
if pcondition(task) and scondition(task))
def callback(t):
logger.debug('%s iterated %d tasks in %s (%s)', self.filter_tasks.__name__,
t.count, t.duration_human, t.throughput_human)
for task in about_time(callback, found_tasks):
yield ClearlyServer._event_to_pb(task)[1] | Filter tasks by matching patterns to name, routing key and state. |
async def send_and_receive(self, message,
generate_identifier=True, timeout=5):
await self._connect_and_encrypt()
if generate_identifier:
identifier = str(uuid.uuid4())
message.identifier = identifier
else:
identifier = 'type_' + str(message.type)
self.connection.send(message)
return await self._receive(identifier, timeout) | Send a message and wait for a response. |
def _keys_to_lower(self):
for k in list(self.keys()):
val = super(CaseInsensitiveDict, self).__getitem__(k)
super(CaseInsensitiveDict, self).__delitem__(k)
self.__setitem__(CaseInsensitiveStr(k), val) | Convert key set to lowercase. |
def _icon_by_painter(self, painter, options):
engine = CharIconEngine(self, painter, options)
return QIcon(engine) | Return the icon corresponding to the given painter. |
def validate(self, value, model_instance, **kwargs):
self.get_choices_form_class().validate(value, model_instance, **kwargs) | This follows the validate rules for choices_form_class field used. |
def _fill_capture_regions(data):
special_targets = {"sv_regions": ("exons", "transcripts")}
ref_file = dd.get_ref_file(data)
for target in ["variant_regions", "sv_regions", "coverage"]:
val = tz.get_in(["config", "algorithm", target], data)
if val and not os.path.exists(val) and not objectstore.is_remote(val):
installed_vals = []
for ext in [".bed", ".bed.gz"]:
installed_vals += glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
"coverage", val + ext)))
if len(installed_vals) == 0:
if target not in special_targets or not val.startswith(special_targets[target]):
raise ValueError("Configuration problem. BED file not found for %s: %s" %
(target, val))
else:
assert len(installed_vals) == 1, installed_vals
data = tz.update_in(data, ["config", "algorithm", target], lambda x: installed_vals[0])
return data | Fill short-hand specification of BED capture regions. |
def structured_iterator(failure_lines):
summary = partial(failure_line_summary, TbplFormatter())
for failure_line in failure_lines:
repr_str = summary(failure_line)
if repr_str:
yield failure_line, repr_str
while True:
yield None, None | Create FailureLine, Tbpl-formatted-string tuples. |
def _next(self, request, application, roles, next_config):
if request.method == "POST":
key = None
while True:
assert next_config['type'] in ['goto', 'transition']
while next_config['type'] == 'goto':
key = next_config['key']
next_config = self._config[key]
instance = load_instance(next_config)
if not isinstance(instance, Transition):
break
next_config = instance.get_next_config(request, application, roles)
assert key is not None
state_key = key
instance.enter_state(request, application)
application.state = state_key
application.save()
log.change(application.application_ptr, "state: %s" % instance.name)
url = get_url(request, application, roles)
return HttpResponseRedirect(url)
else:
return HttpResponseBadRequest("<h1>Bad Request</h1>") | Continue the state machine at given state. |
def request_uri(self):
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri | Absolute path including the query string. |
def pack(field: str, kwargs: Dict[str, Any],
default: Optional[Any] = None, sep: str=',') -> str:
if default is not None:
value = kwargs.get(field, default)
else:
value = kwargs[field]
if isinstance(value, str):
return value
elif isinstance(value, collections.abc.Iterable):
return sep.join(str(f) for f in value)
else:
return str(value) | Util for joining multiple fields with commas |
def _from_dict(cls, _dict):
args = {}
if 'trait_id' in _dict:
args['trait_id'] = _dict.get('trait_id')
else:
raise ValueError(
'Required property \'trait_id\' not present in Trait JSON')
if 'name' in _dict:
args['name'] = _dict.get('name')
else:
raise ValueError(
'Required property \'name\' not present in Trait JSON')
if 'category' in _dict:
args['category'] = _dict.get('category')
else:
raise ValueError(
'Required property \'category\' not present in Trait JSON')
if 'percentile' in _dict:
args['percentile'] = _dict.get('percentile')
else:
raise ValueError(
'Required property \'percentile\' not present in Trait JSON')
if 'raw_score' in _dict:
args['raw_score'] = _dict.get('raw_score')
if 'significant' in _dict:
args['significant'] = _dict.get('significant')
if 'children' in _dict:
args['children'] = [
Trait._from_dict(x) for x in (_dict.get('children'))
]
return cls(**args) | Initialize a Trait object from a json dictionary. |
def _key_to_address(key):
key_parts = key.split('.', maxsplit=_MAX_KEY_PARTS - 1)
key_parts.extend([''] * (_MAX_KEY_PARTS - len(key_parts)))
return SETTINGS_NAMESPACE + ''.join(_short_hash(x) for x in key_parts) | Creates the state address for a given setting key. |
def _yql_query(yql):
url = _YAHOO_BASE_URL.format(urlencode({'q': yql}))
_LOGGER.debug("Send request to url: %s", url)
try:
request = urlopen(url)
rawData = request.read()
data = json.loads(rawData.decode("utf-8"))
_LOGGER.debug("Query data from yahoo: %s", str(data))
return data.get("query", {}).get("results", {})
except (urllib.error.HTTPError, urllib.error.URLError):
_LOGGER.info("Can't fetch data from Yahoo!")
return None | Fetch data from Yahoo! Return a dict if successfull or None. |
def uninstall(
ctx,
state,
all_dev=False,
all=False,
**kwargs
):
from ..core import do_uninstall
retcode = do_uninstall(
packages=state.installstate.packages,
editable_packages=state.installstate.editables,
three=state.three,
python=state.python,
system=state.system,
lock=not state.installstate.skip_lock,
all_dev=all_dev,
all=all,
keep_outdated=state.installstate.keep_outdated,
pypi_mirror=state.pypi_mirror,
ctx=ctx
)
if retcode:
sys.exit(retcode) | Un-installs a provided package and removes it from Pipfile. |
def addPathVariables(self, pathvars):
if type(pathvars) is dict:
self._pathvars = merge(self._pathvars, pathvars) | Adds path variables to the pathvars map property |
def gen_sub(src1, src2, dst):
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SUB, src1, src2, dst) | Return a SUB instruction. |
def _on_new_location(self, form):
self._desired_longitude = float(form.data["long"])
self._desired_latitude = float(form.data["lat"])
self._desired_zoom = 13
self._screen.force_update() | Set a new desired location entered in the pop-up form. |
def indent(self, levels, first_line=None):
self._indentation_levels.append(levels)
self._indent_first_line.append(first_line) | Increase indentation by ``levels`` levels. |
def files(self):
if self._files is None:
self._files = SeriesZipTifPhasics._index_files(self.path)
return self._files | List of Phasics tif file names in the input zip file |
def update_source(ident, data):
source = get_source(ident)
source.modify(**data)
signals.harvest_source_updated.send(source)
return source | Update an harvest source |
def strip_ansi(state):
stu_res = _strip_ansi(state.student_result)
return state.to_child(student_result = stu_res) | Remove ANSI escape codes from student result. |
def init_epoch(self):
if self._restored_from_state:
self.random_shuffler.random_state = self._random_state_this_epoch
else:
self._random_state_this_epoch = self.random_shuffler.random_state
self.create_batches()
if self._restored_from_state:
self._restored_from_state = False
else:
self._iterations_this_epoch = 0
if not self.repeat:
self.iterations = 0 | Set up the batch generator for a new epoch. |
def use_plenary_repository_view(self):
self._repository_view = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_repository_view()
except AttributeError:
pass | Pass through to provider AssetRepositorySession.use_plenary_repository_view |
def connect(self, address):
'connects to the address and wraps the connection in an SSL context'
tout = _timeout(self.gettimeout())
while 1:
self._wait_event(tout.now, write=True)
err = self._connect(address, tout.now)
if err in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK):
continue
if err:
raise socket.error(err, errno.errorcode[err])
return 0 | connects to the address and wraps the connection in an SSL context |
def knob_subgroup(self, cutoff=7.0):
if cutoff > self.cutoff:
raise ValueError("cutoff supplied ({0}) cannot be greater than self.cutoff ({1})".format(cutoff,
self.cutoff))
return KnobGroup(monomers=[x for x in self.get_monomers()
if x.max_kh_distance <= cutoff], ampal_parent=self.ampal_parent) | KnobGroup where all KnobsIntoHoles have max_kh_distance <= cutoff. |
def make_middleware(app=None, *args, **kw):
app = iWSGIMiddleware(app, *args, **kw)
return app | Given an app, return that app wrapped in iWSGIMiddleware |
def put_blob(self, field: str, fileobj: BinaryIO,
filename: str,
mimetype: Optional[str] = None,
size: Optional[int] = None,
encoding: Optional[str] = None) -> IBlob:
raise NotImplementedError | Receive and store blob object |
def read_point_prop(self, device_name, point):
with open("%s.bin" % device_name, "rb") as file:
return pickle.load(file)["points"][point] | Points properties retrieved from pickle |
def publish_data(self):
self.publish_device_stats()
publish = self.publish
for node in self.nodes:
try:
if node.has_update():
for data in node.get_data():
publish(*data)
except NotImplementedError:
raise
except Exception as error:
self.node_error(node, error) | publish node data if node has updates |
def validate_network_topology(network_id,**kwargs):
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_write_permission(user_id=user_id)
except NoResultFound:
raise ResourceNotFoundError("Network %s not found"%(network_id))
nodes = []
for node_i in net_i.nodes:
if node_i.status == 'A':
nodes.append(node_i.node_id)
link_nodes = []
for link_i in net_i.links:
if link_i.status != 'A':
continue
if link_i.node_1_id not in link_nodes:
link_nodes.append(link_i.node_1_id)
if link_i.node_2_id not in link_nodes:
link_nodes.append(link_i.node_2_id)
nodes = set(nodes)
link_nodes = set(link_nodes)
isolated_nodes = nodes - link_nodes
return isolated_nodes | Check for the presence of orphan nodes in a network. |
def mask_umi(umi, umi_quals, quality_encoding, quality_filter_threshold):
below_threshold = get_below_threshold(
umi_quals, quality_encoding, quality_filter_threshold)
new_umi = ""
for base, test in zip(umi, below_threshold):
if test:
new_umi += "N"
else:
new_umi += base
return new_umi | Mask all positions where quals < threshold with "N" |
def decode_endpoint_props(input_props):
ed_props = decode_osgi_props(input_props)
ed_props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = input_props[
ECF_ENDPOINT_CONTAINERID_NAMESPACE
]
ed_props[ECF_RSVC_ID] = int(input_props[ECF_RSVC_ID])
ed_props[ECF_ENDPOINT_ID] = input_props[ECF_ENDPOINT_ID]
ed_props[ECF_ENDPOINT_TIMESTAMP] = int(input_props[ECF_ENDPOINT_TIMESTAMP])
target_id = input_props.get(ECF_ENDPOINT_CONNECTTARGET_ID, None)
if target_id:
ed_props[ECF_ENDPOINT_CONNECTTARGET_ID] = target_id
id_filters = decode_list(input_props, ECF_ENDPOINT_IDFILTER_IDS)
if id_filters:
ed_props[ECF_ENDPOINT_IDFILTER_IDS] = id_filters
rs_filter = input_props.get(ECF_ENDPOINT_REMOTESERVICE_FILTER, None)
if rs_filter:
ed_props[ECF_ENDPOINT_REMOTESERVICE_FILTER] = rs_filter
async_intfs = input_props.get(ECF_SERVICE_EXPORTED_ASYNC_INTERFACES, None)
if async_intfs:
if async_intfs == "*":
ed_props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = async_intfs
else:
async_intfs = decode_list(
input_props, ECF_SERVICE_EXPORTED_ASYNC_INTERFACES
)
if async_intfs:
ed_props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = async_intfs
for key in input_props.keys():
if not is_reserved_property(key):
val = input_props.get(key, None)
if val:
ed_props[key] = val
return ed_props | Decodes the endpoint properties from the given dictionary |
def database_root_path(cls, project, database):
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}",
project=project,
database=database,
) | Return a fully-qualified database_root string. |
def range_metadata(start, end, dst_folder, num_worker_threads=0, writers=[file_writer], geometry_check=None):
assert isinstance(start, date)
assert isinstance(end, date)
delta = end - start
dates = []
for i in range(delta.days + 1):
dates.append(start + timedelta(days=i))
days = len(dates)
total_counter = {
'days': days,
'products': 0,
'saved_tiles': 0,
'skipped_tiles': 0,
'skipped_tiles_paths': []
}
def update_counter(counter):
for key in iterkeys(total_counter):
if key in counter:
total_counter[key] += counter[key]
for d in dates:
logger.info('Getting metadata of {0}-{1}-{2}'.format(d.year, d.month, d.day))
update_counter(daily_metadata(d.year, d.month, d.day, dst_folder, writers, geometry_check,
num_worker_threads))
return total_counter | Extra metadata for all products in a date range |
def sh(args, **kwargs):
if isinstance(args, str):
args = args.split()
if not args:
return
click.echo('$ {0}'.format(' '.join(args)))
try:
return subprocess.check_call(args, **kwargs)
except subprocess.CalledProcessError as exc:
click.secho('run error {}'.format(exc))
except OSError as exc:
click.secho('not found error {}'.format(exc)) | runs the given cmd as shell command |
def reservoir_sample(stream, num_items, item_parser=lambda x: x):
kept = []
for index, item in enumerate(stream):
if index < num_items:
kept.append(item_parser(item))
else:
r = random.randint(0, index)
if r < num_items:
kept[r] = item_parser(item)
return kept | samples num_items from the stream keeping each with equal probability |
def do_ultracache(parser, token):
nodelist = parser.parse(("endultracache",))
parser.delete_first_token()
tokens = token.split_contents()
if len(tokens) < 3:
raise TemplateSyntaxError(""%r" tag requires at least 2 arguments." % tokens[0])
return UltraCacheNode(nodelist,
parser.compile_filter(tokens[1]),
tokens[2],
[parser.compile_filter(token) for token in tokens[3:]]) | Based on Django's default cache template tag |
def _delete_uncompressed(
collection_name, spec, safe, last_error_args, opts, flags=0):
op_delete, max_bson_size = _delete(collection_name, spec, opts, flags)
rid, msg = __pack_message(2006, op_delete)
if safe:
rid, gle, _ = __last_error(collection_name, last_error_args)
return rid, msg + gle, max_bson_size
return rid, msg, max_bson_size | Internal delete message helper. |
def _serialize(self, value, attr, obj):
if isinstance(value, arrow.arrow.Arrow):
value = value.datetime
return super(ArrowField, self)._serialize(value, attr, obj) | Convert the Arrow object into a string. |
def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedded(eh)
try:
resp = view_func()
finally:
app.exit_embedded()
return locals() | Direct insertion of a Dash app |
def _readfloatle(self, length, start):
startbyte, offset = divmod(start + self._offset, 8)
if not offset:
if length == 32:
f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))
elif length == 64:
f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8)))
else:
if length == 32:
f, = struct.unpack('<f', self._readbytes(32, start))
elif length == 64:
f, = struct.unpack('<d', self._readbytes(64, start))
try:
return f
except NameError:
raise InterpretError("floats can only be 32 or 64 bits long, "
"not {0} bits", length) | Read bits and interpret as a little-endian float. |
def _set_timeouts(self, timeouts):
(send_timeout, recv_timeout) = (None, None)
try:
(send_timeout, recv_timeout) = timeouts
except TypeError:
raise EndpointError(
'`timeouts` must be a pair of numbers (2, 3) which represent '
'the timeout values for send and receive respectively')
if send_timeout is not None:
self.socket.set_int_option(
nanomsg.SOL_SOCKET, nanomsg.SNDTIMEO, send_timeout)
if recv_timeout is not None:
self.socket.set_int_option(
nanomsg.SOL_SOCKET, nanomsg.RCVTIMEO, recv_timeout) | Set socket timeouts for send and receive respectively |
def load_zipfile(self, path):
zin = zipfile.ZipFile(path)
for zinfo in zin.infolist():
name = zinfo.filename
if name.endswith("/"):
self.mkdir(name)
else:
content = zin.read(name)
self.touch(name, content) | import contents of a zipfile |
def _CreateRequest(self, url, data=None):
logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
req.add_header(key, value)
return req | Creates a new urllib request. |
def _has_exclusive_option(cls, options):
return any([getattr(options, opt) is not None for opt in
cls.BASE_ERROR_SELECTION_OPTIONS]) | Return `True` iff one or more exclusive options were selected. |
def gencode(self):
ledict = requests.get(self.api_url).json()
ledict = self.dotopdict(ledict)
out = self.dodict(ledict)
self._code = out | Run this to generate the code |
def initWithComplexQuery(query):
q = QueryEvents()
if isinstance(query, ComplexEventQuery):
q._setVal("query", json.dumps(query.getQuery()))
elif isinstance(query, six.string_types):
foo = json.loads(query)
q._setVal("query", query)
elif isinstance(query, dict):
q._setVal("query", json.dumps(query))
else:
assert False, "The instance of query parameter was not a ComplexEventQuery, a string or a python dict"
return q | create a query using a complex event query |
def init_argparser_source_registry(
self, argparser, default=None, help=(
'comma separated list of registries to use for gathering '
'JavaScript sources from the given Python packages'
)):
argparser.add_argument(
'--source-registry', default=default,
dest=CALMJS_MODULE_REGISTRY_NAMES, action=StoreDelimitedList,
metavar='<registry>[,<registry>[...]]',
help=help,
)
argparser.add_argument(
'--source-registries', default=default,
dest=CALMJS_MODULE_REGISTRY_NAMES, action=StoreDelimitedList,
help=SUPPRESS,
) | For setting up the source registry flag. |
def _reg_sighandlers(self):
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) | Registers signal handlers to this class. |
def version_ok(self, version):
return self.attribute is None or self.format is None or \
str(version) != "unknown" and version >= self.requested_version | Is 'version' sufficiently up-to-date? |
def _getActivePassive(obj1, obj2):
speed1 = abs(obj1.lonspeed) if obj1.isPlanet() else -1.0
speed2 = abs(obj2.lonspeed) if obj2.isPlanet() else -1.0
if speed1 > speed2:
return {
'active': obj1,
'passive': obj2
}
else:
return {
'active': obj2,
'passive': obj1
} | Returns which is the active and the passive objects. |
def list_databases(self, limit=None, marker=None):
return self._database_manager.list(limit=limit, marker=marker) | Returns a list of the names of all databases for this instance. |
def act(self):
g = get_root(self).globals
g.ipars.unfreeze()
g.rpars.unfreeze()
g.observe.load.enable()
self.disable() | Carries out the action associated with the Unfreeze button |
def read_14c(fl):
indata = pd.read_csv(fl, index_col=None, skiprows=11, header=None,
names=['calbp', 'c14age', 'error', 'delta14c', 'sigma'])
outcurve = CalibCurve(calbp=indata['calbp'],
c14age=indata['c14age'],
error=indata['error'],
delta14c=indata['delta14c'],
sigma=indata['sigma'])
return outcurve | Create CalibCurve instance from Bacon curve file |
def logging_decorator(func):
def you_will_never_see_this_name(*args, **kwargs):
print('calling %s ...' % func.__name__)
result = func(*args, **kwargs)
print('completed: %s' % func.__name__)
return result
return you_will_never_see_this_name | Allow logging function calls |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.