content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def _is_winning_combination(board, combination, player):
"""
Checks if all 3 positions in given combination are occupied by given player.
:param board: Game board.
:param combination: Tuple containing three position elements.
Example: ((0,0), (0,1), (0,2))
Returns True of a... | 19e2ff1e0c254dbde0f856e994e9b9fe63a20db0 | 230,348 |
def get_param_i(param, i):
"""Gets correct parameter for iteration i.
Parameters
----------
param : list
List of model hyperparameters to be iterated over.
i : integer
Hyperparameter iteration.
Returns
-------
Correct hyperparameter for iteration i.
"""
if len(p... | 52b81a9f1f5a712586bf55dcdd10975fcd1bc8c2 | 482,629 |
def bilinear_interpolation_01(x, y, values):
"""Interpolate values given at the corners of
[0,1]x[0,1] square.
Parameters:
x : float
y : float
points : ((v00, v01), (v10, v11))
input grid with 4 values from which to interpolate.
Inner dimension = x, thus v01 ... | a5e0d8b974803073df159da4d16a01a47ec0f087 | 690,778 |
def get_alternated_ys(ys_count, low, high):
"""
A helper function generating y-positions for x-axis annotations, useful when some annotations positioned along the
x axis are too crowded.
:param ys_count: integer from 1 to 3.
:param low: lower bound of the area designated for annotations
:param h... | e606ef555ff29285d4b7b77076939e66b8997856 | 631,116 |
def get_api_base(api_func):
"""Return the API base for Ghidra's flat API
:param api_func: Any function in Ghidra's flat API - eg. getInstructionAt
:type: function
:return: The api base
:rtype: ghidra.python.PythonScript
"""
return api_func.__self__ | 0a05e4667be620a62ea108f1c31484aa4bcb023c | 359,044 |
def _validate_year(year):
""" Validate year is given as an int"""
if not isinstance(year, int):
raise TypeError("Year must give of type `int`.")
if year <= 1900:
raise ValueError("Please enter a year after 1990.")
return year | 2818f988e32192436bcfd0c6c5d1c0aff9a7488f | 369,612 |
def phrase(term: str) -> str:
"""
Format words to query results containing the desired phrase.
:param term: A phrase that appears in that exact form. (e.q. phrase "Chicago Bulls" vs. words "Chicago" "Bulls")
:return: String in the format google understands
"""
return '"{}"'.format(term) | 8a327ca9dc9b223e4ba9adbba8d7f4ed85d7db68 | 689,958 |
from typing import Dict
from typing import Any
import logging
def web3_mint(userAddress: str, tokenURI: str, eth_json: Dict[str, Any]) -> str:
"""
Purpose:
mint a token for user on blockchain
Args:
userAddress - the user to mint for
tokenURI - uri for token
eth_json - block... | 8848eba9be99e20c9b86215d6752d09dbcc3ee35 | 328,881 |
from typing import Tuple
import math
def factor(x: int) -> Tuple[int, int]:
"""
Factors :attr:`x` into 2 numbers, a and b, such that a + b is as small as possible.
Parameters
-----------
x: :class:`int`
The number to factor
Returns
--------
Tuple[:class:`int`, :class:`int`]
... | bfee87f2812f54f9281bdc316366d037703cedac | 443,114 |
def third_bashforth(state, tendencies_list, timestep):
"""Return the new state using third-order Adams-Bashforth. tendencies_list
should be a list of dictionaries whose values are tendencies in
units/second (from oldest to newest), and timestep should be a timedelta
object."""
return_state = {}
... | 6b1a62b94c662a1b14eafa3be6953e73486b6cfd | 697,519 |
def _unescape_key(string):
"""
Unescape '__type' and '__meta' keys if they occur.
"""
if string.startswith("__") and string.lstrip("_") in ("type", "meta"):
return string[1:]
return string | 593f5f178f9fe94465a85bfee4bd896c97c16dff | 466,020 |
def atom2dict(atom, dictionary=None):
"""Get a dictionary of one of a structure's
:class:`diffpy.structure.Structure.atoms` content.
Only values necessary to initialize an atom object are returned.
Parameters
----------
atom : diffpy.structure.Structure.atom
Atom in a structure.
di... | 6873c64bd39d211a43f302375d6a6c76e3bd0b7e | 28,103 |
def row_includes_spans(table, row, spans):
"""
Determine if there are spans within a row
Parameters
----------
table : list of lists of str
row : int
spans : list of lists of lists of int
Returns
-------
bool
Whether or not a table's row includes spans
"""
for c... | 217aa977b4029a62f379eb61ccef8a3d90ae90e2 | 524,346 |
from typing import Union
def read_file(path: str, mode: str) -> Union[str, bytes]:
""" Reads the content of the given file.
Args:
path (str): the path of the file
mode (str): the open mode, could be "r" or "rb"
Returns:
the content of the file, as string or bytes depending on the ... | 580244b671b4dbba2ee31973d98b3fa99a52a5c4 | 199,008 |
from typing import Union
def count_even(obj: Union[list, int]) -> int:
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
>>> count_even(3)
0
>>> count_even(16)
... | 8d757d7004c11ac77eb85bbc37fd7b3c9e6c4798 | 638,597 |
def ping_time_to_distance(time, calibration=None, distance_units='cm'):
"""
Calculates the distance (in cm) given the time of a ping echo.
By default it uses the speed of sound (at sea level = 340.29 m/s)
to calculate the distance, but a list of calibrated points can
be used to calculate the distan... | db8cba30c8d50d301b6a0e15073c527e285d4aa6 | 51,225 |
def get_var(df, recorded_var, mean=True):
"""
Get variable from dataframe one level deep and optionally the mean.
:param df: Recorded data over time
:type df: pd.DataFrame
:param recorded_var: Variable to retrieve from df
:type recorded_var: str
:param mean: Include the mean in the return t... | 79999aec48023c5dc5ac166613f2e9313f74ba07 | 252,191 |
from typing import Tuple
import re
def remove_markdown_formatting(preamble: str, remainder: str) -> Tuple[str, str]:
"""
Remove Markdown formatting from a preamble and remainder pair.
Parameters
----------
preamble : `str`
The textual preamble.
remainder : `str`
The textual r... | c6c8fff9890c33fc2b93ac4b2f2a05202e576a66 | 246,351 |
import re
def replace_empty_bracket(tokens):
"""
Remove empty bracket
:param tokens: List of tokens
:return: Fixed sequence
"""
merged = "".join(tokens)
find = re.search(r"\{\}", merged)
while find:
merged = re.sub(r"\{\}", "", merged)
find = re.search(r"\{\}", merged)
... | fd2c9f2f1c2e199056e89dbdba65f92e4d5834eb | 707,808 |
import hashlib
def crackPwd(chunk, hashType, password):
"""This is the function that is sent to the nodes"""
#Insert haslib matching function (similar to youtube video)
testHash = None
for item in chunk:
item = item.strip()
if hashType == "MD5":
testHash = hashlib.md5(item.... | a0fae23920b4ead7c38e673c195d96e2f28ac085 | 205,229 |
import torch
def approx_equal(self, other, epsilon=1e-4):
"""
Determines if two tensors are approximately equal
Args:
- self: tensor
- other: tensor
Returns:
- bool
"""
if self.size() != other.size():
raise RuntimeError(
"Size mismatch between self (... | e5187e5724f4dd61c8b680241f74037ff13133fd | 292,467 |
def http_request(transport, method, url, data=None, headers=None):
"""Make an HTTP request.
Args:
transport (object): An object which can make authenticated requests
via a ``request()`` method. This method mustaccept an HTTP method,
an upload URL, a ``data`` keyword argument and... | 41c74c4ffb168dde7e489168e8a6a38e2c1babd5 | 181,345 |
def filter_df(freq_df, prediction=None, top=None):
"""Filter frequency df's columns
Parameters
----------
freq_df : pandas.DataFrame
Only a dataframe returned by `frequency_df()` should be used.
prediction : str, list
Allow only the class predictions that match this string or
... | 68fe77f6c5fc93a662388c98b10e69b29114d9d4 | 277,029 |
def decode_to_utf8(text) -> bytes: # pragma: no cover
"""
Paramiko returns bytes object and we need to ensure it is utf-8 before parsing.
:param text: non-decoded bytes
:return: decoded text
"""
try:
return text.decode("utf-8")
except (AttributeError, UnicodeEncodeError):
r... | f8d7ddf3960b167a7ddf56f90cfef0160d59b03d | 170,281 |
def null_removal_drop(dataframe, colname):
"""Drops rows with nulls on dataframe[colname]"""
dataframe = dataframe.dropna(subset=[colname])
return dataframe | 1cd11752f69d9ed6768e94fbe8ae6bef2637216c | 452,381 |
def is_own_stt(user, requested_stt):
"""Verify user belongs to requested STT."""
user_stt = user.stt_id if hasattr(user, 'stt_id') else None
return bool(
user_stt is not None and
(requested_stt in [None, str(user_stt)])
) | b78b4a7fada170c09c740a7dec6027294b2b3c86 | 356,646 |
import re
def is_issue(text):
"""
Does this token look like an issue reference?
https://help.github.com/articles/autolinked-references-and-urls/#issues-and-pull-requests
>>> is_issue('26')
False
>>> is_issue('#26')
True
>>> is_issue('jlord#26')
True
>>> is_issue('jlord')
F... | d0dac0a0b8743bd2f06abb865b593cf3bce1c174 | 387,760 |
def retreive_details(input_dict,keys_to_extract):
"""
Retreive specific keys from a dictionary object
This function searches through a dictionary, and
retreives keys that match keys from a list. This function
will find matching keys in every level of the dictionary heirarchy.
Inputs:
... | f80c4bac321227a09a9cdf8bac3b1b4e0b16ff5d | 637,039 |
def compute_var_bound(gammas):
""" computes the variance bound for the provided gamma values """
return 1./(1 + gammas**2) | 7807f5be071af7ad4149ef1afa13ecbf8e2f7ef8 | 163,155 |
from pathlib import Path
from typing import List
def path_does_not_contain(path: Path, names: List[str]) -> bool:
"""Check if path does not contain a list of names."""
for name in names:
if name in str(path):
return False
return True | 647aebe4debd5f97ebe686501a6075008f830de4 | 488,526 |
def camelize(string, uppercase_first_letter=True):
"""
Convert a string with underscores to a camelCase string.
Inspired by :func:`inflection.camelize` but even seems to run a little faster.
Args:
string (str): The string to be converted.
uppercase_first_letter (bool): Determin... | 456056892220af135e26bed047a9bf51f178aa7f | 561,495 |
def get_volume(low: list,
up: list) -> float:
"""Returns the volume defined of a box defined by lower and upper limits."""
vol = 1.0
for i in range(len(low)):
vol = vol * (up[i] - low[i])
return vol | 6cf311e064822f4875137e98a51a8d8041aa2c7c | 191,900 |
def sum_all(node):
"""
Sum all list elements together
:param node: value of head node, start of list
:return: int: sum of list elements
"""
if node is not None:
return node.value + sum_all(node.next_node) # tally those bad boys up
return 0 | abecb662291705a615f03040affd861c74f998e4 | 275,811 |
from typing import Dict
def format_location_name(location: Dict):
"""Returns a string with a combination of venue name, city
and state, depending on what information is available"""
if not location:
return None
if "venue" not in location and "city" not in location and "state" not in location... | 192542c15c17dde10feb9f8c0b6ec4a1fa65e991 | 660,889 |
def string_hash(text, mod):
""" Return a hash value for an ASCII string. The value will be
between 0 and mod-1. It is advisable to use a prime number
for mod to guarantee a fairly uniform distribution. """
base = 256 # size of the alphabet (ASCII)
numstr = [ord(char) for char in text]
length = l... | ff6018fbf6404a6ac4dfc088c676581eb0b59b2b | 182,328 |
def get_node_by_id(node_id, dialogue_node_list):
"""
Takes a node id and returns the node from the dialogue_node_list
"""
for dialogue_node in dialogue_node_list:
if dialogue_node["Id"] == node_id:
return dialogue_node
return None | f475e9c3d1d4eae5b1cc95325471bacb204a626d | 500,603 |
import csv
def load_room_list(room_list_file):
"""Returns list rooms from file."""
with open(room_list_file, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
room_list = []
for row in spamreader:
room_list.append(row[1])
return room_list | 0080becc3b2189bf441576901a8f0b14468b4932 | 272,180 |
def _only_one_selected(*args):
"""Test if only one item is True."""
return sum(args) == 1 | 9966cc7c2cde16c689f29ba2add80b2cddce56e7 | 704,592 |
import functools
def retry_with_fallback(triggering_error, **fallback_kwargs):
"""
Rerun a function in case a specific error occurs with new arguments.
:param triggering_error: Error class that triggers the decorator to re-run the function.
:type triggering_error: Exception
:param fallback_kw... | 720320d33681dce682b3643538961cddf577ff29 | 290,392 |
def _calculate_verification_code(hash: bytes) -> int:
"""
Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed.
See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm
"""
return ((0xFC & hash[0]) << 5) |... | 173f9653f9914672160fb263a04fff7130ddf687 | 704,115 |
from typing import Sequence
def hagenbach_bishoff(vector_size: int, scores: Sequence[float]) -> Sequence[int]:
"""
Split a vector between participants based on continuous fractions.
https://en.wikipedia.org/wiki/Hagenbach-Bischoff_system
The code is based on https://github.com/crflynn/voting
:par... | 2e4582176600e37777387d4b0810ffab910d3921 | 215,740 |
def default_while_loop_termination_case(state):
"""
Checks if the state is falsey
Args:
state: An object that should capable of being passed to `bool`
Returns:
True if the state is falsey or False if the state is Truthy
"""
return not bool(state) | 1af71d17ca80ed89cd5179fc375ecdd4a61af9c9 | 279,650 |
def get_input_masks(nx_node, nx_graph):
"""
Return input masks for all inputs of nx_node.
"""
input_edges = list(nx_graph.in_edges(nx_node['key']))
input_masks = [nx_graph.nodes[input_node]['output_mask'] for input_node, _ in input_edges]
return input_masks | f42a6aad02594deb9967c47a265c8cbec39f7b8c | 167,427 |
def fix_top(fig):
"""Normalize memory usage reported by `top` to KB"""
if fig.endswith('m'):
return float(fig.strip('m')) * 1024
else:
return int(fig) | 706642c45f03e7e54728e5d7bac819c91dbcea70 | 393,488 |
def one(nodes, or_none=False):
"""
Assert that there is exactly one node in the give list, and return it.
"""
if not nodes and or_none:
return None
assert len(
nodes) == 1, 'Expected 1 result. Received %d results.' % (len(nodes))
return nodes[0] | adb4d97553e00f53c38d32cf95ecdacb22f252d6 | 475,617 |
def to_hex(value):
"""
Convert decimal value to hex string.
"""
return " 0x%0.4X" % value | 561617c8b4929b6dced807346c0fa9203f9221b8 | 448,663 |
def to_string(value):
""" Convert a boolean to on/off as a string.
"""
if value:
return "On"
else:
return "Off" | 2069b48126a13c6b7a5c51b96dd90929a27a178c | 349,945 |
def reverse(seq):
"""Reverses a string given to it."""
return seq[::-1] | ab4a45809dc81b850dde473dd21a893f9fcd92c6 | 471,540 |
def extract_bool(
params: dict,
key: str,
default: bool,
) -> bool:
"""Safely extract boolean value from user input."""
value = params.get(key)
if value is None:
result = default
else:
result = value == 'on'
return result | dd02e2544eb219c2d10f1d5570dd18b5e934d095 | 473,712 |
def get_steps_kwarg_parsers(cls, method_name):
"""
Analyze a method to extract the parameters with command line parsers.
The parser must be a :class:`Param` so it handles parsing of arguments
coming from the command line. It must be specified in the ``options``
class attribute.
:param method_n... | 5cc991c63c8008e92ff2bdc59c08ae1c96caa120 | 665,065 |
def test(agent, env, policy):
"""
Tests an agent given an environment and the agent's policy
:param agent: the agent to test
:param env: the environment to test in
:param policy: the policy to follow
:return: agent's total reward as float
"""
done = False
obs = env.reset()
total_... | 2a4c334ba00e7a3ec6fe92e48a300187b5476f80 | 226,570 |
def remote_property(name, get_command, set_command, field_name, doc=None):
"""Property decorator that facilitates writing properties for values from a remote device.
Arguments:
name: The field name to use on the local object to store the cached property.
get_command: A function that returns the rem... | 59c81882e69451409e6bb43219faf456cac93e4a | 545,018 |
def count_increases(seq):
"""Count the number of elements in a sequece greater than the previous"""
increases = 0
for i in range(1, len(seq)):
if seq[i] > seq[i-1]:
increases += 1
return increases | 10f2f6f8438b3747daf4e37a05fd21ed10ee745f | 531,703 |
def bytes2str(data):
"""
Convert bytes to string
>>> bytes2str(b'Pwning')
'Pwning'
>>>
"""
data = "".join(map(chr, data))
return data | cd2e7fd59628c7b4eb8fdc918148f960f1226d6f | 18,271 |
import torch
def random_points_1D(N=100):
"""Sample random points in 1d
Parameters
----------
N : int (default: 100)
Number of points
Return
------
x : tensor, shape (1, N)
points
"""
x = 2 * (torch.rand(1, N) - 0.5)
return x | 8bdf44a66e47f28cd4d378d76ffacc0ddca3553e | 189,237 |
def REDUCE(_input, initial_value, _in):
"""
Applies an expression to each element in an array and combines them into a single value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/
for more details
:param _input: Can be any valid expression that resolves to an array.
:... | 730433e32b7d99de794589064bb0a31394ae7b34 | 675,726 |
def next_available_id(v):
"""
Return smallest nonnegative integer not in v.
"""
i = 0
while i in v:
i += 1
return i | f5b3d7215e435de92ebc6ae7d52f64329c82e847 | 259,805 |
def mean_over_dims(x, dims):
"""Take a mean over a list of dimensions keeping the as singletons"""
for dim in dims:
x = x.mean(dim=dim, keepdim=True)
return x | 6e4dcba935b67c6c5e8e028c9e9a0930f1d84201 | 596,832 |
def readlines(path):
"""Read lines from a text file.
Args:
path (str): Full path to file
Returns:
list: File text
"""
with open(path, 'r') as handle:
return handle.readlines() | c899a9383e946e6047dd3945a1b0e02b511a3de4 | 465,683 |
import imghdr
def validateImageHeader(file_path):
"""
Check whether the file header is none
:param file_path: File to validate header of
:return: boolean indicating whether header is none or not
"""
header = imghdr.what(file_path)
if header is None:
return False
else:
... | a9b92a71a4b35455ea401d8f82c448c170d33e63 | 261,642 |
from pathlib import Path
def is_installed_module(module_filename):
"""
Checks if a module is "installed" (e.g. using pip), as opposed to a "local" module, belonging
to user's env (e.g. local development tree).
"""
return any(
p.name in ['site-packages', 'dist-packages']
for p in Pa... | dfecff6c6c033e947271a1bbe04a98d6e8510ba6 | 232,729 |
from typing import Iterable
from typing import Tuple
import networkx
def build_graph(data: Iterable[Tuple[dict, str, dict]]):
"""
Builds a NetworkX DiGraph object from (Child, Edge, Parent) triples.
Each triple is represented as a directed edge from Child to Parent
in the DiGraph.
Child and Paren... | 6d43f3d2b9698eaac54cfcee38fd005e6762eaf6 | 20,813 |
def surround(text: str, tag: str):
"""Surround provided text with a tag.
:param text: text to surround
:param tag: tag to surround the text with
:return: original text surrounded with tag
"""
return "<{tag}>{text}</{tag}>".format(tag=tag, text=text) | b6316770a771a79c859c698406a13e8f8f239231 | 231,917 |
def _GetKubernetesObjectsExportConfigForClusterCreate(options, messages):
"""Gets the KubernetesObjectsExportConfig from create options."""
if options.kubernetes_objects_changes_target is not None or options.kubernetes_objects_snapshots_target is not None:
config = messages.KubernetesObjectsExportConfig()
i... | 34e30e59239e73caa7698f718f01b8192aa98e41 | 260,294 |
def reverse_hex(input_hex):
"""Reverse a HEX string, treating 2 chars as a byte.
Expected results look like this:
reverse_hex('abcdef') = 'efcdab'
Args:
input_hex (str): Input string in hex which needs to be converted.
Returns:
Hex string reversed.
"""
return "".join([inpu... | 4ae94612184f1df6961a09a1f2dfea4167329a1a | 296,250 |
def is_position_sup(pos1, pos2):
"""Return True is pos1 > pos2"""
return pos1 > pos2 | 4704f5053b2de631ab6758ff49c3a243dc479115 | 489,431 |
import re
def split_camel_case(input_string):
"""
This function is used to transform camel case words to more words
Args:
input_string: camel case string
Returns: Extracted words from camel case
"""
splitted = re.sub('([A-Z][a-z]+)', r' \1', re.sub('([A-Z]+)', r' \1', input_string))... | 3ab91f9e3a626fe990d475fb2952f4e2fb479861 | 314,093 |
def hsv_to_rgb(h, s, v):
""" Convert hsv color code to rgb color code.
Naive implementation of Wikipedia method.
See https://ja.wikipedia.org/wiki/HSV%E8%89%B2%E7%A9%BA%E9%96%93
Args:
h (int): Hue 0 ~ 360
s (int): Saturation 0 ~ 1
v (int): Value 0 ~ 1
"""
if s < 0 or 1 ... | 6b210f50b0eaaec7e12b524811fda7bea45cd417 | 262,432 |
def list_product(num_list):
"""Multiplies all of the numbers in a list
"""
product = 1
for x in num_list:
product *= x
return product | 3d6d56f03817f9b4db0e7671f6c95c229a14a042 | 689,175 |
def sort_questions(data_df, grouped_questions, grouped_choices, sort_by_choices):
"""
Sort questions in the dataframe to plot them in their group and sort them in their group according to the responses.
Args:
data_df (df): Dataframe of data to plot
grouped_questions (list): each sub-list is ... | 6239b8369a552c9f02116a980ca9c8b5b55c5daf | 488,519 |
import random
def randhex(n):
"""generate a string of random hex digits"""
return "".join([random.choice("abcdef0123456789") for _ in range(n)]) | 76994a77d6e87b47a91c1e676a48159189112165 | 585,409 |
def IsPrefixLeDecoder(prefix, decoder, name_fcn):
"""Returns true if the prefix is less than or equal to the
corresponding prefix length of the decoder name."""
decoder_name = name_fcn(decoder)
prefix_len = len(prefix)
decoder_len = len(decoder_name)
decoder_prefix = (decoder_name[0:prefix_len]
... | b7f5f01a5fe2a8e626ccbb8b6ec757db34769298 | 150,423 |
def get_passed_tests(log_file_path):
"""Gets passed tests with OK status"""
ok_test_line_pattern = "[ OK ] "
ok_tests = []
with open(log_file_path) as log_file_obj:
for line in log_file_obj.readlines():
if ok_test_line_pattern in line:
ok_tests.append(line.split... | 97fdeab4a2330864f57cd7ac70e8d5f81eaeaa78 | 39,146 |
import itertools
def fast_forward_to_length(sequences, length):
"""
Return an itertools.dropwhile that starts from
the first sequence that has the given length.
>>> list(fast_forward_to_length([list(range(n)) for n in range(6)], 4))
[[0, 1, 2, 3], [0, 1, 2, 3, 4]]
"""
return itertools.drop... | 41650d1bede05d96bfb1c1ceb4b94eee2a1c6f53 | 43,248 |
def get_longitude_tuple(imgMetadata):
"""
Returns the tuple containing the degrees, minutes and seconds of the
longitude coordinate as float values.
"""
return (imgMetadata['Exif.GPSInfo.GPSLongitude'].value[0], imgMetadata['Exif.GPSInfo.GPSLongitude'].value[1], imgMetadata['Exif.GPSInfo.GPSLongitud... | 46b1fa0c319e33c6e75c133446a679f955e6abda | 201,697 |
def pixelsize(info_dict):
""" Computes the pixel size in m/pixel
Parameters
-----------
info_dict: dictionnary
Returns
-------
pixelsize: float
size of the pixel in meter/pixel
"""
# Pixel length (m/pix)
pixsize = info_dict['cameras'][info_dict['channel']]['Photo... | c73f81152a48e8d9211d558b60453ef0bd37f639 | 611,946 |
def f_ema(close_prices, window):
"""Calculates exponential moving average (EMA).
This function takes historical data, and a moving window to calculate EMA.
EMA differs from standard moving average with EMA placing a higher weight on more recent prices.
As the moving average takes previous closing price... | 3f7ece218cc234389da454b24c5a5325b2d932d4 | 505,667 |
def get_machines(graph):
"""
Return list of physical machines in the landscape
:param graph: Networkx graph
:return: List of physical machines
"""
machines = {}
for node, node_data in graph.nodes(data=True):
if node_data["type"] == "machine":
machines[node] = node
re... | 524e12412f5ebe3a717ccfba01eb15bd021eb877 | 594,632 |
import base64
import hashlib
def make_rule_hash(rule):
"""Make a good-enough hash for a rule."""
s = "\r".join([str(rule.severity), str(rule.description), str(rule.tag_pattern)])
return base64.urlsafe_b64encode(hashlib.md5(s.encode('utf-8')).digest())[:8].decode('ascii') | 4281608cecbac4a39c1574a874f469c618dc9f0d | 200,050 |
def add_column(data, col_name, column):
"""Return data where a column has been added."""
return data.assign(**{col_name: column}) | 300b508679891f5b540c96a2b5f8317e13f0d5d7 | 315,657 |
def make_invalid_op(name: str):
"""
Return a binary method that always raises a TypeError.
Parameters
----------
name : str
Returns
-------
invalid_op : function
"""
def invalid_op(self, other=None):
typ = type(self).__name__
raise TypeError(f"cannot perform {n... | 546416345b5040410a438fd1b3f07a4362fb1875 | 522,462 |
def trapezoidal(f, a, b, n=10000):
"""trapez method for numerical integration"""
s = 0.0
h = (b - a) / n
for i in range(0, n):
s += f(a + i * h)
return h * (s + 0.5 * (f(a) + f(b))) | 113a6a047e3fe320f5e0d511dc3119d6564fffa5 | 634,005 |
def tensor_name(tensor):
"""Returns the Tensor's name.
Tensor names always have the structure <op_name>:<int>. This method
returns the portion before the ':'.
Args:
tensor: Tensor.
Returns:
String name of the Tensor.
"""
return tensor.name.split(":")[-2] | 71e814731708d35394697cb3627cc8ad918b3cab | 240,662 |
from typing import Dict
def create_branch(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
name: str,
revision: str,
) -> Dict[str, str]:
"""Execute the OpenAPI `POST /v2/datasets/{owner}/{dataset}/branches`.
Arguments:
access_key: User's access key.
url: T... | 1f9c8c4414faffaa79ee96949662c17051589752 | 478,803 |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
for i in range(0, len(seq)):
iMin = i
for j in range(i+1, len(seq)):
if seq[iMin... | 764c73287b846479bbcde935345c4c0a26fa934e | 619,489 |
import math
def _get_rupture_dimensions(src, mag, nodal_plane):
"""
Calculate and return the rupture length and width
for given magnitude ``mag`` and nodal plane.
:param src:
a PointSource, AreaSource or MultiPointSource
:param mag:
a magnitude
:param nodal_plane:
Inst... | 067b71f4c4f52b82233443cf11c8e03d957f19ce | 533,831 |
def iterpairs(seq):
"""
Parameters
----------
seq: sequence
Returns
-------
iterator returning overlapping pairs of elements
Examples
--------
>>> iterpairs([1, 2, 3, 4])
[(1, 2), (2, 3), (3, 4)
"""
# input may not be sliceable
seq_it = iter(seq)
seq_it_next... | 083f7381187c91259e438fe8aa98ab1f89e8677c | 287,401 |
def check_schedule_cycle_bounds(current_cycle, max_cycle, check_cycle):
"""
Checks whether the provided schedule cycle slot falls within our accepting window
:param current_cycle: int
The current MHP cycle
:param max_cycle: int
The max MHP cycle
:param check_cycle: int
The mh... | bd82b732ecbf9b07b77e4eae4a60fe57f5ad8807 | 553,690 |
def SplitMask(mask, mask_1_length):
"""
Parameters
----------
mask : tuple
tuple of n 1d array of size s, coordonate of s points.
mask_1_length : int
length of mask_1 after spliting
Returns
-------
mask_1 : tuple
tuple of n 1d array of size mask_1_length, c... | 7fcdf87a34bfaa564fdedffe03749e8e4eda1d3a | 480,601 |
def get_size(ser, idx):
"""
Gets indexed value from pd.Series but returns 0 if index not found.
"""
try:
s = ser[idx]
except KeyError:
s = 0
return s | 65f4dc1c936587b85832bbc164419f623f64987f | 400,503 |
def quote(value):
"""Quote a value unambigously w.r.t. its data type.
The result can be used during import into a relational database.
:param value: The value to transform.
:return: ``'null'`` if ``value`` is ``None``, ``'true'`` if it is ``True``,
``'false' if it is ``False``. For numeric v... | 5da0d4faf06e0c1254f828a0d048f56859bbe5b6 | 187,639 |
from typing import Counter
def a_scramble(str_1,str_2):
"""Test if all the letters of word a are contained in word b"""
str_1 = str_1.upper()
str_2 = str_2.upper()
letters = Counter(str_1)
letters.subtract(Counter(str_2))
return all(v >= 0 for v in letters.values()) | e9e088b4c2e18f7efb6ba5749c05eeede4531bef | 402,081 |
def geq_indicate(var, indicator, var_max, thr):
"""Generates constraints that make indicator 1 iff var >= thr, else 0.
Parameters
----------
var : str
Variable on which thresholding is performed.
indicator : str
Identifier of the indicator variable.
var_max : int
An uppe... | 319f18f5343b806b7108dd9c02ca5d647e132dab | 705,773 |
def utility_function(state, monte_carlo):
"""
This functions takes in a state and performs monte carlo
tree search. It returns the utility of the state and
the reward for each possible actions.
:param monte_carlo: a monte_carlo class
:param state: The state should be in the form that monte_carlo... | f0d7e2b341119dcbb1118220f1b4b0b04f79aca5 | 134,110 |
def split_path(path):
"""Split a *canonical* `path` into a parent path and a node name.
The result is returned as a tuple. The parent path does not
include a trailing slash.
>>> split_path('/')
('/', '')
>>> split_path('/foo/bar')
('/foo', 'bar')
"""
lastslash = path.rfind('/')
... | 7c80188a9f84a2c51d684966867efa36e4d807de | 371,887 |
def adjacent(g, x, y):
""" Returns whether nodes x and y are adjacent """
return g.has_edge(x, y) or g.has_edge(y, x) | c7149fe559c8fa6e533f1003b424147e22fba1c6 | 456,959 |
import json
def load_json_schema(filename=None):
""" Loads the given schema file """
if filename is None:
return
with open(filename) as schema_file:
schema = json.loads(schema_file.read())
return schema | f313bba5e3549d5ae161e5ec7a962e92e4e2d96f | 639,903 |
def tally_letters(string):
"""Given a string of lowercase letters, returns a dictionary mapping each
letter to the number of times it occurs in the string."""
tally_dict = {}
for letter in string:
tally_dict[letter] = 0
for letter in string:
tally_dict[letter] += 1
return tally_d... | dba10fc0ac71d27cbbfe02c02d472360ec45a90b | 552,205 |
def get_any(obj, keys, default=None):
"""
Return the first non-None value from any key in `keys`, in order
If all are None, then returns `default`
"""
for key in keys:
val = obj.get(key)
if val is not None:
return val
return default | 8516d455bb5d19bf3a26f1f8f8471e6be3f06816 | 184,212 |
def flows_to_md(flows: dict, disp_num: int) -> str:
"""
Args:
flows: a raw dictionary of flows.
disp_num: The limit of flows to display.
Returns:
A mardkown of <=disp_num of flows, ordered in descending order.
"""
md = '|A|port|B|port|# of Packets|\n|---|---|---|---|---|\n... | d57a3a51396c29930ecb243bf5c21cfef53d2ee2 | 216,745 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.