content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
import pkg_resources
def find_plugins(plug_type):
"""Finds all plugins matching specific entrypoint type.
Arguments:
plug_type (str): plugin entrypoint string to retrieve
Returns:
dict mapping plugin names to plugin entrypoints
"""
return {
entry_point.name: entry_point.load()
for entry_point
in pkg_resources.iter_entry_points(plug_type)
} | f6d6e4debdaec478b14c87582b7e69a9a9bf929b | 26,754 |
from typing import List
def _read_resultset_columns(cursor) -> List[str]:
""" Read names of all columns returned by a cursor
:param cursor: Cursor to read column names from
"""
if cursor.description is None:
return []
else:
return [x[0] for x in cursor.description] | cacefb20b12f327647d1f77bb12216c80388fcd6 | 26,755 |
def max_dict(d):
"""Return dictionary key with the maximum value"""
if d:
return max(d, key=lambda key: d[key])
else:
return None | 446c185a2e986c8a58672d0571f0f100340be7e4 | 26,758 |
import typing
def hex_to_color(color: str) -> typing.Tuple[int, int, int]:
"""
Helper method for transforming a hex string encoding a color into a tuple of color entries
"""
return int(color[:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16) | 40f0c580822effde33a96027863acafb781e44f9 | 26,760 |
import six
def truncate_rows(rows, length=30, length_id=10):
"""
Truncate every string value in a dictionary up to a certain length.
:param rows: iterable of dictionaries
:param length: int
:param length_id: length for dict keys that end with "Id"
:return:
"""
def trimto(s, l):
"""
Trim string to length.
:param s: string to trim
:param l: length
"""
if isinstance(s, six.string_types):
return s[:l + 1]
return s
result = []
for row in rows:
if isinstance(row, dict):
updated = {}
for k, v in row.items():
if k.endswith('Id'):
updated[k] = trimto(v, length_id)
else:
updated[k] = trimto(v, length)
result.append(updated)
elif isinstance(row, six.string_types):
result.append(trimto(row, length))
else:
result.append(row)
return result | db0d02e39f4152ea8dc15a68ab968ae8500bc320 | 26,761 |
def find_adjacent(left, line):
"""
find the indices of the next set of adjacent 2048 numbers in the list
Args:
left: start index of the "left" value
line: the list of 2048 numbers
Returns:
left, right: indices of the next adjacent numbers in the list
if there are no more adjacent numbers, left will be
len(line) - 1
"""
# find the next non zero index for left
while left < (len(line) - 1) and line[left] == 0:
left += 1
right = left + 1
# find the next non zero index after left
while right < len(line) and line[right] == 0:
right += 1
return left, right | 0bca5a7683d5a7d7ab7c25ae416e6448044823f8 | 26,762 |
def max_power_rule(mod, g, tmp):
"""
**Constraint Name**: GenVar_Max_Power_Constraint
**Enforced Over**: GEN_VAR_OPR_TMPS
Power provision plus upward services cannot exceed available power, which
is equal to the available capacity multiplied by the capacity factor.
"""
return (
mod.GenVar_Provide_Power_MW[g, tmp] + mod.GenVar_Upwards_Reserves_MW[g, tmp]
<= mod.Capacity_MW[g, mod.period[tmp]]
* mod.Availability_Derate[g, tmp]
* mod.gen_var_cap_factor[g, tmp]
) | 03cfd061867ce68dcab7068c38eaece69b9906ca | 26,765 |
import itertools
def powerset(iterable):
"""Yield all subsets of given finite iterable.
Based on code from itertools docs.
Arguments:
iterable -- finite iterable
We yield all subsets of the set of all items yielded by iterable.
>>> sorted(list(powerset([1,2,3])))
[(), (1,), (1, 2), (1, 2, 3), (1, 3), (2,), (2, 3), (3,)]
"""
s = list(iterable)
return itertools.chain.from_iterable( itertools.combinations(s, r)
for r in range(len(s)+1) ) | 8bcc95585393e2790a8081337aeb6e9d54173b3d | 26,767 |
import re
def clean_str(s):
""" Clean a string so that it can be used as a Python variable name.
Parameters
----------
s : str
string to clean
Returns
-------
str
string that can be used as a Python variable name
"""
# http://stackoverflow.com/a/3305731
# https://stackoverflow.com/a/52335971
return re.sub(r"\W|^(?=\d)", "_", s) | 26801f0258b61eed5cb2ea7b2da31ccfffad074c | 26,768 |
import fileinput
def get_all_ints(fn):
"""Returns a list of integers from 'fn'.
Arguments:
- fn - a string representing input file name. If None or equal to '-' - read
from STDIN; fn is treated as a single input integer if it is a digit.
"""
if fn is None:
fn = '-'
if fn.isdigit():
return [int(fn)] # just a single integer
all_ints = []
for line in fileinput.input(files=fn):
line = line.rstrip()
if line.isspace():
continue
if not line.isdigit():
raise Exception("Wrong integer '%s'!" % line)
all_ints.append(int(line))
return all_ints | fc0fa992258c87220a674275429ac9a04f999a05 | 26,774 |
def check_answers(answers, answer_key):
"""
Check students’ answers against answer key.
Inputs: answers, a tuple of tuples of strs.
answer_key, a tuple of strs.
Returns: tuple of tuples of ints.
"""
def check_section(current, start, end):
"""
Mark answers in a section.
Inputs: current, a list of strs.
start, an int.
end, an int.
Returns: an int.
"""
counter = 0
for i in range(start, end):
if current[i] == answer_key[i]:
counter += 1
return counter
final = []
for elem in answers:
results = [
check_section(elem, 0, 12),
check_section(elem, 12, 24),
check_section(elem, 24, 36),
check_section(elem, 36, 47),
check_section(elem, 47, 57),
check_section(elem, 57, 71),
]
final.append(tuple(results))
return tuple(final) | 3138247b05f6d33d162ac5dc00bb2e1590ff5fe1 | 26,777 |
from typing import Optional
from typing import List
def parse_match_phase_argument(match_phase: Optional[List[str]] = None) -> List[str]:
"""
Parse match phase argument.
:param match_phase: An optional list of match phase types to use in the experiments.
Currently supported types are 'weak_and' and 'or'. By default the experiments will use
'weak_and'.
:return: A list with all the match phase types to use in the experiments.
"""
if not match_phase:
match_phase_list = ["weak_and"]
else:
assert all(
[x in ["or", "weak_and"] for x in match_phase]
), "match_phase must be a list containing 'weak_and' and/or 'or'."
match_phase_list = match_phase
return match_phase_list | 4d70a4936ebf09e0eb8276bf0477895b726941c2 | 26,780 |
def getMaxMinFreq(msg):
"""
Get the max and min frequencies from a message.
"""
return (msg["mPar"]["fStop"], msg["mPar"]["fStart"]) | 3c28882dce3f2ddd420700997c6f65ed906ec463 | 26,781 |
def l(lam, f, w):
"""Compute l"""
return lam * f * w | 1dca0c85aac1832033fd46b2cf6c9e9045a3c210 | 26,788 |
def isRunning( proc ):
"""is the process running?
Parameters:
* proc (psutil.Popen): Process to be checked
Returns:
* bool: True if the process is running.
"""
if proc == None:
return
proc.poll()
return proc.is_running() | 207afdbf6c6ba5f7a32dcf58f0d0a19cb5ad6085 | 26,789 |
def clean_dict(source, keys=[], values=[]):
"""Removes given keys and values from dictionary.
:param dict source:
:param iterable keys:
:param iterable values:
:return dict:
"""
dict_data = {}
for key, value in source.items():
if (key not in keys) and (value not in values):
dict_data[key] = value
return dict_data | f521ecd878ec0f1a5706d19fec13841d2381745d | 26,795 |
def compute_target(difficulty_target_bits):
"""
Calculate a target hash given a difficulty.
"""
return 2 ** (256 - difficulty_target_bits) | 65f4a5c9e01acf5f829edc949154171b6de96c19 | 26,796 |
def is_available(event):
"""
Checks if the event has the transparency attribute.
:param event: is the event to check.
:return: True if it is transparent and False if not
"""
if 'transparency' in event:
available = True
else:
available = False
return available | 40fe7bb61d2f02a0a030f578cfe44ece79e16d52 | 26,797 |
def is_raisable(obj) -> bool:
"""
Test if object is valid in a "raise obj" statement.
"""
return isinstance(obj, Exception) or (
isinstance(obj, type) and issubclass(obj, Exception)
) | 64c4233b6b8fa0b1f9b8542dd1f06f658e10bf5d | 26,798 |
import re
def check_if_url(string: str) -> bool:
"""Checks if a string passed in is an URL.
Args:
string (str): string to check
Returns:
bool: True if it is, False otherwise
"""
regex = re.compile(
r"^(http://www\.|https://www\.|http://|https://)?[a-z0-9]+([\-.][a-z0-9]+)*\.["
r"a-z]{2,5}(:[0-9]{1,5})?(/.*)?$")
return re.match(regex, string) is not None | badf75a2280fa0e88a162bd853f5f33f231d0137 | 26,799 |
def color_list(s):
"""Convert a list of RGB components to a list of triples.
Example: the string '255,127,0:127,127,127:0,0,255' is converted
to [(255,127,0), (127,127,127), (0,0,255)]."""
return (map(int,rgb.split(',')) for rgb in s.split(':')) | e3c48a2e9c0a2b86c39670317a18916f1cb8ddff | 26,805 |
import json
def read_corpus(file_path):
"""
读取给定的语料库,并把问题列表和答案列表分别写入到 qlist, alist 里面。 在此过程中,不用对字符换做任何的处理(这部分需要在 Part 2.3里处理)
qlist = ["问题1", “问题2”, “问题3” ....]
alist = ["答案1", "答案2", "答案3" ....]
务必要让每一个问题和答案对应起来(下标位置一致)
:param file_path: str, 问答对文件路径
:return:
qlist: list 问题列表
alist: list 答案列表
"""
qlist = []
alist = []
# 读取文件并将json解析为dict
with open(file_path) as f:
json_str = f.read()
qa_dic = json.loads(json_str)
# 解析dict,的到q-a对
for data in qa_dic['data']:
for para in data['paragraphs']:
for qas in para['qas']:
qlist.append(qas['question'])
if len(qas['answers']) == 0:
alist.append(qas['plausible_answers'][0]['text'])
else:
alist.append(qas['answers'][0]['text'])
assert len(qlist) == len(alist) # 确保长度一样
return qlist, alist | b760e92c6dd71336c34d166b668f4cd105357bd4 | 26,809 |
def set_server(client, server_url):
"""Select a Windchill server.
Args:
client (obj): creopyson Client
server_url (str): server URL or Alias
Returns:
None
"""
data = {"server_url": server_url}
return client._creoson_post("windchill", "set_server", data) | 8ba2ad33ad68e41da74804a1a801328fec917f2c | 26,813 |
def dictify(storage_obj):
"""Create a dict object from storage_obj"""
return dict(storage_obj.items()) | 78d09322f27d5e9c4c3d87e63b3cdc46937e7f92 | 26,819 |
from typing import Union
def keycap_digit(c: Union[int, str]) -> str:
"""Returns a keycap digit emoji given a character."""
return (str(c).encode("utf-8") + b"\xe2\x83\xa3").decode("utf-8") | 8db72c79acc173f8e325faca96274b1c08061eb7 | 26,821 |
def worksheet_as_list_of_lists(ws):
"""Convert a Worksheet object to a 2D list."""
table = []
for row in ws.rows:
table.append([c.value for c in row])
return table | a6988996cdd6c64521b20ba3fe23339978dc941d | 26,822 |
def compress(traj, copy=True, **kwds):
"""Wrapper for :meth:`Trajectory.compress`.
Parameters
----------
copy : bool
Return compressed copy or in-place modified object.
**kwds : keywords
keywords to :meth:`Trajectory.compress`
Examples
--------
>>> trc = compress(tr, copy=True, forget=['coords'])
>>> trc.dump('very_small_file.pk')
"""
if copy:
out = traj.copy()
else:
out = traj
out.compress(**kwds)
return out | 42ebefdddeaecd67f61dd884dab31a3ec7f864c9 | 26,823 |
import socket
def binary_ip(host):
"""binary_ip(host) -> str
Resolve host and return IP as four byte string.
Example:
>>> binary_ip("127.0.0.1")
'\\x7f\\x00\\x00\\x01'
"""
return socket.inet_aton(socket.gethostbyname(host)) | d32d8e243e684bbc87ea1e68f91e9a030a5c78c8 | 26,825 |
def _get_integer_intervals(xmin, xmax):
"""
For a given interval [xmin, xmax], returns the minimum interval [iXmin, iXmax] that contains the original one where iXmin and iXmax are Integer numbers.
Examples: [ 3.45, 5.35] => [ 3, 6]
[-3.45, 5.35] => [-4, 6]
[-3.45, -2.35] => [-4, -2]
Parameters
----------
xmin: float
origin of the interval
xmax: float
end of the interval
Returns
-------
Returns the interval [iXmin, iXmax]
iXmin: integer
Minimum value of the integer interval
iMmax: integer
Maximum value of the integer interval
"""
if(xmin<0.0 and xmin!=int(xmin)):
iXmin=int(xmin-1)
else:
iXmin = int(xmin)
if(xmax==int(xmax)):
iXmax=xmax
else:
iXmax=int(xmax+1)
return iXmin, iXmax | 7fa1fd68b960d793c49bc5266d65999c362357ac | 26,826 |
def multByScalar(t , n = 100.0):
"""
Multiply a tuple by a scalar
"""
new = tuple([x * n for x in t])
return new | e91e01b4d45a5b8f200bf65a0eb0466f1e30856a | 26,828 |
def xstr(s):
"""Creates a string object, but for null objects returns
an empty string
Args as data:
s: input object
Returns:
object converted to a string
"""
if s is None:
return ""
else:
return str(s) | b7ea8e906598d259244cc8a7cbb9cb1a142ba3d8 | 26,829 |
import json
def list_to_json_array(value_list, array_name, value_name=None, start=True, stop=True):
"""
Creates a json array from a list. If the optional value_name is passed then the list becomes a json array of dictionary objects.
"""
if start:
start_brace = "{"
else:
start_brace = " "
if stop:
stop_brace = "}"
else:
stop_brace = ","
if value_name is None:
return "%s\"%s\": %s%s" % (start_brace, array_name, json.dumps(value_list), stop_brace)
lst = []
for value in value_list:
data_dict = {value_name: value}
lst.append(data_dict)
return "%s\"%s\": %s%s" % (start_brace, array_name, json.dumps(lst), stop_brace) | 271530c5c318bba12cbb5bfe3e7c908874211923 | 26,830 |
def word(name):
"""\
Function decorator used to tag methods that will be visible in the RPN
builtin namespace.
"""
def decorate_word(function):
function.rpn_name = name.lower()
return function
return decorate_word | 78d76a2a4d260a50aa82f188fde7064d7795ce2c | 26,832 |
import torch
def tensor(data, *args, **kwargs):
"""
In ``treetensor``, you can create a tree tensor with simple data structure.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.tensor(True) # the same as torch.tensor(True)
tensor(True)
>>> ttorch.tensor([1, 2, 3]) # the same as torch.tensor([1, 2, 3])
tensor([1, 2, 3])
>>> ttorch.tensor({'a': 1, 'b': [1, 2, 3], 'c': [[True, False], [False, True]]})
<Tensor 0x7ff363bbcc50>
├── a --> tensor(1)
├── b --> tensor([1, 2, 3])
└── c --> tensor([[ True, False],
[False, True]])
"""
return torch.tensor(data, *args, **kwargs) | 438710f3733886646005367c04e97021c361f7bb | 26,834 |
from typing import Mapping
def isdict(obj):
"""Return True if the obj is a mapping of some sort."""
return isinstance(obj, Mapping) | 641fea1920e9ed17fec2a51116cd8bcad816487a | 26,836 |
def calc_multiplicity(mut_series, purity, cr_diff, c0):
"""Calculate multiplicity for the mutation"""
mu_min_adj = (mut_series['mu_minor'] - c0) / cr_diff
mu_maj_adj = (mut_series['mu_major'] - c0) / cr_diff
# returns the multiplicity * CCF for this mutation
return mut_series['VAF'] * (purity * (mu_min_adj + mu_maj_adj) + 2 * (1 - purity)) / purity | 9b9b818ef7c13a653134ea27dc8518c7619d9428 | 26,838 |
def dictElement(element, prefix=None):
"""Returnss a dictionary built from the children of *element*, which must be
a :class:`xml.etree.ElementTree.Element` instance. Keys of the dictionary
are *tag* of children without the *prefix*, or namespace. Values depend on
the content of the child. If a child does not have any children, its text
attribute is the value. If a child has children, then the child is the
value."""
dict_ = {}
length = False
if isinstance(prefix, str):
length = len(prefix)
for child in element:
tag = child.tag
if length and tag.startswith(prefix):
tag = tag[length:]
if len(child) == 0:
dict_[tag] = child.text
else:
dict_[tag] = child
return dict_ | 20fe0475815fb6bbf685a45b54330738426987fd | 26,853 |
def time_like(line):
"""Test if a line looks like a timestamp"""
# line might be like '12:33 - 12:48' or '19:03'
if line.count(':') == 2:
if line.count('-') >= 1:
line_without = line.replace(':', '')
line_without = line_without.replace('-', '')
line_without = line_without.replace(' ', '')
try:
int(line_without)
return True
except ValueError:
pass
if line.count(':') == 1:
line_without = line.replace(':', '')
try:
int(line_without)
return True
except ValueError:
pass
return False | 19675238633cafd1e30051ff18bb4d1a783663f6 | 26,856 |
def find1Dpeak(arr):
"""
Finds a 1D peak in a list of comparable types
A 1D peak is an x in L such that it is greater
than or equal to all its neighbors.
ex. [1, 1, 2, 1] in this list, the elements at
index 0 and index 2 are peaks.
Complexity: O(log(n))
where n = len(list)
"""
n = len(arr)
if n == 1:
return arr[0]
if n == 2:
return max(arr)
if arr[n / 2] < arr[(n / 2) - 1]:
return find1Dpeak(arr[:n / 2])
if arr[n / 2] < arr[(n / 2) + 1]:
return find1Dpeak(arr[n / 2:])
return arr[n / 2] | e8dc8c0ccf453a0246fa0d59e288e0e4591216e6 | 26,859 |
def set_origin(cut_plane, center_x1=0.0, center_x2=0.0):
"""
Establish the origin of a CutPlane object.
Args:
cut_plane (:py:class:`~.tools.cut_plane.CutPlane`):
Plane of data.
center_x1 (float, optional): x1-coordinate of origin.
Defaults to 0.0.
center_x2 (float, optional): x2-coordinate of origin.
Defaults to 0.0.
Returns:
cut_plane (:py:class:`~.tools.cut_plane.CutPlane`):
Updated plane of data.
"""
# Store the un-interpolated input arrays at this slice
cut_plane.df.x1 = cut_plane.df.x1 - center_x1
cut_plane.df.x2 = cut_plane.df.x2 - center_x2
return cut_plane | f29ecbb82450adeecebdd2652392d37828751348 | 26,863 |
import hashlib
def _hash(mapping: dict) -> str:
"""
Return a hash of an entire dictionary.
Args:
mapping: a dictionary of hash-able keys to hash-able values, i.e.,
__str__ should return a unique representation of each object
Returns:
a hash of the dictionary
"""
# create a string to store the mapping in
mapping_str = ''
# iterate over the sorted dictionary keys to ensure reproducibility
for key in sorted(mapping.keys()):
# add the key value pairing to the string representation
mapping_str += '{}{}'.format(key, mapping[key])
# convert the string to bytes and return the MD5 has of the bytes
return hashlib.md5(bytes(mapping_str, 'utf8')).hexdigest() | 3e608ad0739480bb4fba1367ed2534d09d9a2ed8 | 26,869 |
def parse_arg_type(arg):
"""
Parses the type of an argument based on its string value.
Only checks ints, floats, and bools, defaults to string.
For instance, "4.0" will convert to a float(4.0)
:param arg: The argument value
:return: The value converted to the proper type.
"""
if type(arg) != str:
return arg
else:
# check int
try:
return int(arg)
except ValueError:
pass
# check float
try:
return float(arg)
except ValueError:
pass
# check bool
if arg.lower() == "true":
return True
elif arg.lower() == "false":
return False
# return any other string
return arg | c2897f57f2d6df2e7e1c4a5c41cd35d04a386597 | 26,870 |
def is_substring_divisible(num: tuple) -> bool:
"""
Returns True if the pandigital number passes
all the divisibility tests.
>>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9))
False
>>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9))
False
>>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9))
True
"""
if num[3] % 2 != 0:
return False
if (num[2] + num[3] + num[4]) % 3 != 0:
return False
if num[5] % 5 != 0:
return False
tests = [7, 11, 13, 17]
for i, test in enumerate(tests):
if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0:
return False
return True | bf212de2c82890c950e00fc81bdc781efc608ab7 | 26,874 |
def fizz_buzz_custom_2(string_one="Fizz", string_two="Buzz", num_one=3, num_two=5):
"""
>>> not 0
True
>>> not 5 % 5
True
>>> not 6 % 5
False
>>> "Test" * True
'Test'
>>> "Test" * False
''
>>> "" or 1
1
"""
return [
f"{string_one * (not d % num_one)}{string_two * (not d % num_two)}" or d
for d in range(1, 101)
] | 6faed46a42fb3383a6c0cb42f7807657d82e0aa6 | 26,879 |
def get_threshold(rows, bands):
"""Approximate threshold from bandwidth and number of rows
:param rows: rows per band
:param bands: number of bands
:return: threshold value
:rtype: float
"""
return (1. / bands) ** (1. / rows) | 3c5a5e417e96797e18b571cb7c09597442cb5f44 | 26,886 |
def keypoint_2d_loss(criterion_keypoints, pred_keypoints_2d, gt_keypoints_2d, has_pose_2d):
"""
Compute 2D reprojection loss if 2D keypoint annotations are available.
The confidence (conf) is binary and indicates whether the keypoints exist or not.
"""
conf = gt_keypoints_2d[:, :, -1].unsqueeze(-1).clone()
loss = (conf * criterion_keypoints(pred_keypoints_2d, gt_keypoints_2d[:, :, :-1])).mean()
return loss | d5ffabe27443d6c9ea251a0d8205e8ca33f724c8 | 26,887 |
def getInt(s, notFoundReturn=-1):
""" attempt to find a positive integer in a string
@param s [string]
@param notFoundReturn = value to be returned if no integer is found
@return int
"""
firstIx = -1
for i, c in enumerate(s):
if c in "0123456789":
firstIx = i
break
if firstIx == -1:
return notFoundReturn
to = firstIx+1
while 1:
#print "s=%r firstIx=%r to=%r" % (s, firstIx, to)
# if (nextIx) at end of string, break
if to+1 > len(s): break
ch = s[to]
#print "to=%r ch=%r" % (to, ch)
if ch not in "0123456789": break
to += 1
#print "firstIx=%r to=%r" % (firstIx, to)
numStr = s[firstIx:to]
return int(numStr) | 5f5c5b7bac0b160eddedfde1d2008c628dd7a9a6 | 26,893 |
import curses
def create_window(start_x, start_y, width, height):
"""Create window helper method with sane parameter names."""
return curses.newwin(height, width, start_y, start_x) | 8ba73d8cad2e2b730ea2f79795dd6407d6565192 | 26,901 |
def _get_metadata_revision(metadata_repo, mongo_repo, project, revision):
"""Get the metadata revision that corresponds to a given repository, project, revision."""
for metadata_revision in metadata_repo.list_revisions():
reference = metadata_repo.get_reference(metadata_revision, project)
if not reference:
# No reference for this revision. This should not happen but we keep trying in
# case we can find an older revision with a reference.
continue
if mongo_repo.is_ancestor(reference, revision):
# We found a reference that is a parent of the current revision.
return metadata_revision
return None | 35436be9b586319d5e60dd99e0ff4a3ef6bed042 | 26,903 |
def _positive(index: int, size: int) -> int:
"""Convert a negative index to a non-negative integer.
The index is interpreted relative to the position after the last item. If
the index is smaller than ``-size``, IndexError is raised.
"""
assert index < 0 # noqa: S101
index += size
if index < 0:
raise IndexError("lazysequence index out of range")
return index | ee23eb6ffba4d539d333cd649304b5bd879f43df | 26,907 |
def parse_field_configured(obj, config):
"""
Parses an object to a Telegram Type based on the configuration given
:param obj: The object to parse
:param config: The configuration:
- is array?
- is array in array?
- type of the class to be loaded to
:return: the parsed object
"""
foreign_type = config if type(config) != dict else config['class']
if type(config) == dict:
if 'array' in config and config['array'] is True:
return [foreign_type(x) for x in obj]
elif 'array_of_array' in config and config['array_of_array'] is True:
res = []
for inner_obj in obj:
res.append([foreign_type(x) for x in inner_obj])
return res
return foreign_type(obj) | e03acf6149653b86b8565a492bfd1eeea15464b6 | 26,909 |
def _compute_lineline_intersection(line1_pt1, line1_pt2,
line2_pt1, line2_pt2):
"""Algorithm to compute a line to line intersection, where the
two lines are both defined by two points. Based on this article:
https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
:param line1_pt1: First point on first line
:type line1_pt1: tuple
:param line1_pt2: First point on first line
:type line1_pt2: tuple
:param line2_pt1: First point on first line
:type line2_pt1: tuple
:param line2_pt2: First point on first line
:type line2_pt2: tuple
:return: intersection point (p_x, p_y), if it exists
:rtype: tuple or None
"""
(x1, y1) = line1_pt1
(x2, y2) = line1_pt2
(x3, y3) = line2_pt1
(x4, y4) = line2_pt2
# Check for parallel lines
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if denominator == 0:
return None
p_x = ((x1*y2 - y1*x2) * (x3 - x4) - (x1 - x2) * (x3*y4 - y3*x4)) \
/ denominator
p_y = ((x1*y2 - y1*x2) * (y3 - y4) - (y1 - y2) * (x3*y4 - y3*x4)) \
/ denominator
return (p_x, p_y) | ec34a6f2aca4fc918d1e384d3ac1fb7615af4f35 | 26,919 |
def actionable(msg):
"""
Make instructions to actionable items green so they stand out from generic logging.
"""
return f'\033[92m{msg}\033[0m' | 49a350ee1429baeb39d6affbfc5b8dbc8351172f | 26,926 |
def _create_cg_with_member(vnx_gf):
""" Helper function to create a cg with a lun
:param vnx_gf: the vnx general test fixture
:return: created cg
"""
lun_name = vnx_gf.add_lun_name()
lun = vnx_gf.pool.create_lun(lun_name)
cg_name = vnx_gf.add_cg_name()
cg = vnx_gf.vnx.create_cg(cg_name)
cg.add_member(lun)
return cg | 98f5646cb61b2ae8aecf07865461e45edf4dcb64 | 26,929 |
def get_all_headers(message, key):
"""
Given an HTTPMessage, return all headers matching a given key.
"""
return message.get_all(key) | 079d0e7c6ea3d55228ba3c74f4590a1bf4ee325d | 26,930 |
def as_unsigned_int32_array(byte_array):
"""Interprets array of byte values as unsigned 32 bit ints."""
def uint32(a, b, c, d):
return a + (b << 8) + (c << 16) + (d << 24)
return [uint32(*byte_array[i:i + 4]) for i in range(0, len(byte_array), 4)] | dcfb5b5504056d3784c43a4adda876a6bc51f6ae | 26,931 |
def normalise_period(val):
"""Return an integer from 1 to 12.
Parameters
----------
val : str or int
Variant for period. Should at least contain numeric characters.
Returns
-------
int
Number corresponding to financial period.
Examples
--------
>>> normalise_period('P6')
6
>>> normalise_period(202106)
6
"""
val = ''.join(c for c in str(val) if c.isdigit())
return int(val[-2:]) | bf1d5e334d49d98404193fbbc2047bf41f7b24e5 | 26,937 |
from datetime import datetime
def humanize_timestamp(utc_timestamp, verbose=False):
"""
Convert a utc timestamp into a human readable relative-time.
"""
timedelta = datetime.utcnow() - datetime.utcfromtimestamp(utc_timestamp)
seconds = int(timedelta.total_seconds())
if seconds < 60:
return 'moments ago' if verbose else '0min'
minutes = seconds // 60
if minutes < 60:
return ('%d minutes ago' % minutes) if verbose else ('%dmin' % minutes)
hours = minutes // 60
if hours < 24:
return ('%d hours ago' % hours) if verbose else ('%dhr' % hours)
days = hours // 24
if days < 30:
return ('%d days ago' % days) if verbose else ('%dday' % days)
months = days // 30.4
if months < 12:
return ('%d months ago' % months) if verbose else ('%dmonth' % months)
years = months // 12
return ('%d years ago' % years) if verbose else ('%dyr' % years) | 62a402607f8c96775606892771850d07795a160b | 26,939 |
def get_marker(label, chunk):
"""
Returns marker instance from chunk based on the label correspondence
"""
for marker in chunk.markers:
if label == marker.label:
return marker
print("Marker not found! " + label)
return False | e479568f5b6bc96be0bcdfbf7a428820ab953cce | 26,941 |
def check_default_empty(default):
"""Helper function to validate if a default parameter is empty based on type"""
if isinstance(default, str) or isinstance(default, list):
return len(default) == 0
elif isinstance(default, int):
return False
elif isinstance(default, dict):
return len(default.keys()) == 0 | 19b94f3b25450d39c5c2b3ddc0af2758e1fc1b5f | 26,943 |
import itertools
def flatten(iterable):
"""Reduce dimensionality of iterable containing iterables
Args:
iterable: A multi-dimensional iterable
Returns:
A one dimensional iterable
"""
return itertools.chain.from_iterable(iterable) | 3869bbc5f2e1377d5c893ce7e35c3b91988916a7 | 26,945 |
def check_lead_zero(to_check):
"""Check if a number has a leading 0.
Args:
to_check (str): The number to be checked.
Returns:
True if a leading 0 is found or the string is empty, False otherwise.
"""
if str(to_check) in (None, ''):
return True
elif str(to_check[0]) != '0':
return False
else:
return True | 39302f3f57ac2d9714d3057a744130cd3a5e5aa9 | 26,948 |
def dec2bin(x: int, n: int = 2) -> str:
"""Converts a single decimal integer to it binary representation
and returns as string for length >= n.
"""
return str(int(bin(x)[2:])).zfill(n) | cf5713c5f8855c5f737e4533f780ac75ee3abfa1 | 26,950 |
import math
def convert_bytes_to_string(number: int) -> str:
"""Returns the conversion from bytes to the correct
version (1024 bytes = 1 KB) as a string.
:param number: number to convert to a readable string
:return: the specified number converted to a readable string
"""
num = number
factor = 1024
if num >= factor:
num /= factor
if num >= factor:
num /= factor
if num >= factor:
num /= factor
if num >= factor:
num /= factor
if num >= factor:
num /= factor
suffix = " PB"
else:
suffix = " TB"
else:
suffix = " GB"
else:
suffix = " MB"
else:
suffix = " KB"
else:
suffix = " Bytes"
rounding_factor = 10**2
rounded = math.floor(num * rounding_factor) / rounding_factor
return f"{rounded:.2f}" + suffix | ca8f5d3417ad989bc12b2bf9cb76a561c735c548 | 26,954 |
def _get_location(location_text):
"""Used to preprocess the input location_text for URL encoding.
Doesn't do much right now. But provides a place to add such steps in future.
"""
return location_text.strip().lower() | 979471af5d40f0a58a2c4e4e7e26af18779ca890 | 26,955 |
import fnmatch
def _match_in_cache(cache_tree, list_of_names):
"""
:type cache_tree: defaultdict
:description cache_tree: a defaultdict initialized with the tree() function. Contains names
of entries in the kairosdb, separated by "." per the graphite convention.
:type list_of_names: list
:description list_of_names: list of strings, in order, that will be sought after in the cache tree.
:rtype: list
:return: A list of matches, possibly empty.
Given a cache_tree, and a prefix, returns all of the values associated with that prefix,
that is, the keys that reside under the prefix.
"""
head_item = list_of_names[0]
# print "head_item is {0}".format(head_item)
head_item_matches = [ m for m in cache_tree.keys() if fnmatch.fnmatch(m, head_item) ]
if head_item not in cache_tree.keys():
# print "A"
return [] # Empty List to signify we're done here
elif len(list_of_names) == 1:
# print "B"
return cache_tree[head_item].keys()
else:
# print "C"
tail_list = list_of_names[1:]
return _match_in_cache(cache_tree[head_item], tail_list) | e559125f4b62a87956e0d30f5d8c3e4b2c7abef8 | 26,956 |
def range_intersect(a, b, extend=0):
"""
Returns the intersection between two reanges.
>>> range_intersect((30, 45), (55, 65))
>>> range_intersect((48, 65), (45, 55))
[48, 55]
"""
a_min, a_max = a
if a_min > a_max:
a_min, a_max = a_max, a_min
b_min, b_max = b
if b_min > b_max:
b_min, b_max = b_max, b_min
if a_max + extend < b_min or b_max + extend < a_min:
return None
i_min = max(a_min, b_min)
i_max = min(a_max, b_max)
if i_min > i_max + extend:
return None
return [i_min, i_max] | 9184172de3921cfb74bccaeee9b15405045a1327 | 26,958 |
import codecs
def rot13(s: str) -> str:
"""ROT-13 encode a string.
This is not a useful thing to do, but serves as an example of a
transformation that we might apply."""
return codecs.encode(s, "rot_13") | a2413c3bd835dc09b445eb030aa6179e14411e17 | 26,960 |
from typing import Any
def is_numeric_scalar(x: Any) -> bool:
"""
Returns if the given item is numeric
>>> is_numeric_scalar("hello")
False
>>> is_numeric_scalar("234")
True
>>> is_numeric_scalar("1e-5")
True
>>> is_numeric_scalar(2.5)
True
"""
if isinstance(x, (float, int)):
return True
elif isinstance(x, str):
try:
_ = float(x)
return True
except ValueError:
return False
return False | 7a0b8bd35be91b4ad6bda49d6a3543c1ca8f5ac7 | 26,963 |
def is_file_image(filename):
"""Return if a file's extension is an image's.
Args:
filename(str): file path.
Returns:
(bool): if the file is image or not.
"""
img_ex = ['jpg', 'png', 'bmp', 'jpeg', 'tiff']
if '.' not in filename:
return False
s = filename.split('.')
if s[-1].lower() not in img_ex:
return False
if filename.startswith('.'):
return False
return True | 68df1997c4874cd990ca24739c91555378fc73fd | 26,964 |
def _get_jgroup(grouped_data):
"""Get the JVM object that backs this grouped data, taking into account the different
spark versions."""
d = dir(grouped_data)
if '_jdf' in d:
return grouped_data._jdf
if '_jgd' in d:
return grouped_data._jgd
raise ValueError('Could not find a dataframe for {}. All methods: {}'.format(grouped_data, d)) | 99b2ac71cd6d0ccf98976df43966ccabf14bcb98 | 26,967 |
def parse_fasta (lines):
"""Returns 2 lists: one is for the descriptions and other one for the sequences"""
descs, seqs, data = [], [], ''
for line in lines:
if line.startswith('>'):
if data: # have collected a sequence, push to seqs
seqs.append(data)
data = ''
descs.append(line[1:]) # Trim '>' from beginning
else:
data += line.rstrip('\r\n')
# there will be yet one more to push when we run out
seqs.append(data)
return descs, seqs | 4dea579720f43f348389e53751c0308f1c493296 | 26,968 |
def is_bool(obj):
"""Returns ``True`` if `obj` is a ``bool``."""
return isinstance(obj, bool) | 6b63b9479c8a388a056c80cc62be74c548ac3504 | 26,974 |
def files_are_identical(pathA, pathB):
"""
Compare two files, ignoring carriage returns,
leading whitespace, and trailing whitespace
"""
f1 = [l.strip() for l in pathA.read_bytes().splitlines()]
f2 = [l.strip() for l in pathB.read_bytes().splitlines()]
return f1 == f2 | 60eeba55aa443577e98c45a46c10c1dc585e6c9f | 26,975 |
import uuid
def _maybe_convert(value):
"""Possibly convert the value to a :py:class:`uuid.UUID` or
:py:class:`datetime.datetime` if possible, otherwise just return the value
:param str value: The value to convert
:rtype: uuid.UUID|datetime.datetime|str
"""
try:
return uuid.UUID(value)
except ValueError:
return value | 66e70d33bd9b09c19c762ca66d4f50638a225821 | 26,976 |
import pickle
def load(name: str) -> object:
"""load an object using pickle
Args:
name: the name to load
Returns:
the unpickled object.
"""
with open(name, "rb") as file:
obj = pickle.load(file)
return obj | b8e11b703bea907386e2248c313c390429453a99 | 26,978 |
def decodeAny(string):
"""Try to decode the string from UTF-8 or latin9 encoding."""
if isinstance(string, str):
return string
try:
return string.decode('utf-8')
except UnicodeError:
# decoding latin9 never fails, since any byte is a valid
# character there
return string.decode('latin9') | 4acd087710118e72d8e142a230b36c57a5b70253 | 26,979 |
import pkg_resources
def python_package_version(package: str) -> str:
"""
Determine the version of an installed Python package
:param package: package name
:return: version number, if could be determined, else ''
"""
try:
return pkg_resources.get_distribution(package).version
except pkg_resources.DistributionNotFound:
return '' | 53f8de290418b1d64355f44efde162bed3a36b45 | 26,982 |
def set_extension(path, ext):
"""Set the extension of file.
Given the path to a file and the desired extension, set the extension of the
file to the given one.
Args:
path: path to a file
ext: desired extension
Return:
path with the correct extension
"""
ext = ext.replace(".", "")
current_ext = path.split(".")
if len(current_ext) == 2:
path = path.replace(current_ext[1], ext)
else:
path = path + "." + ext
return path | 5764e085a204aa209f085dbeb8d043c710734e11 | 26,983 |
import re
def get_select_cols_and_rest(query):
"""
Separate the a list of selected columns from
the rest of the query
Returns:
1. a list of the selected columns
2. a string of the rest of the query after the SELECT
"""
from_loc = query.lower().find("from")
raw_select_clause = query[0:from_loc].rstrip()
rest_of_query = query[from_loc:len(query)]
# remove the SELECT keyword from the query
select_pattern = re.compile("select", re.IGNORECASE)
raw_select_clause = select_pattern.sub('', raw_select_clause)
# now create and iterate through a list of of the SELECT'ed columns
selected_columns = raw_select_clause.split(',')
selected_columns = [c.strip() for c in selected_columns]
return selected_columns, rest_of_query | 33b397e7894792c0b354c41f219c609dc4df5927 | 26,984 |
def getTableHTML(rows):
""" Binds rows items into HTML table code.
:param list rows: an array of row items
:return: HTML table code with items at rows
:rtype: str
>>> getTableHTML([["Name", "Radek"], ["Street", "Chvalinska"]])
'<table><tr><td>Name</td><td>Radek</td></tr><tr><td>Street</td><td>Chvalinska</td></tr><table>'
"""
if rows:
result = "<table>"
for row in rows:
result += "<tr>"
for item in row:
result += "<td>%s</td>" % item
result += "</tr>"
result += "<table>"
return result
else:
return "" | 931c8af65052c6a4455feae7f2f3a0f65d33a347 | 26,990 |
def build_complement(c):
"""
The function convert alphabets in input c into certain alphabets.
:param c: str, can be 'A','T','G','C','a','t','g','c'
:return: The string of converted alphabets.
"""
c = c.upper() # The Str Class method changes input c into capital.
total = ''
for i in range(len(c)):
# Using for loop to convert the input alphabet from index 0 to the last index
# to certain alphabet, A to T, C to G vice versa.
ans = ''
if c[i] == 'A':
ans += 'T'
if c[i] == 'T':
ans += 'A'
if c[i] == 'C':
ans += 'G'
if c[i] == 'G':
ans += 'C'
total += ans
print('The complement of', c, 'is', total)
return total | 6fece325432ac061d5f7577c85cb59c19918ed83 | 26,992 |
def normalise_reward(reward, prev_lives, curr_lives):
"""
No reward normalisation is required in pong; -1 indicates opponent has
scored, 0 indicates game is still in play and 1 indicates player has
scored.
"""
return reward | ff3c537ac6090692a05c7ee8c6f5bde890ed4d40 | 26,996 |
import torch
def _make_input(t, requires_grad=False, device=torch.device('cpu')):
"""Make zero inputs for AE loss.
Args:
t (torch.Tensor): input
requires_grad (bool): Option to use requires_grad.
device: torch device
Returns:
torch.Tensor: zero input.
"""
inp = torch.autograd.Variable(t, requires_grad=requires_grad)
inp = inp.sum()
inp = inp.to(device)
return inp | c65c4ba243d786471b810d48af2251fff94c5d5f | 26,997 |
import torch
def bce_loss(pred, target, false_pos_weight=1.0, false_neg_weight=1.0):
"""Custom loss function with options to independently penalise
false positives and false negatives.
"""
norm = torch.tensor(1.0 / float(len(pred)))
tiny = torch.finfo(pred.dtype).tiny
false_neg = torch.sum(target * torch.log(
torch.clip(pred, min=tiny) # preventing -inf
))
false_pos = torch.sum(
(torch.tensor(1.0) - target)
* torch.log(torch.clip(torch.tensor(1.0) - pred, min=tiny))
)
return - norm * (false_pos_weight * false_pos
+ false_neg_weight * false_neg) | b9ed60d886212bc821fed3f21c4e58e6953b1e02 | 26,999 |
def bernoulli_kl(q_probs, p_probs):
"""
computes the KL divergence per batch between two Bernoulli distributions
parametrized by q_probs and p_probs
Note: EPS is added for numerical stability, see
https://github.com/pytorch/pytorch/issues/15288
Args:
q_probs (torch tensor): mean of q [batch_size, *latent_dims]
p_probs (torch tensor): mean of p [batch_size, *latent_dims]
Returns:
kl_div (torch tensor): kl divergence [batch_size, *latent_dims]
"""
EPS = 1e-32
p1 = p_probs
p0 = 1 - p1
q1 = q_probs
q0 = 1 - q1
logq1 = (q1 + EPS).log()
logq0 = (q0 + EPS).log()
logp1 = (p1).log()
logp0 = (p0).log()
kl_div_1 = q1 * (logq1 - logp1)
kl_div_0 = q0 * (logq0 - logp0)
return kl_div_1 + kl_div_0 | 52253d4cd07b6ceb5081236ea5167b87b754c2fc | 27,001 |
def formatGpuCount(gpuCount):
"""
Convert the GPU Count from the SLurm DB, to an int
The Slurm DB will store a string in the form "gpu:1" if a GPU was requested
If a GPU was not requested, it will be empty
"""
if gpuCount:
intGpuCount = int("0"+gpuCount.split(":")[1])
return intGpuCount
else:
return int(0) | bb15f87da94d5994c9a08ff0614f5381eb3265de | 27,002 |
from typing import MutableMapping
from typing import Any
def to_nested_dict(d: dict):
"""
Converts a flat dictionary with '.' joined keys back into
a nested dictionary, e.g., {a.b: 1} -> {a: {b: 1}}
"""
new_config: MutableMapping[str, Any] = {}
for k, v in d.items():
if "." in k:
sub_keys = k.split(".")
sub_d = new_config
for sk in sub_keys[:-1]:
sub_d = sub_d.setdefault(sk, {})
sub_d[sub_keys[-1]] = v
else:
new_config[k] = v
return new_config | 18230ecf0798ee5f2c9b74dccfb90b28547354e8 | 27,004 |
from typing import Any
def validate_boolean(var: Any) -> bool:
"""Evaluates whether an argument is boolean True/False
Args:
var: the input argument to validate
Returns:
var: the value if it passes validation
Raises:
AssertionError: `var` was not boolean
"""
assert isinstance(var, bool), "Argument must be True/False"
return var | 67d8751a60fa6621f0fb366ab44cd017dfe3bd8c | 27,008 |
import functools
def or_none(fn):
"""
Wraps `fn` to return `None` if its first argument is `None`.
>>> @or_none
... def myfunc(x):
... return 2 * x + 3
>>> myfunc(4)
11
>>> myfunc(None)
"""
@functools.wraps(fn)
def wrapped(arg, *args, **kw_args):
return None if arg is None else fn(arg, *args, **kw_args)
return wrapped | 54346619090c1aab12498297a31bb017d85377f5 | 27,012 |
def get_segment_output_path(output_path, muxing_output_path):
"""
Returns the output path for a stream segment.
"""
segment_path = muxing_output_path
substr = muxing_output_path[0:len(output_path)]
if substr == output_path:
return muxing_output_path[len(output_path):]
return segment_path | 7c35c5becf6b6eb4f20399f6fa5b3367bce5af79 | 27,018 |
def read_flat_parameters(fname):
"""Read flat channel rejection parameters from .cov or .ave config file"""
try:
with open(fname, 'r') as f:
lines = f.readlines()
except:
raise ValueError("Error while reading %s" % fname)
reject_names = ['gradFlat', 'magFlat', 'eegFlat', 'eogFlat', 'ecgFlat']
reject_pynames = ['grad', 'mag', 'eeg', 'eog', 'ecg']
flat = dict()
for line in lines:
words = line.split()
if words[0] in reject_names:
flat[reject_pynames[reject_names.index(words[0])]] = \
float(words[1])
return flat | 34ca5d9f4946d8ee087126b7932596949081b0c3 | 27,019 |
def get_rectangle_coordinates(win):
"""
Gets the coordinates of two opposite points that define a rectangle and
returns them as Point objects.
"""
point_1 = win.getMouse()
point_2 = win.getMouse()
return point_1, point_2 | 75a605ea628c8d9c6817bf727de3542894ac555f | 27,021 |
def identifyL23(addition):
"""Check if it is L2 or L3 delta request."""
return 'L3' if 'routes' in list(addition.keys()) else 'L2' | 63c47a0de8142ddae8559d2e4cc236e2f5e972fd | 27,024 |
def find_border_crossing(subset, path, final_state):
"""
Find the transition that steps outside the safe L{subset}.
@param subset: Set of states that are safe.
@type subset: C{set} of L{State}
@param path: Path from starting state to L{final_state}, sequence of state
and its outgoing edge.
@type path: C{list} of pairs (L{State}, L{Event}
@param final_state: Final state of the path.
@type final_state: L{State}
@return: C{None} if the path stays within the safe subset, else a triplet
(from-state, event, dest-state).
@rtype: Either C{None} or (L{State}, L{Event}, L{State})
@precond: Initial state of the path must be in L{subset}
"""
if len(path) == 0:
# No path => final_state is also the first state => must be safe
assert final_state in subset
return None
assert path[0][0] in subset
pred_state, pred_evt = None, None
for state, evt in path:
if pred_state is not None and state not in subset:
# Tests may hold for the second or further entry of the path
return (pred_state, pred_evt, state)
pred_state, pred_evt = state, evt
if final_state in subset:
return None
return (pred_state, pred_evt, final_state) | 8cf7953897066af2453c4bb428fb01326a4aa25f | 27,026 |
def randomize(df, seed):
"""Randomizes the order of a Pandas dataframe"""
return df.sample(len(df), random_state=seed).reset_index(drop=True) | deb6f1327b993a5a39255bdf2a2b22bc61cdd0a3 | 27,028 |
import re
def count_expr_arity(str_desc):
""" Determine the arity of an expression directly from its str
descriptor """
# we start by extracting all words in the string
# and then count the unique occurence of words matching "x", "y", "z" or "t"
return len(set(var for var in re.findall("\w+", str_desc) if re.fullmatch("[xyzt]", var))) | 6e94b6da17b90de4b6b4734add65311842af467d | 27,031 |
from pkg_resources import EntryPoint
def resolveDotted(dotted_or_ep):
""" Resolve a dotted name or setuptools entry point to a callable.
"""
return EntryPoint.parse('x=%s' % dotted_or_ep).resolve() | 504b73a7a3735753db57ae8b86361594b580a3cd | 27,040 |
def get_request_header(headers):
"""
Get all headers that should be included in the pre-signed S3 URL. We do not add headers that will be
applied after transformation, such as Range.
:param headers: Headers from the GetObject request
:return: Headers to be sent with pre-signed-url
"""
new_headers = dict()
headers_to_be_presigned = ['x-amz-checksum-mode', 'x-amz-request-payer', 'x-amz-expected-bucket-owner', 'If-Match',
'If-Modified-Since', 'If-None-Match', 'If-Unmodified-Since']
for key, value in headers.items():
if key in headers_to_be_presigned:
new_headers[key] = value
return new_headers | 97af84f361bc4265d934dbd2cf5398ad4f744e1e | 27,043 |
def check_game(board, last_move):
"""
check if any player has managed to get 3 marks in a row, column or diagonally.
:param {String[]} board : current board with marker locations of both players
:param {int} last_move : between 1-9 where the most recent marker was put.
:return {Boolean} : True if player who played "last_move" has won. False otherwise
"""
win = ["012","345", "678", "036", "147", "258", "048", "246"]
win = list(filter(lambda string : str(last_move) in string, win))
for x in win:
if board[int(x[0])] == board[last_move]:
if board[int(x[1])] == board[last_move]:
if board[int(x[2])] == board[last_move]:
return True
return False | 59bc4f5e38b469cd49b59b342ca402b50d591948 | 27,045 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.