content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main(*args: Tuple[str, ...]):
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
app = ArticleEditor(*args)
app.run() | 14,100 |
def parse_field_pubblicazione(field):
"""
Extracts year, place and publisher from the field `pubblicazione` by applying a cascade of regexps.
"""
exp2 = r'^(?P<place>\D+)(?:\s?\W\s?)(?P<publisher>.*?)\D{1}?(?P<year>\d+)?$'
exp1 = r'^(?P<place>.*?)(?::)(?P<publisher>.*?)\D{1}?(?P<year>\d+)?$'
exp3 = r'(?:.*?)?(?P<... | 14,101 |
def test_change_node_prop_DNE(loaded_lpg):
"""Test that we get error if we try to change a property that DNE."""
loaded_lpg.add_node_props('Charlie', kidneys=1)
with pytest.raises(AttributeError):
loaded_lpg.change_node_prop('Charlie', 'horn', 1) | 14,102 |
def test_invalid_landscape():
"""Invalid landscape type must raise error"""
with pytest.raises(ValueError):
BioSim(island_map="WWW\nWRW\nWWW", ini_pop=[], seed=1, vis_years=0) | 14,103 |
def docker_login(ip: str) -> None:
"""
Login-in to docker on the server to avoid docker rate limit quota violation
Args:
ip: The ip of the server that should be logged in
"""
docker_username = os.environ.get('DOCKERHUB_USER')
docker_password = os.environ.get('DOCKERHUB_PASSWORD')
con... | 14,104 |
def test_api_calendar():
"""Return a test calendar object used in API responses."""
return TEST_API_CALENDAR | 14,105 |
def apply_custom_colormap(image_gray, cmap=plt.get_cmap("seismic")):
"""
Implementation of applyColorMap in OpenCV using colormaps in Matplotlib.
"""
assert image_gray.dtype == np.uint8, "must be np.uint8 image"
if image_gray.ndim == 3:
image_gray = image_gray.squeeze(-1)
# Initialize ... | 14,106 |
def _cond_with_per_branch_args(pred,
true_operand, true_fun: Callable,
false_operand, false_fun: Callable):
"""Conditionally apply ``true_fun`` or ``false_fun``.
Has equivalent semantics to this Python implementation::
def cond(pred, true_operand, ... | 14,107 |
def msgSet(key, notUsed, queryString, body):
"""no treatment on the body (we send exactly the body like we received it)"""
dict = urllib.parse.parse_qs(body.decode('utf-8'))
#sendSMS.writeRawMsg(body)
user = dict['user'][0]
print(dict)
sendSMS.writeMsgUser(dict['msg'][0], user)
return "Messa... | 14,108 |
def example_2():
"""Example with hierarchical basis functions"""
#############
# settings: #
#############
basis = Hat # Hat or, Gauss
level = 1 # highest level of basis functions
eval_num = 60 # number of function evaluations
# evaluation coordinates
input = torch.linspace(0, 1, ... | 14,109 |
def _strip_build_number(api_version):
"""Removes the build number component from a full api version string."""
match = re.match(r"^([A-Z]+-)?([0-9]+)(\.[0-9]+){2}$", api_version)
if match:
return api_version[:match.start(3)]
# if there aren't exactly 3 version number components, just leave it unchanged
re... | 14,110 |
def get_me():
"""サインインしている自分自身の情報を取得"""
jia_user_id = get_user_id_from_session()
return {"jia_user_id": jia_user_id} | 14,111 |
def dec_file(name, out=None, **kwargs):
"""
This is a helper function to decrypt a file and return its contents.
You can provide an optional output file using `out`
`name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc.
CLI Examples:
.. code-bloc... | 14,112 |
async def conversation_steps(month: int = Query(default=1, ge=2, le=6), current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Fetches the number of conversation steps that took place in the chat between the users and the agent
"""
return Utility.trigger_history_server_request(
... | 14,113 |
def off(app: str) -> dict:
"""
Switches the app offline, if it isn't already.
:param app: The name of the Heroku app in which you want formation
:return: dictionary containing information about the app
"""
return Herokron(app).off() | 14,114 |
def put_pets_pet_id(
pet_id: str = Path(..., alias='petId'), body: PetForm = None
) -> None:
"""
update a pet
"""
pass | 14,115 |
def test_invalid_getter_and_setter(
assert_errors,
parse_ast_tree,
default_options,
code,
mode,
):
"""Testing that wrong use of getter/setter is prohibited."""
tree = parse_ast_tree(mode(code))
visitor = WrongClassBodyVisitor(default_options, tree=tree)
visitor.run()
assert_err... | 14,116 |
def parse_csv_from_response(response):
"""
Convenience function for working with CSV responses.
Parses the CSV rows and returns a list of dicts, using the
keys as columns
"""
file_from_string = io.StringIO(response.content.decode("utf-8"))
parsed_rows = []
reader = csv.DictReader(file_fr... | 14,117 |
def log_handler(handler: Any) -> None:
"""Override tornado's logging."""
# log only errors (status >= 500)
if handler.get_status() >= 500:
access_log.error(
'{} {}'.format(handler.get_status(), handler._request_summary())
) | 14,118 |
def count_weekday(start, stop, wd_target=0):
"""
Returns the number of days between start and stop inclusive which is the
first day of the month and is the specified weekday, with 0 being Monday.
"""
counter = 0
while start != stop + timedelta(days=1):
if start.weekday() == wd_target and... | 14,119 |
def _get_ngrams(segment, max_order):
"""Extracts all n-grams upto a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
The Counter c... | 14,120 |
def update_template_resource(template, resource, bucket_name, bucket_dir,
resource_param='CodeUri',
s3_object=None, s3_uri=None):
"""Legacy -> Will be moved to the SAMTemplate class."""
if s3_object:
s3_uri = f's3://{bucket_name}/{bucket_dir}/{s3... | 14,121 |
def test_second_generator() -> None:
"""
important remarks on secp256-zkp prefix for
compressed encoding of the second generator:
https://github.com/garyyu/rust-secp256k1-zkp/wiki/Pedersen-Commitment
"""
H = (
0x50929B74C1A04954B78B4B6035E97A5E078A5A0F28EC96D547BFEE9ACE803AC0,
0... | 14,122 |
def pkg_topics_list(data_dict):
"""
Get a list of topics
"""
pkg = model.Package.get(data_dict['id'])
vocabulary = model.Vocabulary.get('Topics')
topics = []
if vocabulary:
topics = pkg.get_tags(vocab=vocabulary)
return topics | 14,123 |
def get_adrill_cdbs(adrill_user_cfg, adrill_shared_cfg=None):
"""Return the names and locatinos of all user defined MSC Adams Drill databases (cdbs)
Parameters
----------
adrill_user_cfg : str
Full path to an Adams Drill user configuration file. This hould be in the users HOME directory.
... | 14,124 |
def copy_assets(app, exception):
""" Copy asset files to the output """
if "getLogger" in dir(logging):
log = logging.getLogger(__name__).info # pylint: disable=no-member
warn = logging.getLogger(__name__).warning # pylint: disable=no-member
else:
log = app.info
warn = app.... | 14,125 |
def five_five(n):
"""
This checks if n is a power of 2 (or 0).
This is because the only way that n and (n-1) have none of the same bits (the
& check) is when n is a power of 2, or 0.
"""
return ((n & (n-1)) == 0) | 14,126 |
async def send_message(user_id: int,
text: str,
buttons: Optional[list[dict[str, str]]] = None,
disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param buttons: List of inline butt... | 14,127 |
def convert_bytes_to_size(some_bytes):
"""
Convert number of bytes to appropriate form for display.
:param some_bytes: A string or integer
:return: A string
"""
some_bytes = int(some_bytes)
suffix_dict = {
'0': 'B',
'1': 'KiB',
'2': 'MiB',
'3': 'GiB',
... | 14,128 |
def create_bbregister_func_to_anat(fieldmap_distortion=False,
name='bbregister_func_to_anat'):
"""
Registers a functional scan in native space to structural. This is meant to be used
after create_nonlinear_register() has been run and relies on some of it's outputs.
... | 14,129 |
def pointShiftFromRange(dataSize, x = all, y = all, z = all, **args):
"""Calculate shift of points given a specific range restriction
Arguments:
dataSize (str): data size of the full image
x,y,z (tuples or all): range specifications
Returns:
tuple: shift of points from orig... | 14,130 |
def callparser():
"""Parses a group of expressions."""
def cull_seps(tokens):
return tokens[0] or tokens[1]
return RepeatParser(exprparser() + OptionParser(dlmparser(',')) ^ cull_seps) | 14,131 |
def write_section(section_name, section, keys, writer) -> bool:
"""
Saves the specified section to the specified writer starting at the current
point in the writer. It will not throw an exception. On error (IO exception
or not being able to write the section) it will return false. WARNING: It can
no... | 14,132 |
def _rotation_270(image):
"""Rotate an image with 270 degrees (clockwise).
Parameters
----------
image : np.ndarray
Image to rotate with shape (y, x, channels).
Returns
-------
image_rotated : np.ndarray
Image rotated with shape (y, x, channels).
"""
image_rotated ... | 14,133 |
def classification_id_for_objs(object_id: str, url: str, token: str):
"""
Get classification id for a given object
Arguments
----------
object_id : str
Object id to get classification id for
url : str
Skyportal url
token : str
Skyportal token
... | 14,134 |
def ciede2000(Lab_1, Lab_2):
"""Calculates CIEDE2000 color distance between two CIE L*a*b* colors."""
C_25_7 = 6103515625 # 25**7
L1, a1, b1 = Lab_1[0], Lab_1[1], Lab_1[2]
L2, a2, b2 = Lab_2[0], Lab_2[1], Lab_2[2]
C1 = math.sqrt(a1**2 + b1**2)
C2 = math.sqrt(a2**2 + b2**2)
C_ave = (C1 + C2)... | 14,135 |
def ifft2c_new(data: torch.Tensor) -> torch.Tensor:
"""
Apply centered 2-dimensional Inverse Fast Fourier Transform.
Args:
data: Complex valued input data containing at least 3 dimensions:
dimensions -3 & -2 are spatial dimensions and dimension -1 has size
2. All other dimens... | 14,136 |
def _make_options(context, base):
"""Return pyld options for given context and base."""
options = {}
if context is None:
context = default_context()
options['expandContext'] = context
if base is not None:
options['base'] = base
return options | 14,137 |
def datatable(table_config: DatatableConfig, table_id: str, class_name: str = ''):
"""
Deprecated, use instead
<table id="{table_id}" data-datatable-url="{url}" class="{class_name}"></table>
"""
return {
"rich_columns": table_config.enabled_columns,
"search_box_enabled": table_config... | 14,138 |
def main():
#"""Prepare neuromorphic MNIST image datasets for use in caffe
#Each dataset will be generated with different number of unique spikes
#"""
#initial_size = 1e6 #best to make this big enough avoid expensive re-allocation
#test_dir = os.path.abspath('testFull')
#train_dir = os.path.absp... | 14,139 |
def npelpt(point, ellipse):
"""npelpt(ConstSpiceDouble [3] point, ConstSpiceDouble [NELLIPSE] ellipse)"""
return _cspyce0.npelpt(point, ellipse) | 14,140 |
def register_module():
"""Registers this module in the registry."""
# provide parser to verify
verify.parse_content = content.parse_string_in_scope
# setup routes
courses_routes = [('/faq', utils_faq.FaqHandler),('/allresources', utils_allresources.AllResourcesHandler)]
global custom_module
... | 14,141 |
def degreeList(s):
"""Convert degrees given on command line to a list.
For example, the string '1,2-5,7' is converted to [1,2,3,4,5,7]."""
l = []
for r in s.split(','):
t = r.split('-')
if len(t) == 1:
l.append(int(t[0]))
else:
a = int(t[0])
... | 14,142 |
def _gen_simple_while_loop(base_dir):
"""Generates a saved model with a while loop."""
class Module(module.Module):
"""A module with a while loop."""
@def_function.function(
input_signature=[tensor_spec.TensorSpec((), dtypes.float32)])
def compute(self, value):
acc, _ = control_flow_ops.... | 14,143 |
def _get_corrected_msm(msm: pd.DataFrame, elevation: float, ele_target: float):
"""MSMデータフレーム内の気温、気圧、重量絶対湿度を標高補正
Args:
df_msm(pd.DataFrame): MSMデータフレーム
ele(float): 平均標高 [m]
elevation(float): 目標地点の標高 [m]
Returns:
pd.DataFrame: 補正後のMSMデータフレーム
"""
TMP = msm['TMP'].values
P... | 14,144 |
def get_answers_by_qname(sim_reads_sam_file):
"""Get a dictionary of Direction Start CIGAR MDtag by ReadID (qname)."""
answers_by_qname = {}
reads_file = open(sim_reads_sam_file)
reads_file.next() #skip header line
for line in reads_file:
id, dir, start, cigar, mdtag = line.strip().split('\t... | 14,145 |
def post_times(post: Post) -> html_tag:
"""Display time user created post.
If user has edited their post show the timestamp for that as well.
:param post: Post ORM object.
:return: Rendered paragraph tag with post's timestamp information.
"""
p = tags.p(cls="small")
p.add(f"{_('Posted')}: ... | 14,146 |
def read_articles_stat(path):
"""
读取articles_stat文件,生成可以读取法条正负样本数量的字典列表
:param path: articles_stat文件位置
:return: ret: [{'第一条': (负样本数量, 正样本数量), ...}, {...}, ..., {...}]
"""
df = pd.read_csv(path, header=0, index_col=0)
ret = [{} for i in range(4)]
for index, row in df.iterrows():
r... | 14,147 |
def get_bounding_box(font):
""" Returns max and min bbox of given truetype font """
ymin = 0
ymax = 0
if font.sfntVersion == 'OTTO':
ymin = font['head'].yMin
ymax = font['head'].yMax
else:
for g in font['glyf'].glyphs:
char = font['glyf'][g]
if hasattr... | 14,148 |
def show_NativeMethods(dx) :
"""
Show the native methods
:param dx : the analysis virtual machine
:type dx: a :class:`VMAnalysis` object
"""
d = dx.get_vm()
for i in d.get_methods() :
if i.get_access_flags() & 0x100 :
print i.get_class_name(), i.get_name(), i.... | 14,149 |
def display_users_bill():
"""display_users_bill():
This function is used to display the users shopping cart.
The option to view the shopping cart has not been added for this program, but it can be achieved by adding code
between lines 214 and 219 in a different function and this function can... | 14,150 |
def look_over(file_name):
"""
# 查看十六进制文件的内容
:param file_name: 文件的目录
:return: 文件的内容
"""
with open(file_name, "rb") as f:
print(binascii.hexlify(f.read())) | 14,151 |
def untag_resource(ResourceArn=None, TagKeys=None):
"""
Deletes a tag key and value from an AppConfig resource.
See also: AWS API Documentation
Exceptions
:example: response = client.untag_resource(
ResourceArn='string',
TagKeys=[
'string',
]
)
... | 14,152 |
def create_user(client, profile, user, resend=False):
""" Creates a new user in the specified user pool """
try:
if resend:
# Resend confirmation email for get back password
response = client.admin_create_user(
UserPoolId=profile["user_pool_id"],
U... | 14,153 |
def generate_move_probabilities(
in_probs: np.ndarray,
move_dirn: float,
nu_par: float,
dir_bool: np.ndarray
):
""" create move probabilities from a 1d array of values"""
out_probs = np.asarray(in_probs.copy())
if np.isnan(out_probs).any():
print('NANs in move probabilities!')
... | 14,154 |
def add_feed(feed_URL=None):
"""
Description: Adds to the feed to the database
Argument(s):
feed_URL - The http(s):// URL to the feed that you wish to pull from
Returns:
a composite string of tidy JSON to post to the channel if the addition
was successful or not
""" | 14,155 |
def test_body(query, selectors, expected):
"""Tests getting the patchable body from a selector"""
sql = pgmock.sql(query, *selectors)
assert sql == expected | 14,156 |
def register_default_actions():
"""Register default actions for Launcher"""
api.register_plugin(api.Action, ProjectManagerAction)
api.register_plugin(api.Action, LoaderAction) | 14,157 |
def _is_diagonal(x):
"""Helper to identify if `LinearOperator` has only a diagonal component."""
return (isinstance(x, tf.linalg.LinearOperatorIdentity) or
isinstance(x, tf.linalg.LinearOperatorScaledIdentity) or
isinstance(x, tf.linalg.LinearOperatorDiag)) | 14,158 |
def index():
"""Index Controller"""
return render_template('login.html') | 14,159 |
def match_twosided(desc1,desc2):
""" Two-sided symmetric version of match(). """
matches_12 = match(desc1,desc2)
matches_21 = match(desc2,desc1)
ndx_12 = matches_12.nonzero()[0]
# remove matches that are not symmetric
for n in ndx_12:
if matches_21[int(matches_12[n])] != n... | 14,160 |
def parse_header_links(value):
"""Return a list of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
:rtype: list
"""
links = []
replace_chars = ' \'"'
value = value.strip(replace_chars)
if... | 14,161 |
def validate_term(fun):
"""Compares current local (node's) term and request (sender's) term:
- if current local (node's) term is older:
update current local (node's) term and become a follower
- if request (sender's) term is older:
respond with {'success': False}
args:
- data o... | 14,162 |
def test_dict_comprehension_func(template, value):
"""Test running a dict comprehension in a declarative function.
"""
source = template.format('{i: %s for i in range(10)}' % value)
win = compile_source(source, 'Main')()
assert win.call() | 14,163 |
def rsync_sitemaps(dry_run=None, remote_host='ves-pg-a4'):
"""
Copy cached sitemaps from local folder to remote one.
"""
sitemaps_path = os.path.join(settings.PROJECT_PATH, 'rnacentral', 'sitemaps')
cmd = 'rsync -avi{dry_run} --delete {src}/ {remote_host}:{dst}'.format(
src=sitemaps_path,
... | 14,164 |
def _friends_bootstrap_radius(args):
"""Internal method used to compute the radius (half-side-length) for each
ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using
bootstrapping."""
# Unzipping.
points, ftype = args
rstate = np.random
# Resampling.
npoints, ndim = points... | 14,165 |
def _parametrize_plus(argnames=None, # type: Union[str, Tuple[str], List[str]]
argvalues=None, # type: Iterable[Any]
indirect=False, # type: bool
ids=None, # type: Union[Callable, Iterable[str]]
idstyle=None, # type: O... | 14,166 |
def _clip_grad(clip_value, grad):
"""
Clip gradients.
Inputs:
clip_value (float): Specifies how much to clip.
grad (tuple[Tensor]): Gradients.
Outputs:
tuple[Tensor], clipped gradients.
"""
dt = ops.dtype(grad)
new_grad = nn.ClipByNorm()(grad, ops.cast(ops.tuple_to_... | 14,167 |
def sample_cast(user, name='David'):
"""Creates a sample Cast"""
return Cast.objects.create(user=user, name=name) | 14,168 |
def sort_special_vertex_groups(vgroups,
special_vertex_group_pattern='STYMO:',
global_special_vertex_group_suffix='Character'):
"""
Given a list of special vertex group names, all with the prefix of
special_vertex_group_pattern, selects all that ... | 14,169 |
def set_players():
"""Set players pawns and name before start the party"""
if "" in [p1_pawn.get(), p1_name.get(), p2_pawn.get(), p2_name.get()]: # check if any empty entry
showerror("Error", "A entry is blank !") # Show a warning
elif p1_pawn.get() == p2_pawn.get(): # Check if players pawns are ... | 14,170 |
def _GetFullDesktopName(window_station, desktop) -> str:
"""Returns a full name to a desktop.
Args:
window_station: Handle to window station.
desktop: Handle to desktop.
"""
return "\\".join([
win32service.GetUserObjectInformation(handle, win32service.UOI_NAME)
for handle in [window_station... | 14,171 |
def decrypt(plain_text: str, a: np.ndarray, b: np.ndarray, space: str) -> str:
"""Decrypts the given text with given a, b and space
:param plain_text: Text you want to decrypt
:type plain_text: str
:param a: An integer that corresponds to the A parameter in block cypher
:type a: np.ndarray
:param b: An integer... | 14,172 |
def merge_rois(roi_list: List,
temporal_coefficient: float, original_2d_vol: np.ndarray,
roi_eccentricity_limit=1.0, widefield=False):
# TODO is this the most efficient implementation I can do
"""
Merges rois based on temporal and spacial overlap
Parameters
----------
... | 14,173 |
def well2D_to_df1D(xlsx_path, sheet, data_col):
"""
Convert new 2D output format (per well) to 1D dataframe
:param str xlsx_path: path to the xlsx file
:param str sheet: sheet name to load
:param str data_col: new column name of the linearized values
:return dataframe df: linearized dataframe
... | 14,174 |
def obtain_file_hash(path, hash_algo="md5"):
"""Obtains the hash of a file using the specified hash algorithm
"""
hash_algo = hashlib.sha256() if hash_algo=="sha256" else hashlib.md5()
block_size = 65535
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(block_size),b''):
... | 14,175 |
def b_q_bar(z_c):
"""Result of integrating from z_c to 1/2 of the
hard collinear part of the quark splitting function"""
b_q_zc = CF * (-3. + 6. * z_c + 4.* np.log(2. - 2.*z_c))/2.
return b_q_zc | 14,176 |
def _prepare_libarchive() -> None: # coverage: ignore
"""
There are some well documented issues in MacOS about libarchive.
Let's try to do things ourselves...
https://github.com/dsoprea/PyEasyArchive
"""
if sys.platform != "darwin":
return
if "LA_LIBRARY_FILEPATH" in os.environ:
... | 14,177 |
def getsize(store, path=None):
"""Compute size of stored items for a given path."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif isinstance(store, dict):
# compute from size of values
prefix = _path_to_pr... | 14,178 |
def split_2DL5AB(GL, cursor, log):
"""
splits the KIR2DL5 GL-string into 2 separate GL strings for 2DL5A and 2DL5B
:param GL: GL-string for KIR2DL5, combining both A and B
:param cursor: cursor to a connection to the nextype archive
:param log: logger instance
"""
log.info("Splitting 2DL5-a... | 14,179 |
def set_system_bios(context, settings, system_id=None, workaround=False):
"""
Finds a system matching the given ID and sets the BIOS settings
Args:
context: The Redfish client object with an open session
settings: The settings to apply to the system
system_id: The system to locate; ... | 14,180 |
def geometric_augmentation(images,
flow = None,
mask = None,
crop_height = 640,
crop_width = 640,
probability_flip_left_right = 0.5,
probability_flip_up_down ... | 14,181 |
def test_rmse():
"""Test to check RMSE calculation"""
data_url = ('https://raw.githubusercontent.com/jonescompneurolab/hnn/'
'master/data/MEG_detection_data/yes_trial_S1_ERP_all_avg.txt')
if not op.exists('yes_trial_S1_ERP_all_avg.txt'):
urlretrieve(data_url, 'yes_trial_S1_ERP_all_av... | 14,182 |
def main():
"""Function gets google assistant request, handle it and returns answer."""
_ = set(variables['Targets_Commands'].split(' '))
targets, commands = _ & {'pc', 'laptop'}, _ - {'pc', 'laptop'}
for target in targets:
for command in commands:
send_given_reqest(target, command)
... | 14,183 |
def edit_distance_between_seqs(seq1, seq2):
"""Input is two strings. They are globally aligned
and the edit distance is returned. An indel of any length
is counted as one edit"""
aln1, aln2 = _needleman_wunsch(seq1, seq2)
return edit_distance_from_aln_strings(aln1, aln2) | 14,184 |
def sentence_prediction(sentence):
"""Predict the grammar score of a sentence.
Parameters
----------
sentence : str
The sentence to be predicted.
Returns
-------
float
The predicted grammar probability.
"""
tokenizer = config.TOKENIZER.from_pretrained(... | 14,185 |
def DB():
"""Create a DB wrapper object connecting to the test database."""
db = pg.DB(dbname, dbhost, dbport)
if debug:
db.debug = debug
return db | 14,186 |
def build_seq(variants, phased_genotype, ref, pre_start, ref_end=None):
"""
Build or extend the haplotype according to provided genotype. We marked the start position iterator of each haplotype and
update with variant alternative base.
"""
seqs = ""
position = pre_start
for variant, phased... | 14,187 |
def handle_str(x):
"""
handle_str returns a random string of the same length as x.
"""
return random_string(len(x)) | 14,188 |
def clean_profile(profile, sid, state_final, state_canceled):
"""
This method will prepare a profile for consumption in radical.analytics. It
performs the following actions:
- makes sure all events have a `ename` entry
- remove all state transitions to `CANCELLED` if a different final state
... | 14,189 |
def _validate_and_apply_configs(app: Sphinx, config: Config):
"""Callback of `config-inited`` event. """
config.graphtik_default_graph_format is None or _valid_format_option(
config.graphtik_default_graph_format
) | 14,190 |
def test_ap_bss_add_out_of_memory(dev, apdev):
"""Running out of memory while adding a BSS"""
hapd2 = hostapd.add_ap(apdev[1], {"ssid": "open"})
ifname1 = apdev[0]['ifname']
ifname2 = apdev[0]['ifname'] + '-2'
confname1 = hostapd.cfg_file(apdev[0], "bss-1.conf")
confname2 = hostapd.cfg_file(ap... | 14,191 |
def get_process_causality_network_activity_query(endpoint_ids: str, args: dict) -> str:
"""Create the process causality network activity query.
Args:
endpoint_ids (str): The endpoint IDs to use.
args (dict): The arguments to pass to the query.
Returns:
str: The created query.
"... | 14,192 |
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
try:
client = TickTick()
client.login(data.get("username"), data.get("password"))
except RequestExcepti... | 14,193 |
def _shard_batch(xs):
"""Shards a batch for a pmap, based on the number of devices."""
local_device_count = jax.local_device_count()
def _prepare(x):
return x.reshape((local_device_count, -1) + x.shape[1:])
return jax.tree_map(_prepare, xs) | 14,194 |
def get_time_limit(component_limit, overall_limit):
"""
Return the minimum time limit imposed by the component and overall limits.
"""
limit = component_limit
if overall_limit is not None:
try:
elapsed_time = util.get_elapsed_time()
except NotImplementedError:
... | 14,195 |
def remove_alias(conn, alias):
"""
Removes a specific alias reference for all directories with that alias
:param conn: the db connection
:param alias: the alias to remove
:return:
"""
with conn:
c = conn.cursor()
c.execute("""UPDATE projects
SET alias = ... | 14,196 |
def test_tetragonal_bravais():
"""Tests initialization of a TetragonalBravais object."""
# parameters of Wulfenite
# https://www.mindat.org/min-4322.html
a, c = 5.433, 12.11
symbols = ["X"]
center = "P"
tetragonal = TetragonalBravais(a, c, symbols, center)
assert tetragonal.n_atoms == 1
... | 14,197 |
def keras_decay(step, decay=0.0001):
"""Learning rate decay in Keras-style"""
return 1. / (1. + decay * step) | 14,198 |
def get_swagger():
""" Request handler for the /swagger path.
GET: returns the My Cars API spec as a swagger json doc.
"""
try:
return _make_response(response=validator.get_swagger_spec())
except Exception as e:
return _make_error(500, e.message) | 14,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.