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) sound: sound waveform
:param (float) min_time: minimum time value considered for time range (t1, t2) (default: 0.)
:param (float) max_time: maximum time value considered for time range (t1, t2) (default: 0.)
NOTE: If max_time <= min_time, the entire time domain is considered
:param (float) pitch_floor: minimum pitch (default: 75.)
:param (float) pitch_ceiling: maximum pitch (default: 600.)
:param (float) period_floor: the shortest possible interval that will be used in the computation
of jitter, in seconds (default: 0.0001)
:param (float) period_ceiling: the longest possible interval that will be used in the
computation of jitter, in seconds (default: 0.02)
:param (float) max_period_factor: the largest possible difference between consecutive intervals
that will be used in the computation of jitter (default: 1.3)
:return: value of (local) jitter
"""
# Create a PointProcess object
point_process = call(sound, 'To PointProcess (periodic, cc)',
pitch_floor, pitch_ceiling)
local_jitter = call(point_process, 'Get jitter (local)',
min_time, max_time,
period_floor, period_ceiling, max_period_factor)
return local_jitter | 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) & (x <= x2) & (y >= y1) & (y <= y2)
return flags | 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 of teams and their members
"""
guild = bot.get_guild(int(guildId))
teamDistribution = {}
for team in scores:
teamDistribution[team] = []
for member in guild.members:
for role in member.roles:
if role.name.startswith("team"):
try:
assert role.name in teamDistribution
if names:
teamDistribution[role.name].append(member.display_name)
else:
teamDistribution[role.name].append(member)
except:
print("Please check that teamnames match roles (no \
spaces). Someone might have a role of a team \
that isn't in this quiz.")
return teamDistribution | 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:
Void function (Creates JSON file)
"""
def mGap(gap):
return gap * " "
def multipleLabel(multiple_label, f, gap):
labels = multiple_label.split("&&")
f.write(mGap(gap) + '"sideLabels" : [')
for i in range(len(labels)):
if i!=0:
f.write(",")
f.write('"' + labels[i] + '"')
f.write("]")
f.write(mGap(gap-1) + "{\n")
if node.name == "none":
f.write(mGap(gap) + '"name" : ' + '"' + '"' + ",\n")
else:
f.write(mGap(gap) + '"name" : ' + '"' + node.name + '"' + ",\n")
f.write(mGap(gap) + '"nodeOrder" : ' + node.order)
if node.shape == "square":
f.write(",\n")
f.write(mGap(gap) + '"shape" : ' + '"' + "rectangle" + '"')
if node.color != None:
f.write(",\n")
f.write(mGap(gap) + '"nodeColor" : ' + '"' + node.color + '"')
if node.arrow == "to":
f.write(",\n")
f.write(mGap(gap) + '"arrowToNode" : ' + '"' + "yes" + '"')
if node.arrow == "from":
f.write(",\n")
f.write(mGap(gap) + '"arrowFromNode" : ' + '"' + "yes" + '"')
if node.arrow == "both":
f.write(",\n")
f.write(mGap(gap) + '"arrowToNode" : ' + '"' + "yes" + '"')
f.write(",\n")
f.write(mGap(gap) + '"arrowFromNode" : ' + '"' + "yes" + '"')
if node.dash == "yes":
f.write(",\n")
f.write(mGap(gap) + '"dashLine" : ' + '"' + "yes" + '"')
if node.bottom_label != None:
f.write(",\n")
f.write(mGap(gap) + '"nodeLabel" : ' + '"' + node.bottom_label + '"')
if node.side_label != None:
f.write(",\n")
multipleLabel(node.side_label, f, gap)
if node.left_edge_label != None:
f.write(",\n")
f.write(mGap(gap) + '"edgeLabelLeft" : ' + '"' + node.left_edge_label + '"')
if node.right_edge_label != None:
f.write(",\n")
f.write(mGap(gap) + '"edgeLabelRight" : ' + '"' + node.right_edge_label + '"')
if node.jump != None:
f.write(",\n")
f.write(mGap(gap) + '"jump" : ' + node.jump)
if node.action_order != None:
f.write(",\n")
f.write(mGap(gap) + '"actionOrder" : ' + node.action_order)
if node.children != []:
f.write(",\n" + mGap(gap) + '"children" : ' + "[\n")
for ch in node.children:
if not (ch == node.children[0]):
f.write(",\n")
createJSON(f, ch, gap+2)
f.write("\n" + mGap(gap) + "]")
f.write("\n" + mGap(gap-1) + "}") | 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 character is escaped, False otherwise
"""
escapes_uneven = False
# iterate backwards, starting one left of position.
# Slicing provides a sane default behaviour and prevents IndexErrors
for i in range(len(string[:position]) - 1, -1, -1):
if string[i] == '\\':
escapes_uneven = not escapes_uneven
else:
break
return escapes_uneven | 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_name.
Only sum supported.
:return: a list of of values
"""
if groupby is not None:
if group_by_criterion == "sum":
return df.groupby(by=groupby)[col_name].sum().reset_index()[col_name].values
else:
return RuntimeWarning
else:
return list(df[col_name]) | 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 True
# for instance methods on instances.
if im_self is None:
return False
return isinstance(im_self, type) | 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 simulation.gradient | 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,
pose.pose.orientation.z,
pose.pose.orientation.w] | 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 = string.ascii_uppercase[d-1]
digits.append(digit)
if m <= k:
break
m = q
return "".join(reversed(digits)) | 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()
"""
class Monkey(obj.__class__):
def __enter__(self, *a, **kw):
enter(*a, **kw)
return self
def __exit__(self, *a, **kw):
exit(*a, **kw)
obj.__class__ = Monkey | 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(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2)) | 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
fonction vérifie si le mot figure dans cette liste, et retourne True si c’est bien le cas, False sinon.
Exemple
L’appel de la fonction suivant, où words.txt est le fichier indiqué dans les consignes ci-dessous et en supposant qu'il
se trouve dans le même répertoire que le programme :
belongs_to_file("renard", "words.txt")
retourne : False
Consignes
Dans cet exercice, il vous est demandé d’écrire seulement la fonction belongs_to_file. Le code que vous soumettez à
UpyLaB doit donc comporter uniquement la définition de cette fonction, et ne fait en particulier aucun appel à input
ou à print.
Vous pourrez supposer que le fichier passé en paramètre contient bien une liste de mots, chacun sur sa propre ligne.
N’oubliez pas d’ouvrir le fichier dans le code de la fonction.
Le fichier utilisé par UpyLaB pour effectuer les tests est disponible à l’adresse :
https://upylab.ulb.ac.be/pub/data/words.txt
"""
def belongs_to_file(word, filename) :
""" teste si word est dans le fichier filename """
with open(filename, 'r', encoding="utf-8") as fichier :
rep = False
for mot in fichier :
if word == mot[:len(mot)-1] :
print("\n",mot, "\n", word)
rep = True
return rep
test = [("renard", "words.txt"), ("abandonments", "words.txt")]
reponse = [False, True]
for n, (w,f) in enumerate(test) :
rep = belongs_to_file(w,f)
print("\n\n"+120*'_'+"\nà partir du mot :", w, " dans le fichier ", f, "\n la fonction renvoie : \n", rep,
"\n et il est attendu :\n",
reponse[n] )
print("Test réussi ? :", rep == reponse[n]) | 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")
"""
result = set() # type: Set[str]
for curname in group_names:
if (len(curname) == 6) and (curname[0:4] == "POL_"):
result.add(curname[4:6].upper())
return result | 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
"""
if only_none is True:
new_dct = {k: v for k, v in dct.items() if v is not None}
else:
new_dct = {k: v for k, v in dct.items() if v}
for k, v in new_dct.items():
if isinstance(v, dict):
new_dct[k] = delete_nulls(v, only_none=True)
if isinstance(v, list):
for i, elem in enumerate(v):
if isinstance(elem, dict):
v[i] = delete_nulls(elem, only_none=True)
new_dct[k] = v
if only_none is True:
new_dct = {k: v for k, v in dct.items() if v is not None}
else:
new_dct = {k: v for k, v in dct.items() if v}
return new_dct | 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 + '-' + datatype + '-page' + str(pageno).zfill(3) + '.json'
source_folder = os.path.dirname(os.path.realpath(__file__))
return os.path.join(source_folder, 'cache/' + filename) | 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 be added.
suffix : str
The suffix to be inserted.
new_ext : str, optional
If not None, it replaces the original file name extension.
Returns
-------
new_filename : str
The new file name.
"""
base, ext = os.path.splitext(filename)
if new_ext is None:
new_filename = base + suffix + ext
else:
new_filename = base + suffix + new_ext
return new_filename | 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."""
if actual_warning and not expected_warning:
return True
expected_warning = cast(Type[Warning], expected_warning)
return bool(not issubclass(actual_warning.category, expected_warning)) | 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) ** 2 * vis, dim=-1) / torch.sum(vis, dim=-1) # [B]
elif loss_type == "L1":
loss = torch.sum(torch.abs(gt_pose - pred_pose) * vis, dim=-1) / torch.sum(vis, dim=-1) # [B]
else:
assert False, "Unknown loss type"
return loss | 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':
_groups['left'][_group] = font.groups[_group]
if _group[1:6] == 'right':
_groups['right'][_group] = font.groups[_group]
return _groups | 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:
max_index = index
if instruction.cargs:
return qregs[min_index:]
return qregs[min_index:max_index + 1] | 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):
child = random.randint(male, female)
children.append(child)
return children | 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())
set_gain = float(exp.experiment_setpoint_gain.text())
set_offset = float(exp.experiment_setpoint_offset.text())
sr = float(exp.experiment_shunt_resistor.text())
ts = float(exp.experiment_time_step.text())
avg_num = int(exp.experiment_averag_number.text())
AP_parameters = [conv_fact, set_gain, set_offset, sr, ts,avg_num]
return AP_parameters | 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. 'OutbreakLocation', 'LineListRecord', 'BiblioEntry', etc.
api: The API you want to access, either 'fetch' or 'evalmetrics'.
body: The spec you want to pass. For examples, see the API documentation.
"""
response = requests.post(
"https://api.c3.ai/covid/api/1/" + typename + "/" + api,
json=body,
headers={
'Accept': 'application/json',
'Content-Type': 'application/json'
}
)
# if request failed, show exception
if response.status_code != 200:
raise Exception(response.json()["message"])
return response.json() | 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 == "threshold_closeness":
return False
elif filtering_metric == "forgetfulness":
return False
elif filtering_metric == "correctness":
return True
else:
raise NotImplementedError(f"Filtering based on {filtering_metric} not implemented!") | 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.
"""
return [[op(vi, vj) for vj in v] for vi in v] | 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 = []
indexFile = open("DATA/patientIndex.csv", "r")
for line in indexFile:
line = line.split("\n")
lineInArray = line[0].split(";")
ID = lineInArray[0]
status = lineInArray[1]
if(status == diagnostic):
patientIdList.append(ID)
indexFile.close()
return patientIdList | 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 interface.upper().startswith('25GE'):
iftype = '25ge'
elif interface.upper().startswith('4X10GE'):
iftype = '4x10ge'
elif interface.upper().startswith('40GE'):
iftype = '40ge'
elif interface.upper().startswith('100GE'):
iftype = '100ge'
elif interface.upper().startswith('VLANIF'):
iftype = 'vlanif'
elif interface.upper().startswith('LOOPBACK'):
iftype = 'loopback'
elif interface.upper().startswith('METH'):
iftype = 'meth'
elif interface.upper().startswith('ETH-TRUNK'):
iftype = 'eth-trunk'
elif interface.upper().startswith('VBDIF'):
iftype = 'vbdif'
elif interface.upper().startswith('NVE'):
iftype = 'nve'
elif interface.upper().startswith('TUNNEL'):
iftype = 'tunnel'
elif interface.upper().startswith('ETHERNET'):
iftype = 'ethernet'
elif interface.upper().startswith('FCOE-PORT'):
iftype = 'fcoe-port'
elif interface.upper().startswith('FABRIC-PORT'):
iftype = 'fabric-port'
elif interface.upper().startswith('STACK-PORT'):
iftype = 'stack-port'
elif interface.upper().startswith('NULL'):
iftype = 'null'
else:
return None
return iftype.lower() | 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
`connection.Connection()`.
body: JSON formatted user data;
{
"username": "string",
"fullName": "string",
"description": "string",
"password": "string",
"enabled": true,
"passwordModifiable": true,
"passwordExpirationDate": "2020-06-15T13:26:09.616Z",
"requireNewPassword": true,
"standardAuth": true,
"ldapdn": "string",
"trustId": "string",
"memberships": [
"string"
]
}
username(str): username of a user, used in error message
fields(list, optional): Comma separated top-level field whitelist. This
allows client to selectively retrieve part of the response model.
Returns:
HTTP response object returned by the MicroStrategy REST server.
"""
return connection.session.post(
url=f'{connection.base_url}/api/users',
params={'fields': fields},
json=body,
) | 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 run-time we are interested in measuring.
Returns:
A function which does exactly the same, with an additional run-time output value in seconds.
"""
def timed(*args, **kw) -> Tuple:
ts = time.perf_counter_ns()
result = method(*args, **kw)
te = time.perf_counter_ns()
duration_in_ms: float = (te - ts) * 1e-9
if isinstance(result, tuple):
return result + (duration_in_ms,)
else:
return result, duration_in_ms
timed.__name__ = method.__name__ + " with time measure"
return timed | 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:
multitable.append(df.iloc[:, sep_index[i]:sep_index[i + 1] - 1])
except:
if len(df.iloc[:, sep_index[i]:].columns) != 0:
multitable.append(df.iloc[:, sep_index[i]:])
del df
return multitable | 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:
fk_relation = fk_relations_map[(table, table_to_visit)]
unvisited_tables.remove(table_to_visit)
visited_tables.append(table_to_visit)
return fk_relation
return None | 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 part may be None.
"""
current = path
remainder = None
while True:
if os.path.exists(current):
return current, remainder
next_, tail = os.path.split(current)
tail = tail or next_
remainder = tail if remainder is None else os.path.join(tail, remainder)
if next_ == current:
break
current = next_
return None, remainder | 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 iterable of Entry.
"""
result = []
for entry in entry_generator(tenant_id):
for endpoint in entry.endpoints:
result.append({
"region": endpoint.region,
"tenantId": endpoint.tenant_id,
"publicURL": endpoint.url_with_prefix(
prefix_for_endpoint(endpoint)
),
"name": entry.name,
"type": entry.type,
"id": endpoint.endpoint_id,
})
return {"endpoints": result} | 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):
phase -= pi2
return phase | 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)'
variables = re.findall(letter_pattern, query_form_match.group(0))
return variables | 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 be at least one space between each word. Pad extra spaces when necessary so that each
line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any,
distributed starting from the left. If you can only fit one word on a line, then you should pad the right-hand side
with spaces. Each word is guaranteed not to be longer than k.
Example:
>>> coding_problem_28(["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"], 16)
['the quick brown', 'fox jumps over', 'the lazy dog']
"""
lines = []
while word_list:
if len(word_list) == 1: # right-align ending word
lines.append('{:>{mll}}'.format(word_list[0], mll=max_line_length))
break
words = []
while len(' '.join(words + word_list[:1])) <= max_line_length and word_list:
words += word_list[:1]
word_list = word_list[1:]
total_spaces = max_line_length - sum(map(len, words))
gaps = len(words) - 1
gap_len = total_spaces // gaps
first_gap_add = total_spaces - gap_len * gaps
lines.append(words[0] + ' ' * (gap_len + first_gap_add) + (' ' * gap_len).join(words[1:]))
return lines | 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.
output_nodata (float): nodata value assigned to output of
raster_calculator.
Returns:
numpy.ndarray of water yield value (mm).
"""
result = numpy.empty_like(fractp)
result[:] = output_nodata
valid_mask = (~numpy.isclose(fractp, output_nodata) &
~numpy.isclose(precip, precip_nodata))
result[valid_mask] = (1.0 - fractp[valid_mask]) * precip[valid_mask]
return result | 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:
lines = file.read().split('\n')
return lines | 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:
""" Running averager
:param new_value: number to add to the running average,
if None returns the current average
:returns: the current average
"""
nonlocal count, total
if new_value is None:
return total / count if count else float("nan")
count += 1
total += new_value
return total / count
return averager | 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': 'population_count',
'dims': ['LSOA'],
'coords': {'LSOA': ['a', 'b', 'c']},
'dtype': 'int',
'unit': 'people',
'abs_range': None,
'exp_range': None,
'description': None
}
]
} | 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 ["ark", "scp,ark", "ark,scp"]:
raise ValueError("{} is not allowed: {}".format(ark_scp, wspecifier))
ark_scps = ark_scp.split(",")
filepaths = filepath.split(",")
if len(ark_scps) != len(filepaths):
raise ValueError("Mismatch: {} and {}".format(ark_scp, filepath))
spec_dict = dict(zip(ark_scps, filepaths))
return spec_dict | 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: {action_index: reward}}
"""
# Note: We use optimal action-value function instead of value function
# to cache the one-step-ahead searches (trade off space for time)
# initialize Q matrix
Q = {}
# traverse states in a policy
for key in policy.keys():
# for each state, assign each action 0 as reward
Q[key] = {a: 0.0 for a in range(0, env.action_space.n)}
return Q | 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_to_profit([205, 199, 188, 220, 235, 280, 301])
[0, -6, -11, 32, 15, 45, 21]
"""
profit = [lst[i+1] - lst[i] for i in range(len(lst) - 1)]
profit.insert(0, 0)
return profit | 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.append(str(big_port))
iplist.append(str(little_port))
return 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
if sizelevel == 2:
return 25
return 225 | 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) > 1 | 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(time=30, center=True,
min_periods=30).mean()
time_idx = abs(target_dts - cmip_dt).argmin(dim='time').values
year = target_dts.isel(time=time_idx).year.values.astype(int)
target_dt = target_dts.isel(time=time_idx).values.astype(float)
return [year - 14, year + 15], target_dt | 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 {idade} anos: VOTO OBRIGATÓRIO.')
elif idade >= 16 or idade > 70:
return print(f'Com {idade} anos: VOTO OPCIONAL.')
else:
return print(f'Com {idade} anos: NÃO VOTA.') | 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: 'cup', 22316: 'eyeglasses', 46334: 'flashlight', 35949: 'hammer', 93324: 'headphones',
19962: 'knife', 169964: 'mug', 57938: 'pan', 95822: 'ps_controller', 57824: 'scissors',
144605: 'stapler', 19708: 'toothbrush', 42394: 'toothpaste', 126627: 'utah_teapot', 90926: 'water_bottle',
104201: 'wine_glass', 108248: 'door_knob', 71188: 'light_bulb', 42232: 'banana', 93361: 'apple',
8300: 'HO_sugar', 8251: 'HO_soap', 16763: 'HO_mug', 10983: 'HO_mustard', 9174: 'HO_drill',
8291: 'HO_cheezits', 8342: 'HO_spam', 10710: 'HO_banana', 8628: 'HO_scissors',
148245: 'train_exclude'}
if num_verts in num_verts_dict:
return num_verts_dict[num_verts]
return 'DIDNT FIND {}'.format(num_verts) | 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
break
else:
if channel.name == Identifier:
text_channel_object = channel
break
return text_channel_object | 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 max_iter: Max steps, final interval is 1/2**max_iter times smaller
than initial interval.
:param x_tol: Terminate when interval width < tol.
:return: Final interval x.
"""
x = copy.copy(x0)
ftmp = [fn(x[0]), fn(x[1])] # Storage: never calculate fn twice at same location.
if ftmp[0] * ftmp[1] > 0:
raise ValueError(
"Function value doesn't change sign on initial interval: "
"[%e, %e], f = [%e, %e]." % (x[0], x[1], ftmp[0], ftmp[1])
)
for i in range(max_iter):
midpnt = (x[1] + x[0]) / 2.
fmid = fn(midpnt)
if ftmp[0] * fmid < 0:
x[1], ftmp[1] = midpnt, fmid
else:
x[0], ftmp[0] = midpnt, fmid
if abs(x[1] - x[0]) < x_tol:
break
return x | 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_elem, least_common_elem = (
count_elements[0][0],
count_elements[-1][0],
)
return most_common_elem, least_common_elem | 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
"""
pathOld = ""
pathNew = os.path.dirname(os.path.abspath(packageXmlFilename))
while pathOld != pathNew:
pathOld = pathNew
pathNew = os.path.dirname(pathOld)
files = os.listdir(pathNew)
if ".catkin_tools" in files:
return(os.path.join(pathNew, "src"))
if "CMakeLists.txt" in files:
return(pathNew)
return "" | 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
else:
ind = range(len(tf))
td = np.array([datetime.datetime.fromtimestamp(tf[i]) for i in ind])
return td | 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: float) -> float:
return x ** (1 - gamma) / (1 - gamma)
return u | 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, "<port>/<protocol>")
"""
results = []
for svc in svc_group:
port = db.GetService(svc)
results.append((svc, port))
return results | 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 = "%s,%s" % (header, k)
text = "%s,%f" % (text, clip.lpp.TLpp)
header = "%s,Tlpp" % (header)
if "modshiftTask" in clip.config.taskList:
for k in clip.modshift.keys():
text = "%s,%f" % (text, clip['modshift'][k])
header = "%s,%s" % (header, k)
for k in clip.robovet.keys():
text = "%s, %s" % (text, str(clip['robovet'][k]))
header = "%s,rv_%s" % (header, k)
return text,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`, the next
element of input_side_effect will be returned
In the second every invokation of 'buitins.input()' returns '42'.
Both return a tuple of three items, mocked-input, stdout, and stderr.
"""
def _do_run(method, *args, **kwargs):
mocked_input = mocker.patch('builtins.input')
if 'input_side_effect' in kwargs:
mocked_input.side_effect = kwargs['input_side_effect']
del kwargs['input_side_effect']
if 'input_return_value' in kwargs:
mocked_input.return_value = kwargs['input_return_value']
del kwargs['input_return_value']
method(*args, **kwargs)
captured = capsys.readouterr()
return captured.out, captured.err, mocked_input
return _do_run | f82905e8a8cca0fedbb64c896efd52e3a8c0add3 | 691,174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.