content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def parse_mdout(file):
"""
Return energies from an AMBER `mdout` file.
Parameters
----------
file : str
Name of output file
Returns
-------
energies : dict
A dictionary containing VDW, electrostatic, bond, angle, dihedral, V14, E14, and total energy.
"""
vdw, ... | 1cd0fab9342baa70f1ac96bcb917a1f1586a16a7 | 652,351 |
def has_ipv4(network_resource):
"""
Args:
network_resource:
Returns:
"""
for pep in network_resource.public_endpoints:
if pep.version == 4:
return True
return False | 13b28d878b9216a51129d183f1a734b5dd4cc070 | 652,352 |
import re
def changeAllAttributesInText(text, attribute, newValue, append):
"""
Changes the specified attribute in all tags in the provided text to the
value provided in newValue. If append is 0, the value will be replaced.
If append is anything else, the value will be appended to the end
of the o... | 4da10f29eaa032c5d44ba40d9776d66fb1ae59f2 | 652,353 |
def make_count_column(array):
"""Make column name for arrays elements count
>>> make_count_column('/tender/items')
'/tender/itemsCount'
>>> make_count_column('/tender/items/additionalClassifications')
'/tender/items/additionalClassificationsCount'
>>> make_count_column('/tender/items/')
'/t... | fe3dcfb5077e0293e74fc299189d7b09cf0f9249 | 652,354 |
def _float_callback(element, compiler, **kw):
"""Changes all FLOAT types to real"""
return "real" | b89802c852523fec7774af92dd7e9a536c1d511f | 652,355 |
def camelcase(s):
"""Turn strings_like_this into StringLikeThis"""
return ''.join([word.capitalize() for word in s.split('_')]) | bedb2b7a39cca2c2cb27fd24f912bc52a5bb386a | 652,356 |
import numpy
def join_cgr(cgrs: tuple) -> numpy.ndarray:
"""
Takes tuple of cgrs of shape (n,n) and returns one stacked array of size (n,n, len(cgrs) )
:param: cgrs tuple -- tuple of cgrs to be joined
:return: numpy.ndarray
"""
return numpy.dstack(cgrs) | e6608a69f9386cfab21184746e2629e40737a651 | 652,357 |
from datetime import datetime, timedelta
def check_date_past_interval(check_date, interval=None):
"""Return True if given check_date is past the interval from current time.
:param check_date: Datetime string like '2021-08-23 18:14:05'
:type check_date: str
:param interval: Hours amount to check in pa... | 8df45d0e89427e96020e3620de391afe66f7dc3c | 652,358 |
def date_tuple(ovls):
"""
We should have a list of overlays from which to extract day month
year.
"""
day = month = year = 0
for o in ovls:
if 'day' in o.props:
day = o.value
if 'month' in o.props:
month = o.value
if 'year' in o.props:
... | d63df90065fc539c428004705e46cc16820b3ed3 | 652,359 |
import numpy
def squared_distance_point_link(point, link):
"""Find the squared distance between a point and a link.
Parameters
----------
point : tuple
Point coordinates (x,y).
link : list
List of 2 point coordinate tuples [(x0, y0), (x1, y1)].
Returns
-------
... | f4d1ac8e468e3ec31c0837a8d7c31e19f2e76732 | 652,360 |
def generate(script_path=None):
"""
Generates a copy & paste configuration for the VS Code launch.json
"""
if not script_path:
script_path = ""
path = str(script_path)
path_without_py = path if not path.endswith('.py') else path[0:-3]
if not path_without_py:
path_without_py = '<ADD-PYTHON-EXECUT... | b91341556fa13880a756633802df20eab00561e2 | 652,361 |
def fix_negatives(num):
"""
Some scopes represent negative numbers as being between 128-256,
this makes shifts those to the correct negative scale.
:param num: an integer
:return: the same number, shifted negative as necessary.
"""
if num > 128:
return num - 255
else:
re... | b8e5694c96d8199e9488940bd5f47d1da9f0800e | 652,362 |
def identifyCategoricalFeatures(x_data,categorical_cutoff):
""" Takes a dataframe (of independent variables) with column labels and returns a list of column names identified as
being categorical based on user defined cutoff. """
categorical_variables = []
for each in x_data:
if x_data[each].nuni... | 531eb49871155b5042de08b0c7b3189a15e55ca2 | 652,363 |
def _net_get_tx_id(id_offset: int, index: int) -> int:
"""
Returns the transmission id of a board, given its type's start_id and its index.
"""
return 2 * (id_offset + index) | 0e4531054cefcdd01d0d04f960a60b8e634424d4 | 652,364 |
def extract_memory_position(argument):
"""
Extract a memory position from a memory index argument.
See :func:`~.is_memory_index` for details of what a memory index is.
Args:
argument (str): The argument to extract a memory position from.
Returns:
str: The location in memory being r... | 6e30f2bf55d058263766985df2ad49db97cd8b9b | 652,365 |
import pickle
def read_results(pickle_file_name):
"""Reads results from Pickle file.
:param pickle_file_name: Path to input file.
:return: result_dict: Dictionary created by `run_sfs`.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
result_dict = pickle.load(pickle_file_handle)
pic... | 9909ef3100e3b976eb2cc4346e8a02370556b35b | 652,366 |
import os
def testing_args():
"""
arguments for testing.
:return: test arguments
"""
return {'test_flight_logs_path': os.path.join(os.path.dirname(__file__), 'flight_logs'),
'simple_test_flight_log': 'short_f450_log.ulg',
'dummy_log_file': 'short_f450_log.ulg'} | c0dc712a3f9347cac2f71c83a77b290213504701 | 652,367 |
def read_from_file(filename):
"""从文件读取数据,并返回列表格式的数据"""
with open(filename, encoding='utf-8') as f:
frl = f.readlines()
return [x.strip() for x in frl] | d1961183ebf074cbc56b136f4fe1cae319638c18 | 652,368 |
import string
def capitalize(string_raw):
"""Capitalize a string, even if it is between quotes like ", '.
Args:
string_raw (string): text to capitalize.
Returns:
string
"""
# return re.sub(r"\b[\w']", lambda m: m.group().capitalize(), string.lower())
return string.capwords(... | 7228fbf56d99c9ee0e8bf165cb3c993ef8d551c0 | 652,370 |
def trim_table(list_of_strings):
"""Make (narrow) columns with only whitespace to width 1."""
# Definitely not an efficient implementation.
table = list_of_strings
j = 0
while True:
if j==min(len(row) for row in table):
break
if all(row[j-1:j+1]==" " for row in table): # check if col has 2 s... | ae0aa040c6e25c1c1a0162fe20b52d3733a8e872 | 652,371 |
import argparse
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="SilkNOW Gradient Boosting Classifier",
usage="""sngbclassify <command> [<args>]
The available commands are:
train Train a text classification model
evaluate Ev... | af7097d87c4ebc2a9d460baf1db091598a00a602 | 652,372 |
from typing import Counter
from typing import OrderedDict
def get_stats_document(document: Counter) -> OrderedDict:
"""
Résumé
---
Pour un document donné calcule des statistiques liées à ce document comme le nombre unique de terme, la fréquence maximum
d'un terme dans le document ou la fréquence m... | afd386796324631f7a1069ae67be75fb3af4bfdd | 652,374 |
def dict_from_csv(filepath, sep=";"):
"""Read a CSV and store entries in a dict.
Warning: function is used internally. Does not work properly if quoted
cells contain separators, for example: `"ent;ry1";entry2`.
"""
with open(filepath, "r") as f:
return {
line.split(sep)[0]: line... | 547466b0c1c12b7931ff00ee092fc1e92541b68b | 652,375 |
def _apply_presets(preset_dict, *args, **kwargs):
"""
Pair with `unpack` to alter input arguments with preset values.
"""
if 'presets' in kwargs:
presets = kwargs['presets']
if presets is None:
return kwargs
if not isinstance(presets, list):
presets = [pre... | 8e1d7412d97d6cc1e57bdfef509742fb368385c6 | 652,376 |
def fastq_infer_rg(read):
"""
Infer the read group from appended read information, such as produced by the
samtools fastq command.
Requires the read to be formatted such the rg tag is added to the end of the
read name delimited by a ``_``. Returns the read group tag.
"""
rgstr = read.name.s... | a908c2a75f3a7d72e76633595d9ad62e053cd70f | 652,377 |
import argparse
def _getParser(theHelp, theEpilog):
"""
Get a commandline parser with the defaults of the commandline utils.
"""
return argparse.ArgumentParser(description=theHelp,
formatter_class=argparse.RawDescriptionHelpFormatter,
epi... | f101d948348be59d9add735bf09b019d47624ec6 | 652,378 |
import re
def replace_g5_search_dots(keywords_query):
"""Replaces '.' with '-' in G5 service IDs to support old ID search format."""
return re.sub(
r'5\.G(\d)\.(\d{4})\.(\d{3})',
r'5-G\1-\2-\3',
keywords_query
) | 3784af8c674c667e10d51bcd1b84e0df767564be | 652,379 |
import numpy
def change_interval(data, old=None, new=(0.0, 1.0)):
"""Move a matrix from one interval into another.
Parameters
----------
data : ``numpy.array``
The data points.
old : tuple (pair) of numbers or ``None`` (``None``)
The old interval for the data. If it is ``None`` the... | f56f05dcb7f9b72d54f1ddd097cdfef905ab979e | 652,380 |
def replace_tags(template, tags, tagsreplace):
"""Replace occurrences of tags with tagsreplace
Example:
>>> replace_tags('a b c d',('b','d'),{'b':'bbb','d':'ddd'})
'a bbb c ddd'
"""
s = template
for tag in tags:
replacestr = tagsreplace.get(tag, '')
if not replacestr:
... | 78b875a16940d577115eda5128475867c7454a65 | 652,381 |
def disp_corner(sc, L, ct=4):
"""
Nearest displacement along blocks of 4
"""
return min(abs((x-L*ct) - sc) for x in range(ct)) | aeb7034c60105f74894664fc172ba1ffb9f0273d | 652,382 |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
zeros = []
ones = []
twos = []
for input in input_list:
if input == 0:
zeros.append(input)
... | d39f1b7ad04913b1930acdcb9137269e11632887 | 652,383 |
def solution(H):
"""
Codility 100%
https://app.codility.com/demo/results/trainingQKD6JP-PHA/
Idea is to use stack concept
Compute the minimum number of blocks needed to build the wall.
To build the wall start taking blocks of height one by one.
We need to take care of -
- the blocked s... | 9ecc71e05f87c5de5c21b5d299cc9acc98f2555c | 652,384 |
def append_update_post_field_to_posts_list(d_included, l_posts, post_key, post_value):
"""Parse a dict and returns, if present, the desired value. Finally it
updates an already existing dict in the list or add a new dict to it
:param d_included: a dict, as returned by res.json().get("included", {})
:ty... | df14eb40d3d1305e945646171dde228de68d26a3 | 652,385 |
import requests
from bs4 import BeautifulSoup
def get_all_topics():
"""
get all topics
:return:
"""
headers = {
'referer': 'https://www.mzitu.com/best/',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, li... | c9ae814bbe42c95750541e1b454cbac9d1bfdd0d | 652,386 |
def pkcs7pad(cipher_text, block_size, value=b'\x04'):
"""Return ciphertext padded with value until it reach blocksize length.
:param cipher_text: bytes
:param block_size: int
:param value: bytes
:return: bytes
"""
length = len(cipher_text)
pad = block_size - (length % block_size)
ret... | 794a0e11e71974154423cc9039aef1ec13454a80 | 652,388 |
def GCDGood(a, b):
"""
Runtime: O(min(a, b))
"""
best = 0
min_value = min(a, b)
for d in range(2, min_value):
if not a % d and not b % d:
best = d
return best | 398c7f2208a89ad57659be5db04cc1f1708b630a | 652,390 |
def maybe_encode(value):
"""If the value passed in is a str, encode it as UTF-8 bytes for Python 3
:param str|bytes value: The value to maybe encode
:rtype: bytes
"""
try:
return value.encode('utf-8')
except AttributeError:
return value | 48588e31d7ca9a8eb09c41213eec13c13a9a3a8c | 652,391 |
def delay_error(message, etype=TypeError):
""" Return a thunk which raises an error when called. """
def dispatch_error(*_, **__):
raise etype(message)
return dispatch_error | 48ae51f94f4d2456c6e73645c18c828cbdbd10da | 652,393 |
from datetime import datetime
def timeUTCCreate():
""" () -> str
Retorna un string con la fecha actual en UTC Z.
>>> timeUTCCreate()
'2014-05-15 19:01:47.669254'
"""
return str(datetime.utcnow()) | e72683516e364bce74ab50a44ade074adbd28896 | 652,394 |
def _broadcast_params(params, num_features, name):
"""
If one size (or aspect ratio) is specified and there are multiple feature
maps, we "broadcast" anchors of that single size (or aspect ratio)
over all feature maps.
If params is list[float], or list[list[float]] with len(params) == 1, repeat
... | de1f93a8a3ab19679f1936e5d6fb581475fa1893 | 652,395 |
def h_moves_diff(gamestate):
"""
The differential in moves available to the current player. Positive values
are better than negative values for this evaluation heuristic.
"""
my_loc = gamestate._player_locations[gamestate.player()]
op_loc = gamestate._player_locations[gamestate.player() ^ 1]
... | e18765339f33c7a518f0234d0ed970acb0c91ef9 | 652,396 |
def neg_if_even(x):
"""
>>> neg_if_even(2)
-1
>>> neg_if_even(1)
1
>>> neg_if_even(0)
-1
>>> neg_if_even(-1)
1
>>> neg_if_even(-2)
-1
"""
return 1 - (x % 2 == 0) * 2 | 19498e180910cd7fa0de59ec1188b5774738e3bd | 652,397 |
def build_production_array(arr: list) -> list:
"""
Parameters
-----------
Returns
---------
Notes
------
"""
if not arr:
return arr
lenth = len(arr)
out = [1] * lenth
for i in range(1, lenth):
out[i] = out[i-1] * arr[i-1]
tmp = 1
for i in... | d7c42e82f25837b17240040fc2a8a2f56402959a | 652,398 |
def get_fort46_info(NTRII, NATM, NMOL, NION):
"""Collection of labels and dimensions for all fort.46 variables, as collected in the
SOLPS-ITER 2020 manual.
"""
fort46_info = {
"PDENA": [r"Atom particle density ($cm^{-3}$)", (NTRII, NATM)],
"PDENM": [r"Molecule particle density ($cm^{-3... | 8ea70691172399b5592f0a129945a64e4a399bf9 | 652,399 |
def command(command, threaded=False):
"""Plugin command decorator."""
def wrapper(func):
func._command = command
func._is_threaded = threaded
return func
return wrapper | 761b9e7b08d5a1d9335f88e604c00b72e0765720 | 652,400 |
import json
import struct
def rpc(sock, input, params):
"""
Send RPC request.
:param sock:
:param input:
:param params:
:return:
"""
response = json.dumps({"in": input, "params": params})
length_prefix = struct.pack("I", len(response))
sock.send(length_prefix)
sock.sendall(... | 6de774601dc328c6496efdbc75f6bc0baaa05895 | 652,401 |
def modify_axis(axs, xtick_label, ytick_label, xoffset, yoffset, fontsize, grid=True):
"""Change properties of plot axis to make more beautiful"""
axs.spines['top'].set_visible(False)
axs.spines['bottom'].set_visible(True)
axs.spines['left'].set_visible(True)
axs.spines['right'].set_visible(False)
... | 38197fc3e5121a56906b0efb6bfa08afec839b80 | 652,402 |
from typing import Any
from typing import Dict
import json
def _write_jsonl(filepath: str, data: Any, kwargs: Dict) -> Any:
"""See documentation of mpu.io.write."""
with open(filepath, "w", encoding="utf8") as outfile:
kwargs["indent"] = None # JSON has to be on one line!
if "sort_keys" not i... | ebe45eaae3b5779bd510702f7d199f923fb06f91 | 652,403 |
import functools
def protect(method):
"""
Decorator for session-methods to defer their interrupt.
"""
@functools.wraps(method)
def wrapper(obj, *args, **kwargs):
# are we already protected?
if obj._busy:
return method(obj, *args, **kwargs)
# otherwise protect th... | 03b105d83ec54bbe9a874bceef57d763baa69c72 | 652,404 |
import torch
def make_loss(content_weight, style_weight, content_image_content, style_image_style, content_loss_fn, style_loss_fn, Ns, Ms):
"""
Creates our loss function
"""
def loss(generated_image_content, generated_image_style):
"""
The total loss is a linear combination between th... | 66b99aaf2abfb693e74c40d7f83cecae77c51693 | 652,405 |
def binary_tp(gold, pred):
"""
for each member in pred, if it overlaps with any member of gold,
return 1
else
return 0
"""
tps = 0
for p in pred:
tp = False
for word in p:
for span in gold:
if word in span:
tp = True
... | 03985d278c8963bcb094a6b7537d3f6d9a435d3b | 652,406 |
def remove_trailing_characters_from_list(element_list, char_list):
"""
This function removes trailing characters from a all strings in a list
Args:
element_list: list of strings to be formatted
char_list: List of characters to be removed from each string in the list
Returns:
ele... | b63e188a895ded71c513bbcc629002f60c1847f3 | 652,408 |
def norm_text_angle(a):
"""Return the given angle normalized to -90 < *a* <= 90 degrees."""
a = (a + 180) % 180
if a > 90:
a = a - 180
return a | 424df499823743144567c83cc44d9fa809710613 | 652,409 |
def linear_increase(low_bound, up_bound, percentage):
"""low_bound + [0, 1] * (up_bound - low_bound)"""
assert 0 <= percentage <= 1, f"percentage({percentage}) must be in [0, 1]"
return low_bound + (up_bound - low_bound) * percentage | 68fdcb2d2e4b30841dbd5904ffee525cdabdaa2b | 652,411 |
import sympy
def is_quad_residue(n, p):
"""
Returns True if n is a quadratic residue mod p.
"""
return sympy.ntheory.residue_ntheory.is_quad_residue(n, p) | e4f9e820c88fc3c696d6157581d1392a30eda449 | 652,412 |
import collections
def create_embedding_map(reverse_vocab, embedding_matrix):
"""Returns a dictionary mapping word to word embedding."""
return collections.OrderedDict(zip(reverse_vocab, embedding_matrix)) | 4649a6b605a82e40d68f3f99efb86440b805aab7 | 652,413 |
def dir(p_object=None): # real signature unknown; restored from __doc__
"""
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attribute... | c9b21689037760f6c7c9d19d32acc918814fc049 | 652,414 |
import io
def fread(file_path):
"""Read data from file"""
with io.open(file_path, "r", encoding="utf8") as f:
return f.read() | f0c6ce8782e1921d6a1fef4b7c9063437315f4dc | 652,415 |
from typing import Dict
from typing import Any
def _get_revshell_item(item: Dict[str, Any], obfuscated: bool) -> Dict[str, Any]:
"""Get an item."""
builder = item["builder"] if "builder" in item else []
data = {
"name": item["name"],
"desc": item["desc"],
"info": item["info"],
... | 42d6fe5f84acfb6c048127d33a2da499bab51dea | 652,416 |
import numpy
def antisymm_four_body(h4e: numpy.ndarray) -> numpy.ndarray:
"""Given a four body matrix, perform antisymmeterization on the elements.
Args:
h4e (numpy.ndarray): Inumpyut 4-body tensor.
Returns:
numpy.ndarray: Output 4-body tensor.
"""
assert len(h4e.shape) == 8
... | 4d179317901518c59dd9f589fc7e3a84687ac4a4 | 652,417 |
def action(maximize, total_util, payoffs):
"""
>>> action(True, 0.9, [1.1, 0, 1, 0.4])
0
>>> action(True, 1.1, [1.1, 0, 1, 0.4])
1
>>> action(False, 0.9, [1.1, 0, 1, 0.4])
0.9
"""
if maximize:
return int(total_util > payoffs[2])
else:
return total_util | bd57083666ff80469f53a578c6290876b68052ab | 652,418 |
def is_sorted(array):
"""
Check if an array is sorted in ascending order (assumes an array of numbers, such as integers or float)
:param array: the array to be checked
:return: a message ("Array is sorted" or "Array is not sorted")
"""
return "Array is %ssorted" % ('not ' if sorted(array) != lis... | 40cc27dc8685d5fbc581f0df3a3c4714761d295e | 652,419 |
def clean_view(view_orig, superunits):
"""
Define a view of the system that comes from a view of another one.
Superunits are cleaned in such a way that no inconsistencies are present
in the new view.
Args:
view_orig (dict): the original view we would like to clean
superunits (list): l... | f5042d1cedd51d72524f177b00cf3c0635729381 | 652,420 |
def bounds(total_docs, client_index, num_clients, includes_action_and_meta_data):
"""
Calculates the start offset and number of documents for each client.
:param total_docs: The total number of documents to index.
:param client_index: The current client index. Must be in the range [0, `num_clients').... | 0d517300f10aaa511f341f2e8214a70739d8640e | 652,421 |
def int2iso_reference(n):
"""Calculates checksum (and adds the RF prefix) for an international reference number"""
n = int(n)
nt = n * 1000000 + 271500
checksum = 98 - (nt % 97)
return "RF%02d%d" % (checksum, n) | 5050283451afc9953b89683a9ae1a05d6279b365 | 652,422 |
def list_to_ext_header(strings):
"""
turns a list of strings into a string suitable for a header
"""
# ODfE expects the header to be a comma-delimited list of strings,
# each string quoted
quoted = [f'"{string}"' for string in strings]
header = ", ".join(quoted)
return header | 41d76199d8f86fc66a7f441f0d7d54ad40ec95bf | 652,423 |
def pci_bands():
"""
Sentinel-2 bands
Band 1 – Coastal aerosol 442.7 21 442.2 21 60
Band 2 – Blue 492.4 66 492.1 66 10
Band 3 – Green 559.8 36 559.0 36 10
Band 4 – Red 664.6 31 664.9 31 10
Band 5 – Vegetation red edge 704.1 15 703.8 16 20
Band 6 – Vegetation red edge 740.5 15 739.1 15 20... | cd30b5b01e97eba8a7e0f625233a7af57aa6032e | 652,424 |
def is_valid_coordinate(x0: float, y0: float) -> bool:
"""
validates a latitude and longitude decimal degree coordinate pairs.
"""
if isinstance(x0, float) and isinstance(y0, float):
if -90 <= x0 <= 90:
if -180 <= y0 <= 180:
return True
return False | c2833a2786515aa218c329686b3ea4c29b32dc2d | 652,425 |
def fibonacci_py(v):
""" Computes the Fibonacci sequence at point v. """
if v == 0:
return 0
if v == 1:
return 1
return fibonacci_py(v - 1) + fibonacci_py(v - 2) | 4db3932fd1aa9d8a431d2d3b5861c3cf89f3bde4 | 652,426 |
import platform
def platform_combine(*args, is_file):
"""This function combines multiple path elements use when os.path.join doesn't work """
def get_platform_slash():
return '\\' if platform.system() == 'Windows' else '/'
platform_path = ''
if is_file:
for i in range(le... | baac088c55ad6dd6622378c52de74de85298fb91 | 652,428 |
from urllib.parse import parse_qs, urlparse
def get_key(url, key="request_token"):
"""
Get the required key from the query parameter
"""
req = urlparse(url)
key = parse_qs(req.query).get(key)
if key is None:
return None
else:
return key[0] | 901372abc017c9527713bdf782f09d9bb620ac4b | 652,429 |
import six
def get_varval_from_locals(key, locals_, strict=False):
"""
Returns a variable value from locals.
Different from locals()['varname'] because
get_varval_from_locals('varname.attribute', locals())
is allowed
"""
assert isinstance(key, six.string_types), 'must have parsed key into ... | 9bd7ef67b58f561fe3e2594e50592c8e5e4227ef | 652,430 |
def Segments(n):
"""
n has to be greater than 3
"""
# divide Segment into 2 sub Segments
if n % 2 == 0:
n_1 = n / 2
n_2 = n / 2
else:
n_1 = (n + 1) / 2
n_2 = n - n_1
# determine the checking point index of the two sub Segments
if n_1 % 2 == 0:
n_1_checking_point = n_1 / 2
else:
... | 87f9d8a6f8cc454d613547583c5e385f35b3b7b8 | 652,431 |
def train_reformat(train_Xy):
"""
Group train_Xy into articles, with a dictionary containing true and false rows
"""
xy = {}
for row in train_Xy:
p_id = row['p_id']
sentences = row['sentence_span']
t = [] # for when the labels are true
f = [] # for when the labels are... | e4a268b8700d8ecebe0633f09cdb0649b8a05434 | 652,432 |
def f():
""" -> int """
42 + 2
return 42 | db5ad21845bc501775b69071850683300d63f312 | 652,433 |
import os
def _normalize(filename):
""" .. function:: _normalize(filename)
Prepends the filename with the path pointing to the main file.
:type filename: string
:rtype: string
"""
abs_path = os.path.abspath(__file__)
dir_name = os.path.dirname(abs_path)
return os.path.join(dir_name, ... | e4c1b8ce9675dbbca504aa5bc0acc18c69352590 | 652,434 |
def by_data():
"""
:return:
a key function that returns a message's ``data`` field.
"""
return lambda msg: msg['data'] | c8b987883770710ef8534f979df1279d623600b5 | 652,435 |
def _calculate_pages_number(per_page, records_count):
"""Return pages number.
:param per_page: (int) results number fot one page.
:param records_count: (int) total records count.
"""
quotient, remainder = divmod(records_count, per_page)
if remainder > 0:
return quotient + 1
return q... | 08d598b972e22b55f134a2dce97907797074169e | 652,436 |
import math
def rotate(v1, angle):
"""
rotates the vector by an angle around the z axis
:param v1: The vector that will be rotated
:param angle: The angle to rotate the vector by
:return: The vector rotated around the z axis by the angle
"""
x, y, z = v1
# Rotation transformation
... | 7d71f8c7126122f13ea99b3cde4a03d6a0605757 | 652,437 |
def is_waiting_state(state, num_of_servers):
"""Checks if waiting occurs in the given state. In essence, all states (u,v)
where v > C are considered waiting states.
Set of waiting states: S_w = {(u,v) ∈ S | v > C}
Parameters
----------
state : tuple
a tuples of the form (u,v)
num_o... | 335b488f52688baa606928ee137cfb189ee36434 | 652,438 |
from typing import OrderedDict
def map_to_sql(sql_type, column_dict):
"""
Converts soct_type_map to be readable by Civis API.
"""
sql_map = OrderedDict({k: sql_type[v] for k, v in column_dict.items()})
return sql_map | 800ade3e09070416dd427bb87e43176ae6c5f507 | 652,439 |
def get_DNA_seq(mutant_position, all_lines):
"""
Get the DNA lines as a list knowning the mutant position.
:param all_lines = [str]
:param mutant_position: int
:rtype: [str]
"""
dna_lines = []
for i in range(mutant_position + 2, len(all_lines)):
line = all_lines[ i ]
if... | e8082907a95ed3a131c0b54f8ec53361398dd486 | 652,440 |
def attributes(instance):
"""Return all constant attributes of an instance.
This skips over things that require executing code such as properties.
"""
i, t = ( set(dir(_)) for _ in (instance, instance.__class__))
result = {}
for k in i:
v = getattr(instance.__class__, k, callable)
... | 9644d6214e3f8eadef59f6e5f31517d833d1fa49 | 652,441 |
import bz2
def bz2_open(file_name, mode):
"""
Wraps bz2.open to open a .bz2 file.
Parameters
----------
file_name : str
mode : str
Returns
-------
file
Raises
------
RuntimeError
If bz2 is not available.
"""
assert mode in ('r', 'w')
if bz2 is None:
raise RuntimeError('bz2 m... | 79ff4c0284b585a8082e1360ac2b87e114c1ebba | 652,442 |
def _get_remote_field(field):
"""
Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field')
"""
if hasattr(field, 'remote_field'):
return field.remote_field
elif hasattr(field, 'related'):
return field.related
else:
return None | cb61617447b083c042295d1eb63d3c077ab3cd11 | 652,443 |
def sanitize_gene_col(metadata_df, gene_col, control_barcodes):
"""
Sanitize metadata information
Arguments:
metadata_df - a pandas dataframe storing at least a column indicated by gene_col
gene_col - the column to sanitize
control_barcodes - a list of entries in the gene column to ignore sanit... | 35d767958f29169589ebf7d74a1c37a09b711d9a | 652,444 |
def get_parameter_list_from_force(force, paramlist):
"""Create a function that returns the paramters of a function type.
First, we need make some additions to the parameter list dictionary,
which we do once when the forcedata script is imported. Useful to
put the forces here as well. We won't make th... | 2749bbb5731e5945b7344de6b5053d1786a7b81a | 652,445 |
def fix_colwidth(n_columns, width_str="MAKE COLUMN THIS WIDE"):
"""adds a hidden row to the bottom of the table with text width_str, forcing each
column to be at least as wide as width_str"""
html = """<tr>
<th class="colwidth" rowspan=1></th>
<th></th>
"""
for _ in range(n_col... | d681a2cc39ca6695d6573efbc6bce2df9c67a4a4 | 652,446 |
def convert_str_list(my_string):
"""
Function to convert from string to list.
The create_set() function requires a specific input.
Parameters
----------
my_string : str
Input string.
Returns
-------
list
The input string converted to list.
"""
return my_str... | 27ff81ad1c0c408e6fcb37fc813cf844e8fab436 | 652,447 |
def create_composition_of_transformations(input_functions):
"""Function to create a composition of transformations.
Args:
input_functions (list): list with the following shape:
[transformation_function_1, untransform_point_function_1, transformation_function_2, untransform_point_function_2,... | 32b92f77d7be012a6b844f84de76e1d22b562c46 | 652,448 |
def reshape_fortran(tensor, shape):
"""The missing Fortran reshape for mx.NDArray
Parameters
----------
tensor : NDArray
source tensor
shape : NDArray
desired shape
Returns
-------
output : NDArray
reordered result
"""
return tensor.T.reshape(tuple(rever... | 4b4afc1fb30507213d7ecb6869cc07aa33f75d88 | 652,449 |
from typing import List
def max_amount_dp(row: List[int]) -> int:
"""
Max(i, j) = Max(
row[i] + min(Max(i+2, j), Max(i+1, j-1)),
row[j] + min(Max(i+1, j-1), Max(i, j-2))
)
"""
size = len(row)
max_amount = [[0] * size for _ in range(size)]
for index in range(size):
... | ee2c8936106c9c4e1903ac69b0c65c86da8a0812 | 652,450 |
def get_non_conflicting_name(template, conflicts, start=None, get_next_func=None):
""" Find a string containing a number that is not in conflict with any of
the given strings. A name template (containing "%d") is required.
You may use non-numbers (strings, floats, ...) as well. In this case
... | 9ec399179144ac651d55c8e645de1901805097ae | 652,451 |
def onebindingsite(x, A, B, C, D):
"""One binding site model
y = A * x / (B + x) + C * x + D
A is max
B is Kd
C is nonspecific
D is background
"""
return A * x / (B + x) + C * x + D | 540280a89a94bd115325d3592c560dc079355b15 | 652,452 |
from typing import Tuple
import re
import warnings
def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
"""Parse glibc version.
We use a regexp instead of str.split because we want to discard any
random junk that might come after the minor version -- this might happen
in patched/forked vers... | 547df79704865287060b07742a5a1fb0f589da3e | 652,453 |
def cutting_rope(l_rope):
"""
:param l_rope: length of rope
:return: max of mul
"""
if l_rope < 2:
return 'Invalid Input'
max_mul = [0, 1, 2, 3] + [0]*(l_rope-3)
for l in range(4, l_rope+1):
max_mul[l] = max(max_mul[res] * max_mul[l-res] for res in range(1, l-1))
return m... | f001bf7a1b5aecf3a55418d52f8808b0320ea7f9 | 652,454 |
from typing import Optional
def decode_cookies(string_to_decode: Optional[str] = None) -> Optional[str]:
"""
Decode the latin-1 string, and encode it to utf-8.
Args:
string_to_decode: string to decode
Returns:
Optional[str]: decoded string
"""
if string_to_decode:
ret... | f2b3b06af321a0e168d4075ea287c51f0392c824 | 652,455 |
def remove_characters_from_entities(characters, entities):
"""
Consolidate character and entities found by removing characters from entities.
Parameters:
characters: list of the characters found
entities: list of the entities found
Returns:
updated characters and entities lists
""... | 20d74e8b72f25df8780d1f57a62caa1ad3924725 | 652,456 |
def websafe(s):
"""return a string with HTML-safe text"""
s=s.replace("<","<").replace(">",">")
s=s.replace(r'\x',r' \x')
s=s.replace("\n","<br>")
return s | 05e6c78b4f373196a939cf99018a282a3bbc715d | 652,457 |
import os
import shutil
def ArchiveFile(file_to_archive, archive_dir):
"""Archives the specified file.
Args:
file_to_archive: Full path to file to archive.
archive_dir: Local directory for archiving.
Returns:
The base name of the archived file.
"""
filename = os.path.basename(file_to_archive)
... | 6c7f1e2e80035451cffd4fea2b4b17c87f1c42dc | 652,458 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.