content
stringlengths
42
6.51k
def next_permutation(lst): """ 1. Find the highest index k such that str[k] < str[k+1]. If no such index exists, the permutation is the last permutation. Note that all the elements after k will be in non-ascending order. 2. Find the highest index l > k such that str[l] > str[k]. Such an 'l' must exist, since k+1 is such an index. Basically we want the smallest element in the range [k+1, end) bigger than str[k]. 3. Swap str[k] with str[l]. 4. Reverse the order of all of the elements after index k. Basically we want to sort it, but since its already in decreasing order so reversing is same as swapping. """ k_idx = None for i in range(0, len(lst) - 1): if lst[i] < lst[i + 1]: k_idx = i if k_idx is None: return None l_idx = None # CAREFUL: l_idx cannot simply be the last index of the array # as it is possible that the number there is smaller than arr[k_idx]. # For example: 1 2 5 4 3 1 for i in range(k_idx + 1, len(lst)): if lst[i] > lst[k_idx]: l_idx = i lst[k_idx], lst[l_idx] = lst[l_idx], lst[k_idx] return lst[: k_idx + 1] + lst[len(lst): k_idx: -1]
def fields_values(d, k): """ Returns the string contained in the setting ADMIN_MEDIA_PREFIX. """ values = d.get(k,[]) return ",".join(map(str,values))
def _list(x): """Force x to a list.""" if not isinstance(x, list): x = list(x) return x
def share_diagonal(x0, y0, x1, y1): """ Is (x0, y0) on a shared diagonal with (x1, y1)? """ dy = abs(y1 - y0) # Calc the absolute y distance dx = abs(x1 - x0) # CXalc the absolute x distance return dx == dy
def separate (spamlist): """ separate list items with a comma and space Args: (list spamlist) Return: list separated by comma and space """ result = ', '.join(spamlist) #takes items in a iterable and joins the into one string return result
def follows(anno_prev, anno): """ Finds if two annotations can be merged. """ text_id1, sentence_id1, annotation_id1, tokens1, sent_token_start1, \ sent_token_end1, doc_token_start1, doc_token_end1, type1, correction1, comment = anno_prev text_id2, sentence_id2, annotation_id2, tokens2, sent_token_start2, \ sent_token_end2, doc_token_start2, doc_token_end2, type2, correction2, comment = anno if text_id1 != text_id2 or sentence_id1 != sentence_id2: return False return int(sent_token_end1) + 1 == int(sent_token_start2) \ and int(doc_token_end1) + 1 == int(doc_token_start2) \ and type1 == type2
def array_from_prompts_string(str): """ Splits a string of prompts into a list. Args str: A story that is a dictionary with 'title', 'content', and 'prompts' keywords. Returns A list of the prompts of the story. """ prompts_array = str.split('|') return prompts_array
def maxVal(to_consider, available_weight): """Assumes to_consider a list of items, available_weight a weight Returns a tuple of the total value of a solution to 0/1 knapsack problem and the items of that solution""" if to_consider == [] or available_weight == 0: result = (0, ()) elif to_consider[0].get_weight() > available_weight: result = maxVal(to_consider[1:], available_weight) else: next_item = to_consider[0] with_value, with_to_take = maxVal(to_consider[1:], available_weight - next_item.get_weight()) with_value += next_item.get_value() without_value, without_to_take = maxVal(to_consider[1:], available_weight) if with_value > without_value: result = (with_value, with_to_take + (next_item,)) else: result = (without_value, without_to_take) return result
def valid_lopback_number(loopback_number): """Validates a VLAN ID. Args: loopback_number (integer): Loopback port number to validate. If passed as ``str``, it will be cast to ``int``. Returns: bool: ``True`` if it is a valid loopback_number. ``False`` if not. Raises: None Examples: >>> import pyswitch.utilities >>> loopback_number = '2' >>> pyswitch.utilities.valid_lopback_number(loopback_number) True >>> extended = False >>> vlan = '256' >>> pyswitch.os.base.utilities.valid_lopback_number(loopback_number) """ minimum_loopback_id = 1 maximum_loopback_id = 255 return minimum_loopback_id <= int(loopback_number) <= maximum_loopback_id
def someFunc(x): """y = |x| """ if x != 3 and x != -2: return (x+3)/(x**2 -x -6) #return (16-2*x)*(30-2*x)*x #if x<=1: # return .5*x -3 #else: # return 4*x+3 #return x/ (x**2+4) #return (x+3)/(x**2 - x -6) #if x <= 2: # return math.sqrt(4 - x**2)
def is_scalarlike(item): """Is item scalar like?""" try: float(item) return True except TypeError: return False
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]
def readtrj(filename): """ In the case the :class:`Chain` instance must be created from a finite chain of states, the transition matrix is not fully defined. The function defines the transition probabilities as the maximum likelihood probabilities calculated along the chain. Having the file ``/mypath/trj`` with the following format:: 1 1 1 2 1 3 the :class:`Chain` instance defined from that chain is: >>> t = pykov.readtrj('/mypath/trj') >>> t (1, 1, 1, 2, 1, 3) >>> p, P = maximum_likelihood_probabilities(t,lag_time=1, separator='0') >>> p {1: 0.6666666666666666, 2: 0.16666666666666666, 3: 0.16666666666666666} >>> P {(1, 2): 0.25, (1, 3): 0.25, (1, 1): 0.5, (2, 1): 1.0, (3, 3): 1.0} >>> type(P) <class 'pykov.Chain'> >>> type(p) <class 'pykov.Vector'> """ with open(filename) as f: return tuple(line.strip() for line in f)
def time_time2text(s, m, h, seconds_frac=0): """ Semantics: Writes time as s,m,h into the format of text for printing for example. Args: s: seconds m: minutes h: hours seconds_frac: lower than a seconds Returns: Format is ('s+seconds_frac seconds ', 'm minutes ', 'h hours '). The plural is changed depending on how many units there are, and if a variable is 0, the string is empty. """ if s == 0: ts = "" elif s == 1: ts = f"{s + seconds_frac} second " else: ts = f"{s:d} seconds " if m == 0: tm = "" elif m == 1: tm = f"{m:d} minute " else: tm = f"{m:d} minutes " if h == 0: th = "" elif h == 1: th = f"{h:d} hour " else: th = f"{h:d} hours " if h == s and s == m and m == 0: ts = "{} second ".format(seconds_frac) return ts, tm, th
def bold(content): """Corresponds to ``**content**`` in the markup. :param content: HTML that will go inside the tags. >>> 'i said be ' + bold('careful') 'i said be <b>careful</b>' """ return '<b>' + content + '</b>'
def largest_of_three(a: int, b: int, c: int) -> int: """ Find largest of 3 given numbers >>> largest_of_three(1,2,3) 3 """ return(max(a,b,c))
def create_plot_data(f, xmin, xmax, n): """ Computes and returns values of y = f(x). f -- function of x xmin -- minimum value of x xmax -- maximum value of x n -- number of values of x returns values of x and y """ xs = [] ys = [] for i in range(n): xi = xmin + float(i) * (xmax - xmin) / (n - 1) yi = f(xi) xs.append(xi) ys.append(yi) return (xs, ys)
def get_igm_outputs(name, igm_properties): """ Creates Instance Group Manaher (IGM) resource outputs. """ location_prop = 'region' if 'region' in igm_properties else 'zone' return [ { 'name': 'selfLink', 'value': '$(ref.{}.selfLink)'.format(name) }, { 'name': 'name', 'value': name }, { 'name': 'instanceGroupSelfLink', 'value': '$(ref.{}.instanceGroup)'.format(name) }, { 'name': location_prop, 'value': igm_properties[location_prop] } ]
def _addressAndPort(s): """Decode a string representing a port to bind to, with optional address.""" s = s.strip() if ':' in s: addr, port = s.split(':') return addr, int(port) else: return '', int(s)
def get_slurm_dict(arg_dict,slurm_config_keys): """Build a slurm dictionary to be inserted into config file, using specified keys. Arguments: ---------- arg_dict : dict Dictionary of arguments passed into this script, which is inserted into the config file under section [slurm]. slurm_config_keys : list List of keys from arg_dict to insert into config file. Returns: -------- slurm_dict : dict Dictionary to insert into config file under section [slurm].""" slurm_dict = {key:arg_dict[key] for key in slurm_config_keys} return slurm_dict
def BytesKbOrMb(num_bytes): """Return a human-readable string representation of a number of bytes.""" if num_bytes < 1024: return '%d bytes' % num_bytes # e.g., 128 bytes if num_bytes < 99 * 1024: return '%.1f KB' % (num_bytes / 1024.0) # e.g. 23.4 KB if num_bytes < 1024 * 1024: return '%d KB' % (num_bytes / 1024) # e.g., 219 KB if num_bytes < 99 * 1024 * 1024: return '%.1f MB' % (num_bytes / 1024.0 / 1024.0) # e.g., 21.9 MB return '%d MB' % (num_bytes / 1024 / 1024) # e.g., 100 MB
def normalize_copy(numbers): """ This function works for generators by converting the generator to a list first. """ numbers = list(numbers) total = sum(numbers) return [100 * value / total for value in numbers]
def pretty_command(command, gui, plugins=["-deadlock", "-racer"]): """ Assumes command in form <prefix> frama-c -<plugin> [option [value]]* that is printed as: <prefix> frama-c -<plugin> option1 value option2 ... """ result = command[0] if not gui else command[0] + "-gui" prefix = True for elem in command[1:]: if prefix: result += " " + elem if elem in plugins: prefix = False elif elem.startswith("-"): result += " \\\n\t" + elem else: result += " " + elem return result
def order_features_list(flist): """ order the feature list in load_ML_run_results so i don't get duplicates""" import pandas as pd import numpy as np # first get all features: li = [x.split('+') for x in flist] flat_list = [item for sublist in li for item in sublist] f = list(set(flat_list)) nums = np.arange(1, len(f)+1) # now assagin a number for each entry: inds = [] for x in flist: for fe, num in zip(f, nums): x = x.replace(fe, str(10**num)) inds.append(eval(x)) ser = pd.Series(inds) ser.index = flist ser1 = ser.drop_duplicates() di = dict(zip(ser1.values, ser1.index)) new_flist = [] for ind, feat in zip(inds, flist): new_flist.append(di.get(ind)) return new_flist
def is_coach(user): """ Returns True if the user is a coach, False otherwise. """ try: user.coach return True except: return False
def toint(x): """Force conversion to integer""" try: return int(x) except: return 0
def format_schema_listing(schemas, print_header=False): """Formats the listing of schemas Args: schemas (list): A list of schemas as dicts print_header (bool): If set to true, a header is printed Returns: The formated list of services """ if len(schemas) == 0: return "No items available." if print_header: output = (f"{'ID':>3} {'PATH':38} {'SCHEMA NAME':30} {'ENABLED':8} " f"{'AUTH':9}\n") else: output = "" i = 0 for item in schemas: i += 1 url = (item['host_ctx'] + item['request_path']) output += (f"{item['id']:>3} {url[:37]:38} " f"{item['name'][:29]:30} " f"{'Yes' if item['enabled'] else '-':8} " f"{'Yes' if item['requires_auth'] else '-':5}") if i < len(schemas): output += "\n" return output
def surface_tension_temp(T,a=241.322,b=1.26,c=0.0589,d=0.5,e=0.56917,Tc=647.096): """ temperature-dependent surface tension calculation Parameters ---------- T : int array diameters array mapped to their indices to generate an array a, b, c, d, e : float, optional model parameters of sigma parameterization Tc : float, optional triple point temperature Returns ------- sigma : float surface tension --> returned in SI units """ """ This function returns the surface tension of water estimated as a function of instrument temperature. The empirical relationship between the temperature and surface tension has been used as prescribed by Kalova and Mares (2018).""" tau = 1 - T/Tc sigma = a*tau**b * (1 - c*tau**d- e*tau) return sigma*10**-3
def offset_to_line(filename, offsets): """Convert a list of offsets in a file to a dictionary of line, column. [ offset ] -> { offset: (line,column) } """ if not filename: return {offset: (0, 0) for offset in offsets} offsets = sorted(set(offsets)) line = 1 mappings = {} file_offset = 0 try: it = iter(offsets) offset = next(it) for l in open(filename): start_line_offset = file_offset file_offset += len(l) while offset < file_offset: mappings[offset] = (line, offset - start_line_offset + 1) offset = next(it) line += 1 except StopIteration: return mappings raise RuntimeError(f"Invalid offset {offset} (File length: {file_offset})")
def clean_parenthesized_string(string): """Produce a clipped substring of `string` comprising all characters from the beginning of `string` through the closing paren that matches the first opening paren in `string` Parameters ---------- string: String A string that contains a parenthesized statement in its entirety, along with extra content to be removed. The target parenthesized statement may contain additional parentheses Returns ------- clean_string: String A substring of `string`, extending from the beginning of `string`, through the closing paren that matches the first opening paren found, producing a valid parenthesized statement""" extra_closing_parens = 0 for i in range(len(string)): if string[i] == '(': extra_closing_parens += 1 elif string[i] == ')': if extra_closing_parens > 1: extra_closing_parens -= 1 else: return string[:i + 1] raise ValueError('No closing paren for """\n{}\n"""\nRemaining extra_closing_parens: {}'.format(string, extra_closing_parens))
def climbStairs(n): """ :type n: int :rtype: int """ if n <= 0: return 0 if n == 1: return 1 if n == 2: return 2 return climbStairs(n - 1) + climbStairs(n - 2)
def get_serializer_error_response(error): """ Returns error response from serializer :param str error: message :return: error_response :rtype: object """ error_response = {"status": 422, "data": [], "message": error} return error_response
def rank_emoji(i: int) -> str: """Returns a rank emoji for a leaderboard.""" if i < 3: return ( '\N{FIRST PLACE MEDAL}', '\N{SECOND PLACE MEDAL}', '\N{THIRD PLACE MEDAL}', )[i] return '\N{SPORTS MEDAL}'
def probabilities_to_string(probabilities): """ Converts a list of probability values (`float`s) to a list of `str` probability values, where each value is represented in scientific notation with 2 digits after the decimal. Parameters ---------- probabilities : list(float) Returns ------- list(str) """ return ["{:.2e}".format(p) for p in probabilities]
def find_delta(record, prev_rec): """Returns the interval in seconds and the rate of change per minute between the two log records. Returns None, None if the interval is zero (rate of change is infinite)""" if prev_rec is None: return None, None interval = record.timestamp - prev_rec.timestamp if interval == 0: return None, None return interval, 60.0 * (record.depth - prev_rec.depth) / interval
def generate_slurm_script(run_folder_name, slurm_settings): """ Generate slurm script for a given settings. args: run_folder_name, slurm_settings return: slurm script string """ # Generate the slurm file code = f"""#!/bin/bash #SBATCH --job-name={run_folder_name} #SBATCH --output={run_folder_name}/log.slurm #SBATCH --error={run_folder_name}/log.slurm\n""" exceptions = ["code"] for key, value in slurm_settings.items(): if not key in exceptions: code += f'#SBATCH --{key}={value}\n' if slurm_settings.get("time") is None: code += f'#SBATCH --time=24:00:00\n' if slurm_settings.get("code") is None: code += f"srun bash {run_folder_name}/run.sh" else: code += slurm_settings.get("code").replace("{run_folder_name}", f"{run_folder_name}") return code
def is_uniq(values): """ Check if input items are unique Parameters ---------- values : set set of all values Returns ------- True/False, MULTI/unique value """ if len(values) == 0: return True, '' elif len(values) == 1: return True, list(values)[0] else: return False, 'MULTI'
def generate_frame_indices(crt_idx, max_frame_num, num_frames, padding='reflection'): """Generate an index list for reading `num_frames` frames from a sequence of images. Args: crt_idx (int): Current center index. max_frame_num (int): Max number of the sequence of images (from 1). num_frames (int): Reading num_frames frames. padding (str): Padding mode, one of 'replicate' | 'reflection' | 'reflection_circle' | 'circle' Examples: current_idx = 0, num_frames = 5 The generated frame indices under different padding mode: replicate: [0, 0, 0, 1, 2] reflection: [2, 1, 0, 1, 2] reflection_circle: [4, 3, 0, 1, 2] circle: [3, 4, 0, 1, 2] Returns: list[int]: A list of indices. """ assert num_frames % 2 == 1, 'num_frames should be an odd number.' assert padding in ('replicate', 'reflection', 'reflection_circle', 'circle'), f'Wrong padding mode: {padding}.' max_frame_num = max_frame_num - 1 # start from 0 num_pad = num_frames // 2 indices = [] for i in range(crt_idx - num_pad, crt_idx + num_pad + 1): if i < 0: if padding == 'replicate': pad_idx = 0 elif padding == 'reflection': pad_idx = -i elif padding == 'reflection_circle': pad_idx = crt_idx + num_pad - i else: pad_idx = num_frames + i elif i > max_frame_num: if padding == 'replicate': pad_idx = max_frame_num elif padding == 'reflection': pad_idx = max_frame_num * 2 - i elif padding == 'reflection_circle': pad_idx = (crt_idx - num_pad) - (i - max_frame_num) else: pad_idx = i - num_frames else: pad_idx = i indices.append(pad_idx) return indices
def _remove_prefix(path): """Removes prefixed from absolute etcd paths""" _result = path.split('/') _last_index = len(_result)-1 return _result[_last_index]
def params_linear(factors): """Index tuples for linear transition function.""" return factors + ["constant"]
def in_lim(x, a, b): """Greater than or equal to and less than or equal to.""" return (x >= a) & (x <= b)
def kron(a,b): """Kronecker product of two TT-matrices or two TT-tensors""" if hasattr(a,'__kron__'): return a.__kron__(b) if a is None: return b else: raise ValueError('Kron is waiting for two TT-tensors or two TT-matrices')
def js_classnameify(s): """ Makes a classname. """ if not '_' in s: return s return ''.join(w[0].upper() + w[1:].lower() for w in s.split('_'))
def bytesToStr(s): """Force to unicode if bytes""" if type(s) == bytes: return s.decode('utf-8') else: return s
def to_ids(iterable): """ Given an iterable of integers and/or Basecampy objects with an `id` parameter, converts the iterable to be entirely integers (converting the Basecampy objects to their `id`s and not touching the existing integers. If `iterable` is `None`, returns `None`. :param iterable: an iterable of integers and/or Basecampy objects :type iterable: list[basecampy3.endpoints._base.BasecampObject|dict|int] :return: all elements of the iterable converted to integers :rtype: list[int] """ if iterable is None: return None ids = [] for i in iterable: try: _id = int(getattr(i, "id", i)) except TypeError: _id = int(dict.get(i, "id", i)) ids.append(_id) return ids
def scale_to_one(iterable): """ Scale an iterable of numbers proportionally such as the highest number equals to 1 Example: >> > scale_to_one([5, 4, 3, 2, 1]) [1, 0.8, 0.6, 0.4, 0.2] """ m = max(iterable) return [v / m for v in iterable]
def is_primitive(type): """Return true if a type is a primitive""" return type in [ "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "string", "bytes" ]
def list_to_csv(value): """ Converts list to string with comma separated values. For string is no-op. """ if isinstance(value, (list, tuple, set)): value = ",".join(value) return value
def check_rel_attribute(link): """Check rel attribute of link""" rel = link.get('rel') if rel is not None: if 'nofollow' in rel: return False elif 'bookmark' in rel: return False elif 'alternate' in rel: return False elif 'license' in rel: return False elif 'search' in rel: return False return True
def num_in_name(ele): """name parser for the output video""" return int(ele.split('.')[0].split('_')[-1])
def _relative_degree(z, p): """ Return relative degree of transfer function from zeros and poles """ degree = len(p) - len(z) if degree < 0: raise ValueError("Improper transfer function. " "Must have at least as many poles as zeros.") else: return degree
def ApproximateRandomAlignment(length, gc=.4): """Approximate the expected percent identity of an ungapped alignment between two sequences of a given length with a Normal distribution using the Central Limit Theorem""" #The probability that two randomly chosen nucleotides match #Whether or not two nucleotides match p=((gc)**2+(1-gc)**2)/2. #The expected identity is probability of a match can be modelled with a #Bernoulli random variable mean= p std=(p*(1-p)/length)**.5 return mean, std
def get_int_from_str(content): """Returns only the digits from a given string. :type content: str """ return int(''.join(element for element in content if element.isdigit()))
def cir_RsQ_fit(params, w): """ Fit Function: -Rs-Q- """ Rs = params['Rs'] Q = params['Q'] n = params['n'] return Rs + 1/(Q*(w*1j)**n)
def shutdown_timed_call(duration=120): """Like :func:`.shutdown_timed`, but returns the call as a string. Returns: str: Call. """ return f"shutdown_timed(duration={duration})"
def dimx(a): """ Helper to get the "shape" of a multidimensional list """ if not type(a) == list: return [] return [len(a)] + dimx(a[0])
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc :param num: :return: """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def get_allowed_perturbations(counts, cutoff, alphabet, num_seqs=100): """Returns list of allowed perturbations as characters count: Profile object of raw character counts at each position num_seqs: number of sequences in the alignment cutoff: minimum number of sequences in the subalignment (as fraction of the total number of seqs in the alignment. A perturbation is allowed if the subalignment of sequences that contain the specified char at the specified position is larger that the cutoff value * the total number of sequences in the alignment. """ result = [] abs_cutoff = cutoff * num_seqs for char, count in zip(alphabet, counts): if count >= abs_cutoff: result.append(char) return result
def qubo_to_ising(Q, offset=0.0): """Convert a QUBO problem to an Ising problem. Map a quadratic unconstrained binary optimization (QUBO) problem :math:`x' Q x` defined over binary variables (0 or 1 values), where the linear term is contained along the diagonal of Q, to an Ising model defined on spins (variables with {-1, +1} values). Return h and J that define the Ising model as well as the offset in energy between the two problem formulations: .. math:: x' Q x = offset + s' J s + h' s See :meth:`~dimod.utilities.ising_to_qubo` for the inverse function. Args: Q (dict[(variable, variable), coefficient]): QUBO coefficients in a dict of form {(u, v): coefficient, ...}, where keys are 2-tuples of variables of the model and values are biases associated with the pair of variables. Tuples (u, v) represent interactions and (v, v) linear biases. offset (numeric, optional, default=0): Constant offset to be applied to the energy. Default 0. Returns: (dict, dict, float): A 3-tuple containing: dict: Linear coefficients of the Ising problem. dict: Quadratic coefficients of the Ising problem. float: New energy offset. Examples: This example converts a QUBO problem of two variables that have positive biases of value 1 and are positively coupled with an interaction of value 1 to an Ising problem, and shows the new energy offset. >>> Q = {(1, 1): 1, (2, 2): 1, (1, 2): 1} >>> dimod.qubo_to_ising(Q, 0.5)[2] 1.75 """ h = {} J = {} linear_offset = 0.0 quadratic_offset = 0.0 for (u, v), bias in Q.items(): if u == v: if u in h: h[u] += .5 * bias else: h[u] = .5 * bias linear_offset += bias else: if bias != 0.0: J[(u, v)] = .25 * bias if u in h: h[u] += .25 * bias else: h[u] = .25 * bias if v in h: h[v] += .25 * bias else: h[v] = .25 * bias quadratic_offset += bias offset += .5 * linear_offset + .25 * quadratic_offset return h, J, offset
def _checkSetupFit(fit): """ check for setupFit """ keys = {'min error':dict, 'min relative error':dict, 'max error':dict, 'max relative error':dict, 'mult error':dict, 'obs':list, 'wl ranges':list, 'Nr':int, 'spec res pix':float, 'continuum ranges':list, 'ignore negative flux':bool, 'prior':list, 'DPHI order':int, 'NFLUX order': int} ok = True for k in fit.keys(): if not k in keys.keys(): print('!WARNING! unknown fit setup "'+k+'"') ok = False elif type(fit[k]) != keys[k]: print('!WARNING! fit setup "'+k+'" should be of type', keys[k]) ok = False return ok
def get_version(name): """Calculate a version number.""" import os version = None script_dir = os.path.dirname(os.path.realpath(__file__)) script_dir = os.path.join(script_dir, name) if not os.path.exists(os.path.join(script_dir, 'VERSION')): version = '0.9.3' else: with open(os.path.join(script_dir, 'VERSION'), 'r') as version_file: version = version_file.read().rstrip() return version
def mfacebookToBasic(url): """ Reformat a url to load mbasic facebook Reformat a url to load mbasic facebook instead of regular facebook, return the same string if the url does not contain facebook :param url: URL to be transformed :return: Transformed URL or unchanged parameter if URL did not contain 'facebook' """ if "m.facebook.com" in url: return url.replace("m.facebook.com", "mbasic.facebook.com") elif "www.facebook.com" in url: return url.replace("www.facebook.com", "mbasic.facebook.com") else: return url
def generate_user_and_server(server_address, ssh_user) -> str: """ Return user@server to be used with commands run over SSH. If ssh_user is not given, simply return the address of the server, assuming that the current user is suitable for running the command. """ if ssh_user is None: return server_address return ssh_user + '@' + server_address
def walk_json_dict(coll): """ Flatten a parsed SBP object into a dicts and lists, which are compatible for JSON output. Parameters ---------- coll : dict """ if isinstance(coll, dict): return dict((k, walk_json_dict(v)) for (k, v) in iter(coll.items()) if k != '_io') elif isinstance(coll, bytes): return coll.decode('ascii', errors='replace') elif hasattr(coll, '__iter__') and not isinstance(coll, str): return [walk_json_dict(seq) for seq in coll] else: return coll
def count_sentences(text): """ Hints for improvement - Last element in the splitted text is no sentence => minus 1 form no_of_sentences """ splitted_by_full_stop = text.split(".") print("") for sentence in splitted_by_full_stop: print("sentence: " + sentence) no_of_sentences = len(splitted_by_full_stop) return no_of_sentences
def setGM(gm): """Set variable mutation rate, if `gm` is given.""" if gm > 0: mutgamma = ["global shape;\n", "category rateCatMut =(" + str(gm) + ", EQUAL, MEAN, GammaDist(_x_,shape,shape), " "CGammaDist(_x_,shape,shape),0,1e25);\n"] else: mutgamma = ["rateCatMut := 1.0;\n"] return mutgamma
def get_unique_ids(_stories): """ function extract unique ids from received stories :param _stories: list of stories including story title, link, unique id, published time :return: list of unique ids """ # Get the stories titles published = [] for story in _stories: published.append(story['id']) return published
def transpose(matrix): """Transpose the incoming matrix and return a new one. The incoming matrix will remain intact. As an implementation detail, the output would be a list of *tuples*. Regardless, the output would also be accepted by all chart functions. """ return list(zip(*matrix))
def igf_noncenter_general(x1, x2, y1, y2, z1, z2, func): """ Evaluate the 3D integral over cubic domain """ return func(x2,y2,z2)-func(x1,y2,z2)-func(x2,y1,z2)-func(x2,y2,z1) \ -func(x1,y1,z1)+func(x1,y1,z2)+func(x1,y2,z1)+func(x2,y1,z1)
def range_to_level_window(min_value, max_value): """Convert min/max value range to level/window parameters.""" window = max_value - min_value level = min_value + .5 * window return (level, window)
def allowed_base64_image(image: str) -> bool: """Check if base64 image has an allowed format. :param image: :return: """ if not image.startswith('data:image/'): return False return image[11:14] in {'png', 'jpg', 'jpeg', 'gif'}
def field_conversion(field, alias=''): """ Accepts a field name and an option alias. The Alias is used to specificy which of a field is intended when doing joins etc. """ # if the alias isn't empty, add a . to the end of it for alias.field purposes if alias != '': alias += '.' # casting for dates if field['datatype'].upper() == 'DATE': # cast(to_date(from_unixtime(unix_timestamp(LIFE_SUPPORT_EFFECTIVE_DT, 'MM/dd/yyyy'))) as date) tmp = "cast(to_date(from_unixtime(unix_timestamp(" + alias + field['name'] + ", '" + field['format'] +\ "'))) as date)" # casting for timestamps elif field['datatype'].upper() == 'TIMESTAMP': # cast(from_unixtime(unix_timestamp(SCD_EFFECTIVE_TS, 'MM/dd/yyyy hh:mm:ss aa')) as timestamp) tmp = "cast(from_unixtime(unix_timestamp(" + alias + field['name'] + ", '" + field['format'] + \ "')) as timestamp)" # everything else is not cast else: tmp = "cast(" + alias + field['name'] + " as " + field['datatype'] # but if there's a precision field that gets added to the end ie decimal(10,2) if 'precision' in field and field['precision'] != '': tmp += '(' + field['precision'] + ')' tmp += ")" return tmp
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. This file only takes one biom file at a time becuase there is a chance of naming collisions with doing multiple files. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def parse_first_line_header(line): """Parse the first line of the header and extract station code""" station_info = line[0].split(':') station_code_name = station_info[1] station_code = station_code_name.split('_')[0].strip() return station_code
def search(params): """'.g' or '.gc' or '.gcs' || Searches google with any argument after command.""" msg, user, channel, users = params if msg.startswith('.g') \ or msg.startswith('.gc') \ or msg.startswith('.gcs'): return "core/search.py" else: return None
def extcode_cond(sol, source, consume): """ SOL % { """ result = sol and source.char(0) == "%" and source.char(1) == "{" if result and consume: source.consume(2) return result
def compute( op , x , y ): """Compute the value of expression 'x op y', where -x and y are two integers and op is an operator in '+','-','*','/'""" if (op=='+'): return x+y elif op=='-': return x-y elif op=='*': return x*y elif op=='/': return x/y else: return 0
def getFeaturesThreshold(lexicon, featureExs, info, arg1=None, arg2=None, expand=False, threshold=0): """ extracts featurs again. keep the features with freq > threshold getFeaturesThreshold(relationLexicon, featureExtrs, [re[1], re[4], re[5], re[7], re[8], re[6]], re[2], re[3], True, threshold=args.threshold), re[5] ,relation=relationE ) :param lexicon: FeatureLexicon :param featureExs: feature extractors :param info: features :param arg1: entity1 :param arg2: entity2 :param expand: True (always) :param threshold: :return: list of feature id s, all the features is furned, i.e. freq > threshold. """ feats = [] for f in featureExs: res = f(info, arg1, arg2) if res is not None: if type(res) == list: for el in res: featStrId = f.__name__ + "#" + el if expand: # condition that lexicon always contains the feature if lexicon.id2freq[lexicon.getId(featStrId)] > threshold: feats.append(lexicon.getOrAddPruned(featStrId)) else: featId = lexicon.getId(featStrId) if featId is not None: if lexicon.id2freq[featId] > threshold: feats.append(lexicon.getOrAddPruned(featStrId)) else: featStrId = f.__name__ + "#" + res if expand: if lexicon.id2freq[lexicon.getId(featStrId)] > threshold: feats.append(lexicon.getOrAddPruned(featStrId)) else: featId = lexicon.getId(featStrId) if featId is not None: if lexicon.id2freq[featId] > threshold: feats.append(lexicon.getOrAddPruned(featStrId)) return feats
def resolve_cardinality(class_property_name, class_property_attributes, class_definition): """Resolve class property cardinality from yaml definition""" if class_property_name in class_definition.get('required', []): min_count = '1' elif class_property_name in class_definition.get('heritable_required', []): min_count = '1' else: min_count = '0' if class_property_attributes.get('type') == 'array': max_count = class_property_attributes.get('maxItems', 'm') min_count = class_property_attributes.get('minItems', 0) else: max_count = '1' return f'{min_count}..{max_count}'
def title(y_pred, y_test, target_names, i): """ plot the result of the prediction on a portion of the test set :param y_pred: :param y_test: :param target_names: :param i: :return: """ pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1] true_name = target_names[y_test[i]].rsplit(' ', 1)[-1] return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
def find_added(st1, st2): """.""" for i in st1: st2 = st2.replace(i, '') return ''.join(sorted(st2))
def BinaryToDecimal(binary): """ Converts the given binary string to the decimal string Arguments : binary * binary - accepts the binary string """ string = int(binary, 2) return string
def pad(offset, align): """ Number of bytes to add to offset to align it """ return (align - (offset % align)) % align
def bin2int(bin): """convert the binary (as string) to integer""" #print('bin conversion', bin, int(bin, 2)) return int(bin, 2)
def all_words_start_upper_case(search_str): """ >>> all_words_start_upper_case(r"The Rain in Spain") False >>> all_words_start_upper_case(r"The Rain In Spain") True """ ret_val = True for word in search_str.split(): if not word[0].isupper() and word not in ("and"): ret_val = False break return ret_val
def get_dimension_index(data_set, tag, in_stack_position_index): """ Return the dimension index pointer without InStackPosition in order to find the different volumes :param in_stack_position_index: index of the In Stack Position element within the Dimension Index tuple """ value = data_set.get(tag) if value is not None: value = list(value) if in_stack_position_index is not None: del value[in_stack_position_index] return tuple(value) else: raise Exception( "Dimension Index Values found but InStackPosition is missing") return None
def assoc(d, key, value, factory=dict): """ Return a new dict with new key value pair New dict has d[key] set to value. Does not modify the initial dictionary. >>> assoc({'x': 1}, 'x', 2) {'x': 2} >>> assoc({'x': 1}, 'y', 3) # doctest: +SKIP {'x': 1, 'y': 3} """ d2 = factory() d2.update(d) d2[key] = value return d2
def gcd(a,b): """Return greatest common divisor using Euclid's Algorithm.""" while b: a, b = b, a % b return a
def dot(u, v): """ Returns the dot product of two vectors u, v. The vectors u, v are lists. """ if len(u) != len(v): print ("Vector Dot Product Dimension Error:", len(u), ",", len(v)) else: return sum([u[i] * v[i] for i in range(len(u))])
def legrende_polynomials(max_n, v): """ Returns the legendre polynomials Based on the algorithm here: http://uk.mathworks.com/help/symbolic/mupad_ref/orthpoly-legendre.html """ poly = [1, v] + [0] * (max_n - 1) for n in range(2, max_n + 1): poly[n] = (2 * n - 1) / n * v * poly[n - 1] - (n - 1) / n * poly[n - 2] return poly
def rsa_ascii_encode(string_to_encode:str,string_length:int) -> int: """ OS2IP aka RSA's standard string to integer conversion function. :param string_to_encode: The input string. :param string_length: How many bytes the string is. :return: The integer representation of this string. """ x=0 string_to_encode=string_to_encode[::-1] i=0 while i<string_length: tmp=ord(string_to_encode[i:i+1]) x+=(tmp*pow(256,i)) i+=1 return x
def response_ok(): """Return HTTP 200 OK message for when the connection is ok.""" return (b"HTTP/1.1 200 OK\r\n\r\n" b"Success")
def add_total_time(pdict): """ For each line in the profile add an item holding the total execution time for the line. The total execution time is the execution time of the line itself and the execution time of any of the calls associated with the line. Also adds a label adding the total execution of all the lines in the file to the 'file_summary' section. :param pdict: profile dict :return: profile dict """ for line in pdict['lines']: line['total_time'] = line['time'] + sum([c['time'] for c in line['calls']]) pdict['file_summary']['total_time'] = sum([line['total_time'] for line in pdict['lines']]) return pdict
def dydt(h, v, mp, vmp, g, vc, rho, A, CD, ms): """return time derivative of h, v and mp""" dhdt = v dvdt = -g + (vmp*vc - 0.5*rho*v*abs(v)*A*CD)/(ms + mp) dmpdt = -vmp return dhdt, dvdt, dmpdt
def fmt(text: str, textcolor: str = '', bolded: bool = False, underlined: bool = False) -> str: """ The terminal output can be colorized, bolded or underlined. Colors are stored within the Txt-class. :argument text: string which should be formatted textcolor (optional): a property of the Txt-class determines the color :returns string wrapped with ANSI-code. """ bold_str = '\033[1m' underline_str = '\033[4m' end = '\033[0m' if bolded and underlined: return f"{textcolor}{underline_str}{bold_str}{text}{end}" if bolded: return f"{textcolor}{bold_str}{text}{end}" if underlined: return f"{textcolor}{underline_str}{text}{end}" return f"{textcolor}{text}{end}"
def sortSELs(events): """ sorts the sels by timestamp, then log entry number @param events: Dictionary containing events @return: list containing a list of the ordered log entries, and dictionary of keys """ logNumList = [] timestampList = [] eventKeyDict = {} eventsWithTimestamp = {} logNum2events = {} for key in events: if key == 'numAlerts': continue if 'callout' in key: continue timestamp = (events[key]['timestamp']) if timestamp not in timestampList: eventsWithTimestamp[timestamp] = [events[key]['logNum']] else: eventsWithTimestamp[timestamp].append(events[key]['logNum']) #map logNumbers to the event dictionary keys eventKeyDict[str(events[key]['logNum'])] = key timestampList = list(eventsWithTimestamp.keys()) timestampList.sort() for ts in timestampList: if len(eventsWithTimestamp[ts]) > 1: tmplist = eventsWithTimestamp[ts] tmplist.sort() logNumList = logNumList + tmplist else: logNumList = logNumList + eventsWithTimestamp[ts] return [logNumList, eventKeyDict]
def strip_extra_slashes(path): """ Strip extra slashes from a filename. Examples: '//' -> '/' '/' -> '/' '' -> '' 'a//' -> 'a' """ l = [] slash = False for c in path: isslash = (c == '/') if not isslash or not slash: l.append(c) slash = isslash if slash and len(l) > 1 and l[-1] == '/': l.pop() return ''.join(l)
def get_unique_id(algorithm: str, vocab_size: int, min_frequency: int): """ :param algorithm: :param vocab_size: :param min_frequency: :return: """ return f"{algorithm}-vocab_size={vocab_size}-min_frequency={min_frequency}"
def remove_non_latin(input_string, also_keep=None): """Remove non-Latin characters. `also_keep` should be a list which will add chars (e.g. punctuation) that will not be filtered. """ if also_keep: also_keep += [' '] else: also_keep = [' '] latin_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' latin_chars += latin_chars.lower() latin_chars += ''.join(also_keep) no_latin = "".join([char for char in input_string if char in latin_chars]) return no_latin
def natural_bounds(rank, nb_ingredients): """ Computes the upper and lower bounds of the proportion of an ingredient depending on its rank and the number of ingredients in the product given that they are in decreasing proportion order. Examples: >>> natural_bounds(2, 4) (0.0, 50.0) >>> natural_bounds(1, 5) (20.0, 100.0) Args: rank (int): Rank of the ingredient in the list nb_ingredients (int): Number of ingredients in the product Returns: tuple: Lower and upper bounds of the proportion of the ingredient """ if rank == 1: return 100 / nb_ingredients, 100.0 else: return .0, 100 / rank