content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def public(fun, scope=None, cookie=False):
"""
Functions that allow any client access, including those that haven't logged
in should be wrapped in this decorator.
:param fun: A REST endpoint.
:type fun: callable
:param scope: The scope or list of scopes required for this token.
:type scope:... | dad6ba65416ae1cfca26284439c0da7d17dba7e4 | 673,181 |
import copy
def _add_adjusted_col_offsets(table):
"""Add adjusted column offsets to take into account multi-column cells."""
adjusted_table = []
for row in table:
real_col_index = 0
adjusted_row = []
for cell in row:
adjusted_cell = copy.deepcopy(cell)
adjus... | 1b2bd6ea859c4717e6aff35a865b85b9a2eac7ef | 673,182 |
def flip_second_half_direction(team):
"""
Flip coordinates in second half so that each team always shoots in the same direction through the match.
"""
second_half_idx = team.Period.idxmax(2)
columns = [c for c in team.columns if c[-1].lower() in ["x", "y"]]
team.loc[second_half_idx:, columns] *=... | 65f32282e3f04c3c2a703a852f0f8ce23b6ddabf | 673,184 |
import math
def fuel_counter(masses):
"""Function that computes the fuel needed for the input masses.
Expected input is required to either be a list/tuple or scalar"""
if isinstance(masses, (tuple, list)):
return sum(fuel_counter(mass) for mass in masses)
return max(int(math.floor(masses / 3) ... | f4cfa540502bbd4a3eb0c06415dbd9e0e00979cf | 673,185 |
def shutdown_cost_rule(mod, prj, tmp):
"""
If no shutdown_cost_rule is specified in an operational type module, the
default shutdown fuel cost is 0.
"""
return 0 | 5f7c87ed85f77b16e596eaf9c2e360a0891696ec | 673,186 |
def list_medias(api, lang, **params):
# type (ApiClient, str, dict) -> (Iterable[dict])
"""List all the medias.
Args:
api (object): The ApiClient instance used for request.
lang (str): the lang. Defaults to english (en).
``**params``: optional dictionary of search p... | ce2fad1fa02bf69dc4279f9aa7178d2560220209 | 673,188 |
def stringIteration(string, locate, replace):
""" Iteracion de un string """
myNewString = ""
for i in string:
print(i)
if i == locate:
myNewString += replace
else:
myNewString += i
return myNewString | 500832d2c8df30ab956ed739cd84e2f4dc299490 | 673,189 |
def pseudo_residual_regression(target, output):
"""Compute the pseudo residual for regression with least square error."""
if target.size() != output.size():
msg = "The shape of target {} should be the same as output {}."
raise ValueError(msg.format(target.size(), output.size()))
return targ... | 0a346bd827be414cbd52a1905ebaa1b093738065 | 673,190 |
import sys
def checkPythonVersion(expect_major=3, expect_minor=9):
""" Checking Python version.
To upgrade do the following with Anaconda:
conda update conda
conda install python=3.9
conda install anaconda-client
conda update anaconda
conda insta... | 65278747505e3478dc727488c4e545997dba7210 | 673,191 |
def allcomb(listoflists):
"""creates all paths through a list"""
if(len(listoflists)==1):
return([[a] for a in listoflists[0]])
outlist = []
for element in listoflists[0]:
for lists in allcomb(listoflists[1:]):
outlist+=[[element]+lists]
return outlist | e1eff254aa740f610e9b7abc868c80e9838faa72 | 673,192 |
def plural(text, num):
"""Pluralizer: adds "s" at the end of a string if a given number is > 1
"""
return "%s%s" % (text, "s"[num == 1:]) | b958a7b57f95323fbf40fef28dea4e267581330e | 673,195 |
def get_time_signature(h5,songidx=0):
"""
Get signature from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.time_signature[songidx] | 322c18f45daa7a59d47c1edfac10334fd5071c6a | 673,196 |
import os
def check_directory_for_possible_keyloggers (directory):
"""This code will search for files ending in specific extensions (.dll, .scr,
and .pif) and return the file names that do.
These extensions were chosen because they are the most commonly used
extensions for keyloggers, a common virus easy to ... | 146c38f22a6e98659baf3c02db2001a06c1bab2a | 673,197 |
import os
def serverIsReachable(hostname, protocol='https://'):
"""
Check if server is reachable
"""
response = os.system("ping -c 1 " + hostname)
return response == 0 | f1368f687bbc96875d5756a7394e95c5fc1f538f | 673,199 |
def needs_review(effect):
"""
needs review
"""
return effect.instance.activity.review | b83b26a7a4341610ac65b8414cf1fbb96cf4b22d | 673,200 |
def hamming_distance(a, b):
"""
Counts number of nonequal matched elements in two iterables
"""
return sum([int(i != j) for i, j in zip(a, b)]) | 425644ad818f8ee3862bab7b8d15b0e5f8a65e12 | 673,201 |
import torch
def EER(positive_scores, negative_scores):
"""Computes the EER (and its threshold).
Arguments
---------
positive_scores : torch.tensor
The scores from entries of the same class.
negative_scores : torch.tensor
The scores from entries of different classes.
Example
... | 414f162cc43e7b74056e24b46a3b0be71ec10f42 | 673,202 |
def is_parent_of(page1, page2):
"""
Determines whether a given page is the parent of another page
Example:
{% if page|is_parent_of:feincms_page %} ... {% endif %}
"""
if page1 is None:
return False
return (page1.tree_id == page2.tree_id and
page1.lft < page2.lft a... | 6b8f2bb3a41631c565f84c8cdeaa92fcdabee320 | 673,203 |
from typing import Tuple
from typing import Optional
import sys
def get_caller_frame_info() -> Tuple[Optional[str], bool]:
"""
Used inside a function to check whether it was called globally
Will only work against non-compiled code, therefore used only in pydantic.generics
:returns Tuple[module_name,... | 562032a262ee6c841ab9fc3b41670194d38b4954 | 673,204 |
def get_tensor_shape(x):
"""
Get the shape of tensor
Parameters
----------
x : tensor
type float16, float32, float64, int32, complex64, complex128.
Returns
-------
list.
Examples
---------
>>> import tensorlayerx as tlx
>>> x_in = tlx.layers.Input((32, 3, ... | 0b84762060c8ddd0c4d571eedfe7c67c7e1f3d00 | 673,205 |
from typing import Union
from typing import Tuple
from typing import Any
from typing import Dict
import argparse
def _expand_compound_pair(k: Union[Tuple, str], v: Any) -> Dict:
""" given a key-value pair k v, where k is either:
a) a primitive representing a single, e.g. k = 'key', v = 'value', or
b) a ... | 4617b6467a4471c64feb5aa58e7833ec67358266 | 673,206 |
import random
def gen_deterministic_edit_script(length, edit_weights):
"""Generate an edit script which has each edit operation whose number is exactly proportional
to `edit_weights`."""
# Calculate the number of each edit operation to be inserted
weight_sum = sum(edit_weights)
edit_nums = [int(le... | 246b9cee596bef06b84e75867bd80ccf90a2dff2 | 673,207 |
import os
def get_file_ext(file_path: str) -> str:
"""Returns the file extension for the provided file path.
Args:
file_path: a file path with or without a file extension.
Returns:
The file extension, including the leading '.', of file_path. Empty
string when no file extension ex... | 6ea470c05bdf1a859bdcba967231f0351f6dfffb | 673,208 |
def get_text_start(text, length, maxlen=0):
"""Get first words of given text with maximum given length
Text is always truncated between words; if *maxlen* is specified, text is shortened only if
remaining text is longer this value.
:param str text: initial text
:param integer length: maximum lengt... | 45369792702a5bd1c91d5d7840b76cd7049911d6 | 673,209 |
def render_tag_list(tag_list):
"""
Inclusion tag for rendering a tag list.
Context::
Tag List
Template::
tag_list.html
"""
return dict(tag_list=tag_list) | 9b216c8963bb2f2df245a655a78cda3d3295dbca | 673,210 |
import typing
def validate_list(expected, lst: list) -> typing.Union[str, bool]:
"""
Validate a list against our expected schema.
Returns False if the list is valid.
Returns error in string format if invalid.
"""
if not isinstance(lst, list):
return "Expected argument of type `%s`, g... | 1318eaa1b8b4b1730b356475d5b2a3bdc037405f | 673,211 |
def modification_position(molecule, modification_short, modification_ext):
"""
Extract a list of the positions for the modified nucleotides inside a given match
"""
standard_bases = ['A', 'G', 'U', 'C']
modification_positions, output_strings = [], []
for index, nt in enumerate(modification_shor... | e924930dc24447e26b0b7902ad5e4029291466a3 | 673,212 |
from typing import Any
def get_nested(the_dict: dict, nested_key: str, default: Any = None) -> Any:
"""
Returns the value of a nested key in an dictorinary
Args:
the_dict (dict): The dictionary to get the nested value from
nested_key (str): The nested key
default: The value to be ... | a7ad16c4cdf48dd2b48fa82081a2f1a8b57a78a5 | 673,213 |
import re
def percent_decode(data):
""" Percent decode a string of data.
"""
if data is None:
return None
percent_code = re.compile("(%[0-9A-Fa-f]{2})")
try:
bits = percent_code.split(data)
except TypeError:
bits = percent_code.split(str(data))
out = bytearray()
... | b47f6a469056540a2df0d07009b3328d74e024a6 | 673,214 |
import os
def get_valid_directory_list(input_directory):
"""
Get a list of folders
"""
valid_input_directories = []
for directory in os.listdir(input_directory):
if os.path.isdir(os.path.join(input_directory, directory)):
valid_input_directories.append(directory)
else:
... | ba138de9325875fa0bec3f9e5870d3ef19c368bf | 673,215 |
def always_do(action):
"""Returns a policy that always takes the given action."""
def policy(state, rng):
return action
return policy | d8c2f33f0dbe8a112e6472b8e14466b2bdb824a4 | 673,217 |
def f(x, y=0, z=0):
""" A module-level function so that it can be spawn with
multiprocessing.
"""
return x ** 2 + y + z | 29043357bcad562b081239c1a9acf0763416ddcb | 673,218 |
from typing import Sequence
def read_containers(text: str) -> Sequence[int]:
"""
Read the puzzle input into a list of integers representing the container sizes.
"""
return [int(line) for line in text.split("\n")] | 4c0b4dcd80a7934da4560d21d14a5962446d5db8 | 673,219 |
import random
import string
def get_job_id(length=8):
"""Create random job id."""
return "".join(random.choice(string.hexdigits) for x in range(length)) | e968b8e1a466b35545a23e01fe6905f9003eab8c | 673,220 |
import math
def circle_area(diameter):
"""Returns the area of a circle with a diameter of diameter."""
return 1/4*math.pi*(diameter**2) | 67d8225e6e8d1cf9e7c56e265ee067db71c03dfe | 673,221 |
import warnings
def create_gobnilp_settings(score_type, palim=None, alpha=None):
"""
Creates a string of Gobnilp settings given the allowed arities and parent size.
Parameters
----------
score_type : int
The scoring function used to learn the network
0 for BDeu or 2 for BIC
pa... | c78cdb0c4d5351adeca894c8869a4429f3c34578 | 673,222 |
import os
def loadInfoTempl(specials=[], alts=[], tokens=[], duelsPrefix='d!', vanillaPrefix='v!', *, infoMsgTmpl='data/info_msg.templ'):
""" reads and prepares [[info]] template,
{user} will remain for later formatting
"""
if not os.path.isfile(infoMsgTmpl):
return ''
rawTemplate = ''
... | fd4cb59c52157ebbf8da57ebd144b8accbe29643 | 673,223 |
def validate_filename(file):
"""Chek if string."""
if not isinstance(file, str):
raise TypeError(
"File: Argument must be a string. "
"Got instead type {}".format(type(file))
)
return None | d0de6369be17b6eb17864b7697c4c6a8be4c12e9 | 673,224 |
def IReturnOne():
"""This returns 1"""
return 1 | b0ebaa2030afd95b6ed13c3102d1d0f6e9e6375e | 673,225 |
def binary_search(array, item):
"""function to search for the value in a list
Args:
array(list): a sorted list of values
item: the value to be searched for in the array
Returns:
the position of the item from the list or a not found
"""
low = 0
high = len(array) - 1
"""whenever a search is ... | 99b7dc0038ada278090514935924901923824a66 | 673,226 |
def normalize(images, mean, std):
"""normalize ndarray images of shape N x H x W x C"""
return (images - mean) / std | cfbd41e07d70a791aed1031e27f4c9fc4f8897c7 | 673,227 |
def _axes_to_sum(child, parent):
"""Find the indexes of axes that should be summed in `child` to get `parent`"""
return tuple(child.index(i) for i in child if i not in parent) | f7606521efa00be87f1dda2e3940be178c92a530 | 673,228 |
def minimax(val, low, high):
""" Return value forced within range """
try:
val = int(val)
except:
val = 0
if val < low:
return low
if val > high:
return high
return val | 9fdbc8ba8306fc53c4d938b70316b6ea569ebcc3 | 673,229 |
from typing import Tuple
import configparser
def read_login() -> Tuple[str, str]:
"""
read login from file
:return: mail & password
"""
config = configparser.ConfigParser()
config.read("login.ini")
mail = config.get("LOGIN", "email")
password = config.get("LOGIN", "password")
r... | ca4c3ef1cba83be231b7e1c7d84f838a3bcb8f1a | 673,230 |
def rom_to_hex(rom):
"""Convert rom bytearray to hex string."""
return ''.join('{:02x}'.format(x) for x in rom) | e158aba27f2ae3654118ab948aafd0f873ae9e3e | 673,231 |
def remove_nipsa_action(index, annotation):
"""Return an Elasticsearch action to remove NIPSA from the annotation."""
source = annotation["_source"].copy()
source.pop("nipsa", None)
return {
"_op_type": "index",
"_index": index,
"_type": "annotation",
"_id": annotation["_... | 2a997bb9b79f81b203dcfbb198e83e5a8f8d37f5 | 673,232 |
def read_queries(file, interactive=False):
""" Return list of reference and generated queries """
query_list = []
with open(file, 'r') as src:
for line in src.readlines():
if interactive is True:
reference, gen = line.strip('\n').split(",")
else:
... | 4efe991fa364ede10da23a141ed988df6134e7c9 | 673,233 |
def _insert_char_at_pos(text, pos, ch):
"""
Inserts a character at the given position in string.
"""
return text[:pos] + ch + text[pos:] | 0a552d89aca58e1651d513b4543fb4393439dd85 | 673,234 |
def supplementaryName(city):
"""
添加城市名称全名(目前仅限四川内)
:param city: 城市名称(目前仅限四川)
:return : 补充完成的城市完整名称
"""
status = -1
autonomousRegion =["阿坝", "甘孜", "凉山"]
for index, i in enumerate(autonomousRegion):
if i == city:
status = index
break
if status == -1:
... | 3d5cf38dc64e0094ff740c9ad1b8b17eca39dab7 | 673,235 |
import numpy
def running_mean_equal_length(data, width_signal):
"""Returns the running mean in a given window"""
cumsum = numpy.cumsum(numpy.insert(data, 0, 0))
med = (cumsum[width_signal:] - cumsum[:-width_signal]) / float(width_signal)
# Append the first/last value at the beginning/end to match the... | 2c97f6c5283b5bd448fba17ad5c7c330ae0a6027 | 673,236 |
def mk_lst(values, unlst=False):
"""
while iterating through several type of lists and items it is convenient to
assume that we recieve a list, use this function to accomplish this. It
also convenient to be able to return the original type after were done
with it.
"""
# Not a list, were not ... | 670064588bed9f7dd22d3605412a657ddd5204fc | 673,237 |
def porridge_for_the_bears(were_you_robbed):
"""
Did Goldie Locks break in and rob you?
Parameters
----------
were_you_robbed : bool
The question is in the title
Returns
-------
p_bear_emo, m_bear_emo, b_bear_emo : string
The emotional status of the three bears
"""
... | b30cfa2b5855d173c4812d6649ec1a7e655288c9 | 673,238 |
def image_shape(images):
"""Check if all image in `images` have same shape and return that shape."""
shape = None
for image in images:
if not shape:
shape = image.shape
else:
if shape != image.shape:
raise ValueError
return shape | a5724f023f7c0b5602915bd2cfa1c766e068580e | 673,239 |
def trim_description(desc: str, n_words: int) -> str:
"""Return the first `n_words` words of description `desc`/"""
return " ".join(str(desc).split(" ")[0:n_words]) | f0b1a38374455e8e02f8271161a822d8e2e964b6 | 673,241 |
def multiday_checker_STRANGE(start_date, end_date):
"""
Will check if an event is more than day long
:param start_date: Strange Google formatted date of the start of the event
:param end_date: Strange Google formatted date of the end of the event
:return: Boolean
"""
start_date_items = start... | b37b13e537ec9ded3e18716860633346559da462 | 673,242 |
def ahs_url_helper(build_url, config, args):
"""Based on the configured year, get the version arg and replace it into the URL."""
version = config["years"][args["year"]]
url = build_url
url = url.replace("__ver__", version)
return [url] | 0113cfb558e1e23d9f1f25c35e8553796afedd5f | 673,243 |
import argparse
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Runs the the simplex algorithm.")
parser.add_argument("-i", "--input", default="input.txt", type=str,
help="File containing input information.")
parser.add_argume... | 90287ab275c90afacfbfaec925af2af1a02fbdd7 | 673,244 |
import uuid
import json
def create_event(_action, _data):
"""
Create an event.
:param _action: The event action.
:param _data: A dict with the event data.
:return: A dict with the event information.
"""
return {
'event_id': str(uuid.uuid4()),
'event_action': _action,
... | a941043851672a4741696047795f08b2050d007e | 673,245 |
def testlines(infile):
"""
Test if this file is in the MATPOWER format.
NOT YET IMPLEMENTED.
"""
return True | 1454bd4b79f8f7a384bb20be3e8c939698655cb3 | 673,247 |
import math
def morse_force(dist, params):
"""The Morse interaction force
This function is already the negation of the derivative of the Morse energy
with respect to the distance.
"""
de, a, r0 = params
return (
-2 * a * de * math.exp(-a * (dist - r0)) *
(1 - math.exp(-a * (d... | 294f4ebd10e442bcd9c82aead57253f14f3b2bd3 | 673,248 |
def level_up_reward(level, new_level):
""" Coins rewarded when upgrading to new_level. """
coins = 0
while level < new_level:
coins += 5 + level // 15
level += 1
return coins | a655e7e297b1b84d9d20a2873274d7c05ad65544 | 673,249 |
def filter_out_out_pkgs(event_in_pkgs, event_out_pkgs):
"""
In case of a Split or Merge PES events some of the "out" packages can be the same as the "in" packages.
We don't want to remove those "in" packages that are among "out" packages. For example in case of a split of gdbm
to gdbm and gdbm-libs, we... | 3fa8fac75d34cbf268c9b43e0c922646bec23927 | 673,250 |
def substitute_str_idx(s: str, r: str, i: int) -> str:
"""Substitute char at position
Arguments:
s: The str in which to substitute
r: The char to substitute
i: index of the substitution
Returns:
The string `s` with the i'th char substitute with `r`
"""
z = ''.join([(lambda: r,... | 9cdef667249c3447338085ff47de01a58a192be2 | 673,251 |
def desc(sb):
""" A função retorna o valor do desconto de INSS dado o salário bruto como entrada;
float -> float """
dk=0.06*sb
tk=0.08*sb
ddk=0.1*sb
if sb>0 and sb<=2000:
return dk
elif sb>2000 and sb<=3000:
return tk
elif sb>3000:
return ddk
else:
re... | 0d2138a76e8119371111d44539d9d2872f095b6f | 673,252 |
def rotate_address(level, address, rotate_num):
"""Rotates the address with respect to rotational symmetries of SG
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of... | 98048b7d1a6de2a35da55e181f8d7ac4a1bc00f9 | 673,253 |
def get_key(file_name):
"""
Get id from file name
"""
return file_name.split('-')[0] | 500b76f9d0656191759c9fc0be75b0e62c1cba62 | 673,254 |
from tabulate import tabulate
from typing import List
def convert_cross_package_dependencies_to_table(
cross_package_dependencies: List[str],
markdown: bool = True,
) -> str:
"""
Converts cross-package dependencies to a markdown table
:param cross_package_dependencies: list of cross-package depend... | b7753975c3896d7842a8f13f8e2c45a5b044cc6f | 673,255 |
def calc_league_points(pos_map, dsq_list):
"""
A function to work out the league points for each zone, given the rankings within that game.
@param pos_map: a dict of position to array of zone numbers.
@param dsq_list: a list of zones that shouldn't be awarded league points.
@returns: a dict of zone number to leagu... | 72df0c18d919fbdec2241e45337dfdab943fba8a | 673,256 |
import subprocess
def lines_in_file(filename: str) -> int:
"""
https://gist.github.com/zed/0ac760859e614cd03652#file-gistfile1-py-L41
"""
out = subprocess.Popen(
["wc", "-l", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT
).communicate()[0]
return int(out.lstrip().partitio... | 912abcc6b316dd430c80420534810098e2ffab2a | 673,257 |
def getEnd(timefile, end_ind):
"""
Parameter
----------
timefile : array-like 1d
the timefile.
end_ind : integer
the end index.
Returns
-------
the end of the condition.
"""
return timefile['ConditionTime'][end_ind] | 74b31b3028eece0a1398161548cfdb429b7af6a8 | 673,258 |
import random
def green_func(word, font_size, position, orientation, random_state=None,
**kwargs):
"""
Set the color theme of the cloud by recolor and custom coloring functions.
Parameters
----------
word : TYPE
DESCRIPTION.
font_size : TYPE
DESCRIPTION. In... | 3c116296e04074f858dc9c75438950b323519d7e | 673,260 |
import math
def split_float( fval ):
"""Splits a float into integer and fractional parts."""
frac, whole = math.modf( fval )
micros = int( round( frac * 1000000 ))
return int(whole), micros | b0871f99d61a4ba5499e66ee7ac699dbf6fdbadd | 673,261 |
from typing import List
def split_module_names(mod_name: str) -> List[str]:
"""Return the module and all parent module names.
So, if `mod_name` is 'a.b.c', this function will return
['a.b.c', 'a.b', and 'a'].
"""
out = [mod_name]
while '.' in mod_name:
mod_name = mod_name.rsplit('.', ... | f1a8423f5446b7d05c52789194f431e0220f5fa0 | 673,262 |
def cellsDirsNoPos():
"""
Returns all possible directions.
"""
dirs = []
dirs.append([-1,0])
dirs.append([1,0])
dirs.append([0,-1])
dirs.append([0,1])
return dirs | 65102e599b59d528334c3067d3e787b663186f5a | 673,263 |
def import_class(name):
"""Import class from string.
Args:
name (str): class path
Example:
>>> model_cls = import_class("tfchat.models.PreLNDecoder")
"""
components = name.split(".")
mod = __import__(".".join(components[:-1]), fromlist=[components[-1]])
return getattr(mod, co... | 051602a7662706403b8841853e20e468f2bc22a7 | 673,265 |
def is_fractional_es(input_str, short_scale=True):
"""
This function takes the given text and checks if it is a fraction.
Args:
text (str): the string to check if fractional
short_scale (bool): use short scale if True, long scale if False
Returns:
(bool) or (float): False if no... | 3ae68829cda38e64bca1f796dd729930b43fffe2 | 673,266 |
import argparse
def parse_arguments(argv):
"""Parse command-line arguments."""
parser = argparse.ArgumentParser('elevation-to-stl')
parser.add_argument('config_file',
help='Filename of input configuration file')
parser.add_argument('output_file', help='Filename of output STL fi... | 6c1f14d878cf4270d990967413350fd246f9ed54 | 673,267 |
from typing import Iterable
from typing import Any
from typing import List
from typing import Set
from typing import Type
def _get_overloaded_args(relevant_args: Iterable[Any]) -> List[Any]:
"""Returns a list of arguments on which to call __torch_function__.
Checks arguments in relevant_args for __torch_func... | 3e39f179e057d813bbb36bb7d4e0ee05cf09ce79 | 673,268 |
def get_view_setting(view, sname, default=None):
"""Check if a setting is view-specific and only then return its value.
Otherwise return `default`.
"""
s = view.settings()
value = s.get(sname)
s.erase(sname)
value2 = s.get(sname)
if value2 == value:
return default
else:
... | 591647a85fd8e6e14df4f04eefbc5ee9bcb2bdf5 | 673,269 |
import requests
import json
def get_node(node):
"""
:param node: pagename to query
:return: Json representation of the connections of MoinMoin wikipage
"""
r = requests.get('http://localhost/?action=getGraphJSON&pagename={pagename}'.format(pagename=node))
print(r)
json_response = json.dump... | 59a24b1eae0e4b28778bd4f4732a8826d6043844 | 673,270 |
def strip_comments(lines):
"""
Returns the lines from a list of a lines with comments and trailing
whitespace removed.
>>> strip_comments(['abc', ' ', '# def', 'egh '])
['abc', '', '', 'egh']
It should not remove leading whitespace
>>> strip_comments([' bar # baz'])
[' bar']
It... | eaf3e19d53fc2f57376db4f3fcd91a0e9d6840e7 | 673,271 |
import re
import shutil
def re_infile_replace(filename, oldstr, newstr):
"""
Replace every instance of a re in a file with another string. Return
number of replacements performed. Uses temporary file :(
"""
nreplace = 0
fh = open(filename, "r")
fhw = open(filename + ".pytmp", "w")
r... | 92afb50dedee1336706bb6dcda8327634493b61f | 673,272 |
def split_by_standard(df, compl_data):
"""
Return two dataframes, one with standard simulations and one with no-standard
"""
gpcrmd_people = ['Amoralpa11', 'mariona_tf', 'david', 'tste','ismresp']
nonstandard_simulations = set(('dyn4', 'dyn5', 'dyn6', 'dyn7', 'dyn8', 'dyn9', 'dyn10'))
#Find no... | 1a4ac5116ec3324fc7c1d8c0c18622d79210b4b1 | 673,273 |
def calculate_sum(num1, num2):
"""Returns the sum from number 1 to a number 2"""
result = 0
for n in range(num1, num2 + 1):
result = result + n
return result | 722299c56b62fc220db36b42c0341575f10f0d08 | 673,274 |
import os
def is_interactive_mode():
""" Checks if the testdriver should be run in 'interactive mode', which means
that the cluster is created and after that, the script waits for the file
'/cluster_lock' to be deleted.
"""
return 'INTERACTIVE_MODE' in os.environ and os.environ['INTERACTIV... | 35f0ea65504ba39bc42f5ff53a09b3a8b1f65d34 | 673,275 |
def bearings_to_points(bearings, K=None):
"""
Arguments:
bearings: (b, n, 3) Torch tensor,
batch of bearing vector sets
K: (b, 4) Torch tensor or None,
batch of camera intrinsic parameters (fx, fy, cx, cy),
set to None if points are already K-normalised
"... | e68a97d5691e621c171150a439902a9337c6e861 | 673,276 |
import os
def run_split_vcf(job, context, vcf_file_id, split_lines):
""" split vcf into chunks for passing through to the CADD engine for CADD scoring.
"""
# Define work directory for docker calls
work_dir = job.fileStore.getLocalTempDir()
vcf_file = os.path.join(work_dir, os.path.basename(vcf_fi... | c98a6fb75fb271e1351cc1f1e55ee639b7adb46f | 673,278 |
def name_ends(name, endings, addition=""):
"""
Determine if a string ends with something.
Parameters
----------
name: str
The string to determine if it ends with something.
endings: iterable
A list of endings to check.
addition: str
A constant string to search for th... | 871c9628aafc27804e0316aea60f74f09d03db55 | 673,279 |
def _get_new_version(last_str):
""" Return new version number by bumping the requested version level """
# Special case of first version
if not last_str:
print("This is the first release!")
version = input("Please enter the first version number: ")
assert len(version.split('.')) == ... | cb3f8efb0efaf24dae10d23ab247d893bc9a3195 | 673,280 |
def max_alignment(s1, s2, skip_character='~', record=None):
"""
A clever function that aligns s1 to s2 as best it can. Wherever a character from s1 is not found in s2, a '~' is
used to replace that character.
Finally got to use my DP skills!
"""
if record is None:
record = {}
assert... | b367a1334a98daefddeb574f80144dfbcaf8fb61 | 673,281 |
import json
def ppjson(d):
"""
This function prints JSON in a nicer way
"""
return json.dumps(d, sort_keys=True, indent=4) | 485e7912d145cd4145b94ac622be979980fd7407 | 673,283 |
def find_between(s, first, last):
"""
Find sting between two sub-strings
Args:
s: Main string
first: first sub-string
last: second sub-string
Example find_between('[Hello]', '[', ']') -> returns 'Hello'
Returns:
String between the first and second sub-strings, if any... | d2df4c89d63f07678cba8283849917ff767b0903 | 673,284 |
def makeAdder(amount):
"""Make a function that adds the given amount to a number."""
def addAmount(x):
return x + amount
return addAmount | 0c4dc0427f3b30ec4e91dd72f62fe62b494b6074 | 673,285 |
import types
import enum
def skip_non_methods(app, what, name, obj, skip, options):
"""
Skip all class members, that are not methods, enum values or inner
classes, since other attributes are already documented in the class
docstring.
"""
if skip:
return True
if what == "class":
... | 51bbe79bc473e10b6b86114cea42649e4887fa8e | 673,286 |
from typing import Dict
def _answer_types_row(row: Dict[str, str]):
"""
Transform the keys of each answer-type CSV row. If the CSV headers
change, this will make a single place to fix it.
"""
return {
'k': row['Key'],
'c': row['Choices'],
} | 1ff0eddd95a3550209579a96759a0cf2f72d45a3 | 673,288 |
def make_df(df_raw):
"""
Function that takes raw df parsed from csv or db.
Creates columns for multiple choice topic selections.
:return: pd.df, ready to be transformed (transform_data)
"""
# string to lowercase
df = df_raw.apply(lambda x: x.astype(str).str.lower())
# #set index to user... | 0f4a046bb953944029218e4109c52de82d60cde8 | 673,289 |
def twos_complement_to_int(val, length=4):
"""
Two's complement representation to integer.
We assume that the number is always negative.
1. Invert all the bits through the number
2. Add one
"""
invertor = int('1' * length, 2)
return -((int(val, 2) ^ invertor) + 1) | 91e4d93bf334b3cc33e94cec407d09f8d74afb6b | 673,290 |
def batch_slice_select(input, dim, index):
"""
def batch_slice_select(input,dim,index):
index = index.squeeze()
if dim == 1:
return input[range(index.size()[0]), index, :]
else:
return input[range(index.size()[0]), :, index]
Returns a new tensor which indexes ... | 9540e1c983327575ed09e00d71cbae3fdf0acf8a | 673,291 |
import sys
def natural_num(n):
"""Judge whether numstr is positive or not."""
if not n.isdecimal():
print("[!]Err: num {} should be positive integer.".format(n),
file=sys.stderr)
exit(1)
elif int(n) < 1:
print("[!]Err: num {} should be more than 0.".format(n),
... | 267c1bc43419f2a9b1a988dbacc48225ccc9b81e | 673,292 |
def gram_uni_bi_tri(text):
"""
获取文本的unigram, trugram, bigram等特征
:param text: str
:return: list
"""
len_text = len(text)
gram_uni = []
gram_bi = []
gram_tri = []
for i in range(len_text):
if i + 3 <= len_text:
gram_uni.append(text[i])
gram_bi.ap... | 3740108856df6fe8f4cb588b148b07abcee56834 | 673,293 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.