code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def match_string(pattern, search_string):
rexobj = REX(pattern, None)
rexpatstr = reformat_pattern(pattern)
rexpat = re.compile(rexpatstr)
rexobj.rex_patternstr = rexpatstr
rexobj.rex_pattern = rexpat
line_count = 1
for line in search_string.splitlines():
line = line.strip()
... | Match a pattern in a string |
def upload_gunicorn_conf(command='gunicorn', app_name=None, template_name=None, context=None):
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supe... | Upload Supervisor configuration for a gunicorn server. |
def remove_targets(self, type, kept=None):
if kept is None:
kept = [
i for i, x in enumerate(self._targets)
if not isinstance(x, type)
]
if len(kept) == len(self._targets):
return self
self._targets = [self._targets[x] for x in ... | Remove targets of certain type |
def get(app, name):
backend = get_all(app).get(name)
if not backend:
msg = 'Harvest backend "{0}" is not registered'.format(name)
raise EntrypointError(msg)
return backend | Get a backend given its name |
def collect_cmd(self, args, ret):
from dvc.command.daemon import CmdDaemonAnalytics
assert isinstance(ret, int) or ret is None
if ret is not None:
self.info[self.PARAM_CMD_RETURN_CODE] = ret
if args is not None and hasattr(args, "func"):
assert args.func != CmdDae... | Collect analytics info from a CLI command. |
def _cldf2lexstat(
dataset,
segments='segments',
transcription='value',
row='parameter_id',
col='language_id'):
D = _cldf2wld(dataset)
return lingpy.LexStat(D, segments=segments, transcription=transcription, row=row, col=col) | Read LexStat object from cldf dataset. |
def delete(self, request, pzone_pk, operation_pk):
try:
operation = PZoneOperation.objects.get(pk=operation_pk)
except PZoneOperation.DoesNotExist:
raise Http404("Cannot find given operation.")
operation.delete()
return Response("", 204) | Remove an operation from the given pzone. |
async def unmount(self):
self._data = await self._handler.unmount(
system_id=self.node.system_id, id=self.id) | Unmount this block device. |
def salt_master(project, target, module, args=None, kwargs=None):
client = project.cluster.head.ssh_client
cmd = ['salt']
cmd.extend(generate_salt_cmd(target, module, args, kwargs))
cmd.append('--timeout=300')
cmd.append('--state-output=mixed')
cmd = ' '.join(cmd)
output = client.exec_comman... | Execute a `salt` command in the head node |
def _submit_bundle(cmd_args, app):
sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name)
sas = sac.get_streaming_analytics()
sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG])
if 'exception' in sr:
rc = 1
elif 'status_code' in ... | Submit an existing bundle to the service |
def join(self, iterable):
before = []
chunks = []
for i, s in enumerate(iterable):
chunks.extend(before)
before = self.chunks
if isinstance(s, FmtStr):
chunks.extend(s.chunks)
elif isinstance(s, (bytes, unicode)):
ch... | Joins an iterable yielding strings or FmtStrs with self as separator |
def func_interpolate_na(interpolator, x, y, **kwargs):
out = y.copy()
nans = pd.isnull(y)
nonans = ~nans
n_nans = nans.sum()
if n_nans == 0 or n_nans == len(y):
return y
f = interpolator(x[nonans], y[nonans], **kwargs)
out[nans] = f(x[nans])
return out | helper function to apply interpolation along 1 dimension |
def _percolate_query(index, doc_type, percolator_doc_type, document):
if ES_VERSION[0] in (2, 5):
results = current_search_client.percolate(
index=index, doc_type=doc_type, allow_no_indices=True,
ignore_unavailable=True, body={'doc': document}
)
return results['matche... | Get results for a percolate query. |
def autodiscover():
global _RACE_PROTECTION
if _RACE_PROTECTION:
return
_RACE_PROTECTION = True
try:
return filter(None, [find_related_module(app, 'tasks')
for app in settings.INSTALLED_APPS])
finally:
_RACE_PROTECTION = False | Include tasks for all applications in ``INSTALLED_APPS``. |
def _get_cursor(self):
_options = self._get_options()
conn = MySQLdb.connect(host=_options['host'],
user=_options['user'],
passwd=_options['pass'],
db=_options['db'], port=_options['port'],
... | Yield a MySQL cursor |
def ProcessLegacyClient(self, ping, client):
labels = self._GetClientLabelsList(client)
system = client.Get(client.Schema.SYSTEM, "Unknown")
uname = client.Get(client.Schema.UNAME, "Unknown")
self._Process(labels, ping, system, uname) | Update counters for system, version and release attributes. |
def decode(self, poll_interval, buf=None):
if buf is None:
buf = self.receive(poll_interval)
if buf is None:
return None
return decode_network_packet(buf) | Decodes a given buffer or the next received packet. |
def by_name(self):
return {key.split(preferences_settings.SECTION_KEY_SEPARATOR)[-1]: value for key, value in self.all().items()} | Return a dictionary with preferences identifiers and values, but without the section name in the identifier |
def order_mod( x, m ):
if m <= 1: return 0
assert gcd( x, m ) == 1
z = x
result = 1
while z != 1:
z = ( z * x ) % m
result = result + 1
return result | Return the order of x in the multiplicative group mod m. |
def make_label(loss, key):
algo, rate, mu, half, reg = key
slots, args = ['{:.3f}', '{}', 'm={:.3f}'], [loss, algo, mu]
if algo in 'SGD NAG RMSProp Adam ESGD'.split():
slots.append('lr={:.2e}')
args.append(rate)
if algo in 'RMSProp ADADELTA ESGD'.split():
slots.append('rmsh={}')
... | Create a legend label for an optimization run. |
def save(self):
for server, conf in self.servers.iteritems():
self._add_index_server()
for conf_k, conf_v in conf.iteritems():
if not self.conf.has_section(server):
self.conf.add_section(server)
self.conf.set(server, conf_k, conf_v)
... | Saves pypirc file with new configuration information. |
def great_circle_Npoints(lonlat1r, lonlat2r, N):
ratio = np.linspace(0.0,1.0, N).reshape(-1,1)
xyz1 = lonlat2xyz(lonlat1r[0], lonlat1r[1])
xyz2 = lonlat2xyz(lonlat2r[0], lonlat2r[1])
mids = ratio * xyz2 + (1.0-ratio) * xyz1
norm = np.sqrt((mids**2).sum(axis=1))
xyzN = mids / norm.reshape(-1,1)
... | N points along the line joining lonlat1 and lonlat2 |
def _max(ctx, *number):
if len(number) == 0:
raise ValueError("Wrong number of arguments")
result = conversions.to_decimal(number[0], ctx)
for arg in number[1:]:
arg = conversions.to_decimal(arg, ctx)
if arg > result:
result = arg
return result | Returns the maximum value of all arguments |
def _from_dict(cls, _dict):
args = {}
if 'entities' in _dict:
args['entities'] = [
QueryEntitiesEntity._from_dict(x)
for x in (_dict.get('entities'))
]
return cls(**args) | Initialize a QueryRelationsArgument object from a json dictionary. |
def _element_format(self, occur):
if occur:
occ = occur
else:
occ = self.occur
if occ == 1:
if hasattr(self, "default"):
self.attr["nma:default"] = self.default
else:
self.attr["nma:implicit"] = "true"
middle... | Return the serialization format for an element node. |
def handle_password(user, password):
if password is None:
try:
password = keyring.get_password("yagmail", user)
except NameError as e:
print(
"'keyring' cannot be loaded. Try 'pip install keyring' or continue without. See https://github.com/kootenpv/yagmail"
... | Handles getting the password |
def _get_unmanaged_files(self, managed, system_all):
m_files, m_dirs, m_links = managed
s_files, s_dirs, s_links = system_all
return (sorted(list(set(s_files).difference(m_files))),
sorted(list(set(s_dirs).difference(m_dirs))),
sorted(list(set(s_links).difference(... | Get the intersection between all files and managed files. |
def print_meter_record(file_path, rows=5):
m = nr.read_nem_file(file_path)
print('Header:', m.header)
print('Transactions:', m.transactions)
for nmi in m.readings:
for channel in m.readings[nmi]:
print(nmi, 'Channel', channel)
for reading in m.readings[nmi][channel][-rows... | Output readings for specified number of rows to console |
def earth_accel(RAW_IMU,ATTITUDE):
r = rotation(ATTITUDE)
accel = Vector3(RAW_IMU.xacc, RAW_IMU.yacc, RAW_IMU.zacc) * 9.81 * 0.001
return r * accel | return earth frame acceleration vector |
def FDR_BH(self, p):
p = np.asfarray(p)
by_descend = p.argsort()[::-1]
by_orig = by_descend.argsort()
steps = float(len(p)) / np.arange(len(p), 0, -1)
q = np.minimum(1, np.minimum.accumulate(steps * p[by_descend]))
return q[by_orig] | Benjamini-Hochberg p-value correction for multiple hypothesis testing. |
def isfile(self, relpath):
if self.isignored(relpath):
return False
return self._isfile_raw(relpath) | Returns True if path is a file and is not ignored. |
def from_context(cls, ctx, config_paths=None, project=None):
if ctx.obj is None:
ctx.obj = Bunch()
ctx.obj.cfg = cls(ctx.info_name, config_paths, project=project)
return ctx.obj.cfg | Create a configuration object, and initialize the Click context with it. |
def rt(nu, size=None):
return rnormal(0, 1, size) / np.sqrt(rchi2(nu, size) / nu) | Student's t random variates. |
def objective_value(self):
if self._f is None:
raise RuntimeError("Problem has not been optimized yet")
if self.direction == "max":
return -self._f + self.offset
else:
return self._f + self.offset | Returns the optimal objective value |
def write_length_and_key(fp, value):
written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value))
written += write_bytes(fp, value)
return written | Helper to write descriptor key. |
def info():
installation_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
click.echo("colin {} {}".format(__version__, installation_path))
click.echo("colin-cli {}\n".format(os.path.realpath(__file__)))
rpm_installed = is_rpm_installed()
click.echo(get_version_msg_from... | Show info about colin and its dependencies. |
def layers_to_solr(self, layers):
layers_dict_list = []
layers_success_ids = []
layers_errors_ids = []
for layer in layers:
layer_dict, message = layer2dict(layer)
if not layer_dict:
layers_errors_ids.append([layer.id, message])
LOG... | Sync n layers in Solr. |
def ensure_text(str_or_bytes, encoding='utf-8'):
if not isinstance(str_or_bytes, six.text_type):
return str_or_bytes.decode(encoding)
return str_or_bytes | Ensures an input is a string, decoding if it is bytes. |
def tag(message):
release_ver = versioning.current()
message = message or 'v{} release'.format(release_ver)
with conf.within_proj_dir():
log.info("Creating release tag")
git.tag(
author=git.latest_commit().author,
name='v{}'.format(release_ver),
message=me... | Tag the current commit with the current version. |
def _make_plus_helper(obj, fields):
new_obj = {}
for key, value in obj.items():
if key in fields or key.startswith('_'):
if fields.get(key):
if isinstance(value, list):
value = [_make_plus_helper(item, fields[key])
for item in ... | add a + prefix to any fields in obj that aren't in fields |
def addReference(self, reference):
id_ = reference.getId()
self._referenceIdMap[id_] = reference
self._referenceNameMap[reference.getLocalId()] = reference
self._referenceIds.append(id_) | Adds the specified reference to this ReferenceSet. |
def download(self, path):
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
download_get_resp = requests.get(payload["content"])
with open(path, "wb") as config_file:
config_file.write(download_get_resp.content... | downloads a config resource to the path |
def capitalized_words_percent(s):
s = to_unicode(s, precise=True)
words = re.split('\s', s)
words = [w for w in words if w.strip()]
words = [w for w in words if len(w) > 2]
capitalized_words_counter = 0
valid_words_counter = 0
for word in words:
if not INVALID_WORD_START.match(wo... | Returns capitalized words percent. |
def _reorder(string, salt):
len_salt = len(salt)
if len_salt != 0:
string = list(string)
index, integer_sum = 0, 0
for i in range(len(string) - 1, 0, -1):
integer = ord(salt[index])
integer_sum += integer
j = (integer + index + integer_sum) % i
... | Reorders `string` according to `salt`. |
def _sumDiceRolls(self, rollList):
if isinstance(rollList, RollList):
self.rolls.append(rollList)
return rollList.sum()
else:
return rollList | convert from dice roll structure to a single integer result |
def join_sentences(string1, string2, glue='.'):
"concatenate two sentences together with punctuation glue"
if not string1 or string1 == '':
return string2
if not string2 or string2 == '':
return string1
new_string = string1.rstrip()
if not new_string.endswith(glue):
new_strin... | concatenate two sentences together with punctuation glue |
def read_count(self, space, start, end):
read_counts = 0
for read in self._bam.fetch(space, start, end):
read_counts += 1
return self._normalize(read_counts, self._total) | Retrieve the normalized read count in the provided region. |
def getChemicalPotential(self, solution):
if isinstance(solution, Solution):
solution = solution.getSolution()
self.mu = self.solver.chemicalPotential(solution)
return self.mu | Call solver in order to calculate chemical potential. |
def cli_char(name, tibiadata, json):
name = " ".join(name)
char = _fetch_and_parse(Character.get_url, Character.from_content,
Character.get_url_tibiadata, Character.from_tibiadata,
tibiadata, name)
if json and char:
print(char.to_json(indent=2)... | Displays information about a Tibia character. |
def value(self):
if self.root.stale:
self.root.update(self.root.now, None)
return self._value | Current value of the Node |
def tables(subjects=None,
pastDays=None,
include_inactive=False,
lang=DEFAULT_LANGUAGE):
request = Request('tables',
subjects=subjects,
pastDays=pastDays,
includeInactive=include_inactive,
lang=l... | Find tables placed under given subjects. |
def register(self, bucket, name_or_func, func=None):
assert bucket in self, 'Bucket %s is unknown' % bucket
if func is None and hasattr(name_or_func, '__name__'):
name = name_or_func.__name__
func = name_or_func
elif func:
name = name_or_func
if name i... | Add a function to the registry by name |
def peak_load(self):
peak_load = pd.Series(self.consumption).mul(pd.Series(
self.grid.network.config['peakload_consumption_ratio']).astype(
float), fill_value=0)
return peak_load | Get sectoral peak load |
def btc_tx_witness_strip( tx_serialized ):
if not btc_tx_is_segwit(tx_serialized):
return tx_serialized
tx = btc_tx_deserialize(tx_serialized)
for inp in tx['ins']:
del inp['witness_script']
tx_stripped = btc_tx_serialize(tx)
return tx_stripped | Strip the witness information from a serialized transaction |
def place(self):
self.place_children()
self.canvas.append(self.parent.canvas,
float(self.left), float(self.top)) | Place this container's canvas onto the parent container's canvas. |
def refresh_content(self, order=None, name=None):
order = order or self.content.order
url = name or self.content.name
if order == 'ignore':
order = None
with self.term.loader('Refreshing page'):
self.content = SubmissionContent.from_url(
self.reddi... | Re-download comments and reset the page index |
def _check_rev_dict(tree, ebt):
ebs = defaultdict(dict)
for edge in ebt.values():
source_id = edge['@source']
edge_id = edge['@id']
ebs[source_id][edge_id] = edge
assert ebs == tree['edgeBySourceId'] | Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree` |
def render_to_response(self, *args, **kwargs):
if self.request.path != self.object.get_absolute_url():
return HttpResponseRedirect(self.object.get_absolute_url())
return super(TalkView, self).render_to_response(*args, **kwargs) | Canonicalize the URL if the slug changed |
def _lookup_vultrid(which_key, availkey, keyname):
if DETAILS == {}:
_cache_provider_details()
which_key = six.text_type(which_key)
try:
return DETAILS[availkey][which_key][keyname]
except KeyError:
return False | Helper function to retrieve a Vultr ID |
def _module_callers(parser, modname, result):
if modname in result:
return
module = parser.get(modname)
mresult = {}
if module is not None:
for xname, xinst in module.executables():
_exec_callers(xinst, mresult)
result[modname] = mresult
for depkey in module.d... | Adds any calls to executables contained in the specified module. |
def concretize(self, **kwargs):
lengths = [self.state.solver.eval(x[1], **kwargs) for x in self.content]
kwargs['cast_to'] = bytes
return [b'' if i == 0 else self.state.solver.eval(x[0][i*self.state.arch.byte_width-1:], **kwargs) for i, x in zip(lengths, self.content)] | Returns a list of the packets read or written as bytestrings. |
def _update_data_out(self, data, dtype):
try:
self.data_out.update({dtype: data})
except AttributeError:
self.data_out = {dtype: data} | Append the data of the given dtype_out to the data_out attr. |
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False):
if OS == "Darwin":
tty_pattern = "/dev/ttys00[0-9]*"
else:
tty_pattern = "/dev/pts/[0-9]*"
sequences = create_sequences(colors, vte_fix)
if to_send:
for term in glob.glob(tty_pattern):
util.save_file(... | Send colors to all open terminals. |
def generate_gml(username, nodes, edges, cache=False):
node_content = ""
for i in range(len(nodes)):
node_id = "\t\tid %d\n" % (i + 1)
node_label = "\t\tlabel \"%s\"\n" % (nodes[i])
node_content += format_node(node_id, node_label)
edge_content = ""
for i in range(len(edges)):
... | Generate a GML format file representing the given graph attributes |
def invoke(self):
unitdata.kv().flush()
subprocess.check_call([self._filepath, '--invoke', self._test_output], env=os.environ) | Call the external handler to be invoked. |
def com_google_fonts_check_name_match_familyname_fullfont(ttFont):
from fontbakery.utils import get_name_entry_strings
familyname = get_name_entry_strings(ttFont, NameID.FONT_FAMILY_NAME)
fullfontname = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(familyname) == 0:
yield FAIL, Message("no-fo... | Does full font name begin with the font family name? |
def resolve_dependencies(self):
self._concatenate_inner(True)
self._concatenate_inner(False)
self._insert_breaklines() | Resolves chunk dependency by concatenating them. |
def show_keypair(kwargs=None, call=None):
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
... | Show the details of an SSH keypair |
def handle_new_events(self, events):
for event in events:
self.events.append(
self.create_event_object(
event[0],
event[1],
int(event[2]))) | Add each new events to the event queue. |
def statement(self):
return (self.assignment ^ self.expression) + Suppress(
self.syntax.terminator) | A terminated relational algebra statement. |
def flatten(self):
ls = [self.output]
ls.extend(self.state)
return ls | Create a flattened version by putting output first and then states. |
def _transfer_str(self, conn, tmp, name, data):
if type(data) == dict:
data = utils.jsonify(data)
afd, afile = tempfile.mkstemp()
afo = os.fdopen(afd, 'w')
try:
afo.write(data.encode('utf8'))
except:
raise errors.AnsibleError("failure encoding ... | transfer string to remote file |
def _get_auth(username, password):
if username and password:
return requests.auth.HTTPBasicAuth(username, password)
else:
return None | Returns the HTTP auth header |
def write(self):
with open(self.path, 'w') as file_:
file_.write(self.content) | Write content back to file. |
def make_local_dirs(dl_dir, dl_inputs, keep_subdirs):
if not os.path.isdir(dl_dir):
os.makedirs(dl_dir)
print('Created local base download directory: %s' % dl_dir)
if keep_subdirs:
dl_dirs = set([os.path.join(dl_dir, d[1]) for d in dl_inputs])
for d in dl_dirs:
if not... | Make any required local directories to prepare for downloading |
def save_cfg_vals_to_git_cfg(**cfg_map):
for cfg_key_suffix, cfg_val in cfg_map.items():
cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git", "config", "--local", cfg_key, cfg_val
subprocess.check_call(cmd, stderr=subprocess.STDOUT) | Save a set of options into Git config. |
def _set_size_code(self):
if not self._op.startswith(self.SIZE):
self._size_code = None
return
if len(self._op) == len(self.SIZE):
self._size_code = self.SZ_EQ
else:
suffix = self._op[len(self.SIZE):]
self._size_code = self.SZ_MAPPING.g... | Set the code for a size operation. |
def delete(self, filename):
self._failed_atoms.clear()
self.clear()
self.save(filename, padding=lambda x: 0) | Remove the metadata from the given filename. |
def from_cn(cls, common_name):
result_cn = [(cert['id'], [cert['cn']] + cert['altnames'])
for cert in cls.list({'status': ['pending', 'valid'],
'items_per_page': 500,
'cn': common_name})]
result_al... | Retrieve a certificate by its common name. |
def path_iter(self, include_self=True):
if include_self:
node = self
else:
node = self.parent
while node is not None:
yield node
node = node.parent | Yields back the path from this node to the root node. |
def find_tag(match: str, strict: bool, directory: str):
with suppress(CalledProcessError):
echo(git.find_tag(match, strict=strict, git_dir=directory)) | Find tag for git repository. |
def sync_readmes():
print("syncing README")
with open("README.md", 'r') as reader:
file_text = reader.read()
with open("README", 'w') as writer:
writer.write(file_text) | just copies README.md into README for pypi documentation |
def _collectAxisPoints(self):
for l, (value, deltaName) in self.items():
location = Location(l)
name = location.isOnAxis()
if name is not None and name is not False:
if name not in self._axes:
self._axes[name] = []
if l not ... | Return a dictionary with all on-axis locations. |
def find_generator_as_statement(node):
return (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.GeneratorExp)
) | Finds a generator as a statement |
def endpoint_is_activated(endpoint_id, until, absolute_time):
client = get_client()
res = client.endpoint_get_activation_requirements(endpoint_id)
def fail(deadline=None):
exp_string = ""
if deadline is not None:
exp_string = " or will expire within {} seconds".format(deadline)
... | Executor for `globus endpoint is-activated` |
def check_hints(self, reply):
try:
f_ind = reply.index("hints")
l_ind = reply.rindex("hints")
except Exception:
fail_reason = vdp_const.hints_failure_reason % (reply)
LOG.error("%s", fail_reason)
return False, fail_reason
if f_ind != l_... | Parse the hints to check for errors. |
def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,
active_scalar_field='point'):
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
data.copy_meta_from(ido)
if active_scalar is not None:
data.set_a... | A helper to get the algorithm's output and copy input's vtki meta info |
def compute_update_ratio(weight_tensors, before_weights, after_weights):
deltas = [after - before for after,
before in zip(after_weights, before_weights)]
delta_norms = [np.linalg.norm(d.ravel()) for d in deltas]
weight_norms = [np.linalg.norm(w.ravel()) for w in before_weights]
ratios = [... | Compute the ratio of gradient norm to weight norm. |
def register(self, x, graph=False):
if graph:
from inspect import signature
parameters = list(signature(x).parameters)
required_parameters = {"plugins", "services", "strategy"}
assert (
len(parameters) > 0 and parameters[0] == "graph"
)... | Register a function as being part of an API, then returns the original function. |
def _scale(self):
if self._scale_to_box:
scale = 100.0 / self.mesh.scale
else:
scale = 1.0
return scale | Scaling factor for precision. |
def _get_value(self, entity):
value = super(_ClassKeyProperty, self)._get_value(entity)
if not value:
value = entity._class_key()
self._store_value(entity, value)
return value | Compute and store a default value if necessary. |
def new(self):
new_dashboard = models.Dashboard(
dashboard_title='[ untitled dashboard ]',
owners=[g.user],
)
db.session.add(new_dashboard)
db.session.commit()
return redirect(f'/superset/dashboard/{new_dashboard.id}/?edit=true') | Creates a new, blank dashboard and redirects to it in edit mode |
def preload_pages():
try:
_add_url_rule([page.url for page in Page.query.all()])
except Exception:
current_app.logger.warn('Pages were not loaded.')
raise | Register all pages before the first application request. |
def buffer(self, byte_offset=0):
contents = self.ptr.contents
ptr = addressof(contents.buffer.contents) + byte_offset
length = contents.length * 4 - byte_offset
return buffer((c_char * length).from_address(ptr).raw) \
if length else None | Get a copy of the map buffer |
def _get_swig_version(env, swig):
swig = env.subst(swig)
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait()... | Run the SWIG command line tool to get and return the version number |
def reference_image_path(cls, project, location, product, reference_image):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}",
project=project,
location=location,
product=pro... | Return a fully-qualified reference_image string. |
def _action_enabled(self, event, action):
event_actions = self._aconfig.get(event)
if event_actions is None:
return True
if event_actions is False:
return False
return action in event_actions | Check if an action for a notification is enabled. |
def _function_handler(function, args, kwargs, future):
future.set_running_or_notify_cancel()
try:
result = function(*args, **kwargs)
except BaseException as error:
error.traceback = format_exc()
future.set_exception(error)
else:
future.set_result(result) | Runs the actual function in separate thread and returns its result. |
def stopWater(self, dev_id):
path = 'device/stop_water'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | Stop all watering on device. |
def strip_punctuation_space(value):
"Strip excess whitespace prior to punctuation."
def strip_punctuation(string):
replacement_list = (
(' .', '.'),
(' :', ':'),
('( ', '('),
(' )', ')'),
)
for match, replacement in replacement_list:
... | Strip excess whitespace prior to punctuation. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.