code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def standalone(body):
with open(_ROOT + '/html.dat', 'r') as html_template:
head = html_title()
html = "".join(html_template.readlines()) \
.replace("{{HEAD}}", head) \
.replace("{{BODY}}", body)
return html | Returns complete html document given markdown html |
def convert_to_broker_id(string):
error_msg = 'Positive integer or -1 required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
if value <= 0 and value != -1:
raise argparse.ArgumentTypeError(error_msg... | Convert string to kafka broker_id. |
def clear(self):
db = sqlite3.connect(self.path)
c = db.cursor()
c.execute("DELETE FROM dirhashcache")
db.commit()
db.close() | Remove all cache entries. |
def setSr(self, fs):
self.tracePlot.setSr(fs)
self.stimPlot.setSr(fs) | Sets the samplerate of the input operation being plotted |
def update(self):
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_level = data['battery_level']
self.__charging_state = data['charging_state'] | Update the battery state. |
def send_event_to_observers(self, ev, state=None):
for observer in self.get_observers(ev, state):
self.send_event(observer, ev, state) | Send the specified event to all observers of this RyuApp. |
def get(self, mode, metric):
if mode not in self._values:
logging.info("Metric %s not found for mode %s", metric, mode)
return []
return list(self._values[mode][metric]) | Get the history for the given metric and mode. |
def _parse_disambiguate(disambiguatestatsfilename):
disambig_stats = [0, 0, 0]
with open(disambiguatestatsfilename, "r") as in_handle:
for i, line in enumerate(in_handle):
fields = line.strip().split("\t")
if i == 0:
assert fields == ['sample', 'unique species A p... | Parse disambiguation stats from given file. |
def recipe_get(backend, recipe):
recipe_root_dir = DKRecipeDisk.find_recipe_root_dir()
if recipe_root_dir is None:
if recipe is None:
raise click.ClickException("\nPlease change to a recipe folder or provide a recipe name arguement")
kitchen_root_dir = DKKitchenDisk.is_kitchen_root_d... | Get the latest files for this recipe. |
def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
class TopicNameStore(object):
def __init__(self):
self._topic_names = set()
def callback(self, msg, topic):
self._topic_names.add(topic)
def get_topic_names(s... | get the name list of the topics, and print it |
def subject_director(**kwargs):
if kwargs.get('qualifier') not in ['KWD', '']:
return ETD_MSSubject(scheme=kwargs.get('qualifier'), **kwargs)
else:
return ETD_MSSubject(content=kwargs.get('content')) | Direct how to handle a subject element. |
def _get_gosrcs_upper(self, goids, max_upper, go2parentids):
gosrcs_upper = set()
get_nt = self.gosubdag.go2nt.get
go2nt = {g:get_nt(g) for g in goids}
go_nt = sorted(go2nt.items(), key=lambda t: -1*t[1].dcnt)
goids_upper = set()
for goid, _ in go_nt:
goids_up... | Get GO IDs for the upper portion of the GO DAG. |
def Unprotect(protected_stream_id, protected_stream_key, subcon):
return Switch(
protected_stream_id,
{'arcfourvariant': ARCFourVariantStream(protected_stream_key, subcon),
'salsa20': Salsa20Stream(protected_stream_key, subcon),
'chacha20': ChaCha20Stream(protected_stream_key, subc... | Select stream cipher based on protected_stream_id |
def disable_vxlan_feature(self, nexus_host):
starttime = time.time()
self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE,
(snipp.BODY_VXLAN_STATE % "disabled"))
self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE,
(snipp.BODY_... | Disable VXLAN on the switch. |
def _clean_data(self, str_value, file_data, obj_value):
str_value = str_value or None
obj_value = obj_value or None
return (str_value, None, obj_value) | This overwrite is neccesary for work with multivalues |
def setCurrentRegItem(self, regItem):
rowIndex = self.model().indexFromItem(regItem)
if not rowIndex.isValid():
logger.warn("Can't select {!r} in table".format(regItem))
self.setCurrentIndex(rowIndex) | Sets the current registry item. |
def verifyCert(self, cert):
tbsCert = cert.tbsCertificate
sigAlg = tbsCert.signature
h = hash_by_oid[sigAlg.algorithm.val]
sigVal = raw(cert.signatureValue)
return self.verify(raw(tbsCert), sigVal, h=h, t='pkcs') | Verifies either a Cert or an X509_Cert. |
async def authenticate_with_device(atv):
credentials = await atv.airplay.generate_credentials()
await atv.airplay.load_credentials(credentials)
try:
await atv.airplay.start_authentication()
pin = input('PIN Code: ')
await atv.airplay.finish_authentication(pin)
print('Credenti... | Perform device authentication and print credentials. |
def _register_pyflakes_check():
from flake8_isort import Flake8Isort
from flake8_blind_except import check_blind_except
codes = {
"UnusedImport": "F401",
"ImportShadowedByLoopVar": "F402",
"ImportStarUsed": "F403",
"LateFutureImport": "F404",
"Redefined": "F801",
... | Register the pyFlakes checker into PEP8 set of checks. |
def ceilpow2(n):
signif,exponent = frexp(n)
if (signif < 0):
return 1;
if (signif == 0.5):
exponent -= 1;
return (1) << exponent; | convenience function to determine a power-of-2 upper frequency limit |
def existing_path(string):
if not os.path.exists(string):
msg = 'path {0!r} does not exist'.format(string)
raise argparse.ArgumentTypeError(msg)
return string | "Convert" a string to a string that is a path to an existing file. |
def rpc_stop(server_state):
rpc_srv = server_state['rpc']
if rpc_srv is not None:
log.info("Shutting down RPC")
rpc_srv.stop_server()
rpc_srv.join()
log.info("RPC joined")
else:
log.info("RPC already joined")
server_state['rpc'] = None | Stop the global RPC server thread |
def csvpatch_cmd(input_csv, input=None, output=None, strict=True):
patch_stream = (sys.stdin
if input is None
else open(input))
tocsv_stream = (sys.stdout
if output is None
else open(output, 'w'))
fromcsv_stream = open(input_csv... | Apply the changes from a csvdiff patch to an existing CSV file. |
def validate_experimental(context, param, value):
if value is None:
return
config = ExperimentConfiguration(value)
config.validate()
return config | Load and validate an experimental data configuration. |
def display_popup(self, title, content):
assert isinstance(title, six.text_type)
assert isinstance(content, six.text_type)
self.popup_dialog.title = title
self._popup_textarea.text = content
self.client_state.display_popup = True
get_app().layout.focus(self._popup_textare... | Display a pop-up dialog. |
def subgraph_from(self, targets: sos_targets):
if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
env.log_to_file('DAG', 'create subgraph')
subnodes = []
for node in self.nodes():
if node._output_targets.valid() and any(
x in node... | Trim DAG to keep only nodes that produce targets |
def configuration():
'Loads configuration from the file system.'
defaults =
cfg = ConfigParser.SafeConfigParser()
cfg.readfp(io.BytesIO(defaults))
cfg.read([
'/etc/coursera/courseraoauth2client.cfg',
os.path.expanduser('~/.coursera/courseraoauth2client.cfg'),
'courseraoauth2c... | Loads configuration from the file system. |
def list_extensions(request):
blacklist = set(getattr(settings,
'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', []))
nova_api = _nova.novaclient(request)
return tuple(
extension for extension in
nova_list_extensions.ListExtManager(nova_api).show_all()
if extension.... | List all nova extensions, except the ones in the blacklist. |
def _get_evidence_bam(work_dir, data):
evidence_bam = glob.glob(os.path.join(work_dir, "results", "evidence",
"evidence_*.%s*.bam" % (dd.get_sample_name(data))))
if evidence_bam:
return evidence_bam[0] | Retrieve evidence BAM for the sample if it exists |
def _cursor_position_changed(self):
cursor = self._text_edit.textCursor()
position = cursor.position()
document = self._text_edit.document()
char = to_text_string(document.characterAt(position - 1))
if position <= self._start_position:
self.hide()
elif char ==... | Updates the tip based on user cursor movement. |
def opened(self):
if self._ddp_version_index == len(DDP_VERSIONS):
self.ddpsocket._debug_log('* DDP VERSION MISMATCH')
self.emit('version_mismatch', DDP_VERSIONS)
return
if self._retry_new_version in DDP_VERSIONS:
self._ddp_version_index = [i for i, x in e... | Send the connect message to the server. |
def flatten(nested_list: list) -> list:
return list(sorted(filter(lambda y: y is not None,
list(map(lambda x: (nested_list.extend(x)
if isinstance(x, list) else x),
nested_list))))) | Flattens a list, ignore all the lambdas. |
def hsize(bytes):
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
if bytes == 0:
return '0 Byte'
i = int(math.floor(math.log(bytes) / math.log(1024)))
r = round(bytes / math.pow(1024, i), 2)
return str(r) + '' + sizes[i] | converts a bytes to human-readable format |
def star_sep_check(self, original, loc, tokens):
return self.check_py("3", "keyword-only argument separator (add 'match' to front to produce universal code)", original, loc, tokens) | Check for Python 3 keyword-only arguments. |
def IsCloud(self, request, bios_version, services):
if request.bios_version_regex and bios_version:
if re.match(request.bios_version_regex, bios_version):
return True
if request.service_name_regex and services:
if re.search(request.service_name_regex, services):
return True
retur... | Test to see if we're on a cloud machine. |
def js_on_click(self, handler):
self.js_on_event(ButtonClick, handler)
self.js_on_event(MenuItemClick, handler) | Set up a JavaScript handler for button or menu item clicks. |
def insertPhenotypeAssociationSet(self, phenotypeAssociationSet):
datasetId = phenotypeAssociationSet.getParentContainer().getId()
attributes = json.dumps(phenotypeAssociationSet.getAttributes())
try:
models.Phenotypeassociationset.create(
id=phenotypeAssociationSet.g... | Inserts the specified phenotype annotation set into this repository. |
def make_delete_table(table: Table, delete_prefix='delete_from__') -> Table:
name = delete_prefix + table.name
primary_key = table.primary_key
key_names = set(primary_key.column_names)
columns = [column for column in table.columns if column.name in key_names]
table = Table(name, columns, primary_key... | Table referencing a delete from using primary key join. |
def check64bit(current_system="python"):
if current_system == "python":
return sys.maxsize > 2147483647
elif current_system == "os":
import platform
pm = platform.machine()
if pm != ".." and pm.endswith('64'):
return True
else:
if 'PROCESSOR_ARCHIT... | checks if you are on a 64 bit platform |
def key_from_ireq(ireq):
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req) | Get a standardized key for an InstallRequirement. |
def _process_flux_param(self, pval, wave):
if isinstance(pval, u.Quantity):
self._validate_flux_unit(pval.unit)
outval = units.convert_flux(self._redshift_model(wave), pval,
self._internal_flux_unit).value
else:
outval = pval
... | Process individual model parameter representing flux. |
def dependencies(self) -> List[Dependency]:
dependencies_str = DB.get_hash_value(self.key, 'dependencies')
dependencies = []
for dependency in ast.literal_eval(dependencies_str):
dependencies.append(Dependency(dependency))
return dependencies | Return the PB dependencies. |
def spline_factors(u):
X = np.array([(1.-u)**3 , 4-(6.*(u**2))+(3.*(u**3)) , 1.+(3.*u)+(3.*(u**2))-(3.*(u**3)) , u**3]) * (1./6)
return X | u is np.array |
def ngram_intersection(args, parser):
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
store.intersection(catalogue, sys.stdout) | Outputs the results of performing an intersection query. |
def _write_max_gradient(self)->None:
"Writes the maximum of the gradients to Tensorboard."
max_gradient = max(x.data.max() for x in self.gradients)
self._add_gradient_scalar('max_gradient', scalar_value=max_gradient) | Writes the maximum of the gradients to Tensorboard. |
def try_int(o:Any)->Any:
"Try to convert `o` to int, default to `o` if not possible."
if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else int(o)
if isinstance(o, collections.Sized) or getattr(o,'__array_interface__',False): return o
try: return int(o)
except: return o | Try to convert `o` to int, default to `o` if not possible. |
def stop_sequence(self):
return sorted(
self.stop_times(),
key=lambda x:int(x.get('stop_sequence'))
) | Return the sorted StopTimes for this trip. |
def apply_bbox(sf,ax):
limits = sf.bbox
xlim = limits[0],limits[2]
ylim = limits[1],limits[3]
ax.set_xlim(xlim)
ax.set_ylim(ylim) | Use bbox as xlim and ylim in ax |
def query(name):
collection = Collection.query.filter_by(name=name).one()
click.echo(collection.dbquery) | Print the collection query. |
def mode_in_range(a, axis=0, tol=1E-3):
a_trunc = a // tol
vals, counts = mode(a_trunc, axis)
mask = (a_trunc == vals)
return np.sum(a * mask, axis) / np.sum(mask, axis) | Find the mode of values to within a certain range |
def dict_from_object(obj: object):
return (obj if isinstance(obj, dict)
else {attr: getattr(obj, attr)
for attr in dir(obj) if not attr.startswith('_')}) | Convert a object into dictionary with all of its readable attributes. |
def _cache_key_select_daterange(method, self, field_id, field_title, style=None):
key = update_timer(), field_id, field_title, style
return key | This function returns the key used to decide if method select_daterange has to be recomputed |
def images(self):
for ds_id, projectable in self.datasets.items():
if ds_id in self.wishlist:
yield projectable.to_image() | Generate images for all the datasets from the scene. |
def onOpen(self):
self.factory.add_client(self)
self.factory.mease.publisher.publish(
message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage) | Called when a client has opened a websocket connection |
def predict(self, features):
distances = [self._distance(x) for x in features]
class_predict = [np.argmin(d) for d in distances]
return self.le.inverse_transform(class_predict) | Predict class outputs for an unlabelled feature set |
def raw(self, tag, raw, metadata):
raw = base64.b64encode(raw)
return {
'type': 'raw',
'tag': tag,
'raw': raw,
'metadata': metadata
} | Create a raw response object |
def _can_circularise(self, start_hit, end_hit):
if not(self._is_at_ref_start(start_hit) or self._is_at_ref_end(end_hit)):
return False
if self._is_at_qry_end(start_hit) \
and self._is_at_qry_start(end_hit) \
and start_hit.on_same_strand() \
and end_hit.on_same_s... | Returns true iff the two hits can be used to circularise the reference sequence of the hits |
def _audio_item(self, stream_url=None, offset=0, push_buffer=True, opaque_token=None):
audio_item = {'stream': {}}
stream = audio_item['stream']
if not stream_url:
stream['url'] = current_stream.url
stream['token'] = current_stream.token
stream['offsetInMillis... | Builds an AudioPlayer Directive's audioItem and updates current_stream |
def _parse_bbox_list(bbox_list):
if isinstance(bbox_list, BBoxCollection):
return bbox_list.bbox_list, bbox_list.crs
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueError('Expected non-empty list of BBox objects')
for bbox in bbox_list:
if not ... | Helper method for parsing a list of bounding boxes |
def apply(self, df):
if self.subset:
if _axis_is_rows(self.axis):
df = df[self.subset]
if _axis_is_cols(self.axis):
df = df.loc[self.subset]
result = df.agg(self.func, axis=self.axis, *self.args, **self.kwargs)
result.name = self.title
... | Compute aggregate over DataFrame |
def datetime_is_iso(date_str):
try:
if len(date_str) > 10:
dt = isodate.parse_datetime(date_str)
else:
dt = isodate.parse_date(date_str)
return True, []
except:
return False, ['Datetime provided is not in a valid ISO 8601 format'] | Attempts to parse a date formatted in ISO 8601 format |
def _claim_in_progress_and_claim_channels(self, grpc_channel, channels):
payments = self._call_GetListInProgress(grpc_channel)
if (len(payments) > 0):
self._printout("There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them."%len(payments))
... | Claim all 'pending' payments in progress and after we claim given channels |
def _try_then(self):
if self._cached is not None and self._callback is not None:
self._callback(*self._cached[0], **self._cached[1]) | Check to see if self has been resolved yet, if so invoke then. |
def InternalExchange(self, cmd, payload_in):
self.logger.debug('payload: ' + str(list(payload_in)))
payload = bytearray()
payload[:] = payload_in
for _ in range(2):
self.InternalSend(cmd, payload)
ret_cmd, ret_payload = self.InternalRecv()
if ret_cmd == UsbHidTransport.U2FHID_ERROR:
... | Sends and receives a message from the device. |
def run_init_tables(*args):
print('--')
create_table(TabPost)
create_table(TabTag)
create_table(TabMember)
create_table(TabWiki)
create_table(TabLink)
create_table(TabEntity)
create_table(TabPostHist)
create_table(TabWikiHist)
create_table(TabCollect)
create_table(TabPost2Tag... | Run to init tables. |
def stats(self):
return self._client.get('{}/stats'.format(Instance.api_endpoint), model=self) | Returns the JSON stats for this Instance |
def info_community(self,teamid):
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent}
req = self.session.get('http://'+self.domain+'/teamInfo.phtml?tid='+teamid,headers=headers).content
... | Get comunity info using a ID |
def stats_table(self, data):
headers = OrderedDict()
headers['combopairs'] = {
'title': 'Combined pairs',
'description': 'Num read pairs combined',
'shared_key': 'read_count',
'hidden': True,
'scale': False
}
headers['perccombo'... | Add percent combined to general stats table |
async def add(gc: GroupControl, slaves):
click.echo("Adding to existing group: %s" % slaves)
click.echo(await gc.add(slaves)) | Add speakers to group. |
def _build_backend():
ep = os.environ['PEP517_BUILD_BACKEND']
mod_path, _, obj_path = ep.partition(':')
try:
obj = import_module(mod_path)
except ImportError:
raise BackendUnavailable
if obj_path:
for path_part in obj_path.split('.'):
obj = getattr(obj, path_part)... | Find and load the build backend |
def _copy(src_file, dest_path):
tf.io.gfile.makedirs(os.path.dirname(dest_path))
with tf.io.gfile.GFile(dest_path, 'wb') as dest_file:
while True:
data = src_file.read(io.DEFAULT_BUFFER_SIZE)
if not data:
break
dest_file.write(data) | Copy data read from src file obj to new file in dest_path. |
def fields_from_dict(d):
class_container = FieldsContainer.class_container
fields = [field_cls.from_dict(field_dict)
for field_cls, container in class_container.iteritems()
for field_dict in d.get(container, [])]
return fields | Load the fields from the dict, return a list with all the fields. |
def default(self, obj):
if hasattr(obj, '__dict__'):
return obj.__dict__.copy()
elif HAS_NUMPY and isinstance(obj, np.ndarray):
return obj.copy().tolist()
else:
raise TypeError(("Object of type {:s} with value of {:s} is not "
"JSO... | Fired when an unserializable object is hit. |
def _resolve(self):
self.__is_resolved = True
if self.is_complex:
type = self.nested if self.nested else self
type.__reference = self.module.lookup(type.name) | resolve the type symbol from name by doing a lookup |
def raise_right_error(response):
if response.status_code == 200:
return
if response.status_code == 500:
raise ServerError('Clef servers are down.')
if response.status_code == 403:
message = response.json().get('error')
error_class = MESSAGE_TO_ERROR_MAP[message]
if er... | Raise appropriate error when bad response received. |
def deliver_slice(schedule):
if schedule.email_format == SliceEmailReportFormat.data:
email = _get_slice_data(schedule)
elif schedule.email_format == SliceEmailReportFormat.visualization:
email = _get_slice_visualization(schedule)
else:
raise RuntimeError('Unknown email report format... | Given a schedule, delivery the slice as an email report |
def _strip_invisible(s):
"Remove invisible ANSI color codes."
if isinstance(s, _text_type):
return re.sub(_invisible_codes, "", s)
else:
return re.sub(_invisible_codes_bytes, "", s) | Remove invisible ANSI color codes. |
def split_kwargs_by_func(kwargs, func):
"Split `kwargs` between those expected by `func` and the others."
args = func_args(func)
func_kwargs = {a:kwargs.pop(a) for a in args if a in kwargs}
return func_kwargs, kwargs | Split `kwargs` between those expected by `func` and the others. |
def bin_to_int(string):
if isinstance(string, str):
return struct.unpack("b", string)[0]
else:
return struct.unpack("b", bytes([string]))[0] | Convert a one element byte string to signed int for python 2 support. |
def canonical_coords(gate: Gate) -> Sequence[float]:
circ = canonical_decomposition(gate)
gate = circ.elements[6]
params = [gate.params[key] for key in ('tx', 'ty', 'tz')]
return params | Returns the canonical coordinates of a 2-qubit gate |
def _get_header(self, header):
if header is None:
html = self.header()
else:
html = header
return html | Gets the html header |
def DeleteOldCronJobRuns(self, cutoff_timestamp, cursor=None):
query = "DELETE FROM cron_job_runs WHERE write_time < FROM_UNIXTIME(%s)"
cursor.execute(query,
[mysql_utils.RDFDatetimeToTimestamp(cutoff_timestamp)]) | Deletes cron job runs that are older then the given timestamp. |
def html(self):
if self.description:
tooltip = 'tooltip="{}"'.format(self.description)
else:
tooltip = ''
return entry_html(
title=self.title,
thumbnail=self.thumbnail,
link=self.html_link,
tooltip=tooltip) | Return html for a the entry |
def range(self):
match = self._match(in_comment(
'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+'
'step[ \t]+([0-9]+)'
))
return range(
int(match.group(1)),
int(match.group(2)),
int(match.group(3))
) | Returns the range for N |
def _apply_incoming_manipulators(self, son, collection):
for manipulator in self.__incoming_manipulators:
son = manipulator.transform_incoming(son, collection)
return son | Apply incoming manipulators to `son`. |
def remove_sign_link(self, ca_name, signee_name):
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record['signees'] or {}
signees = Counter(signees)
if signee_name in signees:
signees[signee_name] = 0
ca_recor... | Removes signee_name to the signee list for ca_name |
def add_field(self, name, script, lang=None, params=None, ignore_failure=False):
data = {}
if lang:
data["lang"] = lang
if script:
data['script'] = script
else:
raise ScriptFieldsError("Script is required for script_fields definition")
if param... | Add a field to script_fields |
def up(self):
if self.frame:
self.frame = self.frame.f_back
return self.frame is None | Go up in stack and return True if top frame |
def _posterior(self, x):
yedge = self._nuis_pdf.marginalization_bins()
yc = 0.5 * (yedge[1:] + yedge[:-1])
yw = yedge[1:] - yedge[:-1]
like_array = self.like(x[:, np.newaxis], yc[np.newaxis, :]) * yw
like_array /= like_array.sum()
self._post = like_array.sum(1)
se... | Internal function to calculate and cache the posterior |
def current_state_str(self):
if self.sample_ok:
msg = ''
temperature = self._get_value_opc_attr('temperature')
if temperature is not None:
msg += 'Temp: %s ºC, ' % temperature
humidity = self._get_value_opc_attr('humidity')
if humidity ... | Return string representation of the current state of the sensor. |
def print_results(results, outfile):
for stanza_words, scheme in results:
outfile.write(str(' ').join(stanza_words) + str('\n'))
outfile.write(str(' ').join(map(str, scheme)) + str('\n\n'))
outfile.close()
logging.info("Wrote result") | Write results to outfile |
def create_app():
app = Flask(__name__)
app.config_from_envvar = app.config.from_envvar
app.config_from_object = app.config.from_object
configure_app(app)
init_core(app)
register_blueprints(app)
return app | Flask application factory function. |
def _encode(self):
obj = {k: v for k, v in self.__dict__.items()
if not k.startswith('_') and type(v) in SAFE_TYPES}
obj.update({k: v._encode() for k, v in self.__dict__.items()
if isinstance(v, Ent)})
return obj | Generate a recursive JSON representation of the ent. |
def _is_version_range(req):
assert len(req.specifier) > 0
specs = list(req.specifier)
if len(specs) == 1:
return specs[0].operator != '=='
else:
return True | Returns true if requirements specify a version range. |
def blockcode(self, text, lang):
if lang and self._config.get('highlight_syntax', 'True'):
try:
lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True)
except pygments.lexers.ClassNotFound:
lexer = None
if lexer:
formatte... | Pass a code fence through pygments |
def combining_successors(state, last_action=()):
((corner, edge), (L, U, F, D, R, B)) = state
U_turns = [Formula("U"), Formula("U'"), Formula("U2")] if len(last_action) != 1 else []
R_turns = [Formula("R U R'"), Formula("R U' R'"), Formula("R U2 R'")] if "R" not in last_action else []
F_... | Successors function for finding path of combining F2L pair. |
def _get_bucket_name(**values):
app = current_app
values.pop('_external', False)
values.pop('_anchor', None)
values.pop('_method', None)
url_style = get_setting('FLASKS3_URL_STYLE', app)
if url_style == 'host':
url_format = '{bucket_name}.{bucket_domain}'
elif url_style == 'path':
... | Generates the bucket name for url_for. |
def write_into(self, block, level=0):
for line, l in self._lines:
block.write_line(line, level + l)
for name, obj in _compat.iteritems(self._deps):
block.add_dependency(name, obj) | Append this block to another one, passing all dependencies |
def previous_weekday(day=None, as_datetime=False):
if day is None:
day = datetime.datetime.now()
else:
day = datetime.datetime.strptime(day, '%Y-%m-%d')
day -= datetime.timedelta(days=1)
while day.weekday() > 4:
day -= datetime.timedelta(days=1)
if as_datetime:
return... | get the most recent business day |
def parents(self, resources):
if self.docname == 'index':
return []
parents = []
parent = resources.get(self.parent)
while parent is not None:
parents.append(parent)
parent = resources.get(parent.parent)
return parents | Split the path in name and get parents |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.