seed
stringlengths
1
14k
source
stringclasses
2 values
def extracthypos(synset, limit=999): """Given a synset object, return a set with all synsets underneath it in the PWN structure (including the original).""" l = limit-1 result = [] result.append(synset) if synset.hyponyms() and l > 0: for each in synset.hyponyms(): x = extracthypos(each, l) result += x return result
bigcode/self-oss-instruct-sc2-concepts
def decimal_to_percent(value, decimal_place=2): """ Format a decimal to percentage with two decimal :param value: the value to be formatted :param decimal_place default decimal place, default to 2 :return: a string in percentage format, 20.50% etc """ format_str = '{:.' + str(2) + '%}' return format_str.format(value)
bigcode/self-oss-instruct-sc2-concepts
def sec2hms(seconds): """ Convert seconds into a string with hours, minutes and seconds. Parameters: * seconds : float Time in seconds Returns: * time : str String in the format ``'%dh %dm %2.5fs'`` Example:: >>> print sec2hms(62.2) 0h 1m 2.20000s >>> print sec2hms(3862.12345678) 1h 4m 22.12346s """ h = int(seconds / 3600) m = int((seconds - h * 3600) / 60) s = seconds - h * 3600 - m * 60 return '%dh %dm %2.5fs' % (h, m, s)
bigcode/self-oss-instruct-sc2-concepts
def get_HTML(file): """ Retrieves the source code from a specified saved html file args: file: The Specified html to retrieve the source code from """ f = open(file, 'r') lines = f.readlines() f.close() return "".join(lines)
bigcode/self-oss-instruct-sc2-concepts
import fsspec def map_tgt(tgt, connection_string): """Uses fsspec to creating mapped object from target connection string""" tgt_map = fsspec.get_mapper(tgt, connection_string=connection_string) return tgt_map
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_brier_score(y_pred, y_true): """Brier score implementation follows https://papers.nips.cc/paper/7219-simple-and-scalable-predictive-uncertainty-estimation-using-deep-ensembles.pdf. The lower the Brier score is for a set of predictions, the better the predictions are calibrated.""" brier_score = torch.mean(torch.mean(torch.mean((y_true-y_pred)**2, dim=3),dim=2), dim=1) return brier_score
bigcode/self-oss-instruct-sc2-concepts
def color_blend(a, b): """ Performs a Screen blend on RGB color tuples, a and b """ return (255 - (((255 - a[0]) * (255 - b[0])) >> 8), 255 - (((255 - a[1]) * (255 - b[1])) >> 8), 255 - (((255 - a[2]) * (255 - b[2])) >> 8))
bigcode/self-oss-instruct-sc2-concepts
import colorsys def ncolors(levels): """Generate len(levels) colors with darker-to-lighter variants for each color Args: levels(list): List with one element per required color. Element indicates number of variants for that color Returns: List of lists with variants for each rgb color hue """ n = len(levels) def rgb2hex(rgb): return '#%02x%02x%02x' % rgb def hls2hex(h, l, s): return rgb2hex( tuple([int(x*255) for x in colorsys.hsv_to_rgb(h, l, s)])) colors = [] for x in range(n): colors.append([]) nlevels = levels[x] saturation_step = 1/(nlevels + 1) for l in range(nlevels): hsv_triple = (x*1.0/n, saturation_step*(l+1), 0.5) colors[x].append(hls2hex(*hsv_triple)) return colors
bigcode/self-oss-instruct-sc2-concepts
def compileStatus(lOutput, iWarning, iCritical, sFilesystem): """ compiles OK/WARNING/CRITICAL/UNKNOWN status gets: lOutput : list of dicts for each Disk iWarning : warning threshold iCritical : critical threshold sFilesystem: filesystem which to compare iWarning and iCritical against returns: OK/WARNING/CRITICAL/UNKNOWN """ for dPartition in lOutput: if sFilesystem == dPartition['sName'] or sFilesystem == dPartition['sMountpoint']: if dPartition['iPercent'] >= iCritical: return('CRITICAL') elif dPartition['iPercent'] >= iWarning: return('WARNING') elif dPartition['iPercent'] < iCritical and dPartition['iPercent'] < iWarning: return('OK') else: return('UNKNOWN')
bigcode/self-oss-instruct-sc2-concepts
def get_entities_filter(search_entities): """Forms filter dictionary for search_entities Args: search_entities (string): entities in search text Returns: dict: ES filter query """ return { "nested": { "path": "data.entities", "filter":{ "bool":{ "should": [ { "terms": { "data.entities.screen_name": search_entities } }, { "terms": { "data.entities.name": search_entities } } ] } } } }
bigcode/self-oss-instruct-sc2-concepts
import math def rect(r, theta): """ theta in degrees returns tuple; (float, float); (x,y) """ x = r * math.cos(math.radians(theta)) y = r * math.sin(math.radians(theta)) return x, y
bigcode/self-oss-instruct-sc2-concepts
def task_update() -> dict: """Update existing message catalogs from a *.pot file.""" return { "actions": [ "pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l en", "pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l ru", ], "task_dep": ['extract'], "file_dep": ['shooter/po/shooter.pot'], "clean": True, }
bigcode/self-oss-instruct-sc2-concepts
def _json_force_object(v): """Force a non-dictionary object to be a JSON dict object""" if not isinstance(v, dict): v = {'payload': v} return v
bigcode/self-oss-instruct-sc2-concepts
def erbs2hz(erbs): """ Convert values in Equivalent rectangle bandwidth (ERBs) to values in Hertz (Hz) Parameters from [1] Args: erbs (float): real number in ERBs Returns: hz (float): real number in Hertz References: [1] Camacho, A., & Harris, J. G. (2008). A sawtooth waveform inspired pitch estimator for speech and music. The Journal of the Acoustical Society of America, 124(3), 1638–1652. https://doi.org/10.1121/1.2951592 """ hz = (2 ** ((erbs / 6.44) + 7.84)) - 229 return hz
bigcode/self-oss-instruct-sc2-concepts
def split_df_by_regions(df): """ Split the dataframe based on TotalUS, regions and sub-regions """ df_US = df[df.region == 'TotalUS'] regions = ['West', 'Midsouth', 'Northeast', 'SouthCentral', 'Southeast'] df_regions = df[df.region.apply(lambda x: x in regions and x != 'TotalUS')] df_subregions = df[df.region.apply(lambda x: x not in regions and x != 'TotalUS')] return df_US, df_regions, df_subregions
bigcode/self-oss-instruct-sc2-concepts
def is_week_day(the_date): """ Decides if the given date is a weekday. Args: the_date: Date object. The date to decide. Returns: Boolean. Whether the given date is a weekday. """ return the_date.isoweekday() in [1, 2, 3, 4, 5]
bigcode/self-oss-instruct-sc2-concepts
def path_in_book(path): """ A filter function that checks if a given path is part of the book. """ if ".ipynb_checkpoints" in str(path): return False if "README.md" in str(path): return False return True
bigcode/self-oss-instruct-sc2-concepts
from typing import List import posixpath def format_path(base: str, components: List[str]) -> str: """ Formats a base and http components with the HTTP protocol and the expected port. """ url = "http://{}:8000/".format(base) for component in components: url = posixpath.join(url, component) return url + "/" if url[-1] != "/" else url
bigcode/self-oss-instruct-sc2-concepts
def FV(pv:float, r:float, n:float, m = 1): """ FV(): A function to calculate Future Value. :param pv: Present Value :type pv: float :param r: Rate of Interest/Discount Rate (in decimals eg: 0.05 for 5%) :type r: float :param n: Number of Years :type n: float :param m: Frequency of Interest Calculation (eg: 2 for Semi-annually), defaults to 1. :type m: float :return: float, None for -ve values of m. :rtype: float -------- """ if(m<=0):return None return pv*((1+r/m)**(m*n))
bigcode/self-oss-instruct-sc2-concepts
def __equivalent_lists(list1, list2): """Return True if list1 and list2 contain the same items.""" if len(list1) != len(list2): return False for item in list1: if item not in list2: return False for item in list2: if item not in list1: return False return True
bigcode/self-oss-instruct-sc2-concepts
from typing import List import math def check_root(string: str) -> str: """ A function which takes numbers separated by commas in string format and returns the number which is a perfect square and the square root of that number. If string contains other characters than number or it has more or less than 4 numbers separated by comma function returns "incorrect input". If string contains 4 numbers but not consecutive it returns "not consecutive". :param string: :return: """ string_arr: List = string.split(',') if len(string_arr) != 4: return 'incorrect input' try: string_arr = list(int(char) for char in string_arr) except ValueError: return 'incorrect input' result: int = 1 for s in string_arr: result *= s result += 1 root: float = math.sqrt(result) if root % 1 == 0: return '{}, {}'.format(result, int(root)) else: return 'not consecutive'
bigcode/self-oss-instruct-sc2-concepts
def get_dictvalue_from_xpath(full_dict, path_string): """ get a value in a dict given a path's string """ key_value = full_dict for i in path_string.split('/')[1:] : key_value = key_value[i] return key_value
bigcode/self-oss-instruct-sc2-concepts
import re def extract_nterm_mods(seq): """ Extract nterminal mods, e.g. acA. Args: seq: str, peptide sequence Returns: ar-like, list of modifications """ # matches all nterminal mods, e.g. glD or acA nterm_pattern = re.compile(r'^([a-z]+)([A-Z])') mods = [] # test each sequence for non-AA letters for ii, seqi in enumerate(seq): nterm_match = re.findall(nterm_pattern, seqi) # nterminal acetylation if len(nterm_match) != 0: mods.append([nterm_match[0][0]]) return mods
bigcode/self-oss-instruct-sc2-concepts
def cubic_bezier(p0, p1, p2, p3, t): """ evaluate cubic bezier curve from p0 to p3 at fraction t for control points p1 and p2 """ return p0 * (1 - t)**3 + 3 * p1 * t*(1 - t)**2 + 3 * p2 * t**2*(1 - t) + p3 * t**3
bigcode/self-oss-instruct-sc2-concepts
def filter_results(results, filters, exact_match) -> list[dict]: """ Returns a list of results that match the given filter criteria. When exact_match = true, we only include results that exactly match the filters (ie. the filters are an exact subset of the result). When exact-match = false, we run a case-insensitive check between each filter field and each result. exact_match defaults to TRUE - this is to maintain consistency with older versions of this library. """ filtered_list = [] if exact_match: for result in results: # check whether a candidate result matches the given filters if filters.items() <= result.items(): filtered_list.append(result) else: filter_matches_result = False for result in results: for field, query in filters.items(): if query.casefold() in result[field].casefold(): filter_matches_result = True else: filter_matches_result = False break if filter_matches_result: filtered_list.append(result) return filtered_list
bigcode/self-oss-instruct-sc2-concepts
def fact(n): """Finding factorial iteratively""" if n == 1 or n == 0: return 1 result = 1 for i in range(n, 1, -1): result = result * i return result
bigcode/self-oss-instruct-sc2-concepts
def SignDotNetManifest(env, target, unsigned_manifest): """Signs a .NET manifest. Args: env: The environment. target: Name of signed manifest. unsigned_manifest: Unsigned manifest. Returns: Output node list from env.Command(). """ sign_manifest_cmd = ('@mage -Sign $SOURCE -ToFile $TARGET -TimestampUri ' 'http://timestamp.verisign.com/scripts/timstamp.dll ') if env.Bit('build_server'): # If signing fails with the following error, the hash may not match any # certificates: "Internal error, please try again. Object reference not set # to an instance of an object." sign_manifest_cmd += ('-CertHash ' + env['build_server_certificate_hash']) else: sign_manifest_cmd += '-CertFile %s -Password %s' % ( env.GetOption('authenticode_file'), env.GetOption('authenticode_password')) signed_manifest = env.Command( target=target, source=unsigned_manifest, action=sign_manifest_cmd ) return signed_manifest
bigcode/self-oss-instruct-sc2-concepts
def calc_gene_lens(coords, prefix=False): """Calculate gene lengths by start and end coordinates. Parameters ---------- coords : dict Gene coordinates table. prefix : bool Prefix gene IDs with nucleotide IDs. Returns ------- dict of dict Mapping of genes to lengths. """ res = {} for nucl, queue in coords.items(): for loc, is_start, _, gid in queue: if prefix: gid = f'{nucl}_{gid}' if is_start: res[gid] = 1 - loc else: res[gid] += loc return res
bigcode/self-oss-instruct-sc2-concepts
import torch def int_to_one_hot(class_labels, nb_classes, device, soft_target=1.): """ Convert tensor containing a batch of class indexes (int) to a tensor containing one hot vectors.""" one_hot_tensor = torch.zeros((class_labels.shape[0], nb_classes), device=device) for i in range(class_labels.shape[0]): one_hot_tensor[i, class_labels[i]] = soft_target return one_hot_tensor
bigcode/self-oss-instruct-sc2-concepts
def read_file(path: str) -> str: # pragma: nocover """ This function simply reads contents of the file. It's moved out to a function purely to simplify testing process. Args: path: File to read. Returns: content(str): Content of given file. """ return open(path).read()
bigcode/self-oss-instruct-sc2-concepts
def text_to_list(element, delimiter='|'): """ Receives a text and a delimiter Return a list of elements by the delimiter """ return element.split(delimiter)
bigcode/self-oss-instruct-sc2-concepts
def living_expenses(after_tax_income): """ Returns the yearly living expenses, which is 5% of the after tax income. :param after_tax_income: The yearly income after income tax. :return: The living expenses. """ return after_tax_income * 0.05
bigcode/self-oss-instruct-sc2-concepts
def comma_separated(xs): """Convert each value in the sequence xs to a string, and separate them with commas. >>> comma_separated(['spam', 5, False]) 'spam, 5, False' >>> comma_separated([5]) '5' >>> comma_separated([]) '' """ return ', '.join([str(x) for x in xs])
bigcode/self-oss-instruct-sc2-concepts
def dummy_category(create_category): """Create a mocked dummy category.""" return create_category(title='dummy')
bigcode/self-oss-instruct-sc2-concepts
def is_list_like(arg): """Returns True if object is list-like, False otherwise""" return (hasattr(arg, '__iter__') and not isinstance(arg, str))
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def extract_tracks(plist: Dict) -> List[Dict[str, str]]: """Takes a Dict loaded from plistlib and extracts the in-order tracks. :param plist: the xml plist parsed into a Dict. :returns: a list of the extracted track records. """ try: ordering = [ str(a["Track ID"]) for a in plist["Playlists"][0]["Playlist Items"] ] return [plist["Tracks"][track_id] for track_id in ordering] except KeyError: return []
bigcode/self-oss-instruct-sc2-concepts
import inspect def _source(obj): """ Returns the source code of the Python object `obj` as a list of lines. This tries to extract the source from the special `__wrapped__` attribute if it exists. Otherwise, it falls back to `inspect.getsourcelines`. If neither works, then the empty list is returned. """ try: return inspect.getsourcelines(obj.__wrapped__)[0] except: pass try: return inspect.getsourcelines(obj)[0] except: return []
bigcode/self-oss-instruct-sc2-concepts
import csv def precip_table_etl_cnrccep( ws_precip, rainfall_adjustment=1 ): """ Extract, Transform, and Load data from a Cornell Northeast Regional Climate Center Extreme Precipitation estimates csv into an array Output: 1D array containing 24-hour duration estimate for frequencies 1,2,5,10,25,50,100,200 years. Example: [5.207, 6.096, 7.5438, 8.8646, 10.9982, 12.9286, 15.2146, 17.907, 22.1996] """ precips = [] # Open the precipitation data csv and read all the precipitations out. with open(ws_precip) as g: input_precip= csv.reader(g) # Skip the first 10 rows of the csv, which are assorted header information. for j in range (1, 11): next(g) k=1 for row in input_precip: # Grab data from column containing 24-hour estimate P=float(row[10]) # convert to cm and adjust for future rainfall conditions (if rainfall_adjustment is > 1) precips.append(P*2.54*rainfall_adjustment) if k>8: break else: k=k+1 return precips
bigcode/self-oss-instruct-sc2-concepts
def find_9(s): """Return -1 if '9' not found else its location at position >= 0""" return s.split('.')[1].find('9')
bigcode/self-oss-instruct-sc2-concepts
def normalize_cov_type(cov_type): """ Normalize the cov_type string to a canonical version Parameters ---------- cov_type : str Returns ------- normalized_cov_type : str """ if cov_type == 'nw-panel': cov_type = 'hac-panel' if cov_type == 'nw-groupsum': cov_type = 'hac-groupsum' return cov_type
bigcode/self-oss-instruct-sc2-concepts
import json def parse_payload(payload): """Returns a dict of command data""" return json.loads(payload.get('data').decode())
bigcode/self-oss-instruct-sc2-concepts
from typing import List def uniform_knot_vector(count: int, order: int, normalize=False) -> List[float]: """ Returns an uniform knot vector for a B-spline of `order` and `count` control points. `order` = degree + 1 Args: count: count of control points order: spline order normalize: normalize values in range [0, 1] if ``True`` """ if normalize: max_value = float(count + order - 1) else: max_value = 1.0 return [knot_value / max_value for knot_value in range(count + order)]
bigcode/self-oss-instruct-sc2-concepts
def process_mmdet_results(mmdet_results, cat_id=1): """Process mmdet results, and return a list of bboxes. :param mmdet_results: :param cat_id: category id (default: 1 for human) :return: a list of detected bounding boxes """ if isinstance(mmdet_results, tuple): det_results = mmdet_results[0] else: det_results = mmdet_results bboxes = det_results[cat_id - 1] person_results = [] for bbox in bboxes: person = {} person['bbox'] = bbox person_results.append(person) return person_results
bigcode/self-oss-instruct-sc2-concepts
def get_top_header(table, field_idx): """ Return top header by field header index. :param table: Rendered table (dict) :param field_idx: Field header index (int) :return: dict or None """ tc = 0 for th in table['top_header']: tc += th['colspan'] if tc > field_idx: return th
bigcode/self-oss-instruct-sc2-concepts
def incident_related_resource_data_to_xsoar_format(resource_data, incident_id): """ Convert the incident relation from the raw to XSOAR format. :param resource_data: (dict) The related resource raw data. :param incident_id: The incident id. """ properties = resource_data.get('properties', {}) formatted_data = { 'ID': properties.get('relatedResourceName'), 'Kind': properties.get('relatedResourceKind'), 'IncidentID': incident_id } return formatted_data
bigcode/self-oss-instruct-sc2-concepts
import torch def is_gpu_available() -> bool: """Check if GPU is available Returns: bool: True if GPU is available, False otherwise """ return torch.cuda.is_available()
bigcode/self-oss-instruct-sc2-concepts
def find_ingredients_graph_leaves(product): """ Recursive function to search the ingredients graph and find its leaves. Args: product (dict): Dict corresponding to a product or a compound ingredient. Returns: list: List containing the ingredients graph leaves. """ if 'ingredients' in product: leaves = [] for ingredient in product['ingredients']: subleaves = find_ingredients_graph_leaves(ingredient) if type(subleaves) == list: leaves += subleaves else: leaves.append(subleaves) return leaves else: return product
bigcode/self-oss-instruct-sc2-concepts
def getPathName(path): """Get the name of the final entity in C{path}. @param path: A fully-qualified C{unicode} path. @return: The C{unicode} name of the final element in the path. """ unpackedPath = path.rsplit(u'/', 1) return path if len(unpackedPath) == 1 else unpackedPath[1]
bigcode/self-oss-instruct-sc2-concepts
import pipes def shell_join(command): """Return a valid shell string from a given command list. >>> shell_join(['echo', 'Hello, World!']) "echo 'Hello, World!'" """ return ' '.join([pipes.quote(x) for x in command])
bigcode/self-oss-instruct-sc2-concepts
def gen_fasta2phy_cmd(fasta_file, phylip_file): """ Returns a "fasta2phy" command <list> Input: fasta_file <str> -- path to fasta file phylip_file <str> -- path to output phylip file """ return ['fasta2phy', '-i', fasta_file, '-o', phylip_file]
bigcode/self-oss-instruct-sc2-concepts
import re def strip_multi_value_operators(string): """The Search API will parse a query like `PYTHON OR` as an incomplete multi-value query, and raise an error as it expects a second argument in this query language format. To avoid this we strip the `AND` / `OR` operators tokens from the end of query string. This does not stop a valid multi value query executing as expected. """ # the search API source code lists many operators in the tokenNames # iterable, but it feels cleaner for now to explicitly name only the ones # we are interested in here if string: string = re.sub(r'^(OR|AND)', '', string) string = re.sub(r'(OR|AND)$', '', string) string = string.strip() return string
bigcode/self-oss-instruct-sc2-concepts
def get_nodes(database): """Get all connected nodes as a list of objects with node_id and node_label as elements""" results = list(database["nodes"].find()) nodes = [] for node in results: nodes.append({"id": node["_id"], "description": node["label"]}) return nodes
bigcode/self-oss-instruct-sc2-concepts
import re def extract_code(text): """ Extracts the python code from the message Return value: (success, code) success: True if the code was found, False otherwise code: the code if success is True, None otherwise """ regex = r"(?s)```(python)?(\n)?(.*?)```" match = re.search(regex, text) if match: return (True, match.group(3)) else: return (False, None)
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import Mock def get_discovered_bridge(bridge_id="aabbccddeeff", host="1.2.3.4", supports_v2=False): """Return a mocked Discovered Bridge.""" return Mock(host=host, id=bridge_id, supports_v2=supports_v2)
bigcode/self-oss-instruct-sc2-concepts
def host_get_id(host): """ Retrieve the host id """ return host['id']
bigcode/self-oss-instruct-sc2-concepts
def is_nds_service(network_data_source): """Determine if the network data source points to a service. Args: network_data_source (network data source): Network data source to check. Returns: bool: True if the network data source is a service URL. False otherwise. """ return bool(network_data_source.startswith("http"))
bigcode/self-oss-instruct-sc2-concepts
def opacity(token): """Validation for the ``opacity`` property.""" if token.type == 'number': return min(1, max(0, token.value))
bigcode/self-oss-instruct-sc2-concepts
def get_default_alignment_parameters(adjustspec): """ Helper method to extract default alignment parameters as passed in spec and return values in a list. for e.g if the params is passed as "key=value key2=value2", then the returned list will be: ["key=value", "key2=value2"] """ default_alignment_parameters = [] if ( "defaultAlignmentParams" in adjustspec and adjustspec["defaultAlignmentParams"] is not None ): default_alignment_parameters = adjustspec["defaultAlignmentParams"].split() return default_alignment_parameters
bigcode/self-oss-instruct-sc2-concepts
def goldstein_price(x): """ Goldstein-Price function (2-D). Global Optimum: 3.0 at (0.0, -1.0). Parameters ---------- x : array 2 x-values. `len(x)=2`. `x[i]` bound to [-2, 2] for i=1 and 2. Returns ------- float Value of Goldstein-Price function. """ x1 = x[0] x2 = x[1] u1 = (x1 + x2 + 1.0)**2 u2 = 19. - 14.*x1 + 3.*x1**2 - 14.*x2 + 6.*x1*x2 + 3.*x2**2 u3 = (2.*x1 - 3.*x2)**2 u4 = 18. - 32.*x1 + 12.*x1**2 + 48.*x2 - 36.*x1*x2 + 27.*x2**2 u5 = u1 * u2 u6 = u3 * u4 f = (1. + u5) * (30. + u6) return f
bigcode/self-oss-instruct-sc2-concepts
def get_titles(_stories): """ function extract titles from received stories :param _stories: list of stories including story title, link, unique id, published time :return: list of titles """ # Get the stories titles titles = [] for story in _stories: titles.append(story['title']) return titles
bigcode/self-oss-instruct-sc2-concepts
def rgbToHex(rgb: tuple[int, int, int]) -> str: """ convert rgb tuple to hex """ return "#{0:02x}{1:02x}{2:02x}".format(rgb[0], rgb[1], rgb[2])
bigcode/self-oss-instruct-sc2-concepts
def make_sleep_profile_colnames(df): """ Create list of ordered column names for dataframe to be created from sleep_profile dictionary """ colnames = ['Time'] for i in range(11,16): colnames.append(df.columns[i] + ' MR Sum') colnames.append(df.columns[i] + ' Avg Sleep') colnames.append(df.columns[i] + ' Beam Breaks') return colnames
bigcode/self-oss-instruct-sc2-concepts
def nice_column_names(df): """Convenience function to convert standard names from BigQuery to nice names for plotting""" cols = [ ('Open Access (%)', 'percent_OA'), ('Open Access (%)', 'percent_oa'), ('Open Access (%)', 'percent_total_oa'), ('Total Green OA (%)', 'percent_green'), ('Total Gold OA (%)', 'percent_gold'), ('Gold in DOAJ (%)', 'percent_gold_just_doaj'), ('Hybrid OA (%)', 'percent_hybrid'), ('Bronze (%)', 'percent_bronze'), ('Total Green OA (%)', 'percent_green'), ('Green Only (%)', 'percent_green_only'), ('Green in IR (%)', 'percent_green_in_home_repo'), ('Total Publications', 'total'), ('Change in Open Access (%)', 'total_oa_pc_change'), ('Change in Green OA (%)', 'green_pc_change'), ('Change in Gold OA (%)', 'gold_pc_change'), ('Change in Total Publications (%)', 'total_pc_change'), ('Year of Publication', 'published_year'), ('University Name', 'name'), ('Region', 'region'), ('Country', 'country'), ('Citation Count', 'total_citations'), ('Cited Articles', 'cited_articles'), ('Citations to OA Outputs', 'oa_citations'), ('Citations to Gold Outputs', 'gold_citations'), ('Citations to Green Outputs', 'green_citations'), ('Citations to Hybrid Outputs', 'hybrid_citations'), ('Total Outputs', 'total'), ('Journal Articles', 'journal_articles'), ('Proceedings', 'proceedings_articles'), ('Books', 'authored_books'), ('Book Sections', 'book_sections'), ('Edited Volumes', 'edited_volumes'), ('Reports', 'reports'), ('Datasets', 'datasets') ] for col in cols: if col[1] in df.columns.values: df[col[0]] = df[col[1]] return df
bigcode/self-oss-instruct-sc2-concepts
def calculate_FCF(r, T): """ Calculate FCF from given information :param r: Is the rate of inflation :param T: Is the time in years :return: No units cost factor """ r = r / 100 den = r * ((1 + r) ** T) num = ((1 + r) ** T) - 1 return den / num
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def write_sqlite_file(plants_dict, filename, return_connection=False): """ Write database into sqlite format from nested dict. Parameters ---------- plants_dict : dict Has the structure inherited from <read_csv_file_to_dict>. filename : str Output filepath; should not exist before function call. return_connection : bool (default False) Whether to return an active database connection. Returns ------- conn: sqlite3.Connection Only returned if `return_connection` is True. Raises ------ OSError If SQLite cannot make a database connection. sqlite3.Error If database has already been populated. """ try: conn = sqlite3.connect(filename) except: raise OSError('Cannot connect to {0}'.format(filename)) conn.isolation_level = None # faster database insertions c = conn.cursor() try: c.execute('''CREATE TABLE powerplants ( country TEXT, country_long TEXT, name TEXT, gppd_idnr TEXT UNIQUE NOT NULL, capacity_mw REAL, latitude REAL, longitude REAL, primary_fuel TEXT, other_fuel1 TEXT, other_fuel2 TEXT, other_fuel3 TEXT, commissioning_year TEXT, owner TEXT, source TEXT, url TEXT, geolocation_source TEXT, wepp_id TEXT, year_of_capacity_data INTEGER, generation_gwh_2013 REAL, generation_gwh_2014 REAL, generation_gwh_2015 REAL, generation_gwh_2016 REAL, generation_gwh_2017 REAL, generation_data_source TEXT, estimated_generation_gwh REAL )''') except: raise sqlite3.Error('Cannot create table "powerplants" (it might already exist).') c.execute('begin') for k, p in plants_dict.iteritems(): stmt = u'''INSERT INTO powerplants VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''' vals = ( p['country'], p['country_long'], p['name'], p['gppd_idnr'], p['capacity_mw'], p['latitude'], p['longitude'], p['primary_fuel'], p['other_fuel1'], p['other_fuel2'], p['other_fuel3'], p['commissioning_year'], p['owner'], p['source'], p['url'], p['geolocation_source'], p['wepp_id'], p['year_of_capacity_data'], p['generation_gwh_2013'], p['generation_gwh_2014'], p['generation_gwh_2015'], p['generation_gwh_2016'], p['generation_gwh_2017'], p['generation_data_source'], p['estimated_generation_gwh']) c.execute(stmt, vals) c.execute('commit') index_stmt = '''CREATE INDEX idx_country ON powerplants (country)''' c.execute(index_stmt) if return_connection: return conn else: conn.close()
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def determine_sentence_speaker(chunk): """ Validate for a chunk of the transcript (e.g. sentence) that there is one speaker. If not, take a majority vote to decide the speaker """ speaker_ids = [ word[3] for word in chunk ] if len(set(speaker_ids)) != 1: print("Multiple speakers within one sentence:\n", chunk ) return Counter(speaker_ids).most_common(1)[0] return chunk[0][3]
bigcode/self-oss-instruct-sc2-concepts
import random def random_liste(count): """ Returning a list containing 'count' no. of elements with random values between 0 and 100 (both inclusive) """ #Return a list of len 'count', with random numbers from 0..100 return [random.randint(0, 100) for _ in range(count)]
bigcode/self-oss-instruct-sc2-concepts
def linear(interval, offset=0): """Creates a linear schedule that tracks when ``{offset + n interval | n >= 0}``. Args: interval (int): The regular tracking interval. offset (int, optional): Offset of tracking. Defaults to 0. Returns: callable: Function that given the global_step returns whether it should track. """ docstring = "Track at iterations {" + f"{offset} + n * {interval} " + "| n >= 0}." def schedule(global_step): shifted = global_step - offset if shifted < 0: return False else: return shifted % interval == 0 schedule.__doc__ = docstring return schedule
bigcode/self-oss-instruct-sc2-concepts
def _is_valid_sub_path(path, parent_paths): """ Check if a sub path is valid given an iterable of parent paths. :param (tuple[str]) path: The path that may be a sub path. :param (list[tuple]) parent_paths: The known parent paths. :return: (bool) Examples: * ('a', 'b', 'c') is a valid subpath of ('a', ) * ('a', 'd') is not a valid subpath of ('b', ) * ('a', ) is not a valid subpath of ('a', 'b') * ('anything',) is a valid subpath of () """ if not parent_paths: return True for parent_path in parent_paths: if path[:len(parent_path)] == parent_path: return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_valid_loss(model, valid_iter, criterion): """ Get the valid loss :param model: RNN classification model :type model: :param valid_iter: valid iterator :type valid_iter: data.BucketIterator :param criterion: loss criterion :type criterion: nn.CrossEntropyLoss :return: valid loss :rtype: Tensor(shape=[]) """ batch = next(iter(valid_iter)) model.eval() logits = model(batch.text) label = batch.label.type("torch.LongTensor") loss = criterion(logits, label) return loss
bigcode/self-oss-instruct-sc2-concepts
def clean(string): """ Cleans the string by making the case uniform and removing spaces. """ if string: return string.strip().lower() return ''
bigcode/self-oss-instruct-sc2-concepts
def formatFloat(number, decimals=0): """ Formats value as a floating point number with decimals digits in the mantissa and returns the resulting string. """ if decimals <= 0: return "%f" % number else: return ("%." + str(decimals) + "f") % number
bigcode/self-oss-instruct-sc2-concepts
def deserialize_tuple(d): """ Deserializes a JSONified tuple. Args: d (:obj:`dict`): A dictionary representation of the tuple. Returns: A tuple. """ return tuple(d['items'])
bigcode/self-oss-instruct-sc2-concepts
def plan_window(plan, ending_after, starting_before): """ Return list of items in the given window. """ window_tasks = [] for task in plan: if ending_after < task['end'] and task['start'] < starting_before: window_tasks.append(task) return window_tasks
bigcode/self-oss-instruct-sc2-concepts
def helper(A, k, left, right): """binary search of k in A[left:right], return True if found, False otherwise""" print(f'so far ==> left={left}, right={right}, k={k}, A={A}') #1- base case if left > right: # if empty list there is nothing to search return False #2- solve the subproblems mid = (right - left)//2 + left if A[mid] < k: left = mid + 1 # -> search right return helper(A, k, left, right) elif A[mid] > k: right = mid - 1 # -> search left return helper(A, k, left, right) else: return True #3- combine the sub-solutions # nothing to combine --> tail recursion(stay tunned for more)
bigcode/self-oss-instruct-sc2-concepts
def override(left, right, key, default): """Returns right[key] if exists, else left[key].""" return right.get(key, left.get(key, default))
bigcode/self-oss-instruct-sc2-concepts
def delete_fit_attrs(est): """ Removes any fit attribute from an estimator. """ fit_keys = [k for k in est.__dict__.keys() if k.endswith('_')] for k in fit_keys: del est.__dict__[k] return est
bigcode/self-oss-instruct-sc2-concepts
def retrieve_arguments(args): """ Further parses arguments from CLI based on type and constructs concise object containing the parameters that will dictate behavior downstream :param args - arguments retrieved from call to parser.parse_args as part of argparse library :returns dictionary containing all arguments from CLI """ # Retrieve the arguments parsed from CLI countries = args.countries.upper().split(",") states = args.states.upper().split(",") cities = args.cities.upper().split(",") age_group = args.age_group.upper().split(",") summarize_by_age_group = args.by_age summarize_by_country = args.by_country summarize_by_state = args.by_state summarize_by_city = args.by_city reset_db = args.reset # Combine them all together in one object to dictate behavior downstream argument_map = { "countries": countries, "states": states, "cities": cities, "age_group": age_group, "summarize_by": { "age": summarize_by_age_group, "country": summarize_by_country, "state": summarize_by_state, "city": summarize_by_city }, "reset_db": reset_db } return argument_map
bigcode/self-oss-instruct-sc2-concepts
def set_voltage(channel: int, value: float): """ Sets voltage on channel to the value. """ return f"VSET{channel}:{value}"
bigcode/self-oss-instruct-sc2-concepts
def split_name(name): """ Split a name in two pieces: first_name, last_name. """ parts = name.split(' ') if len(parts) == 4 and parts[2].lower() not in ('de', 'van'): first_name = ' '.join(parts[:2]) last_name = ' '.join(parts[2:]) else: first_name = parts[0] last_name = ' '.join(parts[1:]) return first_name.strip(), last_name.strip()
bigcode/self-oss-instruct-sc2-concepts
def jaccard_distance(text1, text2): """ Measure the jaccard distance of two different text. ARGS: text1,2: list of tokens RETURN: score(float): distance between two text """ intersection = set(text1).intersection(set(text2)) union = set(text1).union(set(text2)) return 1 - len(intersection) / len(union)
bigcode/self-oss-instruct-sc2-concepts
def chunks(_list, n): """ Return n-sized chunks from a list. Args: _list - A list of elements. n - Number defining the size of a chunk. Returns: A list of n-sized chunks. """ return list(map(lambda i: _list[i:i + n], range(0, len(_list), n)))
bigcode/self-oss-instruct-sc2-concepts
def objective_rule(model): """ Maximize the sum of all rewards of activities that are 'picked' (selected) """ return sum(model.CHILD_ALLOCATED[cr, ca] * model.child_score[ca] for (cr, ca) in model.cr_ca_arcs)
bigcode/self-oss-instruct-sc2-concepts
def remove_spaces(string): """ Remove triple/double and leading/ending spaces """ while ' ' in string: string = string.replace(' ', ' ') return string.strip()
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Optional from pathlib import Path def check_for_project(path: Union[str, "Path"] = ".") -> Optional["Path"]: """Checks for a Brownie project.""" path = Path(path).resolve() for folder in [path] + list(path.parents): if folder.joinpath("brownie-config.json").exists(): return folder return None
bigcode/self-oss-instruct-sc2-concepts
import colorsys def lighten_rgb(rgb, times=1): """Produce a lighter version of a given base colour.""" h, l, s = colorsys.rgb_to_hls(*rgb) mult = 1.4**times hls_new = (h, 1 - (1 - l) / mult, s) return colorsys.hls_to_rgb(*hls_new)
bigcode/self-oss-instruct-sc2-concepts
def recursive_length(item): """Recursively determine the total number of elements in nested list.""" if type(item) == list: return sum(recursive_length(subitem) for subitem in item) else: return 1.
bigcode/self-oss-instruct-sc2-concepts
from typing import List def numeric_binary_search(ordered_numbers: List[int], search: int) -> int: """Simple numeric binary search Args: ordered_numbers(List[int]): an ordered list of numbers search(int): number to find Returns: int: found index or -1 """ assert isinstance(ordered_numbers, list), 'ordered_numbers Must be a list' assert isinstance(search, int), 'Search must be int' lowest_index = 0 highest_index = len(ordered_numbers) - 1 intermediate_index = highest_index // 2 while lowest_index <= highest_index: actual_value = ordered_numbers[intermediate_index] if actual_value == search: return intermediate_index if actual_value < search: lowest_index = intermediate_index + 1 if actual_value > search: highest_index = intermediate_index - 1 intermediate_index = (highest_index + lowest_index) // 2 return -1
bigcode/self-oss-instruct-sc2-concepts
import random def get_randints(lower, upper, exclude): """Generate a set of unique random numbers in a range (inclusive).""" numbers = [i for i in range(lower, upper, 1)] numbers.remove(exclude) random.shuffle(numbers) return numbers
bigcode/self-oss-instruct-sc2-concepts
def knot_insertion_alpha(u, knotvector, span, idx, leg): """ Computes :math:`\\alpha` coefficient for knot insertion algorithm. :param u: knot :type u: float :param knotvector: knot vector :type knotvector: tuple :param span: knot span :type span: int :param idx: index value (degree-dependent) :type idx: int :param leg: i-th leg of the control points polygon :type leg: int :return: coefficient value :rtype: float """ return (u - knotvector[leg + idx]) / (knotvector[idx + span + 1] - knotvector[leg + idx])
bigcode/self-oss-instruct-sc2-concepts
def pearsonchisquare(counts): """ Calculate Pearson's χ² (chi square) test for an array of bytes. See [http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test #Discrete_uniform_distribution] Arguments: counts: Numpy array of counts. Returns: χ² value """ np = sum(counts) / 256 return sum((counts - np)**2 / np)
bigcode/self-oss-instruct-sc2-concepts
def common_shape(imgs, axis): """ Find smallest height or width of all images. The value along `axis` will be `None`, the other will be the smallest of all values Args: imgs (list[np.array]): list of images axis (int): axis images will be concatenated along Returns: tuple(int): height, width """ if axis == 0: ws = [img.shape[1] for img in imgs] return (None, min(ws)) hs = [img.shape[0] for img in imgs] return (min(hs), None)
bigcode/self-oss-instruct-sc2-concepts
def convert_image(img, coefs): """Sum up image channels with weights from coefs array input: img -- 3-d numpy array (H x W x 3) coefs -- 1-d numpy array (length 3) output: img -- 2-d numpy array Not vectorized implementation. """ x = img.shape[0] y = img.shape[1] res = [[0 for i in range(y)] for j in range(x)] for i in range(x): for j in range(y): for k in range(3): res[i][j] += img[i][j][k] * coefs[k] return res pass
bigcode/self-oss-instruct-sc2-concepts
def build_context(query, query_config): """Build context based on query config for plugin_runner. Why not pass QueryExecConfig to plugins directly? Args: query (str) query_config (QueryExecConfig) Returns: dict str -> str """ context = vars(query_config) context['query'] = query return context
bigcode/self-oss-instruct-sc2-concepts
def index_to_coordinates(string, index): """ Returns the corresponding tuple (line, column) of the character at the given index of the given string. """ if index < 0: index = index % len(string) sp = string[:index+1].splitlines(keepends=True) return len(sp), len(sp[-1])
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def binary_str_to_decimal(chars: Iterable[str]) -> int: """ Converts binary string to decimal number. >>> binary_str_to_decimal(['1', '0', '1']) 5 >>> binary_str_to_decimal('101010') 42 """ return int("".join(chars), base=2)
bigcode/self-oss-instruct-sc2-concepts
def mean(num_list): """ Return the average of a list of number. Return 0.0 if empty list. """ if not num_list: return 0.0 else: return sum(num_list) / float(len(num_list))
bigcode/self-oss-instruct-sc2-concepts
import re def cnvt_to_var_name(s): """Convert a string to a legal Python variable name and return it.""" return re.sub(r"\W|^(?=\d)", "_", s)
bigcode/self-oss-instruct-sc2-concepts
def quick_sort(collection: list) -> list: """ A pure Python implementation of quick sort algorithm :param collection: a mutable collection of comparable items :return: the same collection ordered by ascending Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> quick_sort([]) [] >>> quick_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] """ if len(collection) < 2: return collection pivot = collection.pop() # Use the last element as the first pivot greater: list[int] = [] # All elements greater than pivot lesser: list[int] = [] # All elements less than or equal to pivot for element in collection: (greater if element > pivot else lesser).append(element) return quick_sort(lesser) + [pivot] + quick_sort(greater)
bigcode/self-oss-instruct-sc2-concepts
def pow2(x): """Return the square of x :param float x: input value :rtype: float """ return x*x
bigcode/self-oss-instruct-sc2-concepts