code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def detach_session(self):
if self._session is not None:
self._session.unsubscribe(self)
self._session = None | Allow the session to be discarded and don't get change notifications from it anymore |
def _marshal(self, obj):
logger.debug("Checking if %s needs to be marshalled", obj)
if isinstance(obj, ManagedObject):
logger.debug("obj is a psphere object, converting to MOR")
return obj._mo_ref
if isinstance(obj, list):
logger.debug("obj is a list, recursin... | Walks an object and marshals any psphere object into MORs. |
def _ensure_field(self, key):
if self._has_field:
self._size += 2
self._has_field = True
self._size += len(key) + 4 | Ensure a non-array field |
def read_comment(self, start: int, line: int, col: int, prev: Token) -> Token:
body = self.source.body
body_length = len(body)
position = start
while True:
position += 1
if position > body_length:
break
char = body[position]
... | Read a comment token from the source file. |
def _get_areas(self):
if self.areas is None:
self.areas = []
for surf in self.surfaces:
self.areas.append(surf.get_area())
self.areas = numpy.array(self.areas)
return self.areas | Return surface elements area values in a numpy array. |
def on_select_task(self, task):
logger.info('select %(project)s:%(taskid)s %(url)s', task)
project_info = self.projects.get(task['project'])
assert project_info, 'no such project'
task['type'] = self.TASK_PACK
task['group'] = project_info.group
task['project_md5sum'] = pr... | Called when a task is selected to fetch & process |
def _set_windows(self, ticks, bars):
self.tick_window = ticks
self.bar_window = bars | be aware of default windows |
def remove_blank_dirs(self):
if self.is_blank():
try:
os.rmdir(self.path)
except OSError as e:
print(e)
else:
remove_empty_dir(self.path) | Remove blank dir and all blank subdirectories |
def _remove_from_index(index, obj):
try:
index.value_map[indexed_value(index, obj)].remove(obj.id)
except KeyError:
pass | Removes object ``obj`` from the ``index``. |
def timex_starts(self):
if not self.is_tagged(TIMEXES):
self.tag_timexes()
return self.starts(TIMEXES) | The list of start positions of ``timexes`` layer elements. |
def ServerLoggingStartupInit():
global LOGGER
if local_log:
logging.debug("Using local LogInit from %s", local_log)
local_log.LogInit()
logging.debug("Using local AppLogInit from %s", local_log)
LOGGER = local_log.AppLogInit()
else:
LogInit()
LOGGER = AppLogInit() | Initialize the server logging configuration. |
def find_if_x_retbool_else_retbool(node):
return (
isinstance(node, ast.If)
and isinstance(node.body[0], ast.Return)
and h.is_boolean(node.body[0].value)
and h.has_else(node)
and isinstance(node.orelse[0], ast.Return)
and h.is_boolean(node.orelse[0].value)
) | Finds simplifiable if condition |
def _collect_gpu_info(run_info):
gpu_info = {}
local_device_protos = device_lib.list_local_devices()
gpu_info["count"] = len([d for d in local_device_protos
if d.device_type == "GPU"])
for d in local_device_protos:
if d.device_type == "GPU":
gpu_info["model"] = _parse_gpu_mo... | Collect local GPU information by TF device library. |
def cwd(self, new_path):
old_cwd = self._cwd
self._cwd = new_path
return old_cwd | Sets the cwd during reads and writes |
def apply(self, snapshot):
for name in snapshot:
setattr(self, name, snapshot[name]) | Set the current context from a given snapshot dictionary |
def gausspars(data):
N, mean, d = len(data), 0., 0.
if N < 1:
return "", ""
if N == 1:
return data[0], 0
for j in range(N):
mean += old_div(data[j], float(N))
for j in range(N):
d += (data[j] - mean)**2
stdev = np.sqrt(d * (1./(float(N - 1))))
return mean, std... | calculates gaussian statistics for data |
def reset(self):
self._count = 0
self._exception_count = 0
self._stat_start_time = None
self._time_sum = float(0)
self._time_min = float('inf')
self._time_max = float(0)
self._server_time_sum = float(0)
self._server_time_min = float('inf')
self._se... | Reset the statistics data for this object. |
def _meta_get_resource_sync(md_uuid):
isogeo.resource(id_resource=md_uuid)
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(md_uuid, time_completed_at))
return | Just a meta func to get execution time |
def generic_insert_with_folder(folder_name, file_name, template_name, args):
if not os.path.isdir(
os.path.join(
args['django_application_folder'],
folder_name
)
):
os.mkdir(os.path.join(args['django_application_folder'], folder_name))
codecs.open(
... | In general if we need to put a file on a folder, we use this method |
def run_until(self, endtime, timeunit='minutes', save=True):
integrator = self.case.solver.Integrator
integrator.rununtil(endtime, timeunit)
if save is True:
self.case.save() | Run a case untile the specifiend endtime |
def to_file(file, array):
try:
array.tofile(file)
except (TypeError, IOError, UnsupportedOperation):
file.write(array.tostring()) | Wrapper around ndarray.tofile to support any file-like object |
def default(self):
output = ensure_unicode(self.git.log(
'-1',
'-p',
'--no-color',
'--format=%s',
).stdout)
lines = output.splitlines()
return u'\n'.join(
itertools.chain(
lines[:1],
itertools.isl... | Return last changes in truncated unified diff format |
def clean():
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf puzzle.egg-info')
run('find . -name __pycache__ -delete')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name *~ -delete')
log.info('cleaned up') | clean - remove build artifacts. |
def to_binary_string(self):
if self.priority not in self.PRIORITIES:
raise NotificationInvalidPriorityError()
try:
token = binascii.unhexlify(self.token)
except TypeError as error:
raise NotificationTokenUnhexlifyError(error)
try:
payload =... | Pack the notification to binary form and return it as string. |
def _parse_attributes(self, value):
from zigpy.zcl import foundation as f
attributes = {}
attribute_names = {
1: BATTERY_VOLTAGE_MV,
3: TEMPERATURE,
4: XIAOMI_ATTR_4,
5: XIAOMI_ATTR_5,
6: XIAOMI_ATTR_6,
10: PATH
}
... | Parse non standard atrributes. |
def serialize_on_parent(
self,
parent,
value,
state
):
if not value and self.required:
state.raise_error(MissingValue, 'Missing required array: "{}"'.format(
self.alias))
if not value and self.omit_empty:
return
... | Serialize the value and append it to the parent element. |
def validate_data_files(problem, data_files, min_size):
data_dir = os.path.split(data_files[0])[0]
out_filepaths = problem.out_filepaths(data_dir)
missing_filepaths = set(out_filepaths) - set(data_files)
if missing_filepaths:
tf.logging.error("Missing %d data files", len(missing_filepaths))
too_small = []... | Validate presence and minimum size of files. |
def self_signed(self, value):
self._self_signed = bool(value)
if self._self_signed:
self._issuer = None | A bool - if the certificate should be self-signed. |
def _create_netmap_config(self):
netmap_path = os.path.join(self.working_dir, "NETMAP")
try:
with open(netmap_path, "w", encoding="utf-8") as f:
for bay in range(0, 16):
for unit in range(0, 4):
f.write("{ubridge_id}:{bay}/{unit}{io... | Creates the NETMAP file. |
def make_summary_funcs(rows, ids):
return {
'len': len,
'list': lambda *x: filter(None, list(x)),
'max': max,
'min': min,
'rows': partial(summary_rows, rows, ids),
'sum': sum,
'trace': print_trace
} | Functions available for listing summary fields. |
def add_subsegment(self, subsegment):
self._check_ended()
subsegment.parent_id = self.id
self.subsegments.append(subsegment) | Add input subsegment as a child subsegment. |
def __init(self):
params = {
"f" : "json"
}
json_dict = self._get(url=self._currentURL,
param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
... | populates server admin information |
def main():
trig, echo, speed, samples = get_args()
print('trig pin = gpio {}'.format(trig))
print('echo pin = gpio {}'.format(echo))
print('speed = {}'.format(speed))
print('samples = {}'.format(samples))
print('')
value = sensor.Measurement(trig, echo)
raw_distance = value.raw_distance... | Main function to run the sensor with passed arguments |
def out_shape_from_meshgrid(mesh):
if len(mesh) == 1:
return (len(mesh[0]),)
else:
return np.broadcast(*mesh).shape | Get the broadcast output shape from a `meshgrid`. |
def _delete_percolator(spec, search_pattern):
if spec:
for index in current_search.mappings.keys():
percolator_doc_type = _get_percolator_doc_type(index)
_create_percolator_mapping(index, percolator_doc_type)
current_search_client.delete(
index=index, doc_... | Delete percolator associated with the new oaiset. |
def copy(self, **replacements):
cls = type(self)
kwargs = self._asdict()
for key, val in replacements.items():
if key == 'excludes':
val = JarDependency._prepare_excludes(val)
kwargs[key] = val
org = kwargs.pop('org')
base_name = kwargs.pop('base_name')
return cls(org, base_n... | Returns a clone of this JarDependency with the given replacements kwargs overlaid. |
def _client(self, id, secret):
url = self.api_url + self.auth_token_url
auth_string = '%s:%s' % (id, secret)
authorization = base64.b64encode(auth_string.encode()).decode()
headers = {
'Authorization': "Basic " + authorization,
'Content-Type': "application/x-www-f... | Performs client login with the provided credentials |
def center_important_part(self, crop_box):
if not self.important_box:
return crop_box
ib = self.important_box
cl, ct, cr, cb = crop_box
iw, ih = self.image.size
move_horiz = (ib[0] + ib[2]) // 2 - (cl + cr) // 2
move_verti = (ib[1] + ib[3]) // 2 - (ct + cb) //... | If important_box was specified, make sure it lies inside the crop box. |
def count_changes(change):
if isinstance(change, ChangeSet):
result = 0
for child in change.changes:
result += count_changes(child)
return result
return 1 | Counts the number of basic changes a `Change` will make |
def create(cls, ip_version, datacenter, bandwidth, vm=None, vlan=None,
ip=None, background=False):
return Iface.create(ip_version, datacenter, bandwidth, vlan, vm, ip,
background) | Create a public ip and attach it if vm is given. |
def _deshuffle_field(self, *args):
ip = self._invpermutation
fields = []
for arg in args:
fields.append( arg[ip] )
if len(fields) == 1:
return fields[0]
else:
return fields | Return to original ordering |
def max_spline_jumps(self, convert_to_muC_per_cm2=True, all_in_polar=True):
tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)
sps = self.same_branch_splines(convert_to_muC_per_cm2=convert_to_muC_per_cm2,
... | Get maximum difference between spline and same branch polarization data. |
def max_knob_end_distance(self):
return max([distance(self.knob_end, h) for h in self.hole]) | Maximum distance between knob_end and each of the hole side-chain centres. |
def renamed_tree(self, source, dest):
dirname = osp.abspath(to_text_string(source))
tofile = to_text_string(dest)
for fname in self.get_filenames():
if osp.abspath(fname).startswith(dirname):
new_filename = fname.replace(dirname, tofile)
self.ren... | Directory was renamed in file explorer or in project explorer. |
def notify_update(self, update, urgent=False):
if not isinstance(update, list):
update = [update]
self.update_queue.extend(update)
containers = self.config["py3_config"][".module_groups"]
containers_to_update = set()
for item in update:
if item in containe... | Name or list of names of modules that have updated. |
def need_to_create_symlink(directory, checksums, filetype, symlink_path):
if symlink_path is None:
return False
pattern = NgdConfig.get_fileending(filetype)
filename, _ = get_name_and_checksum(checksums, pattern)
full_filename = os.path.join(directory, filename)
symlink_name = os.path.join(s... | Check if we need to create a symlink for an existing file. |
def _get_policy_set(self, policy_set_id):
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._get(uri) | Get a specific policy set by id. |
def _ctl_cmd(cmd, name, conf_file, bin_env):
ret = [_get_supervisorctl_bin(bin_env)]
if conf_file is not None:
ret += ['-c', conf_file]
ret.append(cmd)
if name:
ret.append(name)
return ret | Return the command list to use |
def shell(self, command, *args, environment=None):
command += ' ' + ' '.join(args)
command = command.strip()
self.debug(self.yellow_style('$ %s' % command))
env = self.env.copy()
env.update(environment or {})
return subprocess.call(command, shell=True, env=env) | Runs a shell command |
def load_installed_plugins():
providers = {}
checkers = {}
for entry_point in pkg_resources.iter_entry_points(group='archan'):
obj = entry_point.load()
if issubclass(obj, Provider):
providers[entry_point.name] = obj
elif issubclass(obj, Checker... | Search and load every installed plugin through entry points. |
def _iname2qname(self, iname: InstanceName) -> QualName:
p, s, loc = iname.partition(":")
return (loc, p) if s else (p, self.ns) | Translate instance name to qualified name in the receiver's context. |
def read_template_source(filename):
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filename, "rb") as f:
text = f.read().decode(settings.FILE_CHARSET)
return text | Read the source of a Django template, returning the Unicode text. |
def sleep_if_necessary(cls, user, token, endpoint='search', msg=''):
my_kw = {'auth': (user, token)} if user else {}
info = requests.get('https://api.github.com/rate_limit', **my_kw)
info_dict = info.json()
remaining = info_dict['resources'][endpoint]['remaining']
logging.debug('... | Sleep a little if hit github recently to honor rate limit. |
def printrdf(wflow, ctx, style):
rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8')
if not rdf:
return u""
return rdf.decode('utf-8') | Serialize the CWL document into a string, ready for printing. |
def _create_event(instance, action):
user = None
user_repr = repr(user)
if CUSER:
user = CuserMiddleware.get_user()
user_repr = repr(user)
if user is not None and user.is_anonymous:
user = None
return TrackingEvent.objects.create(
action=action,
object... | Create a new event, getting the use if django-cuser is available. |
def filterVerticalLines(arr, min_line_length=4):
gy = arr.shape[0]
gx = arr.shape[1]
mn = min_line_length-1
for i in range(gy):
for j in range(gx):
if arr[i,j]:
for d in range(min_line_length):
if not arr[i+d,j]:
br... | Remove vertical lines in boolean array if linelength >=min_line_length |
def addAnalyses(self, analyses):
actions_pool = ActionHandlerPool.get_instance()
actions_pool.queue_pool()
for analysis in analyses:
self.addAnalysis(api.get_object(analysis))
actions_pool.resume() | Adds a collection of analyses to the Worksheet at once |
def finish(self, result, array_id = None):
new_status = 'success' if result == 0 else 'failure'
new_result = result
finished = True
if array_id is not None:
for array_job in self.array:
if array_job.id == array_id:
array_job.status = new_status
array_job.result = result... | Sets the status of this job to 'success' or 'failure'. |
def end_output (self, **kwargs):
self.stats.downloaded_bytes = kwargs.get("downloaded_bytes")
self.stats.num_urls = kwargs.get("num_urls")
if self.has_part('stats'):
self.write_stats()
if self.has_part('outro'):
self.write_outro(interrupt=kwargs.get("interrupt"))
... | Write end of output info, and flush all output buffers. |
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs):
grid = plt_kwargs.pop('grid',True)
same_fig = plt_kwargs.pop('same_fig',False)
if not len(plt_args):
plt_args = ('ko-',)
if 'label' not in plt_kwargs:
plt_kwargs['label'] = 'Current'
if not same_fig:
make_iv_curv... | A single IV curve |
def asDict(self):
return {
'isError': self.isError,
'message': self.message,
'values': self.values,
'value': self.value,
} | Returns a serializable object |
def fileids(self):
return [os.path.join(self.path,i) for i in os.listdir(self.path)] | Returns files from SemEval2007 Coarse-grain All-words WSD task. |
def parse_consumer_offsets(cls, json_file):
with open(json_file, 'r') as consumer_offsets_json:
try:
parsed_offsets = {}
parsed_offsets_data = json.load(consumer_offsets_json)
parsed_offsets['groupid'] = parsed_offsets_data['groupid']
p... | Parse current offsets from json-file. |
def build(id=None, name=None, revision=None,
temporary_build=False, timestamp_alignment=False,
no_build_dependencies=False,
keep_pod_on_failure=False,
force_rebuild=False,
rebuild_mode=common.REBUILD_MODES_DEFAULT):
data = build_raw(id, name, revision, temporary_bui... | Trigger a BuildConfiguration by name or ID |
def _stringify_val(val):
if isinstance(val, list):
return " ".join([str(i) for i in val])
else:
return str(val) | Convert the given value to string. |
def setblocking(self, blocking):
for sock in self.socket():
sock.setblocking(blocking)
self._blocking = blocking | Set whether or not this message is blocking |
def _get_current_label(self):
if len(self._last) == 0:
raise StopIteration
return self._last[:self._last.find(":")] | Get the label from the last line read |
def remove_rule(self, tag):
resp = requests.delete(url=self.REQUEST_URL.format(**self._params),
json={'tag': tag})
return resp.json() | Remove a rule by tag |
def print_file_details_as_csv(self, fname, col_headers):
line = ''
qu = '"'
d = ','
for fld in col_headers:
if fld == "fullfilename":
line = line + qu + fname + qu + d
if fld == "name":
line = line + qu + os.path.basename(fn... | saves as csv format |
def insert(self, events):
if not len(events):
return
keys = sorted(events[0].keys())
ss = ','.join(['%s' for _ in keys])
query = 'INSERT INTO %s (%s) VALUES ' % (self.table, ','.join(keys))
data = []
for event in events:
query += '(%s),' % ss
... | Constructs and executes a MySQL insert for the given events. |
def target_to_ipv6_cidr(target):
splitted = target.split('/')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
block = int(splitted[1])
except (socket.error, ValueError):
return None
if block <= 0 or block > 126:
r... | Attempt to return a IPv6 CIDR list from a target string. |
def engines(opts, functions, runners, utils, proxy=None):
pack = {'__salt__': functions,
'__runners__': runners,
'__proxy__': proxy,
'__utils__': utils}
return LazyLoader(
_module_dirs(opts, 'engines'),
opts,
tag='engines',
pack=pack,
) | Return the master services plugins |
def close(self):
for plugin in self.plugins:
if hasattr(plugin, 'close'): plugin.close()
self.stopped = True | Close the application and all installed plugins. |
def run(self):
_LOGGER.info("Started")
while True:
self._maybe_reconnect()
line = ''
try:
t = self._telnet
if t is not None:
line = t.read_until(b"\n")
except EOFError:
try:
self._lock.acquire()
self._disconnect_locked()
con... | Main thread function to maintain connection and receive remote status. |
def ref_file_from_bam(bam_file, data):
new_ref = os.path.join(utils.safe_makedir(os.path.join(dd.get_work_dir(data), "inputs", "ref")),
"%s-subset.fa" % dd.get_genome_build(data))
if not utils.file_exists(new_ref):
with file_transaction(data, new_ref) as tx_out_file:
... | Subset a fasta input file to only a fraction of input contigs. |
def unserialize(self, data):
if "author" not in data["object"]:
data["object"]["author"] = data["actor"]
for key in ["to", "cc", "bto", "bcc"]:
if key not in data["object"] and key in data:
data["object"][key] = data[key]
Mapper(pypump=self._pump).parse_ma... | From JSON -> Activity object |
def _handle_wikilink(self, token):
title = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.WikilinkSeparator):
title = self._pop()
self._push()
elif isinstance(token, tokens.WikilinkC... | Handle a case where a wikilink is at the head of the tokens. |
def findExtname(fimg, extname, extver=None):
i = 0
extnum = None
for chip in fimg:
hdr = chip.header
if 'EXTNAME' in hdr:
if hdr['EXTNAME'].strip() == extname.upper():
if extver is None or hdr['EXTVER'] == extver:
extnum = i
... | Returns the list number of the extension corresponding to EXTNAME given. |
def do_hotswap(self, msg):
try:
self.app.widget.showTooltip("Hot swapping...", now=True)
except:
pass
self.save_changed_files(msg)
hotswap = self.hotswap
app = self.app
try:
print("Attempting hotswap....")
with hotswap.activ... | Attempt to hotswap the code |
async def is_bot(self):
if self._bot is None:
self._bot = (await self.get_me()).bot
return self._bot | Return ``True`` if the signed-in user is a bot, ``False`` otherwise. |
def unpack_bytes(self, obj_bytes, encoding=None):
assert self.bytes_to_dict or self.string_to_dict
encoding = encoding or self.default_encoding
LOGGER.debug('%r decoding %d bytes with encoding of %s',
self, len(obj_bytes), encoding)
if self.bytes_to_dict:
... | Unpack a byte stream into a dictionary. |
def get(cls, uni_char):
uni_char = unicod(uni_char)
code_point = ord(uni_char)
if Block._RANGE_KEYS is None:
Block._RANGE_KEYS = sorted(Block._RANGES.keys())
idx = bisect.bisect_left(Block._RANGE_KEYS, code_point)
if (idx > 0 and
code_point >= Block._RANGE... | Return the Unicode block of the given Unicode character |
def _write_history(self):
if self.data['history_file'] is None:
return
contents = '\n'.join(self.data['history_lines'])
history = self.data['history_file']
open(history, 'w').write(contents)
logger.info("History file %s updated.", history) | Write previously-calculated history lines back to the file |
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT,
ca_certs=None, validate=None):
if not ca_certs:
return False
xlog.debug("CONNECT SSL %s:%s, cert_file=%s",
hostname, port, ca_certs)
certificate = ssl.get_server_certific... | returns true if connection should verify certificate |
def clear(board, term, height):
for y in xrange(height):
print term.move(y, 0) + term.clear_eol, | Clear the droppings of the given board. |
def Indentation( logical_line,
previous_logical,
indent_level,
previous_indent_level ):
comment = '' if logical_line else ' (comment)'
if indent_level % 2:
code = 'YCM111' if logical_line else 'YCM114'
message = ' indentation is not a multiple of two spaces... | Use two spaces per indentation level. |
def _reduce_input(self, inputs, reducer, final=NotImplemented):
for key, values in groupby(inputs, key=lambda x: self.internal_serialize(x[0])):
for output in reducer(self.deserialize(key), (v[1] for v in values)):
yield output
if final != NotImplemented:
for outp... | Iterate over input, collect values with the same key, and call the reducer for each unique key. |
def ProcessFlow(self, flow_processing_request):
client_id = flow_processing_request.client_id
flow_id = flow_processing_request.flow_id
data_store.REL_DB.AckFlowProcessingRequests([flow_processing_request])
try:
rdf_flow = data_store.REL_DB.LeaseFlowForProcessing(
client_id, flow_id, pro... | The callback for the flow processing queue. |
def process_relation_class(self, relation_class, context, assert_declared=False):
relation_class.database = self.database
relation_class._connection = self.connection
relation_class._heading = Heading()
instance = relation_class()
is_declared = instance.is_declared
if not... | assign schema properties to the relation class and declare the table |
def download_files(files):
for (url, file) in files:
print("Downloading %s as %s" % (url, file))
data = download_url(url)
if data is None:
continue
try:
open(file, mode='wb').write(data)
except Exception as e:
print("Failed to save to %s : ... | download an array of files |
def __registerSeqStr():
_SeqStr = lambda self: (self and "[%s]" % (", ".join(map(repr, self)))) or "[]"
_SeqRepr = lambda self: (self and "[%s]" % (", ".join(map(repr, self)))) or "[]"
seqs = (StdStringVector, StdLongVector, CommandInfoList,
AttributeInfoList, AttributeInfoListEx, PipeInfoList,
... | helper function to make internal sequences printable |
def removefromreadergroup(self, groupname):
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise EstablishContextException(hresult)
try:
hresult = SCardRemoveReaderFromGroup(hcontext, self.name,
groupname)
if 0 != ... | Remove a reader from a reader group |
def install_API_key(api_key, profile_name='default'):
fname = API_profile_fname(profile_name)
if not os.path.isdir(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
with open(fname, 'w') as fh:
fh.write(api_key) | Put the given API key into the given profile name. |
def read(self, path, environ):
try:
inp = open(path, 'rb')
except FileNotFoundError as error:
if error.errno != 2:
raise
return None
parsing = parse_vexrc(inp, environ)
for heading, key, value in parsing:
heading = self.defa... | Read data from file into this vexrc instance. |
def min_abs(self):
if self.__len__() == 0:
return ArgumentError('empty set has no minimum absolute value.')
if self.contains(0):
return 0
return numpy.min([numpy.abs(val)
for val in [self.max_neg(), self.min_pos()]
if va... | Returns minimum absolute value. |
def _get_tree_paths(tree, node_id, depth=0):
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
if left_child != _tree.TREE_LEAF:
left_paths = _get_tree_paths(tree, le... | Returns all paths through the tree as list of node_ids |
def variables(self):
url = self.base_url + 'ts'
headers = {'Authorization': 'Bearer {}'.format(self.auth())}
r = requests.get(url, headers=headers)
df = pd.read_json(r.content, orient='records')
return pd.Series(df['variable'].unique(), name='variable') | All variables in the connected data source |
def add_node(self, node):
if _debug: Network._debug("add_node %r", node)
self.nodes.append(node)
node.lan = self
if not node.name:
node.name = '%s:%s' % (self.name, node.address) | Add a node to this network, let the node know which network it's on. |
def _load_options(self, container, **options):
for opt in self.dict_options():
options.setdefault(opt, container)
return anyconfig.utils.filter_options(self._load_opts, options) | Select backend specific loading options. |
def sponsor_tagged_image(sponsor, tag):
if sponsor.files.filter(tag_name=tag).exists():
return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url
return '' | returns the corresponding url from the tagged image list. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.