content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def normalize_ordinal(ordinal):
"""
Given a string like "first" or "1st" or "1", return the canonical version ('1').
"""
return ordinal[0] if ordinal[0].isdigit() else str('ieho'.index(ordinal[1].lower()) + 1)
|
eceb5e26c54ce987eb65ce40c711000cc3164086
| 35,548 |
def comp_height(self):
"""Compute the height of the Hole (Rmax-Rmin)
Parameters
----------
self : Hole
A Hole object
Returns
-------
H : float
Height of the hole
"""
(Rmin, Rmax) = self.comp_radius()
return Rmax - Rmin
|
4dbab93edbe3d7f277480e96b4a5e885e6e9161e
| 35,554 |
import random
def GenerateRandomChoice(choices, prev=None):
"""Generates a random choice from a sequence.
Args:
choices: sequence.
Returns:
A value.
"""
return random.choice(choices)
|
1d38dd313b19f235d4ea367e841ce7e74ee8f69b
| 35,555 |
def list2pairs(l):
"""
Turns any list with N items into a list of (N-1) pairs of consecutive items.
"""
res = []
for i in range(len(l)-1):
res.append((l[i], l[i+1]))
return res
|
b1c3770e66354862d2dd96eedd473582549aae96
| 35,556 |
def normalize_br_tags(s):
"""
I like 'em this way.
>>> normalize_br_tags('Hi there')
'Hi there'
>>> normalize_br_tags('Hi <br>there')
'Hi <br />there'
>>> normalize_br_tags('Hi there<br/>')
'Hi there<br />'
"""
return s.replace("<br>", "<br />").replace("<br/>", "<br />")
|
21df28ca4a8bfc03375d2e07e8a1b3840d840557
| 35,557 |
def filter_none_values(kwargs: dict) -> dict:
"""Returns a new dictionary excluding items where value was None"""
return {k: v for k, v in kwargs.items() if v is not None}
|
f5a1f767291a72ebeac7b92c0bbe78b890330916
| 35,558 |
from typing import List
import yaml
def get_training_class_names(training_config_file: str) -> List[str]:
"""get class names from training config file
Args:
training_config_file (str): path to training config file, NOT YOUR MINING OR INFER CONFIG FILE!
Raises:
ValueError: when class_names key not in training config file
Returns:
List[str]: list of class names
"""
with open(training_config_file, 'r') as f:
training_config = yaml.safe_load(f.read())
if 'class_names' not in training_config or len(training_config['class_names']) == 0:
raise ValueError(f"can not find class_names in {training_config_file}")
return training_config['class_names']
|
4caba056481c653f97d5bb0b0f007cea20494412
| 35,563 |
def anticom(A,B):
"""
Compute the anticommutator between matrices A and B.
Arguments:
A,B -- square matrices
Return:
antcom -- square matrix of the anticommutator {A,B}
"""
antcom = A.dot(B) + B.dot(A)
return antcom
|
734f435228fe3c69b52f3c5e8cc09e7f79bd01ce
| 35,564 |
import json
def json_file_to_dict(file_path):
"""load a dict from file containing JSON
Args:
file_path (str): path to JSON file
Returns:
json_dict (dict): object representation of JSON contained in file
"""
return json.loads(open(file_path, "r").read())
|
bf95cdf3ba049718caf2a5ca38ba3293c2eb308e
| 35,568 |
import re
def restore_dash(arg: str) -> str:
"""Convert leading tildes back to dashes."""
return re.sub(r"^~", "-", arg)
|
63313a006ed934eff1ca83486a3dde4f6ea9ef74
| 35,569 |
import hashlib
def __mysql_password_hash(passwd):
"""
Hash string twice with SHA1 and return uppercase hex digest,
prepended with an asterisk.
This function is identical to the MySQL PASSWORD() function.
"""
pass1 = hashlib.sha1(passwd.encode('utf-8')).digest()
pass2 = hashlib.sha1(pass1).hexdigest()
return "*" + pass2.upper()
|
f505025ea0459d42f118698c476fa83afb63f382
| 35,572 |
def extract_version_fields(version, at_least=0):
"""
For a specified version, return a list with major, minor, patch.. isolated
as integers.
:param version: A version to parse
:param at_least: The minimum number of fields to find (else raise an error)
"""
fields = [int(f) for f in version.strip().split('-')[0].lstrip('v').split('.')] # v1.17.1 => [ '1', '17', '1' ]
if len(fields) < at_least:
raise IOError(f'Unable to find required {at_least} fields in {version}')
return fields
|
04209b0029160b19bbdb80d45f560c696214f90a
| 35,573 |
def change_rate_extractor(change_rates, initial_currency, final_currency):
""" Function which tests directions of exchange factors and returns the
appropriate conversion factor.
Example
-------
>>> change_rate_extractor(
... change_rates = {'EUR/USD': .8771929824561404},
... initial_currency = 'EUR',
... final_currency = 'USD',
... )
1.14
>>> change_rate_extractor(
... change_rates = {'USD/EUR': 1.14},
... initial_currency = 'EUR',
... final_currency = 'USD',
... )
1.14
"""
ACR_1 = '%s/%s'%(
initial_currency, final_currency
)
ACR_2 = '%s/%s'%(
final_currency, initial_currency
)
if ACR_1 in change_rates:
return pow(change_rates[ACR_1], -1.)
if ACR_2 in change_rates:
return change_rates[ACR_2]
|
3ada3badcfa16c06c2a50ba943d67711e48b62a0
| 35,575 |
def get_codebook(ad_bits, codebook):
"""Returns the exhaustive codebooks for a given codeword length
:param ad_bits: codewor length
:type ad_bits: int
:return: Codebook
:rtype: list(str)
"""
return codebook[ad_bits-2]
|
331c33e54abe5fd0d71edbc32d5f76d2ec6f03a9
| 35,576 |
def _shiftedWord(value, index, width=1):
"""
Slices a width-word from an integer
Parameters
----------
value: int
input word
index : int
start bit index in the output word
width: int
number of bits of the output word
Returns
-------
An integer with the sliced word
"""
if not isinstance(value, int):
raise ValueError("value must be integer.")
if not isinstance(index, int):
raise ValueError("index must be integer.")
if not isinstance(width, int):
raise ValueError("width must be integer.")
elif width < 0:
raise ValueError("width cannot be negative.")
return (value >> index) & ((2 ** width) - 1)
|
d3c3ab1e1f34684607fb9f55f807053fd7052be0
| 35,577 |
import copy
def merge(dest, src):
"""Merge two config dicts.
Merging can't happen if the dictionaries are incompatible. This happens when the same path in `src` exists in `dest`
and one points to a `dict` while another points to a non-`dict`.
Returns: A new `dict` with the contents of `src` merged into `dest`.
Raises:
ValueError: If the two dicts are incompatible.
"""
dest = copy.deepcopy(dest)
for src_name, src_val in src.items():
if isinstance(src_val, dict):
dest_val = dest.get(src_name, {})
if not isinstance(dest_val, dict):
raise ValueError('Incompatible config structures')
dest[src_name] = merge(dest_val, src_val)
else:
try:
if isinstance(dest[src_name], dict):
raise ValueError('Incompatible config structures')
except KeyError:
pass
dest[src_name] = src_val
return dest
|
e03bd548294ee8df71dc802672d22085ac85ee83
| 35,578 |
def list_to_number(column):
"""
Turns a columns of 0s and 1s to an integer
Args:
column: List of 0s and 1s to turn into a number
"""
# Cast column integers to strings
column = [str(cell) for cell in column]
# Turn to an integer with base2
return int(''.join(column), 2)
|
b6176726517133711d12e47ed47d55ef5bc8ab82
| 35,581 |
def matrix_to_string(matrix, header=None):
"""
Returns a pretty and aligned string representation of a NxM matrix.
This representation can be used to print any tabular data, such as
database results. It works by scanning the lengths of each element
in each column and determining the format string dynamically.
:param matrix: Matrix representation (list with N rows and M elements).
:param header: Optional tuple or list with header elements to be displayed.
"""
if type(header) is list:
header = tuple(header)
lengths = []
if header:
for column in header:
lengths.append(len(column))
for row in matrix:
for column in row:
i = row.index(column)
column = str(column)
cl = len(column)
try:
ml = lengths[i]
if cl > ml:
lengths[i] = cl
except IndexError:
lengths.append(cl)
lengths = tuple(lengths)
format_string = ""
for length in lengths:
format_string += "%-" + str(length) + "s "
format_string += "\n"
matrix_str = ""
if header:
matrix_str += format_string % header
for row in matrix:
matrix_str += format_string % tuple(row)
return matrix_str
|
7eb430356357de9d6a6b51c196df4aba29decada
| 35,584 |
def SNR_kelly(spiketrain):
"""
returns the SNR of the waveforms of spiketrains, as computed in
Kelly et al (2007):
* compute the mean waveform
* define the signal as the peak-to-through of such mean waveform
* define the noise as double the std.dev. of the values of all waveforms,
each normalised by subtracting the mean waveform
Parameters:
-----------
spiketrain : SpikeTrain
spike train loaded with rgio (has attribute "vaweforms")
Returns:
--------
snr: float
The SNR of the input spike train
"""
mean_waveform = spiketrain.waveforms.mean(axis=0)
signal = mean_waveform.max() - mean_waveform.min()
SD = (spiketrain.waveforms - mean_waveform).std()
return signal / (2. * SD)
|
f827008138e9b02625db02ee6755da3451256d2d
| 35,585 |
import math
def my_func(x):
"""
simple function that computes : sin(x) + 2x
Inputs:
1.x: input value (in radians)
Output:
returns y = sin(x) + 2x
"""
y = math.sin(x) + 2.0*x
return y
|
15c14af682051d972d16ca3bf14a4f50f54cd79c
| 35,586 |
import json
from datetime import datetime
import time
def iso_to_unix_secs(s):
""" convert an json str like {'time': '2022-02-05T15:20:09.429963Z'} to microsecs since unix epoch
as a json str {'usecs': 1644927167429963}
"""
dt_str = json.loads(s)["time"]
dt = datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S.%fZ")
usecs = int(time.mktime(dt.timetuple()) * 1000000 + dt.microsecond)
return json.dumps({"usecs": usecs})
|
7421e6b1781b712ebc3b8bafd1d96f49c5f1d10c
| 35,587 |
import requests
def check_time_response(domain):
"""Return the response time in seconds."""
try:
latency = requests.get(domain, headers={'Cache-Control': 'no-cache'}).elapsed.total_seconds()
return latency
except Exception:
return '?'
|
be208715ceae98122f7012a2982833e46b6979c7
| 35,595 |
def _safe_delay(delay):
"""Checks that `delay` is a positive float number else raises a
ValueError."""
try:
delay = float(delay)
except ValueError:
raise ValueError("{} is not a valid delay (not a number)".format(delay))
if delay < 0:
raise ValueError("{} is not a valid delay (not positive)".format(delay))
return delay
|
ff3014047c5f4bcd7d4054f8af11ccd722401546
| 35,598 |
from typing import Dict
from typing import Any
def bundle_json_get_next_link(bundle_json: Dict[str, Any]) -> str:
"""get the 'next' link from a bundle, if it exists
Args:
bundle_json (Dict[str, Any]): the bundle to examine
Returns:
str: the url of the 'next' bundle or None
"""
filtered_link = [link for link in bundle_json["link"] if link["relation"] == "next"]
if len(filtered_link) > 0:
return filtered_link[0]["url"]
return ""
|
db311eba00952b7d00bf5c9187cc52fb210c5560
| 35,601 |
def strip_headers(post):
"""Find the first blank line and drop the headers to keep the body"""
if '\n\n' in post:
headers, body = post.split('\n\n', 1)
return body.lower()
else:
# Unexpected post inner-structure, be conservative
# and keep everything
return post.lower()
|
ac5b5a7b06f700a42698b3a65fd4c9017a001f30
| 35,603 |
def check_continuity(array):
"""
Check whether the array contains continous values or not like 1, 2, 3, 4, ..
"""
max_v = max(array)
min_v = min(array)
n = len(array)
# print(n, min_v, max_v)
if max_v - min_v + 1 == n:
# print("Given array has continous values")
return True
else:
# print("Given array is not continous")
return False
|
6b279cce3b332d5c593afe9590800fe3c8472710
| 35,604 |
def get_node_type(conn, graph_node_pkey):
""" Returns the node type of a given graph node"""
c = conn.cursor()
c.execute(
"""
SELECT graph_node_type FROM graph_node WHERE pkey = ?""",
(graph_node_pkey, )
)
return c.fetchone()[0]
|
f68f29e45127854781c8fe5422ab754014df1d6b
| 35,608 |
def getPixelFromLabel(label):
"""
Function to get the pizel from the class label. This reverse mapping is use to generate an image file fom available class labels.
:param label: class label
:type label: int
:return: (r,g,b) equivalent of class label color.
:rtype: tuple
"""
if label == 0:
return (0, 255, 0)
if label == 1:
return (255, 0, 0)
else:
return (255, 255, 153)
|
746ae72f4adff1615f399ff5b591b7013ebdce46
| 35,611 |
import time
def ms_time_to_srt_time_format(d: int) -> str:
"""Convert decimal durations into proper srt format.
ms_time_to_srt_time_format(3890) -> '00:00:03,890'
"""
sec, ms = d // 1000, d % 1000
time_fmt = time.strftime("%H:%M:%S", time.gmtime(sec))
# if ms < 100 we get ...,00 or ...,0 when expected ...,000
ms = "0" * (3 - len(str(ms))) + str(ms)
return f"{time_fmt},{ms}"
|
3ca2713615b7fb8ef1ea9e9712e0b26b23c5f7e1
| 35,616 |
def format_float(value: float, precision: int = 4) -> str:
"""
Formats a float value to a specific precision.
:param value: The float value to format.
:param precision: The number of decimal places to use.
:return: A string containing the formatted float.
"""
return f'{value:.{precision}f}'
|
41ec3acf02f3400fd484c8e6f7a72509d3f20cd9
| 35,618 |
import logging
def TruncateStr(text, max_len=500):
"""Truncates strings to the specified maximum length or 500.
Args:
text: Text to truncate if longer than max_len.
max_len: Maximum length of the string returned by the function.
Returns:
A string with max_len or less letters on it.
"""
if len(text) > max_len:
logging.warning(
'Text length of %d is greater than the max length allowed. '
'Truncating to a length of %d. Text: %s', len(text), max_len, text)
return text[:max_len]
|
2401d6d56c6f99bd64cfd825aca0ab5badca1964
| 35,622 |
def get_parameters(params, t, verbose=True):
"""
Convenience method for the numeric testing/validation system.
Params is a dictionary, each key being a parameter name,
and each value a list of values of length T (the number of trials).
The method returns a list of the argument values for test number `t` < T.
"""
def print_v(str):
if verbose:
print(str)
num_params = len(params)
print_v('')
print_v('-----------------------------------------------')
print_v(' t='+str(t))
p = []
for p_idx in range(num_params):
dict_tuple = list(params.items())[p_idx]
key = dict_tuple[0]
value = dict_tuple[1]
p.append(value[t])
if verbose:
print(key, value[t])
print_v('-----------------------------------------------')
return p
|
70b624b465022efd9ef29e59b875881387f28935
| 35,625 |
def map_element(element):
"""Convert an XML element to a map"""
# if sys.version_info >= (2, 7):
# return {e.tag: e.text.strip() for e in list(element)}
# return dict((e.tag, e.text and e.text.strip() or "")
# for e in list(element))
return dict((e.tag, e.text) for e in list(element))
|
b8a84be91f28757f28622a5909a569d35e38282f
| 35,627 |
def _zone_group_topology_location_to_ip(location):
"""Takes a <ZoneGroupMember Location=> attribute and returns the IP of
the player."""
# Assume it is of the form http://ip:port/blah/, rather than supporting
# any type of URL and needing `urllib.parse`. (It is available for MicroPython
# but it requires a million dependencies).
scheme_prefix = 'http://'
assert location.startswith(scheme_prefix)
location = location[len(scheme_prefix):]
port_idx = location.find(':')
return location[:port_idx]
|
e3b038b92d4fcb24650dd6905847c9ca3f1fa13e
| 35,628 |
from typing import Union
def transfrom_operand(operand: str) -> Union[str, int, bool]:
"""Transforms operand."""
result = operand.strip()
if result.isdigit():
result = int(result)
elif result in ['True', 'true', 'Yes', 'yes', 'T', 't', 'N', 'n']:
result = True
elif result in ['False', 'false', 'No', 'no', 'F', 'f', 'N', 'n']:
result = False
elif result.startswith('"') and result.endswith('"'):
result = result[1:-1]
return result
|
64bd30316d7176b01e66cd40d8852806b4da0e7b
| 35,629 |
def get_or_create(session, model, **kwargs):
"""
Determines if a given record already exists in the database.
Args:
session: The database session.
model: The model for the record.
**kwargs: The properties to set on the model. The first
specified property will be used to determine if
the model already exists.
Returns:
Two values. The first value is a boolean
indicating if this item is a new record. The second
value will be the created/retrieved model.
"""
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return False, instance
else:
instance = model(**kwargs)
return True, instance
|
74c77cfcbee09313b96284c34e59eb0ff1440f0c
| 35,630 |
def n_distinct(series):
"""
Returns the number of distinct values in a series.
Args:
series (pandas.Series): column to summarize.
"""
n_distinct_s = series.unique().size
return n_distinct_s
|
5f262c376e844cff324b5e0376be91ead8e20c0d
| 35,633 |
def get_index_offset_contents(result, source):
"""Return (line_index, column_offset, line_contents)."""
line_index = result['line'] - 1
return (line_index,
result['column'] - 1,
source[line_index])
|
5ee12a8c991ab50c71426cacf8db255f4f938de9
| 35,635 |
def avg_eval_metrics(metrics):
"""Average evaluation metrics (divide values by sample count).
Args:
metrics: evaluation metrics
Returns:
averaged metrics as a dict
"""
n = metrics['sample_count']
metrics['loss'] = metrics['loss_sum'] / n
metrics['error_rate'] = metrics['error_count'] / n
if 'top5_error_count' in metrics:
metrics['top5_error_rate'] = metrics['top5_error_count'] / n
return metrics
|
cfa3461c94b320a44438483f1d037c0b545cf02a
| 35,637 |
import copy
def dreplace(d, fv=None, rv='None', new=False):
"""replace dict value
Parameters
----------
d : dict
the dict
fv : any, optional
to be replaced, by default None
rv : any, optional
replaced with, by default 'None'
new : bool, optional
if true, deep copy dict, will not change input, by default False
Returns
-------
dict
dict with replaced value
"""
fvtype = type(fv)
if new:
d = copy.deepcopy(d)
for k, v in d.items():
if type(v) is dict:
dreplace(v, fv=fv, rv=rv)
else:
if type(v) == fvtype:
if v == fv:
d[k] = rv
return d
|
86e29b6b3b8839ccf1de26483b71e8cd2e0fd6b8
| 35,642 |
from typing import List
from typing import Any
from typing import Callable
from typing import Optional
def extract_self_if_method_call(args: List[Any],
func: Callable) -> Optional[object]:
"""Check if this is a method rather than a function.
Does this by checking to see if `func` is the attribute of the first
(`self`) argument under `func.__name__`. Unfortunately, this is the most
robust solution to this I was able to find. It would also be preferable
to do this check when the decorator runs, rather than when the method is.
Returns the `self` object if it's a method call, else None.
Arguments:
args (List[Any]): arguments to the function/method call.
func (Callable): the unbound function that was called.
"""
if len(args) > 0:
method = getattr(args[0], func.__name__, False)
if method:
wrapped = getattr(method, "__wrapped__", False)
if wrapped and wrapped == func:
return args.pop(0)
return None
|
e93850cdad0bbe8fccfa1e508d14acd92f980b35
| 35,649 |
def encode_string(s, index):
"""
Transform a string in a list of integers.
The ints correspond to indices in an
embeddings matrix.
"""
return [index[symbol] for symbol in s]
|
bba25330f6d40b6211d11dda74fed8caa3dcfc16
| 35,650 |
def as_linker_lib_path(p):
"""Return as an ld library path argument"""
if p:
return '-L' + p
return ''
|
567509c01a4d24978b22834aeaded4f33762d6fe
| 35,653 |
def get_frame(video_camera):
"""
Checks if the camera is open and takes a frame if so.
:param video_camera: A cv2.VideoCapture object representing the camera.
:return: Last frame taken by the camera.
"""
if video_camera.isOpened():
_, frame = video_camera.read()
else:
raise Exception("Camera is not opened")
return frame
|
2c36b77b9f7e907276b397a1225cfa60f027d847
| 35,663 |
def get_pwsh_script(path: str) -> str:
"""
Get the contents of a script stored in pypsrp/pwsh_scripts. Will also strip out any empty lines and comments to
reduce the data we send across as much as possible.
Source: https://github.com/jborean93/pypsrp
:param path: The filename of the script in pypsrp/pwsh_scripts to get.
:return: The script contents.
"""
with open(path, "rt") as f:
script = f.readlines()
block_comment = False
new_lines = []
for line in script:
line = line.strip()
if block_comment:
block_comment = not line.endswith('#>')
elif line.startswith('<#'):
block_comment = True
elif line and not line.startswith('#'):
new_lines.append(line)
return '\n'.join(new_lines)
|
43d1f0e526b9807ab729cb7b2b85ea1340699770
| 35,665 |
def is_numeric(obj):
"""Check whether object is a number or not, include numpy number, etc."""
try:
float(obj)
return True
except (TypeError, ValueError):
# TypeError: obj is not a string or a number
# ValueError: invalid literal
return False
|
3cce07df54d6d83410cbd79580cdfdfd29f3edb1
| 35,666 |
def resource_name_for_asset_type(asset_type):
"""Return the resource name for the asset_type.
Args:
asset_type: the asset type like 'google.compute.Instance'
Returns:
a resource name like 'Instance'
"""
return asset_type.split('.')[-1]
|
00604d1285e8e275976a026aaf0e7afb200ba1c8
| 35,667 |
def get_merged_gaps(gaps):
"""Get gaps merged across channels/streams
Parameters
----------
gaps: dictionary
contains channel/gap array pairs
Returns
-------
array_like
an array of startime/endtime arrays representing gaps.
Notes
-----
Takes an dictionary of gaps, and merges those gaps across channels,
returning an array of the merged gaps.
"""
merged_gaps = []
for key in gaps:
merged_gaps.extend(gaps[key])
# sort gaps so earlier gaps are before later gaps
sorted_gaps = sorted(merged_gaps, key=lambda gap: gap[0])
# merge gaps that overlap
merged_gaps = []
merged_gap = None
for gap in sorted_gaps:
if merged_gap is None:
# start of gap
merged_gap = gap
elif gap[0] > merged_gap[2]:
# next gap starts after current gap ends
merged_gaps.append(merged_gap)
merged_gap = gap
elif gap[0] <= merged_gap[2]:
# next gap starts at or before next data
if gap[1] > merged_gap[1]:
# next gap ends after current gap ends, extend current
merged_gap[1] = gap[1]
merged_gap[2] = gap[2]
if merged_gap is not None:
merged_gaps.append(merged_gap)
return merged_gaps
|
59c6c04ca20800040eaa2a4909708b4880fcb11f
| 35,668 |
def get_lrmost(T, segs):
"""
Finds the leftmost and rightmost segments of segs in T
"""
l = []
for s in list(T):
if s in segs:
l.append(s)
if len(l) < 1:
return None, None
return l[0], l[-1]
|
a0af5055292b3253cd27300181e7aee9e0b9653a
| 35,669 |
def overall_dwelling_dimensions(
area,
average_storey_height
):
"""Calculates the overall dwelling dimensions, Section 1.
:param area: A list of the areas of each floor.
The first item is the basement, the second the ground floor etc.
See (1a) to (1n).
:type area: list (float)
:param average_storey_height: A list of the average storey height of each floor.
The first item is the basement, the second the ground floor etc.
See (2a) to (2n).
:type average_storey_height: list (float)
:return: A dictionary with keys (volume,total_floor_area,dwelling_volume).
- **volume** (`list` (`float`)) - A list of the volumes of each floor.
The first item is the basement, the second the ground floor etc.
See (3a) to (3n).
- **total_floor_area** (`float`) - See (4).
- **dwelling_volume** (`float`) - See (5).
:rtype: dict
"""
# calculate volume
volume=[]
for i in range(len(area)):
volume.append(area[i] * average_storey_height[i])
# calculate total floor area
total_floor_area=sum(area)
# calculate dwelling volume
dwelling_volume=sum(volume)
return dict(volume=volume,
total_floor_area=total_floor_area,
dwelling_volume=dwelling_volume)
|
72408ae8c0aa782b6a6b2f86dd5635f9c9e984c9
| 35,670 |
def speedx(clip, factor = None, final_duration=None):
"""
Returns a clip playing the current clip but at a speed multiplied
by ``factor``. Instead of factor one can indicate the desired
``final_duration`` of the clip, and the factor will be automatically
computed.
The same effect is applied to the clip's audio and mask if any.
"""
if final_duration:
factor = 1.0* clip.duration / final_duration
newclip = clip.fl_time(lambda t: factor * t, apply_to=['mask', 'audio'])
if clip.duration is not None:
newclip = newclip.set_duration(1.0 * clip.duration / factor)
return newclip
|
e6bf9595bc958cd0fc39bab95bef31fe6fba6ba6
| 35,672 |
def binarize_worker(document):
"""Binarizes a BOW document.
Parameters
----------
document : list of (int, float)
A document.
Returns
-------
binarized_document : list of (int, float)
The binarized document.
"""
binarized_document = [(term_id, 1) for term_id, _ in document]
return binarized_document
|
eadf535337dec095b9f287b422541fe5de8ae932
| 35,674 |
import networkx as nx
def split_graph(G):
"""splits graph(s) on interactions and return a dictionary of graphs with interaction as keys."""
# Find all interactions to split the graph on
split_by = "interaction"
split_list = list()
for u, v, d in G.edges(data=True):
split_list.append(d[split_by])
split_set = set(split_list)
G_splits = dict()
for split in split_set:
G_split = nx.from_edgelist(
[(u, v, d) for u, v, d in G.edges(data=True) if d[split_by] == split],
create_using=nx.MultiDiGraph())
G_split.add_nodes_from(G.nodes(data=True))
G_splits[split] = G_split
return G_splits
|
4ac596e472afb57cb3f6094fb0f4166aca4b1a2a
| 35,675 |
def test_trainable_parameters_changed(trainer):
"""Performs a training step and verifies that at least one parameter
in every trainable layer has changed."""
print("At least one parameter changed in the trainable layers", end="")
passed, msg = True, ""
trainer.fit(epochs=1, max_steps=1, max_eval_steps=0)
for name, new_param in trainer.model.named_parameters():
if new_param.requires_grad:
old_param = trainer._saved_state["model"][name]
if not (new_param.data != old_param).any():
msg += " expected changes in: %s\n" % name
passed = False
return passed, msg
|
29a0b0ffab55b62e9cb5ff5d4b29f1b655e99ad9
| 35,677 |
def strategy(history, memory):
"""
Tit for Tat, but it only defects once in a row.
"""
choice = 1
if (
history.shape[1] >= 1
and history[1, -1] == 0
and memory is not None
and 1 == memory
):
choice = 0
return choice, choice
|
ec4a016acd66374c56b57bbeb1d0e54813edd829
| 35,682 |
def _pixel_to_coords(col, row, transform):
"""Returns the geographic coordinate pair (lon, lat) for the given col, row, and geotransform."""
lon = transform[0] + (col * transform[1]) + (row * transform[2])
lat = transform[3] + (col * transform[4]) + (row * transform[2])
return lon, lat
|
f610340b5eb2ea652774d753920076f59a6faccd
| 35,684 |
def round_to_factor(num: float, base: int) -> int:
"""Rounds floating point number to the nearest integer multiple of the
given base. E.g., for floating number 90.1 and integer base 45, the result
is 90.
# Attributes
num : floating point number to be rounded.
base: integer base
"""
return round(num / base) * base
|
3679b884523253cec51659ceaf6f78292f87a401
| 35,685 |
def get_doc_content(content):
"""
Return the doc fields from request (not auth-related fields).
"""
return {
"title": content.get("title"),
"link": content.get("link"),
"tags": content.get("tags"),
"authors": content.get("authors"),
"year": content.get("year"),
"notes": content.get("notes"),
"read": content.get("read"),
}
|
ffd5037aee65dcc1cc104e8fc47df708fd5e7c64
| 35,687 |
def join_strings(lst):
"""Join a list to comma-separated values string."""
return ",".join(lst)
|
fbbc195a53d2d4b15012861251d676dbf9369cde
| 35,688 |
def l_system(depth, axiom, **rules):
"""Generate L-system from axiom using rules, up to given depth"""
if not depth:
return axiom
# Basic, most straight-forward implementation
# Note 1: it doesn't matter if axiom is a string or a list
# Note 2: consider the difference between .extend() and .append()
out = []
for char in axiom:
if char in rules:
out.extend(rules[char])
else:
out.append(char)
return l_system(depth - 1, out, **rules)
|
ed59af25848c5074be7b1da1a796dcdb0422e87e
| 35,689 |
def call_with_ensured_size(method, max_size, arg):
"""
Breaks a list of arguments up into chunks of a maximum size and calls the given method on each chunk
Args:
method (function): the method to call
max_size (int): the maximum number of arguments to include in a single call
arg (any | list<any>): the arguments to split up
Returns:
list<any> | dict<any>: the combined results of the function calls on each chunk
"""
if not isinstance(arg, list) or len(arg) <= max_size:
return method(arg)
results = method(arg[0:max_size])
i = max_size
if isinstance(results, list):
while(i < len(arg)):
sublist = arg[i:i + max_size]
try:
results = results + method(sublist)
except:
results = results + ([None] * len(sublist))
i += max_size
elif isinstance(results, dict):
while(i < len(arg)):
sublist = arg[i:i + max_size]
try:
results.update(method(sublist))
except:
pass
i += max_size
return results
|
e31dfbd03de5e4caabb46241957b98d1b76eee1a
| 35,690 |
def safe_str(maybe_str):
"""To help with testing between python 2 and 3, this function attempts to
decode a string, and if it cannot decode it just returns the string.
"""
try:
return maybe_str.decode('utf-8')
except AttributeError:
return maybe_str
|
f9713f98b4d32558855d46d82c2f5cc9bce568ee
| 35,692 |
def get_snapshot(ec2, snapshot_name: str):
"""Returns a snapshot by its name."""
res = ec2.describe_snapshots(Filters=[
{'Name': 'tag:Name', 'Values': [snapshot_name]},
])
if len(res['Snapshots']) > 1:
raise ValueError('Several snapshots with Name=%s found.' % snapshot_name)
snapshot = res['Snapshots'][0] if len(res['Snapshots']) else {}
return snapshot
|
cd6076e04fd2c83e50b3a0ac7bc117793c92731d
| 35,697 |
from datetime import datetime
def get_datetime_from_timestamp(timestamp):
"""Return datetime from unix timestamp"""
try:
return datetime.fromtimestamp(int(timestamp))
except:
return None
|
553d24a532681d139845777cd71ca54fc3e16f96
| 35,701 |
def get_pubmed_id_for_doc(doc_id):
"""Because our doc_id is currently just the PMID, and we intend to KEEP it this way, return the doc_id here"""
return doc_id
|
a1d9241406b9655553d008ff7839c1f2b730f994
| 35,705 |
def generate_onehot_dict(word_list):
"""
Takes a list of the words in a text file, returning a dictionary mapping
words to their index in a one-hot-encoded representation of the words.
"""
word_to_index = {}
i = 0
for word in word_list:
if word not in word_to_index:
word_to_index[word] = i
i += 1
return word_to_index
|
1408cfbf8360134b4d9a95165e693a972cc4f4e3
| 35,706 |
def valid_file(path: str) -> bool:
"""
Check if regressi file is valid
:param path: path to the file to test
:return: whether the file is valid or not
"""
with open(path, 'r') as file:
if file.readline() == "EVARISTE REGRESSI WINDOWS 1.0":
return False
else:
return True
|
81e407fd24a830b32a0ba55bb4e912a2d32d61ef
| 35,714 |
import re
def alphanum_key(s):
""" Key func for sorting strings according to numerical value. """
return [int(c) if c.isdigit() else c for c in re.split('([0-9]+)', s)]
|
c9147a41cad775700db280e92efe500fb6d8469e
| 35,719 |
def value_or_default(value, default):
"""
Returns the supplied value of it is non None, otherwise the supplied default.
"""
return value if value is not None else default
|
d3fdf1cee4029c5617623e2834a6f05d962b2e94
| 35,727 |
import re
def parse_k(msg):
"""Parse create keypoint message and return keypoint number"""
if not re.search(r"KEYPOINT NUMBER", msg):
res = re.search(r"(KEYPOINT\s*)([0-9]+)", msg)
else:
res = re.search(r"(KEYPOINT NUMBER =\s*)([0-9]+)", msg)
if res:
result = int(res.group(2))
else:
result = None
return result
|
92f45ea09a7c9e1eecf48664c49218657687a217
| 35,729 |
def confirm(prompt=None, response=False):
"""Prompts for a yes or no response from the user
Arguments
---------
prompt : str, default=None
response : bool, default=False
Returns
-------
bool
True for yes and False for no.
Notes
-----
`response` should be set to the default value assumed by the caller when
user simply types ENTER.
Examples
--------
>>> confirm(prompt='Create Directory?', response=True)
Create Directory? [y]|n:
True
>>> confirm(prompt='Create Directory?', response=False)
Create Directory? [n]|y:
False
>>> confirm(prompt='Create Directory?', response=False)
Create Directory? [n]|y: y
True
"""
if prompt is None:
prompt = 'Confirm'
if response:
prompt = '{} [{}]|{}: '.format(prompt, 'y', 'n')
else:
prompt = '{} [{}]|{}: '.format(prompt, 'n', 'y')
while True:
ans = input(prompt)
if not ans:
return response
if ans not in ['y', 'Y', 'n', 'N']:
print('please enter y or n.')
continue
if ans in ['y', 'Y']:
return True
if ans in ['n', 'N']:
return False
|
4e60be0b9973de67ee718eb255c10efdbd7666aa
| 35,730 |
def READ_RECORD(SFI:int, record:int) -> dict:
"""READ_RECORD(): generate APDU for READ RECORD command
"""
return {'CLA' : '00', 'INS' : 'B2', 'P1' : F"{record:02X}", 'P2' : F"{SFI*8+4:02X}", 'Le' : '00'}
|
746e09d86b42eb822b197ebb3ff8f4bb36ad018a
| 35,733 |
def transform_vertex(u, phi):
"""
Given a vertex id u and a set of partial isomorphisms phi.
Returns the transformed vertex id
"""
for _phi in phi:
if _phi[0] == u:
return _phi[1]
raise Exception('u couldn\' be found in the isomorphisms')
|
d35d0a819d795098190f8578b115b04231a53902
| 35,740 |
def write_normal(fname,triplets,na,angd,agr):
"""
Write out ADF data in normal ADF format.
"""
outfile= open(fname,'w')
outfile.write('# 1:theta[i], ')
for it,t in enumerate(triplets):
outfile.write(' {0:d}:{1:s}-{2:s}-{3:s},'.format(it+2,*t))
outfile.write('\n')
for i in range(na):
outfile.write(' {0:10.4f}'.format(angd[i]))
for it,t in enumerate(triplets):
outfile.write(' {0:11.3e}'.format(agr[it,i]))
outfile.write('\n')
outfile.close()
return None
|
d12e858060dad0f398beb139aaf9a4edda255807
| 35,741 |
import random
def bomber(length, width, bomb, m, n):
"""
Place bombs randomly (position of first click and its surroundings cannot be bombs)
:param length: length of the board
:param width: width of the board
:param bomb: number of bombs
:param m: horizontal position of first click
:param n: vertical position of first click
:return: list of bomb positions
"""
forbidden = ((m - 1, n - 1), (m - 1, n), (m - 1, n + 1), (m, n - 1), (m, n), (m, n + 1), (m + 1, n - 1), (m + 1, n),
(m + 1, n + 1))
candidates = [(x, y) for x in range(length) for y in range(width) if (x, y) not in forbidden]
return random.sample(candidates, bomb)
|
52591fe68d7d03e29559072148a945700b6aad06
| 35,743 |
def format_example_name(example):
"""Formats an example command to a function or file name
"""
return '_'.join(example).replace('-', '_').replace(
'.', '_').replace('/examples/', '')[1:]
|
223301709fb52aac98e2622c7df760fd3d7056e1
| 35,747 |
def value(card):
"""Returns the numeric value of a card or card value as an integer 1..13"""
prefix = card[:len(card) - 1]
names = {'A': 1, 'J': 11, 'Q': 12, 'K': 13}
if prefix in names:
return names.get(prefix)
else:
return int(prefix)
|
534681894f67dc626173d952e7eddb0ecd8da20d
| 35,748 |
import re
def make_command(name):
"""Convert a string into a space-less command."""
name = re.sub('[^\w]', ' ', name) # Replace special characters with spaces
name = name.strip().lower()
while " " in name: name = name.replace(' ', ' ') # Replace duplicate spaces
name = name.replace(' ', '-') # In the end, we want no whitespace
return name
|
e1f154f89e0e54ead76a4492325fb1c547043cea
| 35,752 |
def add_prefix(name, prefix=None, split='.'):
"""Add prefix to name if given."""
if prefix is not None:
return '{}{}{}'.format(prefix, split, name)
else:
return name
|
b22ab3ce8a286716579892a4bf9627674aea1f62
| 35,761 |
import torch
def f_get_raster_image(cfg,
images,
history_weight=0.9):
"""
Creates single raster image from sequence of images from l5kit's AgentDataset
Args:
cfg {dict}: Dictionary config.
images: (batch_size, 2*(history_num_frames+1)+3, H, H) - sequences of images after applying l5kit's rasterizer:
There is (history_num_frames+1) ego-car images, (history_num_frames+1) agent-car's images + 3 scene RGB images
history_weight {float}: Amount of history fading (for rendering).
Returns:
RGB image of the scene and agents.
Red color stays for EGO car.
Yellow color stays for Agent's cars.
"""
batch_size = images.shape[0]
image_size = images.shape[-1]
# get number of history steps
hnf = cfg['model_params']['history_num_frames']
# define ego-car's indices range in channels (images):
# ind (0, hnf) correspond to all agents except ego car,
# from hnf+1 to 2*hnf+1 correspond to ego car,
# last 3 indices correspond to rgb scene
ego_index = range(hnf+1, 2*hnf+2)
# iterate through ego-car's frames and sum them according to history_weight (history fading) in single channel.
ego_path_image = torch.zeros(size=(batch_size, image_size, image_size), device=cfg['device'])
for im_id in reversed(ego_index):
ego_path_image = (images[:, im_id, :, :] + ego_path_image * history_weight).clamp(0, 1)
# define agent's range
agents_index = range(0, hnf+1)
# iterate through agent-car's frames and sum them according to history_weight in single channel
agents_path_image = torch.zeros(size=(batch_size, image_size, image_size), device=cfg['device'])
for im_id in reversed(agents_index):
agents_path_image = (images[:, im_id, :, :] + agents_path_image*history_weight).clamp(0, 1)
# RGB path for ego (red (255, 0, 0)); channels last
ego_path_image_rgb = torch.zeros((ego_path_image.shape[0],
ego_path_image.shape[1],
ego_path_image.shape[2],
3), device=cfg['device'])
ego_path_image_rgb[:, :, :, 0] = ego_path_image
# RGB paths for agents (yellow (255, 255, 0)); channels last
agents_path_image_rgb = torch.zeros((agents_path_image.shape[0],
agents_path_image.shape[1],
agents_path_image.shape[2],
3), device=cfg['device'])
# yellow
agents_path_image_rgb[:, :, :, 0] = agents_path_image
agents_path_image_rgb[:, :, :, 1] = agents_path_image
# generate full RGB image with all cars (ego + agents)
all_vehicles_image = ego_path_image_rgb + agents_path_image_rgb # (batch_size, 3, H, H)
# get RGB image for scene from rasterizer (3 last images); channels last
scene_image_rgb = images[:, 2*hnf+2:, :, :].permute(0, 2, 3, 1)
# Add mask to positions of cars (to merge all layers):
# We need to take into account that the off-road is white, i.e. 1 in all channels
# So, we have to prevent disappearing of off-road cars after clipping when we add images together.
# For ex. (1, 1, 1) + (1, 0, 0) = (2, 1, 1) --> (1, 1, 1) = off-road car disappears.
# In order to solve this, we cut the scene at the car's area.
scene_image_rgb[(all_vehicles_image > 0).any(dim=-1)] = 0.0
# generate final raster map
full_raster_image = (all_vehicles_image + scene_image_rgb).clamp(0, 1)
# channels as a second dimension
full_raster_image = full_raster_image.permute(0, 3, 1, 2)
return full_raster_image
|
aff05d51041c909a73a93c9dbef2970e302677b1
| 35,764 |
def a_send(text, ctx):
"""Send text line to the controller."""
ctx.ctrl.send(text)
return True
|
7a5b8412f5099138afedc892c893f413ab4eba21
| 35,766 |
def path_info_split(path_info):
"""
Splits off the first segment of the path. Returns (first_part,
rest_of_path). first_part can be None (if PATH_INFO is empty), ''
(if PATH_INFO is '/'), or a name without any /'s. rest_of_path
can be '' or a string starting with /.
"""
if not path_info:
return None, ''
assert path_info.startswith('/'), (
"PATH_INFO should start with /: %r" % path_info)
path_info = path_info.lstrip('/')
if '/' in path_info:
first, rest = path_info.split('/', 1)
return first, '/' + rest
else:
return path_info, ''
|
2b8429767feee1d271f8370684dddd34362390af
| 35,768 |
import time
def unixtime(dt_obj):
"""Format datetime object as unix timestamp
:param dt_obj: datetime.datetime object
:returns: float
"""
return time.mktime(dt_obj.utctimetuple())
|
7b2e6a923be2c05abed0ad8d324e818646e8f0c1
| 35,774 |
def star_wars(x, y, elem, neighbours):
"""Star Wars preset of the Generations family. (345/2/4)"""
red_count = 0
for neighbour in neighbours:
if neighbour == 3:
red_count += 1
if elem == 3: # The cell is alive
if red_count in [3,4,5]:
return 3
else:
return 2
elif elem > 0: # The cell is decaying
return elem - 1
elif red_count == 2: # The cell is dead, but will be brought to life
return 3
else: # The cell is dead
return 0
|
b9929d132b42744439052600019b852833e2c032
| 35,776 |
import json
def construct_event_json(event, data):
"""
Helper function to construct a payload for sending to clients
"""
return json.dumps([event, data], ensure_ascii=False).encode('utf8')
|
0693dacbf3592a6965fda925d8b3eab9c11dddf0
| 35,778 |
def is_private(message) -> bool:
"""Whether message is private."""
# See "type" at https://core.telegram.org/bots/api#chat.
return message.chat.type == 'private'
|
d45dca82c3a46d25997b1dbde2803fb50d08c871
| 35,780 |
import calendar
def to_timestamp(date):
"""Convert a datetime object into a calendar timestamp object
Parameters
----------
date : datetime.datetime
Datetime object e.g. datetime.datetime(2020, 10, 31, 0, 0)
Returns
-------
cal : calendar.timegm
Calendar timestamp corresponding to the input datetime
"""
return calendar.timegm(date.timetuple())
|
514ea392268dc94aa0a14b1dd5ce04425d1ed3bb
| 35,782 |
def title_getter(node):
"""Return the title of a node (or `None`)."""
return node.get('title','')
|
0825f4a2d6360d4845b3379ba9ade7a8e5fa11dc
| 35,783 |
def get_automl_options_string(args):
""" This function creates a string suitable for passing to another script
of the automl command line options.
The expected use case for this function is that a "driver" script is given
the automl command line options (added to its parser with add_automl_options),
and it calls multiple other scripts which also accept the automl options.
Parameters
----------
args : argparse.Namespace
A namespace containing all of the options from add_automl_options
Returns
-------
string:
A string containing all of the automl options
"""
args_dict = vars(args)
# first, pull out the text arguments
automl_options = ['out', 'tmp', 'seed', 'total_training_time',
'iteration_time_limit', 'ensemble_size', 'ensemble_nbest']
# create a new dictionary mapping from the flag to the value
automl_flags_and_vals = {'--{}'.format(o.replace('_', '-')) : args_dict[o]
for o in automl_options if args_dict[o] is not None}
estimators = ""
if args_dict['estimators'] is not None:
estimators = " ".join(mt for mt in args_dict['estimators'])
estimators = "--estimators {}".format(estimators)
s = ' '.join("{} {}".format(k,v) for k,v in automl_flags_and_vals.items())
s = "{} {}".format(estimators, s)
return s
|
bfe27e8e76666e0e5ca0f74feef8465234baebe8
| 35,788 |
import torch
def get_normal(xs):
"""Normals of xs.
Args:
xs: tensor [num_xs, 2]
Returns: tensor [num_xs, 2]
"""
return torch.stack([xs[:, 1], -xs[:, 0]], dim=-1)
|
b8bb383e4750651d391885a898d481e53d80add8
| 35,790 |
def mock_purge_unauth_url(url, request):
"""
Mock a purge request in which the credentials are valid, but the
url that was requested is not allowed
"""
return {'status_code': 403,
'content-type': 'application/json',
'server': 'Apache',
'content': {
"supportId": "123456789",
"title": "unauthorized arl",
"httpStatus": 403,
"detail": "http://www.example.com/bogus",
"describedBy": "https://api.ccu.akamai.com/ccu/v2/errors/"
"unauthorized-arl"}
}
|
a15e329f79fb6a004e88624781d8b8e90d438e00
| 35,795 |
import csv
def extract_pids_from_file(pid_file):
"""
Extracts pids from file containing a header and pids in each line
:param pid_file: path to the file containing the pids
:return: list of ints
"""
pids = []
with open(pid_file, 'r') as f:
csv_rows = csv.reader(f)
next(csv_rows)
for row in csv_rows:
pids.append(int(row[0]))
return pids
|
77c74ec079d4c55d4c115b5966f415d6ae78e4e6
| 35,796 |
def pythagorean_triplet(a, b, c):
"""
Tests whether a^2 + b^2 = c^2.
"""
return a**2 + b**2 == c**2
|
3bda7322d0a8f4af5d4faa3f4ef5d5c34acbc6d3
| 35,797 |
from pathlib import Path
import filecmp
def are_directories_equal(dir1: Path, dir2: Path) -> bool:
"""Compares two directories recursively.
Files in each directory are
assumed to be equal if their names and contents are equal.
Args:
dir1: The first directory.
dir2: The second directory.
Returns:
`True` if they are equal, `False` otherwise.
"""
dirs_cmp = filecmp.dircmp(dir1, dir2)
if dirs_cmp.left_only or dirs_cmp.right_only:
return False
(_, mismatches, errors) = filecmp.cmpfiles(
dir1, dir2, dirs_cmp.common_files, shallow=False
)
if mismatches or errors:
return False
for common_dir in dirs_cmp.common_dirs:
new_dir1 = Path(dir1, common_dir)
new_dir2 = Path(dir2, common_dir)
is_equal = are_directories_equal(new_dir1, new_dir2)
if not is_equal:
return False
return True
|
976fe0ba26c50b67204b9888eec4176a328d114e
| 35,799 |
def int16_to_bits(x):
"""
Unpack a 16 bit integer into binary fields. See the syntax for
this here https://docs.python.org/3/library/string.html#format-specification-mini-language
Parameters
----------
x : int16
single integer.
Returns
-------
List of binary fields aligned so int16_to_bits(1024)[0] = bit 0
"""
assert isinstance(x, int), 'x should be integer'
return [int(b) for b in f'{x:016b}'.format(x)[::-1]]
|
5993bfdae9666d364f9b2629fbbb862965cedddd
| 35,803 |
def permute_observation(obs, perm):
"""Given a permutation, shuffle pixels of the observation."""
return obs.flatten()[perm].reshape(obs.shape)
|
ac18bce7d344b89cbcba8ea22ebcb92ff3f9c0e9
| 35,812 |
def size_to_bytes(size):
""" Return the size as a bytes object.
@param int size: a 32-bit integer that we want to convert to bytes
@rtype: bytes
>>> list(size_to_bytes(300))
[44, 1, 0, 0]
"""
# little-endian representation of 32-bit (4-byte)
# int size
return size.to_bytes(4, "little")
|
722ab782250570779519f8d8fdca4d5b449324d5
| 35,817 |
from typing import Any
def issubclass_safe(candidate: Any, ancestor: Any) -> bool:
"""Returns True the candidate is a subclass of the ancestor, else False. Will return false instead of raising TypeError if the candidate is not a class."""
try:
return issubclass(candidate, ancestor)
except TypeError:
return False
|
54fec7e6861de36015d8264978b76073704080d6
| 35,822 |
import requests
def served(url):
"""Return True if url returns 200."""
r = requests.get(url, allow_redirects=False)
return r.status_code == 200
|
1c4f1025bc36dc6e1b1f7fe1d519e5d557ade813
| 35,823 |
def czyMur(mapObj, x, y):
"""Zwraca True jesli (x,y) pozycja na mapie jest murem,
w.p.p. zwraca False"""
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return False # (x,y) nie sa na mapie
elif mapObj[x][y] in ('#'):
return True # mur na drodze
return False
|
617ebf983c41fdcb5399f57b89d126469e93875e
| 35,825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.