content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def isPostCSP(t, switch=961986575.):
"""
Given a GALEX time stamp, return TRUE if it corresponds to a "post-CSP"
eclipse. The actual CSP was on eclipse 37423, but the clock change
(which matters more for calibration purposes) occured on 38268
(t~=961986575.)
:param t: The time stamp to test.
:type t: float
:param switch: The GALEX time stamp that defines pre- and post-CSP.
:type switch: float
:returns: bool -- Does this time correspond to a post-CSP eclipse?
"""
# Check that the tscale has been applied properly
if not switch/100. < t < switch*100.:
raise ValueError('Did you apply tscale wrong?')
return t >= switch | 2b731ec0bb06ce08d2a36137e3d48563e5cb0c11 | 7,803 |
import uuid
def get_a_uuid() -> str:
"""Gets a base 64 uuid
Returns:
The id that was generated
"""
r_uuid = str(uuid.uuid4())
return r_uuid | 20e87638c3718b4b75ffc48cf980216120edaea8 | 7,806 |
from pathlib import Path
def cookiecutter_cache_path(template):
"""
Determine the cookiecutter template cache directory given a template URL.
This will return a valid path, regardless of whether `template`
:param template: The template to use. This can be a filesystem path or
a URL.
:returns: The path that cookiecutter would use for the given template name.
"""
template = template.rstrip('/')
tail = template.split('/')[-1]
cache_name = tail.rsplit('.git')[0]
return Path.home() / '.cookiecutters' / cache_name | cbdc72195bf47fb1bb91368ac2bbca3890775a60 | 7,807 |
def generate_comic_html(comic={}):
"""Generates part HTML for the qotd supplied"""
return """
<h3>Dilbert by Scott Adams -</h3>
<a href="{0}"><img alt="{1} - Dilbert by Scott Adams" src="{2}"></a>
""".format(comic['url'], comic['title'], comic['image']) | 6003abddbe7b8f3ca281787b09d92b42907669fb | 7,808 |
def get_cloudify_endpoint(_ctx):
"""
ctx.endpoint collapses the functionality for local and manager
rest clients.
:param _ctx: the NodeInstanceContext
:return: endpoint object
"""
if hasattr(_ctx._endpoint, 'storage'):
return _ctx._endpoint.storage
return _ctx._endpoint | 37ac79f564626399bd940d4c9d9fd9fb8417c424 | 7,809 |
def get_vendors(ven):
"""
Input arguments for function = tuple
Coverts tuple into a list. I know, it is silly.
Input example:
get_vendors(("Neste", "Circle K"))
Output example:
['Neste', 'Circle K']
"""
vendors_list = list(ven)
return vendors_list | 7703a1efc2f6cb329f8c15dc4df19a966d3c4197 | 7,810 |
from typing import Any
from datetime import datetime
def stringify_mongovalues(v: Any):
"""
Mostly the values are fine, but at least datetime needs handled.
Also need to handle datetimes embedded in dicts, so use recursion to get them.
"""
if type(v) == datetime:
return v.isoformat()
elif type(v) == dict:
return {key: stringify_mongovalues(value) for key, value in v.items()}
else:
return v | 27349086a58681f0d06ce795b3792cc4e25e97fc | 7,812 |
def get_log_info(prefix='', rconn=None):
"""Return info log as a list of log strings, newest first. On failure, returns empty list"""
if rconn is None:
return []
# get data from redis
try:
logset = rconn.lrange(prefix+"log_info", 0, -1)
except:
return []
if logset:
loglines = [ item.decode('utf-8') for item in logset ]
else:
return []
loglines.reverse()
return loglines | d333fbeaff754e352a0b84c10f4d28e148badfa0 | 7,816 |
def text_to_html(string):
"""Take text as input and return html that renders nicely.
For example replace newlines with '<br/>'
This was built for use in reminder emails, please check for
effects there if you are updating it."""
string = "<html><body>" + string + "</body></html>"
string = string.replace("\n", "<br/>")
return string | 86cbbc0d35bc994450bb16e989264f96c992aaa3 | 7,818 |
def spacecraft_vel(deltaw, deltan, deltar, dij, vmap):
"""
function to calculate pixel-wise spacecraft velocities for Sunpy map
Based on Haywood et al. (2016) and described in Ervin et al. (2021) - In Prep.
Parameters
----------
deltaw: float, array
relative westward position of pixel
deltan: float, array
relative northward position of pixel
deltar: float, array
relative radial position of pixel
dij: float
distance between pixel ij and spacecraft
vmap: map
Sunpy map object (Dopplergram)
Returns
-------
vsc: float, array
array of spacecraft velocities
"""
# velocity of spacecraft relative to sun
vscw = vmap.meta['obs_vw']
vscn = vmap.meta['obs_vn']
vscr = vmap.meta['obs_vr']
# pixel-wise magnitude of spacecraft velocity
vsc = - (deltaw * vscw + deltan * vscn + deltar * vscr) / dij
return vsc | 78c2acffc4f14c3f707cc50e1594ad7012bc1b08 | 7,819 |
import time
def convert_time(t):
"""Takes epoch time and translates it to a human readable version"""
return time.strftime('%Y-%m-%d', time.localtime(t)) | e591e32e30a8ceb81c9934f4e67556896a56b79a | 7,822 |
from typing import List
from functools import reduce
def singleNumber(nums: List[int]) -> int:
"""
思路:排序,哈希,位运算(异或) 0^1 = 1, 1^1 = 0
"""
# n = 0
# for val in nums:
# n ^= val
# return n
return reduce(lambda x, y: x ^ y, nums) | 444b2e2685d42bcc717d95058a6c86dc4da31609 | 7,823 |
def valid_box(box, host_extent):
"""Returns True if the entire box is within a grid of size host_extent.
input arguments (unmodified):
box: numpy int array of shape (2, 3)
lower & upper indices in 3 dimensions defining a logical cuboid subset of a 3D cartesian grid
in python protocol of zero base, kji (normally) or ijk ordering same as for host_extent
host_extent: triple int
the extent (shape) of a 3D cartesian grid
returns: boolean
True if box is a valid box within a grid of shape host_extent, False otherwise
"""
if box.ndim != 2 or box.shape != (2, 3) or box.dtype != 'int':
return False
if len(host_extent) != 3:
return False
for d in range(3):
if box[0, d] < 0 or box[0, d] > box[1, d] or box[1, d] >= host_extent[d]:
return False
return True | c6b1bc144e23b35002a1fbf17d4e02d9ba904655 | 7,824 |
import yaml
def yaml_dump_result(obj, stream):
"""Redefinition of yaml.safe_dump with added float representer
The float representer uses float precision of four decimal digits
"""
def float_representer(dumper, value):
text = '{0:.4f}'.format(value)
return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
class ResultDumper(yaml.SafeDumper):
def __init__(self, *args, **kwargs):
super(ResultDumper, self).__init__(*args, **kwargs)
self.add_representer(float, float_representer)
yaml.dump(obj, stream, Dumper=ResultDumper, default_flow_style=False, sort_keys=True) | 55a8a06e918276060505224a680e1cb136d4a541 | 7,825 |
def rho_NFW(r, rs, rhos):
"""
The density profile [GeV/cm**3] of an NFW halo.
Parameters
----------
r : the distance from the center [kpc]
rs : the NFW r_s parameter [kpc]
rhos : the NFW rho_s parameter [GeV/cm**3]
"""
res = rhos/(r/rs)/(1.+r/rs)**2
return res | 3b8f97713610c1622815e15f13a75d39ad7e64ba | 7,827 |
def breakup_names(df):
"""Breakup full name into surname, title, first name"""
df[['surname','given_name']] = df['Name'].str.split(",", expand= True)
df[['title', 'first_name']] = df['given_name'].str.split(n=1, expand= True)
df = df.drop(columns=['Name', 'given_name'])
return df | ee76975b88702daf47fa9638c4d1217ca22e1e6e | 7,830 |
import os
def cat(dir, file_name=None, input=None):
""" act like unix 'cat' - put string into file (or echo data out """
ret_val = None
# step 1: figure out the file path
if dir:
if file_name:
file_path = os.path.join(dir, file_name)
else:
file_path = dir
# step 2: write to the file if we have something to input
if input:
with open(file_path, "w+") as f:
f.write(input)
# step 3: read contents of the file
if os.path.exists(file_path):
with open(file_path, "r") as f:
ret_val = f.readlines()
return ret_val | 5ef0ae24d1ea3bd23c98d43ab2ddca80233a75b9 | 7,831 |
from pathlib import Path
def image_content_type(outfile: Path) -> str:
""" Derives a content type from an image file's suffix """
return f"image/{outfile.suffix[1:]}" | 4c1545dbdcaa31826fd8567cabe2935ed7237961 | 7,832 |
def play_again() -> str:
"""Ask the user if he wants to play another turn"""
yes_or_no = input('Play again? [y/n]: ')
while yes_or_no not in ['y', 'n']:
yes_or_no = input('Please insert "y" or "n": ')
return yes_or_no | 8b3d74456b7ce13a0ffffab8dc9e946cbb5e594c | 7,833 |
def UserTypingFilter(cli):
"""Determine if the input field is empty."""
return (cli.current_buffer.document.text and
cli.current_buffer.document.text != cli.config.context) | 420b24cdeb17cb97294a937e49096c5462d4061e | 7,834 |
def scale_image(image, new_width=600):
"""
scales the image to new_width while maintaining aspect ratio
"""
new_w = new_width
(old_w, old_h) = image.size
aspect_ratio = float(old_h)/float(old_w)
new_h = int(aspect_ratio * new_w)
new_dim = (new_w, new_h)
image = image.resize(new_dim)
return image | e9bfdf6309cf97b1a7f44dff96b655aa09d64fd5 | 7,835 |
def get_container_metadata(item):
"""Extract desired metadata from Docker container object."""
if type(item) is str:
return item
tags = getattr(item, 'tags', None)
if tags is not None:
return tags[0]
else:
return str(item) | bf805e33f17dc664a62989f36ae164ee3c348b3e | 7,836 |
def percentage(sub, all):
"""Calculate percent relation between "sub" and "all".
Args:
sub (int): Some value.
all (int): Maximum value.
Returns:
int: (sum * 100) / all
"""
return int((sub * 100) / all) | 21b398c81f76de0ec81be9d26b2f79d8b0d08edc | 7,837 |
def value(colors: list):
"""
Each resistor has a resistance value.
Manufacturers print color-coded bands onto
the resistors to denote their resistance values.
Each band acts as a digit of a number.
The program will take two colors as input,
and output the correct number.
:param colors:
:return:
"""
encoded_colors = {
'black': 0,
'brown': 1,
'red': 2,
'orange': 3,
'yellow': 4,
'green': 5,
'blue': 6,
'violet': 7,
'grey': 8,
'white': 9
}
result = ''
for color in colors:
if color not in encoded_colors.keys():
raise Exception("Invalid color: {}".format(color))
result += str(encoded_colors[color])
return int(result) | 14a52f12bfcfccd921ade8fa7708d3563c9c2508 | 7,838 |
import torch
def nan_mode(input):
"""Mode value for tensor (ignoring NaNs)."""
return torch.mode(input[~torch.isnan(input)])[0] | cf2ef4fb23a0dfbc251dd385a38ed8e01142ac08 | 7,840 |
def activation(func_a):
"""Activation function wrapper
"""
return eval(func_a) | ad7f668aec546de452ef4968b22c338c2ca873b6 | 7,841 |
def quote_columns_data(data: str) -> str:
"""When projecting Queries using dot notation (f.e. inventory [ facts.osfamily ])
we need to quote the dot in such column name for the DataTables library or it will
interpret the dot a way to get into a nested results object.
See https://datatables.net/reference/option/columns.data#Types."""
return data.replace('.', '\\.') | db5e82e5d3641bebcac069ac4d5a7bb42baafcbb | 7,843 |
def sort_kv_pairs_by_value(d):
"""Turn a dict into a list of key-value pairs, sorted by value."""
return [
(k, v) for v, k in sorted([(v, k) for k, v in d.items()], reverse=True)
] | 58f3e40c4993a64f71212157fdd73ad82712fa44 | 7,844 |
import os
def newcd(path):
"""DEPRICATE"""
cwd = os.getcwd()
os.chdir(path)
return cwd | 5def36e28a4125fafcfdab697be842841ed767b1 | 7,845 |
import string
def is_string_formatted(s, return_parsed_list=False):
""" check if a string has formatted characters (with curly braces) """
l = list(string.Formatter().parse(s))
if len(l) == 1 and l[0][0] == s:
is_formatted = False
else:
is_formatted = True
if return_parsed_list:
return is_formatted, l
return is_formatted | a47a698d1c53bbf4bfb88ec7aca9e1ed3b0958d5 | 7,846 |
from datetime import datetime
def _get_creation_date():
"""作成時刻を返す"""
return datetime.utcnow().strftime('%Y-%m-%d-T%H:%M:%SZ') | a6725716361b0b37c35c62fe1f9600224d8d04f2 | 7,848 |
def check_length(min_length: int,
max_length: int,
mode: str = 'and',
*args) -> bool:
"""
check items length is between min_length and max_length
:param min_length: minimum length
:param max_length: maximum length
:param mode: check mode, 'and': all items need clear length check, 'or': more than one item need clear length check
:param args: items
:return: status, [correct] or [incorrect]
"""
if mode == 'and':
for item in args:
if not (min_length <= len(item) <= max_length):
return False # if found incorrect item, stop check-loop and return False
return True # if can't found incorrect item, return True
else:
for item in args:
if min_length <= len(item) <= max_length:
return True # if found correct item, stop check-loop and return True
return False | f959619a466f62bf6ecfaf10e0fbb316652891e7 | 7,850 |
def check_processed_data(df,col_list,na_action):
""" Checks if provided dataframe consists of required columns and no missing values
"""
check_passed = True
# Check columns
df_cols = df.columns
if set(df_cols) != set(col_list):
check_passed = False
print('Column names mismatched')
# Check missing values
n_missing = df.isnull().sum().sum()
if n_missing > 0:
print('Data contains missing {} values'.format(n_missing))
if na_action == 'drop':
print('Dropping rows with missing values')
elif na_action == 'ignore':
print('Keeping missing values as it is')
else:
print('Not adding this data into master dataframe')
check_passed = False
return check_passed | fd26d00eabd9eb1dfd1f8bce01a3fb86582a740f | 7,851 |
import subprocess
def execute_command(command):
"""Executes a command, capturing the output"""
output = subprocess.run(command, capture_output=True, encoding='utf-8')
if len(output.stderr) > 0:
print(output.stderr)
output.check_returncode()
return output | 7b768251d0ad52091e79b55aadeebc2481e07b26 | 7,852 |
def feed_conversation(samples, limit=5, threshold=.85):
"""helper function to feed result of classifier to Conversation module."""
try:
iter(samples)
assert not any(not isinstance(sub, tuple) for sub in samples)
except (AssertionError, TypeError) as e:
raise TypeError('samples must be an iterable contains tuples.')
samples.sort(key=lambda x: x[1], reverse=True)
samples = samples[:limit]
if samples[0][1] > threshold:
return samples[0]
elif samples[0][1] > threshold / 5:
return samples
else:
return None | 4c3d9b7c63e71790bb1a8445662754d48e31524f | 7,853 |
def point_inside_volume(p, ab1, ab2, eps = 0.01):
"""
Check if point p is inside the aabb volume
"""
ab1 = ab1.copy() - eps
ab2 = ab2.copy() + eps
if ab1[0] <= p[0] <= ab2[0] and \
ab1[1] <= p[1] <= ab2[1] and \
ab1[2] <= p[2] <= ab2[2]:
return True
else:
return False | 9cdb6323343fdc23dae4b2c899927450c92cb7a2 | 7,854 |
def _determine_levels(index):
"""Determine the correct levels argument to groupby."""
if isinstance(index, (tuple, list)) and len(index) > 1:
return list(range(len(index)))
else:
return 0 | 2eaed820eb45ff17eb4911fe48670d2e3412fb41 | 7,855 |
def format_val(v):
"""Takes in float and formats as str with 1 decimal place
:v: float
:returns: str
"""
return '{:.1f}%'.format(v) | 932ca312a573a7e69aa12e032d7b062ac22f3709 | 7,858 |
import re
def you_to_yall(text: str) -> str:
"""Convert all you's to y'all."""
pattern = r'\b(y)(ou)\b'
return re.sub(pattern, r"\1'all", text, flags=re.IGNORECASE) | 1a3ee7ebf2394f84ad296e18da789dff8ca50a12 | 7,860 |
def to_aws_tags(tags):
"""
When you assign tags to an AWS resource, you have to use the form
[{"key": "KEY1", "value": "VALUE1"},
{"key": "KEY2", "value": "VALUE2"},
...]
This function converts a Python-style dict() into these tags.
"""
return [
{"key": key, "value": value}
for key, value in tags.items()
] | d1e18ea1e4de08fcae59febbe97ab3eb5bc2a2f1 | 7,863 |
def check_for_winner(players) -> bool:
"""Checks all players for a single winner. Returns True if there is a winner.
Keyword arguments:
players -- list of player objects
"""
return sum(map(lambda x: not x.is_bankrupt(), players)) == 1 | 17d39e92a38a9474f080ddebfac1d4813f464a1e | 7,864 |
def get_game_player(game_state):
"""Get the game player whose turn it is to play."""
num_players = len(game_state.game_players)
for game_player in game_state.game_players:
if game_state.turn_number % num_players == game_player.turn_order:
return game_player
return None | a75a0b1b7f1ce4da8c944ad40208fba6f9a50f5a | 7,865 |
import re
def get_headers_pairs_list(filename, verbose=False):
"""
Read data for clustering from a given file.
Data format: <email_number> <header>.
Clusters are separated with a blank line.
:param filename: file with input data for clustering.
:param verbose: Whether to be verbose. Default - False.
:return: List of pairs (email_number, header).
"""
if verbose:
print("Reading headers...", end="")
with open(filename, encoding='utf-8') as inf:
lines = list(map(lambda x: x.strip(), inf.readlines()))
lines = list(filter(lambda x: x != "", lines))
def make_pair(line):
words = re.split(re.compile("\s+"), line)
return (
int(words[0]),
" ".join(words[1:])
)
if verbose:
print("Done")
return list(map(make_pair, lines)) | d6b457652e1025475075fb601ba81b6a7fe346fc | 7,867 |
from pathlib import Path
def _run_jlab_string(talktorials_dst_dir):
"""
Print command for starting JupyterLab from workspace folder.
Parameters
----------
talktorials_dst_dir : str or pathlib.Path
Path to directory containing the talktorial folders.
"""
talktorials_dst_dir = Path(talktorials_dst_dir)
message = f"""
To start working with the talktorials in JupyterLab run:
jupyter lab {talktorials_dst_dir}
Enjoy!
"""
return message | 76c45f77f419b6a302d63d92e51cd0ea1bb92ebb | 7,869 |
def get_full_names(pdb_dict):
"""Creates a mapping of het names to full English names.
:param pdb_dict: the .pdb dict to read.
:rtype: ``dict``"""
full_names = {}
for line in pdb_dict.get("HETNAM", []):
try:
full_names[line[11:14].strip()] += line[15:].strip()
except: full_names[line[11:14].strip()] = line[15:].strip()
return full_names | be31bb2c8e59e7b2ef4b51aba45f3cbafcb23a63 | 7,871 |
def refsoot_imag(wavelengths, enhancement_param=1):
"""imaginary part ot the refractive index for soot
:param wavelengths: wavelength(s) in meter.
:param enhancement_param: This parameter enhances the mass absoprtion efficiency of BC.
It makes it possible to scale BC absorption. Values of this parameters associated
with the BC MAE at 550nm are detailed below, with index prescribed by Bond and Bergstrom 2006:
1 for a MAE of 6.9 m² / g at 550nm ;
1.09 for a MAE of 7.5 m² / g at 550nm ;
1.638 pour un MAC de 11.25 m² / g at 550nm; (Tuzet et al. 2019)
2.19 pour un MAC de 15m² / g at 550nm (tipycal values of hadley & kirchstetter 2012))
"""
m_soot = 1.95 - 1j * 0.79 # Bond and Bergstrom 2006, section 7.6
temp = (m_soot**2 - 1) / (m_soot**2 + 2)
# The multiplication by the enhancement parameter scales the absorption efficacity.
# A similar approach is done in SNICAR by tuning impurity density
return temp.imag * enhancement_param | bbd7a9ad7f14088739c8eeaef926dbc63f5a2385 | 7,873 |
import os
def _file_path_check(filepath=None, format="png", interactive=False, is_plotly=False):
"""Helper function to check the filepath being passed.
Args:
filepath (str or Path, optional): Location to save file.
format (str): Extension for figure to be saved as. Defaults to 'png'.
interactive (bool, optional): If True and fig is of type plotly.Figure, sets the format to 'html'.
is_plotly (bool, optional): Check to see if the fig being passed is of type plotly.Figure.
Returns:
String representing the final filepath the image will be saved to.
"""
if filepath:
filepath = str(filepath)
path_and_name, extension = os.path.splitext(filepath)
extension = extension[1:].lower() if extension else None
if is_plotly and interactive:
format_ = "html"
elif not extension and not interactive:
format_ = format
else:
format_ = extension
filepath = f"{path_and_name}.{format_}"
try:
f = open(filepath, "w")
f.close()
except (IOError, FileNotFoundError):
raise ValueError(
("Specified filepath is not writeable: {}".format(filepath))
)
return filepath | 27d47df198331ee3dd3f6d4d0d1490520f09fd4b | 7,874 |
def get_table_type(filename):
""" Accepted filenames:
device-<device_id>.csv,
user.csv,
session-<time_iso>.csv,
trials-<time_iso>-Block_<n>.csv
:param filename: name of uploaded file.
:type filename: str
:return: Name of table type.
:rtype: str|None
"""
basename, ext = filename.split('.')
parts = basename.split('-')
first = parts[0]
if ext == 'csv' and first in ['device', 'user', 'session', 'trials']:
return first
else:
return None | bc4f39e4c9138168cec44c492b5d1965de711a7e | 7,876 |
def length_of_longest_substring(s: str) -> int:
"""
The most obvious way to do this would be to go through all possible substrings of the string which would result in
an algorithm with an overall O(n^2) complexity.
But we can solve this problem using a more subtle method that does it with one linear traversal( O(n)complexity ).
First,we go through the string one by one until we reach a repeated character. For example if the string is
“abcdcedf”, what happens when you reach the second appearance of "c"?
When a repeated character is found(let’s say at index j), it means that the current substring (excluding the
repeated character of course) is a potential maximum, so we update the maximum if necessary. It also means that the
repeated character must have appeared before at an index i, where i<j
Since all substrings that start before or at index i would be less than the current maximum, we can safely start
to look for the next substring with head which starts exactly at index i+1.
"""
# creating set to store last positions of occurrence
seen = {}
max_length = 0
# staring the initial window at 0
start = 0
for end in range(len(s)):
# have we seen this element already?
if s[end] in seen:
# move the start pointer to position after last occurrence
start = max(start, seen[s[end]] + 1)
# update last seen value of character
seen[s[end]] = end
max_length = max(max_length, end - start + 1)
return max_length | 3844c6fd1c62025b704284e76da25f7c63aa0fc9 | 7,877 |
def make_download_filename(genome, args, response_format):
"""
Make filename that will explain to the user what the predictions are for
:param genome: str: which version of the genome we are pulling data from
:param args: SearchArgs: argument used for search
:param response_format: str file extension/format
:return: str filename that will be returned to the user
"""
prefix = 'predictions_{}_{}_{}'.format(genome, args.get_model_name(), args.get_gene_list())
middle = ''
if not args.is_custom_ranges_list():
middle = '_{}_{}'.format(args.get_upstream(), args.get_downstream())
filename = '{}{}.{}'.format(prefix, middle, response_format)
return filename.replace(' ', '_') | 4645e3175de0db81e940d0e64740e937bce7afc3 | 7,878 |
def window_to_bounds(window, affine):
"""Convert pixels to coordinates in a window"""
minx = ((window[1][0], window[1][1]) * affine)[0]
maxx = ((window[1][1], window[0][0]) * affine)[0]
miny = ((window[1][1], window[0][1]) * affine)[1]
maxy = ((window[1][1], window[0][0]) * affine)[1]
return minx, miny, maxx, maxy | 6377d792271a86175349daa277b8eb937dd740f5 | 7,879 |
import os
import uuid
def docker_compose_package_project_name():
"""Generate a project name using the current process PID and a random uid.
Override this fixture in your tests if you need a particular project name.
This is a package scoped fixture. The project name will contain the scope"""
return "pytest{}-package{}".format(os.getpid(), str(uuid.uuid4()).split("-")[1]) | 7e7960a5e34e93618338765b95f5a4c8eb874a3f | 7,882 |
import numpy
import random
def time_mask(spec, T=40, n_mask=2, replace_with_zero=True, inplace=False):
"""freq mask for spec agument
:param numpy.ndarray spec: (time, freq)
:param int n_mask: the number of masks
:param bool inplace: overwrite
:param bool replace_with_zero: pad zero on mask if true else use mean
"""
if inplace:
cloned = spec
else:
cloned = spec.copy()
len_spectro = cloned.shape[0]
ts = numpy.random.randint(0, T, size=(n_mask, 2))
for t, mask_end in ts:
# avoid randint range error
if len_spectro - t <= 0:
continue
t_zero = random.randrange(0, len_spectro - t)
# avoids randrange error if values are equal and range is empty
if t_zero == t_zero + t:
continue
mask_end += t_zero
if replace_with_zero:
cloned[t_zero:mask_end] = 0
else:
cloned[t_zero:mask_end] = cloned.mean()
return cloned | f69364510c78f2fc3e96fb4f028737c6c415d5df | 7,883 |
def change(csq):
"""
>>> change("missense|TMEM240|ENST00000378733|protein_coding|-|170P>170L|1470752G>A")
('170P', '170L', True)
>>> change('synonymous|AGRN|ENST00000379370|protein_coding|+|268A|976629C>T')
('268A', '268A', False)
"""
parts = csq.split("|")
if len(parts) < 7:
return 0, 0, False
if not ">" in parts[-2]:
return (parts[-2], parts[-2], False)
aa_from, aa_to = parts[-2].split(">")
# 533PLGQGYPYQYPGPPPCFPPAYQDPGFSYGSGSTGSQQSEGSKSSGSTRSSRRAPGREKERRAAGAGGSGSESDHTAPSGVGSSWRERPAGQLSRGSSPRSQASATAPGLPPPHPTTKAYTVVGGPPGGPPVRELAAVPPELTGSRQSFQKAMGNPCEFFVDIM*>533LWVRATPTSTRDPHPASRLPTRTRALAMAAAAPGVSRVKGAKAVGPPGAAAGPRAVRRSVGRRELGAVAVNRITRHRVGWGAAGESVRPASSAVAAAHAVRPRLPPRGSPRPTPRPRPIQWWGGHPGDPLSGSWLPSPRN*
return aa_from, aa_to, True | da43c6bd45e641b885469d07c2e6befff334d8a3 | 7,884 |
def with_coordinates(pw_in_path, positions_type, atom_symbols, atom_positions):
"""Return a string giving a new input file, which is the same as the one at
`pw_in_path` except that the ATOMIC_POSITIONS block is replaced by the one
specified by the other parameters of this function.
`positions_type`, `atom_symbols`, and `atom_positions` have the same
meaning as the return values from `final_coordinates_from_scf()`.
Assumes that there are no whitespace lines in the ATOMIC_POSITIONS block
(not sure whether this is allowed by QE).
"""
with open(pw_in_path, 'r') as fp:
in_lines = fp.readlines()
out_lines = []
in_atomic_block = False
atom_count = 0
for i, line in enumerate(in_lines):
if 'ATOMIC_POSITIONS' in line:
out_lines.append("ATOMIC_POSITIONS {}\n".format(positions_type))
in_atomic_block = True
elif in_atomic_block:
sym, pos = atom_symbols[atom_count], atom_positions[atom_count]
pos_line = " {} {} {} {}\n".format(sym, str(pos[0]), str(pos[1]),
str(pos[2]))
out_lines.append(pos_line)
atom_count += 1
if atom_count == len(atom_symbols):
in_atomic_block = False
else:
out_lines.append(line)
return ''.join(out_lines) | 11dc207a4f17a6521a1aa6299d455f0548c50566 | 7,885 |
def calculate_factor_initial_size(n, key):
"""
Calculate different initial embedding sizes by a chosen factor.
:param n: Number of nodes in the graph
:param key: The factor- for example if key==10, the sizes will be n/10, n/100, n/100, .... the minimum is 100 nodes
in the initial embedding
:return: List of initial embedding sizes
"""
initial = []
i = n
while i > 100:
i = int(i/key)
i_2 = int(i/2)
key = pow(key, 2)
if i > 100:
initial.append(i)
if i_2 > 100:
initial.append(i_2)
initial.append(100)
ten_per = int(n/10)
initial.append(ten_per)
initial.sort()
return initial | 35fdef82e55647b20f9d86ec926e77c1d5244e2e | 7,887 |
def is_iterable(value):
""" Verifies the value is an is_iterable
:param value: value to identify if iterable or not.
"""
try:
iterable_obj = iter(value)
return True
except TypeError as te:
return False | 13728b7c28506086a3eb9b8faefcdc6276eba00e | 7,888 |
def rw_normalize(A):
"""
Random walk normalization: computes D^⁼1 * A.
Parameters
----------
A: torch.Tensor
The matrix to normalize.
Returns
-------
A_norm: torch.FloatTensor
The normalized adjacency matrix.
"""
degs = A.sum(dim=1)
degs[degs == 0] = 1
return A / degs[:, None] | 2a9f90d1f2bf02545e9719b0f373e6eb215fa0cd | 7,889 |
import logging
def _get_areas(params, feature_names):
"""Returns mapping between areas and constituent feature types."""
areas = {}
for feature_id in range(len(params)):
feature_info = params[feature_id]
feature = feature_info["ID"]
area = feature_info["Area"]
if area not in areas:
areas[area] = [feature]
else:
areas[area].append(feature)
# Update the mapping from ID to name.
feature_names[feature]["Name"] = feature_info["Name"]
logging.info("Collected %d areas (%s).", len(areas), ",".join(areas.keys()))
return areas | 937797d7634ac6cd73af941c783f26d5a8028b4d | 7,891 |
import numpy
def calc_m_sq_cos_sq_para(tensor_sigma, flag_tensor_sigma: bool = False):
"""Calculate the term P2 for paramagnetic sublattice.
For details see documentation "Integrated intensity from powder diffraction".
"""
sigma_13 = tensor_sigma[2]
sigma_23 = tensor_sigma[5]
p_2 = numpy.square(numpy.abs(sigma_13)) + numpy.square(numpy.abs(sigma_23))
dder = {}
if flag_tensor_sigma:
ones = numpy.ones_like(sigma_13.real)
dder_sigma_13_real = 2*sigma_13.real * ones
dder_sigma_13_imag = 2*sigma_13.imag * ones
dder_sigma_23_real = 2*sigma_23.real * ones
dder_sigma_23_imag = 2*sigma_23.imag * ones
zeros = numpy.zeros_like(dder_sigma_13_real)
dder["tensor_sigma_real"] = numpy.stack([
zeros, zeros, dder_sigma_13_real,
zeros, zeros, dder_sigma_23_real, zeros, zeros, zeros], axis=0)
dder["tensor_sigma_imag"] = numpy.stack([
zeros, zeros, dder_sigma_13_imag,
zeros, zeros, dder_sigma_23_imag, zeros, zeros, zeros], axis=0)
return p_2, dder | 910087c34ffc5ec43376fbdbc6368761fb4580ee | 7,892 |
def transform_seed_objects(objects):
"""Map seed objects to state format."""
return {obj['instance_id']: {
'initial_player_number': obj['player_number'],
'initial_object_id': obj['object_id'],
'initial_class_id': obj['class_id'],
'created': 0,
'created_x': obj['x'],
'created_y':obj['y'],
'destroyed': None,
'destroyed_by_instance_id': None,
'destroyed_building_percent': None,
'deleted': False,
'destroyed_x': None,
'destroyed_y': None,
'building_started': None,
'building_completed': None,
'total_idle_time': None
} for obj in objects} | 685c0c5b22fdff108311338354bb42fb53fd07f6 | 7,894 |
def remove_digits(text):
"""
Remove all digits from the text document
take string input and return a clean text without numbers.
Use regex to discard the numbers.
"""
result = ''.join(i for i in text if not i.isdigit()).lower()
return ' '.join(result.split()) | d9604c31391e48ab826089d39201577bdf83c2fa | 7,896 |
def _ipaddr(*args, **kwargs):
"""Fake ipaddr filter"""
return "ipaddr" | 8550ebc305442620e57d9b164d6751c1a16b4ef6 | 7,897 |
def QueryEncode(q: dict):
"""
:param q:
:return:
"""
return "?" + "&".join(["=".join(entry) for entry in q.items()]) | b92aaf02b3322b3c35b8fe8d528e2e4bc6f91813 | 7,899 |
import re
def _fast_suggest(term):
"""Return [] of suggestions derived from term.
This list is generated by removing punctuation and some stopwords.
"""
suggest = [term]
def valid(subterm):
"""Ensure subterm is valid."""
# poor man stopwords collection
stopwords = ['and', 'the', 'in', 'of']
return subterm and subterm.lower() not in stopwords
subterms = [st for st in re.split(r'\W', term) if valid(st)]
if len(subterms) > 1:
suggest.extend(subterms)
return suggest | f4790e22abae7b33ee5585ea4a21189d7954cf40 | 7,900 |
def fixture_perform_migrations_at_unlock():
"""Perform data migrations as normal during user unlock"""
return False | a8a8ae9118b2de4f0cdbb7ba3e39fdd7a552f77b | 7,903 |
from pathlib import Path
def getFileAbsolutePath(rel_path):
"""
Retorna o caminho absoluto de um arquivo a partir de seu caminho relativo no projeto
:param rel_path:
:return: absolute_path
"""
data_folder = Path("PythoWebScraper/src")
file_to_open = data_folder / rel_path
return file_to_open | b39baaa26e3c8a7c7a8c41dbb4fafceb7ca78c70 | 7,904 |
import requests
def generate_text(query, genre):
"""
Функция отправляет POST-запрос к Балабобе,
и получает ответ в виде словаря.
Параметры POST-запроса:
query: ключевая фраза
genre: id жанра, в котором Балабоба должен сгенерировать текст
"""
text_url = 'https://zeapi.yandex.net/lab/api/yalm/text3'
data = {
"query": query,
"intro": genre
}
try:
response = requests.post(url=text_url, json=data)
dict_response = response.json()
except:
print('Во время выполнения функции get_genres() возникла ошибка!')
dict_response = {}
return dict_response | 467c40145db532f912ba2d17ad3ba588273fa682 | 7,905 |
def directive_exists(name, line):
"""
Checks if directive exists in the line, but it is not
commented out.
:param str name: name of directive
:param str line: line of file
"""
return line.lstrip().startswith(name) | eb69044de8860b1779ce58ef107859028b8c98cf | 7,906 |
import timeit
def search_set(n):
"""Search for an element in a set.
"""
my_set = set(range(n))
start = timeit.default_timer()
n in my_set # pylint: disable=pointless-statement
return timeit.default_timer() - start | f0d8ba45df45130cc81d70e2d391825ed46dc93e | 7,907 |
import os
def sweepnumber_fromfile(fname):
"""Returns the sweep number of a polar file based on its name"""
return int(os.path.basename(fname).split('.')[1]) | 4648bfcf10ea0645266109a5c0ab1a7e41ffe46d | 7,908 |
import os
import subprocess
def add(printer_name, uri, ppd, location, description):
"""
Add a new printer to the system with the given parameters.
"""
try:
if ppd[:4] == 'drv:':
type = '-m'
else:
type = '-P'
with open(os.devnull, "w") as fnull:
args = ["lpadmin", "-p", printer_name, "-v", uri, type, ppd, "-D", description, "-L", location, "-E"]
status = subprocess.call(args, stdout=fnull, stderr=subprocess.STDOUT)
except:
return False
return True if status == 0 else False | 8066f5ba76fc039efd5dc4a3f53fa84c28b825c7 | 7,910 |
def unitSpacing2MM(unit):
""" Converts KLE unit spacing into wxPoint spacing. Used in placing KiCAD components """
unitSpacing = 19.050000
wxConversionFactor = 1000000
return unit*unitSpacing | 2cc137b7db7a8b1871a7329fa482351fd52ed544 | 7,911 |
def entrypoint(label):
"""
If a class if going to be registered with setuptools as an entrypoint it
must have the label it will be registered under associated with it via this
decorator.
This decorator sets the ENTRY_POINT_ORIG_LABEL and ENTRY_POINT_LABEL class
proprieties to the same value, label.
Examples
--------
>>> from dffml import entrypoint, Entrypoint
>>>
>>> @entrypoint('mylabel')
... class EntrypointSubclassClass(Entrypoint): pass
In setup.py, EntrypointSubclassClass needs to have this decorator applied to
it with label set to mylabel.
.. code-block:: python
entry_points={
'dffml.entrypoint': [
'mylabel = module.path.to:EntrypointSubclassClass',
]
}
"""
def add_entry_point_label(cls):
cls.ENTRY_POINT_ORIG_LABEL = label
cls.ENTRY_POINT_LABEL = label
return cls
return add_entry_point_label | 68cb3f2d2a982fefd34f412888ae50fcea6a743f | 7,913 |
def hide_empty(value, prefix=', '):
"""Return a string with optional prefix if value is non-empty"""
value = str(value)
return prefix + value if value else '' | d2943dbce763bd054dc26839b2d24232867b3312 | 7,915 |
import logging
import os
import csv
def check_table_and_warn_if_dmg_freq_is_low(folder):
"""Returns true if the damage frequencies are too low to allow
Bayesian estimation of DNA damages, i.e < 1% at first position.
"""
logger = logging.getLogger(__name__)
filename = "misincorporation.txt"
mismatches = {
"5p": {"C": 0, "C>T": 0},
"3p": {"G": 0, "G>A": 0},
}
try:
with open(os.path.join(folder, filename), newline="") as csvfile:
reader = csv.DictReader(csvfile, delimiter="\t")
if not reader.fieldnames:
logger.error("%r is empty; please re-run mapDamage", filename)
return False
for row in reader:
if int(row["Pos"]) == 1:
counts = mismatches[row["End"]]
for key in counts:
counts[key] += int(row[key])
except (csv.Error, IOError, OSError, KeyError) as error:
logger.error("Error reading misincorporation table: %s", error)
return False
if not (mismatches["5p"]["C"] and mismatches["3p"]["G"]):
logger.error(
"Insufficient data in %r; cannot perform Bayesian computation", filename
)
return False
total = 0.0
total += mismatches["5p"]["C>T"] / mismatches["5p"]["C"]
total += mismatches["3p"]["G>A"] / mismatches["3p"]["G"]
if total < 0.01:
logger.warning(
"DNA damage levels are too low, the Bayesian computation should not be "
"performed (%f < 0.01)",
total,
)
return True | d776bf11d311ae1fac9f259e8f7a78f9caf8d1b8 | 7,916 |
def preauction_filters(participants, task, indivisible_tasks=False):
"""Apply some preauction filters to the participants list in order to remove any invalid candidates.
Args:
participants (list): A list of participating nodes and their info.
indivisible_tasks (bool): Only allow nodes that offer full usage time.
Returns:
[list]: A list of participants.
"""
if indivisible_tasks:
participants = [
x for x in participants if x['usage_time'] >= task.loc['usage_time']]
return participants | 7eadb0f8e95942ae0b3033cbca90ea44fba4d199 | 7,917 |
def isSymmetric(root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
leftPart=[root.left]
rightPart=[root.right]
while leftPart and rightPart:
leftNode=leftPart.pop()
rightNode=rightPart.pop()
if leftNode and rightNode:
if leftNode.val!=rightNode.val:
return False
leftPart.append(leftNode.left)
leftPart.append(leftNode.right)
rightPart.append(rightNode.right)
rightPart.append(rightNode.left)
elif leftNode or rightNode:
return False
return True | 7026794a5e94df15439da1e776b485927fcf6078 | 7,918 |
import time
from datetime import datetime
def check_date(birth_date):
"""If false it has a validation message with it"""
if birth_date != None:
birth_date = birth_date.strip()
if birth_date == '':
return (False, "Please Enter Your Birth Date")
try:
time.strptime(birth_date, '%m/%d/%Y')
birth_date_year = int((str(birth_date)).split("/")[2])
print(birth_date_year)
current_year = datetime.now().year
print(current_year)
if current_year - birth_date_year < 10:
return (False, "Sorry , You have to be at least 10 Years old or above ")
except:
return (False, "Please Enter Your Birth Date in the Correct Format")
return (True, "") | 06c7a10413d1509201ae672cca5985769d12871e | 7,919 |
import heapq
def min_window(k):
"""
Algorithm to find minimum window length between k lists. Uses
a heap.
"""
heap = []
p=[0 for i in range(len(k))]
min_r = 99999999
ma=0
for i in range(len(k)):
if k[i][0]>ma:
ma=k[i][0]
heapq.heappush(heap,(k[i][0],i))
while True:
mi = heapq.heappop(heap)
if ma-mi[0] < min_r:
min_r = ma-mi[0]
p[mi[1]]+=1
if(p[mi[1]]>=len(k[mi[1]])):
return min_r
else:
num = k[mi[1]][p[mi[1]]]
if num > ma:
ma=num
heapq.heappush(heap, (num,mi[1])) | 4ad706eac321a43924a32e2883c3ffae24a7f989 | 7,920 |
def as_dict_with_keys(obj, keys):
"""
Convert SQLAlchemy model to list of dictionary with provided keys.
"""
return [dict((a, b) for (a, b) in zip(keys, item)) for item in obj] | 1fcab95f9f94696c1af652b0b181e6e3e69f7f53 | 7,922 |
def get_required_fields():
""" Get required fields for the deployment from UI.
Fields required for update only:
eventId, rd, deploymentNumber, versionNumber,
[lastModifiedTimestamp, deployCruiseInfo, recoverCruiseInfo, ingestInfo]
At a minimum, deploymentNumber, versionNumber and (instrument) rd must be provided to create a deployment.
"""
required_fields = [
'@class',
'assetUid',
'editPhase',
'eventName',
'eventStartTime',
'eventStopTime',
'eventType',
'dataSource',
'deployedBy',
'deployCruiseInfo',
'deploymentNumber',
'depth',
'inductiveId',
'ingestInfo',
'latitude',
'longitude',
'orbitRadius',
'mooring_uid',
'node_uid',
'notes',
'recoveredBy',
'recoverCruiseInfo',
'rd',
'sensor_uid',
'versionNumber'
]
return required_fields | fe2439b7e5adcd7b9d98f828c3315253e0786bc8 | 7,923 |
def maximo_libreria(a: float, b: float) -> float:
"""Re-escribir utilizando el built-in max.
Referencia: https://docs.python.org/3/library/functions.html#max
"""
return max(a, b) | 41f4c37c2dcb0a64c11c1517f93c119722002e3d | 7,924 |
from typing import List
import os
import fnmatch
def glob(glob_pattern: str, directoryname: str) -> List[str]:
"""
Walks through a directory and its subdirectories looking for files matching
the glob_pattern and returns a list=[].
:param directoryname: Any accessible folder name on the filesystem.
:param glob_pattern: A string like "*.txt", which would find all text files.
:return: A list=[] of absolute filepaths matching the glob pattern.
"""
matches = []
for root, dirnames, filenames in os.walk(directoryname):
for filename in fnmatch.filter(filenames, glob_pattern):
absolute_filepath = os.path.join(root, filename)
matches.append(absolute_filepath)
return matches | 3155ce1037c39339439805024f1d6abac6b24460 | 7,926 |
def test_store_decorator(sirang_instance):
"""Test dstore"""
db = 'dstore'
collection = 'test'
def test_func(arg1, arg2, arg3, arg4):
return arg2
# Test inversions
no_invert = sirang_instance.dstore(
db, collection, keep=['arg1', 'arg2'], inversion=False,
doc_id_template='~invert', store_return=False)(test_func)
invert = sirang_instance.dstore(
db, collection, keep=['arg1', 'arg2'], inversion=True,
doc_id_template='invert', store_return=False)(test_func)
a, b, c, d = range(4)
assert no_invert(arg1=a, arg2=b, arg3=c, arg4=d) == b
assert invert(arg1=a, arg2=b, arg3=c, arg4=d) == b
no_invert_doc = sirang_instance.retrieve(
db, collection, filter_criteria={'_id': '~invert'})[0]
invert_doc = sirang_instance.retrieve(
db, collection, filter_criteria={'_id': 'invert'})[0]
assert 'arg1' in no_invert_doc.keys()
assert 'arg2' in no_invert_doc.keys()
assert 'arg3' not in no_invert_doc.keys()
assert 'arg4' not in no_invert_doc.keys()
assert 'arg1' not in invert_doc.keys()
assert 'arg2' not in invert_doc.keys()
assert 'arg3' in invert_doc.keys()
assert 'arg4' in invert_doc.keys()
# Test store_return=True and doc_id_template != None
test_key = 'x'
counter = 5
def store_returns_func(arg1, arg2, arg3, arg4):
return {test_key: arg2}, arg3
ret_store = sirang_instance.dstore(
db, collection, keep=['arg1', 'arg2'], inversion=False,
doc_id_template="res_store_{}", id_counter=counter,
store_return=True)(store_returns_func)
a, b, c, d = range(4)
assert ret_store(arg1=a, arg2=b, arg3=c, arg4=d) == c
store_return_doc = sirang_instance.retrieve(
db, collection,
filter_criteria={'_id': "res_store_{}".format(counter)})[0]
assert test_key in store_return_doc.keys()
assert store_return_doc[test_key] == b | 868d26de1db3af3ea22e129c757400d8d013c9b1 | 7,927 |
def sdate_from_datetime(datetime_object, format='%y-%m-%d'):
"""
Converts a datetime object to SDATE string.
"""
return datetime_object.strftime(format) | 3f7ee70c47e1971e1c690f564fc8d4df519db5b6 | 7,929 |
def get_version(release):
""" Given x.y.z-something, return x.y
On ill-formed return verbatim.
"""
if '.' in release:
sl = release.split(".")
return '%s.%s' % (sl[0], sl[1])
else:
return release | 520438d5ca260caf27df31c4742d9da8c31f3218 | 7,931 |
def arrays_shape(*arrays):
"""Returns the shape of the first array that is not None.
Parameters
----------
arrays : ndarray
Arrays.
Returns
-------
tuple of int
Shape.
"""
for array in arrays:
if array is not None:
shape = array.shape
return shape | e9e6a4876b938934c843386dffc58f0eccfb20a3 | 7,932 |
import os
def check_is_board(riotdir, board):
"""Verify if board is a RIOT board.
:raises ValueError: on invalid board
:returns: board name
"""
if board == 'common':
raise ValueError("'%s' is not a board" % board)
board_dir = os.path.join(riotdir, 'boards', board)
if not os.path.isdir(board_dir):
raise ValueError("Cannot find '%s' in %s/boards" % (board, riotdir))
return board | 94ecf0ca5762e66e667f7021af83038d982a0ff0 | 7,933 |
def max_profit(prices):
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
:param prices:
:return:
"""
if not prices:
return 0
max_profit, max_price = (0,0)
for price in prices[::-1]:
max_price = max(max_price, price)
max_profit = max(max_profit, max_price - price)
return max_profit | 056dff9d2ad4af9d38f2ce0f1ad27c1c0df69121 | 7,934 |
def model_as_json(bot_entries):
""" Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB
@param
bot_entries (list) list of sub-lists
@returns
json_list (list) list of modeled dictionaries
"""
json_list = []
for bot_entry in bot_entries:
json_object = {
"_id": bot_entry[2],
"Category": "Botnets",
"Entity-Type": "IP",
"IP": bot_entry[0],
"Botscout-id": bot_entry[2],
"Bot-Name": bot_entry[4],
"Email": bot_entry[5],
"TimestampUTC": bot_entry[6],
"mongoDate": bot_entry[7],
"DatetimeUTC": bot_entry[8],
"TimestampUTC-CTI": bot_entry[9],
"mongoDate-CTI": bot_entry[10],
"DatetimeUTC-CTI": bot_entry[11],
"Country": bot_entry[1],
}
json_list.append(json_object)
return json_list | e18d4c29cdeda950bd0b32db5354f197e38f27ff | 7,935 |
def cone(toplexes, subcomplex, coneVertex="*"):
"""Construct the cone over a subcomplex. The cone vertex can be renamed if desired. The resulting complex is homotopy equivalent to the quotient by the subcomplex."""
return toplexes + [spx + [coneVertex] for spx in subcomplex] | 6b1328a2f7c32988666b0c7039efd0ce6ecdffef | 7,937 |
def replace(correct, guess, correct2):
"""
Find out if your guess is in the correct answer or not, if yes, put it into your answer
"""
ans = ''
i = 0
for ch in correct:
if guess == ch:
ans += correct[i]
else:
ans += correct2[i]
i += 1
# for i in range(len(correct)):
# if guess == correct[i]:
# ans += guess
# else:
# ans += correct2[i]
return ans | aacd9142599cc815a5526350c96b4db09b74777d | 7,938 |
def broadcastable(shape_1, shape_2):
"""Returns whether the two shapes are broadcastable."""
return (not shape_1 or not shape_2 or
all(x == y or x == 1 or y == 1
for x, y in zip(shape_1[::-1], shape_2[::-1]))) | 9a968fdee4a401b5f9cee42286de7553afa02183 | 7,939 |
def bipartite_sets(bg):
"""Return two nodes sets of a bipartite graph.
Parameters:
-----------
bg: nx.Graph
Bipartite graph to operate on.
"""
top = set(n for n, d in bg.nodes(data=True) if d['bipartite']==0)
bottom = set(bg) - top
return (top, bottom) | 618756dbfa87dc0b5d878545fa5395c4a122c84c | 7,940 |
def htmlize(widget):
"""
Jinja filter to render a widget to a html string
"""
html = widget.render(widget)
try:
html = html.decode('utf-8')
except Exception:
pass
return html | a6c4aeac2bc27aeaaccbe78b893ca33181234169 | 7,943 |
def _merge_block(internal_transactions, transactions, whitelist):
"""
Merge responses with trace and chain transactions. Remove non-whitelisted fields
Parameters
----------
internal_transactions : list
List of trace transactions
transactions : list
List of chain transactions
whitelist : list
List of allowed fields
Returns
-------
list
List of trace transactions extended with whitelisted fields from related chain transactions
"""
transactions_by_id = {
(transaction["hash"], transaction["blockHash"]): transaction
for transaction in transactions
}
for transaction in internal_transactions:
hash = transaction["transactionHash"]
block = transaction["blockHash"]
if (hash, block) in transactions_by_id:
whitelisted_fields = {
key: value
for key, value in transactions_by_id[(hash, block)].items()
if key in whitelist
}
transaction.update(whitelisted_fields)
del transactions_by_id[(hash, block)]
return internal_transactions | b60c9cde133d97ac84b2899956a15a72c720bbaa | 7,945 |
def remove_virtual_slot_cmd(lpar_id, slot_num):
"""
Generate HMC command to remove virtual slot.
:param lpar_id: LPAR id
:param slot_num: virtual adapter slot number
:returns: A HMC command to remove the virtual slot.
"""
return ("chhwres -r virtualio --rsubtype eth -o r -s %(slot)s "
"--id %(lparid)s" %
{'slot': slot_num, 'lparid': lpar_id}) | 2c6f14949910865f3a60c0016b4587088441572e | 7,948 |
import json
def dict_to_bytestring(dictionary):
"""Converts a python dict to json formatted bytestring"""
return json.dumps(dictionary).encode("utf8") | 31e201d87e92075d6078450ad019cc51f474f9d4 | 7,949 |
def _merge_candidate_name(src, dest):
"""Returns the formatted name of a merge candidate branch."""
return f"xxx-merge-candidate--{src}--{dest}" | a08b6d4b57385bc390e649448ce264cffd5a1ffa | 7,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.