content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def unknown(bot, update):
"""Message sent when an un unrecognized command is sent"""
bot.send_message(chat_id=update.message.chat_id, text="No compriendo nu caz.") | 5,323,700 |
def SMA(value, day):
"""
返回简单移动平均序列。传入可以是列表或序列类型。传出是历史到当前周期为止的简单移动平均序列。
"""
import talib
# result = statistics.mean(value[-day:])
result = talib.SMA(value, day)
return result | 5,323,701 |
def get_filtered_ecs_service_names(ecs_client, ecs_cluster_name, name_prefix):
"""Retrives the service names for the given cluster, using an optional regex
Keyword arguments:
ecs_client -- Autoscaling boto3 client (if None, will create one)
ecs_cluster_name -- the name of the cluster the service is in
... | 5,323,702 |
def read_stdin(format='fasta'):
"""
Read stdin() and check whether
a) line is a read or not
b) if a read: convert to fasta/fastq
"""
last_written_read = ""
for line in sys.stdin:
la = line.strip().split("\t")
if (len(la)) == 14 and last_written_read != la[0]:
# ye... | 5,323,703 |
def main(
folder_toxic: str,
folder_unintended: str,
output: str,
unintended_threshold: float,
folder_ruddit: str,
text_process: bool,
preprocess_type: str
) -> None:
"""Tool to convert test and train dataset from
https://www.kaggle.com/c/jigsaw-to... | 5,323,704 |
def remove_zero_pairs(xy):
"""Returns new xy-pair Numpy array where x=y=0 pairs have been removed
Arguments:
xy(numpy array): input array
"""
mask = np.where((xy[:, __X] != 0.0) & (xy[:, __Y] != 0.0))[0]
return xy[mask, :] | 5,323,705 |
def AddMEBTChopperPlatesAperturesToSNS_Lattice(accLattice,aprtNodes):
"""
Function will add two Aperture nodes at the entrance and exit of
MEBT chopper plates. It returns the list of Aperture nodes.
"""
x_size = 0.060
y_size = 0.018
shape = 3
node_pos_dict = accLattice.getNodePositionsDict()
node1 = accLattice... | 5,323,706 |
def build_parser():
"""Build argument parser."""
parse = argparse.ArgumentParser(description=("Use this script to generate new APBS input "
"files or split an existing parallel input "
"file into multiple async fil... | 5,323,707 |
def find_adjective(sent):
"""Given a sentence, find the best candidate adjective."""
adj = None
for w, p in sent.pos_tags:
if p == 'JJ': # This is an adjective
adj = w
break
return adj | 5,323,708 |
def verify_signatures(item: Any, verify_types: bool = True) -> None:
"""Verifies the signature of all examples associated with the provided item.
Provided item should be of type function, module, or module name.
- *verify_types*: If `True` all examples will have have their types checked against
... | 5,323,709 |
def tensor_index_by_number(data, number):
"""Tensor getitem by a Number which may be integer/float/bool value"""
number_type = const_utils.check_number_index_type(number)
if number_type == const_utils.BOOL_:
return tensor_index_by_bool(data, number)
if number_type == const_utils.INT_:
re... | 5,323,710 |
def data_overview(human_file, disease_file):
"""
"""
curated_df = pd.read_csv(disease_file, sep='\t')
interactome_df = pd.read_csv(human_file, sep='\t')
interactome_g = nx.from_pandas_edgelist(interactome_df, source='A',
target='B')
curated_g = interac... | 5,323,711 |
def _get_stop_as_datetime(event_json)->datetime:
"""Reads the stop timestamp of the event and returns it as a datetime
object.
Args:
event_json (json): The event encapsulated as json.
Returns
datetime: Timestamp of the stop of the event.
"""
name = event_json['info']['name']
... | 5,323,712 |
def handle_nssend(bot, ievent):
""" arguments: <txt> - send string to the nickserv. """
if bot.jabber: return
if not ievent.rest:
ievent.missing('<txt>')
return
nsauth.sendstring(bot, ievent.rest)
ievent.reply('send') | 5,323,713 |
def fetch_incidents_command():
"""
Fetches incidents from the ProofPoint API.
"""
integration_params = demisto.params()
last_fetch = demisto.getLastRun().get('last_fetch', {})
last_fetched_id = demisto.getLastRun().get('last_fetched_incident_id', {})
fetch_delta = integration_params.get... | 5,323,714 |
def ascon_finalize(S, rate, a, key):
"""
Ascon finalization phase - internal helper function.
S: Ascon state, a list of 5 64-bit integers
rate: block size in bytes (8 for Ascon-128, Ascon-80pq; 16 for Ascon-128a)
a: number of initialization/finalization rounds for permutation
key: a bytes object... | 5,323,715 |
def test_generate_end_connection():
"""
Tests the generate_end_connection function of Road
:return: Tests pass if end connection is generated properly. Fail if otherwise.
"""
start = Coordinates(90, 70)
end = Coordinates(70, 70)
length = 20
out_ln = 1
in_ln = 1
angle = math.pi / ... | 5,323,716 |
def _click_command(
state: State,
path: str,
files: str,
batch: int,
runid_log: str = None,
wait: bool = False,
skip_existing: str = False,
simulate: bool = False,
):
"""Ingest files into OSDU."""
return ingest(state, path, files, batch, runid_log, wait, skip_existing, simulate) | 5,323,717 |
def datasheet_search_query(doctype, txt, searchfield, start, page_len, filters):
"""
:param doctype:
:param txt:
:param searchfield:
:param start:
:param page_len:
:param filters:
:return:
"""
db_name = frappe.conf.get("db_name")
sql = f"""
SELECT
`m`.`name`
, `m`.`title`
FROM `{db_name}`.tabDC_Doc_Datas... | 5,323,718 |
def client():
"""Define client connection to server BaseManager
Returns: BaseManager object
"""
port, auth = get_auth()
mgr = BaseManager(address=('', port), authkey=auth)
mgr.register('set_event')
mgr.connect()
return mgr | 5,323,719 |
def test_SetView_ior(testcase, setview, other, exp_result):
"""
Test function for SetView: self |= other (= __ior__() / __or__() + assign)
"""
# Don't change the testcase data, but a copy
setview_copy = SetView(setview)
setview_copy_id = id(setview_copy)
# The code to be tested
setview... | 5,323,720 |
def end_message():
"""
Prints an end message to the log file.
Parameters
----------
None
Returns
-------
None
"""
# get logger
logger = logging.getLogger(sys._getframe().f_code.co_name) # pylint: disable=protected-access
# dump logo
logger.info(
"Calcula... | 5,323,721 |
def set_remote_sense(is_remote=False):
"""Docstring"""
built_packet = build_cmd(0x56, value=int(is_remote))
resp = send_recv_cmd(built_packet)
return resp | 5,323,722 |
def printImproperDihedral(dihedral, shift, molecule, alchemicalTransformation):
"""Generate improper dihedral line
Parameters
----------
dihedral : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
... | 5,323,723 |
def test_xibo_time_format_new_york(epoch_ms, expected_formatted_time, new_york_datetime_creator):
"""Test creating date/times in New York and formatting them for the Meetup API."""
a_datetime = new_york_datetime_creator.from_epoch_ms(epoch_ms)
assert expected_formatted_time == xibo_time_format(a_datetime) | 5,323,724 |
def check_null_records(field, table, cursor, record_count, report_width):
"""for for null records in the field <field> in the table <table>.
Used by the script "check_stocking_data.py"
Arguments:
- `field`:
- `table`:
- `cursor`:
- `record_count`:
"""
sql = "select stock_id from [... | 5,323,725 |
def logDB2OwnedSemaphores(logFn="db2andsyssems.csv"):
"""
Retrieve the max semaphores in the system the
semaphore count allocated by the db2instance user
and fmp user and the rest of the apps them log a record
in csv format into the logFn file.
Row structure: ts,db2inst_semcnt,db2fmp_semcn... | 5,323,726 |
def initdb(drop):
"""Initialize the database."""
if drop:
click.confirm('This operation will delete the database, do you want to continue?', abort=True)
db.drop_all()
click.echo('Drop tables.')
db.create_all()
click.echo('Initialized database.') | 5,323,727 |
def mmd_est(x, y, c):
"""
Function for estimating the MMD between samples x and y using Gaussian RBF
with scale c.
Args:
x (np.ndarray): (n_samples, n_dims) samples from first distribution.
y (np.ndarray): (n_samples, n_dims) samples from second distribution.
Returns:
float: The mmd estimate."""
n_x = x.s... | 5,323,728 |
def contents_append_notable_sequence_event_types(sequence, asset_sequence_id) -> Dict:
"""Appends a dictionary of filtered data to the base list for the context
Args:
sequence: sequence object
asset_sequence_id: asset sequence ID
Returns:
A contents list with the relevant notable s... | 5,323,729 |
def get_tx_in_db(session: Session, tx_sig: str) -> bool:
"""Checks if the transaction signature already exists for Challenge Disburements"""
tx_sig_db_count = (
session.query(ChallengeDisbursement).filter(
ChallengeDisbursement.signature == tx_sig
)
).count()
exists = tx_sig_... | 5,323,730 |
def demo_version():
"""Get version"""
v = requests.get(end_point, headers=hdrs)
LOG.info('Version: {0}\n'.format(v.text)) | 5,323,731 |
def saturation_correlate(Ch_L, L_L):
"""
Returns the correlate of *saturation* :math:`S_L`.
Parameters
----------
Ch_L : numeric or array_like
Correlate of *chroma* :math:`Ch_L`.
L_L : numeric or array_like
Correlate of *Lightness* :math:`L_L`.
Returns
-------
numer... | 5,323,732 |
def test_get_model_results__multiple_finds(ihme):
"""Expect an exception if no db and table are given and the mvid is found in multiple locations"""
with pytest.raises(ValueError):
model_version_id = 265844
db = None
table = None
_get_model_results(model_version_id, db, table) | 5,323,733 |
def teardown():
"""Called at end of any test @with_setup()"""
for f in list(dakota_files.values()):
if os.path.exists(f):
os.remove(f) | 5,323,734 |
async def test_async_setup_entry_hosts(opp, config_entry, config, soco):
"""Test static setup."""
await setup_platform(opp, config_entry, config)
speakers = list(opp.data[DATA_SONOS].discovered.values())
speaker = speakers[0]
assert speaker.soco == soco
media_player = opp.states.get("media_pla... | 5,323,735 |
def RHS(qmc_data):
"""
RHS(qmc_data)
-------------
We solve A x = b with a Krylov method. This function extracts
b from Sam's qmc_data structure by doing a transport sweep with
zero scattering term.
"""
G = qmc_data.G
Nx = qmc_data.Nx
Nv = Nx*G
zed = np.zeros((Nx,G))
... | 5,323,736 |
def parseThesaurus(eInfo):
"""Return thesaurus object
"""
assert (isinstance(eInfo, pd.Series))
try:
res = eInfo.apply(parseJsonDatum)
except:
# print "\nWarning: parseThesaurus(): blanks or non pd.Series"
res = eInfo.apply(lambda x: "" if x is None else x)
return ... | 5,323,737 |
def gen_pass(length=8, no_numerical=False, punctuation=False):
"""Generate a random password
Parameters
----------
length : int
The length of the password
no_numerical : bool, optional
If true the password will be generated without 0-9
punctuation : bool, optional
If true... | 5,323,738 |
def document_version_title(context):
"""Document version title"""
return context.title | 5,323,739 |
def get_validation_errors(schema, value, validate_invariants=True):
"""
Validate that *value* conforms to the schema interface *schema*.
This includes checking for any schema validation errors (using
`get_schema_validation_errors`). If that succeeds, and
*validate_invariants* is true, then we proce... | 5,323,740 |
def kruskal_suboptimal_mst(graph):
""" Computes the MST of a given graph using Kruskal's algorithm.
Complexity: O(m*n) - it's dominated by determining if adding a new edge
creates a cycle which is O(n). This implementation does not use union-find.
This algorithm also works for directed graphs.
Di... | 5,323,741 |
async def aenumerate(iterable: AsyncIterable[T], start: int = 0) -> AsyncIterator[Tuple[int, T]]:
"""enumerate for async iterators
:param iterable: An async iterable
:param start: The starting value
"""
__tracebackhide__ = True # for pytest
i = start
async for x in iterable:
yield... | 5,323,742 |
def set_url_for_recrawl(db, url):
"""Set url for recrawl later"""
url_hash = urls.hash(url)
result = db['Urls'].find_one_and_update({'_id': url_hash},
{'$set': {'queued': False,
'visited': False}})
return... | 5,323,743 |
def plotScores(data, palette, pdf):
"""
This function creates a PDF file with 3 scatter plots for the combinations
of the 3 principal components. PC1 vs PC2, PC1 vs PC3, PC2 vs PC3.
:Arguments:
:type data: pandas.core.frame.DataFrame
:param data: Data frame with the data to plot.
... | 5,323,744 |
def vertical(hfile):
"""Reads psipred output .ss2 file.
@param hfile psipred .ss2 file
@return secondary structure string.
"""
result = ''
for l in hfile:
if l.startswith('#'):
continue
if not l.strip():
continue
l_arr = l.strip().split()
... | 5,323,745 |
def run(command, use_sudo=False, user='', group='', freturn=False, err_to_out=False, input=None, use_which=True, sumout='', sumerr='', status=0):
"""Dummy executing command on host via ssh or subprocess.
If use_which is not False, original run command will be executed with 'which' command,
and it returns w... | 5,323,746 |
def decide_play(lst):
"""
This function will return the boolean to control whether user should continue the game.
----------------------------------------------------------------------------
:param lst: (list) a list stores the input alphabet.
:return: (bool) if the input character is alphabet and if only one char... | 5,323,747 |
def vocabfile_to_hashdict(vocabfile):
"""
A basic vocabulary hashing strategy just uses the line indices
of each vocabulary word to generate sequential hashes. Thus,
unique hashes are provided for each word in the vocabulary, and the
hash is trivially reversable for easy re-translati... | 5,323,748 |
def lnprior(theta, ref_time, fit_qm=False, prior_params=prior_params_default):
"""
Function to compute the value of ln(prior) for a given set of parameters.
We compute the prior using fixed definitions for the prior distributions
of the parameters, allowing some optional parameters for some of them... | 5,323,749 |
def doy_to_month(year, doy):
"""
Converts a three-digit string with the day of the year to a two-digit
string representing the month. Takes into account leap years.
:param year: four-digit year
:param doy: three-digit day of the year
:return: two-digit string month
"""
dt = datetime... | 5,323,750 |
def process_shot(top, full_prefix):
"""
Given the top directory and full prefix,
return essential info about the shot
Parameters
----------
top: string
directory place of the shot
full_prefix: string
shot description
returns: tuple
shot parameters
"""
... | 5,323,751 |
def open(filename, debug=False):
"""This function opens an existing object pool, returning a
:class:`PersistentObjectPool`.
Raises RuntimeError if the file cannot be opened or mapped.
:param filename: Filename must be an existing file containing an object
pool as created by :func:... | 5,323,752 |
def test_get_queryset(entry_comment_factory, entry_factory):
"""
The view should operate on the comments that belong to the journal
entry specified in the URL.
"""
entry = entry_factory()
entry_comment_factory(entry=entry)
entry_comment_factory()
view = views.EntryCommentListView()
... | 5,323,753 |
def dplnckqn(spectral, temperature):
"""Temperature derivative of Planck function in wavenumber domain for photon rate.
Args:
| spectral (scalar, np.array (N,) or (N,1)): wavenumber vector in [cm^-1]
| temperature (scalar, list[M], np.array (M,), (M,1) or (1,M)): Temperature in [K]
Ret... | 5,323,754 |
def specificity(ground_true, predicted):
"""Computes the specificity.
Args:
ground_true ground_true (np.ndarray[bool]): ground true mask to be compared with predicted one.
predicted predicted (np.ndarray[bool]): predicted mask.
Should be the same dimension as `ground_true`.
Retu... | 5,323,755 |
def _get_node_feature_mapper(
node_feature_mapper_cls: Type[NodeFeatureMapper],
current_state: FrozenSet[Proposition],
problem: STRIPSProblem,
) -> NodeFeatureMapper:
"""
The node feature mappers need to be instantiated based on the current
state and goal states. Hence, a separate one is needed ... | 5,323,756 |
def localize(pathToFolder, pathToDictionary, thresholdsAndLengths, support, confidence, allMalBehaviors, expId):
"""
Localize malicious segments by generating association rules on the maliciously classified files with the tool 'Apyori'
:param pathToFolder: path to the folder containing the classification results
... | 5,323,757 |
def curvInterp(curv,p1,p2,size):
"""
Args:
curv: 2D ndarray
N-by-2 matrix, N points
p1,p2: list or ndarray
length = 2, p1 left point, p2 right point
size: int
the size of new curv (number of points)
"""
if curv[0,0]>curv[-1,0]:
print("... | 5,323,758 |
def test_too_many_returns_in_fixture(absolute_path):
"""End-to-End test to check returns count."""
filename = absolute_path('fixtures', 'complexity', 'wrong_returns.py')
process = subprocess.Popen(
['flake8', filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout... | 5,323,759 |
def create_key_pair(key_pair_name):
"""Create a new key pair with a provided name and story to a local file"""
pem_outfile = open(f"{key_pair_name}.pem", "w")
response = ec2.create_key_pair(KeyName=key_pair_name)
key_pair = str(response.key_material)
pem_outfile.write(key_pair)
print(f"Create Ke... | 5,323,760 |
async def 秒数3(ctx, zan,la,la2):
"""?秒数 戦闘時間 残HP ひとりめ ふたりめ =持越し秒数がでる フルタイム前提"""
b = int(zan) - int(la2)
c = 90 - (int(b) / int(la)) * 90 + 20
if c > 90:
c = 90
b2 = int(zan) - int(la)
c2 = 90 - (int(b2) / int(la2)) * 90 + 20
if c2 > 90:
c2 = 90
await ctx.send(ctx.autho... | 5,323,761 |
def chunk_hash( data ):
""" We need to hash data in a data stream chunk and store the hash in mongo. """
return hashlib.md5( data ).digest().encode('base64') | 5,323,762 |
def jsonify(obj,
builtin_types=(int, float, string_t), key=None,
keyfilter=None,
unknown_type_filter=None):
"""Transforms object making it suitable for json serialization"""
from kombu.abstract import Object as KombuDictType
_jsonify = partial(jsonify, builtin_types=built... | 5,323,763 |
def pack(code, *args):
"""Original struct.pack with the decorator applied.
Will change the code according to the system's architecture.
"""
return struct.pack(code, *args) | 5,323,764 |
def send_email(
template,
context,
subject="",
to=None,
from_email=None,
bcc=None,
connection=None,
attachments=None,
headers=None,
alternatives=None,
cc=None,
reply_to=None,
):
"""
Send an email given a template, context, and to email.
"""
html_content =... | 5,323,765 |
def find_faces(image: Image) -> Iterable[CropData]:
"""
Get a list of the location of each face found in an image.
"""
detector = cv2.CascadeClassifier(
str(
MODELS_DIR / "haarcascades" / "haarcascade_frontalface_default.xml"
)
)
grayscale_image: Image = cv2.cvtColor(... | 5,323,766 |
def getpath():
""" Generate filepath to the present file.
:return: filepath to the present file.
:rtype: str
"""
return os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) | 5,323,767 |
async def test_websocket_transport(unused_tcp_port_factory):
""" Test WebSocket Transport """
port = unused_tcp_port_factory()
conn_queue = asyncio.Queue()
transport = websocket.WebSocketInboundTransport(conn_queue, port=port)
transport_task = create_task(transport.accept())
out_conn = await w... | 5,323,768 |
def connect_nodes(contents: List[str]) -> path.NODES:
"""Connect the nodes of the cave system by assigning input pairs.
Args:
contents (List[str]): the file contents
Returns:
path.NODES: a mapping of start to end in a path
"""
nodes: path.NODES = defaultdict(list)
for line in ... | 5,323,769 |
def create_clients(KEY, SECRET):
"""
Creates the necessary recources and clients
that will be used to create the redshift cluster
:return: ec2, iam, redshift clients and resources
"""
ec2 = boto3.resource(
'ec2',
region_name="us-west-2",
aws_access_key_id=K... | 5,323,770 |
def create_app() -> FastAPI:
"""Create and do initial configuration of fastapi app"""
db = Database()
try:
db.create_database()
except Exception: # pylint: disable=broad-except
sys.exit(1)
app_ = FastAPI()
# Add routers
# app_.include_router(project_controller.router, pre... | 5,323,771 |
def _md_fix(text):
"""
sanitize text data that is to be displayed in a markdown code block
"""
return text.replace("```", "``[`][markdown parse fix]") | 5,323,772 |
def play_sequence():
"""Play the entire sequence for a given round by animating the buttons"""
#Change button label
change_label("Playing!")
#Without delay, all buttons will animate at the same time. The delay adds the 'time' variable to each .after()
delay = 0
for value in game_sequence:
... | 5,323,773 |
def nameOrIdentifier(token):
"""
Determine if the given object is a name or an identifier, and return the
textual value of that name or identifier.
@rtype: L{str}
"""
if isinstance(token, Identifier):
return token.get_name()
elif token.ttype == Name:
return token.value
e... | 5,323,774 |
def exact_kinematic_aug_diff_f(t, y, args_tuple):
"""
"""
_y, _, _ = y
_params, _key, diff_f = args_tuple
aug_diff_fn = lambda __y : diff_f(t, __y, (_params,))
_f, scales, translations = aug_diff_fn(_y)
trace = jnp.sum(scales)
return _f, trace, jnp.sum(scales**2) + jnp.sum(translations**... | 5,323,775 |
def inverse_hybrid_transform(value):
"""
Transform back from the IRAF-style hybrid log values.
This takes the hybrid log value and transforms it back to the
actual value. That value is returned. Unlike the hybrid_transform
function, this works on single values not a numpy array. That is because
... | 5,323,776 |
def regress_trend_channel(arr):
"""
通过arr计算拟合曲线及上下拟合通道曲线,返回三条拟合曲线,组成拟合通道
:param arr: numpy array
:return: y_below, y_fit, y_above
"""
# 通过ABuRegUtil.regress_y计算拟合曲线和模型reg_mode,不使用缩放参数zoom
reg_mode, y_fit = ABuRegUtil.regress_y(arr, zoom=False)
reg_params = reg_mode.params
x = np.ara... | 5,323,777 |
def test_graceful_exit_outside_notebook():
"""Test if running interact outside of a notebook does fails gracefully."""
try:
import bokeh
tpf = KeplerTargetPixelFile(filename_tpf_one_center)
result = tpf.interact()
assert(result is None)
except ImportError:
# bokeh is ... | 5,323,778 |
def assert_tap_mysql_row_count_equals(tap_mysql_query_runner_fn: callable, target_query_runner_fn: callable):
"""Count the rows in tap mysql and in a target database
and compare row counts"""
row_counts_in_tap_mysql = tap_mysql_query_runner_fn("""
SELECT tbl, row_count
FROM ( SELECT 'address'... | 5,323,779 |
def answers(provider):
"""Default answers data for copier"""
answers = {}
answers["class_name"] = "TemplateTestCharm"
# Note "TestCharm" can't be used, that's the name of the deafult unit test class
answers["charm_type"] = provider
return answers | 5,323,780 |
def test_register_boundary():
"""capsys -- object created by pytest to
capture stdout and stderr"""
# testing boundary case 1
output = subprocess.run(
['python', '-m', 'qbay'],
stdin=expected_in1,
capture_output=True,
).stdout.decode()
# remove all whitespace
convert... | 5,323,781 |
def pytest_configure(config):
"""add custom marker"""
config.addinivalue_line('markers', 'test_number(number): test case number') | 5,323,782 |
def encode(ds, is_implicit_vr, is_little_endian):
"""Encode a *pydicom* :class:`~pydicom.dataset.Dataset` `ds`.
Parameters
----------
ds : pydicom.dataset.Dataset
The dataset to encode
is_implicit_vr : bool
The element encoding scheme the dataset will be encoded with, ``True``
... | 5,323,783 |
def DetectGae():
"""Determine whether or not we're running on GAE.
This is based on:
https://developers.google.com/appengine/docs/python/#The_Environment
Returns:
True iff we're running on GAE.
"""
server_software = os.environ.get('SERVER_SOFTWARE', '')
return (server_software.startswith('Developm... | 5,323,784 |
def set_static_assets(all_objects, log):
"""Save reloading the same thing over and over."""
new_objects = []
if len(all_objects) > 0:
try:
from PIL import Image, ImageDraw, ImageFont, ImageChops
except ImportError:
log.import_error('Pillow')
for obj in all_obje... | 5,323,785 |
def get_side_effects_from_sider(meddra_all_se_file):
"""
Get the most frequent side effects from SIDER
"""
pubchem_to_umls = {}
umls_to_name = {}
with open(meddra_all_se_file, 'r') as med_fd:
for line in med_fd:
fields = line.strip().split('\t')
pubchem = str(int(... | 5,323,786 |
def beam_constraint_I_design_jac(samples):
"""
Jacobian with respect to the design variables
Desired behavior is when constraint is less than 0
"""
X,Y,E,R,w,t = samples
L = 100
grad = np.empty((samples.shape[1],2))
grad[:,0] = (L*(12*t*X + 6*w*Y))/(R*t**2*w**3)
grad[:,1] = (L*(6*t*... | 5,323,787 |
def get_env_var(name, default_value = None):
"""Get the value of an environment variable, if defined"""
if name in os.environ:
return os.environ[name]
elif default_value is not None:
return default_value
else:
raise RuntimeError('Required environment variable %s not found' % name... | 5,323,788 |
def save_model(model: pl.LightningModule):
"""Saves the current model weight dir on disk
:param model: model
:type model: pl.LightningModule
"""
state_dict_dir = STATE_DICT_DIR
if not os.path.isdir(state_dict_dir):
pathlib.Path(state_dict_dir).mkdir(parents=True, exist_ok=True)
... | 5,323,789 |
def check_usage_quota(vol_size_in_MB, tenant_uuid, datastore_url, privileges, vm_datastore_url):
""" Check if the volume can be created without violating the quota. """
if privileges:
error_msg, total_storage_used = get_total_storage_used(tenant_uuid, datastore_url, vm_datastore_url)
if error_ms... | 5,323,790 |
def _css_to_rect(css):
"""
Convert a tuple in (top, right, bottom, left) order to a dlib `rect` object
:param css: plain tuple representation of the rect in (top, right, bottom, left) order
:return: a dlib `rect` object
"""
return dlib.rectangle(css[2], css[1], css[0], css[3]) | 5,323,791 |
def parse_arguments():
""" Use arparse to parse the input arguments and return it as a argparse.ArgumentParser. """
ap = standard_parser()
add_annotations_arguments(ap)
add_task_arguments(ap)
return ap.parse_args() | 5,323,792 |
def get_alert_contacts(alert_contact_name: Optional[str] = None,
email: Optional[str] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
output_file: Optional[str] = None,
phone... | 5,323,793 |
def read_response(rfile, request_method, body_size_limit, include_body=True):
"""
Return an (httpversion, code, msg, headers, content) tuple.
By default, both response header and body are read.
If include_body=False is specified, content may be one of the
following:
- None, ... | 5,323,794 |
def epi_approx_tiramisu(image_shape: tuple, num_classes: int,
class_weights=None,
initial_filters: int=48,
growth_rate: int=16,
layer_sizes: list=[4, 5, 7, 10, 12],
bottleneck_size: int=15,
dropout: float=0.2,
learning_rate: float=1e-3,
momentum: float=0.75,
):
"""
Build a Tirami... | 5,323,795 |
def matrix_modinv(matrix, m):
"""Return inverse of the matrix modulo m"""
matrix_det = int(round(linalg.det(matrix)))
return modinv(abs(matrix_det), m)*linalg.inv(matrix)*matrix_det*sign(matrix_det) | 5,323,796 |
def watch(
ctx, settings_file: click.Path, output_dir: Optional[click.Path], clean: bool
):
"""Watch input_dir and rebuild when changes are detected."""
ctx.ensure_object(dict)
ctx.obj = populate_context(settings_file, output_dir)
site = Site.from_settings_file(ctx.obj["settings_file"], ctx.obj["out... | 5,323,797 |
def _check_java_jar_classes(sources, classes_dir):
"""Check if all the classes are generated into classes_dir completely. """
sources = sorted([os.path.basename(s) for s in sources])
sources = [s for s in sources if s[0].isupper()]
classes = ['%s.class' % s[:-5] for s in sources]
if not classes:
... | 5,323,798 |
def hexStringToRGB(hex):
"""
Converts hex color string to RGB values
:param hex: color string in format: #rrggbb or rrggbb with 8-bit values in hexadecimal system
:return: tuple containing RGB color values (from 0.0 to 1.0 each)
"""
temp = hex
length = len(hex)
if temp[0] == "#":
... | 5,323,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.