content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
|---|---|---|
def remove_redundant_characters(str, char1, char2):
"""
remove substrings before and after two characters
exmaple:
input: '12@[123]57'. '[',']'
output: '[123]'
"""
left_index = str.find(char1)
right_index = str.find(char2)
result = str[left_index: (right_index +1)]
return result
|
7e7dc284cd1ee4b8709bdc76b6ac864fb0dead8f
| 698,513
|
def double(number):
"""
This function returns twice the value of a given number
"""
return number * 2
|
65a4bb13ecb45b37f0349f4be2f834f2fd23f813
| 698,514
|
def fund_nav_df_fillna(fund_nav_df):
"""
为 fund_nav_df 补充nav数据并记录错误日志
:param fund_nav_df:
:return:
"""
fund_nav_df.dropna(subset=['nav'], inplace=True)
fund_nav_df['nav_acc'] = fund_nav_df[['nav', 'nav_acc']].fillna(method='ffill', axis=1)['nav_acc']
return fund_nav_df
|
b61fdf7986c782a831bb9c97c190e161210ff925
| 698,515
|
def eliminate_duplicates(duplicated_iterable):
"""
对于包含重复元素且基于数组(可以通过下标访问)的可迭代对象,清除其重复元素并保持原顺序不变
@日期: 过去的某个时刻
@作者: 徐嘉辉
Args:
duplicated_iterable: 包含重复元素且基于数组(可以通过下标访问)的可迭代对象
Returns:
返回一个保持了原来元素顺序且去重完毕的列表
"""
return sorted(set(duplicated_iterable), key=duplicated_iterable.index)
|
ca86f37050ed6b1830c952bd76f5ac57a76eb149
| 698,516
|
def unique_dict_in_list(array):
"""Returns the unique dictionaries in the input list,
preserving the original order. Replaces ``unique_elements_in_list``
because `dict` is not hashable.
Parameters
----------
array: `List` [`dict`]
List of dictionaries.
Returns
-------
unique_array : `List` [`dict`]
Unique dictionaries in `array`, preserving the order of first appearance.
"""
if not array:
return array
result = []
# Brute force.
# Avoids comparing json dumped ordered dictionary.
# The reason is that when dictionary contains list/dict unhashable items, set does not work.
for item in array:
if not any([item == element for element in result]):
result.append(item)
return result
|
ef18d64c4a896321d57f984c0ede3e0e897c59f5
| 698,517
|
def merge(prevArtifacts, nextArtifacts):
"""Merge artifact lists with nextArtifacts masking prevArtifacts"""
artifactList = list(nextArtifacts.copy())
artifactList.extend(prevArtifacts)
merged = []
excludedNames = set()
for artifact in artifactList:
if artifact.name not in excludedNames:
merged.append(artifact)
excludedNames.add(artifact.name)
return merged
|
089aaf140111b08a98e64118fde8f8a4fd413982
| 698,518
|
import os
def getpyfile(filename, split=os.path.splitext, exists=os.path.exists):
"""Return the .py file for a filename.
Resolves things like .pyo and .pyc files to the original .py. If *filename*
doesn't have a .py extension, it will be returned as-is.
:param filename: the path to a file.
:param split: a function to split extensions from basenames,
usually :func:`os.path.splitext`.
:param exists: a function to determine whether a file exists,
usually :func:`os.path.exists`.
"""
sourcefile = filename
base, ext = split(filename)
if ext[:3] == ".py":
sourcefile = base + ".py"
if not exists(sourcefile):
sourcefile = filename
return sourcefile
|
fe004fd9f9d635a4c6538df1cc7fd48517e3d975
| 698,519
|
import argparse
def parse_arguments():
""" Must specify a directory path, a Clowder url and a service key"""
parser = argparse.ArgumentParser(description='Upload nested folders to clowder')
parser.add_argument('--path', required=True)
parser.add_argument('--host', required=True)
parser.add_argument('--key', required=True)
return parser.parse_args()
|
5f2cd0a16ca5d9566dee67f42e1d99e58d8197b8
| 698,521
|
def circularArrayLoop( nums):
"""
:type nums: List[int]
:rtype: bool
"""
def move(i):
res = (i+nums[i])%len(nums)
return res
slow = move(0)
fast = move(slow)
while slow != fast:
slow = move(slow)
fast = move(move(fast))
fast = move(slow)
if fast == slow: return False
if nums[slow]>0:
while fast != slow:
fast = move(fast)
if nums[fast]<0: return False
else:
while fast != slow:
fast = move(fast)
if nums[fast] > 0: return False
return True
|
bb25883c698abd0b7d9183799e9c4c866d342409
| 698,522
|
def _clean_str(value, strip_whitespace=True):
"""
Remove null values and whitespace, return a str
This fn is used in two places: in SACTrace.read, to sanitize strings for
SACTrace, and in sac_to_obspy_header, to sanitize strings for making a
Trace that the user may have manually added.
"""
null_term = value.find('\x00')
if null_term >= 0:
value = value[:null_term] + " " * len(value[null_term:])
if strip_whitespace:
value = value.strip()
return value
|
41b9f0a1388045b86d019464512a0253eb5d6523
| 698,523
|
import random
def createRandomGraph():
"""Creates a digraph with 7 randomly chosen integer nodes from 0 to 9 and
randomly chosen directed edges (between 10 and 20 edges)
"""
g = {}
n = random.sample([0,1,2,3,4,5,6,7,8,9], 7)
for i in n:
g[i] = []
edges = random.randint(10,20)
count = 0
while count < edges:
a = random.choice(n)
b = random.choice(n)
if b not in g[a] and a != b:
g[a].append(b)
count += 1
return g
|
e2ca213a594ad03c5df7a3231e7d246fe7fcb416
| 698,524
|
def ini_elec_levels(spc_dct_i, spc_info):
""" get initial elec levels
"""
if 'elec_levels' in spc_dct_i:
elec_levels = spc_dct_i['elec_levels']
else:
elec_levels = [[0., spc_info[2]]]
return elec_levels
|
95a55a90c95466b2288799e4e24b3250c3afdd84
| 698,525
|
def check_for_factor(base, factor):
"""
This function should test if the
factor is a factor of base.
Factors are numbers you can multiply
together to get another number.
Return true if it is a factor or
false if it is not.
:param base:
:param factor:
:return:
"""
return True if base % factor == 0 else False
|
6d20a7d2e2ec459e8307007adb332507d0078118
| 698,526
|
def has_access(user, users):
"""A list of users should look as follows: ['!deny', 'user1',
'user2'] This means that user1 and user2 have deny access. If we
have something longer such as ['!deny', 'user1', '!allow',
'user2'] then user2 has access but user1 does not have access. If
no keywords are found then it returns None if the user is in the
list. """
if user not in users:
return None
rusers = users[::-1]
try:
action = next(x[1] for x in enumerate(rusers) if x[1][0] == '!')
except StopIteration:
return None
if action == '!allow':
return True
if action == '!deny':
return False
return False
|
07d3f47cf3725002023d8c9e487e14280dabc2bf
| 698,528
|
import subprocess
def check_dfs():
"""
This function checks if the dfs is running
"""
process = subprocess.Popen("jps", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
results = str(stdout)
flag = 0
if results.find("NameNode") > -1:
flag += 1
if results.find("SecondaryNameNode") > -1:
flag += 1
if results.find("DataNode") > -1:
flag += 1
if flag == 3:
print("INFO: dfs is up and running!")
return "ok"
else:
print("WARN: dfs is not running correctly or not running at all. Run <jps> for more information")
return "error"
|
6f82750992a5b30322b8c1de12b94b44f7257efb
| 698,529
|
def by_cities(sdat):
"""
this function determines from how often people fly from every city
:return: int[from moscow; from st pet.]
"""
borm = sdat.groupby(["Город вылета"]).size()
cities = []
for i in borm:
cities.append(i)
return cities
|
d5e438ea7f9d298ff879df479f250342cc02eff1
| 698,530
|
def isVowel(letter):
"""
isVowel checks whether a given letter is a vowel. For purposes of this
function, treat y as always a vowel, w never as a vowel.
letter should be a string containing a single letter
return "error" if the value of the parameter is not a single letter string,
return True, if the letter is a vowel, otherwise False
"""
if (type(letter) != str): # letter must be a string
return "error"
if (len(letter) != 1): # letter must only be a single character
return "error"
# return True if letter is a vowel (capital or lowercase)
if (letter in ["a","e","i","o","u","y","A","E","I","O","U","Y"]):
return True
return False
|
5ba6917c80c4679a59580b8f3a05513d0904cd63
| 698,531
|
def fn_winkler(weight_jaro, pre_matches, pre_scale):
"""
Scale the standard Jaro metric by 'pre_scale' units per 'pre_matches'.
Note the warning in the docstring of jaro_winkler() regarding the scale.
"""
weight_jaro += pre_matches * pre_scale * (1.0 - weight_jaro)
assert weight_jaro <= 1.0
return weight_jaro
|
c938b932038e5344c19847555b70545d239cbb5a
| 698,532
|
def isCCW(ring):
"""
Determines if a LinearRing is oriented counter-clockwise or not
"""
area = 0.0
for i in range(0,len(ring)-1):
p1 = ring[i]
p2 = ring[i+1]
area += (p1[1] * p2[0]) - (p1[0] * p2[1])
if area > 0:
return False
else:
return True
|
ef7b3ad88a3a5926896ab1c627b65f2e4e4dc47f
| 698,533
|
def get_grant_key(grant_statement):
"""
Create the key from the grant statement.
The key will be used as the dictionnary key.
:param grant_statement: The grant statement
:return: The key
"""
splitted_statement = grant_statement.split()
grant_privilege = splitted_statement[1]
if "." in splitted_statement[3]:
grant_table = splitted_statement[3].split('.')[1]
else:
grant_table = splitted_statement[3]
return grant_privilege + "_" + grant_table
|
200b77d0988090628e013463bba5fe395dd76c00
| 698,534
|
def get_timediff(dataset,
start_time,
end_time):
"""
Usage: [arg1]:[Pandas DataFrame],[arg2]:[column-start_time],[arg3]:[column-end_time]
Returns: DataFrame with additional column [Duration in seconds]
"""
dataset['secs_diff_' + start_time + '_' + end_time] = (dataset[end_time] - dataset[start_time]).dt.total_seconds()
return dataset
|
8fff531201953cd637027c0b6ac76e9ae45dc380
| 698,535
|
def invert(d):
"""Dict of lists -> list of dicts."""
if d:
return [dict(zip(d, i)) for i in zip(*d.values())]
|
1ac60d7c294e159836be3f6c83817ad7de4f7125
| 698,536
|
def get_format_style(deck) -> str:
""" Возвращает соответствующий класс стиля формата колоды """
matching = {0: 'unknown',
1: 'wild',
2: 'standard',
3: 'classic'}
return matching[deck.deck_format.numerical_designation]
|
79fd7febf913deb684c5499768cdb11621952a6e
| 698,537
|
def custom_filter(image):
"""
Allows the user to modify the image by multiplying each of the RGB values of each pixel by their input number.
"""
red_constant = float(input ("Multiply the R value of each pixel by: "))
green_constant = float(input ("Multiply the G value of each pixel by: "))
blue_constant = float(input ("Multiply the B value of each pixel by: "))
for pixel in image:
pixel.red *= red_constant
pixel.green *= green_constant
pixel.blue *= blue_constant
return image
|
c1a23f13f7d5cdf49b7c9a4c1b9a84fa4cb56051
| 698,538
|
import json
def unpack_msrest_error(e):
"""Obtains full response text from an msrest error"""
op_err = None
try:
op_err = json.loads(e.response.text)
except (ValueError, TypeError):
op_err = e.response.text
if not op_err:
return str(e)
return op_err
|
f55b08443b0f97f967de837732159b82fd8b5a60
| 698,539
|
from datetime import datetime
def datetime_str_to_datetime(datetime_str):
"""
This converts the strings generated when matlab datetimes are written to a table to python datetime objects
"""
if len(datetime_str) == 24: # Check for milliseconds
return datetime.strptime(datetime_str, '%d-%b-%Y %H:%M:%S.%f')
else:
return datetime.strptime(datetime_str, '%d-%b-%Y %H:%M:%S')
|
84960880bccfb21bdb2dc1a15b0bd09ef358187c
| 698,540
|
def mangle(prefix, name):
"""Make a unique identifier from the prefix and the name. The name
is allowed to start with $."""
if name.startswith('$'):
return '%sinternal_%s' % (prefix, name[1:])
else:
return '%s_%s' % (prefix, name)
|
6d949e61a87c6667fdfb262376e476aea64bde4b
| 698,541
|
def de_normalize_minmax(x_scale, x, min_r, max_r):
""" Transforms a min-max normalized and
scaled vector back to its un-normalized
form.
"""
x_t = [((i - min_r)/(max_r - min_r)) for i in x_scale]
x_inv = [(i*(max(x) - min(x)) + min(x)) for i in x_t]
return x_inv
|
d1a2bd2740552eae2c4bc0b94f2093de7ed03b70
| 698,542
|
import torch
def update_ntk_inv(ntk, ntk_inv, keep_indices):
""" A little bit faster implementation. Uses the fact that ntk is a symmetric matrix. """
S = set(keep_indices)
remove_indices = [i for i in range(ntk.shape[0]) if i not in S]
A12 = ntk[keep_indices][:, remove_indices]
A22 = ntk[remove_indices][:, remove_indices]
F11_inv = ntk_inv[keep_indices][:, keep_indices]
C = torch.mm(F11_inv, A12)
mid_inv = torch.inverse(A22 + torch.mm(C.T, A12))
A11_inv = F11_inv - torch.mm(torch.mm(C, mid_inv), C.T)
return A11_inv
|
26b62e0c1bca79643930ee822f34cfdd74e977fd
| 698,543
|
import subprocess
import sys
def shell_cmd(cmd, alert_on_failure=True):
"""Execute shell command and return (ret-code, stdout, stderr)."""
print('SHELL > {}'.format(cmd))
proc = subprocess.Popen(cmd, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ret = proc.wait()
stdout = proc.stdout.read() if proc.stdout else None
stderr = proc.stderr.read() if proc.stderr else None
if alert_on_failure and stderr and ret != 0:
sys.stderr.write('{}\n'.format(stderr))
return (ret, stdout, stderr)
|
31299cd69991254ecbca2ecb314c55eb2d9b0544
| 698,544
|
def time_to_sec(time_str: str) -> int:
"""Convert time in string format to seconds.
Skipping seconds since sometimes the last column is truncated
for entries where >10 days.
"""
total_sec = 0
if '-' in time_str:
# parse out days
days, time_str = time_str.split('-')
total_sec += (int(days) * 24 * 60 * 60)
# parse out the hours and mins (skip seconds)
hours_min_raw = time_str.split(':')[:-1]
time_parts = [int(round(float(val))) for val in hours_min_raw]
total_sec += time_parts[-1] * 60 # minutes
if len(time_parts) > 1:
total_sec += time_parts[-2] * 60 * 60 # hours
return total_sec
|
e08667cc35a3d85dc30ea3eb63e5d91f2ba99252
| 698,545
|
def get_string_value(value_format, vo):
"""Return a string from a value or object dictionary based on the value format."""
if "value" in vo:
return vo["value"]
elif value_format == "label":
# Label or CURIE (when no label)
return vo.get("label") or vo["id"]
elif value_format == "curie":
# Always the CURIE
return vo["id"]
# IRI or CURIE (when no IRI, which shouldn't happen)
return vo.get("iri") or vo["id"]
|
0efaa0850a63076dd0334bc54f2c96e4f352d6ae
| 698,546
|
def create_msearch_payload(host, st, mx=1):
"""
Create an M-SEARCH packet using the given parameters.
Returns a bytes object containing a valid M-SEARCH request.
:param host: The address (IP + port) that the M-SEARCH will be sent to. This is usually a multicast address.
:type host: str
:param st: Search target. The type of services that should respond to the search.
:type st: str
:param mx: Maximum wait time, in seconds, for responses.
:type mx: int
:return: A bytes object containing the generated M-SEARCH payload.
"""
data = (
"M-SEARCH * HTTP/1.1\r\n"
"HOST:{}\r\n"
'MAN: "ssdp:discover"\r\n'
"ST:{}\r\n"
"MX:{}\r\n"
"\r\n"
).format(host, st, mx)
return data.encode("utf-8")
|
cb0da629716e992dd35a5b211f26cae3ad949dcb
| 698,547
|
from pathlib import Path
def valid_folder(path_):
"""
Returns True if path_.match any of the conditions. False otherwise.
conditions assigned:
- "_*"
"""
# ignores dunders, __pycache__
conditions = (
"_*",
)
p = Path(path_)
return not(any(p.match(condition) for condition in conditions))
|
a0ddff2667eea34d7b00e3aac8623e65140894f9
| 698,548
|
def _balance(target, weight):
"""Assume `cross_entropy(ignore_index=-100)`.
Args:
target (Tensor[H, W]): input tensor.
weight (Tensor[H, W]): probability of BG.
"""
negative_mask = target.eq(0)
limit = 3 + 3 * target.gt(0).sum().item()
if negative_mask.sum().item() > limit:
p = weight[negative_mask].sort()[0][limit]
target[negative_mask * weight.gt(p)] = -100
return target
|
fd59351331319d10b89f70ef816fb9f922e61046
| 698,549
|
import requests
from bs4 import BeautifulSoup
def get_google_image_link(word):
"""
Function returns a url for the movie image in google search resoults
Returns second image as first is a search_url
:param word: search word
:return: url
"""
url = 'https://www.google.com/search?q=' + word + '&client=opera&hs=cTQ&source=lnms&tbm=isch&sa=X&ved=0ahUKEwig3LOx4PzKAhWGFywKHZyZAAgQ_AUIBygB&biw=1920&bih=982'
page = requests.get(url).text
soup = BeautifulSoup(page, 'html.parser')
try:
link = soup.find_all('img')[1].get('src')
except:
link = ''
return link
|
54b7e4626d0825dee6baaecc6a41ddb14c384797
| 698,550
|
def get_values_from_line(line):
"""Get values of an observation as a list from string,
splitted by semicolons.
Note 1: Ignore ';' inside \"...\". E.g. consider \"xxx;yyy\" as one value.
Note 2: Null string '' for NA values.
"""
raw_list = line.strip().split(';')
i = 0
values = []
while i < len(raw_list):
if raw_list[i] == "" or raw_list[i][0] != '\"':
values.append(raw_list[i])
i = i + 1
else:
if raw_list[i][-1] == '\"':
values.append(raw_list[i][1:-1])
i = i + 1
else:
j = i + 1
entry = raw_list[i][1:]
while j < len(raw_list) and raw_list[j][-1] != '\"':
entry = entry + raw_list[j]
j = j + 1
if j == len(raw_list):
i = j
else:
entry = entry + raw_list[j][:-1]
values.append(entry)
i = j + 1
return values
|
585c6c9484f6ad145f7265613dc189351cc2d556
| 698,551
|
import os
def find_basic_file(dir, adventure_name):
"""
Try to figure out which basic file belongs to this adventure.
Args:
dir: The directory where the adventure's EDX data files live, e.g., "C:/EDX/C/EAMONDX/E001"
adventure_name: The name of the adventure, e.g., "The Beginner's Cave"
Returns:
The filename as a string (e.g., "BEGCAVES.BAS")
"""
for fname in os.listdir(dir):
full_filename = dir + "/" + fname
if os.path.isfile(full_filename) and fname.endswith(".BAS"):
with open(full_filename) as f:
file_header = f.read(2048)
if adventure_name in file_header:
return fname
|
26761043299826286fab4dacd6092287f674866b
| 698,552
|
import torch
def map2central(cell, coordinates, pbc):
"""Map atoms outside the unit cell into the cell using PBC.
Arguments:
cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three
vectors defining unit cell:
.. code-block:: python
tensor([[x1, y1, z1],
[x2, y2, z2],
[x3, y3, z3]])
coordinates (:class:`torch.Tensor`): Tensor of shape
``(molecules, atoms, 3)``.
pbc (:class:`torch.Tensor`): boolean vector of size 3 storing
if pbc is enabled for that direction.
Returns:
:class:`torch.Tensor`: coordinates of atoms mapped back to unit cell.
"""
# Step 1: convert coordinates from standard cartesian coordinate to unit
# cell coordinates
inv_cell = torch.inverse(cell)
coordinates_cell = torch.matmul(coordinates, inv_cell)
# Step 2: wrap cell coordinates into [0, 1)
coordinates_cell -= coordinates_cell.floor() * pbc
# Step 3: convert from cell coordinates back to standard cartesian
# coordinate
return torch.matmul(coordinates_cell, cell)
|
5ab75804efa182516ec4e99ec6707e65f205b842
| 698,553
|
def get_left_strip(chonk):
"""
Compute the left vertical strip of a 2D list.
"""
return [chonk[_i][0] for _i in range(len(chonk))]
|
dfc57a0776e5ab97a808a75170634fa6a072d9d3
| 698,554
|
def filter_waveforms(stream,f1,f2):
"""
Bandpass filter waveforms
INPUTS
stream - list of obspy streams, one for each station/channel combo, each 60 s long
f1 - lower bandpass limit in Hz
f2 - upper bandpass limit in Hz
OUTPUTS
stream - same list of streams, but filtered
"""
for st in stream:
st.filter('bandpass',freqmin=f1,freqmax=f2)
return stream
|
6a563a987e50d668a164c7020449dd2ce5cf28a8
| 698,555
|
def _shift_num_right_by(num: int, digits: int) -> int:
"""Shift a number to the right by discarding some digits
We actually use string conversion here since division can provide
wrong results due to precision errors for very big numbers. e.g.:
6150000000000000000000000000000000000000000000000 // 1e27
6.149999999999999e+21 <--- wrong
"""
return int(str(num)[:-digits])
|
ba459cb419ef19ac2884d8299d4f1a9213832fa3
| 698,556
|
import json
def js2str(js, sort_keys=True, indent=4):
"""Encode js to nicely formatted human readable string. (utf-8 encoding)
Usage::
>>> from weatherlab.lib.dataIO.js import js2str
>>> s = js2str({"a": 1, "b": 2})
>>> print(s)
{
"a": 1,
"b": 2
}
**中文文档**
将可Json化的Python对象转化成格式化的字符串。
"""
return json.dumps(js, sort_keys=sort_keys,
indent=indent, separators=(",", ": "))
|
17fac42012b5abae77a00083e183d851baaab5b3
| 698,557
|
def handle_extends(tail, line_index):
"""Handles an extends line in a snippet."""
if tail:
return 'extends', ([p.strip() for p in tail.split(',')],)
else:
return 'error', ("'extends' without file types", line_index)
|
3b20cc5719d123e36db954c5ffc4537df64f268a
| 698,560
|
import os
import codecs
def get_lines_of_cha_files(path):
"""
Gets the lines in the cha files in the given path
:param path: The path that is looked at, this includes the subfolders
:return: a list of cha files with the lines
"""
results = []
for file in os.listdir(path):
with codecs.open(os.path.join(path, file), "r", "utf-8") as f:
count = 0
for line in f.readlines():
if ("*" == line[0]):
count += 1
results.append((file[:-4], [i for i in range(count)]))
return results
|
6c9fdb90d5f59d5cdd4aa47d7c43b707839ce998
| 698,561
|
def entryID(entry):
"""Try to make an unique ID for entry."""
id = None
if entry.get('guidislink', None):
id = entry.get('id', None)
if id is None:
id = entry.get('link', None)
if id is None:
raise Exception
return id
|
f1ca161d60db7197e8b51f40585d74690a00c004
| 698,562
|
import torch
def repackage_hidden(h):
"""Wraps hidden states in new Tensors,
to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h)
|
b435d7537e4418d3877db55077285d35a24e46b3
| 698,563
|
def minus(evaluator, ast, state):
"""Evaluates "-expr"."""
return -evaluator.eval_ast(ast["expr"], state)
|
bf945c368e84d3badd7a90bfce74cb3c89b6890a
| 698,564
|
def angle_M(M_r: float, n: float, t_r: float, t: float) -> float:
"""
M = Mr + n * (t - tr)
:param M_r: mean anomaly at tr
:type M_r: float
:param n: mean movement
:type n: float
:param t_r: reference time
:type t_r: float
:param t: time
:type t: float
:return: mean anomaly at t
:rtype: float
"""
return M_r + n * (t - t_r)
|
c99e5dacffea44fa7fadfaebaf6ce734eea81e16
| 698,565
|
from typing import Union
from typing import Dict
import torch
def convert_double_to_float(data: Union[Dict, torch.Tensor]):
"""
Utility function to convert double tensors to float tensors in nested dictionary with Tensors
"""
if type(data) is torch.Tensor and data.dtype == torch.float64:
return data.float()
elif type(data) is dict:
for k, v in data.items():
data[k] = convert_double_to_float(v)
return data
else:
return data
|
737edbb9625b6cc1dbce425f7e8df8e06cb80410
| 698,566
|
import re
def is_transaction_expired_exception(e):
"""
Checks if exception occurred for an expired transaction
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception denote that a transaction has expired. False otherwise.
"""
is_invalid_session = e.response['Error']['Code'] == 'InvalidSessionException'
if "Message" in e.response["Error"]:
return is_invalid_session and re.search("Transaction .* has expired", e.response["Error"]["Message"])
return False
|
c836521a7137b61ad8443157824ca5da59de65e3
| 698,567
|
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Experimenting Trackers with SORT')
parser.add_argument('--NoDisplay', dest='display', help='Disables online display of tracker output (slow)',action='store_false')
parser.add_argument('--dlib', dest='use_dlibTracker', help='Use dlib correlation tracker instead of kalman tracker',action='store_true')
parser.add_argument('--save', dest='saver', help='Saves frames with tracking output, not used if --NoDisplay',action='store_true')
args = parser.parse_args()
return args
|
3ff5d05f2a800a5338c2ac386d0ae78610b285d3
| 698,568
|
def get_legal_moves_lshift(size, mask, player, blank, shift_size):
"""
左シフトで石が置ける場所を取得
"""
tmp = mask & (player << shift_size)
for _ in range(size-3):
tmp |= mask & (tmp << shift_size)
return blank & (tmp << shift_size)
|
42a259f21b2ae1c0c57007f939e5e7e935761b88
| 698,569
|
def parse_int(sin):
"""A version of int but fail-safe"""
return int(sin) if sin.isdigit() else -99
|
204cbcb01b6df1bbdd09af318fdfe90feb5fe68f
| 698,570
|
def check_read(read):
"""
a callback function for pysam.count function, returns true if the read should be included in the count
:param read: the read to check
:return: True of False whether the read should be included in the count
"""
return read.is_proper_pair
|
1bc80c9156bdeb0bc34b2724da8d0147a435b3dd
| 698,571
|
def createAggregatedTestCase(doc, parent_node, testclass_name):
"""
Create a node which represents a single aggregated testcase.
Aggregated testcase sums the result of all test cases that
belong to the speified classname. If one of these test cases
fails, the aggregated test case's status is set to failed.
"""
testcase = doc.createElement('testcase')
# This holds the complete test id.
testcase.setAttribute('classname', testclass_name)
# classname holds the whole test id already, so the 'name'
# attribute holds just a persistent label, common to all
# test cases. Let's call it aggregated, to indicate that
# the result represents multiple steps in lettuce scenario.
testcase.setAttribute('name', 'aggregated')
testcase.setAttribute('time', "0")
return testcase
|
a6cfaa405464a09e76d3e4840f99a3d5ff9a87b1
| 698,572
|
def makeToUnicodeCMap(fontname, subset):
"""Creates a ToUnicode CMap for a given subset. See Adobe
_PDF_Reference (ISBN 0-201-75839-3) for more information."""
cmap = [
"/CIDInit /ProcSet findresource begin",
"12 dict begin",
"begincmap",
"/CIDSystemInfo",
"<< /Registry (%s)" % fontname,
"/Ordering (%s)" % fontname,
"/Supplement 0",
">> def",
"/CMapName /%s def" % fontname,
"/CMapType 2 def",
"1 begincodespacerange",
"<00> <%02X>" % (len(subset) - 1),
"endcodespacerange",
"%d beginbfchar" % len(subset)
] + ["<%02X> <%04X>" % (i,v) for i,v in enumerate(subset)] + [
"endbfchar",
"endcmap",
"CMapName currentdict /CMap defineresource pop",
"end",
"end"
]
return '\n'.join(cmap)
|
dbcb57eddcaa63373da63a90cd937f6d9e4cb835
| 698,573
|
import pandas
def ReadData():
"""Reads data about cannabis transactions.
http://zmjones.com/static/data/mj-clean.csv
returns: DataFrame
"""
transactions = pandas.read_csv('mj-clean.csv', parse_dates=[5])
return transactions
|
2652635ae2ed765bc9465706866c017ea171383f
| 698,574
|
from typing import List
import subprocess
def run_command(cmd: List[str]) -> str:
"""Execute a command in the shell.
Args:
cmd: :obj:`List[str]`. The command with its arguments to execute.
Returns:
The standard output of the command.
Raises:
:obj:`OSError`: if the standard error stream is not empty.
"""
ps = subprocess.run(args=cmd, capture_output=True)
if ps.stderr:
raise OSError(f"Failed running {' '.join(cmd)} with error message: "
f"{ps.stderr.decode('utf-8')}.")
return ps.stdout.decode("utf-8")
|
5e4025b232c87e52608ea394c782bae0039d15d5
| 698,575
|
def create_dict(**kwargs):
"""Create a dict only with values that exists so we avoid send keys with
None values
"""
return {k: v for k, v in kwargs.items() if v}
|
0abd94a4ec3a84685635affbe038d9b513287f6e
| 698,576
|
def hospitalized_case(I, AGE_DATA):
""" Calculated hospitalization cases"""
AGE_DATA['Snapshot_hospitalized'] = round(AGE_DATA['Proportion_DE_2020'] *
I *
AGE_DATA['Hospitalization Rate'])
no_h = AGE_DATA['Snapshot_hospitalized'].sum()
return no_h
|
9876bd1e6420b0e12db3ef4300d25fb84931b759
| 698,577
|
def enable_cdc(client):
"""Utility method to enable Change Data Capture for Contact change events in an org.
Args:
client (:py:class:`simple_salesforce.Salesforce`): Salesforce client
Returns:
(:obj:`str`) Event channel Id
"""
payload = {
"FullName": "ChangeEvents_ContactChangeEvent",
"Metadata": {
"eventChannel": "ChangeEvents",
"selectedEntity": "ContactChangeEvent"
}
}
result = client.restful('tooling/sobjects/PlatformEventChannelMember', method='POST', json=payload)
assert True == result['success']
return result['id']
|
2c7bc57f33e83029caea542db9daeaa81f6661cc
| 698,579
|
def extract_first_appearance(string, type_, last_possible):
"""Extract the first appearance of the character in manga or anime
Note: the complete list of manga_chapters and anime_episodes seems
incorrect on Hokuto Renkitōza.
Parameters
----------
string : str
entire appearances string from the infobox on Hokuto Renkitōza
type_ : str
"manga", "anime"
last_possible : int
last manga chapter or last anime episode
Returns
-------
d : dict
"""
i_start = string.lower().find(type_)
if i_start > -1:
substring = string[i_start:]
i0 = substring.find("(") + 1
i1 = substring[i0:].find(")")
splits = substring[i0 : i0 + i1].split()
appearances = []
appearances_single = [int(s) for s in splits if s.isdigit()]
appearances.extend(appearances_single)
appearances_range = [s for s in splits if "-" in s]
for app_range in appearances_range:
app_start, app_stop = app_range.strip(" ").strip(",").split("-")
app_range_start = int(app_start)
try:
app_range_stop = int(app_stop)
except ValueError:
app_range_stop = last_possible
appearances_in_range = list(range(app_range_start, app_range_stop + 1))
appearances.extend(appearances_in_range)
appearances.sort()
first_appearance = appearances[0]
else:
first_appearance = None
return first_appearance
|
baee950b7f3f0cbba2f3dee2e136f7d63b737489
| 698,581
|
def get(key: str, dic, default=None):
"""Gets key even from not a dictionary."""
try:
return dict(dic).get(key, default)
except TypeError:
return default
|
5302868de0b6b4a94bded35654d6a9ad215d867e
| 698,582
|
import argparse
def get_arguments():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description="Code for domain adaptation (DA) training")
parser.add_argument('--cfg', type=str, default=None,
help='optional config file', )
parser.add_argument("--random-train", action="store_true",
help="not fixing random seed.")
parser.add_argument("--tensorboard", action="store_true",
help="visualize training loss with tensorboardX.")
parser.add_argument("--viz-every-iter", type=int, default=None,
help="visualize results.")
parser.add_argument("--exp-suffix", type=str, default=None,
help="optional experiment suffix")
return parser.parse_args()
|
c1d52553350100ae8a9722d95a88fd87b7af62af
| 698,583
|
import yaml
def load_config_from_yaml(filename='fsm.yaml'):
"""
Returns the current fsm configuration dictionary, loaded from file.
:return: a dict.
"""
yaml_file = open(filename, 'r')
yaml_dict = yaml.safe_load(yaml_file.read())
return yaml_dict
|
e1ff03a8fcc2a77288d8971cd76fd17e7a30f65a
| 698,584
|
import torch
def atanh(x, eps=1e-2):
"""
The inverse hyperbolic tangent function, missing in pytorch.
:param x: a tensor or a Variable
:param eps: used to enhance numeric stability
:return: :math:`\\tanh^{-1}{x}`, of the same type as ``x``
"""
x = x * (1 - eps)
return 0.5 * torch.log((1.0 + x) / (1.0 - x))
|
27b0e8de0eeceb44d739f686ca22d616bc8f75de
| 698,585
|
def index_names_from_symbol(symbol):
"""
Return the domain names of a GAMS symbol,
except ['*'] cases are replaced by the name of the symbol
and ['*',..,'*'] cases are replaced with ['index_0',..'index_n']
"""
index_names = list(symbol.domains_as_strings)
if index_names == ["*"]:
return [symbol.name]
if index_names.count("*") > 1:
for i, name in enumerate(index_names):
if name == "*":
index_names[i] = f"index_{i}"
return index_names
|
dc4acc473eaf13d18f553abd722384bf4fe3115a
| 698,586
|
from pathlib import Path
import json
def read_description(filename):
"""Read the description from .zenodo.json file."""
with Path(filename).open() as file:
info = json.load(file)
return info['description']
|
0568aa956f3b0c3f5be4ba75ea8e6b98e08c469e
| 698,588
|
import argparse
def parsing():
"""
Parse arguments
"""
descr = "Superimpose all .pdb conformations onto the provided template"
descr_pdbDir = "Directory containing conformation ensemble"
descr_templatePath = "Template onto which superimpose the conformation " \
"ensemble"
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("pdbDir", help=descr_pdbDir)
parser.add_argument("templatePath", help=descr_templatePath)
args = parser.parse_args()
pdbDir = args.pdbDir
templatePath = args.templatePath
return pdbDir, templatePath
|
45e96831e82adf04fd974631a303418db42fc09a
| 698,589
|
import zipfile
import os
def zip_file(dir, filename):
"""
Add the contents of dir to zipfile.
:param dir: str
:param filename: str (the name of the zip file)
:return: None
"""
zp = zipfile.ZipFile(filename, "w")
for i in os.walk(dir, followlinks=True):
for fp in i[2]:
path = os.path.join(i[0], fp)
rel = os.path.relpath(path, dir)
zp.write(path, rel)
return zp
|
23fa15682bd1e0917830139ef0848fddee36dbd0
| 698,590
|
def cocktail_shaker_sort(list_: list) -> list:
"""Returns a sorted list, by cocktail shaker sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by cocktail shaker sort method
"""
higher = len(list_) - 1
lower = 0
Flag = False
while not Flag and higher - lower > 1:
Flag = True
for j in range(lower, higher):
if list_[j + 1] < list_[j]:
list_[j], list_[j + 1] = list_[j + 1], list_[j]
Flag = False
higher -= 1
for j in range(higher, lower, -1):
if list_[j - 1] > list_[j]:
list_[j], list_[j - 1] = list_[j - 1], list_[j]
Flag = False
lower += 1
return list_
|
5a5214100859f95a34fd6f89786f5b93dad426ce
| 698,592
|
from bs4 import BeautifulSoup
import requests
import re
def getProductInfo(link):
"""
gets a random item link and looks for item_name,
item_price and item_main_image
returns all three infos as string
"""
req = requests.get(link)
soup = BeautifulSoup(req.text, 'html.parser')
# get image
images = soup.find_all('div', {'class': 'image-wrapper'})
regex = r'src=".*jpg"'
image = re.findall(regex, str(images[0]))[0].replace('src=', '').strip('"')
# get price
prices = soup.find_all('span', {'class': 'price'})
regex = r'(?<=>)(.*)(?=<)'
price = re.findall(regex, str(prices[0]))[0]
# get name
names = soup.find_all('span', {'class': 'base'})
regex = r'(?<=>)(.*)(?=<)'
name = re.findall(regex, str(names[0]))[0]
return image, price, name
|
b1d1a2fc28db46fbc506865a9c5a470408680ba0
| 698,593
|
import os
def GetEnvInt(variable):
"""Returns the environment variable value as an integer."""
return int(os.getenv(variable) or 0)
|
dc87a87318efe816fdb1f0a96b4e14ea226d7a5d
| 698,594
|
def convertBoolean(value: bool):
"""Convert Python bool to JS boolean.
Args:
value (bool): True/False
"""
if value:
jvalue = "true"
else:
jvalue = "false"
return jvalue
|
d9f3f58eed31f960050df25b5a8ec69fad5f8754
| 698,595
|
def a_or_an(word):
"""Naively returns "a word" or "an word" depending on the word."""
if len(word) > 0:
if word[0] in 'aeiouAEIOU':
return 'an'
else:
return 'a'
else:
return 'a'
|
45f53fbc100511364d56c06b4030055f7671ff3e
| 698,597
|
def find_earliest_start(t_goal, deltas):
"""Find the earliest start time with an active range reaching t_goal.
Example
-------
t_goal == 5
delta[t_goal - 1] == 3
We first take a guess...
|√-2|√-1| √ |
<------3
* ... Case 1 (e.g. deltas = [4, 4, 3, 3, 3]): guess DOES reach √
|√-2|√-1| √ |
3------>
* Does the one before also reach √?
|√-3|√-2|√-1| √ |
4---------->
* Yes! Does the one before also reach √?
|√-4|√-3|√-2|√-1| √ |
4---------->
No! so return √-3
* ... Case 2 (e.g. deltas = [2, 2, 2, 3, 3]): guess does NOT reach √
|√-2|√-1| √ |
2-->
* Does the one after reach √?
|√-2|√-1| √ |√+1|
3------>
Yes! So return √-1
* ... Case 3 (e.g. deltas = [4, 4, 2, 3, 3]): will incorrectly return √-1!
"""
# t_guess = ti + 1
ti = max(0, t_goal - deltas[t_goal - 1])
if ti + deltas[ti] >= t_goal:
# starting at t_guess reaches t_goal, reducing time until it doesn't...
ti -= 1
while ti > 0 and ti + deltas[ti] >= t_goal:
ti -= 1
return ti + 2 # ti is the first index for which t_goal is NOT reached
else: # t_guess does not reach t_goal, increase time until it does...
ti += 1
while ti + deltas[ti] < t_goal:
ti += 1
return ti + 1
|
f2716df58b8986a016dd79943b43959554a1786b
| 698,598
|
def to_numbers(line, dictionary):
"""
Turn a nature language sentence string to a list of numbers.
:param line:
:param dictionary:
:return:
"""
return [dictionary[string] for string in line.split()]
|
754cd8e10fda44a53e06a57cabb8f4663548c5e1
| 698,599
|
import importlib
def get_func(func_name):
"""Helper to return a function object by name. func_name must identify a
function in this module or the path to a function relative to the base
'modeling' module.
"""
if func_name == '':
return None
try:
parts = func_name.split('.')
# Refers to a function in this module
if len(parts) == 1:
return globals()[parts[0]]
# Otherwise, assume we're referencing a module under modeling
module_name = 'models.' + '.'.join(parts[:-1])
module = importlib.import_module(module_name)
return getattr(module, parts[-1])
except Exception:
print('Failed to find function: %s', func_name)
raise
|
da95b0933ce60cd55049c13ef198eba4d9d0b0ee
| 698,600
|
import os
def _add_travis_info(capabilities):
"""
"""
capabilities['tunnel-identifier'] = os.getenv('TRAVIS_JOB_NUMBER')
capabilities['build'] = os.getenv('TRAVIS_BUILD_NUMBER')
capabilities['tags'] = [os.getenv('TRAVIS_PYTHON_VERSION'), 'CI']
return capabilities
|
c47d4c6f4524b7e1e6c01c0b5186ef1f4dd5fb88
| 698,601
|
def cica_const_ratio(ambient_co2, const):
"""ci/ca is constant."""
"""Return ci = intercellular CO2 concentration, kg/m^3."""
return const * ambient_co2
|
418f5172def68cede271767943a3af5817ccfe62
| 698,602
|
def MTFfreq(MTFpos, MTF, modulation=0.2):
""" Return the frequency for the requested modulation height. """
mtf_freq = 0
for f in range(len(MTFpos)):
if MTF[f] < modulation:
if f > 0:
# Linear interpolation:
x0 = MTFpos[f-1]
x1 = MTFpos[f]
y0 = MTF[f-1]
y1 = MTF[f]
m = (y1-y0)/(x1-x0)
n = y0 - m*x0
mtf_freq = (modulation-n)/m
else:
mtf_freq = MTFpos[f]
break
return mtf_freq
|
fadec075afaffa405ef4135f714be6e2bceb71c7
| 698,603
|
import codecs
def countsyll(instring):
"""This function counts the number of characters in a tamil string
This is done by ignoring the vowel additions. If one uses the len
function, the sample string has a length of 17 - but there are actually
only 11 characters"""
s = codecs.utf_8_encode(instring)
print(s)
x = codecs.utf_8_decode(s[0])[0]
print(repr(x))
syllen = 0
vowels = ['\u0bbe','\u0bbf','\u0bc0',
'\u0bc1','\u0bc2','\u0bc6',
'\u0bc7','\u0bc8','\u0bca',
'\u0bcb','\u0bcc','\u0bcd',]
for y in x:
if y not in vowels:
syllen += 1
return syllen
|
3340eb844014c2c53661f9ea278dd38eff8e8a33
| 698,604
|
def infer_relationship(coeff: float, ibs0: float, ibs2: float) -> str:
"""
Inferres relashionship labels based on the kin coefficient
and ibs0 and ibs2 values.
"""
result = 'ambiguous'
if coeff < 0.1:
result = 'unrelated'
elif 0.1 <= coeff < 0.38:
result = 'below_first_degree'
elif 0.38 <= coeff <= 0.62:
if ibs0 / ibs2 < 0.005:
result = 'parent-child'
elif 0.015 < ibs0 / ibs2 < 0.052:
result = 'siblings'
else:
result = 'first_degree'
elif coeff > 0.8:
result = 'duplicate_or_twins'
return result
|
c24ab30a4a9d06ef552abe728f78d8081f40e87f
| 698,605
|
def allStudentsMajoringIn(thisMajor,listOfStudents):
"""
return a list of the students with the major, thisMajor
>>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
[Student(fName='MARY',lName='KAY',major="MATH")]
>>>
"""
answerList = []
for student in listOfStudents:
# step through every item in listOfStudents
# when you find a match, return that students's major
if student.major == thisMajor:
answerList.append(student)
# if you got all the way through the loop and didn't find
# the name, return False
return answerList
|
ad32dfd68b2daa4aa3e46ff8563e4575bd940336
| 698,606
|
def float_to_string(f):
""" this prints a number with a certain number of digits after the point,
while removing trailing zeros.
"""
num_digits = 6 # we want to print 6 digits after the zero
g = f
while abs(g) > 1.0:
g *= 0.1
num_digits += 1
format_str = '%.{0}g'.format(num_digits)
return format_str % f
|
41ad07eb610044ae54a201ebc77c20e2b647da3a
| 698,607
|
import os
import tempfile
def is_path_sibling_creatable(pathname: str) -> bool:
"""
`True` if the current user has sufficient permissions to create **siblings**
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise.
"""
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
try:
# For safety, explicitly close and hence delete this temporary file
# immediately after creating it in the passed path's parent directory.
with tempfile.TemporaryFile(dir=dirname):
pass
return True
# While the exact type of exception raised by the above function depends on
# the current version of the Python interpreter, all such types subclass the
# following exception superclass.
except EnvironmentError:
return False
|
6558cbcc6d3a16f1e0eea207bd09557a66ec400c
| 698,608
|
def flatten(iterable):
"""
Extracts nested file items from path
to single iter.
"""
return iterable
# Os walk with absolute path returns
# non-nested
#
# return [item for it in iterable for item in it]
|
c0b53c44c12a9307c62ce8cb54d5214b2648388f
| 698,609
|
def bounding_box(ptlist):
"""
Returns the bounding box for the list of points, in the form
(x1, y1, x2, y2), where (x1, y1) is the top left of the box and
(x2, y2) is the bottom right of the box.
"""
xs = [pt[0] for pt in ptlist]
ys = [pt[1] for pt in ptlist]
return (min(xs), max(ys), max(xs), min(ys))
|
cd27b3e5783ee7dd8c5960389079b32768516e4d
| 698,611
|
def goodreads(soup):
"""
Read the book titles from the image alt text.
"""
tags = soup.find_all(lambda x: x.next_element.name ==
'img' and '/book/show/' in x.get('href', ''))
titles = set(map(lambda x: x.img.get('alt').strip(), tags))
return titles
|
b2385a8778711661f7ead88cc9357663dce38e32
| 698,612
|
def is_good(filename: str, force: bool = False) -> bool:
"""
Verify whether a file is good or not, i.e., it does not need
any shape or illumination modification. By default a file is
good if it is a pdf.
Parameters
----------
filename
The file name.
force
Wether to force the goodness of a file.
Returns
-------
good
True whether the file is a pdf or its goodnes is forced,
False otherwise.
"""
return filename.endswith('.pdf') or force
|
acaee589288db3eb48bd7bc89dc21c0a7d75822c
| 698,613
|
def patched_repo_get_default_identity(original_repo_get_default_identity):
""" Allow to run without valid identity """
def patched_function():
try:
return original_repo_get_default_identity()
except: # pylint: disable=W0702
return ("Git User", "git@localhost")
return patched_function
|
99049874102efbec318b4ba0f23e7a8732695665
| 698,616
|
def discovery(request):
"""
defined in Core API Specification 7
:type request: pyramid.request.Request
:rtype: dict
"""
resp = request.response
resp.content = """\
<XRDS xmlns="xri://$xrds">
<XRD xmlns:simple="http://xrds-simple.net/core/1.0" xmlns="xri://$XRD*($v*2.0)" version="2.0">
<Type>xri://$xrds*simple</Type>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/people</Type>
<URI>http://api.example.org/people</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/groups</Type>
<URI>http://api.example.org/groups</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/activities</Type>
<URI>http://api.example.org/activities</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org//2008/opensocial/appData</Type>
<URI>http://api.example.org/appData</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/cache/invalidate</Type>
<URI>http://api.example.org/cache/invalidate</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/messages</Type>
<URI>http://api.example.org/messages</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/albums</Type>
<URI>http://api.example.org/albums</URI>
</Service>
<Service>
<Type>http://ns.opensocial.org/2008/opensocial/mediaItems</Type>
<URI>http://api.example.org/mediaItems</URI>
</Service>
</XRD>
</XRDS>
"""
return resp
|
c8ffad72903ab13298fc71f150f20c2e7dd47136
| 698,617
|
import platform
def is_windows():
"""是否Windows操作系统"""
return 'Windows' in platform.system()
|
5d0820d442668ad42fbc3253664be8a67f508159
| 698,620
|
import re
def all_whitespace(string):
""" all_whitespace(string : str) -> bool
>>> all_whitespace(' ')
True
Returns True if a string has only whitespace.
"""
return re.search('^[ \t]*(\r|\n|$)', string)
|
766b92da0b6e91fbcd05eed408cb5651cdf42b4e
| 698,622
|
import copy
import uuid
import collections
def deep_copy(item_original):
"""Return a recursive deep-copy of item where each copy has a new ID."""
item = copy.copy(item_original)
item._id = uuid.uuid4().hex
if hasattr(item, '_children') and len(item._children) > 0:
children_new = collections.OrderedDict()
for subitem_original in item._children.values():
subitem = deep_copy(subitem_original)
subitem._parent = item
children_new[subitem.get_name()] = subitem
item._children = children_new
return item
|
83c8ee5dd620e30a518391752905ba1966d27aa4
| 698,623
|
import sys
def use_sys_args():
""" Parse the command line arguments using sys.args. """
# There are 2 possible ways to achieve the result in one line.
# One using a map:
# return sum(list(map(int, sys.argv[1:])))
# or using a list comprehension.
return sum([int(i) for i in sys.argv[1:]])
# per http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map
# list comprehesion is considered more pythonic but if lambdas are not used then
# map will be microscopically faster.
|
790b50332755d5a35637fa7ab9f33b41a89fc32f
| 698,624
|
import os
import json
def diff_location():
"""
:params none
Returns the non-repeated address co-ordinates
"""
loc = input('Enter facebook archive extracted location: ')
if not os.path.isdir(loc):
print("The provided location doesn't seem to be right")
exit(1)
fname = loc+'/location/location_history.json'
# fname = "location_history.json"
if not os.path.isfile(fname):
print("The file location_history.json is not present at the entered location.")
exit(1)
with open(fname, 'r') as f:
txt = f.read()
raw_data = json.loads(txt)
usable_data = raw_data["location_history"]
locations = list()
for i in usable_data:
for j in i["attachments"]:
for k in j["data"]:
#print(k["place"]["coordinate"]["latitude"], ",", k["place"]["coordinate"]["longitude"], "\n")
lat = k["place"]["coordinate"]["latitude"]
long = k["place"]["coordinate"]["longitude"]
curr_loc = (lat, long)
locations.append(curr_loc)
diff_loc = list()
diff_loc.append(locations[0])
for i in locations[1:]:
flag = True
for j in diff_loc:
threshold = 0.001
if(abs(j[0]-i[0])<threshold or abs(j[0]-i[0])<threshold):
flag = False
break
if flag==True:
diff_loc.append(i)
else :
pass
return diff_loc
|
b1ef5e3c4fd85351b45de5d33e54458f626333d2
| 698,625
|
import os
def get_files():
"""Get a list of files/folders in the cwd"""
return os.listdir(os.getcwd())
|
4888620176a33a3ad97b49af7e532fd4f53bf8e3
| 698,626
|
import os
import imp
def find_module(modname):
"""Finds and returns a module in the local dist/checkout.
"""
modpath = os.path.join(
os.path.dirname(os.path.dirname(__file__)), "Lib")
return imp.load_module(modname, *imp.find_module(modname, [modpath]))
|
ef308748c969889459abaef511bbf071d0ab6fe9
| 698,627
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.