code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def expiration_time(self):
logging_forgotten_time = configuration.behavior.login_forgotten_seconds
if logging_forgotten_time <= 0:
return None
now = timezone.now()
delta = now - self.modified
time_remaining = logging_forgotten_time - delta.seconds
return time_remaining | Returns the time until this access attempt is forgotten. |
def _setintbe(self, intbe, length=None):
if length is not None and length % 8 != 0:
raise CreationError("Big-endian integers must be whole-byte. "
"Length = {0} bits.", length)
self._setint(intbe, length) | Set bitstring to a big-endian signed int interpretation. |
def servers(self):
url = "%s/servers" % self.root
return Servers(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | gets the federated or registered servers for Portal |
def clear_cache(cls):
for key in cls._cached:
cls._cached[key] = None
cls._cached = {} | Call this before closing tk root |
def reset_field_value(self, name):
name = self.get_real_name(name)
if name and self._can_write_field(name):
if name in self.__modified_data__:
del self.__modified_data__[name]
if name in self.__deleted_fields__:
self.__deleted_fields__.remove(name)
try:
self.__original_data__[name].clear_modified_data()
except (KeyError, AttributeError):
pass | Resets value of a field |
def BytesSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = local_len(element)
result += local_VarintSize(l) + l
return result
return RepeatedFieldSize
else:
def FieldSize(value):
l = local_len(value)
return tag_size + local_VarintSize(l) + l
return FieldSize | Returns a sizer for a bytes field. |
def _send(self, message, fail_silently=False):
seeds = '1234567890qwertyuiopasdfghjklzxcvbnm'
file_part1 = datetime.now().strftime('%Y%m%d%H%M%S')
file_part2 = ''.join(sample(seeds, 4))
filename = join(self.tld, '%s_%s.msg' % (file_part1, file_part2))
with open(filename, 'w') as fd:
fd.write(str(message.to_message())) | Save message to a file for debugging |
def post_request(self, endpoint, body=None, timeout=-1):
return self.request('POST', endpoint, body, timeout) | Perform a POST request to a given endpoint in UpCloud's API. |
def recatalog_analyses_due_date(portal):
logger.info("Updating Analyses getDueDate")
catalog = api.get_tool(CATALOG_ANALYSIS_LISTING)
review_states = ["retracted", "sample_due", "attachment_due",
"sample_received", "to_be_verified"]
query = dict(portal_type="Analysis", review_state=review_states)
analyses = api.search(query, CATALOG_ANALYSIS_LISTING)
total = len(analyses)
num = 0
for num, analysis in enumerate(analyses, start=1):
analysis = api.get_object(analysis)
catalog.catalog_object(analysis, idxs=['getDueDate'])
if num % 100 == 0:
logger.info("Updating Analysis getDueDate: {0}/{1}"
.format(num, total))
logger.info("{} Analyses updated".format(num)) | Recatalog the index and metadata field 'getDueDate' |
def confirmation(self, pdu):
if _debug: NetworkAdapter._debug("confirmation %r (net=%r)", pdu, self.adapterNet)
npdu = NPDU(user_data=pdu.pduUserData)
npdu.decode(pdu)
self.adapterSAP.process_npdu(self, npdu) | Decode upstream PDUs and pass them up to the service access point. |
def add_address(self, fqdn, address, ttl=0):
" Add a new address to a domain."
data = {'rdata': {'address': address}, 'ttl': str(ttl)}
response = self.post('/REST/ARecord/%s/%s' % (
self.zone, fqdn), data=data)
return Address(self, data=response.content['data']) | Add a new address to a domain. |
def _query(self, action, qobj):
title = self.params.get('title')
pageid = self.params.get('pageid')
if action == 'random':
return qobj.random(namespace=14)
elif action == 'category':
return qobj.category(title, pageid, self._continue_params()) | Form query to enumerate category |
def _unpack_msg(self, *msg):
l = []
for m in msg:
l.append(str(m))
return " ".join(l) | Convert all message elements to string |
def find_parent_outputs(provider: Provider, utxo: TxIn) -> TxOut:
network_params = net_query(provider.network)
index = utxo.txout
return TxOut.from_json(provider.getrawtransaction(utxo.txid,
1)['vout'][index],
network=network_params) | due to design of the btcpy library, TxIn object must be converted to TxOut object before signing |
def cli(yamlfile, format, output):
print(OwlSchemaGenerator(yamlfile, format).serialize(output=output)) | Generate an OWL representation of a biolink model |
def convert_job(row: list) -> dict:
state = row[-2]
start_time_raw = row[-4]
end_time_raw = row[-3]
if state not in ('PENDING', 'CANCELLED'):
start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S')
if state != 'RUNNING':
end_time = datetime.strptime(end_time_raw, '%Y-%m-%dT%H:%M:%S')
else:
end_time = None
else:
start_time = end_time = None
job_name = row[1]
step_name, step_context = job_name.rstrip('_BOTH').rstrip('_SV').rsplit('_', 1)
return {
'id': int(row[0]),
'name': job_name,
'step': step_name,
'context': step_context,
'state': state,
'start': start_time,
'end': end_time,
'elapsed': time_to_sec(row[-5]),
'cpu': time_to_sec(row[-6]),
'is_completed': state == 'COMPLETED',
} | Convert sacct row to dict. |
def wait_while(self, condition, *args, **kw):
return self.wait_for(lambda: not condition(), *args, **kw) | Wait while a condition holds. |
def main(args=None, **kwargs):
LOG.info('Starting %s', __service_id__)
return run([SDPMasterDevice], verbose=True, msg_stream=sys.stdout,
args=args, **kwargs) | Run the Tango SDP Master device server. |
def _page_has_text(text_blocks, page_width, page_height):
pw, ph = float(page_width), float(page_height)
margin_ratio = 0.125
interior_bbox = (
margin_ratio * pw,
(1 - margin_ratio) * ph,
(1 - margin_ratio) * pw,
margin_ratio * ph,
)
def rects_intersect(a, b):
return a[0] < b[2] and a[2] > b[0] and a[1] > b[3] and a[3] < b[1]
has_text = False
for bbox in text_blocks:
if rects_intersect(bbox, interior_bbox):
has_text = True
break
return has_text | Smarter text detection that ignores text in margins |
def add_int(self,oid,value,label=None):
self.add_oid_entry(oid,'INTEGER',value,label=label) | Short helper to add an integer value to the MIB subtree. |
def topological_sort(dependency_pairs):
"Sort values subject to dependency constraints"
num_heads = defaultdict(int)
tails = defaultdict(list)
heads = []
for h, t in dependency_pairs:
num_heads[t] += 1
if h in tails:
tails[h].append(t)
else:
tails[h] = [t]
heads.append(h)
ordered = [h for h in heads if h not in num_heads]
for h in ordered:
for t in tails[h]:
num_heads[t] -= 1
if not num_heads[t]:
ordered.append(t)
cyclic = [n for n, heads in num_heads.items() if heads]
return Results(ordered, cyclic) | Sort values subject to dependency constraints |
def _f90str(self, value):
result = repr(str(value)).replace("\\'", "''").replace('\\"', '""')
result = result.replace('\\\\', '\\')
return result | Return a Fortran 90 representation of a string. |
async def get_soundfield(self) -> List[Setting]:
res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"})
return Setting.make(**res[0]) | Get the current sound field settings. |
def attended_by(self, email):
for attendee in self["attendees"] or []:
if (attendee["email"] == email
and attendee["responseStatus"] == "accepted"):
return True
return False | Check if user attended the event |
def get(self, key, sort_key):
key = self.prefixed('{}:{}'.format(key, sort_key))
self.logger.debug('Storage - get {}'.format(key))
if key not in self.cache.keys():
return None
return self.cache[key] | Get an element in dictionary |
def _verify_default(self, spec, path):
field_type = spec['type']
default = spec['default']
if callable(default):
return
if isinstance(field_type, Array):
if not isinstance(default, list):
raise SchemaFormatException("Default value for Array at {} is not a list of values.", path)
for i, item in enumerate(default):
if isinstance(field_type.contained_type, Schema):
if not self._valid_schema_default(item):
raise SchemaFormatException("Default value for Schema is not valid.", path)
elif not isinstance(item, field_type.contained_type):
raise SchemaFormatException("Not all items in the default list for the Array field at {} are of the correct type.", path)
elif isinstance(field_type, Schema):
if not self._valid_schema_default(default):
raise SchemaFormatException("Default value for Schema is not valid.", path)
else:
if not isinstance(default, field_type):
raise SchemaFormatException("Default value for {} is not of the nominated type.", path) | Verifies that the default specified in the given spec is valid. |
def ck2respth(argv=None):
parser = ArgumentParser(
description='Convert a ChemKED YAML file to a ReSpecTh XML file.'
)
parser.add_argument('-i', '--input',
type=str,
required=True,
help='Input filename (e.g., "file1.xml")'
)
parser.add_argument('-o', '--output',
type=str,
required=False,
default='',
help='Output filename (e.g., "file1.yaml")'
)
args = parser.parse_args(argv)
c = chemked.ChemKED(yaml_file=args.input)
c.convert_to_ReSpecTh(args.output) | Command-line entry point for converting a ChemKED YAML file to a ReSpecTh XML file. |
def startAll(self):
self.logger.info("Starting all threads...")
for thread in self.getThreads():
thr = self.getThread(thread)
self.logger.debug("Starting {0}".format(thr.name))
thr.start()
self.logger.info("Started all threads") | Start all registered Threads. |
def dc_element(self, parent, name, text):
if self.dc_uri in self.namespaces:
dcel = SchemaNode(self.namespaces[self.dc_uri] + ":" + name,
text=text)
parent.children.insert(0,dcel) | Add DC element `name` containing `text` to `parent`. |
def build_grid(self):
build_grid.transformer(self)
build_grid.build_ret_ind_agr_branches(self.grid_district)
build_grid.build_residential_branches(self.grid_district) | Create LV grid graph |
def add_ssh_options(self, parser):
parser.add_argument(
"--username", metavar='USER', help=(
"Username for the SSH connection."))
parser.add_argument(
"--boot-only", action="store_true", help=(
"Only use the IP addresses on the machine's boot interface.")) | Add the SSH arguments to the `parser`. |
def _convert_volume(self, volume):
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data | This is for ingesting the "volumes" of a app description |
def ffmpeg(*args, **kwargs):
ff = FFMPEG(*args, **kwargs)
ff.start(
stdin=kwargs.get("stdin", None),
stdout=kwargs.get("stdout", None),
stderr=kwargs.get("stderr", subprocess.PIPE)
)
ff.wait(kwargs.get("progress_handler", None))
if ff.return_code:
err = indent(ff.error_log)
logging.error("Problem occured during transcoding\n\n{}\n\n".format(err))
return False
return True | Universal ffmpeg wrapper with progress and error handling |
def set(self, key, value):
"Set value to the key store."
if not isinstance(value, dict):
raise BadValueError(
'The value {} is incorrect.'
' Values should be strings'.format(value))
_value = deepcopy(value)
if key in self.data:
self.delete_from_index(key)
self.data[key] = _value
self.update_index(key, _value) | Set value to the key store. |
async def async_get_bridgeid(session, host, port, api_key, **kwargs):
url = 'http://{}:{}/api/{}/config'.format(host, str(port), api_key)
response = await async_request(session.get, url)
bridgeid = response['bridgeid']
_LOGGER.info("Bridge id: %s", bridgeid)
return bridgeid | Get bridge id for bridge. |
def getPixelAttrMost(self, x, y):
'most common attr at this pixel.'
r = self.pixels[y][x]
c = sorted((len(rows), attr, rows) for attr, rows in list(r.items()) if attr and attr not in self.hiddenAttrs)
if not c:
return 0
_, attr, rows = c[-1]
if isinstance(self.source, BaseSheet) and anySelected(self.source, rows):
attr = CursesAttr(attr, 8).update_attr(colors.color_graph_selected, 10).attr
return attr | most common attr at this pixel. |
def close(self):
if not self.closed:
self._ipython.events.unregister('post_run_cell', self._fill)
self._box.close()
self.closed = True | Close and remove hooks. |
def _print_fields(self, fields):
longest_name = max(fields, key=lambda f: len(f[1]))[1]
longest_type = max(fields, key=lambda f: len(f[2]))[2]
field_format = '%s%-{}s %-{}s %s'.format(
len(longest_name) + self._padding_after_name,
len(longest_type) + self._padding_after_type)
for field in fields:
self._print(field_format % field) | Print the fields, padding the names as necessary to align them. |
def __create_profile(self, profile, uuid, verbose):
kw = profile.to_dict()
kw['country_code'] = profile.country_code
kw.pop('uuid')
kw.pop('country')
api.edit_profile(self.db, uuid, **kw)
self.log("-- profile %s updated" % uuid, verbose) | Create profile information from a profile object |
def _GetPqlService(self):
if not self._pql_service:
self._pql_service = self._ad_manager_client.GetService(
'PublisherQueryLanguageService', self._version, self._server)
return self._pql_service | Lazily initializes a PQL service client. |
def add_table(self, dataframe, isStyled = False):
if isStyled :
table_string = dataframe.render()
else :
table_string = dataframe.style.render()
table_string = table_string.replace("\n", "").replace("<table", ).replace("<thead>", """<thead class="thead-inverse">""")
self.table = table_string | This method stores plain html string. |
def update_room(self, stream_id, room_definition):
req_hook = 'pod/v2/room/' + str(stream_id) + '/update'
req_args = json.dumps(room_definition)
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response | update a room definition |
def find_type_conversion(source_type, target_type):
if type(source_type) == type(target_type):
return 'identity'
elif type(target_type) == FloatTensorType:
return 'imageToFloatTensor'
else:
raise ValueError('Unsupported type conversion from %s to %s' % (
source_type, target_type)) | Find the operator name for converting source_type into target_type |
def Wp(self):
Wp = trapz_loglog(self._Ep * self._J, self._Ep) * u.GeV
return Wp.to("erg") | Total energy in protons |
def writelines(self, lines):
self.make_dir()
with open(self.path, "w") as f:
return f.writelines(lines) | Write a list of strings to file. |
def createTopicPage1():
topic = TopicPage(er)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("biofuel"), 50)
topic.addConcept(er.getConceptUri("solar energy"), 50)
topic.addCategory(er.getCategoryUri("renewable"), 50)
topic.articleHasDuplicateFilter("skipHasDuplicates")
topic.articleHasEventFilter("skipArticlesWithoutEvent")
arts1 = topic.getArticles(page=1, sortBy="rel")
arts2 = topic.getArticles(page=2, sortBy="rel")
events1 = topic.getEvents(page=1) | create a topic page directly |
def roles_autocomplete(self, text, line, start_index, end_index):
"Return full list of roles"
if '-' not in line:
return [s + '-' for s in self.services_autocomplete(text, line, start_index, end_index)]
else:
key, role = line.split()[1].split('-', 1)
if key not in self.CACHED_ROLES:
service = api.get_cluster(self.cluster).get_service(key)
roles = []
for t in service.get_role_types():
for r in service.get_roles_by_type(t):
roles.append(r.name)
self.CACHED_ROLES[key] = roles
if not role:
return self.CACHED_ROLES[key]
else:
return [r for r in self.CACHED_ROLES[key] if r.startswith(line.split()[1])] | Return full list of roles |
def wait(self, interval=SGE_WAIT):
finished = False
while not finished:
time.sleep(interval)
interval = min(2 * interval, 60)
finished = os.system("qstat -j %s > /dev/null" % (self.name)) | Wait until the job finishes, and poll SGE on its status. |
def _slugify(text, delim=u'-'):
result = []
for word in _punct_re.split(text.lower()):
word = word.encode('utf-8')
if word:
result.append(word)
slugified = delim.join([i.decode('utf-8') for i in result])
return re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, slugified).lower() | Generates an ASCII-only slug. |
def msg(self, level, s, *args):
if s and level <= self.debug:
print "%s%s %s" % (" " * self.indent, s, ' '.join(map(repr, args))) | Print a debug message with the given level |
def datetime_to_timestamp(dt):
delta = dt - datetime.utcfromtimestamp(0)
return delta.seconds + delta.days * 24 * 3600 | Convert a UTC datetime to a Unix timestamp |
def generate (self, ps):
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets().log(
"Building project '%s' with '%s'" % (self.name (), str(ps)))
self.manager_.targets().increase_indent ()
result = GenerateResult ()
for t in self.targets_to_build ():
g = t.generate (ps)
result.extend (g)
self.manager_.targets().decrease_indent ()
return result | Generates all possible targets contained in this project. |
def _recv(self):
from . import mavutil
start_time = time.time()
while time.time() < start_time + self.timeout:
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
type='SERIAL_CONTROL', blocking=False, timeout=0)
if m is not None and m.count != 0:
break
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |
mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,
0,
0,
0, [0]*70)
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
type='SERIAL_CONTROL', blocking=True, timeout=0.01)
if m is not None and m.count != 0:
break
if m is not None:
if self._debug > 2:
print(m)
data = m.data[:m.count]
self.buf += ''.join(str(chr(x)) for x in data) | read some bytes into self.buf |
def _first(self, tag):
self.getelements()
for element in self.elements:
if tag in self.pos(element):
return element
return None | Returns the first element with required POS-tag. |
def end_headers(self):
for name, value in self._headers.items():
self._handler.send_header(name, value)
self._handler.end_headers() | Ends the headers part |
def _enableTracesVerilog(self, verilogFile):
fname, _ = os.path.splitext(verilogFile)
inserted = False
for _, line in enumerate(fileinput.input(verilogFile, inplace = 1)):
sys.stdout.write(line)
if line.startswith("end") and not inserted:
sys.stdout.write('\n\n')
sys.stdout.write('initial begin\n')
sys.stdout.write(' $dumpfile("{}_cosim.vcd");\n'.format(fname))
sys.stdout.write(' $dumpvars(0, dut);\n')
sys.stdout.write('end\n\n')
inserted = True | Enables traces in a Verilog file |
def title_from_content(content):
for end in (". ", "?", "!", "<br />", "\n", "</p>"):
if end in content:
content = content.split(end)[0] + end
break
return strip_tags(content) | Try and extract the first sentence from a block of test to use as a title. |
def parse_string(self, string):
self.log.info("Parsing ASCII data")
if not string:
self.log.warning("Empty metadata")
return
lines = string.splitlines()
application_data = []
application = lines[0].split()[0]
self.log.debug("Reading meta information for '%s'" % application)
for line in lines:
if application is None:
self.log.debug(
"Reading meta information for '%s'" % application
)
application = line.split()[0]
application_data.append(line)
if line.startswith(application + b' Linux'):
self._record_app_data(application_data)
application_data = []
application = None | Parse ASCII output of JPrintMeta |
def expire(app, sandbox, exit=True):
success = []
failures = []
service = _mturk_service_from_config(sandbox)
hits = _current_hits(service, app)
for hit in hits:
hit_id = hit["id"]
try:
service.expire_hit(hit_id)
success.append(hit_id)
except MTurkServiceException:
failures.append(hit_id)
out = Output()
if success:
out.log("Expired {} hits: {}".format(len(success), ", ".join(success)))
if failures:
out.log(
"Could not expire {} hits: {}".format(len(failures), ", ".join(failures))
)
if not success and not failures:
out.log("No hits found for this application.")
if not sandbox:
out.log(
"If this experiment was run in the MTurk sandbox, use: "
"`dallinger expire --sandbox --app {}`".format(app)
)
if exit and not success:
sys.exit(1) | Expire hits for an experiment id. |
def _read_config_file(self):
try:
with open(self.config, 'r') as f:
config_data = json.load(f)
except FileNotFoundError:
config_data = {}
return config_data | read in the configuration file, a json file defined at self.config |
def find_file_dir_up(filename, path=None, n=None):
if path is None:
path = os.getcwd()
i = 0
while True:
current_path = path
for _ in range(i):
current_path = os.path.split(current_path)[0]
if os.path.isfile(os.path.join(current_path, filename)):
return os.path.join(current_path, filename)
elif os.path.dirname(current_path) == current_path:
return
elif n is not None and i == n:
return
else:
i += 1
continue | Finding file in directory upwards. |
def get(self, key, defaultValue=None):
if defaultValue is None:
if self._jconf is not None:
if not self._jconf.contains(key):
return None
return self._jconf.get(key)
else:
if key not in self._conf:
return None
return self._conf[key]
else:
if self._jconf is not None:
return self._jconf.get(key, defaultValue)
else:
return self._conf.get(key, defaultValue) | Get the configured value for some key, or return a default otherwise. |
def db_url_from_hass_config(path):
config = load_hass_config(path)
default_path = os.path.join(path, "home-assistant_v2.db")
default_url = "sqlite:///{}".format(default_path)
recorder = config.get("recorder")
if recorder:
db_url = recorder.get("db_url")
if db_url is not None:
return db_url
if not os.path.isfile(default_path):
raise ValueError(
"Unable to determine DB url from hass config at {}".format(path)
)
return default_url | Find the recorder database url from a HASS config dir. |
def _get_ll_pointer_type(self, target_data, context=None):
from . import Module, GlobalVariable
from ..binding import parse_assembly
if context is None:
m = Module()
else:
m = Module(context=context)
foo = GlobalVariable(m, self, name="foo")
with parse_assembly(str(m)) as llmod:
return llmod.get_global_variable(foo.name).type | Convert this type object to an LLVM type. |
def as_slice(slice_):
if isinstance(slice_, (Integral, numpy.integer, type(None))):
return slice(0, None, 1)
if isinstance(slice_, (slice, numpy.ndarray)):
return slice_
if isinstance(slice_, (list, tuple)):
return tuple(map(as_slice, slice_))
raise TypeError("Cannot format {!r} as slice".format(slice_)) | Convert an object to a slice, if possible |
def _ResolveContext(self, context, name, raw_data, path=None):
if path is None:
path = []
for element in context:
if element not in self.valid_contexts:
raise InvalidContextError("Invalid context specified: %s" % element)
if element in raw_data:
context_raw_data = raw_data[element]
value = context_raw_data.get(name)
if value is not None:
if isinstance(value, string_types):
value = value.strip()
yield context_raw_data, value, path + [element]
for context_raw_data, value, new_path in self._ResolveContext(
context, name, context_raw_data, path=path + [element]):
yield context_raw_data, value, new_path | Returns the config options active under this context. |
def generate_network(user=None, reset=False):
token = collect_token()
try:
gh = login(token=token)
root_user = gh.user(user)
except Exception, e:
raise e
graph_nodes = []
graph_edges = []
username = user if user is not None else root_user.login
if not is_cached(username_to_file(username)) or reset:
graph_nodes.append(username)
try:
for person in gh.iter_following(username):
graph_nodes.append(str(person))
graph_edges.append((root_user.login, str(person)))
for i in range(1, root_user.following):
user = gh.user(graph_nodes[i])
user_following_edges = [(user.login, str(person)) for person in gh.iter_following(
user) if str(person) in graph_nodes]
graph_edges += user_following_edges
except Exception, e:
raise e
generate_gml(username, graph_nodes, graph_edges, True)
else:
reuse_gml(username)
return username | Assemble the network connections for a given user |
def destroy_dns_records(fqdn):
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False | Deletes DNS records for the given hostname if the domain is managed with DO. |
def select_workers_to_close(scheduler, n_to_close):
workers = list(scheduler.workers.values())
assert n_to_close <= len(workers)
key = lambda ws: ws.metrics['memory']
to_close = set(sorted(scheduler.idle, key=key)[:n_to_close])
if len(to_close) < n_to_close:
rest = sorted(workers, key=key, reverse=True)
while len(to_close) < n_to_close:
to_close.add(rest.pop())
return [ws.address for ws in to_close] | Select n workers to close from scheduler |
def package_releases(self, package_name):
if self.debug:
self.logger.debug("DEBUG: querying PyPI for versions of " \
+ package_name)
return self.xmlrpc.package_releases(package_name) | Query PYPI via XMLRPC interface for a pkg's available versions |
def validate(config):
if not isinstance(config, list):
return False, 'Configuration for napalm beacon must be a list.'
for mod in config:
fun = mod.keys()[0]
fun_cfg = mod.values()[0]
if not isinstance(fun_cfg, dict):
return False, 'The match structure for the {} execution function output must be a dictionary'.format(fun)
if fun not in __salt__:
return False, 'Execution function {} is not availabe!'.format(fun)
return True, 'Valid configuration for the napal beacon!' | Validate the beacon configuration. |
def _osquery(sql, format='json'):
ret = {
'result': True,
}
cmd = ['osqueryi'] + ['--json'] + [sql]
res = __salt__['cmd.run_all'](cmd)
if res['stderr']:
ret['result'] = False
ret['error'] = res['stderr']
else:
ret['data'] = salt.utils.json.loads(res['stdout'])
log.debug('== %s ==', ret)
return ret | Helper function to run raw osquery queries |
def argparser(self):
if self.__argparser is None:
self.__argparser = self.argparser_factory()
self.init_argparser(self.__argparser)
return self.__argparser | For setting up the argparser for this instance. |
def custom_add_user_view(request):
page_name = "Admin - Add User"
add_user_form = AddUserForm(request.POST or None, initial={
'status': UserProfile.RESIDENT,
})
if add_user_form.is_valid():
add_user_form.save()
message = MESSAGES['USER_ADDED'].format(
username=add_user_form.cleaned_data["username"])
messages.add_message(request, messages.SUCCESS, message)
return HttpResponseRedirect(reverse('custom_add_user'))
return render_to_response('custom_add_user.html', {
'page_name': page_name,
'add_user_form': add_user_form,
'members': User.objects.all().exclude(username=ANONYMOUS_USERNAME),
}, context_instance=RequestContext(request)) | The page to add a new user. |
def _get_slave_timeout(self, dpid, port):
slave = self._get_slave(dpid, port)
if slave:
return slave['timeout']
else:
return 0 | get the timeout time at some port of some datapath. |
def lock(self, resource_id, region, account_id=None):
account_id = self.get_account_id(account_id)
return self.http.post(
"%s/%s/locks/%s/lock" % (self.endpoint, account_id, resource_id),
json={'region': region},
auth=self.get_api_auth()) | Lock a given resource |
def _trim_xpath(self, xpath, prop):
xroot = self._get_xroot_for(prop)
if xroot is None and isinstance(xpath, string_types):
xtags = xpath.split(XPATH_DELIM)
if xtags[-1] in _iso_tag_primitives:
xroot = XPATH_DELIM.join(xtags[:-1])
return xroot | Removes primitive type tags from an XPATH |
def printStats(self):
printDebug("----------------")
printDebug("Parents......: %d" % len(self.parents()))
printDebug("Children.....: %d" % len(self.children()))
printDebug("Ancestors....: %d" % len(self.ancestors()))
printDebug("Descendants..: %d" % len(self.descendants()))
printDebug("Domain of....: %d" % len(self.domain_of))
printDebug("Range of.....: %d" % len(self.range_of))
printDebug("Instances....: %d" % self.count())
printDebug("----------------") | shortcut to pull out useful info for interactive use |
def to_136_array(tiles):
temp = []
results = []
for x in range(0, 34):
if tiles[x]:
temp_value = [x * 4] * tiles[x]
for tile in temp_value:
if tile in results:
count_of_tiles = len([x for x in temp if x == tile])
new_tile = tile + count_of_tiles
results.append(new_tile)
temp.append(tile)
else:
results.append(tile)
temp.append(tile)
return results | Convert 34 array to the 136 tiles array |
def pageSize(cls):
try:
try:
pageSize = win32.GetSystemInfo().dwPageSize
except WindowsError:
pageSize = 0x1000
except NameError:
pageSize = 0x1000
cls.pageSize = pageSize
return pageSize | Try to get the pageSize value on runtime. |
def monitor(msg, *args, **kwargs):
if len(logging.root.handlers) == 0:
logging.basicConfig()
logging.root.monitor(msg, *args, **kwargs) | Log a message with severity 'MON' on the root logger. |
def add_subscribers(self, subscribers, **kwargs):
if subscribers:
with self._callbacks_lock:
self._add_subscribers_for_type(
'done', subscribers, self._done_callbacks, **kwargs)
self._add_subscribers_for_type(
'queued', subscribers, self._queued_callbacks, **kwargs)
self._add_subscribers_for_type(
'progress', subscribers, self._progress_callbacks, **kwargs) | Add a callbacks to be invoked during transfer |
def region_selection(request):
form = get_region_select_form(request.GET)
abbr = form.data.get('abbr')
if not abbr or len(abbr) != 2:
return redirect('homepage')
return redirect('region', abbr=abbr) | Handle submission of the region selection form in the base template. |
def prepare_bam(bam_in, precursors):
a = pybedtools.BedTool(bam_in)
b = pybedtools.BedTool(precursors)
c = a.intersect(b, u=True)
out_file = utils.splitext_plus(op.basename(bam_in))[0] + "_clean.bam"
c.saveas(out_file)
return op.abspath(out_file) | Clean BAM file to keep only position inside the bigger cluster |
def login(self):
try:
(sid, challenge) = self._login_request()
if sid == '0000000000000000':
secret = self._create_login_secret(challenge, self._password)
(sid2, challenge) = self._login_request(username=self._user,
secret=secret)
if sid2 == '0000000000000000':
_LOGGER.warning("login failed %s", sid2)
raise LoginError(self._user)
self._sid = sid2
except xml.parsers.expat.ExpatError:
raise LoginError(self._user) | Login and get a valid session ID. |
def colour_for_wp(self, wp_num):
wp = self.module('wp').wploader.wp(wp_num)
command = wp.command
return self._colour_for_wp_command.get(command, (0,255,0)) | return a tuple describing the colour a waypoint should appear on the map |
def _check_requirements(self):
path = self._vpcs_path()
if not path:
raise VPCSError("No path to a VPCS executable has been set")
self.ubridge_path
if not os.path.isfile(path):
raise VPCSError("VPCS program '{}' is not accessible".format(path))
if not os.access(path, os.X_OK):
raise VPCSError("VPCS program '{}' is not executable".format(path))
yield from self._check_vpcs_version() | Check if VPCS is available with the correct version. |
def insert(self):
ret = True
schema = self.schema
fields = self.depopulate(False)
q = self.query
q.set_fields(fields)
pk = q.insert()
if pk:
fields = q.fields
fields[schema.pk.name] = pk
self._populate(fields)
else:
ret = False
return ret | persist the field values of this orm |
def insertLine(self, i) :
self.data.insert(i, CSVEntry(self))
return self.lines[i] | Inserts an empty line at position i and returns it |
def _get_sv_callers(items):
callers = []
for data in items:
for sv in data.get("sv", []):
callers.append(sv["variantcaller"])
return list(set([x for x in callers if x != "sv-ensemble"])).sort() | return a sorted list of all of the structural variant callers run |
def siget(fullname=""):
fullname = str(fullname)
if not len(fullname):
return None
return sidict.GetObject(fullname, False) | Returns a softimage object given its fullname. |
def _create_empty_run(
self, status=RunStatus.FINISHED, status_description=None
) -> Run:
run = Run(
job_id=self.summary["job_id"],
issue_instances=[],
date=datetime.datetime.now(),
status=status,
status_description=status_description,
repository=self.summary["repository"],
branch=self.summary["branch"],
commit_hash=self.summary["commit_hash"],
kind=self.summary["run_kind"],
)
return run | setting boilerplate when creating a Run object |
def _create_lock_object(self, key):
return redis_lock.Lock(self.redis_conn, key,
expire=self.settings['REDIS_LOCK_EXPIRATION'],
auto_renewal=True) | Returns a lock object, split for testing |
def _get_pltdag_ancesters(self, hdrgo, usrgos, desc=""):
go_srcs = usrgos.union([hdrgo])
gosubdag = GoSubDag(go_srcs,
self.gosubdag.get_go2obj(go_srcs),
relationships=self.gosubdag.relationships,
rcntobj=self.gosubdag.rcntobj,
go2nt=self.gosubdag.go2nt)
tot_usrgos = len(set(gosubdag.go2obj.keys()).intersection(self.usrgos))
return self.ntpltgo(
hdrgo=hdrgo,
gosubdag=gosubdag,
tot_usrgos=tot_usrgos,
parentcnt=False,
desc=desc) | Get GoSubDag containing hdrgo and all usrgos and their ancesters. |
def python_console(namespace=None):
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who start this console.")
caller = frame
namespace = dict(caller.f_globals)
namespace.update(caller.f_locals)
return get_python_console(namespace=namespace).interact() | Start a interactive python console with caller's stack |
def tmp(p_queue, host=None):
if host is not None:
return _path(_c.FSQ_TMP, root=_path(host, root=hosts(p_queue)))
return _path(p_queue, _c.FSQ_TMP) | Construct a path to the tmp dir for a queue |
def write_volume(self):
data = datatools.get_data()
data["discord"]["servers"][self.server_id][_data.modulename]["volume"] = self.volume
datatools.write_data(data) | Writes the current volume to the data.json |
def create_question(self, question, type=None, **kwargs):
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs) | Returns a Question of specified type. |
def upload_buffer(self, target_id, page, address, buff):
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page, address)
for i in range(0, len(buff)):
pk.data.append(buff[i])
count += 1
if count > 24:
self.link.send_packet(pk)
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page,
i + address + 1)
self.link.send_packet(pk) | Upload data into a buffer on the Crazyflie |
def check_counts(self):
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x | Disables tweet parsing if the count API is used. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.