seed
stringlengths
1
14k
source
stringclasses
2 values
def is_pow2(n): """ Check whether a number is power of 2 Parameters ---------- n: int A positive integer number Returns ------- bool """ return n > 0 and ((n & (n - 1)) == 0) # Solution 2 # return math.log2(n) % 1 == 0
bigcode/self-oss-instruct-sc2-concepts
import difflib def gen_ndiff(a, b): """ Return a binary diff result of the byte sequence as a YARA signature. :param list a: First buffer representing code block as hexlified bytes. :param list b: Second buffer representing code block as hexlified bytes. :return: YARA compliant hex string sequen...
bigcode/self-oss-instruct-sc2-concepts
def allocated_size(allocation_unit, requested_size): """ Round ``requested_size`` up to the nearest ``allocation_unit``. :param int allocation_unit: The interval in ``bytes`` to which ``requested_size`` will be rounded up. :param int requested_size: The size in ``bytes`` that is required. :...
bigcode/self-oss-instruct-sc2-concepts
def rotate_word(s, r): """ Rotate each char in a string by through the alphabet by the given amount. Wrap around to the beginning (if necessary). """ r_s = '' for c in s: num = ord(c) r_num = num + r r_c = chr(r_num) r_s += r_c return r_s
bigcode/self-oss-instruct-sc2-concepts
def default_cmdline_options(config): """ Return default command line options required for every run of terraform. Args: config: dictionary containing all variable settings required to run terraform with Returns: cmdline_options: list of command-line arguments to run ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def utcnow_timestamp_ms() -> int: """UTC timestamp in milliseconds. Returns: timestamp (int): UTC time in milliseconds """ return int(datetime.utcnow().timestamp() * 1000)
bigcode/self-oss-instruct-sc2-concepts
def time_string(seconds): """Returns time in seconds as a string formatted HHHH:MM:SS.""" s = int(round(seconds)) # round to nearest second h, s = divmod(s, 3600) # get hours and remainder m, s = divmod(s, 60) # split remainder into minutes and seconds return "%2i:%02i:%02i" % (h, m, s)
bigcode/self-oss-instruct-sc2-concepts
def get_input_output_filenames_from_args(args): """Return strings inserted to input and output filenames.""" input_filename = args.input_filename output_filename = args.output_filename if args.input_output_filename is not None: input_filename = args.input_output_filename output_filename ...
bigcode/self-oss-instruct-sc2-concepts
def humanise_seconds(seconds): """ Takes `seconds` as an integer and returns a human readable string, e.g. "2 hours, 5 minutes". """ units = [] unit_table = [('hour', 3600), ('minute', 60)] for unit in unit_table: quotient, seconds = divmod(seconds, unit[1]) if quotient: ...
bigcode/self-oss-instruct-sc2-concepts
def v_str(v_tuple): """turn (2,0,1) into '2.0.1'.""" return ".".join(str(x) for x in v_tuple)
bigcode/self-oss-instruct-sc2-concepts
def suffix_opt(opt_arg=''): """ return suffix for backup file """ suffix = '' if len(opt_arg) != 0: suffix = '.' + opt_arg return suffix
bigcode/self-oss-instruct-sc2-concepts
import itertools def nonzero_entries(array, eps=1e-7): """Extracts sparse [(value, *indices), ...] array representation. Args: array: The numpy array to obtain a sparse representation for, eps: Threshold magnitude. Entries <= `eps` are skipped. Returns: List of (coefficient, index0, ..., indexN) tu...
bigcode/self-oss-instruct-sc2-concepts
def flatten_batch_X(X): """ Flattens images """ return X.reshape(len(X), -1)
bigcode/self-oss-instruct-sc2-concepts
def read_mol_dict(file): """ Read dict of molecules from file. Returns ------- molecules : :class:`dict` of :class:`dict` Dictionary of molecule definitions with `key` = name. """ with open(file, 'r') as f: lines = f.readlines() molecules = {} for line in lines: ...
bigcode/self-oss-instruct-sc2-concepts
from json import load import logging def read_json(filename): """ Reads input from a JSON file and returns the contents. :param str filename: Path to JSON file to read :return: Contents of the JSON file :rtype: dict or None """ try: with open(filename) as json_file: re...
bigcode/self-oss-instruct-sc2-concepts
import re def filter_location(location): """ (str) -> str Filter input string from such characters as parentheses and blank symbols >>> filter_location("United Kingdom {(UK)}") 'United Kingdom' """ location = re.sub("[(].*?[)]", "", location) location = re.sub("[{].*?[}]", "", location...
bigcode/self-oss-instruct-sc2-concepts
def serialize_primitive(obj, spec, ctx): """ Serialize a primitive value. """ return ctx.dumpval('', obj)
bigcode/self-oss-instruct-sc2-concepts
def assert_interrupt_signal(library, session, mode, status_id): """Asserts the specified interrupt or signal. Corresponds to viAssertIntrSignal function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param mode: How...
bigcode/self-oss-instruct-sc2-concepts
def build_reagent_vectors(portion_reagents, portion_chemicals): """Write the reagents in a vector form, where the vectors live in the complete portion basis The basis is spanned by all chemicals in all reagents in the portion (sans solvent) :param portion_reagents: a list of all reagents in the portion ...
bigcode/self-oss-instruct-sc2-concepts
def translate(tile, offset): """ Move a tile. This returns a moved copy; the original is unchaged. Parameters ---------- tile : tuple containing y and x slice objects offset : tuple translation, given as ``(y, x)`` Returns ------- tile : tuple a copy; the in...
bigcode/self-oss-instruct-sc2-concepts
def get_finegrained_count(text, gender_dct): """ Count the number of female, male, and neutral gendered words in a string, given the gender dict. """ text = text.lower() f_count = 0 m_count = 0 n_count = 0 for line in text.split('\n'): words = line.split(' ') for word...
bigcode/self-oss-instruct-sc2-concepts
def to_dict(X): """Make dict-like. Parameters ---------- X : dict """ if hasattr(X, "items"): return X elif X is None: return {None: None} else: return {None: X}
bigcode/self-oss-instruct-sc2-concepts
def CommonChecks(input_api, output_api): """Presubmit checks run on both upload and commit. This is currently limited to pylint. """ checks = [] blimp_tools_dir = input_api.PresubmitLocalPath() def J(*dirs): """Returns a path relative to presubmit directory.""" return input_api.os_path.join(blimp...
bigcode/self-oss-instruct-sc2-concepts
def decrypt(m,d,n): """ Returns decrypted message. Parameters: m (int): encrypted message d (int): private key n (int): modulus Output: decrypted message in numeral form """ return(pow(m,d,n))
bigcode/self-oss-instruct-sc2-concepts
def remove_padding(data: bytes, block_n_bytes: int) -> bytes: """Removes 0x80... padding according to NIST 800-38A""" if len(data) % block_n_bytes != 0: raise ValueError("Invalid data") for i in range(len(data) - 1, -1, -1): if data[i] == 0x80: return data[:i] elif data[...
bigcode/self-oss-instruct-sc2-concepts
def freq_wise_bmm(a, b): """ Parameters ---------- a: (..., n_freq, n_channels_1, n_channels_2) op 1 b: (..., n_channels_2, n_freq, n_frames) op 2 Returns ------- The batch matrix multiplication along the frequency axis, then flips the axis back Tensor of shape (...
bigcode/self-oss-instruct-sc2-concepts
import math def get_code_len(class_range, mode=0): """ Get encode length :param class_range: angle_range/omega :param mode: 0: binary label, 1: gray label :return: encode length """ if mode in [0, 1]: return math.ceil(math.log(class_range, 2)) else: raise Exception('On...
bigcode/self-oss-instruct-sc2-concepts
def mergesort(input_list): """ Takes in a list and splits it into halves recursively, then compares parts of the list to each other and merges them sorted into another list """ output = [] if len(input_list) > 1: mid = len(input_list) // 2 first_half = input_list[:mid] second...
bigcode/self-oss-instruct-sc2-concepts
def logical_right_shift(n: int , shifted_by: int)-> str: """ Take in 2 positive integers. 'n' is the integer to be logically right shifted 'shifted_by' times. i.e. (number >> shifted_by) Return the shifted binary representation. """ if n < 0 or shifted_by < 0: raise ValueError('The ...
bigcode/self-oss-instruct-sc2-concepts
def _first_label(label_list): """ Find first non-blank label """ llist = [lobj.get_text().strip() for lobj in label_list] for label_index, label_text in enumerate(llist): if label_text not in [None, '']: return label_index
bigcode/self-oss-instruct-sc2-concepts
import logging def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if not isinstance(number, int): logging.error("Invalid input type. Should be integer.") ...
bigcode/self-oss-instruct-sc2-concepts
import math def utilityY(c1,c2,rho): """Compute the utility of the young agents Args: c1 (float): consumption of the young generation c2 (float): consumption of the old generation rho (float): discount parameter Returns: (float): utilit...
bigcode/self-oss-instruct-sc2-concepts
import operator def _sortIssues(issues): """ Helper function from _formatIssues(). Sort a list of issues by issue number and then by comment creation date. GIVEN: issues (list) -- nested list of issues and their comments RETURN: new_issues (list) -- the given 'issues' list, but sorte...
bigcode/self-oss-instruct-sc2-concepts
def time_to_string(time: int) -> str: """Convert time to string representation Args: time (int): Time in seconds Returns: str: Time in MM:SS format """ if time < 0: raise ValueError("Negative integer not supported") return "%02d:%02d" % (time // 60, time % 60)
bigcode/self-oss-instruct-sc2-concepts
def rgb_hex_to_rgb_list(hex_string: str): """Return an RGB color value list from a hex color string.""" return [ int(hex_string[i: i + len(hex_string) // 3], 16) for i in range(0, len(hex_string), len(hex_string) // 3) ]
bigcode/self-oss-instruct-sc2-concepts
import binascii def bytes_to_hex(seq): """Converts seq from byte array to hex string""" return str(binascii.hexlify(bytes(seq)), 'ascii')
bigcode/self-oss-instruct-sc2-concepts
def check_inequality(left_version, right_op, right_version, **_): """ Checks for version compatibility when the dependency for 'left_version' has specified an explicitly disallowed version Args: left_version (packaging.version.Version): The version on the left side of the comparison...
bigcode/self-oss-instruct-sc2-concepts
def thermal_energy(particles): """ Returns the total internal energy of the (gas) particles in the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(2) >>> particles.u = [0.5, 0.5] | units.ms**2 >>> particles.mass = [1.0, 1.0] | units.kg >>> particles.th...
bigcode/self-oss-instruct-sc2-concepts
def ensure_existence(f): """ Ensures that method is not marked as non_existent Parameters ---------- f Method Raises ------ NotImplementedError if the method is marked as non existent Returns ------- Method f """ if getattr(f, 'not_existing', False): raise Not...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def get_evaluations(data: Dict[int, List[int]]) -> Dict[int, float]: """ Turns a dictionary with float lists into a dict with mean values. :param data: Input dictionary with float lists :return: Output dictionary with float mean values ...
bigcode/self-oss-instruct-sc2-concepts
def has_all_dims(dp_or_event, dims): """ Tests if `dims`'s are all in a certain datapoint or event """ return dims.items() <= {d.key: d.value for d in dp_or_event.dimensions}.items()
bigcode/self-oss-instruct-sc2-concepts
def compound_noun_list(token): """Find compound nouns. :param token: token for which to generate potential compound nouns :type token: :class:`spacy.token` :return: list of potential compounds :rtype: [string] """ nouns = [token.text] for nc in token.lefts: if nc.dep_ == "compou...
bigcode/self-oss-instruct-sc2-concepts
def find_num_player_in_group(group): """ find the number of players in a group :param group: A Group object :return: number of players in the group """ players = group.players.all() return (len(players))
bigcode/self-oss-instruct-sc2-concepts
import json async def _sendLambdaRequest(session, lambdaUrl, anomalyServiceObj): """ Async method to send anomaly detection request to lambda :param session: ClientSession instance for aiohttp :param lambdaUrl: AWS Lambda invocation endpoint :param anomalyServiceObject: Dict containing parameter d...
bigcode/self-oss-instruct-sc2-concepts
def csv_to_list(x): """Converts a comma separated string to a list of strings.""" return x.split(",")
bigcode/self-oss-instruct-sc2-concepts
def nbAlternatives(instance): """ Returns the number of alternatives of the instance. :param instance: The instance. :type instance: preflibtools.instance.preflibinstance.PreflibInstance :return: The number of alternatives of the instance. :rtype: int """ return instance.nbAlternatives
bigcode/self-oss-instruct-sc2-concepts
def do_selective_backprop( epoch: int, batch_idx: int, start_epoch: int, end_epoch: int, interrupt: int, ) -> bool: """Decide if selective backprop should be run based on time in training. Returns true if the current ``epoch`` is between ``start_epoch`` and ``end_epoch``. Recommend that...
bigcode/self-oss-instruct-sc2-concepts
def extract_CA_coords(helices, model, verbose=False): """get CA coordinates for rach residue in each helix input: helix list, each helix is list of its residues in format (chain, ('', resnum, '')) output: list of helices, each helix is list of CA coords (Biopython Vector class) of its residues """ print('Extracti...
bigcode/self-oss-instruct-sc2-concepts
import typing from pathlib import Path def valid_voice_dir(voice_dir: typing.Union[str, Path]) -> bool: """Return True if directory exists and has an onnx file""" voice_dir = Path(voice_dir) return voice_dir.is_dir() and (len(list(voice_dir.glob("*.onnx"))) > 0)
bigcode/self-oss-instruct-sc2-concepts
def get_most_sold_item(df): """Return a tuple of the name of the most sold item and the number of units sold""" most_sold_df = df.groupby(['Item'])['Units'].sum() return (most_sold_df.idxmax(), most_sold_df.loc[most_sold_df.idxmax()]) pass
bigcode/self-oss-instruct-sc2-concepts
def function1(a,b): """This is a function which will calculate average of two numbers.""" #docstrings average = (a+b)/2 #print(average) return average
bigcode/self-oss-instruct-sc2-concepts
def prc_rerouted(XMLDataFrame, XMLDataFrameRef): """ Compute the % of rerouted vehicles """ # diffPaths = pd.concat( # [XMLDataFrame["itineraire"], XMLDataFrameRef["itineraire"]] # ).drop_duplicates(keep=False) # nChangedPaths = diffPaths.count() # nGeneratedVeh = XMLDataFrameRe...
bigcode/self-oss-instruct-sc2-concepts
def _isLinked(self): """Return True if another record links to this record""" if len( self._inx.iref_by_sect[self.uid].a.keys() ) == 0: return False for k in self._inx.iref_by_sect[self.uid].a.keys(): if len( self._inx.iref_by_sect[self.uid].a[k] ) > 0: return True return False
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _md5_of_file(path): """Compute and return the MD5 sum of a flat file. The MD5 is returned as a hexadecimal string. """ md5 = hashlib.md5() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(4096), b''): md5.update(chunk) return md5.hexdigest(...
bigcode/self-oss-instruct-sc2-concepts
def read_file(filename) -> str: """Read the contents of the file into a string :param filename: path to the file to be read :return: string will contents of the file """ with open(filename, 'r', encoding='utf-8') as file_content: return file_content.read()
bigcode/self-oss-instruct-sc2-concepts
def query_successful(api_response): """This function reviews the API response from the Community API to verify whether or not the call was successful. :param api_response: The response from the API in JSON format :type api_response: dict :returns: Boolean indicating whether or not the API call was succ...
bigcode/self-oss-instruct-sc2-concepts
def crop_image_to_bounding_box(img, bnd_box): """Crops the given image to the given bounding box""" result = img[bnd_box[0][1] : bnd_box[1][1] + 1, bnd_box[0][0] : bnd_box[1][0] + 1] return result
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import secrets import hmac import hashlib def get_nonce_and_hash() -> Tuple[str, str]: """ Get a secure random nonce and a hmac of that nonce """ nonce: str = secrets.token_hex(32) nonce_hash: str = hmac.HMAC( bytes.fromhex(nonce), digestmod=hashlib.sha256 ).he...
bigcode/self-oss-instruct-sc2-concepts
import torch def accuracy(y_pred: torch.Tensor, y: torch.Tensor) -> float: """ Return predictive accuracy. Parameters --- y_pred: torch.Tensor (BATCH, NUM_CLASS) Predicted values. y: torch.Tensor (BATCH,) Real class values. """ return (y_pred.argmax(dim=1) == y).float(...
bigcode/self-oss-instruct-sc2-concepts
def min(self, parameter_min): """ It returns the minimum value of a parameter and the value's indexes. Parameters ---------- parameter_min: str Name of the parameter. Returns ------- min_dict: dict Dictionary with the following format: { ...
bigcode/self-oss-instruct-sc2-concepts
def estimate_fuse_passengers(fus_nb, FLOORS_NB, PASS_PER_TOILET, cabin_area,\ MASS_PASS, pass_density): """ The function evaluates the number of passengers members on board in case of an unconventional aircraft with fuselage. Source : passengers density is defined averaging...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import requests def google_oauth2_info() -> Dict: """Return Google's spec for their OAuth endpoints.""" resp = requests.get("https://accounts.google.com/.well-known/openid-configuration") info = resp.json() return info
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def events_v2_data(alert, routing_key, with_record=True): """Helper method to generate the payload to create an event using PagerDuty Events API v2 Args: alert (Alert): Alert relevant to the triggered rule routing_key (str): Routing key for this PagerDuty integr...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def dict_to_list(data: Dict[str, Dict]) -> List[Dict]: """Convert a dictionary to a list of 1-element dictionaries. """ return [{k: v} for k, v in data.items()]
bigcode/self-oss-instruct-sc2-concepts
def _rk12_step(func, y0, dt): """Improved Euler-Integration step to integrate dynamics. Args: func: Function handle to time derivative. y0: Current state. dt: Integration step. Returns: Next state. """ dy = func(y0) y_ = y0 + dt * dy return y0 + dt / 2. * (dy + func(y_))
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def fixture_fixtures_path() -> Path: """Path to dir with fixture files""" return Path("tests/fixtures")
bigcode/self-oss-instruct-sc2-concepts
def msg2dict(msg): """Convert a generic ROS message into a dictionary (un-nested) :param msg: ROS message to convert :rtype: dict """ return {k: getattr(msg, k) for k in msg.get_fields_and_field_types().keys()}
bigcode/self-oss-instruct-sc2-concepts
def srcds_functional(**filter_): """Enable SRCDS functional testing for a test case This decorator will cause the test case to be parametrised with addresses for Source servers as returned from the master server. The test case should request a fixture called ``address`` which is a two-item tuple of...
bigcode/self-oss-instruct-sc2-concepts
import difflib def get_close_matches_icase(word, possibilities, *args, **kwargs): """Case-insensitive version of difflib.get_close_matches""" lword = word.lower() lpos = {p.lower(): p for p in possibilities} lmatch = difflib.get_close_matches(lword, lpos.keys(), *args, **kwargs) return [lpos[m] fo...
bigcode/self-oss-instruct-sc2-concepts
def pascal2snake(string: str): """String Convert: PascalCase to snake_case""" return ''.join( word.title() for word in string.split('_') )
bigcode/self-oss-instruct-sc2-concepts
def data_classification_level(dsv): """Returns the data classification level of the calculated data sensitivity value.""" if dsv < 15: return 1 elif 15 <= dsv < 100: return 2 elif 100 <= dsv < 150: return 3 else: return 4
bigcode/self-oss-instruct-sc2-concepts
def apply_styles(graph, styles): """ Apply the styles to a Graphviz graph. """ graph.graph_attr.update( ('graph' in styles and styles['graph']) or {} ) graph.node_attr.update( ('nodes' in styles and styles['nodes']) or {} ) graph.edge_attr.update( ('edges' in styl...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_arrays(name): """Load arrays from file.""" with open(name, 'rb') as file: coords = pickle.load(file) edof = pickle.load(file) dofs = pickle.load(file) bdofs = pickle.load(file) elementmarkers = pickle.load(file) boundaryElements = pickle....
bigcode/self-oss-instruct-sc2-concepts
def read_translated_file(filename, data): """Read a file inserting data. Arguments: filename (str): file to read data (dict): dictionary with data to insert into file Returns: list of lines. """ if filename: with open(filename) as f: text = f.read().repl...
bigcode/self-oss-instruct-sc2-concepts
def not_better_than_after(minimal, n_iter): """Return a stop criterion that returns True if the error is not less than `minimal` after `n_iter` iterations.""" def inner(info): return info['n_iter'] > n_iter and info['loss'] >= minimal return inner
bigcode/self-oss-instruct-sc2-concepts
def int_or_None(val): """converter that casts val to int, or returns None if val is string 'None'""" if val == 'None': return None else: return int(val)
bigcode/self-oss-instruct-sc2-concepts
def create_test_partition(df, N_batch): """ Creates a partition of the dataset into a single test set. Parameters ---------- df : pandas dataframe Dataframe corresponding to the dataset. split_ratio : float Training sample percentage, must be between 0 and 1....
bigcode/self-oss-instruct-sc2-concepts
def dist_interval(v, mi, ma): """ Distance from v to interval [min,max] """ if v < mi: return mi - v if v > ma: return v - ma return 0
bigcode/self-oss-instruct-sc2-concepts
def prune_nones(mydict): """ Remove keys from `mydict` whose values are `None` :arg mydict: The dictionary to act on :rtype: dict """ # Test for `None` instead of existence or zero values will be caught return dict([(k, v) for k, v in mydict.items() if v != None and v != 'None'])
bigcode/self-oss-instruct-sc2-concepts
def str_to_act(env, actions): """ Simplifies specifying actions for the scripted part of the agent. Some examples for a string with a single action: 'craft:planks' 'camera:[10,0]' 'attack' 'jump' '' There should be no spaces in single actions, as we use spaces to ...
bigcode/self-oss-instruct-sc2-concepts
def namedModule(name): """ Return a module given its name. """ topLevel = __import__(name) packages = name.split(".")[1:] m = topLevel for p in packages: m = getattr(m, p) return m
bigcode/self-oss-instruct-sc2-concepts
def add_(string = ''): """ Add an _ if string is not empty """ s = '' if string: s = string + '_' return s
bigcode/self-oss-instruct-sc2-concepts
import json def load_json_schema(filename=None): """ Loads the given schema file """ if filename is None: return with open(filename) as schema_file: schema = json.loads(schema_file.read()) return schema
bigcode/self-oss-instruct-sc2-concepts
def proc_create_query(prname, prtext, argslist=None): """Base method for creating procedure with given name, body and args.""" prtext = prtext.replace("'", "''") TEMPLATE = """ CREATE OR REPLACE FUNCTION {prname}({argstext}) RETURNS VOID AS' {prtext}' LANGUAGE plpgsql; """ argstext =...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Optional import operator def _ensure_int(item: Any, item_name: Optional[str] = None) -> int: """Ensure a variable is an integer. Parameters ---------- item : Any Item to check. item_name : str | None Name of the item to show inside the err...
bigcode/self-oss-instruct-sc2-concepts
import socket def get_ip_hostname(node): """ Takes in either a hostname or an IP address and returns (ip, hostname). Note if IP is given both values will be the same, i.e. we don't actually care about finding the hostname if user specified an IP""" if '.' in node: return (node, node) ...
bigcode/self-oss-instruct-sc2-concepts
def Total_Dots(link): """ Function to calculate the Total Number of Dots in a URL """ dot='.' count=0 for i in link: if i==dot: count+=1 return count
bigcode/self-oss-instruct-sc2-concepts
def kappa_no_prevalence_calc(overall_accuracy): """ Calculate kappa no prevalence. :param overall_accuracy: overall accuracy :type overall_accuracy : float :return: kappa no prevalence as float """ try: result = 2 * overall_accuracy - 1 return result except Exception: ...
bigcode/self-oss-instruct-sc2-concepts
def wdwd_obj(X, y, W, C, beta, offset, eta): """ Objective function for DWD. """ d = y * (X.dot(beta) + offset) + eta return sum(W / d) + C * sum(eta)
bigcode/self-oss-instruct-sc2-concepts
def etree_to_dict(t): """Convert etree to dictionary""" d = {t.tag : map(etree_to_dict, t.iterchildren())} d.update(('@' + k, v) for k, v in t.attrib.iteritems()) d['text'] = t.text return d
bigcode/self-oss-instruct-sc2-concepts
from typing import BinaryIO def read_batch_from_end(byte_stream: BinaryIO, *, size: int, end_position: int) -> bytes: """ Reads batch from the end of given byte stream. >>> import io >>> byte_stream = io.BytesIO(b'Hello\\nWorld!'...
bigcode/self-oss-instruct-sc2-concepts
def rivers_with_station(stations): """receives list of station obhjects and returns a list of names of rivers that have at least one station on""" rivers = set() for station in stations: rivers.add(station.river) return rivers
bigcode/self-oss-instruct-sc2-concepts
def replace(node, **kw): """Equivalent to namedtuple's _replace. When **kw is empty simply returns node itself. >>> o = BinOp(Add(), NumberConstant(2), NumberConstant(3)) >>> o2 = replace(o, op=Sub(), left=NumberConstant(3)) >>> print(o, o2) (2 + 3) (3 - 3) """ if kw: vals =...
bigcode/self-oss-instruct-sc2-concepts
def get_daily_mean_voltages(data): """ Get daily average voltage for each channel. Returns positive voltages """ return data.loc[:, data.columns.str.startswith('voltage')].mean().abs()
bigcode/self-oss-instruct-sc2-concepts
def _get_baseline_value(baseline, key): """ We need to distinguish between no baseline mode (which should return None as a value), baseline mode with exceeded timeout (which is stored as None, but should return 0). """ if key in baseline: return 0 if baseline[key] is None else baseline[k...
bigcode/self-oss-instruct-sc2-concepts
import torch def test(network, loss_function, test_set, batch_size_test, device="cpu"): """ Tests a model in a test set using the loss function provided. (Please note that this is not to be used for testing with a compatibility loss function.) Args: network: The model which is undergoing...
bigcode/self-oss-instruct-sc2-concepts
def get_config(self,dst_name=''): """ Gets the current configuration file of the router to current ``result`` folder. Default ``dst_name`` is ``juniper.conf.gz`` """ return self.get_file('/config/juniper.conf.gz',dst_name)
bigcode/self-oss-instruct-sc2-concepts
def completeCube(hdf, colour, group): # ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ """ Check that a requested cube is all there (data, var, wht). """ if (colour+'_Cube_Data' not in group.keys()) or \ (colour+'_Cube_Variance' not in group.keys()) or \ (colour...
bigcode/self-oss-instruct-sc2-concepts
def maybe_center(do_center, image): """Possibly center image data from [0,1] -> [-1, 1]. This assumes the image tensor is scaled between [0, 1]. Args: do_center: To do the centering or not. image: [0, 1] Scaled image to be centered. Returns: A possibly centered image. """ if do_center: re...
bigcode/self-oss-instruct-sc2-concepts
def default_freeze_dataset_task_spec(dtool_config): """Provide default test task_spec for FreezeDatasetTask.""" return { 'dtool_config': dtool_config, 'stored_data': True, }
bigcode/self-oss-instruct-sc2-concepts