content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def coding_problem_47(prices): """ Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it. For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars. >>> coding_problem_47([9, 11, 8, 5, 7, 10]) 5 Here's the inefficient one-liner: >>> prices = [9, 11, 8, 5, 7, 10] >>> max([max(prices[today + 1:]) - prices[today] for today in range(len(prices) - 1)]) 5 """ max_future_price, max_profit = prices[-1], 0 for index in range(len(prices) - 1, 0, -1): max_future_price = max(max_future_price, prices[index]) max_profit = max(max_profit, max_future_price - prices[index - 1]) return max_profit
c2a844dd2e0404000a405f415a1ed585c687cce6
601,866
def is_next_east_cell_empty(i, j, field): """ check if next to the right cell is empty :param i: :param j: :param field: :return: True if next right cell of the field is empty, False otherwise """ if j == len(field[0]) - 1: if field[i][0] == '.': return True return False if field[i][j + 1] == '.': return True return False
75da08d76653648002ab36cdb68b72bc58ace52a
305,524
def _process_mbar_lambdas(secp): """ Extract the lambda points used to compute MBAR energies from an AMBER MDOUT file. Parameters ---------- secp: .out file from amber simulation. Returns ------- mbar_lambdas: lambda values used for MBAR energy collection in simulation. """ in_mbar = False mbar_lambdas = [] for line in secp: if line.startswith(' MBAR - lambda values considered:'): in_mbar = True continue if in_mbar: if line.startswith(' Extra'): break if 'total' in line: data = line.split() mbar_lambdas.extend(data[2:]) else: mbar_lambdas.extend(line.split()) return mbar_lambdas
4a3b5f0e812fdaeeb8b182e5ef79ce370a1c847d
384,977
def get_key(dict, key): """Trivial helper for the common case where you have a dictionary and want one value""" return dict.get(key, None)
1a2c4f0bba9e1176569c86e9deabccfc840a9229
106,602
def _SanitizeBaseName(base_name): """Make sure the base_name will be a valid resource name. Args: base_name: Name of a template file, and therefore not empty. Returns: base_name with periods and underscores removed, and the first letter lowercased. """ # Remove periods and underscores. sanitized = base_name.replace('.', '-').replace('_', '-') # Lower case the first character. return sanitized[0].lower() + sanitized[1:]
2266d90624ed49f3c315687fd0adf817ede89ae3
381,269
def fib(n): """Compute the nth Fibonacci number""" pred, curr = 0, 1 k = 1 while k < n: pred, curr = curr, curr + pred k += 1 return curr
22e5e4e238c07675f8d1dd9fa09a2cec95ebbe91
321,612
def hostname_from_fqdn(fqdn): """Will take a fully qualified domain name and return only the hostname.""" split_fqdn = fqdn.split('.', 1) # Split fqdn at periods, but only bother doing first split return split_fqdn[0]
3717199a1df7d64f14c7ef3cea66e51217ac252b
509,046
from typing import Dict from typing import Any def normalize_dict(from_dict: Dict[str, Any], key_mapping: Dict[str, str]) -> Dict[str, Any]: """ Return a subset of the values in ``from_dict`` re-keyed according to the mapping in ``key_mapping``. The key mapping dict has the format of ``key_mapping[new_key] = old_key``. """ to_dict = {} for new_key, old_key in key_mapping.items(): if old_key in from_dict: to_dict[new_key] = from_dict[old_key] return to_dict
b3de8c70342f86c5f8a0586e08c9d688803101fc
432,250
import signal def translate_exit_code(exit_code): """ @brief Check exit code and convert it to a human readable string @param exit_code The exit code from a program @return tuple containing a human readeable representation of the exit code and a boolean value indicating succcess of the exit code, in that order """ hr_str = '' success = False if exit_code == None: hr_str = 'Process timed out' success = True elif exit_code == 0: hr_str = 'Process exited with code 0' success = True elif exit_code < 0: signal_name = signal.Signals(abs(exit_code)).name hr_str = 'Process exited with Signal ' + signal_name success = False else: hr_str = 'Process exited with a non-zero exit code ' + str(exit_code) success = False return hr_str, success
cffa455fc96fa3fa3b0f1bea66255e4617328917
98,759
import calendar def dt2jsts(mdatetime): """ Given a python datetime, convert to javascript timestamp format (milliseconds since Jan 1 1970). Do so with microsecond precision, and without adding any timezone offset. """ return calendar.timegm(mdatetime.timetuple())*1e3+mdatetime.microsecond/1e3
f2622b58373b2f150783573418d39d98b4ff5e8a
137,160
import json def load_schema(path): """Loads a JSON schema file.""" with open(path) as json_data: schema = json.load(json_data) return schema
e5164cf49150ffdf57be62d74212ac4b53942557
155,216
def issue_to_dict(issue): """ Convert an issue to a dictionary suitable for outputting to csv """ issue_data = {} issue_data['id'] = issue.id issue_data['title'] = issue.title issue_data['description'] = issue.description issue_data['due_date'] = issue.due_date issue_data['labels'] = '; '.join(issue.labels) if len(issue.labels) > 0 else '' issue_data['web_url'] = issue.web_url issue_data['author'] = issue.author.name issue_data['assignees'] = '; '.join([a['name'] for a in issue.assignees]) if len(issue.labels) > 0 else '' issue_data['last_updated'] = issue.updated_at issue_data['state'] = issue.state if issue.milestone: issue_data['milestone'] = issue.milestone.title issue_data['milestone_duedate'] = issue.milestone.due_date return issue_data
3ae05441a873a54c04588684f45581d2d7d17b04
667,915
def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'): """ Convert n bytes into a human readable string based on format. Symbols can be either "customary", "customary_ext", "iec" or "iec_ext", see: http://goo.gl/kTQMs >>> bytes2human(0) '0.0 B' >>> bytes2human(0.9) '0.0 B' >>> bytes2human(1) '1.0 B' >>> bytes2human(1.9) '1.0 B' >>> bytes2human(1024) '1.0 K' >>> bytes2human(1048576) '1.0 M' >>> bytes2human(1099511627776127398123789121) '909.5 Y' >>> bytes2human(9856, symbols="customary") '9.6 K' >>> bytes2human(9856, symbols="customary_ext") '9.6 kilo' >>> bytes2human(9856, symbols="iec") '9.6 Ki' >>> bytes2human(9856, symbols="iec_ext") '9.6 kibi' >>> bytes2human(10000, "%(value).1f %(symbol)s/sec") '9.8 K/sec' >>> # precision can be adjusted by playing with %f operator >>> bytes2human(10000, format="%(value).5f %(symbol)s") '9.76562 K' """ SYMBOLS = { 'customary' : ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'), 'customary_ext' : ('byte', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zetta', 'iotta'), 'iec' : ('Bi', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'), 'iec_ext' : ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi', 'zebi', 'yobi'), } n = int(n) if n < 0: raise ValueError("n < 0") symbols = SYMBOLS[symbols] prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i+1)*10 for symbol in reversed(symbols[1:]): if n >= prefix[symbol]: value = float(n) / prefix[symbol] return format % locals() return format % dict(symbol=symbols[0], value=n)
95e2a386b3f1c3fb75457d3a1d15368a18dc4452
468,108
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback): """ Build the feedback when an user has completed the quiz and has failed the quiz. :param actor_name: Name of the user that has completed the quiz. :type actor_name: str :param quiz_name: Name of the quiz. :type quiz_name: str :param course_name: Name of the course. :type course_name: str :param score: Result of the user. :type score: str :param feedback: String with the feedback. :type feedback: str :return: String of the message. :rtype: str """ if feedback == '': return '' message = f'Hi {actor_name},\n You have completed the quiz "{quiz_name}" for the course "{course_name}". ' \ f'You did not answer every question correct. For information about the topics of the questions ' \ f'you answered wrong, please take a look at: {feedback}' return message
b447fb45c742e9f13b0b67b149cd65f5ccb354c2
666,578
def smoothed_epmi(matrix, alpha=0.75): """ Performs smoothed epmi. See smoothed_ppmi for more info. Derived from this: #(w,c) / #(TOT) -------------- (#(w) / #(TOT)) * (#(c)^a / #(TOT)^a) ==> #(w,c) / #(TOT) -------------- (#(w) * #(c)^a) / #(TOT)^(a+1)) ==> #(w,c) ---------- (#(w) * #(c)^a) / #(TOT)^a ==> #(w,c) * #(TOT)^a ---------- #(w) * #(c)^a """ row_sum = matrix.sum(axis=1) col_sum = matrix.sum(axis=0).power(alpha) total = row_sum.sum(axis=0).power(alpha)[0, 0] inv_col_sum = 1 / col_sum # shape (1,n) inv_row_sum = 1 / row_sum # shape (n,1) inv_col_sum = inv_col_sum * total mat = matrix * inv_row_sum mat = mat * inv_col_sum return mat
e2f72c4169aee2f394445f42e4835f1b55f347c9
706,482
from pathlib import Path def _build_path(file_name: str) -> Path: """Build path to test data file based on file name.""" test_dir = Path(__file__).parent return test_dir / "testdata" / file_name
f597630b33d280370d27c66fcac087cbd3a2656c
402,275
def format_verify_msg(status): """Format validation message in color""" OK = '\033[92m OK \033[0m' FAIL = '\033[91mFAIL\033[0m' if status: return OK else: return FAIL
b20fb9ffd375ee9faac08198997f39f090b89d20
668,859
def cleanup_favorite(favorite): """Given a dictionary of a favorite record, return a new dictionary for output as JSON.""" favorite_data = favorite favorite_data["user"] = str(favorite["user"]) favorite_data["post"] = str(favorite["post"]) favorite_data["id"] = str(favorite["_id"]) del favorite_data["_id"] return favorite_data
48cd8469a7918e1b02062a5f804ea78d855199a4
490,707
import math def get_bound_radius(rect): """ Returns the radius of a circle that bounds the given rect """ return math.sqrt((rect.height/2)**2 + (rect.width/2)**2)
9b44a82532645a95f7a84852e58de6a2d8c5eac2
228,546
def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ hand_clone = hand.copy() if word in wordList: for c in word: if hand_clone.get(c, 0) == 0: return False hand_clone[c] = hand_clone.get(c, 0) - 1 return True return False # ALITER - Create list of characters in 'hand' with respective frequencies # hand_list = [] # for letter in hand.keys(): # for i in range(hand[letter]): # hand_list.append(letter) # # if word in wordList: # for c in word: # try: # hand_list.remove(c) # except ValueError: # return False # return True # return False
8eee69c02c01f8ef31195c56213889228c1fb8bd
129,222
from typing import Tuple def _parse_repo_info(repo: str) -> Tuple[str, str, str]: """ Gets the repo owner, name and ref from a repo specification string. """ repo_owner = repo.split("/")[0] repo_name = repo.split("/")[1].split(":")[0] if ":" in repo: repo_ref = repo.split("/")[1].split(":")[1] else: repo_ref = "master" return repo_owner, repo_name, repo_ref
9fd8fc4f91580217b7b5deeb3674b9a676a3061e
390,402
def fixture(cls): """ A simple decorator to set the fixture flag on the class.""" setattr(cls, '__FIXTURE__', True) return cls
abb835d9f99e9d4df7d055303ef0789e86b5bd91
432,144
def dist_median(distribution, count): """Returns the median value for a distribution """ counter = 0 previous_value = None for value, instances in distribution: counter += instances if counter > count / 2.0: if (not count % 2 and (counter - 1) == (count / 2) and previous_value is not None): return (value + previous_value) / 2.0 return value previous_value = value return None
ac0ad2c538101ef0f44b07a3967fa8cf8cae8602
213,296
import functools def flatten(x): """Flatten a list of lists once """ return functools.reduce(lambda cum, this: cum + this, x, [])
6d776f8367831ed03ba662f9d04945b50c39b443
132,430
def get_url(sandbox=True): """Return the url for the sandbox or the real account Usage:: url = get_url(sandbox=sandbox) :type sandbox: bool :param sandbox: determines whether you get the url for the sandbox account (True) or the real account (False). :rtype: str :returns: the entrypoint url to access the FNAC WebServices """ use_sandbox = { True: "https://partners-test.mp.fnacdarty.com/api.php/", False: "https://vendeur.fnac.com/api.php/", } return use_sandbox[sandbox]
3f0f32ee000c7f8c9ede28739209ae79e77dd279
291,794
def state2iset(s): """ Return a set that contains the index of each 1 in the binary representation of non-negative number s """ iset = [] i = 0 while s > 0: if (s & 1) != 0: iset.append(i) s = s >> 1 i += 1 return iset
d5ed00faa49cb215dc93c2cf7dc01876f625ac5b
192,050
def capacity_translate(capacity): """ 容量单位自动转换 :param capacity: capacity 以B为的单位的值 :return: 自适应单位 """ unit_list = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] idx = 0 capacity = float(capacity) while True: capacity /= 1024 if capacity > 1024: idx += 1 continue else: idx += 1 break return '%0.2f' % capacity + ' ' + unit_list[idx]
019ebf58cd44b4f0708fe72d6339feeda439f6e2
202,773
def isolate_rightmost_0_bit(n: int) -> int: """ Isolate the rightmost 0-bit. >>> bin(isolate_rightmost_0_bit(0b10000111)) '0b1000' """ return ~n & (n + 1)
1abac335b8570474121bbf307f52f7af2f0c736f
642,901
def determine_set_y_logscale(cfg, metadata): """ Determine whether to use a log scale y axis. Parameters ---------- cfg: dict the opened global config dictionairy, passed by ESMValTool. metadata: dict The metadata dictionairy for a specific model. Returns ---------- bool: Boolean to flag whether to plot as a log scale. """ set_y_logscale = True if 'set_y_logscale' in cfg: set_y_logscale = cfg['set_y_logscale'] if 'set_y_logscale' in metadata: set_y_logscale = metadata['set_y_logscale'] return set_y_logscale
c6def09b9b7468d9e5aec073d73ab9ad29146ea5
78,406
def get_frequency(samples, element) -> float: """Find the frequency of the given element in given samples Args: samples: List of elements element: Element whose frequency needs to be determined Returns: Frequency of the element """ return samples.count(element) / len(samples)
4c3f95392ab2185bebc47b8e0a38b4c2c940e765
498,272
import json def json_from_file(filepath): """Load JSON from file.""" with open(filepath) as fp: return json.load(fp)
362db738e21fd07db68b6b2acc35dc56ff594327
358,103
def get_user_profile_url(user): """Return project user's github profile url.""" return 'https://github.com/{}'.format(user)
41e8f7c7cfdb479622766224c827f7611f906484
94,780
def single_value_fetcher(cursor): """ Return the first value in the first row of the cursor. """ return cursor.fetchall()[0][0]
0773bbe4107d72bd5366d40ad0698c4625e61e9b
573,845
from typing import List def calculate_initial_prices(ps_recipes:List[List[int]], max_price_per_category:float)->List[float]: """ Calculate a vector of initial prices such that (a) the sum of prices in all recipes is the same (b) the price in each category is at most max_price_per_category (a negative number). :param ps_recipes: A list of PS recipes. :param max_price_per_category: a negative number indicating the maximum price per category (should be smaller than all valuations of traders in this category). :return: A vector of initial prices. >>> calculate_initial_prices([[1,1,0,0],[1,0,1,1]], -100) [-100.0, -200.0, -100.0, -100.0] >>> calculate_initial_prices([[1,2,0,0],[1,0,1,2]], -100) [-100.0, -150.0, -100.0, -100.0] >>> calculate_initial_prices([[1,2,0,0],[1,0,1,3]], -100) [-100.0, -200.0, -100.0, -100.0] >>> calculate_initial_prices([[2,3,0,0],[2,0,1,3]], -300) [-300.0, -400.0, -300.0, -300.0] """ num_recipes = len(ps_recipes) num_categories = len(ps_recipes[0]) # variables: 0 (the sum); 1, ..., num_categories-1 [the prices) weighted_depths = [] price_vector = [float(max_price_per_category)] * num_categories for recipe in ps_recipes: weighted_depths.append(sum(recipe)) max_weighted_depth = max(weighted_depths) for i in range(len(ps_recipes)): recipe = ps_recipes[i] for j in range(num_categories - 1, -1, -1): if recipe[j] > 0: if price_vector[j] != max_price_per_category: raise ValueError("Cannot determine initial prices: "+str(price_vector)) price_vector[j] = float(max_price_per_category * (max_weighted_depth - weighted_depths[i] + recipe[j])/recipe[j]) break return price_vector
fc51cefc23a30fa9462bab84ff99363d51b79ea6
554,670
import math def round_up(number, ndigits=0): """Round a floating point number *upward* to a given precision. Unlike the builtin `round`, the return value `round_up` is always the smallest float *greater than or equal to* the given number matching the specified precision. Parameters ---------- number : float Number to be rounded up. ndigits : int, optional Number of decimal digits in the result. Default is 0. Returns ------- float Examples -------- >>> round_up(math.pi) 4.0 >>> round_up(math.pi, ndigits=1) 3.2 >>> round_up(math.pi, ndigits=2) 3.15 >>> round_up(-math.pi, ndigits=4) -3.1415 """ multiplier = 10 ** ndigits return math.ceil(number * multiplier) / multiplier
5662baabe4a56424526749fdc61d4140a170fe61
95,389
import builtins from typing import Optional from typing import Tuple from typing import Any def tuple( env_var: builtins.str, default: Optional[Tuple[Any, ...]] = None, ) -> Optional[Tuple[Any, ...]]: """ Parse environment variable value into a tuple. Args: env_var (str): Name of desired environment variable. default (tuple, optional): Optional fallback value. Returns: tuple (optional): Environment variable typecast into a tuple. """ if env_var == "": return default return builtins.tuple(env_var.split(","))
76016fe3c89e7ebd530b5afb6d0c90183f5c1bfc
267,911
def same_prefix(cebuano_word, word): """ Vérifie si deux mots ont le même préfixe (longueur 2 ou 3) Si les premières lettres sont des voyelles on les considère similaires """ if cebuano_word and word: if cebuano_word[0] in "aeiou" and word[0] in "eaiou": return cebuano_word[1:2] == word[1:2] else: return cebuano_word[0:2] == word[0:2] else: return False
0b3b8951fd82cc31ab62a9a72ba02b4b52404b77
696,768
def _iam_ident_to_email(ident): """Given IAM identity returns email address or None.""" for p in ('user:', 'serviceAccount:'): if ident.startswith(p): return ident[len(p):] return None
ada4ce18470d67d2311ccd6536d261a464ebe8b9
69,494
def is_page_phpbb(soup): """Detect if page is phpBB, from soup""" return (soup.find('body', id='phpbb') is not None)
58dc83a974fb80d9230aca6b3c96044b3777a378
508,157
def has_permission(page, request): """Tell if a user has permissions on the page. :param page: the current page :param request: the request object where the user is extracted """ return page.has_page_permission(request)
d17a56e45a371dc0d7b26aa081c5905bfacd32b8
274,297
def intersect2D(segment, point): """ Calculates if a ray of x->inf from "point" intersects with the segment segment = [(x1, y1), (x2, y2)] """ x, y = point #print(segment) x1, y1 = segment[0] x2, y2 = segment[1] if (y1<=y and y<y2) or (y2<=y and y<y1): x3 = x2*(y1-y)/(y1-y2) + x1*(y-y2)/(y1-y2) if x3 >= x: return True else: return False else: return False
403bf09794036572d4eb198951e89379634825c8
688,809
from typing import List def parameter_order(config) -> List[str]: """ Return the order in which the parameters occur in the given dockerfile. This is needed for optimising the order in which the images are built. """ order = list() for line in config.dockerfile: order += [ parameter for parameter in config.parameters if parameter in line and '{{' in line and parameter not in order ] return order
4f02e4c04c9afb936699323714d3d9c2e0cc2317
650,871
def parse_line(line): """Parse line to (instruction, value) tuple.""" return [int(part) if part.isdigit() else part for part in line.split()]
9521d236ecf77a727a233385c901dc5c17a6f5a0
622,461
def getBasesLinear(cls, stop_at=object): """Return a list of the linear tree of base classes of a given class.""" bases = [cls] next_base = cls.__bases__[0] while next_base != stop_at: bases.append(next_base) next_base = next_base.__bases__[0] bases.append(next_base) return bases
f49a191ddc6b49e0835f5b03d5420e0297212666
114,279
def lstDiff(a, b): """Intelligently find signed difference in 2 lsts, b-a Assuming a clockwise coordinate system that wraps at 24=0 A value ahead clockwise is "larger" for subtraction purposes, even if it is on the other side of zero. Parameters: ----------- a : np.float32, float first lst in hours b : np.float32, float second lst in hours Returns: -------- diff: float b-a, wrapped correctly Comments: --------- """ if a < b: # if a is closer going through zero, wrap is used # meaning a is clockwise of a, technically ahead of it # so its direction is negative simple = b - a wrap = a + 24 - b if wrap < simple: return -wrap else: return simple else: # a is greater, but direction is tricky simple = b - a # always negative now wrap = b + 24 - a # always positive # if wrap < abs(simple), it is closer to go through zero again # in this case though that means b is clockwise a # so wrap is appropriately positive # otherwise simple is appropriately negative if wrap < abs(simple): return wrap else: return simple
f35ed768e4b67239b6f4fe499b30e0f74c524990
389,407
def get_unique_groups(input_list): """Function to get a unique list of groups.""" out_list = [] for item in input_list: if item not in out_list: out_list.append(item) return out_list
a31f44154c3a553a3ac5e1c96e0694b70dd266fd
281,935
def get_number_rows(ai_settings, ship_height, alien_height): """calculate how many row can the screen hold""" available_space_y = ai_settings.screen_height-3*alien_height-ship_height number_rows = int(available_space_y/(2*alien_height)) return number_rows
4cd769a162bc47447293d0ac34ff86298e9beb65
35,206
def get_mixture_weights_index_tuples(n_mixtures): """Index tuples for mixture_weight. Args: n_mixtures (int): Number of elements in the mixture distribution of the factors. Returns: ind_tups (list) """ ind_tups = [] for emf in range(n_mixtures): ind_tups.append(("mixture_weights", 0, f"mixture_{emf}", "-")) return ind_tups
03bd80c9ec6d7df1b7e43bde899b199876adacf5
577,720
def rank_scoring(rank: float, num_players: int) -> float: """Convert rank into a score (points). Args: rank: float, rank value num_players: int, number of players in league Returns: _: float, score value (points) """ return rank/num_players
78a2a4671027f0f82cc99865cf8d30ed93b9102b
543,841
def datetime_from_msdos_time(data, timezone): """ Convert from MSDOS timestamp to date/time string """ data_high = (data & 0xffff0000) >> 16 data_low = data & 0xffff year = 1980 + ((data_low & 0xfe00) >> 9) month = ((data_low & 0x1e0) >> 5) day = data_low & 0x1f hour = (data_high & 0xf800) >> 11 minute = (data_high & 0x7e0) >> 5 second = 2 * (data_high & 0x1f) return "%04d-%02d-%02d %02d:%02d:%02d (MSDOS date/time, %s)" % (year, month, day, hour, minute, second, timezone)
7326043515aa7c20ea5c87fdb8bdbafd5f98671a
654,859
def GetTitle( text ): """Given a bit of text which has a form like this: '\n\n Film Title\n \n (OmU)\n ' return just the film title. """ pp = text.splitlines() pp2 = [p.strip() for p in pp if len(p.strip()) >= 1] return pp2[0]
d152282610072fa88c7a45a3aca2991b6fedb79c
20,493
def _create_buckets(size, years): """ Assigns buckets for the given years, of a given size Args: size (int): Size of buckets in years years (list[int]): List of years to bucket (must be consecutive) Returns: dict: key=year, value=bucket_id """ buckets = {} bucket_id = 1 i = 0 while i < len(years): bucket_years = years[i:i + size] for y in bucket_years: buckets[y] = bucket_id bucket_id += 1 i += size return buckets
0d28221a0444c9399999e8dc280cadfb2a9817f4
211,679
from typing import Sequence from typing import List import copy def cut_list_to_limit_concatenated_str_length( target_list: Sequence[str], separator: str, max_total_str_length: int) -> List[str]: """Removes the last items from the list to limit the length of concatenated string of the items. For example, when target_list = ['Hello', 'Shoptimizer'] and separator = ',', the concatenated string is 'Hello,Shoptimizer' and the length of the string is 17. If max_total_str_length = 10, the length exceeds the maximum. So, this function removes the last item and returns transformed list: ['Hello']. Args: target_list: A list to be cut. separator: Characters used as separator when concatenating the items in the list. max_total_str_length: The maximum length of the concatenated string. Returns: A list cut from target_list. """ output_list = list(copy.deepcopy(target_list)) # Concatenated string length > max str length.. while len(separator.join(output_list)) > max_total_str_length: output_list.pop() return output_list
cc366ce2c251b80bdff186aa22c115ae5dd6d039
153,231
import random def MERB_config(BIM): """ Rules to identify a HAZUS MERB configuration based on BIM data Parameters ---------- BIM: dictionary Information about the building characteristics. Returns ------- config: str A string that identifies a specific configration within this buidling class. """ year = BIM['year_built'] # just for the sake of brevity # Roof cover if BIM['roof_shape'] in ['gab', 'hip']: roof_cover = 'bur' # no info, using the default supoorted by HAZUS else: if year >= 1975: roof_cover = 'spm' else: # year < 1975 roof_cover = 'bur' # shutters if year >= 2000: shutters = BIM['WBD'] else: if BIM['WBD']: shutters = random.random() < 0.45 else: shutters = False # Wind Debris (widd in HAZSU) # HAZUS A: Res/Comm, B: Varies by direction, C: Residential, D: None WIDD = 'C' # residential (default) if BIM['occupancy_class'] in ['RES1', 'RES2', 'RES3A', 'RES3B', 'RES3C', 'RES3D']: WIDD = 'C' # residential elif BIM['occupancy_class'] == 'AGR1': WIDD = 'D' # None else: WIDD = 'A' # Res/Comm # Metal RDA # 1507.2.8.1 High Wind Attachment. # Underlayment applied in areas subject to high winds (Vasd greater # than 110 mph as determined in accordance with Section 1609.3.1) shall # be applied with corrosion-resistant fasteners in accordance with # the manufacturer’s instructions. Fasteners are to be applied along # the overlap not more than 36 inches on center. if BIM['V_ult'] > 142: MRDA = 'std' # standard else: MRDA = 'sup' # superior # Window area ratio if BIM['window_area'] < 0.33: WWR = 'low' elif BIM['window_area'] < 0.5: WWR = 'med' else: WWR = 'hig' if BIM['stories'] <= 2: bldg_tag = 'MERBL' elif BIM['stories'] <= 5: bldg_tag = 'MERBM' else: bldg_tag = 'MERBH' bldg_config = f"{bldg_tag}_" \ f"{roof_cover}_" \ f"{WWR}_" \ f"{int(shutters)}_" \ f"{WIDD}_" \ f"{MRDA}_" \ f"{int(BIM['terrain'])}" return bldg_config
53ab72ed19ebeb3e55f83fcccb80bff665de955e
680,166
import csv def read_csv_fieldnames(filename, separator, quote): """ Inputs: filename - name of CSV file separator - character that separates fields quote - character used to optionally quote fields Ouput: A list of strings corresponding to the field names in the given CSV file. """ #function assumes first row of CSV file contains the field names csvtable = [] with open(filename, "rt", newline = '') as csvfile: #open reader with delimeter and quotechar options to set seperator and quote csvreader = csv.reader(csvfile, delimiter = separator, quotechar = quote) #easiest way to access a row for row in csvreader: csvtable.append(row) #beak becuase you only need first row break #instead returning csvtable = [[]] lst is returned = [] lst = csvtable[0] return lst
ead8b5ff5ca11d47771cf793309a640e2b1410a1
696,717
import math def pearson_C_calc(chi_square, POP): """ Calculate Pearson's C (C). :param chi_square: chi squared :type chi_square: float :param POP: population or total number of samples :type POP: int :return: C as float """ try: C = math.sqrt(chi_square / (POP + chi_square)) return C except Exception: return "None"
ffbc8c033cbda9a6204297d1443956672bf1d341
93,215
import random def number(minimum=0, maximum=9999): """Generate a random number""" return random.randint(minimum, maximum)
b3f06823431cfaca549e3dc9544e68fd13171571
61,314
from typing import Dict def get_request_organization_id(request_data: Dict) -> str: """ Get the organization ID from the request data. Args: request_data (Dict): Request data as a dictionary. Returns: str if organization_id is included in request_data. Raises: rest_framework.serializers.ValidationError if organization ID is not included in the request data. """ organization_id = request_data.get('organization_id', None) if organization_id is None: raise serializers.ValidationError('organization_id is required') # type: ignore return organization_id
1ec26da5b6a6a3dd08367c5db1c72217a631356c
558,547
def filter_ignore(annotations, filter_fns): """ Set the ``ignore`` attribute of the annotations to **True** when they do not pass the provided filter functions. Args: annotations (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of annotations filter_fns (list or fn): List of filter functions that get applied or single filter function Returns: (dict or list): boxes after filtering """ if callable(filter_fns): filter_fns = [filter_fns] if isinstance(annotations, dict): for _, values in annotations.items(): for anno in values: if not anno.ignore: for fn in filter_fns: if not fn(anno): anno.ignore = True break else: for anno in annotations: if not anno.ignore: for fn in filter_fns: if not fn(anno): anno.ignore = True break return annotations
f59e6c481eb744245ae9503ae07ed88d1f3f8253
8,850
def homo_degree_dist_filename(filestem): """Return the name of the homology degree distribution file.""" return f"{filestem}-degreedist.tsv"
ca75ec91578d7c7cb9e61636c8d8399eced5e6d5
360,069
import keyword def is_correct_variable_name(string: str) -> bool: """ Check if string is a valid variable name and is not a reserved keyword. :param string: string to check :return: True/False """ return string.isidentifier() and not keyword.iskeyword(string)
68cf772b78ccaaafd8a22ea4db430a83868723f0
587,770
def format_list_entry(str_list: list) -> str: """ Converts list of strings into a single string with values separated by comma. :param list str_list: list of strings :return: formatted string """ out_str = '' for elm in str_list: out_str += elm out_str += ', ' return out_str[:-2]
6586c4e47825db3b2978a79a780802d2744feed4
407,284
def count_consonants(string: str) -> int: """ Counts the number of consonants in the given string :param string: String to count :return: int Example: >>> count_consonants("Hello World") >>> 7 """ return sum(1 for char in string if char.lower() in 'bcdfghjklmnpqrstvwxyz')
85f293199e71406bfbec1ff4f10db62568f6bd97
600,545
def IsCoverageBuild(env): """Returns true if this is a coverage build. Args: env: The environment. Returns: whether this is a coverage build. """ return 'coverage' in env.subst('$BUILD_TYPE')
9742599d8173812f2d995d801dd6a03688941934
634,975
import random def weighted_choice(choices): """ Provides a weighted version of random.choice :param choices: A dictionary of choices, with the choice as the key and weight the value :type choices: list of tuple of (str, int) """ total = sum(weight for choice, weight in choices) rand = random.uniform(0, total) most = 0 for choice, weight in choices: if most + weight > rand: return choice most += weight
b95c046fb009414f3b16bb78652169d0c7bdae84
631,159
from typing import Union from typing import Tuple from typing import List def fields_to_device_number(fields: Union[Tuple[int, int], List[int]]) -> int: """ Joins the two 8 bit fields into a 16 bit device number Example with fields 3 and 232 3: 0b00000011 232: 0b11101000 1000: (3 << 8) | 232 (3 << 8) == 0b1100000000 0b1100000000 | 232 == 1000 """ # return struct.unpack('<H', bytes(fields))[0] return (fields[1] << 8) | fields[0]
e6873ffcc6c4f88d58ad25eccc2893a47ec9f3de
328,646
def concatenate_or_append(value, output): # O(1) """ Either concatenate a list or append to it, in order to keep list flattened as list of lists >>> concatenate_or_append([42], []) [[42]] >>> concatenate_or_append([[42, 49]], [[23, 35]]) [[23, 35], [42, 49]] """ if isinstance(value[0], list): # O(1) output += value # O(1) else: # O(1) output.append(value) # O(1) return output # O(1)
3123dc5b57fdb5792a5d65647088e1aea45abf19
100,786
def bin_widths(bin_edges): """Return array of bin widths given an array of bin edges""" return bin_edges[1:] - bin_edges[:-1]
f5db56912f1ed6a4e2f5a7d8080f0767aa31ce0e
434,474
def has_label(l): """ return a function that accepts a race and returns true if the race is labeled with l """ return lambda race: (race.filter(labels=l).count() > 0)
81b312e336ebec1ddaf48ac40eb606c5c9d8314e
373,521
import operator def reverse_sort_lists(list_1, list_2): """Reverse sorting two list based on the first one""" list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2), key=operator.itemgetter(0), reverse=True)) return list_1_sorted, list_2_sorted
bf9be3111c17c83e5ef3b87f14ee77d502ff3e0e
452,860
import string import random def _generate_random_sequence(sequence_length=6) -> str: """ Generates a random string of letters and digits. From https://pynative.com/python-generate-random-string/ :param sequence_length: length of the output string """ sequence_options = string.ascii_letters + string.digits return ''.join( random.choice(sequence_options) for _ in range(sequence_length) ).upper()
25dceeb343752ab9e04faeefb9862a6af6c941d7
486,876
import re def get_name_and_email(address): """ Function to get name and email from addresses like Company <contact@company.com>, returned as tuple (name, email) """ custom_sender_name = re.search(r'^([^<>]+)\s<([^<>]+)>$', address) if custom_sender_name: return custom_sender_name.group(1), custom_sender_name.group(2) else: return "", address
20cc05de3317ffc8d7bd7724ab61296e01f1c532
634,200
def parser_mod_shortname(parser): """short name of the parser's module name (no -- prefix and dashes converted to underscores)""" return parser.replace('--', '').replace('-', '_')
7088e25d295339e1988d23a87b177f838f6bf1f6
502,892
def point_on_rectangle(rect, point, border=False): """ Return the point on which ``point`` can be projecten on the rectangle. ``border = True`` will make sure the point is bound to the border of the reactangle. Otherwise, if the point is in the rectangle, it's okay. >>> point_on_rectangle(Rectangle(0, 0, 10, 10), (11, -1)) (10, 0) >>> point_on_rectangle((0, 0, 10, 10), (5, 12)) (5, 10) >>> point_on_rectangle(Rectangle(0, 0, 10, 10), (12, 5)) (10, 5) >>> point_on_rectangle(Rectangle(1, 1, 10, 10), (3, 4)) (3, 4) >>> point_on_rectangle(Rectangle(1, 1, 10, 10), (0, 3)) (1, 3) >>> point_on_rectangle(Rectangle(1, 1, 10, 10), (4, 3)) (4, 3) >>> point_on_rectangle(Rectangle(1, 1, 10, 10), (4, 9), border=True) (4, 11) >>> point_on_rectangle((1, 1, 10, 10), (4, 6), border=True) (1, 6) >>> point_on_rectangle(Rectangle(1, 1, 10, 10), (5, 3), border=True) (5, 1) >>> point_on_rectangle(Rectangle(1, 1, 10, 10), (8, 4), border=True) (11, 4) >>> point_on_rectangle((1, 1, 10, 100), (5, 8), border=True) (1, 8) >>> point_on_rectangle((1, 1, 10, 100), (5, 98), border=True) (5, 101) """ px, py = point rx, ry, rw, rh = tuple(rect) x_inside = y_inside = False if px < rx: px = rx elif px > rx + rw: px = rx + rw elif border: x_inside = True if py < ry: py = ry elif py > ry + rh: py = ry + rh elif border: y_inside = True if x_inside and y_inside: # Find point on side closest to the point if min(abs(rx - px), abs(rx + rw - px)) > min(abs(ry - py), abs(ry + rh - py)): if py < ry + rh / 2.0: py = ry else: py = ry + rh else: if px < rx + rw / 2.0: px = rx else: px = rx + rw return px, py
761d3cd918b353e18195f8817292b9c2c9ec4f40
673,070
def reversedbinary(i,numbits): """Takes integer i and returns its binary representation as a list, but in reverse order, with total number of bits numbits. Useful for trying every possibility of numbits choices of two.""" num = i count = 0 revbin = [] while count < numbits: revbin.append(num%2) num = num//2 count += 1 return revbin
dd9f394a60f796481917f2c67568c1538a6cb071
421,977
def position_to_number(func): """Decorator that transforms volleyball positions into numerical positions. Description ----------- The usal positions on a volleyball court are: 4 3 2 ----------- 5 6 1 Setter -> 1 Outside Hitter -> 2 Middle Blocker -> 3 Universal -> 4 Libero -> 6 """ def convert(self, position): if not isinstance(position, int): raise TypeError positions = ['Setter', 'Outside Hitter', 'Middle Blocker'] if position == 'Universal': return 4 if position in positions: return positions.index(position) + 1 return None return convert
6e4465db1430fcec45f9d1dd145a4c0c75b9043f
357,884
def datenum_to_season(path, datenum): """ Transform %Y%m%d into %Y%SEASON, e.g. 20180506 --> 2018S2 """ month_season_table = {"01":"S1", "02":"S1", "03":"S1", "04":"S2", "05":"S2", "06":"S2", "07":"S3", "08":"S3", "09":"S3", "10":"S4", "11":"S4", "12":"S4"} if not isinstance(datenum, str): datenum = str(datenum) year = datenum[:4] month = datenum[4:6] return year + month_season_table[month]
87ea8fe77e974856d3fb0ca2faacbccadd6b5ea5
576,503
from functools import reduce def bcc(data): """ Calculate BCC (Block Check Character) checksum for data :param data: :type data: string :return: BCC checksum :rtype: int """ return reduce(lambda a,b: a^b, bytearray(data))
399f4e4e8135f31029fe29addf42c4d27f5930ac
493,529
def clip_line(line, size): """ :param line: (xmin, ymin, xmax, ymax) :param size: (height, width) :return: (xmin, ymin, xmax, ymax) """ xmin, ymin, xmax, ymax = line if xmin < 0: xmin = 0 if xmax > size[1] - 1: xmax = size[1] - 1 if ymin < 0: ymin = 0 if ymax > size[0] - 1: ymax = size[0] - 1 return xmin, ymin, xmax, ymax
8ea9c09e70a61b8c9d4bdfc9039bc192add6e5d4
269,687
import yaml def read_config(file_path): """Read the configuration file and load the YAML data. :param file_path: The path of the YAML config file. :type file_path: str :return: The complete configuration data loaded into a dictionary. :rtype: dict """ with open(file_path) as config_file: config = yaml.load(config_file, Loader=yaml.FullLoader) return config
7946dd2b013d0a0451c3df185aa28acc4cd1df41
132,800
def sublist(full_list, index): """ returns a sub-list of contiguous non-emtpy lines starting at index """ sub_list = [] while index < len(full_list): line = full_list[index].strip() if line != "": sub_list.append(line) index += 1 else: break return sub_list
ee4ed5e730829a22cb825e39aa95b19e037dda00
686,617
import imaplib def open_session(imap_url, username, password): """Function creates and returns an object of the connection with specified credentials and imap_url""" con = imaplib.IMAP4_SSL(imap_url) con.login(username, password) return con
f19a342e562bfc0352af54b642f79a332fd818c7
416,382
def trdata(trin): """Obtain data points from a trace-table record""" return trin.data()
832c36015d0923a4cd1e899751dad3828d8fdc99
343,318
def add_row(content, row_index, row_info=[]): """ From the position of the cursor, add a row Arguments: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content - cursor index for col - cursor index for row Returns: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content """ for i in range(len(content)): content[i].insert(row_index+1, "") return content
99b256ed6581462488d396ece5261ef5fa431b45
597,736
def clamp(value, parameter): """ Clamp value to parameter's min and max values """ value = parameter.min if value < parameter.min else value value = parameter.max if value > parameter.max else value return value
7bd154e9221c288810ab9470e37beca9cb58b068
634,490
def get_length(self, is_pattern=False): """Returns the length of the axis taking symmetries into account. Parameters ---------- self: DataPattern a DataPattern object is_pattern: bool return length of pattern Returns ------- Length of axis """ if is_pattern: return len(self.values) else: return len(self.rebuild_indices)
d1b8eb0d51a3f699aa252a191de41b17d20df9ef
277,898
def _utf8_encoded_json(request): """Checks if content of the request is defined to be utf-8 encoded json. 'Content-type' header should be set to 'application/json; charset=utf-8'. The function allows whitespaces around the two segments an is case-insensitive. """ content_type = request.META.get('CONTENT_TYPE', '') parts = content_type.split(';') if (len(parts) != 2 or parts[0].strip().lower() != 'application/json' or parts[1].strip().lower() != 'charset=utf-8'): return False return True
f279b095fda6b3f0a55fc7ecaec65cd813036f7a
179,522
def binding_array_names(experiment_proto): """Return all binding array names from an Experiment proto. Args: experiment_proto: selection_pb2.Experiment describing the experiment. Returns: List of strings in sorted order. """ names = [array.name for array in experiment_proto.binding_arrays] return sorted(names)
d9777fd2f4dabf3d11eda0668afda1e5b4845613
412,757
def tab(s): """indent multiline text""" s = s.split("\n") s = [f" {l}" for l in s] s = "\n".join(s) return s
324e3f1625c230f8c4c8daa84abe5d861b518ba0
422,037
import struct def read_plain_int96(fo): """Reads a 96-bit int using the plain encoding""" tup = struct.unpack("<qi", fo.read(12)) return tup[0] << 32 | tup[1]
39d924fe211a17192b4b3158340d40b3f28948d1
22,587
import pickle def dump_obj(path, obj): """ Dump obj in path Args: path (string): path where dump the obj obj (object): object to dump Returns: path where you dumped """ with open(path, "wb") as fp: pickle.dump(obj, fp) return path
9a107a2e18e1c2d5f923c62bf16c6b882f9724c7
224,316
def get_labels_from_sample(sample): """ Each label of Chinese words having at most N-1 elements, assuming that it contains N characters that may be grouped. Parameters ---------- sample : list of N characters Returns ------- list of N-1 float on [0,1] (0 represents no split) """ labels = [] for word in sample: if len(word) > 1: for _ in range(len(word)-1): labels.append(0) # within a word, append a '0' for each interstice labels.append(1) # at the end of a word, append a '1' else: labels.append(1) labels = labels[:-1] # Throw away the last value, it doesn't represent an interstice return labels
4b21b878d1ae23b08569bda1f3c3b91e7a6c48b9
707,651
def dirs(obj, st='', caseSensitive=False): """ I very often want to do a search on the results of dir(), so do that more cleanly here :param obj: the object to be dir'd :param st: the strig to search :param caseSensitive: If False, compares .lower() for all, else doesn't :return: The results of dir() which contain st """ if caseSensitive: return [ii for ii in dir(obj) if st in ii] return [ii for ii in dir(obj) if st.lower() in ii.lower()]
35a4ec780cf99396cbdb57c8f21633b8242b3764
610,109
def clamp(val, min, max): """ Clamps the number """ if val > max: return max elif val < min: return min return val
59174310981e65cfdf6b4c1fb83ab8565478ac9e
309,094
def check_more_than_one_row(df_test): """ This function can verify that the dataframe has at least one row Input: dataframe Output: Boolean value (If the dataframe has at least one row, then return True, otherwise return False) """ if df_test.shape[0] < 1: return False return True
b01ef000be3700d480656e494db8a34d4ae7db05
312,865
from datetime import datetime def time_compare(a, b=None): """ Compare datetime objects a and b. If a < b, that is, a means time before b, return -1. If b < a, return 1. Otherwise return 0. If b is not given, assume b is now. """ if b == None: b = datetime.now() if a < b: return -1 if b < a: return 1 return 0
e81198b34b88e0a9ec6f4a464cf982a50736481d
210,562
def _start_stop_block(size, proc_grid_size, proc_grid_rank): """Return `start` and `stop` for a regularly distributed block dim.""" nelements = size // proc_grid_size if size % proc_grid_size != 0: nelements += 1 start = proc_grid_rank * nelements if start > size: start = size stop = start + nelements if stop > size: stop = size return start, stop
e7ac2edba2ff57e96adde139afc5fc09218063bc
484,892
def get_coordinates( x,y,direction ): """ Given (x,y) coordinates and direction, this function returns the coordinates of the next tile The strange coordinate system used to represent hexagonal grids here is called the 'Axial Coordinate System'. Reference: https://www.redblobgames.com/grids/hexagons/ """ coordinate_transform = { 'e' : ( x+1, y ), 'se': ( x , y+1 ), 'sw': ( x-1, y+1 ), 'w' : ( x-1, y ), 'nw': ( x , y-1 ), 'ne': ( x+1, y-1 ), } return coordinate_transform[ direction ]
67aa21e3648b7273e5e9a8b7221e6abe20db37be
225,352
def get_module_masses(massfile): """Parse input file to get masses of each module. Input file has the mass of each module on its own line. Return list of module masses. """ module_masses = [] with open(massfile, "r") as infile: module_masses = [int(line) for line in infile] return module_masses
129eafe214cf17572379e0ba0a54a71d9ddf213e
362,152
def make_rowid(city: str, date: str, num: str, name: str) -> str: """Create a unique row ID for the horse entry.""" return "{}_{}_{}_{}".format(city, date.replace("/", ""), num, name.replace(" ", ""))
98cb86a38670a33f0495599a62620b426881cf93
142,226