code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def meson_setup():
meson_exe = shutil.which('meson')
ninja_exe = shutil.which('ninja')
if not meson_exe or not ninja_exe:
raise FileNotFoundError('Meson or Ninja not available')
if not (BINDIR / 'build.ninja').is_file():
subprocess.check_call([meson_exe, str(SRCDIR)], cwd=BINDIR)
ret = subprocess.run(ninja_exe, cwd=BINDIR, stderr=subprocess.PIPE,
universal_newlines=True)
result(ret) | attempt to build with Meson + Ninja |
def _write_log(self, log_type, log_time, message):
timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S")
log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message)
if self._logger and callable(getattr(self._logger, self._logger_methods[log_type], None)):
getattr(
self._logger,
self._logger_methods[log_type],
None
)(message if self._logger_no_prefix else log_entry)
elif self._log_file:
with open(self._log_file, 'a') as logfile:
try:
logfile.write(unicode(log_entry + "\n"))
except NameError:
logfile.write(log_entry + "\n")
else:
print(log_entry) | Private method to abstract log writing for different types of logs |
async def close(self):
if self.__isClosed:
return
self.__isClosed = True
self.__setSignalingState('closed')
for transceiver in self.__transceivers:
await transceiver.stop()
if self.__sctp:
await self.__sctp.stop()
for transceiver in self.__transceivers:
await transceiver._transport.stop()
await transceiver._transport.transport.stop()
if self.__sctp:
await self.__sctp.transport.stop()
await self.__sctp.transport.transport.stop()
self.__updateIceConnectionState()
self.remove_all_listeners() | Terminate the ICE agent, ending ICE processing and streams. |
def mpub(self, topic, *messages):
return self.send(constants.MPUB + ' ' + topic, messages) | Publish multiple messages to a topic |
def generate_file(fname, ns_func, dest_dir="."):
with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f:
tpl = f.read()
out = tpl.format(**ns_func())
dest = pjoin(dest_dir, fname)
info("generating %s from template" % dest)
with open(dest, 'w') as f:
f.write(out) | generate a constants file from its template |
def full_name(self):
formatted_user = []
if self.user.first_name is not None:
formatted_user.append(self.user.first_name)
if self.user.last_name is not None:
formatted_user.append(self.user.last_name)
return " ".join(formatted_user) | Returns the first and last name of the user separated by a space. |
def SetValue(self, row, col, value):
self.dataframe.iloc[row, col] = value | Set value in the pandas DataFrame |
def _add_type_node(self, node, label):
child = node.add_child(name=label)
child.add_feature(TYPE_NODE_TAG, True)
return child | Add a node representing a SubjectInfo type. |
def add_user(self, name, password=None, read_only=None, db=None, **kwargs):
if db is None:
return self.get_connection().admin.add_user(
name, password=password, read_only=read_only, **kwargs)
return self.get_connection()[db].add_user(
name, password=password, read_only=read_only, **kwargs) | Adds a user that can be used for authentication |
def find_loops( record, index, stop_types = STOP_TYPES, open=None, seen = None ):
if open is None:
open = []
if seen is None:
seen = set()
for child in children( record, index, stop_types = stop_types ):
if child['type'] in stop_types or child['type'] == LOOP_TYPE:
continue
if child['address'] in open:
start = open.index( child['address'] )
new = frozenset( open[start:] )
if new not in seen:
seen.add(new)
yield new
elif child['address'] in seen:
continue
else:
seen.add( child['address'])
open.append( child['address'] )
for loop in find_loops( child, index, stop_types=stop_types, open=open, seen=seen ):
yield loop
open.pop( -1 ) | Find all loops within the index and replace with loop records |
def run(port, like, use_json, server):
if not port and not server[0]:
raise click.UsageError("Please specify a port")
if server[0]:
app.run(host=server[0], port=server[1])
return
ports = get_ports(port, like)
if not ports:
sys.stderr.write("No ports found for '{0}'\n".format(port))
return
if use_json:
print(json.dumps(ports, indent=4))
else:
table = get_table(ports)
print(table) | Search port names and numbers. |
def listen(self):
while self._listen:
key = u''
key = self.term.inkey(timeout=0.2)
try:
if key.code == KEY_ENTER:
self.on_enter(key=key)
elif key.code in (KEY_DOWN, KEY_UP):
self.on_key_arrow(key=key)
elif key.code == KEY_ESCAPE or key == chr(3):
self.on_exit(key=key)
elif key != '':
self.on_key(key=key)
except KeyboardInterrupt:
self.on_exit(key=key) | Blocking call on widgets. |
def _stmt_from_rule(model, rule_name, stmts):
stmt_uuid = None
for ann in model.annotations:
if ann.predicate == 'from_indra_statement':
if ann.subject == rule_name:
stmt_uuid = ann.object
break
if stmt_uuid:
for stmt in stmts:
if stmt.uuid == stmt_uuid:
return stmt | Return the INDRA Statement corresponding to a given rule by name. |
def change_dir(directory):
def cd_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
org_path = os.getcwd()
os.chdir(directory)
func(*args, **kwargs)
os.chdir(org_path)
return wrapper
return cd_decorator | Wraps a function to run in a given directory. |
def change_authentication(self, client_id=None, client_secret=None,
access_token=None, refresh_token=None):
self.client_id = client_id or self.client_id
self.client_secret = client_secret or self.client_secret
self.access_token = access_token or self.access_token
self.refresh_token = refresh_token or self.refresh_token | Change the current authentication. |
def trigger_frontend_build(self, event):
from hfos.database import instance
install_frontend(instance=instance,
forcerebuild=event.force,
install=event.install,
development=self.development
) | Event hook to trigger a new frontend build |
def toc_print(self):
res = self.toc()
for n, k, v in res:
logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v)) | End collecting and print results. |
def name(self):
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | Returns the human-readable name of the place. |
def disconnect(self):
all_conns = chain(
self._available_connections.values(),
self._in_use_connections.values(),
)
for node_connections in all_conns:
for connection in node_connections:
connection.disconnect() | Nothing that requires any overwrite. |
def to_list(self):
ret = OrderedDict()
for attrname in self.attrs:
ret[attrname] = self.__getattribute__(attrname)
return ret | Returns list containing values of attributes listed in self.attrs |
def results(self, request):
"Match results to given term and return the serialized HttpResponse."
results = {}
form = self.form(request.GET)
if form.is_valid():
options = form.cleaned_data
term = options.get('term', '')
raw_data = self.get_query(request, term)
results = self.format_results(raw_data, options)
return self.response(results) | Match results to given term and return the serialized HttpResponse. |
def _GeneratorFromPath(path):
if not path:
raise ValueError('path must be a valid string')
if io_wrapper.IsTensorFlowEventsFile(path):
return event_file_loader.EventFileLoader(path)
else:
return directory_watcher.DirectoryWatcher(
path,
event_file_loader.EventFileLoader,
io_wrapper.IsTensorFlowEventsFile) | Create an event generator for file or directory at given path string. |
def eject(self, auth_no_user_interaction=None):
return self._assocdrive._M.Drive.Eject(
'(a{sv})',
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | Eject media from the device. |
def shell_context_processor(self, fn):
self._defer(lambda app: app.shell_context_processor(fn))
return fn | Registers a shell context processor function. |
def api_call(endpoint, args, payload):
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
resp = requests.post(
url, data=json.dumps(payload), headers=headers,
verify=args['--cacert']
)
resp.raise_for_status()
break
except (socket_timeout, requests.Timeout,
requests.ConnectionError, requests.URLRequired) as ex:
abort('{}'.format(ex))
except requests.HTTPError as ex:
warn('Requests HTTP error: {}'.format(ex))
if attempt >= 5:
abort('Too many HTTP errors.')
if resp is not None:
try:
return resp.json()
except ValueError:
abort('Unexpected response from server:\n\n{}'.format(resp.text))
else:
abort("Couldn't POST to Red October") | Generic function to call the RO API |
def contains_all(self, other):
dtype = getattr(other, 'dtype', None)
if dtype is None:
dtype = np.result_type(*other)
dtype_str = np.dtype('S{}'.format(self.length))
dtype_uni = np.dtype('<U{}'.format(self.length))
return dtype in (dtype_str, dtype_uni) | Return ``True`` if all strings in ``other`` have size `length`. |
def dump(self):
self.print("Dumping data to {}".format(self.dump_filename))
pickle.dump({
'data': self.counts,
'livetime': self.get_livetime()
}, open(self.dump_filename, "wb")) | Write coincidence counts into a Python pickle |
def _get_dest_file_and_url(self, filepath, page_meta={}):
filename = filepath.split("/")[-1]
filepath_base = filepath.replace(filename, "").rstrip("/")
slug = page_meta.get("slug")
fname = slugify(slug) if slug else filename \
.replace(".html", "") \
.replace(".md", "") \
.replace(".jade", "")
if page_meta.get("pretty_url") is False:
dest_file = os.path.join(filepath_base, "%s.html" % fname)
else:
dest_dir = filepath_base
if filename not in ["index.html", "index.md", "index.jade"]:
dest_dir = os.path.join(filepath_base, fname)
dest_file = os.path.join(dest_dir, "index.html")
url = "/" + dest_file.replace("index.html", "")
return dest_file, url | Return tuple of the file destination and url |
def team(self):
team_dict = self._json_data.get('team')
if team_dict and team_dict.get('id'):
return self._client.team(id=team_dict.get('id'))
else:
return None | Team to which the scope is assigned. |
def convert_row_to_sdpa_index(block_struct, row_offsets, row):
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i, j | Helper function to map to sparse SDPA index values. |
def consume_keys_asynchronous_threads(self):
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool = ThreadPool(jobs)
for x in range(jobs):
pool.apply(self.data_worker, [], self.worker_args)
pool.close()
pool.join() | Work through the keys to look up asynchronously using multiple threads |
def decrypt(crypt_text) -> str:
cipher = Fernet(current_app.config['KEY'])
if not isinstance(crypt_text, bytes):
crypt_text = str.encode(crypt_text)
return cipher.decrypt(crypt_text).decode("utf-8") | Use config.json key to decrypt |
def extend_schema_spec(self) -> None:
super().extend_schema_spec()
identity_field = {
'Name': '_identity',
'Type': BtsType.STRING,
'Value': 'identity',
ATTRIBUTE_INTERNAL: True
}
if self.ATTRIBUTE_FIELDS in self._spec:
self._spec[self.ATTRIBUTE_FIELDS].insert(0, identity_field)
self.schema_loader.add_schema_spec(identity_field, self.fully_qualified_name) | Injects the identity field |
def say_tmp_filepath(
text = None,
preference_program = "festival"
):
filepath = shijian.tmp_filepath() + ".wav"
say(
text = text,
preference_program = preference_program,
filepath = filepath
)
return filepath | Say specified text to a temporary file and return the filepath. |
def _submit_results(self):
if self._cur_res_id and self._cur_values:
self._addRawResult(self._cur_res_id, self._cur_values)
self._reset() | Adding current values as a Raw Result and Resetting everything. |
def gen_slot_variables(self, cls: ClassDefinition) -> str:
return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] +
[self.gen_slot_variable(cls, slot)
for slot in cls.slots
if not self.schema.slots[slot].primary_key and not self.schema.slots[slot].identifier]) | Generate python definition for class cls, generating primary keys first followed by the rest of the slots |
def make_request_fn():
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_version)
else:
request_fn = serving_utils.make_grpc_request_fn(
servable_name=FLAGS.servable_name,
server=FLAGS.server,
timeout_secs=FLAGS.timeout_secs)
return request_fn | Returns a request function. |
def update_from_json(self, json_device):
self.identifier = json_device['Id']
self.license_plate = json_device['EquipmentHeader']['SerialNumber']
self.make = json_device['EquipmentHeader']['Make']
self.model = json_device['EquipmentHeader']['Model']
self.equipment_id = json_device['EquipmentHeader']['EquipmentID']
self.active = json_device['EngineRunning']
self.odo = json_device['Odometer']
self.latitude = json_device['Location']['Latitude']
self.longitude = json_device['Location']['Longitude']
self.altitude = json_device['Location']['Altitude']
self.speed = json_device['Speed']
self.last_seen = json_device['Location']['DateTime'] | Set all attributes based on API response. |
def read_http_header(sock):
buf = []
hdr_end = '\r\n\r\n'
while True:
buf.append(sock.recv(bufsize).decode('utf-8'))
data = ''.join(buf)
i = data.find(hdr_end)
if i == -1:
continue
return data[:i], data[i + len(hdr_end):] | Read HTTP header from socket, return header and rest of data. |
def _mix(color1, color2, weight=0.5, **kwargs):
weight = float(weight)
c1 = color1.value
c2 = color2.value
p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight
w = p * 2 - 1
a = c1[3] - c2[3]
w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0
w2 = 1 - w1
q = [w1, w1, w1, p]
r = [w2, w2, w2, 1 - p]
return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)]) | Mixes two colors together. |
def create_group(cls, prefix: str, name: str) -> ErrorGroup:
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group | Create a new error group and return it. |
def select(yerrs, amps, amp_errs, widths):
keep_1 = np.logical_and(amps < 0, widths > 1)
keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
keep = np.logical_and(keep_1, keep_2)
return keep | criteria for keeping an object |
def radio_buttons_clicked(self):
for spin_box in list(self.spin_boxes.values()):
spin_box.setEnabled(False)
self.list_widget.setEnabled(False)
radio_button_checked_id = self.input_button_group.checkedId()
if radio_button_checked_id > -1:
selected_value = list(self._parameter.options.values())[
radio_button_checked_id]
if selected_value.get('type') == MULTIPLE_DYNAMIC:
self.list_widget.setEnabled(True)
elif selected_value.get('type') == SINGLE_DYNAMIC:
selected_key = list(self._parameter.options.keys())[
radio_button_checked_id]
self.spin_boxes[selected_key].setEnabled(True) | Handler when selected radio button changed. |
def do_opt(self, *args, **kwargs):
args = list(args)
if not args:
largest = 0
keys = [key for key in self.conf if not key.startswith("_")]
for key in keys:
largest = max(largest, len(key))
for key in keys:
print("%s : %s" % (key.rjust(largest), self.conf[key]))
return
option = args.pop(0)
if not args and not kwargs:
method = getattr(self, "getopt_" + option, None)
if method is None:
self.getopt_default(option)
else:
method()
else:
method = getattr(self, "opt_" + option, None)
if method is None:
print("Unrecognized option %r" % option)
else:
method(*args, **kwargs)
self.save_config() | Get and set options |
def process_user_input(self):
user_input = self.get_input()
try:
num = int(user_input)
except Exception:
return
if 0 < num < len(self.items) + 1:
self.current_option = num - 1
self.select()
return user_input | Gets the next single character and decides what to do with it |
def ready(self):
self.options = {}
self.options.update(DEFAULT_OPTIONS)
for template_engine in settings.TEMPLATES:
if template_engine.get('BACKEND', '').startswith('django_mako_plus'):
self.options.update(template_engine.get('OPTIONS', {}))
self.registration_lock = threading.RLock()
self.registered_apps = {}
self.engine = engines['django_mako_plus']
self.template_imports = [
'import django_mako_plus',
'import django.utils.html',
]
self.template_imports.extend(self.options['DEFAULT_TEMPLATE_IMPORTS'])
ProviderRun.initialize_providers()
from .converter.base import ParameterConverter
ParameterConverter._sort_converters(app_ready=True) | Called by Django when the app is ready for use. |
def deferToGreenlet(*args, **kwargs):
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
return deferToGreenletPool(reactor, reactor.getGreenletPool(), *args, **kwargs) | Call function using a greenlet and return the result as a Deferred |
def convert_to_bytes(mem_str):
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1024))
else:
return int(round(float(mem_str))) | Convert a memory specification, potentially with M or G, into bytes. |
def input_flush():
try:
import sys, termios
termios.tcflush(sys.stdin, termios.TCIFLUSH)
except ImportError:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch() | Flush the input buffer on posix and windows. |
def fix_text_escapes(self, txt: str, quote_char: str) -> str:
def _subf(matchobj):
return matchobj.group(0).translate(self.re_trans_table)
if quote_char:
txt = re.sub(r'\\'+quote_char, quote_char, txt)
return re.sub(r'\\.', _subf, txt, flags=re.MULTILINE + re.DOTALL + re.UNICODE) | Fix the various text escapes |
def _blend_layers(self, imagecontent, z_x_y):
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
for (layer, opacity) in self._layers:
try:
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
logger.warn(e)
continue
overlay = overlay.convert("RGBA")
r, g, b, a = overlay.split()
overlay = Image.merge("RGB", (r, g, b))
a = ImageEnhance.Brightness(a).enhance(opacity)
overlay.putalpha(a)
mask = Image.merge("L", (a,))
result.paste(overlay, (0, 0), mask)
return self._image_tile(result) | Merge tiles of all layers into the specified tile path |
def update_target(self, name, current, total):
self.refresh(self._bar(name, current, total)) | Updates progress bar for a specified target. |
def _block_shape(values, ndim=1, shape=None):
if values.ndim < ndim:
if shape is None:
shape = values.shape
if not is_extension_array_dtype(values):
values = values.reshape(tuple((1, ) + shape))
return values | guarantee the shape of the values to be at least 1 d |
def _inner(self, x1, x2):
return self.tspace._inner(x1.tensor, x2.tensor) | Raw inner product of two elements. |
def remove(self, item):
self.items.pop(item)
self._remove_dep(item)
self.order = None
self.changed(code_changed=True) | Remove an item from the list. |
def logv(msg, *args, **kwargs):
if settings.VERBOSE:
log(msg, *args, **kwargs) | Print out a log message, only if verbose mode. |
def _update_display(self, event=None):
try:
if self._showvalue:
self.display_value(self.scale.get())
if self._tickinterval:
self.place_ticks()
except IndexError:
pass | Redisplay the ticks and the label so that they adapt to the new size of the scale. |
def char_conv(out):
out_conv = list()
for i in range(out.shape[0]):
tmp_str = ''
for j in range(out.shape[1]):
if int(out[i][j]) >= 0:
tmp_char = int2char(int(out[i][j]))
if int(out[i][j]) == 27:
tmp_char = ''
tmp_str = tmp_str + tmp_char
out_conv.append(tmp_str)
return out_conv | Convert integer vectors to character vectors for batch. |
def report(self):
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in self.socket_warnings.values()
)
def format_test_statistics(test, counter):
return "%s:\n%s" % (
test,
'\n'.join(
' - %s: %s' % (socket, count)
for socket, count in counter.items()
)
)
def format_statistics(aggregations):
return '\n'.join(
format_test_statistics(test, counter)
for test, counter in aggregations.items()
)
if aggregations:
print('=' * 70, file=self.stream)
print(
'NON-WHITELISTED SOCKETS OPENED: %s' % total,
file=self.stream,
)
print('-' * 70, file=self.stream)
print(format_statistics(aggregations), file=self.stream) | Performs rollups, prints report of sockets opened. |
def _construct_url(self, endpoint):
parsed_url = urlparse(self.host)
scheme = parsed_url[0]
host = parsed_url[1]
if scheme == "":
scheme = "http"
host = self.host
if not endpoint.startswith("/"):
endpoint = "/" + endpoint
if self.config["api_version"] is not None:
endpoint = "/v%d%s" % (self.config["api_version"], endpoint)
return urlunparse((scheme, host, endpoint, '', '', '')) | Return the full URL to the specified endpoint |
def enc_name_descr(name, descr, color=a99.COLOR_DESCR):
return enc_name(name, color)+"<br>"+descr | Encodes html given name and description. |
def host_info(host=None):
data = query(host, quiet=True)
for id_ in data:
if 'vm_info' in data[id_]:
data[id_].pop('vm_info')
__jid_event__.fire_event({'data': data, 'outputter': 'nested'}, 'progress')
return data | Return information about the host connected to this master |
def make_request(parameters):
r = requests.get(bcdata.WFS_URL, params=parameters)
return r.json()["features"] | Submit a getfeature request to DataBC WFS and return features |
def reset(self):
self.filename = None
self.dataset = None
self.idx_filename.setText('Open Recordings...')
self.idx_s_freq.setText('')
self.idx_n_chan.setText('')
self.idx_start_time.setText('')
self.idx_end_time.setText('')
self.idx_scaling.setText('')
self.idx_distance.setText('')
self.idx_length.setText('')
self.idx_start.setText('') | Reset widget to original state. |
def max_spline_jump(self):
sp = self.spline()
return max(self.energies - sp(range(len(self.energies)))) | Get maximum difference between spline and energy trend. |
def insert_statement(table, columns, values):
if not all(isinstance(r, (list, set, tuple)) for r in values):
values = [[r] for r in values]
rows = []
for row in values:
new_row = []
for col in row:
if col is None:
new_col = 'NULL'
elif isinstance(col, (int, float, Decimal)):
new_col = str(MySQLConverterBase().to_mysql(col))
else:
string = str(MySQLConverterBase().to_mysql(col))
if "'" in string:
new_col = '"' + string + '"'
else:
new_col = "'" + string + "'"
new_row.append(new_col)
rows.append(', '.join(new_row))
vals = '(' + '),\n\t('.join(rows) + ')'
statement = "INSERT INTO\n\t{0} ({1}) \nVALUES\n\t{2}".format(wrap(table), cols_str(columns), vals)
return statement | Generate an insert statement string for dumping to text file or MySQL execution. |
def changes(self):
deprecation_msg = 'Model.changes will be removed in warlock v2'
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
return copy.deepcopy(self.__dict__['changes']) | Dumber version of 'patch' method |
def nameValue(name, value, valueType=str, quotes=False):
if valueType == bool:
if value:
return "--%s" % name
return ""
if value is None:
return ""
if quotes:
return "--%s '%s'" % (name, valueType(value))
return "--%s %s" % (name, valueType(value)) | Little function to make it easier to make name value strings for commands. |
def dehydrate(self):
result = dict(limit_class=self._limit_full_name)
for attr in self.attrs:
result[attr] = getattr(self, attr)
return result | Return a dict representing this limit. |
def profile(self):
leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0)
return (np.arange(self.num_vertices()) - leftmost_idx).sum() | Measure of bandedness, also known as 'envelope size'. |
def draw_header(self, stream, header):
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | Draw header with underline |
def _organize_tools_on(data, is_cwl):
if is_cwl:
if tz.get_in(["algorithm", "jointcaller"], data):
val = tz.get_in(["algorithm", "tools_on"], data)
if not val:
val = []
if not isinstance(val, (list, tuple)):
val = [val]
if "gvcf" not in val:
val.append("gvcf")
data["algorithm"]["tools_on"] = val
return data | Ensure tools_on inputs match items specified elsewhere. |
def distance2_to(self, other: "Point2"):
assert isinstance(other, Point2)
return (self[0] - other[0]) ** 2 + (self[1] - other[1]) ** 2 | Squared distance to a point. |
def stop(self):
self._running = False
if self._self_thread is not None:
self._self_thread.cancel()
self._self_thread = None | Stop running scheduled function. |
def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True):
humanized = '{} {}'.format(
numberformat.format(
number=number,
decimal_sep=',',
decimal_pos=2 if show_decimal_place else 0,
grouping=3,
thousand_sep=' ',
force_grouping=True
),
force_text(currency)
)
return mark_safe(humanized.replace(' ', '\u00a0')) if use_nbsp else humanized | Return a given `number` formatter a price for humans. |
def detect_encoding(sample, encoding=None):
from cchardet import detect
if encoding is not None:
return normalize_encoding(sample, encoding)
result = detect(sample)
confidence = result['confidence'] or 0
encoding = result['encoding'] or 'ascii'
encoding = normalize_encoding(sample, encoding)
if confidence < config.ENCODING_CONFIDENCE:
encoding = config.DEFAULT_ENCODING
if encoding == 'ascii':
encoding = config.DEFAULT_ENCODING
return encoding | Detect encoding of a byte string sample. |
def async_get_ac_state_log(self, uid, log_id, fields='*'):
return (
yield from self._get('/pods/{}/acStates/{}'.format(uid, log_id),
fields=fields)) | Get a specific log entry. |
def _parse_vmconfig(config, instances):
vmconfig = None
if isinstance(config, (salt.utils.odict.OrderedDict)):
vmconfig = salt.utils.odict.OrderedDict()
for prop in config:
if prop not in instances:
vmconfig[prop] = config[prop]
else:
if not isinstance(config[prop], (salt.utils.odict.OrderedDict)):
continue
vmconfig[prop] = []
for instance in config[prop]:
instance_config = config[prop][instance]
instance_config[instances[prop]] = instance
if 'mac' in instance_config:
instance_config['mac'] = instance_config['mac'].lower()
vmconfig[prop].append(instance_config)
else:
log.error('smartos.vm_present::parse_vmconfig - failed to parse')
return vmconfig | Parse vm_present vm config |
def dshield_ip_check(ip):
if not is_IPv4Address(ip):
return None
headers = {'User-Agent': useragent}
url = 'https://isc.sans.edu/api/ip/'
response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
return response.json() | Checks dshield for info on an IP address |
def place_data_on_block_device(blk_device, data_src_dst):
mount(blk_device, '/mnt')
copy_files(data_src_dst, '/mnt')
umount('/mnt')
_dir = os.stat(data_src_dst)
uid = _dir.st_uid
gid = _dir.st_gid
mount(blk_device, data_src_dst, persist=True)
os.chown(data_src_dst, uid, gid) | Migrate data in data_src_dst to blk_device and then remount. |
def enable_aliases_autocomplete_interactive(_, **kwargs):
subtree = kwargs.get('subtree', None)
if not subtree or not hasattr(subtree, 'children'):
return
for alias, alias_command in filter_aliases(get_alias_table()):
if subtree.in_tree(alias_command.split()):
subtree.add_child(CommandBranch(alias)) | Enable aliases autocomplete on interactive mode by injecting aliases in the command tree. |
def do_it(self, dbg):
try:
frame = dbg.find_frame(self.thread_id, self.frame_id)
completions_xml = pydevd_console.get_completions(frame, self.act_tok)
cmd = dbg.cmd_factory.make_send_console_message(self.sequence, completions_xml)
dbg.writer.add_command(cmd)
except:
exc = get_exception_traceback_str()
cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error in fetching completions" + exc)
dbg.writer.add_command(cmd) | Get completions and write back to the client |
def backend_calibration(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsError('credentials invalid')
backend_type = self._check_backend(backend, 'calibration')
if not backend_type:
raise BadBackendError(backend)
if backend_type in self.__names_backend_simulator:
ret = {}
return ret
url = get_backend_stats_url(self.config, hub, backend_type)
ret = self.req.get(url + '/calibration')
if not bool(ret):
ret = {}
else:
ret["backend"] = backend_type
return ret | Get the calibration of a real chip |
def get(self, aspect):
classification = [(network, self.networks), (system, self.systems),
(configure, self.configures)]
aspect_list = [l for t, l in classification if isinstance(aspect, t)]
assert len(aspect_list) == 1, "Unexpected aspect for RADL."
aspect_list = aspect_list[0]
old_aspect = [a for a in aspect_list if a.getId() == aspect.getId()]
return old_aspect[0] if old_aspect else None | Get a network, system or configure or contextualize with the same id as aspect passed. |
def on_feed_key(self, key_press):
if key_press.key in {Keys.Escape, Keys.ControlC}:
echo(carriage_return=True)
raise Abort()
if key_press.key == Keys.Backspace:
if self.current_command_pos > 0:
self.current_command_pos -= 1
return key_press
ret = None
if key_press.key != Keys.CPRResponse:
if self.current_command_pos < len(self.current_command):
current_key = self.current_command_key
ret = KeyPress(current_key)
increment = min(
[self.speed, len(self.current_command) - self.current_command_pos]
)
self.current_command_pos += increment
else:
if key_press.key != Keys.Enter:
return None
self.current_command_index += 1
self.current_command_pos = 0
ret = key_press
return ret | Handles the magictyping when a key is pressed |
def IsImage(self, filename):
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/") | Returns true if the filename has an image extension. |
def include(self, path):
for extension in IGNORE_EXTENSIONS:
if path.endswith(extension):
return False
parts = path.split(os.path.sep)
for part in parts:
if part in self.ignore_dirs:
return False
return True | Returns `True` if the file is not ignored |
def _condition_as_sql(self, qn, connection):
def escape(value):
if isinstance(value, bool):
value = str(int(value))
if isinstance(value, six.string_types):
if '%' in value:
value = value.replace('%', '%%')
if "'" in value:
value = value.replace("'", "''")
value = "'" + value + "'"
return value
sql, param = self.condition.query.where.as_sql(qn, connection)
param = map(escape, param)
return sql % tuple(param) | Return sql for condition. |
def pivot(self):
self.op_data = [list(i) for i in zip(*self.ip_data)] | transposes rows and columns |
def foreign(self, value, context=None):
if self.none and value is None:
return ''
try:
value = self.native(value, context)
except Concern:
value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value)
if value in self.truthy or value:
return self.truthy[self.use]
return self.falsy[self.use] | Convert a native value to a textual boolean. |
def json_formatter(subtitles):
subtitle_dicts = [
{
'start': start,
'end': end,
'content': text,
}
for ((start, end), text)
in subtitles
]
return json.dumps(subtitle_dicts) | Serialize a list of subtitles as a JSON blob. |
def create(cls, path, encoding='utf-8'):
cmd = [GIT, 'init', '--quiet', '--bare', path]
subprocess.check_call(cmd)
return cls(path, encoding) | Create a new bare repository |
def setup_mimetypes(self):
mimetypes.add_type('text/xml', '.ui')
mimetypes.add_type('text/x-rst', '.rst')
mimetypes.add_type('text/x-cython', '.pyx')
mimetypes.add_type('text/x-cython', '.pxd')
mimetypes.add_type('text/x-python', '.py')
mimetypes.add_type('text/x-python', '.pyw')
mimetypes.add_type('text/x-c', '.c')
mimetypes.add_type('text/x-c', '.h')
mimetypes.add_type('text/x-c++hdr', '.hpp')
mimetypes.add_type('text/x-c++src', '.cpp')
mimetypes.add_type('text/x-c++src', '.cxx')
for ext in ['.cbl', '.cob', '.cpy']:
mimetypes.add_type('text/x-cobol', ext)
mimetypes.add_type('text/x-cobol', ext.upper()) | Setup additional mime types. |
def create_widget(self):
widget = QDoubleSpinBox(self.parent_widget())
widget.setKeyboardTracking(False)
self.widget = widget | Create the underlying QDoubleSpinBox widget. |
def send_error_json(self, code, message, headers=None):
"send an error to the client. text message is formatted in a json stream"
if headers is None:
headers = {}
self.end_response(HttpResponseJson(code,
{'code': code,
'message': message},
headers)) | send an error to the client. text message is formatted in a json stream |
def add_cmd_handler(self, cmd, func):
len_args = len(inspect.getargspec(func)[0])
def add_meta(f):
def decorator(*args, **kwargs):
f(*args, **kwargs)
decorator.bytes_needed = len_args - 1
decorator.__name__ = f.__name__
return decorator
func = add_meta(func)
self._command_handlers[cmd] = func | Adds a command handler for a command. |
def _extract(self, raw: str, station: str) -> str:
report = raw[raw.find(station.upper() + ' '):]
report = report[:report.find(' =')]
return report | Extracts the reports message using string finding |
def class_name(obj):
name = obj.__name__
module = getattr(obj, '__module__')
if module:
name = f'{module}.{name}'
return name | Get the name of an object, including the module name if available. |
def _structure_frozenset(self, obj, cl):
if is_bare(cl) or cl.__args__[0] is Any:
return frozenset(obj)
else:
elem_type = cl.__args__[0]
dispatch = self._structure_func.dispatch
return frozenset(dispatch(elem_type)(e, elem_type) for e in obj) | Convert an iterable into a potentially generic frozenset. |
def determine_hostname(display_name=None):
if display_name:
return display_name
else:
socket_gethostname = socket.gethostname()
socket_fqdn = socket.getfqdn()
try:
socket_ex = socket.gethostbyname_ex(socket_gethostname)[0]
except (LookupError, socket.gaierror):
socket_ex = ''
gethostname_len = len(socket_gethostname)
fqdn_len = len(socket_fqdn)
ex_len = len(socket_ex)
if fqdn_len > gethostname_len or ex_len > gethostname_len:
if "localhost" not in socket_ex and len(socket_ex):
return socket_ex
if "localhost" not in socket_fqdn:
return socket_fqdn
return socket_gethostname | Find fqdn if we can |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.