content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def create_outlier_mask(df, target_var, number_of_stds, grouping_cols=None):
"""
Create a row-wise mask to filter-out outliers based on target_var.
Optionally allows you to filter outliers by group for hier. data.
"""
def flag_outliers_within_groups(df, target_var,
grouping_cols, number_of_stds):
groups = df.groupby(grouping_cols)
means = groups[target_var].transform('mean')
stds = groups[target_var].transform('std')
upper_bound = means + stds * number_of_stds
lower_bound = means - stds * number_of_stds
return df[target_var].between(lower_bound, upper_bound)
def flag_outliers_without_groups(df, target_var, number_of_stds):
mean_val = df[target_var].mean()
std_val = df[target_var].std()
upper_bound = (mean_val + (std_val * number_of_stds))
lower_bound = (mean_val - (std_val * number_of_stds))
return (df[target_var] > lower_bound) & (df[target_var] < upper_bound)
if grouping_cols:
mask = flag_outliers_within_groups(
df=df, target_var=target_var,
number_of_stds=number_of_stds, grouping_cols=grouping_cols
)
else:
mask = flag_outliers_without_groups(
df=df, target_var=target_var,
number_of_stds=number_of_stds
)
return mask | 95a7e3e5a0cb8dcc4aa3da1af7e9cb4111cf6b81 | 3,239 |
def binary_search(x,l):
""" Esse algorítmo é o algorítmo de busca binária, mas ele retorna
qual o índice o qual devo colocar o elemento para que a lista
permaneça ordenada.
Input: elemento x e lista l
Output: Índice em que o elemento deve ser inserido para manter a ordenação da lista
"""
lo = 0 # Cota inferior inicial (Lower bound)
up = len(l) # Cota superior inicial (Upper bound)
while lo < up:
mid = int((lo+up)/2) #Ponto Médio
if l[mid] < x:
lo = mid + 1
else:
up = mid
return up | 457c403ffeb2eb5529c2552bdbe8d7beee9199f2 | 3,240 |
import os
import requests
def get_port_use_db():
"""Gets the services that commonly run on certain ports
:return: dict[port] = service
:rtype: dict
"""
url = "http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv"
db_path = "/tmp/port_db"
if not os.path.isfile(db_path):
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(db_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
db = {}
with open(db_path) as f:
content = f.read()
for line in content.split("\n")[1:]:
if line:
parts = line.split(",")
if len(parts) >= 4:
service = parts[0]
port = parts[1]
if service:
db[port] = service
return db | 4462ef74b5575905b75980827d5a5bb5ed05aee8 | 3,241 |
def generate_config(context):
""" Generate the deployment configuration. """
resources = []
name = context.properties.get('name', context.env['name'])
resources = [
{
'name': name,
'type': 'appengine.v1.version',
'properties': context.properties
}
]
outputs = [
{
'name': 'name',
'value': '$(ref.{}.name)'.format(name)
},
{
'name': 'createTime',
'value': '$(ref.{}.createTime)'.format(name)
},
{
'name': 'versionUrl',
'value': '$(ref.{}.versionUrl)'.format(name)
}
]
return {'resources': resources, 'outputs': outputs} | 9a997b87a8d4d8f46edbbb9d2da9f523e5e2fdc6 | 3,242 |
def remove_end_same_as_start_transitions(df, start_col, end_col):
"""Remove rows corresponding to transitions where start equals end state.
Millington 2009 used a methodology where if a combination of conditions
didn't result in a transition, this would be represented in the model by
specifying a transition with start and end state being the same, and a
transition time of 0 years.
AgroSuccess will handle 'no transition' rules differently, so these dummy
transitions should be excluded.
"""
def start_different_to_end(row):
if row[start_col] == row[end_col]:
return False
else:
return True
return df[df.apply(start_different_to_end, axis=1)] | f4b3ddca74e204ed22c75a4f635845869ded9988 | 3,243 |
def sieve(iterable, inspector, *keys):
"""Separates @iterable into multiple lists, with @inspector(item) -> k for k in @keys defining the separation.
e.g., sieve(range(10), lambda x: x % 2, 0, 1) -> [[evens], [odds]]
"""
s = {k: [] for k in keys}
for item in iterable:
k = inspector(item)
if k not in s:
raise KeyError(f"Unexpected key <{k}> found by inspector in sieve.")
s[inspector(item)].append(item)
return [s[k] for k in keys] | 6ebb76dfb3131342e08a0be4127fba242d126130 | 3,244 |
def divide(x, y):
"""A version of divide that also rounds."""
return round(x / y) | 1bf9e5859298886db7c928613f459f163958ca7b | 3,246 |
def dot(u, v):
"""
Returns the dot product of the two vectors.
>>> u1 = Vec([1, 2])
>>> u2 = Vec([1, 2])
>>> u1*u2
5
>>> u1 == Vec([1, 2])
True
>>> u2 == Vec([1, 2])
True
"""
assert u.size == v.size
sum = 0
for index, (compv, compu) in enumerate(zip(u.store,v.store)):
sum = sum + compv * compu
return sum | e431800750c8f7c14d7412753814e2498fdd3c09 | 3,247 |
def fix_lng_degrees(lng: float) -> float:
"""
For a lng degree outside [-180;180] return the appropriate
degree assuming -180 = 180°W and 180 = 180°E.
"""
sign = 1 if lng > 0 else -1
lng_adj = (abs(lng) % 360) * sign
if lng_adj > 180:
return (lng_adj % 180) - 180
elif lng_adj < -180:
return lng_adj % 180
return lng_adj | bde58152883874095b15ec38cfb24ea68d73c188 | 3,248 |
import typing
import inspect
def resolve_lookup(
context: dict, lookup: str, call_functions: bool = True
) -> typing.Any:
"""
Helper function to extract a value out of a context-dict.
A lookup string can access attributes, dict-keys, methods without parameters and indexes by using the dot-accessor (e.g. ``person.name``)
This is based on the implementation of the variable lookup of the django template system:
https://github.com/django/django/blob/master/django/template/base.py
"""
current = context
for bit in lookup.split("."):
try:
current = current[bit]
except (TypeError, AttributeError, KeyError, ValueError, IndexError):
try:
current = getattr(current, bit)
except (TypeError, AttributeError):
# Reraise if the exception was raised by a @property
if not isinstance(current, dict) and bit in dir(current):
raise
try: # list-index lookup
current = current[int(bit)]
except (
IndexError, # list index out of range
ValueError, # invalid literal for int()
KeyError, # current is a dict without `int(bit)` key
TypeError,
): # unsubscriptable object
return None
# raise LookupError(
# "Failed lookup for key " "[%s] in %r", (bit, current)
# ) # missing attribute
if callable(current) and call_functions:
try: # method call (assuming no args required)
current = current()
except TypeError:
signature = inspect.signature(current) # type: ignore
try:
signature.bind()
except TypeError: # arguments *were* required
pass # but we continue because we might use an attribute on the object instead of calling it
else:
raise
return current | a2090f2488ee10f7c11684952fd7a2498f6d4979 | 3,249 |
import os
import subprocess
def linux_gcc_name():
"""Returns the name of the `gcc` compiler. Might happen that we are cross-compiling and the
compiler has a longer name.
Args:
None
Returns:
str: Name of the `gcc` compiler or None
"""
cc_env = os.getenv('CC')
if cc_env is not None:
if subprocess.Popen([cc_env, "--version"], stdout=subprocess.DEVNULL):
return cc_env
return "gcc" if subprocess.Popen(["gcc", "--version"], stdout=subprocess.DEVNULL) else None | 47cf0ee9af4b1b7c9169632b86bc9b5e1db96ad3 | 3,252 |
def old_func5(self, x):
"""Summary.
Bizarre indentation.
"""
return x | 5bc9cdbc406fa49960613578296e81bdd4eeb771 | 3,253 |
def get_str_cmd(cmd_lst):
"""Returns a string with the command to execute"""
params = []
for param in cmd_lst:
if len(param) > 12:
params.append('"{p}"'.format(p=param))
else:
params.append(param)
return ' '.join(params) | a7cc28293eb381604112265a99b9c03e762c2f2c | 3,255 |
def calculate_score(arr):
"""Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
It check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1"""
if sum(arr) == 21 and len(arr) == 2:
return 0 # represents blackjack
if sum(arr) > 21 and 11 in arr:
arr.remove(11)
arr.append(1)
return sum(arr) | 0890c55068b8a92d9f1f577ccf2c5a770f7887d4 | 3,256 |
def calculate_phase(time, period):
"""Calculates phase based on period.
Parameters
----------
time : type
Description of parameter `time`.
period : type
Description of parameter `period`.
Returns
-------
list
Orbital phase of the object orbiting the star.
"""
return (time % period) / period | a537810a7705b5d8b0144318469b249f64a01456 | 3,257 |
import os
def _check_shebang(filename, disallow_executable):
"""Return 0 if the filename's executable bit is consistent with the
presence of a shebang line and the shebang line is in the whitelist of
acceptable shebang lines, and 1 otherwise.
If the string "# noqa: shebang" is present in the file, then this check
will be ignored.
"""
with open(filename, mode='r', encoding='utf8') as file:
content = file.read()
if "# noqa: shebang" in content:
# Ignore.
return 0
is_executable = os.access(filename, os.X_OK)
if is_executable and disallow_executable:
print("ERROR: {} is executable, but should not be".format(filename))
print("note: fix via chmod a-x '{}'".format(filename))
return 1
lines = content.splitlines()
assert len(lines) > 0, f"Empty file? {filename}"
shebang = lines[0]
has_shebang = shebang.startswith("#!")
if is_executable and not has_shebang:
print("ERROR: {} is executable but lacks a shebang".format(filename))
print("note: fix via chmod a-x '{}'".format(filename))
return 1
if has_shebang and not is_executable:
print("ERROR: {} has a shebang but is not executable".format(filename))
print("note: fix by removing the first line of the file")
return 1
shebang_whitelist = {
"bash": "#!/bin/bash",
"python": "#!/usr/bin/env python3",
}
if has_shebang and shebang not in list(shebang_whitelist.values()):
print(("ERROR: shebang '{}' in the file '{}' is not in the shebang "
"whitelist").format(shebang, filename))
for hint, replacement_shebang in shebang_whitelist.items():
if hint in shebang:
print(("note: fix by replacing the shebang with "
"'{}'").format(replacement_shebang))
return 1
return 0 | 205fa2bc88b4c80899223e691b6f9cd00492c011 | 3,260 |
def deconstruct_DMC(G, alpha, beta):
"""Deconstruct a DMC graph over a single step."""
# reverse complementation
if G.has_edge(alpha, beta):
G.remove_edge(alpha, beta)
w = 1
else:
w = 0
# reverse mutation
alpha_neighbors = set(G.neighbors(alpha))
beta_neighbors = set(G.neighbors(beta))
x = len(alpha_neighbors & beta_neighbors)
y = len(alpha_neighbors | beta_neighbors)
for neighbor in alpha_neighbors:
G.add_edge(beta, neighbor)
# reverse duplication
G.remove_node(alpha)
return (w, x, y) | fa32a325fd49435e3191a20b908ac0e9c3b992f8 | 3,261 |
def metadata_columns(request, metadata_column_headers):
"""Make a metadata column header and column value dictionary."""
template = 'val{}'
columns = {}
for header in metadata_column_headers:
columns[header] = []
for i in range(0, request.param):
columns[header].append(template.format(i))
return columns | ca1f89935260e9d55d57df5fe5fbb0946b5948ac | 3,262 |
def get_nodeweight(obj):
"""
utility function that returns a
node class and it's weight
can be used for statistics
to get some stats when NO Advanced Nodes are available
"""
k = obj.__class__.__name__
if k in ('Text',):
return k, len(obj.caption)
elif k == 'ImageLink' and obj.isInline():
return 'InlineImageLink', 1
return k, 1 | 1ab88f73621c8396fca08551dd14c9a757d019ad | 3,263 |
def CMYtoRGB(C, M, Y):
""" convert CMY to RGB color
:param C: C value (0;1)
:param M: M value (0;1)
:param Y: Y value (0;1)
:return: RGB tuple (0;255) """
RGB = [(1.0 - i) * 255.0 for i in (C, M, Y)]
return tuple(RGB) | cfc2c7b91dd7f1faf93351e28ffdd9906613471a | 3,264 |
from typing import Any
import json
def json_safe(arg: Any):
"""
Checks whether arg can be json serialized and if so just returns arg as is
otherwise returns none
"""
try:
json.dumps(arg)
return arg
except:
return None | 97ac87464fb4b31b4fcfc7896252d23a10e57b72 | 3,265 |
import math
def h(q):
"""Binary entropy func"""
if q in {0, 1}:
return 0
return (q * math.log(1 / q, 2)) + ((1 - q) * math.log(1 / (1 - q), 2)) | ad3d02d6e7ddf622c16ec8df54752ac5c77f8972 | 3,266 |
from typing import IO
def write_file(filename: str, content: str, mode: str = "w") -> IO:
"""Save content to a file, overwriting it by default."""
with open(filename, mode) as file:
file.write(content)
return file | 5d6b7ac1f9097d00ae2b67e3d34f1135c4e90946 | 3,267 |
def get_list(_list, persistent_attributes):
"""
Check if the user supplied a list and if its a custom list, also check for for any saved lists
:param _list: User supplied list
:param persistent_attributes: The persistent attribs from the app
:return: The list name , If list is custom or not
"""
if _list is not None and (_list.lower() != 'watchlist' and _list.lower() != 'watch list'):
return _list, True
else:
# if default isnt set use watchlist
if "list" in persistent_attributes:
if persistent_attributes["list"] != 'watchlist' and persistent_attributes["list"] != 'watch list':
_list = persistent_attributes["list"]
_usecustomlist = True
else:
_list = 'watchlist'
_usecustomlist = False
else:
_list = 'watchlist'
_usecustomlist = False
return _list, _usecustomlist | 497fa8427660bafa3cc3023abf0132973693dc6e | 3,268 |
import socket
import re
def inode_for_pid_sock(pid, addr, port):
"""
Given a pid that is inside a network namespace, and the address/port of a LISTEN socket,
find the inode of the socket regardless of which pid in the ns it's attached to.
"""
expected_laddr = '%02X%02X%02X%02X:%04X' % (addr[3], addr[2], addr[1], addr[0], socket.htons(port))
for line in open('/proc/{}/net/tcp'.format(pid), 'r').readlines():
parts = re.split(r'\s+', line.strip())
local_addr = parts[1]
remote_addr = parts[2]
if remote_addr != '00000000:0000': continue # not a listen socket
if local_addr == expected_laddr:
return int(parts[9]) | 4d47d9de118caa87854b96bf759a75520b8409cb | 3,269 |
def nicer(string):
"""
>>> nicer("qjhvhtzxzqqjkmpb")
True
>>> nicer("xxyxx")
True
>>> nicer("uurcxstgmygtbstg")
False
>>> nicer("ieodomkazucvgmuy")
False
"""
pair = False
for i in range(0, len(string) - 3):
for j in range(i + 2, len(string) - 1):
if string[i:i + 2] == string[j:j + 2]:
pair = True
break
if not pair:
return False
for i in range(0, len(string) - 2):
if string[i] == string[i + 2]:
return True
return False | 7c543bbd39730046b1ab3892727cca3a9e027662 | 3,270 |
from typing import Union
def multiple_choice(value: Union[list, str]):
""" Handle a single string or list of strings """
if isinstance(value, list):
# account for this odd [None] value for empty multi-select fields
if value == [None]:
return None
# we use string formatting to handle the possibility that the list contains ints
return ", ".join([f"{val}" for val in value])
return value | aae54f84bc1ccc29ad9ad7ae205e130f66601131 | 3,271 |
def CleanFloat(number, locale = 'en'):
"""\
Return number without decimal points if .0, otherwise with .x)
"""
try:
if number % 1 == 0:
return str(int(number))
else:
return str(float(number))
except:
return number | 03ccc3bfe407becf047515b618621058acff37e7 | 3,273 |
def getGlobals():
"""
:return: (dict)
"""
return globals() | 0fa230d341ba5435b33c9e6a9d9f793f99a74238 | 3,274 |
def arith_relop(a, t, b):
"""
arith_relop(a, t, b)
This is (arguably) a hack.
Represents each function as an integer 0..5.
"""
return [(t == 0).implies(a < b),
(t == 1).implies(a <= b),
(t == 2).implies(a == b),
(t == 3).implies(a >= b),
(t == 4).implies(a > b),
(t == 5).implies(a != b)
] | 8b06d545e8d651803683b36facafb647f38fb2ff | 3,276 |
import collections
def get_duplicates(lst):
"""Return a list of the duplicate items in the input list."""
return [item for item, count in collections.Counter(lst).items() if count > 1] | 8f10226c904f95efbee447b4da5dc5764b18f6d2 | 3,277 |
import math
def regular_poly_circ_rad_to_side_length(n_sides, rad):
"""Find side length that gives regular polygon with `n_sides` sides an
equivalent area to a circle with radius `rad`."""
p_n = math.pi / n_sides
return 2 * rad * math.sqrt(p_n * math.tan(p_n)) | 939ff5de399d7f0a31750aa03562791ee83ee744 | 3,279 |
def dbl_colour(days):
"""
Return a colour corresponding to the number of days to double
:param days: int
:return: str
"""
if days >= 28:
return "orange"
elif 0 < days < 28:
return "red"
elif days < -28:
return "green"
else:
return "yellow" | 46af7d57487f17b937ad5b7332879878cbf84220 | 3,280 |
def read_requirements_file(path):
""" reads requirements.txt file """
with open(path) as f:
requires = []
for line in f.readlines():
if not line:
continue
requires.append(line.strip())
return requires | ab224bd3adac7adef76a2974a9244042f9aedf84 | 3,281 |
import threading
def thread_it(obj, timeout = 10):
""" General function to handle threading for the physical components of the system. """
thread = threading.Thread(target = obj.run())
thread.start()
# Run the 'run' function in the obj
obj.ready.wait(timeout = timeout)
# Clean up
thread.join()
obj.ready.clear()
return None | 02ed60a560ffa65f0364aa7414b1fda0d3e62ac5 | 3,282 |
def obj_setclass(this, klass):
"""
set Class for `this`!!
"""
return this.setclass(klass) | 4447df2f3055f21c9066a254290cdd037e812b64 | 3,283 |
def trimAlphaNum(value):
"""
Trims alpha numeric characters from start and ending of a given value
>>> trimAlphaNum(u'AND 1>(2+3)-- foobar')
u' 1>(2+3)-- '
"""
while value and value[-1].isalnum():
value = value[:-1]
while value and value[0].isalnum():
value = value[1:]
return value | e9d44ea5dbe0948b9db0c71a5ffcdd5c80e95746 | 3,285 |
def _median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0
"""
data = sorted(data)
n = len(data)
if n == 0:
raise ValueError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
i = n // 2
return (data[i - 1] + data[i]) / 2 | f05a6b067f95fc9e3fc9350b163b3e89c0792814 | 3,288 |
def generate_styles():
""" Create custom style rules """
# Set navbar so it's always at the top
css_string = "#navbar-top{background-color: white; z-index: 100;}"
# Set glossdef tip
css_string += "a.tip{text-decoration:none; font-weight:bold; cursor:pointer; color:#2196F3;}"
css_string += "a.tip:hover{position: relative;border-bottom: 1px dashed #2196F3;}"
# Set glossdef span
css_string += "a.tip span{display: none;background-color: white;font-weight: normal;border:1px solid gray;width: 250px;}"
css_string += "a.tip:hover span{display: block;position: absolute;z-index: 100;padding: 5px 15px;}"
return css_string | 44b36321dedba352c6aa30a352c7cd65cca1f79a | 3,289 |
def kilometers_to_miles(dist_km):
"""Converts km distance to miles
PARAMETERS
----------
dist_km : float
Scalar distance in kilometers
RETURNS
-------
dist_mi : float
Scalar distance in kilometers
"""
return dist_km / 1.609344 | 61707d483961e92dcd290c7b0cd8ba8f650c7b5b | 3,290 |
import requests
import time
def SolveCaptcha(api_key, site_key, url):
"""
Uses the 2Captcha service to solve Captcha's for you.
Captcha's are held in iframes; to solve the captcha, you need a part of the url of the iframe. The iframe is usually
inside a div with id=gRecaptcha. The part of the url we need is the query parameter k, this is called the site_key:
www.google.com/recaptcha/api2/anchor?ar=1&k=6LcleDIUAAAAANqkex-vX88sMHw8FXuJQ3A4JKK9&co=aHR0cHM6Ly93d3cuZGljZS5jb206NDQz&hl=en&v=oqtdXEs9TE9ZUAIhXNz5JBt_&size=normal&cb=rpcg9w84syix
k=6LcleDIUAAAAANqkex-vX88sMHw8FXuJQ3A4JKK9
Here the site_key is 6LcleDIUAAAAANqkex-vX88sMHw8FXuJQ3A4JKK9
You also need to supply the url of the current page you're on.
This function will return a string with the response key from captcha validating the test. This needs to be inserted
into an input field with the id=g-recaptcha-response.
:param api_key: The 2Captcha API key.
:param site_key: The site_key extracted from the Captcha iframe url
:param url: url of the site you're on
:return: The response from captcha validating the test
"""
print("Solving Captcha...")
print("Sending Request...")
request_response = requests.get("https://2captcha.com/in.php?", params={
"googlekey": site_key,
"method": "userrecaptcha",
"pageurl": url,
"key": api_key,
"json": 1,
"invisible": 0,
})
request_response.raise_for_status()
print("Waiting for Response...")
time.sleep(30)
answer_response_json = {'status': 0, 'request': 'CAPCHA_NOT_READY'}
while answer_response_json['request'] == 'CAPCHA_NOT_READY':
answer_response = requests.get("https://2captcha.com/res.php", params={
"key": api_key,
"action": "get",
"id": request_response.json()['request'],
"json": 1
})
answer_response_json = answer_response.json()
print(answer_response_json)
time.sleep(5)
if answer_response_json['status'] == 1:
print("Solved!")
return answer_response_json['request']
elif answer_response_json['request'] == 'ERROR_CAPTCHA_UNSOLVABLE':
raise TimeoutError("ERROR_CAPTCHA_UNSOLVABLE")
else:
raise Exception(answer_response_json['request']) | e610a265d03be65bfd6321a266776a8102c227d0 | 3,295 |
def _cifar_meanstd_normalize(image):
"""Mean + stddev whitening for CIFAR-10 used in ResNets.
Args:
image: Numpy array or TF Tensor, with values in [0, 255]
Returns:
image: Numpy array or TF Tensor, shifted and scaled by mean/stdev on
CIFAR-10 dataset.
"""
# Channel-wise means and std devs calculated from the CIFAR-10 training set
cifar_means = [125.3, 123.0, 113.9]
cifar_devs = [63.0, 62.1, 66.7]
rescaled_means = [x / 255. for x in cifar_means]
rescaled_devs = [x / 255. for x in cifar_devs]
image = (image - rescaled_means) / rescaled_devs
return image | 286ab555d30fd779c093e3b8801821f8370e1ca8 | 3,296 |
def boolean(entry, option_key="True/False", **kwargs):
"""
Simplest check in computer logic, right? This will take user input to flick the switch on or off
Args:
entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1.
option_key (str): What kind of Boolean we are setting. What Option is this for?
Returns:
Boolean
"""
error = f"Must enter 0 (false) or 1 (true) for {option_key}. Also accepts True, False, On, Off, Yes, No, Enabled, and Disabled"
if not isinstance(entry, str):
raise ValueError(error)
entry = entry.upper()
if entry in ("1", "TRUE", "ON", "ENABLED", "ENABLE", "YES"):
return True
if entry in ("0", "FALSE", "OFF", "DISABLED", "DISABLE", "NO"):
return False
raise ValueError(error) | d62b36d08651d02719b5866b7798c36efd2a018f | 3,297 |
def case_insensitive_equals(name1: str, name2: str) -> bool:
"""
Convenience method to check whether two strings match, irrespective of their case and any surrounding whitespace.
"""
return name1.strip().lower() == name2.strip().lower() | 28b7e5bfb5e69cf425e1e8983895f1ad42b59342 | 3,298 |
def ensure_listable(obj):
"""Ensures obj is a list-like container type"""
return obj if isinstance(obj, (list, tuple, set)) else [obj] | bdc5dbe7e06c1cc13afde28762043ac3fb65e5ac | 3,299 |
def merge_dicts(*dicts: dict) -> dict:
"""Merge dictionaries into first one."""
merged_dict = dicts[0].copy()
for dict_to_merge in dicts[1:]:
for key, value in dict_to_merge.items():
if key not in merged_dict or value == merged_dict[key]:
merged_dict[key] = value
else:
raise ValueError(
f"Test {key} already has a mark we don't want to overwrite: \n"
f"- existing: {merged_dict[key]} "
f"- new value: {value}"
)
merged_dict.update(dict_to_merge)
return merged_dict | b32a9f4bed149144a3f75b43ed45c8de4351f3d1 | 3,300 |
import calendar
def convert_ts(tt):
"""
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
>>> tt = time.strptime("23.10.2012", "%d.%m.%Y")
>>> convert_ts(tt)
1350950400
tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=0)
>>> tt = time.strptime("1.1.1513", "%d.%m.%Y")
>>> convert_ts(tt)
0
>>> tt = 12
>>> convert_ts(tt)
"""
try:
ts = calendar.timegm(tt)
"""
As from the github issue https://github.com/prashanthellina/rsslurp/issues/680,
there are some cases where we might get timestamp in negative values, so consider
0 if the converted timestamp is negative value.
"""
if ts < 0:
ts = 0
except TypeError:
ts = None
return ts | a3c2f5ae3d556290b6124d60fd4f84c1c2685195 | 3,301 |
def cmd(f):
"""Decorator to declare class method as a command"""
f.__command__ = True
return f | 3bdc82f0c83b0a4c0a0dd6a9629e7e2af489f0ae | 3,303 |
def small_prior():
"""Give string format of small uniform distribution prior"""
return "uniform(0, 10)" | fb636b564b238e22262b906a8e0626a5dff305d1 | 3,304 |
def skip_device(name):
""" Decorator to mark a test to only run on certain devices
Takes single device name or list of names as argument
"""
def decorator(function):
name_list = name if type(name) == list else [name]
function.__dict__['skip_device'] = name_list
return function
return decorator | 1bacdce5396ada5e2ba7a8ca70a8dfb273016323 | 3,305 |
from typing import Iterable
from typing import Any
from typing import Tuple
def tuple_from_iterable(val: Iterable[Any]) -> Tuple[Any, ...]:
"""Builds a tuple from an iterable.
Workaround for https://github.com/python-attrs/attrs/issues/519
"""
return tuple(val) | 7880b1395f14aa690f967b9548456105b544d337 | 3,308 |
def sensitivity_metric(event_id_1, event_id_2):
"""Determine similarity between two epochs, given their event ids."""
if event_id_1 == 1 and event_id_2 == 1:
return 0 # Completely similar
if event_id_1 == 2 and event_id_2 == 2:
return 0.5 # Somewhat similar
elif event_id_1 == 1 and event_id_2 == 2:
return 0.5 # Somewhat similar
elif event_id_1 == 2 and event_id_1 == 1:
return 0.5 # Somewhat similar
else:
return 1 | b04c5fa27ef655dd3f371c3ce6ef0410c55dd05b | 3,309 |
def duracion_promedio_peliculas(p1: dict, p2: dict, p3: dict, p4: dict, p5: dict) -> str:
"""Calcula la duracion promedio de las peliculas que entran por parametro.
Esto es, la duración total de todas las peliculas dividida sobre el numero de peliculas.
Retorna la duracion promedio en una cadena de formato 'HH:MM' ignorando los posibles decimales.
Parametros:
p1 (dict): Diccionario que contiene la informacion de la pelicula 1.
p2 (dict): Diccionario que contiene la informacion de la pelicula 2.
p3 (dict): Diccionario que contiene la informacion de la pelicula 3.
p4 (dict): Diccionario que contiene la informacion de la pelicula 4.
p5 (dict): Diccionario que contiene la informacion de la pelicula 5.
Retorna:
str: la duracion promedio de las peliculas en formato 'HH:MM'.
"""
# Se extraen las duraciones de las películas.
duracion1 = p1["duracion"]
duracion2 = p2["duracion"]
duracion3 = p3["duracion"]
duracion4 = p4["duracion"]
duracion5 = p5["duracion"]
# Promedio de duraciones de las películas.
promedio = (duracion1 + duracion2 + duracion3 + duracion4 + duracion5) / 5
# Conversión a formato 'HH:MM'.
horas = promedio // 60
minutos = promedio % 60
if horas < 10:
horas = '0' + str(int(horas))
else:
horas = str(int(horas))
if minutos < 10:
minutos = '0' + str(int(minutos))
else:
minutos = str(int(minutos))
return horas + ":" + minutos | a8cfcc96a43480ee6830cc212343a33148036c5d | 3,310 |
def _to_test_data(text):
"""
Lines should be of this format: <word> <normal_form> <tag>.
Lines that starts with "#" and blank lines are skipped.
"""
return [l.split(None, 2) for l in text.splitlines()
if l.strip() and not l.startswith("#")] | 8f0bae9f81d2d14b5654622f1493b23abd88424d | 3,311 |
def align2local(seq):
"""
Returns list such that
'ATG---CTG-CG' ==> [0,1,2,2,2,3,4,5,5,6,7]
Used to go from align -> local space
"""
i = -1
lookup = []
for c in seq:
if c != "-":
i += 1
lookup.append(i)
return lookup | aa914a60d5db7801a3cf1f40e713e95c98cd647e | 3,313 |
import os
def get_system_path():
""" Get the system path as a list of files
Returns:
List of names in the system path
"""
path = os.getenv('PATH')
if path:
return path.split(os.pathsep)
return [] | 766931b403444c584edf71d053f5b3f5de6bf265 | 3,315 |
def parsec_params_list_to_dict(var):
"""
convert parsec parameter array to dictionary
:param var:
:return:
"""
parsec_params = dict()
parsec_params["rle"] = var[0]
parsec_params["x_pre"] = var[1]
parsec_params["y_pre"] = var[2]
parsec_params["d2ydx2_pre"] = var[3]
parsec_params["th_pre"] = var[4]
parsec_params["x_suc"] = var[5]
parsec_params["y_suc"] = var[6]
parsec_params["d2ydx2_suc"] = var[7]
parsec_params["th_suc"] = var[8]
return parsec_params | 4ea4b4d2c0cbcb8fb49619e103b09f354c80de6a | 3,316 |
def parse_msiinfo_suminfo_output(output_string):
"""
Return a dictionary containing information from the output of `msiinfo suminfo`
"""
# Split lines by newline and place lines into a list
output_list = output_string.splitlines()
results = {}
# Partition lines by the leftmost ":", use the string to the left of ":" as
# the key and use the string to the right of ":" as the value
for output in output_list:
key, _, value = output.partition(':')
if key:
results[key] = value.strip()
return results | 6883e8fba9a37b9f877bdf879ebd14d1120eb88a | 3,317 |
import time
import json
async def ping(ws):
"""Send a ping request on an established websocket connection.
:param ws: an established websocket connection
:return: the ping response
"""
ping_request = {
'emit': "ping",
'payload': {
'timestamp': int(time.time())
}
}
await ws.send(json.dumps(ping_request))
return json.loads(await ws.recv()) | 587d2a72cbc5f50f0ffb0bda63668a0ddaf4c9c3 | 3,319 |
def target(x, seed, instance):
"""A target function for dummy testing of TA
perform x^2 for easy result calculations in checks.
"""
# Return x[i] (with brackets) so we pass the value, not the
# np array element
return x[0] ** 2, {'key': seed, 'instance': instance} | 131560778f51ebd250a3077833859f7e5addeb6e | 3,321 |
def prop_GAC(csp, newVar=None):
"""
Do GAC propagation. If newVar is None we do initial GAC enforce
processing all constraints. Otherwise we do GAC enforce with
constraints containing newVar on GAC Queue
"""
constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons()
pruned = []
# NOTE: although <constraints> is a list, the order is unimportant and acts like a set.
# See page 209 of RN textbook
while constraints != []:
constraint = constraints.pop(0) # grab the first constraint
for var in constraint.get_unasgn_vars(): # get_scope()?
for val in var.cur_domain():
if not constraint.has_support(var, val):
# Check if we have already pruned (var, val)
if (var, val) not in pruned:
var.prune_value(val)
pruned.append((var, val))
# We have modified var's domain, so add back all constraints
# that have var in it's scope
for c in csp.get_cons_with_var(var):
if c not in constraints:
constraints.append(c)
# Check if var's domain is empty
if var.cur_domain_size() == 0:
return False, pruned
return True, pruned | a1c576cfd9920a51eb9b9884bd49b4e8f4194d02 | 3,322 |
def submit_only_kwargs(kwargs):
"""Strip out kwargs that are not used in submit"""
kwargs = kwargs.copy()
for key in ['patience', 'min_freq', 'max_freq', 'validation',
"max_epochs", "epoch_boost", "train_size", "valid_size"]:
_ = kwargs.pop(key, None)
return kwargs | e93a4b8921c5b80bb487caa6057c1ff7c1701305 | 3,323 |
import os
def convert_rscape_svg_to_one_line(rscape_svg, destination):
"""
Convert R-scape SVG into SVG with 1 line per element.
"""
output = os.path.join(destination, 'rscape-one-line.svg')
cmd = (r"perl -0777 -pe 's/\n +fill/ fill/g' {rscape_svg} | "
r"perl -0777 -pe 's/\n d=/ d=/g' | "
r"perl -0777 -pe 's/\n +<tspan/ <tspan/g' | "
r"perl -0777 -pe 's/\n<\/text>/<\/text>/g' "
r"> {output}").format(rscape_svg=rscape_svg, output=output)
os.system(cmd)
return output | 7f561dcd1b9c6e540bb96fab363781dad73db566 | 3,324 |
def bags_with_gold( parents_of, _ ):
"""
Starting from leaf = 'gold', find recursively its parents upto the root and add them to a set
Number of bags that could contain gold = length of the set
"""
contains_gold = set()
def find_roots( bag ):
for outer_bag in parents_of[ bag ]:
contains_gold.add( outer_bag )
find_roots( outer_bag )
find_roots('shiny gold')
return len(contains_gold) | 3fd2b1c260d41867a5787a14f0c50a9b5d1a2f08 | 3,325 |
def get_netcdf_filename(batch_idx: int) -> str:
"""Generate full filename, excluding path."""
assert 0 <= batch_idx < 1e6
return f"{batch_idx:06d}.nc" | 5d916c4969eb96653ea9f0a21ab8bec93ebcfafa | 3,326 |
def close(x, y, rtol, atol):
"""Returns True if x and y are sufficiently close.
Parameters
----------
rtol
The relative tolerance.
atol
The absolute tolerance.
"""
# assumes finite weights
return abs(x-y) <= atol + rtol * abs(y) | bd2597c0c94f2edf686d0dc9772288312cb36d83 | 3,328 |
def min_spacing(mylist):
"""
Find the minimum spacing in the list.
Args:
mylist (list): A list of integer/float.
Returns:
int/float: Minimum spacing within the list.
"""
# Set the maximum of the minimum spacing.
min_space = max(mylist) - min(mylist)
# Iteratively find a smaller spacing.
for item in mylist:
spaces = [abs(item - item2) for item2 in mylist if item != item2]
min_space = min(min_space, min(spaces))
# Return the answer.
return min_space | b8ce0a46bacb7015c9e59b6573bc2fec0252505d | 3,330 |
def has_even_parity(message: int) -> bool:
""" Return true if message has even parity."""
parity_is_even: bool = True
while message:
parity_is_even = not parity_is_even
message = message & (message - 1)
return parity_is_even | 8982302840318f223e9c1ab08c407d585a725f97 | 3,331 |
def mock_mkdir(monkeypatch):
"""Mock the mkdir function."""
def mocked_mkdir(path, mode=0o755):
return True
monkeypatch.setattr("charms.layer.git_deploy.os.mkdir", mocked_mkdir) | e4e78ece1b8e60719fe11eb6808f0f2b99a933c3 | 3,332 |
import zipfile
import os
def zip_dir_recursively(base_dir, zip_file):
"""Zip compresses a base_dir recursively."""
zip_file = zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED)
root_len = len(os.path.abspath(base_dir))
for root, _, files in os.walk(base_dir):
archive_root = os.path.abspath(root)[root_len:]
for f in files:
fullpath = os.path.join(root, f)
archive_name = os.path.join(archive_root, f)
zip_file.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)
zip_file.close()
return zip_file | 79dc58f508b2f1e78b2cc32208471f75c6a3b15c | 3,333 |
def reautorank(reaumur):
""" This function converts Reaumur to rankine, with Reaumur as parameter."""
rankine = (reaumur * 2.25) + 491.67
return rankine | aec2299999e9798530272939125cb42476f095c3 | 3,335 |
import re
def is_sedol(value):
"""Checks whether a string is a valid SEDOL identifier.
Regex from here: https://en.wikipedia.org/wiki/SEDOL
:param value: A string to evaluate.
:returns: True if string is in the form of a valid SEDOL identifier."""
return re.match(r'^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}\d$', value) | 207ff94a4df99e7a546440cef1242f9a48435118 | 3,337 |
def get_img_size(src_size, dest_size):
"""
Возвращает размеры изображения в пропорции с оригиналом исходя из того,
как направлено изображение (вертикально или горизонтально)
:param src_size: размер оригинала
:type src_size: list / tuple
:param dest_size: конечные размеры
:type dest_size: list / tuple
:rtype: tuple
"""
width, height = dest_size
src_width, src_height = src_size
if height >= width:
return (int(float(width) / height * src_height), src_height)
return (src_width, int(float(height) / width * src_width)) | 133dab529cd528373a1c7c6456a34cf8fd22dac9 | 3,339 |
def _get_split_idx(N, blocksize, pad=0):
"""
Returns a list of indexes dividing an array into blocks of size blocksize
with optional padding. Padding takes into account that the resultant block
must fit within the original array.
Parameters
----------
N : Nonnegative integer
Total array length
blocksize : Nonnegative integer
Size of each block
pad : Nonnegative integer
Pad to add on either side of each index
Returns
-------
split_idx : List of 2-tuples
Indices to create splits
pads_used : List of 2-tuples
Pads that were actually used on either side
Examples
--------
>>> split_idx, pads_used = _get_split_idx(5, 2)
>>> print split_idx
[(0, 2), (2, 4), (4, 5)]
>>> print pads_used
[(0, 0), (0, 0), (0, 0)]
>>> _get_split_idx(5, 2, pad=1)
>>> print split_idx
[(0, 3), (1, 5), (3, 5)]
>>> print pads_used
[(0, 1), (1, 1), (1, 0)]
"""
num_fullsplits = N // blocksize
remainder = N % blocksize
split_idx = []
pads_used = []
for i in range(num_fullsplits):
start = max(0, i * blocksize - pad)
end = min(N, (i + 1) * blocksize + pad)
split_idx.append((start, end))
leftpad = i * blocksize - start
rightpad = end - (i + 1) * blocksize
pads_used.append((leftpad, rightpad))
# Append the last split if there is a remainder
if remainder:
start = max(0, num_fullsplits * blocksize - pad)
split_idx.append((start, N))
leftpad = num_fullsplits * blocksize - start
pads_used.append((leftpad, 0))
return split_idx, pads_used | 21935190de4c42fa5d7854f6608387dd2f004fbc | 3,340 |
import pkg_resources
def _get_highest_tag(tags):
"""Find the highest tag from a list.
Pass in a list of tag strings and this will return the highest
(latest) as sorted by the pkg_resources version parser.
"""
return max(tags, key=pkg_resources.parse_version) | 8d2580f6f6fbb54108ee14d6d4834d376a65c501 | 3,342 |
import warnings
def disable_warnings_temporarily(func):
"""Helper to disable warnings for specific functions (used mainly during testing of old functions)."""
def inner(*args, **kwargs):
warnings.filterwarnings("ignore")
func(*args, **kwargs)
warnings.filterwarnings("default")
return inner | 5e19b8f51ca092709a1e1a5d6ff0b2543a41e5e1 | 3,343 |
def norm(x):
"""Normalize 1D tensor to unit norm"""
mu = x.mean()
std = x.std()
y = (x - mu)/std
return y | ea8546da2ea478edb0727614323bba69f6af288d | 3,344 |
import re
def formatKwargsKey(key):
"""
'fooBar_baz' -> 'foo-bar-baz'
"""
key = re.sub(r'_', '-', key)
return key | 24c79b37fdd1cd6d73ab41b0d2234b1ed2ffb448 | 3,345 |
import re
def _remove_invalid_characters(file_name):
"""Removes invalid characters from the given file name."""
return re.sub(r'[/\x00-\x1f]', '', file_name) | 49a9f668e8142855ca4411921c0180977afe0370 | 3,346 |
import os
def write_curies(filepaths: dict, ontoid: str, prefix_map: dict, pref_prefix_map: dict) -> bool:
"""
Update node id field in an edgefile
and each corresponding subject/object
node in the corresponding edges
to have a CURIE, where the prefix is
the ontology ID and the class is
inferred from the IRI.
:param in_path: str, path to directory
:param ontoid: the Bioportal ID of the ontology
:return: True if complete, False otherwise
"""
success = False
nodepath = filepaths["nodelist"]
edgepath = filepaths["edgelist"]
outnodepath = nodepath + ".tmp"
outedgepath = edgepath + ".tmp"
update_these_nodes = {}
try:
with open(nodepath,'r') as innodefile, \
open(edgepath, 'r') as inedgefile:
with open(outnodepath,'w') as outnodefile, \
open(outedgepath, 'w') as outedgefile:
for line in innodefile:
updated_node = False
line_split = (line.rstrip()).split("\t")
node_iri = line_split[0]
if ontoid in prefix_map:
for prefix in prefix_map[ontoid]["prefixes"]:
if node_iri.startswith(prefix[0]):
split_iri = node_iri.rsplit(prefix[1],1)
if ontoid in pref_prefix_map:
ontoid = pref_prefix_map[ontoid]
if len(split_iri) == 2:
new_curie = f"{ontoid}:{split_iri[1]}"
else:
new_curie = f"{ontoid}:"
line_split[0] = new_curie
update_these_nodes[node_iri] = new_curie
updated_node = True
continue
# If we don't have a native prefix OR this is a foreign prefix
# then look at other ontologies
if ontoid not in prefix_map or not updated_node:
for prefix_set in prefix_map:
for prefix in prefix_map[prefix_set]["prefixes"]:
if node_iri.startswith(prefix[0]):
split_iri = node_iri.rsplit(prefix[1],1)
if prefix_set in pref_prefix_map:
prefix_set = pref_prefix_map[prefix_set]
if len(split_iri) == 2:
new_curie = f"{prefix_set}:{split_iri[1]}"
else:
new_curie = f"{prefix_set}:"
line_split[0] = new_curie
update_these_nodes[node_iri] = new_curie
continue
outnodefile.write("\t".join(line_split) + "\n")
for line in inedgefile:
line_split = (line.rstrip()).split("\t")
# Check for edges containing nodes to be updated
if line_split[1] in update_these_nodes:
line_split[1] = update_these_nodes[line_split[1]]
if line_split[3] in update_these_nodes:
line_split[3] = update_these_nodes[line_split[3]]
outedgefile.write("\t".join(line_split) + "\n")
os.replace(outnodepath,nodepath)
os.replace(outedgepath,edgepath)
success = True
except (IOError, KeyError) as e:
print(f"Failed to write CURIES for {nodepath} and/or {edgepath}: {e}")
success = False
return success | d574142a634b9a4998f8b887e4bc309661c5625e | 3,348 |
def items(dic):
"""Py 2/3 compatible way of getting the items of a dictionary."""
try:
return dic.iteritems()
except AttributeError:
return iter(dic.items()) | 2664567765efe172591fafb49a0efa36ab9fcca8 | 3,351 |
import random
import logging
import time
def request_retry_decorator(fn_to_call, exc_handler):
"""A generic decorator for retrying cloud API operations with consistent repeatable failure
patterns. This can be API rate limiting errors, connection timeouts, transient SSL errors, etc.
Args:
fn_to_call: the function to call and wrap around
exc_handler: a bool return function to check if the passed in exception is retriable
"""
def wrapper(*args, **kwargs):
MAX_ATTEMPTS = 10
SLEEP_SEC_MIN = 5
SLEEP_SEC_MAX = 15
for i in range(1, MAX_ATTEMPTS + 1):
try:
return fn_to_call(*args, **kwargs)
except Exception as e:
if i < MAX_ATTEMPTS and exc_handler(e):
sleep_duration_sec = \
SLEEP_SEC_MIN + random.random() * (SLEEP_SEC_MAX - SLEEP_SEC_MIN)
logging.warn(
"API call failed, waiting for {} seconds before re-trying (this was attempt"
" {} out of {}).".format(sleep_duration_sec, i, MAX_ATTEMPTS))
time.sleep(sleep_duration_sec)
continue
raise e
return wrapper | 0813cc19d9826275917c9eb701683a73bfe597f9 | 3,352 |
def as_string(raw_data):
"""Converts the given raw bytes to a string (removes NULL)"""
return bytearray(raw_data[:-1]) | 6610291bb5b71ffc0be18b4505c95653bdac4c55 | 3,353 |
import math
def generate_trapezoid_profile(max_v, time_to_max_v, dt, goal):
"""Creates a trapezoid profile with the given constraints.
Returns:
t_rec -- list of timestamps
x_rec -- list of positions at each timestep
v_rec -- list of velocities at each timestep
a_rec -- list of accelerations at each timestep
Keyword arguments:
max_v -- maximum velocity of profile
time_to_max_v -- time from rest to maximum velocity
dt -- timestep
goal -- final position when the profile is at rest
"""
t_rec = [0.0]
x_rec = [0.0]
v_rec = [0.0]
a_rec = [0.0]
a = max_v / time_to_max_v
time_at_max_v = goal / max_v - time_to_max_v
# If profile is short
if max_v * time_to_max_v > goal:
time_to_max_v = math.sqrt(goal / a)
time_from_max_v = time_to_max_v
time_total = 2.0 * time_to_max_v
profile_max_v = a * time_to_max_v
else:
time_from_max_v = time_to_max_v + time_at_max_v
time_total = time_from_max_v + time_to_max_v
profile_max_v = max_v
while t_rec[-1] < time_total:
t = t_rec[-1] + dt
t_rec.append(t)
if t < time_to_max_v:
# Accelerate up
a_rec.append(a)
v_rec.append(a * t)
elif t < time_from_max_v:
# Maintain max velocity
a_rec.append(0.0)
v_rec.append(profile_max_v)
elif t < time_total:
# Accelerate down
decel_time = t - time_from_max_v
a_rec.append(-a)
v_rec.append(profile_max_v - a * decel_time)
else:
a_rec.append(0.0)
v_rec.append(0.0)
x_rec.append(x_rec[-1] + v_rec[-1] * dt)
return t_rec, x_rec, v_rec, a_rec | 5851cfab06e20a9e79c3a321bad510d33639aaca | 3,354 |
import six
def str_to_bool(s):
"""Convert a string value to its corresponding boolean value."""
if isinstance(s, bool):
return s
elif not isinstance(s, six.string_types):
raise TypeError('argument must be a string')
true_values = ('true', 'on', '1')
false_values = ('false', 'off', '0')
if s.lower() in true_values:
return True
elif s.lower() in false_values:
return False
else:
raise ValueError('not a recognized boolean value: %s'.format(s)) | c228321872f253ce3e05c6af9284ec496dea8dcf | 3,355 |
import os
import re
import sys
def help(user_display_name, module_file_fullpath, module_name):
"""Generate help message for all actions can be used in the job"""
my_path = os.path.dirname(module_file_fullpath)
my_fname = os.path.basename(module_file_fullpath)
my_package = module_name.rsplit(u'.')[-2] # ex: sayhello
my_package_path = module_name.rsplit(u'.', 1)[-2] # ex: wechatbot.sayhello
help_msg = u'Actions in "%s":\n========\n' % (my_package)
for action_py in os.listdir(my_path):
action_name = u''
action_desc = u''
# Skip non-file
if not os.path.isfile(os.path.join(my_path, action_py)):
continue
# Skip self
if action_py == my_fname:
continue
# Folders start with "__"
if re.findall(u'^__.+', action_py):
continue
# Folders start with "."
if re.findall(u'^\..*', action_py):
continue
action_name = re.sub(u'\.py$', u'', action_py)
# Load action module
action_module_path = u'%s.%s' % (my_package_path, action_name)
action_from_path = my_package_path
# Import the "help" module
try:
action_module = __import__(
action_module_path, fromlist = [action_from_path])
except:
print(u"Cannot import %s." % (action_module_path), file = sys.stderr)
continue
# Get Job description
try:
action_desc = action_module._help_desc
except:
action_desc = u'[no description]'
print(u"No _help_desc for %s." % (action_module_path), file = sys.stderr)
# Arrange action_name and action_desc in help_msg
help_msg += u'> %s\n\t%s\n' % (action_name, action_desc)
# Tail messages
help_msg += u'========\nTo get detailed usage for\neach action, try:\n'
if user_display_name:
help_msg += u'@%s\u2005%s <action> -h' % (user_display_name, my_package)
else:
help_msg += u'%s <action> -h' % (my_package)
return help_msg | d76d0a2c07f7d60d1f9409281dc699d402fa1dd7 | 3,356 |
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
#looking horizontal winner
i = 0
while i < len(board):
j = 1
while j <len(board):
if board[i][j-1]==board[i][j] and board[i][j] == board[i][j+1]:
return board[i][j]
j += 2
i += 1
#looking vertical winner
i = 1
while i < len(board):
j = 0
while j <len(board):
if board[i-1][j]==board[i][j] and board[i][j] == board[i+1][j]:
return board[i][j]
j += 1
i += 2
#looking diagonal winner
if board[1][1] ==board[0][0] and board[1][1] == board[2][2]:
return board[1][1]
elif board[1][1] ==board[0][2] and board[1][1] == board[2][0]:
return board[1][1]
else:
return None | 31ab2cf04dfe269598efdd073762505643563a96 | 3,358 |
import socket
def _nslookup(ipv4):
"""Lookup the hostname of an IPv4 address.
Args:
ipv4: IPv4 address
Returns:
hostname: Name of host
"""
# Initialize key variables
hostname = None
# Return result
try:
ip_results = socket.gethostbyaddr(ipv4)
if len(ip_results) > 1:
hostname = ip_results[0]
except:
hostname = None
return (ipv4, hostname) | 7771887dbfcd60e73b8fce0ce4029fcd7058a7d1 | 3,359 |
def sessions(request):
"""
Cookies prepeocessor
"""
context = {}
return context | 562f4e9da57d3871ce780dc1a0661a34b3279ec5 | 3,360 |
import six
import base64
def Base64WSEncode(s):
"""
Return Base64 web safe encoding of s. Suppress padding characters (=).
Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type
unicode to string type first.
@param s: string to encode as Base64
@type s: string
@return: Base64 representation of s.
@rtype: string
NOTE: Taken from keyczar (Apache 2.0 license)
"""
if isinstance(s, six.text_type):
# Make sure input string is always converted to bytes (if not already)
s = s.encode("utf-8")
return base64.urlsafe_b64encode(s).decode("utf-8").replace("=", "") | cb28001bddec215b763936fde4652289cf6480c0 | 3,361 |
def onlyWikipediaURLS(urls):
"""Some example HTML page data is from wikipedia. This function converts
relative wikipedia links to full wikipedia URLs"""
wikiURLs = [url for url in urls if url.startswith('/wiki/')]
return ["https://en.wikipedia.org"+url for url in wikiURLs] | df9ecbb73dfc9a764e4129069a4317517830307a | 3,362 |
import fcntl
import os
def SetFdBlocking(fd, is_blocking):
"""Set a file descriptor blocking or nonblocking.
Please note that this may affect more than expected, for example it may
affect sys.stderr when called for sys.stdout.
Returns:
The old blocking value (True or False).
"""
if hasattr(fd, 'fileno'):
fd = fd.fileno()
old = fcntl.fcntl(fd, fcntl.F_GETFL)
if is_blocking:
value = old & ~os.O_NONBLOCK
else:
value = old | os.O_NONBLOCK
if old != value:
fcntl.fcntl(fd, fcntl.F_SETFL, value)
return bool(old & os.O_NONBLOCK) | 58d1496152cc752b59e8abc0ae3b42387a2f8926 | 3,363 |
def RetrieveResiduesNumbers(ResiduesInfo):
"""Retrieve residue numbers."""
# Setup residue IDs sorted by residue numbers...
ResNumMap = {}
for ResName in ResiduesInfo["ResNames"]:
for ResNum in ResiduesInfo["ResNum"][ResName]:
ResNumMap[ResNum] = ResName
ResNumsList = []
if len(ResNumMap):
ResNumsList = sorted(ResNumMap, key = int)
return ResNumsList | e9f522af368a8a058792b26f9cf53b1114e241ef | 3,366 |
import requests
import json
def search(keyword, limit=20):
"""
Search is the iTunes podcast directory for the given keywords.
Parameter:
keyword = A string containing the keyword to search.
limit: the maximum results to return,
The default is 20 results.
returns:
A JSON object.
"""
keyword = keyword.replace(' ', '+') # Replace white space with +.
# Set user agent.
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
headers = {'User-Agent': user_agent}
# ITunes podcast search URL.
itunesurl = 'https://itunes.apple.com/search?term=%s&country=us&limit=%d&entity=podcast' % (keyword, limit)
req = requests.get(itunesurl, headers=headers)
return json.loads(req.text) | 922cd7dfaea30e7254c459588d28c33673281dac | 3,367 |
import torch
def permute(x, in_shape='BCD', out_shape='BCD', **kw):
""" Permute the dimensions of a tensor.\n
- `x: Tensor`; The nd-tensor to be permuted.
- `in_shape: str`; The dimension shape of `x`. Can only have characters `'B'` or `'C'` or `'D'`,
which stand for Batch, Channel, or extra Dimensions. The default value `'BCD'` means
the input tensor `x` should be at lest 2-d with shape `(Batch, Channel, Dim0, Dim1, Dim2, ...)`,
where `Dim0, Dim1, Dim2 ...` stand for any number of extra dimensions.
- `out_shape: str or tuple or None`; The dimension shape of returned tensor. Default: `'BCD'`.
If a `str`, it is restricted to the same three characters `'B'`, `'C'` or `'D'` as the `in_shape`.
If a `tuple`, `in_shape` is ignored, and simply `x.permute(out_shape)` is returned.
If `None`, no permution will be performed.
- `return: Tensor`; Permuted nd-tensor. """
if (in_shape == out_shape) or (out_shape is None):
return x
if isinstance(out_shape, (list, tuple, torch.Size)):
return x.permute(*out_shape)
if isinstance(in_shape, str) and isinstance(out_shape, str) :
assert set(in_shape) == set(out_shape) <= {'B', 'C', 'D'}, 'In and out shapes must have save set of chars among B, C, and D.'
in_shape = in_shape.lower().replace('d', '...')
out_shape = out_shape.lower().replace('d', '...')
return torch.einsum(f'{in_shape}->{out_shape}', x)
return x | e74594df581c12891963e931999563374cd89c7d | 3,373 |
import re
def fullmatch(regex, string, flags=0):
"""Emulate python-3.4 re.fullmatch()."""
matched = re.match(regex, string, flags=flags)
if matched and matched.span()[1] == len(string):
return matched
return None | 72de0abe5c15dd17879b439562747c9093d517c5 | 3,374 |
def myFunction(objectIn):
"""What you are supposed to test."""
return objectIn.aMethodToMock() + 2 | 1907db338a05f2d798ccde63366d052404324e6f | 3,376 |
def get_training_set_count(disc):
"""Returns the total number of training sets of a discipline and all its
child elements.
:param disc: Discipline instance
:type disc: models.Discipline
:return: sum of training sets
:rtype: int
"""
training_set_counter = 0
for child in disc.get_descendants(include_self=True):
training_set_counter += child.training_sets.count()
return training_set_counter | 9b28a9e51e04b559f05f1cc0255a6c65ca4a0980 | 3,377 |
def _async_attr_mapper(attr_name, val):
"""The `async` attribute works slightly different than the other bool
attributes. It can be set explicitly to `false` with no surrounding quotes
according to the spec."""
if val in [False, 'False']:
return ' {}=false'.format(attr_name)
elif val:
return ' {}'.format(attr_name)
else:
return '' | 79e72067b244d705df9aa09a78db656f0847938c | 3,378 |
def print_pos_neg(num):
"""Print if positive or negative in polarity level
>>> print_pos_neg(0.8)
'positive'
>>> print_pos_neg(-0.5)
'negative'
"""
if num > 0:
return "positive"
elif num == 0:
return "neutral"
else:
return "negative" | 414aa98f54a2f01af24d591ae47ec4f394adf682 | 3,379 |