code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def defan(self, pattern):
self.checkpat(pattern)
self.A_a_user_defined.extend((pattern, "an"))
return 1 | Define the indefinate article as 'an' for words matching pattern. |
def behavior_script(url, template_parameters=None, behaviors_dir=None):
import re, logging, json
for behavior in behaviors(behaviors_dir=behaviors_dir):
if re.match(behavior['url_regex'], url):
parameters = dict()
if 'default_parameters' in behavior:
parameters.up... | Returns the javascript behavior string populated with template_parameters. |
def _validate_tag_sets(tag_sets):
if tag_sets is None:
return tag_sets
if not isinstance(tag_sets, list):
raise TypeError((
"Tag sets %r invalid, must be a list") % (tag_sets,))
if len(tag_sets) == 0:
raise ValueError((
"Tag sets %r invalid, must be None or co... | Validate tag sets for a MongoReplicaSetClient. |
def docker_context():
try:
client = docker.from_env(
version = "auto"
, timeout = int(os.environ.get("DOCKER_CLIENT_TIMEOUT", 180))
, assert_hostname = False
)
info = client.info()
log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", ... | Make a docker context |
def _output_tags(self):
for class_name, properties in sorted(self.resources.items()):
for key, value in sorted(properties.items()):
validator = self.override.get_validator(class_name, key)
if key == 'Tags' and validator is None:
print("from troposp... | Look for a Tags object to output a Tags import |
def logger(self, iteration, ret):
print("Learning rate: {:f}".format(self.lr_scheduler.get_lr()[0]))
entropies = getEntropies(self.model)
print("Entropy and max entropy: ", float(entropies[0]), entropies[1])
print("Training time for epoch=", self.epoch_train_time)
for noise in self.noise_values:
... | Print out relevant information at each epoch |
def _get_coarse_dataset(self, key, info):
angles = self.root.find('.//Tile_Angles')
if key in ['solar_zenith_angle', 'solar_azimuth_angle']:
elts = angles.findall(info['xml_tag'] + '/Values_List/VALUES')
return np.array([[val for val in elt.text.split()] for elt in elts],
... | Get the coarse dataset refered to by `key` from the XML data. |
def remote_interruptCommand(self, stepId, why):
log.msg("asked to interrupt current command: {0}".format(why))
self.activity()
if not self.command:
log.msg(" .. but none was running")
return
self.command.doInterrupt() | Halt the current step. |
def write_boundaries(self, filename):
fid = open(filename, 'w')
for i in self.Boundaries:
print(i)
fid.write(
'{0} {1} {2} {3} {4}\n'.format(
i[0][0], i[0][1], i[1][0], i[1][1], i[2]))
fid.close() | Write boundary lines X1 Y1 X2 Y2 TYPE to file |
def removeComments(element):
global _num_bytes_saved_in_comments
num = 0
if isinstance(element, xml.dom.minidom.Comment):
_num_bytes_saved_in_comments += len(element.data)
element.parentNode.removeChild(element)
num += 1
else:
for subelement in element.childNodes[:]:
... | Removes comments from the element and its children. |
def compute_default_choice(self):
choices = self.choices
if len(choices) == 0:
return None
high_choice = max(choices, key=lambda choice: choice.performance)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name)
self.refresh()
... | Computes and sets the default choice |
def make_node_dict(outer_list, sort="zone"):
raw_dict = {}
x = 1
for inner_list in outer_list:
for node in inner_list:
raw_dict[x] = node
x += 1
if sort == "name":
srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
(k[1].c... | Convert node data from nested-list to sorted dict. |
def dtraj_T100K_dt10_n(self, divides):
disc = np.zeros(100, dtype=int)
divides = np.concatenate([divides, [100]])
for i in range(len(divides)-1):
disc[divides[i]:divides[i+1]] = i+1
return disc[self.dtraj_T100K_dt10] | 100K frames trajectory at timestep 10, arbitrary n-state discretization. |
def drop_index(self, table, column):
self.execute('ALTER TABLE {0} DROP INDEX {1}'.format(wrap(table), column))
self._printer('\tDropped index from column {0}'.format(column)) | Drop an index from a table. |
def knn_impute_reference(
X,
missing_mask,
k,
verbose=False,
print_interval=100):
n_rows, n_cols = X.shape
X_result, D, effective_infinity = \
knn_initialize(X, missing_mask, verbose=verbose)
for i in range(n_rows):
for j in np.where(missing_mask[i, :]... | Reference implementation of kNN imputation logic. |
def make_prototype_request(*args, **kwargs):
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
if args[1:] or kwargs:
raise_args_er... | Make a prototype Request for a Matcher. |
def _delete_plot(cls, plot_id):
plot = cls._plots.get(plot_id)
if plot is None:
return
plot.cleanup()
del cls._plots[plot_id] | Deletes registered plots and calls Plot.cleanup |
def julian_day(t: date) -> int:
dt = t - julian_base_date
return julian_base_number + dt.days | Convert a Python datetime to a Julian day |
def Parse(self, stat, file_object, knowledge_base):
_, _ = stat, knowledge_base
users = {}
wtmp = file_object.read()
while wtmp:
try:
record = UtmpStruct(wtmp)
except utils.ParsingError:
break
wtmp = wtmp[record.size:]
if record.ut_type != 7:
continue
... | Parse the wtmp file. |
def _reconnect(self):
self.close()
self._db = psycopg2.connect(**self._db_args)
if self._search_path:
self.execute('set search_path=%s;' % self._search_path)
if self._timezone:
self.execute("set timezone='%s';" % self._timezone) | Closes the existing database connection and re-opens it. |
def bump_context(self, name):
data = self._context(name)
data["priority"] = self._next_priority
self._flush_tools() | Causes the context's tools to take priority over all others. |
def filter_by_rows(self, rows, ID=None):
rows = to_list(rows)
fil = lambda x: x in rows
applyto = {k: self._positions[k][0] for k in self.keys()}
if ID is None:
ID = self.ID
return self.filter(fil, applyto=applyto, ID=ID) | Keep only Measurements in corresponding rows. |
def minute_change(device):
hours = datetime.now().strftime('%H')
minutes = datetime.now().strftime('%M')
def helper(current_y):
with canvas(device) as draw:
text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT))
text(draw, (15, 1), ":", fill="white", font=prop... | When we reach a minute change, animate it. |
def returner(ret):
_options = _get_options(ret)
from_jid = _options.get('from_jid')
password = _options.get('password')
recipient_jid = _options.get('recipient_jid')
if not from_jid:
log.error('xmpp.jid not defined in salt config')
return
if not password:
log.error('xmpp.... | Send an xmpp message with the data |
def modify(self, view):
view.params['extra_context'][self.get['name']] = self.get['value']
return view | adds the get item as extra context |
def create_user(
self, username, email, short_name, full_name,
institute, password=None, **extra_fields):
return self._create_user(
username=username, email=email,
short_name=short_name, full_name=full_name,
institute=institute, password=password,
... | Creates a new ordinary person. |
def merge_rects(rect1, rect2):
r = pygame.Rect(rect1)
t = pygame.Rect(rect2)
right = max(r.right, t.right)
bot = max(r.bottom, t.bottom)
x = min(t.x, r.x)
y = min(t.y, r.y)
return pygame.Rect(x, y, right - x, bot - y) | Return the smallest rect containning two rects |
def create_columns(self):
reader = self._get_csv_reader()
headings = six.next(reader)
try:
examples = six.next(reader)
except StopIteration:
examples = []
found_fields = set()
for i, value in enumerate(headings):
if i >= 20:
... | For each column in file create a TransactionCsvImportColumn |
def triangle_area(p0, p1, p2):
if p2.ndim < 2:
p2 = p2[np.newaxis, :]
area = 0.5 * np.abs(p0[0] * p1[1] - p0[0] * p2[:,1] +
p1[0] * p2[:,1] - p1[0] * p0[1] +
p2[:,0] * p0[1] - p2[:,0] * p1[1])
return area | p2 can be a vector |
def register_series_method(method):
def inner(*args, **kwargs):
class AccessorMethod(object):
__doc__ = method.__doc__
def __init__(self, pandas_obj):
self._obj = pandas_obj
@wraps(method)
def __call__(self, *args, **kwargs):
re... | Register a function as a method attached to the Pandas Series. |
def OnDialectChoice(self, event):
dialect_name = event.GetString()
value = list(self.choices['dialects']).index(dialect_name)
if dialect_name == 'sniffer':
if self.csvfilepath is None:
event.Skip()
return None
dialect, self.has_header = sni... | Updates all param widgets confirming to the selcted dialect |
def append_message(self, text, output_format=OutputFormat.NormalMessageFormat):
self._append_message(text, self._formats[output_format]) | Parses and append message to the text edit. |
def entry_path(cls, project, location, entry_group, entry):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}",
project=project,
location=location,
entry_group=entry_group,
e... | Return a fully-qualified entry string. |
def sarea_(self, col, x=None, y=None, rsum=None, rmean=None):
try:
charts = self._multiseries(col, x, y, "area", rsum, rmean)
return hv.Area.stack(charts)
except Exception as e:
self.err(e, self.sarea_, "Can not draw stacked area chart") | Get an stacked area chart |
def placeholders(cls,dic):
keys = [str(x) for x in dic]
entete = ",".join(keys)
placeholders = ",".join(cls.named_style.format(x) for x in keys)
entete = f"({entete})"
placeholders = f"({placeholders})"
return entete, placeholders | Placeholders for fields names and value binds |
def jsonify(*args, **kwargs):
return Response(
json.dumps(
dict(
*args,
**kwargs),
cls=MongoJSONEncoder),
mimetype='application/json') | jsonify with support for MongoDB ObjectId |
def convert_bytes(bytes):
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fT' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fG' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 10... | Convert bytes into human readable |
def slugify(s, delimiter='-'):
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')
return RE_SLUG.sub(delimiter, s).strip(delimiter).lower() | Normalize `s` into ASCII and replace non-word characters with `delimiter`. |
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]
a = _twos_comp_conditional(A, aneg)
b = _twos_comp_conditional(B, bne... | Same as tree_multiplier, but uses two's-complement signed integers |
def RegisterProtoDescriptors(db, *additional_descriptors):
db.RegisterFileDescriptor(artifact_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(client_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(config_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(cron_pb2.DESCRIPTOR)
db.RegisterFileDescriptor(flow_pb2.DESCRIPTOR)
db.Reg... | Registers all API-releated descriptors in a given symbol DB. |
def _parse_ftp_time(cls, time_text):
try:
tm_year = int(time_text[0:4])
tm_month = int(time_text[4:6])
tm_day = int(time_text[6:8])
tm_hour = int(time_text[8:10])
tm_min = int(time_text[10:12])
tm_sec = int(time_text[12:14])
except ... | Parse a time from an ftp directory listing. |
def _construct_bower_command(bower_command):
if not bower_command:
raise CommandExecutionError(
'bower_command, e.g. install, must be specified')
cmd = ['bower'] + shlex.split(bower_command)
cmd.extend(['--config.analytics', 'false',
'--config.interactive', 'false',
... | Create bower command line string |
def preview_from_config(name, url, backend,
description=None,
frequency=DEFAULT_HARVEST_FREQUENCY,
owner=None,
organization=None,
config=None,
):
if owner and not isinstanc... | Preview an harvesting from a source created with the given parameters |
def _check_inputs(z, m):
try:
nz = len(z)
z = np.array(z)
except TypeError:
z = np.array([z])
nz = len(z)
try:
nm = len(m)
m = np.array(m)
except TypeError:
m = np.array([m])
nm = len(m)
if (z < 0).any() or (m < 0).any():
raise ... | Check inputs are arrays of same length or array and a scalar. |
def login(provider_id):
provider = get_provider_or_404(provider_id)
callback_url = get_authorize_callback('login', provider_id)
post_login = request.form.get('next', get_post_login_redirect())
session[config_value('POST_OAUTH_LOGIN_SESSION_KEY')] = post_login
return provider.authorize(callback_url) | Starts the provider login OAuth flow |
def connect_params_async(self):
kwargs = self.connect_params.copy()
kwargs.update({
'minsize': self.min_connections,
'maxsize': self.max_connections,
'autocommit': True,
})
return kwargs | Connection parameters for `aiomysql.Connection` |
def serve(config):
"Serve the app with Gevent"
from gevent.pywsgi import WSGIServer
app = make_app(config=config)
host = app.config.get("HOST", '127.0.0.1')
port = app.config.get("PORT", 5000)
http_server = WSGIServer((host, port), app)
http_server.serve_forever() | Serve the app with Gevent |
def log_with_color(level):
def wrapper(text):
color = log_colors_config[level.upper()]
getattr(logger, level.lower())(coloring(text, color))
return wrapper | log with color by different level |
def entities(self):
r = fapi.get_entities_with_type(self.namespace,
self.name, self.api_url)
fapi._check_response_code(r, 200)
edicts = r.json()
return [Entity(e['entityType'], e['name'], e['attributes'])
for e in edicts] | List all entities in workspace. |
def router_del(self, cluster_id, router_id):
cluster = self._storage[cluster_id]
result = cluster.router_remove(router_id)
self._storage[cluster_id] = cluster
return result | remove router from the ShardedCluster |
def pipe(cmd, txt):
return Popen(
cmd2args(cmd),
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=win32
).communicate(txt)[0] | Pipe `txt` into the command `cmd` and return the output. |
def tryload_cache_list(dpath, fname, cfgstr_list, verbose=False):
data_list = [tryload_cache(dpath, fname, cfgstr, verbose) for cfgstr in cfgstr_list]
ismiss_list = [data is None for data in data_list]
return data_list, ismiss_list | loads a list of similar cached datas. Returns flags that needs to be computed |
def start(self, interval, now=True):
if interval < 0:
raise ValueError('interval must be >= 0')
if self._running:
self.stop()
self._running = True
self._interval = interval
if now:
self._self_thread = hub.spawn_after(0, self)
else:
... | Start running pre-set function every interval seconds. |
def lnlike(x, star):
ll = lnprior(x)
if np.isinf(ll):
return ll, (np.nan, np.nan)
per, t0, b = x
model = TransitModel('b', per=per, t0=t0, b=b, rhos=10.)(star.time)
like, d, vard = star.lnlike(model, full_output=True)
ll += like
return ll, (d,) | Return the log likelihood given parameter vector `x`. |
def increment_bucket_count(self, value):
if len(self._bounds) == 0:
self._counts_per_bucket[0] += 1
return 0
for ii, bb in enumerate(self._bounds):
if value < bb:
self._counts_per_bucket[ii] += 1
return ii
else:
last... | Increment the bucket count based on a given value from the user |
def border(self, L):
if self.shape == L_shape:
L.append(self.value)
else:
for x in self.sons:
x.border(L) | Append to L the border of the subtree. |
def assert_lt(left, right, message=None, extra=None):
assert left < right, _assert_fail_message(message, left, right, ">=", extra) | Raises an AssertionError if left_hand >= right_hand. |
def update_user_password(new_pwd_user_id, new_password,**kwargs):
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encode('utf-8'), bcrypt.gensalt())
return user_i
except NoResultFound:
raise ResourceN... | Update a user's password |
def detect_fastq_annotations(fastq_file):
annotations = set()
queryread = tz.first(read_fastq(fastq_file))
for k, v in BARCODEINFO.items():
if v.readprefix in queryread:
annotations.add(k)
return annotations | detects annotations preesent in a FASTQ file by examining the first read |
def _setup(self):
self._populate_local()
try:
self._populate_latest()
except Exception as e:
self.log.exception('Unable to retrieve latest %s version information', self.meta_name)
self._sort() | Run setup tasks after initialization |
def delete_by_query(self, indices, doc_types, query, **query_params):
path = self._make_path(indices, doc_types, '_query')
body = {"query": query.serialize()}
return self._send_request('DELETE', path, body, query_params) | Delete documents from one or more indices and one or more types based on a query. |
def AddTrainingOperators(model, softmax, label):
xent = model.LabelCrossEntropy([softmax, label], 'xent')
loss = model.AveragedLoss(xent, "loss")
AddAccuracy(model, softmax, label)
model.AddGradientOperators([loss])
ITER = brew.iter(model, "iter")
LR = model.LearningRate(
ITER, "LR", bas... | Adds training operators to the model. |
def basic_search(self, pattern):
lookup = None
for pattern in pattern.split():
query_part = models.Q()
for field in SEARCH_FIELDS:
query_part |= models.Q(**{'%s__icontains' % field: pattern})
if lookup is None:
lookup = query_part
... | Basic search on entries. |
def removeNullPadding(str, blocksize=AES_blocksize):
'Remove padding with null bytes'
pad_len = 0
for char in str[::-1]:
if char == '\0':
pad_len += 1
else:
break
str = str[:-pad_len]
return str | Remove padding with null bytes |
def _check_items_limit(self):
if self.items_limit and self.items_limit == self.get_metadata('items_count'):
raise ItemsLimitReached('Finishing job after items_limit reached:'
' {} items written.'.format(self.get_metadata('items_count'))) | Raise ItemsLimitReached if the writer reached the configured items limit. |
def print_options(self):
summary = []
for opt_name, opt in self.options.items():
if opt.hidden:
continue
summary.append(opt.summary())
print("\n".join(summary)) | print description of the component options |
def append_result(self, results, num_matches):
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_color)
file_item.setExpanded(True)
... | Real-time update of search results |
def Attach(self, pid):
if self.inferior.is_running:
answer = raw_input('Already attached to process ' +
str(self.inferior.pid) +
'. Detach? [y]/n ')
if answer and answer != 'y' and answer != 'yes':
return None
self.Detach()
for plugin i... | Attach to the process with the given pid. |
def euler_tour_dfs(G, source=None):
if source is None:
nodes = G
else:
nodes = [source]
yielder = []
visited = set()
for start in nodes:
if start in visited:
continue
visited.add(start)
stack = [(start, iter(G[start]))]
while stack:
... | adaptation of networkx dfs |
def csv_array_clean_format(csv_data, c_headers=None, r_headers=None):
result = []
real_num_header = len(force_list(r_headers[0])) if r_headers else 0
result.append([""] * real_num_header + c_headers)
for k_index in range(0, len(csv_data)):
if r_headers:
result.append(
... | Format csv rows parsed to Array clean format. |
def _debugGraph(self):
print("Len of graph: ", len(self.rdflib_graph))
for x, y, z in self.rdflib_graph:
print(x, y, z) | internal util to print out contents of graph |
def getline(self):
if self.index >= len(self.lines):
line = ''
else:
line = self.lines[self.index]
self.index += 1
return line | Line-getter for tokenize. |
def load_manifest(app, filename='manifest.json'):
if os.path.isabs(filename):
path = filename
else:
path = pkg_resources.resource_filename(app, filename)
with io.open(path, mode='r', encoding='utf8') as stream:
data = json.load(stream)
_registered_manifests[app] = path
return... | Load an assets json manifest |
def setup_gui_analysis_done(self):
self.progress_bar.hide()
self.lblAnalysisStatus.setText(tr('Analysis done.'))
self.pbnReportWeb.show()
self.pbnReportPDF.show()
self.pbnReportPDF.clicked.connect(self.print_map) | Helper method to setup gui if analysis is done. |
def _get_tool_str(self, tool):
res = tool['file']
try:
res += '.' + tool['function']
except Exception as ex:
print('Warning - no function defined for tool ' + str(tool))
res += '\n'
return res | get a string representation of the tool |
def format(self, record):
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record)
exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None)
exc_info_on_loglevel_formatted = getattr(record, 'exc_info_on_loglevel_formatted', None)
if exc_info_on_loglevel is N... | Format the log record to include exc_info if the handler is enabled for a specific log level |
def visit(self, node):
if isinstance(node, Placeholder):
return self.placeholders[node.id]
else:
return super(PlaceholderReplace, self).visit(node) | Replace the placeholder if it is one or continue. |
def intersection(self, *others, **kwargs):
return self._combine_variant_collections(
combine_fn=set.intersection,
variant_collections=(self,) + others,
kwargs=kwargs) | Returns the intersection of variants in several VariantCollection objects. |
def ncVarAttributes(ncVar):
try:
return ncVar.__dict__
except Exception as ex:
logger.warn("Unable to read the attributes from {}. Reason: {}"
.format(ncVar.name, ex))
return {} | Returns the attributes of ncdf variable |
def _match(self):
optimized_rows = None
optimized_columns = None
for match in self.__match_rows(optimized_rows):
yield match
for match in self.__match_rows(optimized_columns,
transpose=True):
yield match | Find all matches and generate a position group for each match. |
def should_exclude(type_or_instance, exclusion_list):
if type_or_instance in exclusion_list:
return True
if type(type_or_instance) in exclusion_list:
return True
try:
if type_or_instance.__class__ in exclusion_list:
return True
except:
pass
return False | Tests whether an object should be simply returned when being wrapped |
def put(self, data, request, id):
if not id:
raise errors.MethodNotAllowed()
userdata = self._dict_to_model(data)
userdata.pk = id
try:
userdata.save(force_update=True)
except DatabaseError:
raise errors.NotFound() | Update a single user. |
def compile_pillar(self):
load = {'id': self.minion_id,
'grains': self.grains,
'saltenv': self.opts['saltenv'],
'pillarenv': self.opts['pillarenv'],
'pillar_override': self.pillar_override,
'extra_minion_data': self.extra_minion_dat... | Return a future which will contain the pillar data from the master |
def tokey(*args):
salt = '||'.join([force_text(arg) for arg in args])
hash_ = hashlib.md5(encode(salt))
return hash_.hexdigest() | Computes a unique key from arguments given. |
def _handle_results(options):
results_processor = options.get('_process_results')
if not results_processor:
results_processor = _process_results
processor_result = results_processor()
if isinstance(processor_result, (Async, Context)):
processor_result.start() | Process the results of executing the Async's target. |
def start_address(self):
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.START_ADDRESS) | Return the start address attribute of the BFD file being processed. |
def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir):
opts = 'x'
if verbosity > 1:
opts += 'v'
opts += "w=%s" % outdir
return [cmd, opts, archive] | Extract a LZH archive. |
def _req_directory(self, cid):
res = self._req_files(cid=cid, offset=0, limit=1, show_dir=1)
path = res['path']
count = res['count']
for d in path:
if str(d['cid']) == str(cid):
res = {
'cid': d['cid'],
'name': d['name']... | Return name and pid of by cid |
def refuse_transfer(transfer, comment=None):
TransferResponsePermission(transfer).test()
transfer.responded = datetime.now()
transfer.responder = current_user._get_current_object()
transfer.status = 'refused'
transfer.response_comment = comment
transfer.save()
return transfer | Refuse an incoming a transfer request |
def load_unixtime(buf, pos):
secs, pos = load_le32(buf, pos)
dt = datetime.fromtimestamp(secs, UTC)
return dt, pos | Load LE32 unix timestamp |
def createTable(dbconn, pd):
cols = ('%s %s' % (defn.name, getTypename(defn)) for defn in pd.fields)
sql = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (pd.name, ', '.join(cols))
dbconn.execute(sql)
dbconn.commit() | Creates a database table for the given PacketDefinition. |
def previous_track(self):
if self._input_func in self._netaudio_func_list:
body = {"cmd0": "PutNetAudioCommand/CurUp",
"cmd1": "aspMainZone_WebUpdateStatus/",
"ZoneName": "MAIN ZONE"}
try:
return bool(self.send_post_command(
... | Send previous track command to receiver command via HTTP post. |
def convert_to_record(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if result is not None:
if isinstance(result, dict):
return _record(result)
return (_record(i) for i in result)
return resul... | Wrap mongodb record to a dict record with default value None |
def _bin(self, bin):
bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "")
if not bin_path.exists():
return bin
return str(bin_path) | Return path to the given executable. |
def import_mod(mod_name:str, ignore_errors=False):
"Return module from `mod_name`."
splits = str.split(mod_name, '.')
try:
if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0])
else: mod = importlib.import_module(mod_name)
return mod
except:
... | Return module from `mod_name`. |
def manifest(self):
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest | The manifest definition of the stencilset as a dict. |
def initial_step(self, phase, x, y):
self.x[0] = x
self.y[0] = y
self.phase[0] = phase
if self.MODE == CordicMode.ROTATION:
if phase > 0.5:
self.x[0] = -x
self.phase[0] = phase - 1.0
elif phase < -0.5:
self.x[0] = -x... | Transform input to the CORDIC working quadrants |
def start(self, request, application, extra_roles=None):
roles = self._get_roles_for_request(request, application)
if extra_roles is not None:
roles.update(extra_roles)
if 'is_authorised' not in roles:
return HttpResponseForbidden('<h1>Access Denied</h1>')
return ... | Continue the state machine at first state. |
def add_legends(self, xhists=True, yhists=False, scatter=True, **kwargs):
axs = []
if xhists:
axs.extend(self.hxs)
if yhists:
axs.extend(self.hys)
if scatter:
axs.extend(self.ax)
for ax in axs:
ax.legend(**kwargs) | Add legends to axes. |
def _put_bucket_tagging(self):
all_tags = self.s3props['tagging']['tags']
all_tags.update({'app_group': self.group, 'app_name': self.app_name})
tag_set = generate_s3_tags.generated_tag_data(all_tags)
tagging_config = {'TagSet': tag_set}
self.s3client.put_bucket_tagging(Bucket=sel... | Add bucket tags to bucket. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.