content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
import re
import os
def patch_shebang_line(fname, pad=b' ', fLOG=print):
"""
Remove absolute path to python.exe in shebang lines.
@param python python extractor
@param pad pad
@param fLOG logging function
@return boolean, True if p... | 37eba96befb257fc2d951a6971fcee6a921668a4 | 695,747 |
def parse_zone_groups(player):
"""Creates a list of all Zones with attrbute
whether they are a group or a single player"""
all_zones = []
for group in player.all_groups:
if len(group.members) > 1:
all_zones.append({"kind":"G", "master":group.coordinator})
else:
al... | c5074a3b88f661dcc0e310e2447071348ecf346f | 695,748 |
def get_default_memory_overhead(memory):
"""
The default memory overhead (related to both driver and executor) depends on how much memory is used: 0.10*memory,
with minimum of 384 MB.
:param memory: driver or executor memory
:return: default memory overhead
"""
MINIMUM_OVERHEAD = 384 << 20 ... | 25db1cfe67651cf0b32371e2d8a056b5215e264a | 695,749 |
from typing import List
from typing import Dict
from typing import Any
def format_traffic_calming_json(
traffic_calming_list: List[Dict[str, Any]],
speed_cameras: List[Dict[str, Any]],
speed_humps: List[Dict[str, Any]],
) -> str:
"""
Purpose:
Format the json to a text response
Args:
... | 4a997a8663c8deb4781eec07db2aeb163583ba1c | 695,750 |
def _difference(idxs):
""" Returns the chained difference of the indexes given.
Parameters
----------
idxs : list
List of pandas.Index objects.
Returns
-------
idx : pandas.Index
The result of the chained difference of the indexes
given.
"""
idx = idxs[0]
... | d48e491f0c145d4286bf6c7675e0b511d39b87a4 | 695,752 |
import json
def python2js(value, check_list=(None, True, False)):
"""
把check_list中的值从python类型转成js(json)类型,以适配前端显示
:param value:
:param check_list:
:return:
"""
if check_list is not None and value in check_list:
value = json.dumps(value)
else:
value = str(value)
retu... | c445ac97ce4b02262f908a9ba10fef5d35a7f452 | 695,753 |
def load_stopwords( inpath = "text/stopwords.txt" ):
"""
Load stopwords from a file into a set.
"""
stopwords = set()
with open(inpath) as f:
lines = f.readlines()
for l in lines:
l = l.strip()
if len(l) > 0:
stopwords.add(l)
return stopwords | 5e733e97a3f56867d80edeb3db5a392362a23fe1 | 695,754 |
def parse_tweet(tweet):
""" Parse elements of tweet into dict
Return dict
"""
tweet_dict = {
'created_at': tweet['created_at'],
'full_text': tweet['full_text'],
'tweet_id': tweet['id_str'],
'source': tweet['source'],
'retweets': tweet['retweet_count'],
'fa... | 301e78016972f54c31ae05c9d84de6eda32c441d | 695,755 |
def ppr(b2, b3):
"""
Plant Pigment Ratio (Metternicht, 2003).
.. math:: PPR = (b3 - b2)/(b3 + b2)
:param b2: Blue.
:type b2: numpy.ndarray or float
:param b3: Green.
:type b3: numpy.ndarray or float
:returns PPR: Index value
.. Tip::
Metternicht, G. 2003. Vegetation indic... | 77a071d3c437dc3f202f6c7a35147c7473e17749 | 695,756 |
def is_sorted(array):
"""Write a function called is_sorted that takes a list as a parameter and returns True
if the list is sorted in ascending order and False otherwise. You can assume (as a precondition) that
the elements of the list can be compared with the relational operators <, >, etc."""
copy_array = arr... | 875afc4d41c82a77bea70899c06e74c40bfe3c36 | 695,757 |
def test(r, v, source_body):
"""This function does something.
:param name: The name to use.
:type name: str.
:param state: Current state to be in.
:type state: bool.
:returns: int -- the return code.
:raises: AttributeError, KeyError
"""
print('meet me')
return None | 21842482feb961ea7cc058d72e78086c15fc8880 | 695,758 |
def transform_points(points, world_to_image):
"""
pts are nparray of shape(B, 2)
world_to_image is nparray of shape(3,3)
Returns nparray of shape(B, 2)
"""
world_to_image = world_to_image.T
return points @ world_to_image[:2,:2] + world_to_image[2,:2] | 245080a69a793c39f21654adc92871f743633eb5 | 695,759 |
def add(nmbr1, nmbr2):
"""Add Function"""
return nmbr1 + nmbr2 | de78b1340134b759f0471a50c76ffe3e3f79b54f | 695,761 |
import random
import torch
def non_nearest_neighbors(D, nb_neighbors, labels=None):
"""
Like nearest neighbors, but choose set difference with
equal (like nearest neighbors) number of non nearest neighbors.
"""
N = []
for d in D:
N += [random.sample(
list(*[torch.sort(d)[1]... | bf168c14bdf0ccfcdba29ca639f15cfadd87b323 | 695,763 |
def get_file_extension(file_name):
"""e.g.: "/home/j/path/my.video.mp4" -> ".mp4"
Throws an exception, ValueError, if there is no "." character in file_name
:param file_name: <str> any string or path that is the name of a file
:return: the file extension of the param
"""
return file_name[file_na... | 03789c21b6478f8cfa2707697e74f8d51995923b | 695,764 |
from collections import defaultdict
def optimal_weight_defaultdict(maximum, weights):
"""
Instead of a values matrix, use a defaultdict. TOO MUCH MEMORY!
"""
values = defaultdict(int)
for item in range(len(weights)):
for subweight in range(1, maximum + 1):
values[subweight, it... | 7aa6b157610cad9e1fdc7c382e2c3c85b2cb8a45 | 695,765 |
def expand_bboxes(bboxes,
image_width,
image_height,
expand_left=2.,
expand_up=2.,
expand_right=2.,
expand_down=2.):
"""
Expand bboxes, expand 2 times by defalut.
"""
expand_boxes = []
for bbo... | 12d3f4df9f79130898db620a90f80fb200e0b23d | 695,766 |
from typing import get_type_hints
def get_handler_original_typehints(handler):
"""
Retorna a assinatura do handler asyncworker que está sendo decorado.
O retorno dessa chamada é equivalente a:
typing.get_type_hints(original_handler)
Onde `original_handler` é o handler asyncworker original.
Id... | cde66d18f13ce702c91808b85d3ac6f4c8599a14 | 695,767 |
import random
def sample_corpus(collections):
"""
create proportional sizes of subcorpora across event types. randomize when selecting the texts for this sample.
:param collections: collection of collections of dictionaries per event type
:type collections: dictionary
"""
lengths_dict = {}
... | 70efacbce2538ee55d454e7799275317b88f7316 | 695,768 |
def pg_utcnow(element, compiler, **kw):
"""
Postgres UTC timestamp object
"""
return "TIMEZONE('utc', CURRENT_TIMESTAMP)" | 3deb31b98b8c75417ff0ecf5c7b5fa9eb0b91df9 | 695,769 |
def assign_value_if_none(value, default):
"""
Assign a value to a variable if that variable has value ``None`` on input.
Parameters
----------
value : object
A variable with either some assigned value, or ``None``
default : object The value to assign to the variable ``value`` if
``... | 5034a65741bb763e632bb8493eb661229e75279a | 695,770 |
def get_dict_val(dictionary, path, splitchar='/'):
"""
Return the value of the dictionnary at the given path of keys.
----------
INPUT
|---- dictionary (dict) the dict to search in.
|---- path (str) path-like string for key access ('key1/key2/key3' for ex.).
|---- splitchar (str)... | eb58e42edc705f05d9e046e65f4ed823f42c9aac | 695,771 |
import re
def acquireCliProgramVersion(s):
"""
Acquire the version of a cli program
param s: The output of the programm version string.
example: 'gcc --version'
"""
regex = r"(\d+)(\.\d+)(\.\d+)?"
matches = re.finditer(regex, s, re.MULTILINE)
version = None
for matchNum, match in enumerate(matches, start=1... | 0d50e4e1a6fce17af2f61d2de175ee0ec82d8f30 | 695,773 |
def construct_order_structure(species_order_list, current_species_string_list):
"""
Order structure for reaction order operations. Returns the cyclic_dictionary to be used by the order operator.
The meta-species objects are the keys of this dictionary and a lists of species strings currently being u... | a69c6eccffb1d22f5a4006089f6c7f12a5144a3d | 695,774 |
def find_non_base_case_job(jobs):
"""Return a job that is not a base case."""
for job in jobs:
if job.model.base_case is not None:
assert not job.model.is_base_case
return job
raise Exception("Did not find a non-base-case job") | ab80ca1ad2e5293876ffa7973112bf19ae8ab308 | 695,775 |
def _get_new_steplist(reqs_to_keep, old_step_data, req_ids):
"""Returns a list similar to `old_step_data` but with unwanted requests removed.
Uses the requests and request components in `old_step_data` and the entitiy ids in `req_ids` to determine which elements in `old_step_data` to keep.
Parameters
----------
... | 61e3c88dda3fae29a10c91b4abfc02ed4762f22e | 695,776 |
def slon_e(lon_e, precision=0):
"""East longitude string.
Parameters
----------
lon_e: float
Input east longitude (degE).
precision: int, optional
Displayed float precision.
Returns
-------
str
Formatter longitude (`180°|90°W|0°|90°E|180°|`)
"""
return ... | 1968def96ac276e23e19991672653acdc00d65d2 | 695,777 |
import os
def is_css_file(path):
"""
Return True if the given file path is a CSS file.
"""
ext = os.path.splitext(path)[1].lower()
return ext in [
'.css',
] | 370340c819b402903a70d4125dc0b805af21b645 | 695,778 |
from math import log
def is_power_of_two(x):
"""
Returns true if x is a power of two, false otherwise.
"""
if x <= 0:
return False
log2 = int(log(x, 2))
return x == 2 ** log2 | 092c13924e076c31c85ff93906c0947b61708c5a | 695,779 |
import pathlib
def make_report_file_names(proj_full_path):
"""
make the directory and file names for a report
Args:
proj_full_path (string): the path of the results directory
Returns:
report_dir (pathlib.Path)
html_outfile (pathlib.Path)
hash_fil... | 8d995bb15c2b8710ad2fb16e2476b5a96421f379 | 695,780 |
import time
import math
def __project_gdf(gdf, to_crs=None, to_latlong=False):
"""
Project a GeoDataFrame to the UTM zone appropriate for its geometries'
centroid.
The simple calculation in this function works well for most latitudes, but
won't work for some far northern locations like Svalbard a... | 6b3e67285ff9229fb96d609ffd222296dc1d7ae2 | 695,781 |
import re
def is_valid_rvpsa_id(rvpsa_id):
"""
Validates a remote VPSA ID, also known as the remote VPSA "name". A valid
remote VPSA name should look like: rvpsa-00000001 - It should always start
with "rvpsa-" and end with 8 hexadecimal characters in lower case.
:type rvpsa_id: str
:param rv... | aabe9e64dbc9003f3cc5f18842b91f4a3e34c8a8 | 695,782 |
def xyxy2xywh(bbox):
"""Transform the bbox coordinate to [x,y ,w,h].
:param bbox: the predict bounding box coordinate
:type bbox: list
:return: [x,y ,w,h]
:rtype: list
"""
_bbox = bbox.tolist()
return [
_bbox[0],
_bbox[1],
_bbox[2] - _bbox[0] + 1,
_bbox[3... | d81c9f88b8192d0ec519dd185572c9d926971cc1 | 695,783 |
import numpy
def _pixel_borders(xlim, npix, log=False, base=10.0):
"""
Determine the borders of the pixels in a vector given the first, last and
number of pixels
Args:
xlim (numpy.ndarray) : (Geometric) Centers of the first and last
pixel in the vector.
npix (int) : Numbe... | c5473a890266cc47ccb685599fa3e32237f04967 | 695,784 |
import argparse
def init_args():
"""
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('--image_path', type=str, help='The image path or the src image save dir')
parser.add_argument('--weights_path', type=str, help='The model weights path')
parser.add_argument('--is_batc... | bba33fbb37ff4ed11779298b4056313126b01ba3 | 695,785 |
def compute_prior_probability(alpha):
"""
Calculate the probability of the node being a LeafNode (1 - p(being SplitNode)).
Taken from equation 19 in [Rockova2018].
Parameters
----------
alpha : float
Returns
-------
list with probabilities for leaf nodes
References
-------... | 664734536a8a973bf77e6d9e723dc2954f663e21 | 695,786 |
def lat_opposite(side):
"""
Returns the lateral opposite as defined by the keyword pair {"Right", "Left"}
"""
if side == 'Right': return 'Left'
elif side == 'Left': return 'Right'
else: raise ValueError("Lateral side error, (%s)" % side) | 2273b4e43e37fd206cac52d81591afa12ecf68ee | 695,787 |
def ParseFiles(input, output):
"""
Makes a bed file out of each sample that is in the header of the input .bed file.
"""
input_file = open(input, 'r')
output_file_dict = dict()
header = input_file.readline()
samples = header.split()[4:]
# Iterates through the sample in the header.
f... | cc040458869edd7712acf43f4f1a72856f0d0dda | 695,788 |
def count_col_nans(col):
"""
Returns the number of NaNs of a specific column in the dataset.
Parameters:
col (pandas Series): Column in the dataset
Returns:
col_count_nans (float): Count of NaNs in col
"""
col_count_nans = col.isna().sum()
return col_count_nan... | ea055c003805112dbebd11fa5b9beea8ecc4c127 | 695,790 |
def parse_headers(env):
"""Parse HTTP headers out of a WSGI environ dictionary
Args:
env: A WSGI environ dictionary
Returns:
A dict containing (name, value) pairs, one per HTTP header
Raises:
KeyError: The env dictionary did not contain a key that is required by
PE... | 31c2d2eac9a888535d57ecaf57c91748173bd948 | 695,791 |
import os
import unicodedata
def scan_target(path, files, directories):
"""
Processes given path.
Adds files to files list.
If path is a directory, all subfiles and directories are added to
the files and directories lists as appropriate.
Returns list of files and list of directories.
"""... | f5e17abb6d73ef3d243c801b2a962793fdc24839 | 695,792 |
import random
def generate_secret_key():
"""
Generate a random secret key, suitable to be used as a SECRET_KEY setting.
"""
return ''.join(
[random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]
) | a5d2220c95338d8afdf287354b1f8f538707639a | 695,793 |
import json
def load_json_file(json_path):
"""Function to load a JSON file from the filename path"""
with open(json_path) as fp:
data = json.load(fp)
print('JSON file successfully loaded')
return data | e11ad820ce211582e646ba545be7d860718e14d9 | 695,794 |
from datetime import datetime
import os
def file_modified_iso8601(filepath):
"""
Provide a file's ctime in ISO8601
:param filepath: path to file
:returns: string of ISO8601
"""
return datetime.fromtimestamp(
os.path.getctime(filepath)).strftime('%Y-%m-%dT%H:%M:%SZ') | ca06314f64243a56aed2700a4af43bac829719fa | 695,795 |
import requests
import json
def build_link_list(client_id, num_of_images):
"""
builds a list of image links.
"""
i = 1
cnt = 0
url_list = []
url_list_len = []
try:
while(cnt < num_of_images):
# get request
response = requests.get(
f'http... | f83be601467649179992c7de621ffd777d76a4a9 | 695,796 |
import os
def remove_file(filename: str) -> bool:
"""
removes the file "filename" from disk
>>> remove_file('foobar')
True
"""
if os.path.isfile(filename):
try:
os.remove(filename)
except(IOError, OSError):
print('Can not delete {}'.format(filename))
... | c97b1d5418d086766c86f5ad6ebd07f91efb57e6 | 695,797 |
def get_node_proto(graph_proto, node_name):
"""Get a `NodeProto` from `GraphProto` by node name.
Args:
graph_proto: A `GraphProto`.
node_name: Name of the node.
Returns:
A `NodeProto` or None.
"""
for node_proto in graph_proto.nodes:
if node_proto.name == node_name:
return node_proto
... | ddc1aebeb3450de8dd6dfa85b988997a163601b4 | 695,798 |
import warnings
def warn(action):
"""Set warnings filter"""
warnings.simplefilter(action)
return action | 143fb081685769b9d189c1600ca6a51c4a084d70 | 695,799 |
def fetch_project(api, project_name=None, project_id=None):
"""
fetch a project from the sb api.
:param api: API object generated by sevenbridges.Api()
:type api: Sevenbridges API Object
:param project_name: name of a project to return e.g. 'forsure'
:type project_name: string
:param project... | f33d70367bd4a52ae0099a83110182afdb8862d5 | 695,800 |
def num_generator(num):
""" We must ensure that we always send 2 bytes
to control the frames."""
num = str(num)
if len(num) == 1:
return '0'+num
elif len(num) == 2:
return num
else:
print('There was a problem with the number generator') | 74bd94124e149ad803cecdedb2e826dc64ad0ecb | 695,801 |
import itertools
def get_global_pbm_set(notes):
"""全ノート内のピッチ形状が同一か否かを返す。
"""
# 各ノートからピッチ形状の項目を取り出して2次元リストにする。
all_pbm_2d = [note.pbm for note in notes if 'PBM' in note]
# 1次元にする。
all_pbm_1d = itertools.chain.from_iterable(all_pbm_2d)
# 選択範囲に含まれるピッチ形状の種類を列挙
pbm_types = set(all_pbm_1d)
... | fd5e4dbf797131ddb5cf93f5ae67e30e8e978fa6 | 695,802 |
def calculate_heartbeats(shb, chb):
"""
Given a heartbeat string from the server, and a heartbeat tuple from the client,
calculate what the actual heartbeat settings should be.
:param shb: server heartbeat numbers
:param chb: client heartbeat numbers
"""
(sx, sy) = shb
(cx, cy) = chb
... | e97569838c90c4f204204b3c23ce7871aa093c8a | 695,803 |
def filter_any_answer(group):
"""Filter questions answered by anyone in group."""
answers = set()
for person in group:
for question in person:
answers.add(question)
return answers | 5dca4f80e069bb3e9d9541145cbbc18eb22daf3f | 695,804 |
def jokbo(realcards):
"""
return cards' priority written with integer
:param realcards: dealer or player's cards
:return: priority (written with integer)
"""
cards = realcards[:]
for i in range(len(cards)):
if cards[i][1] == "J":
cards[i][1] = 11
if cards[i][1] ==... | ab81e38b3c2620e74ee0154df445df2088111d0a | 695,805 |
import operator
def sort(word_freq, func):
"""
Takes a dictionary of words and their frequencies
and returns a list of pairs where the entries are
sorted by frequency
"""
return func(sorted(word_freq.iteritems(), key=operator.itemgetter(1), reverse=True), None) | 829c9bf83cb1058b4af3301444793924f919d0f9 | 695,806 |
from typing import Iterable
def clean_key(k: Iterable[str]) -> str:
"""
Utility function for formatting keys.
This is a no-op if the input is a string, otherwise expects an iterable
of strings, which it joins with a period.
"""
return k if isinstance(k, str) else '.'.join(k) | 78f241056141a2549ae981a7ab18268e23fd2b0a | 695,807 |
def _get_scaffold(captured_scaffold_fn):
"""Retrieves the Scaffold from `captured_scaffold_fn`."""
scaffold_fn = captured_scaffold_fn.get()
if not scaffold_fn:
return None
scaffold = scaffold_fn()
if scaffold is None:
raise ValueError(
'TPUEstimatorSpec.scaffold_fn returns None, which is not... | dbbb3184a765d785169f66fa3385f15552aa34d4 | 695,808 |
def getFieldShortName(field_name):
""" Simplifies `field_name` in the exported dataframe by removing Watson Assistant prefixes """
return field_name.replace('request.','').replace('response.','').replace('context.system.','').replace('context.','') | 42c05ebef5d6ec0fe23ffa789f67a8aa37f364bd | 695,809 |
def hyperlink_title(body, docpath, docname):
"""
Hyperlink titles by embedding appropriate a tag inside
h1 tags (which should only be post titles).
"""
body = body.replace("<h1>", '<h1><a href="%s.html">' %
(docpath + docname), 1)
body = body.replace("</h1>", "</a></h1>", 1)
retu... | ae316226ef64a45c97cd6d094617edc2624d1cc8 | 695,810 |
def calc_host_nums(netmask: str) -> int:
"""
Calculates the number of possible IP addresses and the number
of hosts and returns an int type number.
"""
return 2 ** sum([i.count("0") for i in netmask]) | 7429efa501999d1c59a38ac7ecad0a6830dedfbe | 695,811 |
async def run_query(query_runner, sample, semaphore, pool):
"""Run query with limit on concurrent connections."""
async with semaphore:
return await query_runner.run(sample, pool) | d9005ee36ab308d6d7611af4644198ba7ccf8b5b | 695,812 |
def Home():
"""List all available api routes."""
return (
f"Available Routes:<br/><br/>"
f"-Date and Precipitation information <br/>"
f"/api/v1.0/precipitation<br/><br/>"
f"-Station information<br/>"
f"/api/v1.0/stations<br/><br/>"
f"Temperature Observation for pr... | c41f3409c1b90db5345fd1f5824dffaaee156911 | 695,813 |
import numpy
def gaussian_smooth(read_list, degree=5):
"""Smoothing function for raw bamliquidator output."""
window = degree * 2 - 1
weight = numpy.array([1.0] * window)
weight_gauss = []
for i in range(window):
i = i - degree + 1
frac = i / float(window)
gauss = 1 / (num... | 9c1e21480c2faea403e512325bd748dcc8f70405 | 695,814 |
import sys
def is_tty_supported() -> bool:
"""
Taken with appreciation from Django codebase
https://github.com/django/django/blob/0d67481a6664a1e66d875eef59b96ed489060601/django/core/management/color.py
Permissable use under the Django BSD License
"""
# isatty is not always implemented, https:... | 4d62694a919b2bbf3b293ee633bf1d94ef440643 | 695,815 |
import toml
def get_version(poetry="pyproject.toml") -> str:
"""Get the version of the package from pyproject file"""
with open("pyproject.toml", "r", encoding="utf-8") as f:
data = toml.loads(f.read())
return data["tool"]["poetry"]["version"].strip() | 56c4d658dbca656bd5964080036c9ca3df079f0d | 695,817 |
def cp_lt_stage_aware(cp0, cp1):
""" Less-than comparison of two CriticalPath objects in stage-aware mode """
if cp0.stage is None:
# CriticalPath with None stage is always shorter than any other
# critical path
return True
elif cp1.stage is None:
return False
return (cp0... | 783ee58a893bb52cd515605728ab4df743661052 | 695,818 |
import requests
def load_dynamic_nba_2022_html():
"""Load NBA 2022 team summary html from Basketball Reference"""
html_url = 'https://www.basketball-reference.com/leagues/NBA_2022.html'
result = requests.get(html_url).content
return result | 0b856dc170337fabf13fa65cd19966b043edc39d | 695,819 |
def copyfile(infile, outfile, chunksize=8192):
"""Read all data from infile and write them to outfile.
"""
size = 0
while True:
chunk = infile.read(chunksize)
if not chunk:
break
outfile.write(chunk)
size += len(chunk)
return size | 62d9d475ac7d9d93f92c2631ec405a8c4981d65e | 695,820 |
def nextGreaterElement_optimal(nums1, nums2):
""" Sizes of both arrays are small enough, so we just can do brute-force
solution in O(m * n), where n is size of nums2 and m is size of nums1.
If we want to solve this problem in O(n) time, it is not so simple. The
idea is to traverse nums2 an... | 6c0bff5f6e320c53134c13bddd74b8ad60e794c5 | 695,821 |
def mul(value, arg):
"""Multiplication
>>> mul(2, 2)
4
"""
return value * arg | 50e8f39e52c754c8448f5ce32c040e3e5106af75 | 695,822 |
from typing import Optional
from typing import Dict
def get_first_api_gateway(api_gateway_client, api_gateway_name: str) -> Optional[Dict]:
"""
Get the first API Gateway with the given name. Note, that API Gateways can have the same name.
They are identified by AWS-generated ID, which is unique. Therefore... | fee768f319f2670ecaf9f8c6c66fffc62bcd66f3 | 695,823 |
def _arg_ulen1(dvi, delta):
"""Unsigned length *delta*+1
Read *delta*+1 bytes, returning the bytes interpreted as unsigned."""
return dvi._arg(delta+1, False) | 11c34f27864b75f3b56f1a023a5226598b3845ac | 695,824 |
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n) because at most loop through the entire array
Memory usage: O(1) because not creating any new space and everything is done in place"""
for i in range(len(items) - 1):
# if next item i... | 59094cd421c104509e54d7c8a40e27b4fcb97d63 | 695,825 |
def remove_empty(data):
"""Removes empty items from list"""
out = []
for item in data:
if item == '':
continue
out.append(item)
return out | 9ef46381bb76846c92375f47eb481a26359b1d92 | 695,827 |
def api_settings(settings):
"""
Pytest fixture that sets a few default Django settings for the API
tests in this module. Returns the `settings` object. Doing setup
like this here via a fixture seems slightly better than putting
this in the `test` settings module--the relevant settings are
closer... | 3a0ef2592400b45205279a6039a7d56750893ddf | 695,828 |
import os
import sys
def resource_path(relative_path: str) -> str:
"""
Get the absolute path to a resource in a manner friendly to PyInstaller.
PyInstaller creates a temp folder and stores path in _MEIPASS which this function swaps
into a resource path so it is available both when building binaries an... | 5abb43eca1c241590867542693a71461074e068c | 695,829 |
import re
def MatchPattern(file_path, pattern):
"""Looks for matching specified pattern in the file line by line.
Args:
file_path: file path.
pattern: pattern for matching.
Returns:
the match or None.
"""
try:
with open(file_path, "r") as f:
prog = re.compile(pattern)
for line i... | 1ab4f7cf675c3be72bd6b01fb6f6c7fee2668275 | 695,830 |
import numpy
def fractional_anisotropy_from_eigenvalues(evals):
""" Taken from dipy/reconst/dti.py
see for documentation
:return:
"""
ev1, ev2, ev3 = evals
denom = (evals * evals).sum(0)
if denom > 1e-9:
fa = numpy.sqrt(
0.5 *
((ev1 - ev2) ** 2 + (ev2 - ev3)... | e5f06b3cad9f6fb74f8f2407faf2851b87e3301a | 695,831 |
def makeAssessList(df):
"""
makeAssessList produces a list of assessment weightings for the file pointed to by df (a pandas datafile)
Output: list of integer values
"""
nAssess = int(df.iloc[4,2]) # number of assessments
#make list of assessment values
assList=[]
for index in r... | 0b50cfb4f5d19649eb55080b7e3c6f2fd246163c | 695,832 |
def rem_item_from_list(item, string):
""" Removes all occurrences of token from string. If no occurrences of
items are in string, nothing is removed."""
return string.replace(item, "") | 5b0406c57aed3b786c4f20501be80e18f945928f | 695,833 |
def post_message_commands(channel, text, thread_ts):
"""
Check slack message
"""
assert text == "Tracking for following tests:\n*test* (2100-01-01 00:00:00)\n"
return {"ok": "ok"} | 20e1a74b8e71c77c79fff60488d5401300ea7ab2 | 695,834 |
def call_behavior_action_compute_output(self, inputs, parameter):
"""
Get parameter value from call behavior action
:param self:
:param inputs: token values for object pins
:param parameter: output parameter to define value
:return: value
"""
primitive = self.behavior.lookup()
inputs... | 48d3167657afaa89c86754e59380b63ab5874607 | 695,835 |
from bs4 import BeautifulSoup
def strip_html(string: str):
"""
Use BeautifulSoup to strip out any HTML tags from strings.
"""
return BeautifulSoup(string, "html.parser").get_text() | 796fc52ddd303906c7fd217275cb2a897e76767c | 695,836 |
def email_sort(email):
""" Split the given email address into a reverse order tuple, for sorting i.e (domain, name) """
return tuple(reversed(email[0].split('@'))) | d841ea1f468d11e89df5d493ac74c28705bd6c27 | 695,837 |
from typing import List
import math
def euclidian_distance(a: List[float], b: List[float]) -> float:
""" Returns the euclidian distance between two N-dimensional points """
return math.sqrt(sum((x - y) ** 2 for (x, y) in zip(a, b))) | 57aac940e12c64978c7ecc4aea567653d6ee780a | 695,838 |
def canWin2(s):
"""
:type s: str
:rtype: bool
"""
if not s or len(s)<2:
return False
for i in range(len(s)-1):
if s[i]=='+' and s[i+1]=='+':
temp=s
s=s[:i]+'--'+s[i+2:]
if not canWin2(s):
return True
s=temp
retur... | 471f21459e0aaf930ae2dd2bef79200523c9f29a | 695,839 |
def cu_gene(obj):
"""Extracts the gene name from a codon usage object in std. format"""
return str(obj.Gene).lower() | 5df9facb6de7b954efe8e273f83c4f9cc9b2725a | 695,840 |
import json
def load_config(config_filename):
"""
Load the population config for this simulation.
Args:
config_filename (str): Filename for the simulation's config.
Returns:
Dict containing data from the config file.
"""
if not config_filename:
return {}
config_... | fffa9ceade1f83ff142da2b8de6484647e165dd8 | 695,841 |
def prune_rare_cats(df):
"""Remove any categories that have less than 5 restaurants"""
new_df = df.copy()
categories = []
[categories.append(item) for item in list(df.columns) if 'category_' in item]
[new_df.drop(columns=category, inplace=True) for category in categories if df[category].... | 475d3de9b5b3937ce856bb303c6582d29d070d2b | 695,842 |
import torch
def extract_slice_from_mri(image, index_slice, view):
"""
This is a function to grab one slice in each view and create a rgb image for transferring learning: duplicate the slices into R, G, B channel
:param image: (tensor)
:param index_slice: (int) index of the wanted slice
:param vie... | 84b6120aab497f03347f5a76ba7a42abe8bb4741 | 695,843 |
def get_buildings_in_buffer(buf, buildings, ids, idx):
"""
Input the buffer polygon and building geometries to check
if the building intersects with the buffer. Return all
buildings within the buffer (based on ID). An R-tree
is used to speed up things.
"""
bld_in_buffer = {}
for i in id... | ffb55879125997f824965998999225311c221c33 | 695,844 |
def istag(arg, symbol='-'):
"""Return true if the argument starts with a dash ('-') and is not a number
Parameters
----------
arg : str
Returns
-------
bool
"""
return arg.startswith(symbol) and len(arg) > 1 and arg[1] not in '0123456789' | fd8c1edcf4289177883e3fe9efef626128bc583e | 695,845 |
def _jupyter_nbextension_paths():
"""Called by Jupyter Notebook Server to detect if it is a valid nbextension and
to install the widget
Returns
=======
section: The section of the Jupyter Notebook Server to change.
Must be 'notebook' for widget extensions
src: Source directory name to c... | 84850ab88ec4f43cd035258ad99070133ec07077 | 695,846 |
def sparse_max(A,B):
"""Max of two sparse matrices
======
Computes the elementwise max of two sparse matrices.
Matrices should both be nonegative and square.
Parameters
----------
A : (n,n) scipy sparse matrix
First matrix.
B : (n,n) scipy sparse matrix
Second matrix.
... | 93a18d367067f7d2f99212f078e4013525414adf | 695,847 |
def refine_positions(position, wfn, x_grid, y_grid):
""" Perform a least squares fitting to correct the vortex positions."""
x_pos, y_pos = position
# If at edge of grid, skip the correction:
if x_pos == len(x_grid) - 1:
return x_pos, y_pos
if y_pos == len(y_grid) - 1:
return x_pos,... | 49e7437eaca961d1576887829caf16d90567000d | 695,848 |
def list_():
"""Lists the existing entries."""
return "Sorry I forgot it all :(" | 8fa581b896ecc0118265563d1ca2f7ad3d57601b | 695,849 |
import requests
def PostcodeGeocode(postcodes):
"""" This is to return coordinates for a series of postcodes.
Each request can only handle 100 postcodes, so this will paginate through until complete.
:param postcodes: An array of postcodes to be geocoded
:return: A zipped array of lat/long coordinates... | d9274025d1b834fa6d33b6341fde31c408bcd825 | 695,850 |
def get_traces_from_log(log):
"""
Desc. read the traces from the log
Used perform_pattern_abstraction(), abstraction_suppot_functions.py
Input log, object of log imported by PM4py
Output list of traces
BY SAUD
"""
traces = []
for trace in log:
t = [l['Activity'] for ... | ea0a17dba6eb06668dab4e99b191f1c3e19c058f | 695,851 |
def custom_feature_set():
"""
Return a custom set of feature operators.
Use this function to expose any custom ruleset logic you want to add that
doesn't rely on the Operator model system. This function will be called by
all agents created by the system so you can use it for custom logic but we
... | 195f53ec296138d0018fa0886d97f3ad7fc031c7 | 695,852 |
def weeks_elapsed(day1: int, day2: int) -> int:
"""
def weeks_elapsed(day1, day2): (int, int) -> int
day1 and day2 are days in the same year. Return the number of full weeks
that have elapsed between the two days.
>>> weeks_elapsed(3, 20)
2
>>> weeks_elapsed(20, 3)
2
>>> weeks_elapse... | 856fd5439dbdb50581e9a41f30c66b6fce3a7c00 | 695,853 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.