content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def homo_line(a, b):
"""
Return the homogenous equation of a line passing through a and b,
i.e. [ax, ay, 1] cross [bx, by, 1]
"""
return (a[1] - b[1], b[0] - a[0], a[0] * b[1] - a[1] * b[0]) | 44888650c16d2a48b2a60adaf9e9bd89e0a0de67 | 691,056 |
from unittest.mock import call
def get_local_jitter(sound, min_time=0., max_time=0., pitch_floor=75., pitch_ceiling=600.,
period_floor=0.0001, period_ceiling=0.02, max_period_factor=1.3):
"""
Function to calculate (local) jitter from a periodic PointProcess.
:param (parselmouth.Sound... | ba9302f7593f9d324193ba8be6b64982b515e878 | 691,057 |
def anchor_ctr_inside_region_flags(anchors, stride, region):
"""Get the flag indicate whether anchor centers are inside regions."""
x1, y1, x2, y2 = region
f_anchors = anchors / stride
x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5
y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5
flags = (x >= x1) &... | 5f1e3b764145a9ee8abb709cd43f7f99c8515eb7 | 691,059 |
def getTeamDistribution(bot, guildId, scores, names=False):
"""
@param bot the instance of the running bot in use by the calling function
@param guildId the Guild ID in use by the calling function
@param scores the scores dictionary that also tracks active teams
@return teamDistribution Dictionary o... | 65557f6b9e68771b1f380eb05ff631aaafa68d03 | 691,060 |
def createJSON(f, node, gap):
"""Creates JSON file by starting at root node and recursively adding children nodes
Parameters:
f (file) Output JSON file
node (Node) A node in our custom made tree datastructure
gap (int) Counts the spaces for indentation for JSON format
Returns:
... | ff5756d19c6869fcce1ccbb9811b55eeb34a004a | 691,061 |
def position_is_escaped(string, position=None):
"""
Checks whether a char at a specific position of the string is preceded by
an odd number of backslashes.
:param string: Arbitrary string
:param position: Position of character in string that should be checked
:return: True if the char... | 8fbaa26a6fb56f56819e5937a921efa3a6882627 | 691,062 |
def select_column_values(df, col_name="totale_casi", groupby=["data"], group_by_criterion="sum"):
"""
:param df: pandas dataFrame
:param col_name: column of interest
:param groupby: column to group by (optional) data.
:param group_by_criterion: how to merge the values of grouped elements in col_nam... | cb0d63fa3c29447353163ae8336eb42f6f454ced | 691,063 |
import inspect
def is_classmethod(fn):
"""Returns whether f is a classmethod."""
# This is True for bound methods
if not inspect.ismethod(fn):
return False
if not hasattr(fn, "__self__"):
return False
im_self = fn.__self__
# This is None for instance methods on classes, but Tru... | 92513cb832f9e9e1d6197ed06f7ff4e8f2de108b | 691,064 |
import warnings
def gradient(simulation):
"""Deprecated, moved directly to `emg3d.Simulations.gradient`."""
msg = ("emg3d: `optimize` is deprecated and will be removed in v1.4.0."
"`optimize.gradient` is embedded directly in Simulation.gradient`.")
warnings.warn(msg, FutureWarning)
return s... | 7fb640997c09d75bd82124f3f77d6b3a154ae5f2 | 691,065 |
import socket
def is_unbind_port(port, family=socket.AF_INET, protocol=socket.SOCK_STREAM):
"""check is bind port by server"""
try:
with socket.socket(family, protocol) as sock:
sock.bind(("127.0.0.1", port))
return True
except socket.error:
return False | 298869dbeb73ec0dcdb24fce15f216e5055c1507 | 691,066 |
from typing import Iterable
from functools import reduce
def prod(data: Iterable[int]) -> int:
"""
>>> prod((1,2,3))
6
"""
return reduce(lambda x, y: x*y, data, 1) | c51c988e18a7eb7d00d16a6d17a328f8d89e43a0 | 691,068 |
def normalize_min_max(x, x_min, x_max):
"""Normalized data using it's maximum and minimum values
# Arguments
x: array
x_min: minimum value of x
x_max: maximum value of x
# Returns
min-max normalized data
"""
return (x - x_min) / (x_max - x_min) | e31028c84603d0fc6d1ad00b768fb6373aee975c | 691,069 |
def get_orientation_from(pose):
""" Extract and convert the pose's orientation into a list.
Args:
pose (PoseStamped): the pose to extract the position from
Returns:
the orientation quaternion list [x, y, z, w]
"""
return [pose.pose.orientation.x,
pose.pose.orientation.y... | 2c3116c4070779511df54f0aafd488d22bc1c94b | 691,072 |
import string
def index_to_column(index):
"""
0ベース序数をカラムを示すアルファベットに変換する。
Params:
index(int): 0ベース座標
Returns:
str: A, B, C, ... Z, AA, AB, ...
"""
m = index + 1 # 1ベースにする
k = 26
digits = []
while True:
q = (m-1) // k
d = m - q * k
digit = stri... | 2d1b1018e91e3408aee7e8adbe51ea2e9867bd45 | 691,073 |
def version():
"""Get the driver version from doxygenConfig.
"""
with open("doxygenConfig") as f:
for line in f.readlines():
if line.startswith("PROJECT_NUMBER"):
return line.split("=")[1].strip() | 7075722182ea80de25d88cd82323207340d086a6 | 691,074 |
def _monkeypatch(obj, enter, exit):
"""
Python, why do you hate me so much?
>>> class A(object): pass
...
>>> a = A()
>>> a.__len__ = lambda: 3
>>> a.__len__()
3
>>> len(a)
Traceback (most recent call last):
...
TypeError: object of type 'A' has no len()
"""
clas... | ba97b6dceeb88e857b8bdd7ec5863d2707dd12de | 691,075 |
def _listen_count(opp):
"""Return number of event listeners."""
return sum(opp.bus.async_listeners().values()) | b342b040292ab846206d46210f834fef042af3b4 | 691,076 |
def ensembl_column_key(c):
"""
:param c:
:return:
"""
cols = {'chrom': 0, 'start': 1, 'end': 2, 'name': 3,
'score': 4, 'strand': 5, 'feature': 6,
'feature_type': 7, 'gene_name': 8}
return cols.get(c, 9) | 3518d4494d465b6c3754c9bc0728d3b224d21440 | 691,080 |
import math
def distance(point1, point2):
""" Calculates distance between two points.
:param point1: tuple (x, y) with coordinates of the first point
:param point2: tuple (x, y) with coordinates of the second point
:return: distance between two points in pixels
"""
return math.sqrt(math.pow(po... | e38be3e5cc3418ab8c5edefb560e95e583dede21 | 691,082 |
def upilab6_5_3 () :
"""6.5.3. Exercice UpyLaB 6.12 - Parcours vert bleu rouge
Écrire une fonction belongs_to_file(word, filename) qui reçoit deux chaînes de caractères en paramètre. La première
correspond à un mot, et la deuxième au nom d’un fichier contenant une liste de mots, chacun sur sa propre ligne. La
fonct... | a8da479192e96259f28193e7818417f6392b8210 | 691,083 |
from typing import List
from typing import Set
def scan_polarimeter_names(group_names: List[str]) -> Set[str]:
"""Scan a list of group names and return the set of polarimeters in it.
Example::
>>> group_names(["BOARD_G", "COMMANDS", "LOG", "POL_G0", "POL_G6"])
set("G0", "G6")
"""
res... | d4ae998041401beb40df7746ec0afc2b98c9d6b1 | 691,084 |
from typing import Dict
def delete_nulls(dct: Dict, only_none: bool = False) -> Dict:
"""Delete null keys in a dictionnary.
Args
only_none: If True, only None keys are deleted.
Otherwise delete all None, False, 0. Default to False.
Returns
A dictionnary without empty values
... | 217c2a1770fecaf1c7bc763a20120b273f7dff56 | 691,085 |
def hello_world():
"""
A function to make sure the app is running during initial testing
"""
return "Hello world!" | b7faa3f12ff6c11041bd8824dae1b87526a75c57 | 691,086 |
def is_prefix(needle, p):
"""
Is needle[p:end] a prefix of needle?
"""
j = 0
for i in range(p, len(needle)):
if needle[i] != needle[j]:
return 0
j += 1
return 1 | 81e20f65ff4ea8d9a152c51f6204f4e0a2c26552 | 691,087 |
def get_project_folders(window):
"""Get project folder."""
data = window.project_data()
if data is None:
data = {'folders': [{'path': f} for f in window.folders()]}
return data.get('folders', []) | d3bc83067e4acdf0df1a29891cebcb60422fe5e6 | 691,088 |
import textwrap
def dedented_lines(description):
"""
Each line of the provided string with leading whitespace stripped.
"""
if not description:
return []
return textwrap.dedent(description).split('\n') | 8a398b0afe6aa1f9cdf5f4ae386ecebef06bdd2b | 691,090 |
def behavior_get_required_inputs(self):
"""Return all required Parameters of type input for this Behavior
Note: assumes that type is all either in or out
Returns
-------
Iterator over Parameters
"""
return (p for p in self.get_inputs() if p.property_value.lower_value.value > 0) | 13063f7708d518928aed7556ca9da7a851de6622 | 691,091 |
import os
def cache_filename(*, user_id, pageno, datatype):
"""Get filename for local cached page of Flickr data.
user_id = Flickr user ID
pageno = page #
datatype = 'tags' or 'photostream'
Returns the filename to be used for reading/writing this cached data.
"""
filename = user_id + '-'... | 4998246f5ec79eb27449ce5b2bedb30aa2f710c2 | 691,093 |
def features_to_components(features, W, mu):
"""from feature space to principal component space"""
centered_X = features - mu
return W @ centered_X.T | 55308368c7cec010dc0fc2f9dc949fd58f9f9d88 | 691,095 |
def _AddNGrad(op, grad):
"""Copies the gradient to all inputs."""
# Not broadcasting.
return [grad] * len(op.inputs) | 9cbeee4a863b44e45475b4161fdc7b94f576005a | 691,097 |
def audio_uri():
"""Provide some handy audio file locations."""
return {
'RADIO': 'http://ice1.somafm.com/groovesalad-256-mp3',
'SONG': ''.join([
'https://archive.org/download/',
'gd1977-05-08.shure57.stevenson.29303.flac16/',
'gd1977-05-08d02t04.flac'
... | 84e2f32c4e64807932b89944c84d592d92eb17cf | 691,098 |
import os
def edit_filename(filename, prefix="", suffix="", new_ext=None):
"""
Edit a file name by add a prefix, inserting a suffix in front of a file
name extension or replacing the extension.
Parameters
----------
filename : str
The file name.
prefix : str
The prefix to ... | a06dd32d448b22350d9b11b0f1cea2e07eb5b7e1 | 691,099 |
def oneof(*args):
"""Returns true iff one of the parameters is true.
Args:
*args: arguments to check
Returns:
bool: true iff one of the parameters is true.
"""
return len([x for x in args if x]) == 1 | 14731b54f19658d25ca3e62af439d7d2000c1872 | 691,100 |
import warnings
from typing import Optional
from typing import Union
from typing import Type
from typing import cast
def _is_unexpected_warning(
actual_warning: warnings.WarningMessage,
expected_warning: Optional[Union[Type[Warning], bool]],
) -> bool:
"""Check if the actual warning issued is unexpected."... | 7b4be666af4f963ef94758d5061224e2806b60ca | 691,101 |
import torch
def get_pose_loss(gt_pose, pred_pose, vis, loss_type):
"""
gt_pose: [B, J*2]
pred_pose: [B, J*2]
vis: [B, J]
Loss: L2 (MSE), or L1
"""
vis = torch.repeat_interleave(vis, 2, dim=-1) # [B, 1122...JJ]
if loss_type == "L2":
loss = torch.sum((gt_pose - pred_pose) ** ... | 2cedc132ec5e6fc9870ba3439b756d7b421486d6 | 691,102 |
def wrap_cdata(s: str) -> str:
"""Wraps a string into CDATA sections"""
s = str(s).replace("]]>", "]]]]><![CDATA[>")
return "<![CDATA[" + s + "]]>" | 861d086e77b02c354815da11278fc0c3b6297a68 | 691,103 |
def get_uptime():
"""
Returns the uptime in seconds.
"""
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
return uptime_seconds | 5f0602c8fca534874b26d76d90f50577eda37532 | 691,104 |
import re
def clean_statement(string):
"""
Remove carriage returns and all whitespace to single spaces
"""
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
return _RE_COMBINE_WHITESPACE.sub(" ", string).strip().upper() | 6db3d1aff2c388d902cfd2a443d0c0b5a8fd7e12 | 691,105 |
def get_spacing_groups(font):
"""
Return a dictionary containing the ``left`` and ``right`` spacing groups in the font.
"""
_groups = {}
_groups['left'] = {}
_groups['right'] = {}
for _group in list(font.groups.keys()):
if _group[:1] == '_':
if _group[1:5] == 'left':
... | 778a27b49ce9d869d7867774df8dfe22a3cd6140 | 691,106 |
def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction.qargs:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
... | b85b1a0e5dd6691e9b460dea90cb205ce46227e9 | 691,107 |
import random
def breed(males, females, offspring_amount):
"""Breed the stonger males and females"""
#This one is pretty self explanitory.
random.shuffle(males)
random.shuffle(females)
children = []
for male, female in zip(males, females):
for child in range(offspring_amount):
... | a6bd7f385baf32e365ae63149471abb1a90ceb9a | 691,108 |
def get_AP_parameters(exp):
"""
This function is connect with'Advanced Parameter' button.
Parameters
------
exp: the Ui_Experiment object
Return
------
AP_parameters: list contains all the advanced parameters
"""
conv_fact = float(exp.experiment_conversion_factor.text(... | 079759600626e3c7cbb4fee882d1b9623a1f4a43 | 691,109 |
import requests
def read_data_json(typename, api, body):
"""
read_data_json directly accesses the C3.ai COVID-19 Data Lake APIs using the requests library,
and returns the response as a JSON, raising an error if the call fails for any reason.
------
typename: The type you want to access, i.e. 'Ou... | b0aed423512408efa97e0f5cf406bb442b876a3d | 691,110 |
def consider_ascending_order(filtering_metric: str) -> bool:
"""
Determine if the metric values' sorting order to get the most `valuable` examples for training.
"""
if filtering_metric == "variability":
return False
elif filtering_metric == "confidence":
return True
elif filtering_metric == "thresho... | 749a5d1de19ca131c86f49a8cadeb983473f399f | 691,111 |
def version_tuple_to_string(version_tuple):
"""
Parameters
----------
version_tuple : tuple of int
the version, e.g, (1, 0) gives 1.0; (0, 2, 3) gives 0.2.3
"""
return ".".join([str(x) for x in version_tuple]) | cab4322172242d3e0040ff70b73d5f7a124987aa | 691,113 |
def matrix_from_vectors(op, v):
"""
Given vector v, build matrix
[[op(v1, v1), ..., op(v1, vn)],
...
[op(v2, v1), ..., op(vn, vn)]].
Note that if op is commutative, this is redundant: the matrix will be equal to its transpose.
The matrix is represented as a list of lists.
... | cfefaf9e66db33e993044b2cc609f25f89e103ea | 691,114 |
def get_listOfPatientWithDiagnostic(diagnostic):
"""
IN PRGRESS
-> get the list of OMIC ID for patients
matching diagnostic
-> diagnostic is a string, could be:
- Control
- RA
- MCTD
- PAPs
- SjS
- SLE
- SSc
- UCTD
-> return a list of OMIC ID
"""
patientIdList = []
inde... | 4b212f82b3d257b91c1470632c048f504c1b41ea | 691,115 |
def get_interface_type(interface):
"""Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF..."""
if interface is None:
return None
iftype = None
if interface.upper().startswith('GE'):
iftype = 'ge'
elif interface.upper().startswith('10GE'):
iftype = '10ge'
elif ... | f57115c1189a38bc911a5eec0ee623fe6c5bc6a2 | 691,117 |
import os
import pwd
def get_home_dir():
"""Return the user's home directory."""
home = os.environ.get('HOME')
if home is not None:
return home
try:
pw = pwd.getpwuid(os.getuid())
except Exception:
return None
return pw.pw_dir | b6a2568e2c3b0e3d006f4d837a52f44ea3ff003a | 691,118 |
def createVocabList(dataSet):
"""
获取所有单词的集合
:param dataSet: 数据集
:return: 所有单词的集合(即不含重复元素的单词列表)
"""
vocabSet = set([]) # create empty set
for document in dataSet:
# 用于求两个集合的并集
vocabSet = vocabSet | set(document) # union of the two sets
return list(vocabSet) | cb8d3c29deac4cd5161d46adf0deb58c94b1a18f | 691,119 |
def create_user(connection, body, username, fields=None):
"""Create a new user. The response includes the user ID, which other
endpoints use as a request parameter to specify the user to perform an
action on.
Args:
connection(object): MicroStrategy connection object returned by
`con... | c4f11b3b39ba2a84417ca667ab1d66e978d33bd3 | 691,120 |
from typing import Callable
from typing import Tuple
import time
def measure_time(method: Callable) -> Callable:
"""
A method which receives a method and returns the same method, while including run-time measure
output for the given method, in seconds.
Args:
method(Callable): A method whose r... | 49bf1c6676ee4e9a5c4d6e4e1b62a6f7068fd1f8 | 691,121 |
def plus_all(tem, sum):
"""
:param tem:int, the temperature user entered.
:param sum:int, the sum of temperatures user entered.
This function plus all temperatures user entered.
"""
return sum+tem | 187d81f2bbebc2a21e6a23a297c56550216141fa | 691,122 |
def check_input(saved_input):
"""Checks for yes and no awnsers from the user."""
if saved_input.lower() == "!yes":
return True
if saved_input.lower() == "!no":
return False | 8e0cb2613434a2e7dc00a758dd0df03cb8b06d36 | 691,124 |
def _get_multi_df_columns(df, sep_index):
"""
multi df by columns
"""
if 0 not in sep_index:
sep_index = [0] + sep_index
multitable = []
for i in range(len(sep_index)):
try:
if len(df.iloc[:, sep_index[i]:sep_index[i + 1] - 1].columns) != 0:
multitabl... | 554c040a25de7ec3a7866f333f5a842448b26dbf | 691,125 |
def read_hdf5( h5file, sample_name):
""" Apply motif stat function to all data in motif_file_name.
Data in numpy array val corresponds to idx entries. If idx if None all entries are used."""
a = h5file.get_node("/", sample_name )
m = a.read()
return m | 1762a328a6e70f5ecf90d4e1ed69b4cb40d20541 | 691,126 |
def _get_fk_relations_helper(unvisited_tables, visited_tables,
fk_relations_map):
"""Returns a ForeignKeyRelation connecting to an unvisited table, or None."""
for table_to_visit in unvisited_tables:
for table in visited_tables:
if (table, table_to_visit) in fk_relations_map:
... | fb2458437d16d94341f037ddf65347dc6d6169e4 | 691,127 |
import os
def split_path_where_exists(path):
"""
Splits a path into 2 parts: the part that exists and the part that doesn't.
:param path: the path to split
:return: a tuple (exists_part, remainder) where exists_part is the part that exists and remainder is the part that
doesn't. Either ... | 657c5352404eaa8586a49f64c2b7c229ad3f2434 | 691,129 |
def get_endpoints(tenant_id, entry_generator, prefix_for_endpoint):
"""
Canned response for Identity's get endpoints call. This returns endpoints
only for the services implemented by Mimic.
:param entry_generator: A callable, like :func:`canned_entries`, which
takes a datetime and returns an i... | a4b37277fff21f40b9ce40b4f8eb7c9d707e07b7 | 691,131 |
import math
def phaseNearTargetPhase(phase,phase_trgt):
"""
Adds or subtracts 2*math.pi to get the phase near the target phase.
"""
pi2 = 2*math.pi
delta = pi2*int((phase_trgt - phase)/(pi2))
phase += delta
if(phase_trgt - phase > math.pi):
phase += pi2
return phase
if(phase_trgt - phase < -math.pi):
... | dbd1a7c291b47703fa64756c986815d2cf706677 | 691,132 |
def emitlist(argslist):
"""Return blocks of code as a string."""
return "\n".join([str(x) for x in argslist if len(str(x)) > 0]) | 0a4280f342cdb61f3bae1ff02e7a9b10c3779556 | 691,133 |
import re
def extract_variables(query):
""" find variables in query by checking for the variable pattern symbols """
variables = []
query_form_pattern = r'^.*?where'
query_form_match = re.search(query_form_pattern, query, re.IGNORECASE)
if query_form_match:
letter_pattern = r'\?(\w)'
... | 6f1729a0b4209f43c14177eaf58930d5c697ea5e | 691,134 |
def coding_problem_28(word_list, max_line_length):
"""
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of
strings which represents each line, fully justified. More specifically, you should have as many words as possible
in each line. There should... | 59beff7b181730ab094f7f797128de9bfc83ef8b | 691,135 |
import numpy
def wyield_op(fractp, precip, precip_nodata, output_nodata):
"""Calculate water yield.
Parameters:
fractp (numpy.ndarray float): fractp raster values.
precip (numpy.ndarray): precipitation raster values (mm).
precip_nodata (float): nodata value from the precip raster.
... | 5bb117e237365986903829411de6677fdaef1bb7 | 691,136 |
def truncate(value):
"""
Takes a float and truncates it to two decimal points.
"""
return float('{0:.2f}'.format(value)) | b47412443fa55e0fd9158879b3c0d85c5ecc7aad | 691,137 |
def open_file(filename, mode='r'):
"""
常用文件操作,可在python2和python3间切换.
mode: 'r' or 'w' for read or write
"""
return open(filename, mode, encoding='utf-8', errors='ignore') | 100179e22f140c4e8d25a1ccab94f9ca3831b5f3 | 691,138 |
def get_pubmed_ids_from_csv(ids_txt_filepath):
"""
Function retrieves PubMed ids from a csv file
:param ids_txt_filepath: String - Full file path including file name to txt file containing PubMed IDs
:return lines: List of PubMed article IDs
"""
with open(ids_txt_filepath, 'r') as file:
... | 4f6f53eee0d14bb3beae27ac6f15f7c14b33dbe5 | 691,139 |
from typing import Callable
from typing import Optional
def make_averager() -> Callable[[Optional[float]], float]:
""" Returns a function that maintains a running average
:returns: running average function
"""
count = 0
total = 0
def averager(new_value: Optional[float]) -> float:
"""... | d2a9e0bfb896eda4574f022ce20240001c9dea61 | 691,140 |
def scenario_model_dict():
"""Dict serialisation of sample scenario model
"""
return {
'name': 'population',
'scenario': 'High Population (ONS)',
'description': 'The High ONS Forecast for UK population out to 2050',
'outputs': [
{
'name': 'populati... | 5c5d1777d9425d0596fd0dc9d06bdced179c0a57 | 691,142 |
def get_rst_string(module_name, help_string):
"""
Generate rst text for module
"""
dashes = "========================\n"
rst_text = ""
rst_text += dashes
rst_text += module_name + "\n"
rst_text += dashes + "\n"
rst_text += help_string
return rst_text | a33bdcaf0cb1321d9d83142581770c84652863fc | 691,143 |
from typing import Dict
def parse_wspecifier(wspecifier: str) -> Dict[str, str]:
"""Parse wspecifier to dict
Examples:
>>> parse_wspecifier('ark,scp:out.ark,out.scp')
{'ark': 'out.ark', 'scp': 'out.scp'}
"""
ark_scp, filepath = wspecifier.split(":", maxsplit=1)
if ark_scp not in ... | cdd28f17387c43d475abdcf463dcd58bee2ede5c | 691,144 |
def get_nodes(graph, metanode):
"""
Return a list of nodes for a given metanode, in sorted order.
"""
metanode = graph.metagraph.get_metanode(metanode)
metanode_to_nodes = graph.get_metanode_to_nodes()
nodes = sorted(metanode_to_nodes[metanode])
return nodes | 1decea0c15425bdba58d8ab2a8735aaff8d44b98 | 691,145 |
def create_state_action_dictionary(env, policy: dict) -> dict:
"""
return initial Q (state-action) matrix storing 0 as reward for each action in each state
:param env:
:param policy: 2D dictionary of {state_index: {action_index: action_probability}}
:return: Q matrix dictionary of {state_index: {act... | cfa546add31b8668ba065a4635c041679bbe319a | 691,146 |
async def check_win(ctx, player_id, game):
"""Checks if the player has won the game"""
player = game.players[player_id]
if len(player.hand) == 0:
await ctx.send(f"Game over! {player.player_name} has won!")
return True
return False | cb3fb54f499f9127ebecbbed5cbfb0be518697cf | 691,147 |
def price_to_profit(lst):
"""
Given a list of stock prices like the one above,
return a list of of the change in value each day.
The list of the profit returned from this function will be our input in max_profit.
>>> price_to_profit([100, 105, 97, 200, 150])
[0, 5, -8, 103, -50]
>>> price_t... | 5539c7c22f10c06199855e8c495221b111f67377 | 691,148 |
def upgrade(request):
"""Specify if upgrade test is to be executed."""
return request.config.getoption('--upgrade') | e52e3cd3af930f6867e6807bd7fa1402e1993b8c | 691,149 |
def ftpify(ip, port):
"""Convert ipaddr and port to FTP PORT command."""
iplist = ["","","",""]
for octet in range(0, 4):
iplist[octet] = ip.split('.')[octet]
port_hex = hex(int(port)).split('x')[1]
big_port = int(port_hex[:-2], 16)
little_port = int(port_hex[-2:], 16)
iplist.... | 2d0b2ff3267955a5bb3b990423271aeace470ecb | 691,150 |
def _inlining_threshold(optlevel, sizelevel=0):
"""
Compute the inlining threshold for the desired optimisation level
Refer to http://llvm.org/docs/doxygen/html/InlineSimple_8cpp_source.html
"""
if optlevel > 2:
return 275
# -Os
if sizelevel == 1:
return 75
# -Oz
i... | dd4a2ac54fc9dea53bf667095e41ca6d768a4627 | 691,151 |
def clip(st,length):
"""
will clip down a string to the length specified
"""
if len(st) > length:
return st[:length] + "..."
else:
return st | 3e0c952259e213026f60a4bf23de5820b2596d9a | 691,152 |
def dummy_func(arg1, arg2):
"""Summary line.
Extended description of function.
:param int arg1: Description of arg1.
:param str arg2: Description of arg2.
:raise ValueError: if arg1 is equal to arg2
:return: Description of return value
:rtype: bool
"""
return 1 / (arg1 - arg2) ... | b4a23766ca5355c0f5964ebfcb69a9cfd7e38af7 | 691,153 |
def get_resampling_period(target_dts, cmip_dt):
"""Return 30-year time bounds of the resampling period.
This is the period for which the target model delta T
matches the cmip delta T for a specific year.
Uses a 30-year rolling window to get the best match.
"""
target_dts = target_dts.rolling(ti... | d335fe1300703bc11ac3210d5ffce4b8c0ffd0f7 | 691,154 |
from sys import version
def post_message_empty_commands(channel, text, thread_ts):
"""
Check slack message when there are no registered commands
"""
assert text == "Hi <@test>!\nI'm EBR-Trackerbot v{version}\nSupported commands:\n".format(version=version)
return {"ok": "ok"} | e335bdcae07af11680d0012b3e6ac6f4028da852 | 691,155 |
import struct
def read_data(file, endian, num=1):
"""
Read a given number of 32-bits unsigned integers from the given file
with the given endianness.
"""
res = struct.unpack(endian + "L" * num, file.read(num * 4))
if len(res) == 1:
return res[0]
return res | 74b58ea11d3818ce6bdd56ba04ee1d1d34e9913a | 691,156 |
from datetime import date
def voto (anonasc):
"""
Função que retorna se uma pessoa vota ou não.
:param anonasc: O ano de nascimento
:return: Retorna se uma pessoa vota ou não
"""
anoatual = date.today().year
idade = anoatual - anonasc
if 18 <= idade <= 70:
return print(f'Com {i... | 9b9d49fa1577873c987eace88af11e652b76f394 | 691,157 |
import yaml
def _ParseYaml(stream):
"""Parses the file or stream and returns object."""
return yaml.safe_load(stream) | 231bea92bb6d367cddd8893fd555d73ca57a4a41 | 691,158 |
def raw_values(y_true, y):
"""
Returns input value y. Used for numerical diagnostics.
"""
return y | 5ca341e6ed14899df6a51564ee2d8f8b90dae04b | 691,159 |
def verts_to_name(num_verts):
"""Hacky function allowing finding the name of an object by the number of vertices.
Each object happens to have a different number."""
num_verts_dict = {100597: 'mouse', 29537: 'binoculars', 100150: 'bowl', 120611: 'camera', 64874: 'cell_phone',
177582: '... | cc7b851409366c14023378d670809409f8d8b039 | 691,160 |
def default_filter(src,dst):
"""The default progress/filter callback; returns True for all files"""
return dst | 8b76498b6c740ec0a3c882fd42cdabbc6608ac25 | 691,161 |
def retrieve_channel(Client, UseNameOrId, Identifier):
"""Returns a channel object based or either name or Id.
"""
text_channel_object = None
for channel in Client.get_all_channels():
if UseNameOrId == 'id':
if channel.id == Identifier:
text_channel_object = channel
... | 0a70268583f87dc088f3a3154d43b70830bb2680 | 691,162 |
def with_subfolder(location: str, subfolder: str):
"""
Wrapper to appends a subfolder to a location.
:param location:
:param subfolder:
:return:
"""
if subfolder:
location += subfolder + '/'
return location | 9c5c50e08ff6e2b250ac25bc317df834c359a1f3 | 691,163 |
import copy
def fzero_repeated_bisection(fn, x0=[0., 1.], max_iter=100, x_tol=1.e-8):
"""
Solve fn(x) = 0 using repeated bisection - 1d only. Initial guess and
result are both intervals.
:param fn: Function to solve.
:param x0: Initial interval [a, b], must contain a root.
:param... | 27205f3d0f233deef8dea754f98b30584140f238 | 691,164 |
from typing import List
from typing import Tuple
from typing import Counter
def major_and_minor_elem(inp: List) -> Tuple[int, int]:
"""Return most common element is the element that appears more than n // 2 times
and the least common element"""
count_elements = Counter(inp).most_common()
most_common_... | 68c8af05e1d4698a03db011783feaf160cd344e9 | 691,165 |
import os
def findWorkspaceRoot(packageXmlFilename):
"""
Tries to find the root of the workspace by search top down
and looking for a CMakeLists.txt or .catkin_tools file / folder. If no
workspace is found an empty string is returned.
@param[in] packageXmlFilename: package xml file name
"""
... | 1bb9645307a0a1dcd29e45bfac8d2d87a6d12ea1 | 691,166 |
import unicodedata
def remove_accents(string: str) -> str:
"""Remove wired characters from string"""
return "".join(
c for c in unicodedata.normalize("NFKD", string) if not unicodedata.combining(c)
) | 310457528cd42138804e4b95cd15bf07d6d257ce | 691,167 |
import numpy as np
import datetime
def trans_tf_to_td(tf, dtype="dframe"):
"""July 02, 2015, Y.G.@CHX
Translate epoch time to string
"""
"""translate time.float to time.date,
td.type dframe: a dataframe
td.type list, a list
"""
if dtype is "dframe":
ind = tf.index
... | d040f13345a62ed53cf227ee67acddd346c017f6 | 691,168 |
from typing import Callable
def pow_util(gamma: float) -> Callable[[float], float]:
"""
べき乗関数的な効用関数を返します。
Parameters
----------
gamma: float
実指数
Returns
-------
Callable[[float], float]
x >= 0 について、u(x) = x^{1 - gamma} / (1 - gamma) を満たす効用関数u
"""
def u(x: flo... | 39a1e134f5fc22c406c823387a7b51e8370b79b4 | 691,169 |
import os
def sbwshome_only_datadir(sbwshome_empty):
"""Create sbws home inside of the tests tmp dir with only datadir."""
os.makedirs(os.path.join(sbwshome_empty, 'datadir'), exist_ok=True)
return sbwshome_empty | 47eecd91ee1ff7402c04bab294819903b7f01771 | 691,170 |
def get_ports(svc_group, db):
"""Gets the ports and protocols defined in a service group.
Args:
svc_group: a list of strings for each service group
db: network and service definitions
Returns:
results: a list of tuples for each service defined, in the format:
(service name, "<po... | 04502215d32742465a9b22c8630997f00016b236 | 691,171 |
def outputInfo(clip):
"""Create a text string to output to a file
"""
header="tic,planetNum"
text = "%i" % (clip.config.tic)
text = "%s,%i" % (text, clip.config.planetNum)
for k in clip.serve.param.keys():
text = "%s,%f" % (text, clip['serve']['param'][k])
header ... | 71af53ba0fa19a4f5f641080cfa7b5712285bba2 | 691,173 |
def run(capsys, mocker):
"""CLI run method fixture
To use:
run(meth, *args, input_side_effect=['first', 'second', 'last'])
run(meth, *args, input_return_value='42')
This would run the method `meth` with arguments `*args`.
In the first every time `builtins.input()` is called by `meth`, ... | f82905e8a8cca0fedbb64c896efd52e3a8c0add3 | 691,174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.