content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def split_multibody(beam, tstep, mb_data_dict, ts): """ split_multibody This functions splits a structure at a certain time step in its different bodies Args: beam (:class:`~sharpy.structure.models.beam.Beam`): structural information of the multibody system tstep (:class:`~sharpy.utils.datastructures.StructTimeStepInfo`): timestep information of the multibody system mb_data_dict (dict): Dictionary including the multibody information ts (int): time step number Returns: MB_beam (list(:class:`~sharpy.structure.models.beam.Beam`)): each entry represents a body MB_tstep (list(:class:`~sharpy.utils.datastructures.StructTimeStepInfo`)): each entry represents a body """ MB_beam = [] MB_tstep = [] for ibody in range(beam.num_bodies): ibody_beam = None ibody_tstep = None ibody_beam = beam.get_body(ibody = ibody) ibody_tstep = tstep.get_body(beam, ibody_beam.num_dof, ibody = ibody) ibody_beam.FoR_movement = mb_data_dict['body_%02d' % ibody]['FoR_movement'] if ts == 1: ibody_beam.ini_info.pos_dot *= 0 ibody_beam.timestep_info.pos_dot *= 0 ibody_tstep.pos_dot *= 0 ibody_beam.ini_info.psi_dot *= 0 ibody_beam.timestep_info.psi_dot *= 0 ibody_tstep.psi_dot *= 0 MB_beam.append(ibody_beam) MB_tstep.append(ibody_tstep) return MB_beam, MB_tstep
25d3d3496bdf0882e732ddfb14d3651d54167adc
819
def hook_name_to_env_name(name, prefix='HOOKS'): """ >>> hook_name_to_env_name('foo.bar_baz') HOOKS_FOO_BAR_BAZ >>> hook_name_to_env_name('foo.bar_baz', 'PREFIX') PREFIX_FOO_BAR_BAZ """ return '_'.join([prefix, name.upper().replace('.', '_')])
b0dabce88da8ddf8695303ac4a22379baa4ddffa
822
def readline_skip_comments(f): """ Read a new line while skipping comments. """ l = f.readline().strip() while len(l) > 0 and l[0] == '#': l = f.readline().strip() return l
c4b36af14cc48b1ed4cd72b06845e131015da6c6
823
def _verify_weight_parameters(weight_parameters): """Verifies that the format of the input `weight_parameters`. Checks that the input parameters is a 2-tuple of tensors of equal shape. Args: weight_parameters: The parameters to check. Raises: RuntimeError: If the input is not a 2-tuple of tensors with equal shape. Returns: The input `weight_parameters`. """ if len(weight_parameters) != 2: raise RuntimeError("Incorrect number of weight parameters. Expected " "2 tensors, got {}".format(len(weight_parameters))) if weight_parameters[0].shape != weight_parameters[1].shape: raise RuntimeError("Expected theta and log alpha parameter tensor " "to be same shape. Got shapes {} and {}" .format(weight_parameters[0].get_shape().as_list(), weight_parameters[1].get_shape().as_list())) return weight_parameters
9ec018c66d48e830250fd299cd50f370118132cc
824
def _crc16_checksum(bytes): """Returns the CRC-16 checksum of bytearray bytes Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html Initial value changed to 0x0000 to match Stellar configuration. """ crc = 0x0000 polynomial = 0x1021 for byte in bytes: for i in range(8): bit = (byte >> (7 - i) & 1) == 1 c15 = (crc >> 15 & 1) == 1 crc <<= 1 if c15 ^ bit: crc ^= polynomial return crc & 0xFFFF
2b00d11f1b451f3b8a4d2f42180f6f68d2fbb615
825
def reverse(segment): """Reverses the track""" return segment.reverse()
74632b8a8a192970187a89744b2e8c6fa77fb2cf
826
def is_bond_member(yaml, ifname): """Returns True if this interface is a member of a BondEthernet.""" if not "bondethernets" in yaml: return False for _bond, iface in yaml["bondethernets"].items(): if not "interfaces" in iface: continue if ifname in iface["interfaces"]: return True return False
521186221f2d0135ebcf1edad8c002945a56da26
827
def lift2(f, a, b): """Apply f => (a -> b -> c) -> f a -> f b -> f c""" return a.map(f).apply_to(b)
6b54cacf23ac4acb9bf9620cd259aa6f9630bbc3
831
def short_whitelist(whitelist): """A condensed version of the whitelist.""" for x in ["guid-4", "guid-5"]: whitelist.remove(x) return whitelist
e0de5f4f8c86df301af03c9362b095f330bffc14
832
def extract_paths(actions): """ <Purpose> Given a list of actions, it extracts all the absolute and relative paths from all the actions. <Arguments> actions: A list of actions from a parsed trace <Returns> absolute_paths: a list with all absolute paths extracted from the actions relative_paths: a list with all relative paths extracted from the actions """ absolute_paths = [] relative_paths = [] actions_with_path = ['open', 'creat', 'statfs', 'access', 'stat', 'link', 'unlink', 'chdir', 'rmdir', 'mkdir'] for action in actions: # get the name of the syscall and remove the "_syscall" part at the end. action_name = action[0][:action[0].find("_syscall")] # we only care about actions containing paths if action_name not in actions_with_path: continue # we only care about paths that exist action_result = action[2] if action_result == (-1, 'ENOENT'): continue path = action[1][0] if path.startswith("/"): if path not in absolute_paths: absolute_paths.append(path) else: if path not in relative_paths: relative_paths.append(path) # get the second path of link if action_name == "link": path = action[1][1] if path.startswith("/"): if path not in absolute_paths: absolute_paths.append(path) else: if path not in relative_paths: relative_paths.append(path) return absolute_paths, relative_paths
94aaf8fef1a7c6d3efd8b04c980c9e87ee7ab4ff
833
def str2int(s): """converts a string to an integer with the same bit pattern (little endian!!!)""" r = 0 for c in s: r <<= 8 r += ord(c) return r
0dd190b8711e29e12be8cc85a641d9a68251205b
834
def count_infected(pop): """ counts number of infected """ return sum(p.is_infected() for p in pop)
03b3b96994cf4156dcbe352b9dafdd027de82d41
837
def _prompt(func, prompt): """Prompts user for data. This is for testing.""" return func(prompt)
c5e8964e5b3a3d0a222e167341a44d8953d1e0c1
838
def to_percent__xy(x, y): """ To percent with 2 decimal places by diving inputs. :param x: :param y: :return: """ return '{:.2%}'.format(x / y)
3d5cfcde6f1dbd65b99a4081790e03efb669ee02
839
import re def only_letters(answer): """Checks if the string contains alpha-numeric characters Args: answer (string): Returns: bool: """ match = re.match("^[a-z0-9]*$", answer) return bool(match)
32c8905294f6794f09bb7ea81ed7dd4b6bab6dc5
841
def _InUse(resource): """All the secret names (local names & remote aliases) in use. Args: resource: Revision Returns: List of local names and remote aliases. """ return ([ source.secretName for source in resource.template.volumes.secrets.values() ] + [ source.secretKeyRef.name for source in resource.template.env_vars.secrets.values() ])
cf13ccf1d0fffcd64ac8b3a40ac19fdb2b1d12c5
842
import re def re_identify_image_metadata(filename, image_names_pattern): """ Apply a regular expression to the *filename* and return metadata :param filename: :param image_names_pattern: :return: a list with metadata derived from the image filename """ match = re.match(image_names_pattern, filename) return None if match is None else match.groups()
1730620682f2457537e3f59360d998b251f5067f
843
import yaml import sys def load_config(config_file: str) -> dict: """ Function to load yaml configuration file :param config_file: name of config file in directory """ try: with open(config_file) as file: config = yaml.safe_load(file) except IOError as e: print(e) sys.exit(1) return config
f811aa4d6a16d8a5e56d14b91d616f9f8b3ad492
844
def mark_task(func): """Mark function as a defacto task (for documenting purpose)""" func._is_task = True return func
9f0156fff2a2a6dcb64e79420022b78d1c254490
846
def make_slack_message_divider() -> dict: """Generates a simple divider for a Slack message. Returns: The generated divider. """ return {'type': 'divider'}
9d0243c091065056a29d9fa05c62fadde5dcf6f6
847
import os def username(): """ Return username from env. """ return os.environ["USER"]
adcb6da63823d78203d02b2a3910f92e3ae97724
848
def get_batch(source, i, cnf): """ Gets a batch shifted over by shift length """ seq_len = min(cnf.batch_size, len(source) - cnf.forecast_window - i) data = source[i : i + seq_len] target = source[ i + cnf.forecast_window : i + cnf.forecast_window + seq_len ].reshape(-1) return data, target
8f4bbfca44bed498dc22d52706389378bf03f7e0
851
def _stringify(item): """ Private funtion which wraps all items in quotes to protect from paths being broken up. It will also unpack lists into strings :param item: Item to stringify. :return: string """ if isinstance(item, (list, tuple)): return '"' + '" "'.join(item) + '"' if isinstance(item, str) and len(item) == 0: return None return '"%s"' % item
7187b33dccce66cb81b53ed8e8c395b74e125633
853
def _get_tree_filter(attrs, vecvars): """ Pull attributes and input/output vector variables out of a tree System. Parameters ---------- attrs : list of str Names of attributes (may contain dots). vecvars : list of str Names of variables contained in the input or output vectors. Returns ------- function A function that takes a System and returns a list of name value pairs. """ def _finder(system): found = [] for attr in attrs: parts = attr.split('.') # allow attrs with dots try: obj = system for p in parts: obj = getattr(obj, p) found.append((attr, obj)) except AttributeError: pass for var in vecvars: if var in system._outputs: found.append((var, system._outputs[var])) elif var in system._inputs: found.append((var, system._inputs[var])) return found return _finder
fb96025a075cfc3c56011f937d901d1b87be4f03
854
import re import copy def _filter(dict_packages, expression): """Filter the dict_packages with expression. Returns: dict(rst): Filtered dict with that matches the expression. """ expression_list = ['(' + item + ')' for item in expression.split(',')] expression_str = '|'.join(expression_list) compiled_exp = re.compile('(?i:^(' + expression_str + ')$)') cp_dict_packages = copy.deepcopy(dict_packages) for key in dict_packages.keys(): match = re.search(compiled_exp, key) if not match: del cp_dict_packages[key] return cp_dict_packages
866bca2847b9d3c8220319f4b394f932931fc076
856
def similarity(item, user, sim_dict): """ similarity between an item and a user (a set of items) """ if user not in sim_dict or item not in sim_dict[user]: return 0 else: return sim_dict[user][item]
e63eec781f7ed9fa72d21d1119daf9ce89d39b1b
857
def menu(function_text): """ Decorator for plain-text handler :param function_text: function which set as handle in bot class :return: """ def wrapper(self, bot, update): self.text_menu(bot, update) function_text(self, bot, update) return wrapper
dc68a46aaf402cd5ce3bd832a0f2a661b5cbc71b
859
from typing import Dict from typing import List def generate_markdown_metadata(metadata_obj: Dict[str, str]) -> List[str]: """generate_markdown_metadata Add some basic metadata to the top of the file in HTML tags. """ metadata: List[str] = ["<!---"] passed_metadata: List[str] = [ f" {key}: {value}" for key, value in metadata_obj.items() ] metadata.extend(passed_metadata) metadata.append(f" Tags:") metadata.append("--->") metadata.append(f"# Diary for {metadata_obj['Date']}") metadata.append("") return metadata
02ef3952c265276f4e666f060be6cb1d4a150cca
860
def replace_string(original, start, end, replacement): """Replaces the specified range of |original| with |replacement|""" return original[0:start] + replacement + original[end:]
c71badb26287d340170cecdbae8d913f4bdc14c6
861
def dictionarify_recpat_data(recpat_data): """ Covert a list of flat dictionaries (single-record dicts) into a dictionary. If the given data structure is already a dictionary, it is left unchanged. """ return {track_id[0]: patterns[0] for track_id, patterns in \ [zip(*item.items()) for item in recpat_data]} \ if not isinstance(recpat_data, dict) else recpat_data
d1cdab68ab7445aebe1bbcce2f220c73d6db308f
862
def pre_process_data(full_data): """ pre process data- dump invalid values """ clean_data = full_data[(full_data["Temp"] > -10)] return clean_data
6172d4a77f5805c60ae9e4f146da2bd8283beef0
863
def user_exists(keystone, user): """" Return True if user already exists""" return user in [x.name for x in keystone.users.list()]
17d99e12c0fc128607a815f0b4ab9897c5d45578
864
def text_split(in_text, insert_points, char_set): """ Returns: Input Text Split into Text and Nonce Strings. """ nonce_key = [] encrypted_nonce = "" in_list = list(in_text) for pos in range(3967): if insert_points[pos] >= len(in_list) - 1: point = len(in_list) - 2 else: point = insert_points[pos] char = in_list[point] in_list.pop(point) nonce_key.append(char) if char is not char_set[-1]: break length = ((len(nonce_key) - 1) * (len(char_set) -2)) + char_set.index(nonce_key[len(nonce_key) - 1]) for pos in range(length): if insert_points[pos + len(nonce_key)] >= len(in_list) - 1: point = len(in_list) - 2 else: point = insert_points[pos + len(nonce_key)] char = in_list[point] in_list.pop(point) encrypted_nonce = encrypted_nonce + char return "".join(in_list), encrypted_nonce
15f496513e63236b0df7e2d8a8949a8b2e632af4
867
def _module_exists(module_name): """ Checks if a module exists. :param str module_name: module to check existance of :returns: **True** if module exists and **False** otherwise """ try: __import__(module_name) return True except ImportError: return False
8f3ed2e97ee6dbb41d6e84e9e5595ec8b6f9b339
868
def check_cstr(solver, indiv): """Check the number of constraints violations of the individual Parameters ---------- solver : Solver Global optimization problem solver indiv : individual Individual of the population Returns ------- is_feasible : bool Individual feasibility """ # Non valid simulation violate every constraints if indiv.is_simu_valid == False: indiv.cstr_viol = len(solver.problem.constraint) return True # To not add errors to infeasible # Browse constraints for constraint in solver.problem.constraint: # Compute value to compare var_val = constraint.get_variable(indiv.output) # Compare the value with the constraint type_const = constraint.type_const if type_const == "<=": if var_val > constraint.value: indiv.cstr_viol += 1 elif type_const in ["==", "="]: if var_val != constraint.value: indiv.cstr_viol += 1 elif type_const == ">=": if var_val < constraint.value: indiv.cstr_viol += 1 elif type_const == "<": if var_val >= constraint.value: indiv.cstr_viol += 1 elif type_const == ">": if var_val <= constraint.value: indiv.cstr_viol += 1 else: raise ValueError("Wrong type of constraint") return indiv.cstr_viol == 0
2aa52d2badfb45d8e289f8314700648ddc621252
869
def normal_shock_pressure_ratio(M, gamma): """Gives the normal shock static pressure ratio as a function of upstream Mach number.""" return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0)
30d0a339b17bab2b662fecd5b19073ec6478a1ec
871
from typing import Tuple import numpy def _lorentz_berthelot( epsilon_1: float, epsilon_2: float, sigma_1: float, sigma_2: float ) -> Tuple[float, float]: """Apply Lorentz-Berthelot mixing rules to a pair of LJ parameters.""" return numpy.sqrt(epsilon_1 * epsilon_2), 0.5 * (sigma_1 + sigma_2)
b27c282cec9f880442be4e83f4965c0ad79dfb1e
872
def get_ical_file_name(zip_file): """Gets the name of the ical file within the zip file.""" ical_file_names = zip_file.namelist() if len(ical_file_names) != 1: raise Exception( "ZIP archive had %i files; expected 1." % len(ical_file_names) ) return ical_file_names[0]
7013840891844358f0b4a16c7cefd31a602d9eae
873
def circular_mask_string(centre_ra_dec_posns, aperture_radius="1arcmin"): """Get a mask string representing circular apertures about (x,y) tuples""" mask = '' if centre_ra_dec_posns is None: return mask for coords in centre_ra_dec_posns: mask += 'circle [ [ {x} , {y}] , {r} ]\n'.format( x=coords[0], y=coords[1], r=aperture_radius) return mask
04e66d160eb908f543990adf896e494226674c71
875
def dataset_hdf5(dataset, tmp_path): """Make an HDF5 dataset and write it to disk.""" path = str(tmp_path / 'test.h5') dataset.write_hdf5(path, object_id_itemsize=10) return path
4a7920adf7715797561513fbb87593abf95f0bca
876
def actions(__INPUT): """ Regresamos una lista de los posibles movimientos de la matriz """ MOVIMIENTOS = [] m = eval(__INPUT) i = 0 while 0 not in m[i]: i += 1 # Espacio en blanco (#0) j = m[i].index(0); if i > 0: #ACCION MOVER ARRIBA m[i][j], m[i-1][j] = m[i-1][j], m[i][j]; MOVIMIENTOS.append(str(m)) m[i][j], m[i-1][j] = m[i-1][j], m[i][j]; if i < 3: # ACCION MOVER ABAJO m[i][j], m[i+1][j] = m[i+1][j], m[i][j] MOVIMIENTOS.append(str(m)) m[i][j], m[i+1][j] = m[i+1][j], m[i][j] if j > 0: # ACCION MOVER IZQUIERDA m[i][j], m[i][j-1] = m[i][j-1], m[i][j] MOVIMIENTOS.append(str(m)) m[i][j], m[i][j-1] = m[i][j-1], m[i][j] if j < 3: # ACCION MOVER DERECHA m[i][j], m[i][j+1] = m[i][j+1], m[i][j] MOVIMIENTOS.append(str(m)) m[i][j], m[i][j+1] = m[i][j+1], m[i][j] return MOVIMIENTOS
46875f83d7f50bbd107be8ad5d926397960ca513
879
from shutil import which as shwhich import os def which(program, mode=os.F_OK | os.X_OK, path=None): """ Mimics the Unix utility which. For python3.3+, shutil.which provides all of the required functionality. An implementation is provided in case shutil.which does not exist. :param program: (required) string Name of program (can be fully-qualified path as well) :param mode: (optional) integer flag bits Permissions to check for in the executable Default: os.F_OK (file exists) | os.X_OK (executable file) :param path: (optional) string A custom path list to check against. Implementation taken from shutil.py. Returns: A fully qualified path to program as resolved by path or user environment. Returns None when program can not be resolved. """ try: return shwhich(program, mode, path) except ImportError: def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, _ = os.path.split(program) if fpath: if is_exe(program): return program else: if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) for pathdir in path: pathdir = pathdir.strip('"') exe_file = os.path.join(pathdir, program) if is_exe(exe_file): return exe_file return None
fbba58ba489db2c2813e4aadf9781c35d6955f0f
880
def choose_string(g1, g2): """Function used by merge_similar_guesses to choose between 2 possible properties when they are strings. If the 2 strings are similar, or one is contained in the other, the latter is returned with an increased confidence. If the 2 strings are dissimilar, the one with the higher confidence is returned, with a weaker confidence. Note that here, 'similar' means that 2 strings are either equal, or that they differ very little, such as one string being the other one with the 'the' word prepended to it. >>> s(choose_string(('Hello', 0.75), ('World', 0.5))) ('Hello', 0.25) >>> s(choose_string(('Hello', 0.5), ('hello', 0.5))) ('Hello', 0.75) >>> s(choose_string(('Hello', 0.4), ('Hello World', 0.4))) ('Hello', 0.64) >>> s(choose_string(('simpsons', 0.5), ('The Simpsons', 0.5))) ('The Simpsons', 0.75) """ v1, c1 = g1 # value, confidence v2, c2 = g2 if not v1: return g2 elif not v2: return g1 v1, v2 = v1.strip(), v2.strip() v1l, v2l = v1.lower(), v2.lower() combined_prob = 1 - (1 - c1) * (1 - c2) if v1l == v2l: return (v1, combined_prob) # check for common patterns elif v1l == 'the ' + v2l: return (v1, combined_prob) elif v2l == 'the ' + v1l: return (v2, combined_prob) # if one string is contained in the other, return the shortest one elif v2l in v1l: return (v2, combined_prob) elif v1l in v2l: return (v1, combined_prob) # in case of conflict, return the one with highest confidence else: if c1 > c2: return (v1, c1 - c2) else: return (v2, c2 - c1)
e39a66c9f3f941b12225dde879bc92956694d2d0
881
import argparse def get_parser(): """Return base parser for scripts. """ parser = argparse.ArgumentParser() parser.add_argument('config', help='Tuning configuration file (examples: configs/tuning)') return parser
6f394f836fae278b659a0612a088f53563c8f34b
882
import os def cd(path): """Context manager to switch working directory""" def normpath(path): """Normalize UNIX path to a native path.""" normalized = os.path.join(*path.split('/')) if os.path.isabs(path): return os.path.abspath('/') + normalized return normalized path = normpath(path) cwd = os.getcwd() os.chdir(path) try: yield path finally: os.chdir(cwd)
f1664765e26e3ff4ec8a70d16d6beca5a23f4d68
883
from datetime import datetime def add_filter(field, bind, criteria): """Generate a filter.""" if 'values' in criteria: return '{0}=any(:{1})'.format(field, bind), criteria['values'] if 'date' in criteria: return '{0}::date=:{1}'.format(field, bind), datetime.strptime(criteria['date'], '%Y-%m-%d').date() if 'gte' in criteria: return '{0}>=:{1}'.format(field, bind), criteria['gte'] if 'lte' in criteria: return '{0}<=:{1}'.format(field, bind), criteria['lte'] raise ValueError('criteria not supported')
2358cab297b2a2cbc42af02b3b6d14ac134c8b71
884
def decode_field(value): """Decodes a field as defined in the 'Field Specification' of the actions man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt """ parts = value.strip("]\n\r").split("[") result = { "field": parts[0], } if len(parts) > 1 and parts[1]: field_range = parts[1].split("..") start = field_range[0] end = field_range[1] if len(field_range) > 1 else start if start: result["start"] = int(start) if end: result["end"] = int(end) return result
1a1659e69127ddd3c63eb7d4118ceb4e53a28ca0
885
def _nonempty_line_count(src: str) -> int: """Count the number of non-empty lines present in the provided source string.""" return sum(1 for line in src.splitlines() if line.strip())
ad2ac0723f9b3e1f36b331175dc32a8591c67893
886
import os def _validate_source(source): """ Check that the entered data source paths are valid """ # acceptable inputs (for now) are a single file or directory assert type(source) == str, "You must enter your input as a string." assert ( os.path.isdir(source) == True or os.path.isfile(source) == True ), "Your data source string is not a valid data source." return True
45e1f88f6c246713f85d83cf6a9753ec67799774
887
def recursion_detected(frame, keys): """Detect if we have a recursion by finding if we have already seen a call to this function with the same locals. Comparison is done only for the provided set of keys. """ current = frame current_filename = current.f_code.co_filename current_function = current.f_code.co_name current_locals = {k: v for k, v in current.f_locals.items() if k in keys} while frame.f_back: frame = frame.f_back fname = frame.f_code.co_filename if not(fname.endswith(".py") or fname == "<template>"): return False if fname != current_filename or \ frame.f_code.co_name != current_function: continue if ({k: v for k, v in frame.f_locals.items() if k in keys} == current_locals): return True return False
ebf30e715d2901169095bc920e8af6c715f2a1de
888
def _dump_multipoint(obj, fmt): """ Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] mp = 'MULTIPOINT (%s)' points = (' '.join(fmt % c for c in pt) for pt in coords) # Add parens around each point. points = ('(%s)' % pt for pt in points) mp %= ', '.join(points) return mp
cdea05b91c251b655e08650807e3f74d3bb5e77b
889
def binary_distance(label1, label2): """Simple equality test. 0.0 if the labels are identical, 1.0 if they are different. >>> from nltk.metrics import binary_distance >>> binary_distance(1,1) 0.0 >>> binary_distance(1,3) 1.0 """ return 0.0 if label1 == label2 else 1.0
2c4eaebda2d6955a5012cc513857aed66df60194
890
def calc_commission_futures_global(trade_cnt, price): """ 国际期货:差别很大,最好外部自定义自己的计算方法,这里只简单按照0.002计算 :param trade_cnt: 交易的股数(int) :param price: 每股的价格(美元) :return: 计算结果手续费 """ cost = trade_cnt * price # 国际期货各个券商以及代理方式差别很大,最好外部自定义计算方法,这里只简单按照0.002计算 commission = cost * 0.002 return commission
ddd2c4571abfcdf7021a28b6cc78fe6441da2bd3
891
def make_collector(entries): """ Creates a function that collects the location data from openLCA. """ def fn(loc): entry = [loc.getCode(), loc.getName(), loc.getRefId()] entries.append(entry) return fn
83fb167c38626fde79262a32f500b33a72ab8308
892
def apiname(funcname): """ Define what name the API uses, the short or the gl version. """ if funcname.startswith('gl'): return funcname else: if funcname.startswith('_'): return '_gl' + funcname[1].upper() + funcname[2:] else: return 'gl' + funcname[0].upper() + funcname[1:]
06575fce76ac02990c973a6dd17ff177ae5e3ddc
893
import argparse from pathlib import Path def _parse_args() -> argparse.Namespace: """Registers the script's arguments on an argument parser.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source-root', type=Path, required=True, help='Prefix to strip from the source files') parser.add_argument('sources', type=Path, nargs='*', help='Files to mirror to the directory') parser.add_argument('--directory', type=Path, required=True, help='Directory to which to mirror the sources') parser.add_argument('--path-file', type=Path, help='File with paths to files to mirror') return parser.parse_args()
cda37a6282b95fca4db51e91bfe98cc44f46fd07
896
def filter_marker_y_padding(markers_y_indexes, padding_y_top, padding_y_bottom): """ Filter the markers indexes for padding space in the top and bottom of answer sheet :param markers_y_indexes: :param padding_y_top: :param padding_y_bottom: :return: """ return markers_y_indexes[(markers_y_indexes > padding_y_top) & (markers_y_indexes < padding_y_bottom)]
b1eed0ac24bd6a6354072427be4375ad188572a5
897
def apply_function(f, *args, **kwargs): """ Apply a function or staticmethod/classmethod to the given arguments. """ if callable(f): return f(*args, **kwargs) elif len(args) and hasattr(f, '__get__'): # support staticmethod/classmethod return f.__get__(None, args[0])(*args, **kwargs) else: assert False, "expected a function or staticmethod/classmethod"
374be0283a234d4121435dbd3fa873640f2b9ad1
898
import sys def read_lines_from_input(file): """ Reads the provided file line by line to provide a list representation of the contained names. :param file: A text file containing one name per line. If it's None, the input is read from the standard input. :return: A list of the names contained in the provided text file """ if file is None: file = sys.stdin return map(lambda l: l.strip(), file.readlines())
4a653979ee51afea8e7199772199c1a93dbfecc3
899
import os def installDirectory(): """ Return the software installation directory, by looking at location of this method. """ #path = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir)) path = os.path.abspath(os.path.realpath(__file__)) path = os.path.abspath(os.path.join(path, '../..')) #path = path.replace("EGG-INFO/scripts/smodels-config", "") #path = path.replace("installation.py", "") return path + "/"
d79d57eea1eb38ec56a864246ac2388d7320a0fa
901
def make_file_iterator(filename): """Return an iterator over the contents of the given file name.""" # pylint: disable=C0103 with open(filename) as f: contents = f.read() return iter(contents.splitlines())
e7b612465717dafc3155d9df9fd007f7aa9af509
902
def little_endian_bytes_to_int(little_endian_byte_seq): """Converts a pair of bytes into an integer. The `little_endian_byte_seq` input must be a 2 bytes sequence defined according to the little-endian notation (i.e. the less significant byte first). For instance, if the `little_endian_byte_seq` input is equals to ``(0xbc, 0x02)`` this function returns the decimal value ``700`` (0x02bc in hexadecimal notation). :param bytes little_endian_byte_seq: the 2 bytes sequence to be converted. It must be compatible with the "bytes" type and defined according to the little-endian notation. """ # Check the argument and convert it to "bytes" if necessary. # Assert "little_endian_byte_seq" items are in range (0, 0xff). # "TypeError" and "ValueError" are sent by the "bytes" constructor if # necessary. # The statement "tuple(little_endian_byte_seq)" implicitely rejects # integers (and all non-iterable objects) to compensate the fact that the # bytes constructor doesn't reject them: bytes(2) is valid and returns # b'\x00\x00' little_endian_byte_seq = bytes(tuple(little_endian_byte_seq)) # Check that the argument is a sequence of two items if len(little_endian_byte_seq) != 2: raise ValueError("A sequence of two bytes is required.") integer = little_endian_byte_seq[1] * 0x100 + little_endian_byte_seq[0] return integer
d8d0c6d4ebb70ea541e479b21deb913053886748
903
def higher_follower_count(A, B): """ Compares follower count key between two dictionaries""" if A['follower_count'] >= B['follower_count']: return "A" return "B"
d4d182ca5a3c5bff2bc7229802603a82d44a4d67
904
import os def make_non_absolute(path): """ Make a path non-absolute (so it can be joined to a base directory) @param path: The file path """ drive, path = os.path.splitdrive(path) index = 0 while os.path.isabs(path[index:]): index = index + 1 return path[index:]
51eefa84423077273931a3a4c77b4e53669a6599
905
def pad_in(string: str, space: int) -> str: """ >>> pad_in('abc', 0) 'abc' >>> pad_in('abc', 2) ' abc' """ return "".join([" "] * space) + string
325c0751da34982e33e8fae580af6f439a2dcac0
908
import time def confirm_channel(bitcoind, n1, n2): """ Confirm that a channel is open between two nodes """ assert n1.id() in [p.pub_key for p in n2.list_peers()] assert n2.id() in [p.pub_key for p in n1.list_peers()] for i in range(10): time.sleep(0.5) if n1.check_channel(n2) and n2.check_channel(n1): return True addr = bitcoind.rpc.getnewaddress("", "bech32") bhash = bitcoind.rpc.generatetoaddress(1, addr)[0] n1.block_sync(bhash) n2.block_sync(bhash) # Last ditch attempt return n1.check_channel(n2) and n2.check_channel(n1)
bcbf895b286b446f7bb0ad2d7890a0fa902cdbd1
909
def extend_params(params, more_params): """Extends dictionary with new values. Args: params: A dictionary more_params: A dictionary Returns: A dictionary which combines keys from both dictionaries. Raises: ValueError: if dicts have the same key. """ for yak in more_params: if yak in params: raise ValueError('Key "%s" is already in dict' % yak) params.update(more_params) return params
626db0ae8d8a249b8c0b1721b7a2e0f1d4c084b8
910
def _AccumulatorResultToDict(partition, feature, grads, hessians): """Converts the inputs to a dictionary since the ordering changes.""" return {(partition[i], feature[i, 0], feature[i, 1]): (grads[i], hessians[i]) for i in range(len(partition))}
20cc895cf936749a35c42a1158c9ea6645019e7d
911
def _evolve_cx(base_pauli, qctrl, qtrgt): """Update P -> CX.P.CX""" base_pauli._x[:, qtrgt] ^= base_pauli._x[:, qctrl] base_pauli._z[:, qctrl] ^= base_pauli._z[:, qtrgt] return base_pauli
5d0529bc4bfe74a122c24069eccb20fa2b69f153
912
def get_block_devices(bdms=None): """ @type bdms: list """ ret = "" if bdms: for bdm in bdms: ret += "{0}\n".format(bdm.get('DeviceName', '-')) ebs = bdm.get('Ebs') if ebs: ret += " Status: {0}\n".format(ebs.get('Status', '-')) ret += " Snapshot Id: {0}\n".format(ebs.get('SnapshotId', '-')) ret += " Volume Size: {0}\n".format(ebs.get('VolumeSize', '-')) ret += " Volume Type: {0}\n".format(ebs.get('VolumeType', '-')) ret += " Encrypted: {0}\n".format(str(ebs.get('Encrypted', '-'))) ret += " Delete on Termination: {0}\n".format(ebs.get('DeleteOnTermination', '-')) ret += " Attach Time: {0}\n".format(str(ebs.get('AttachTime', '-'))) return ret.rstrip() else: return ret
bd375f988b13d8fe5949ebdc994210136acc3405
914
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_grpc_interface] interface_dir=<<path to the parent directory of your Protocol Buffer (pb2) files>> #<<package_name>>=<<communication_type>>, <<secure connection type>>, <<certificate_path or google API token>> # 'package_name' is a CSV list of length 3, where each possible value is described in the documentation # Note: to setup, in your interface_dir, create a sub-directory that has # the same name as your package, and copy the Protocol Buffer pb2 files # into that directory. # # If the package_name was 'helloworld', your app.config would look like: # [fn_grpc_interface] # interface_dir=/home/admin/integrations/grpc_interface_files # helloworld=unary, None, None""" return config_data
cb26012ff6ad1a2dbccbbcc5ef81c7a91def7906
916
import multiprocessing import os def get_workers_count_based_on_cpu_count(): """ Returns the number of workers based available virtual or physical CPUs on this system. """ # Python 2.6+ try: return multiprocessing.cpu_count() * 2 + 1 except (ImportError, NotImplementedError): pass try: res = int(os.sysconf('SC_NPROCESSORS_ONLN')) if res > 0: return res * 2 + 1 except (AttributeError, ValueError): pass raise Exception('Can not determine number of CPUs on this system')
0f42840196e596a371a78f16443b4bc22a89c460
917
def get_rdf_lables(obj_list): """Get rdf:labels from a given list of objects.""" rdf_labels = [] for obj in obj_list: rdf_labels.append(obj['rdf:label']) return rdf_labels
2bcf6a6e8922e622de602f5956747955ea39eeda
919
def _identifier(name): """ :param name: string :return: name in lower case and with '_' instead of '-' :rtype: string """ if name.isidentifier(): return name return name.lower().lstrip('0123456789. ').replace('-', '_')
fbbbc9dd3f2bc5b6e43520c0685f63a10ee95f0a
921
def get_request_list(flow_list: list) -> list: """ 将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。 :param flow_list: flow的列表 :return: request的列表 """ req_list = [] for flow in flow_list: request = flow.get("request") req_list.append(request) return req_list
a70e0120ef2be88bd0644b82317a2a0748352c6c
922
def _get_resource(span): """Get resource name for span""" if "http.method" in span.attributes: route = span.attributes.get("http.route") return ( span.attributes["http.method"] + " " + route if route else span.attributes["http.method"] ) return span.name
71b4d2e568350ccfb436bbff6e7a2cff1f3cb251
924
def _B(slot): """Convert slot to Byte boundary""" return slot*2
97f13e9fd99989a83e32f635193a0058656df68b
925
import torch def nll(perm, true): """ perm: (n, n) or (s, n, n) true: (n) """ n = true.size(-1) # i = torch.arange(n, device=perm.device) # j = true.to(perm.device) # print("perm.nll:", perm.size(), true.size()) elements = perm.cpu()[..., torch.arange(n), true] # elements = perm.cpu()[torch.arange(n), true] nll = -torch.sum(torch.log2(elements.to(perm.device))) if perm.dim() == 3: # normalize by number samples nll = nll / perm.size(0) # print("nll", nll) return nll
a63c95e814529539ecd964f4309ea96f78cfcbb1
926
import pathlib import json def load_towns(): """Sample of Wikipedia dataset that contains informations about Toulouse, Paris, Lyon and Bordeaux. Examples -------- >>> from pprint import pprint as print >>> from cherche import data >>> towns = data.load_towns() >>> print(towns[:3]) [{'article': 'Paris (French pronunciation: \u200b[paʁi] (listen)) is the ' 'capital and most populous city of France, with an estimated ' 'population of 2,175,601 residents as of 2018, in an area of more ' 'than 105 square kilometres (41 square miles).', 'id': 0, 'title': 'Paris', 'url': 'https://en.wikipedia.org/wiki/Paris'}, {'article': "Since the 17th century, Paris has been one of Europe's major " 'centres of finance, diplomacy, commerce, fashion, gastronomy, ' 'science, and arts.', 'id': 1, 'title': 'Paris', 'url': 'https://en.wikipedia.org/wiki/Paris'}, {'article': 'The City of Paris is the centre and seat of government of the ' 'region and province of Île-de-France, or Paris Region, which has ' 'an estimated population of 12,174,880, or about 18 percent of ' 'the population of France as of 2017.', 'id': 2, 'title': 'Paris', 'url': 'https://en.wikipedia.org/wiki/Paris'}] """ with open(pathlib.Path(__file__).parent.joinpath("towns.json"), "r") as towns_json: return json.load(towns_json)
72aa393cfc40db5f254059d78679ea5615f494d2
927
import numpy as np def minimum_distance(object_1, object_2): """ Takes two lists as input A list of numpy arrays of coordinates that make up object 1 and object 2 Measures the distances between each of the coordinates Returns the minimum distance between the two objects, as calculated using a vector norm Stops the calculation and returns 0 if two coordinates overlap """ # package import # main algorithm minimum_distance = 100000 for coord_1 in object_1: for coord_2 in object_2: distance_btwn_coords = np.linalg.norm(coord_1 - coord_2) if distance_btwn_coords == 0: minimum_distance = distance_btwn_coords return float(minimum_distance) elif distance_btwn_coords < minimum_distance: minimum_distance = distance_btwn_coords return float(minimum_distance)
e61fbb1ab83c5147f69351022f59ebab3295cb5a
930
def union(l1, l2): """ return the union of two lists """ return list(set(l1) | set(l2))
573e3b0e475b7b33209c4a477ce9cab53ec849d4
931
def k1(f, t, y, paso): """ f : funcion a integrar. Retorna un np.ndarray t : tiempo en el cual evaluar la funcion f y : para evaluar la funcion f paso : tamano del paso a usar. """ output = paso * f(t, y) return output
55a358a5d099111bd399bf1a0e0211d6616ab3d0
932
def get_start_end(sequence, skiplist=['-','?']): """Return position of first and last character which is not in skiplist. Skiplist defaults to ['-','?']).""" length=len(sequence) if length==0: return None,None end=length-1 while end>=0 and (sequence[end] in skiplist): end-=1 start=0 while start<length and (sequence[start] in skiplist): start+=1 if start==length and end==-1: # empty sequence return -1,-1 else: return start,end
b67e0355516f5aa5d7f7fad380d262cf0509bcdb
934
def workerfunc(prob, *args, **kwargs): """ Helper function for wrapping class methods to allow for use of the multiprocessing package """ return prob.run_simulation(*args, **kwargs)
620799615b60784e754385fac31e5a7f1db37ed3
936
def test_curve_plot(curve): """ Tests mpl image of curve. """ fig = curve.plot().get_figure() return fig
033ee4ce5f5fa14c60914c34d54af4c39f6f84b3
937
def simplifiedview(av_data: dict, filehash: str) -> str: """Builds and returns a simplified string containing basic information about the analysis""" neg_detections = 0 pos_detections = 0 error_detections = 0 for engine in av_data: if av_data[engine]['category'] == 'malicious' or av_data[engine]['category'] == 'suspicious': neg_detections += 1 elif av_data[engine]['category'] == 'undetected': pos_detections += 1 elif av_data[engine]['category'] == 'timeout' or av_data[engine]['category'] == 'type-unsupported' \ or av_data[engine]['category'] == 'failure': error_detections += 1 vt_url = f'https://www.virustotal.com/gui/file/{filehash}' response = f"__VirusTotal Analysis Summary__:\n\nHash: `{filehash}`\n\nLink: [Click Here]({vt_url})\n\n❌" \ f" **Negative: {neg_detections}**\n\n✅ Positive: {pos_detections}\n\n⚠ " \ f"Error/Unsupported File: {error_detections}" return response
c6aecf6c12794453dd8809d53f20f6152ac6d5a3
938
def quote_key(key): """特殊字符'/'转义处理 """ return key.replace('/', '%2F')
ce1978ca23ed3c00489c134a35ae8d04370b49dd
939
def middle(word): """Returns all but the first and last characters of a string.""" return word[1:-1]
257a159c46633d3c3987437cb3395ea2be7fad70
940
import argparse def _validate_int(value, min, max, type): """Validates a constrained integer value. """ try: ivalue = int(value) if min and max: if ivalue < min or ivalue > max: raise ValueError() except ValueError: err = f"{type} index must be an integer" if min and max: err += f" between {min} and {max}" raise argparse.ArgumentTypeError(err) return ivalue
6e85ea9d97a4c906cad410847de6f21eace33afd
941
import re from pathlib import Path import json def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]: """Load stdlib public names data from JSON file""" if not re.fullmatch(r"\d+\.\d+", version): raise ValueError(f"{version} is not a valid version") try: json_file = Path(__file__).with_name("stdlib_public_names") / ( version + ".json" ) json_text = json_file.read_text(encoding="utf-8") json_obj = json.loads(json_text) return {module: frozenset(names) for module, names in json_obj.items()} except FileNotFoundError: raise ValueError( f"there is no data of stdlib public names for Python version {version}" ) from None
02775d96c8a923fc0380fe6976872a7ed2cf953a
942
def readlines(filepath): """ read lines from a textfile :param filepath: :return: list[line] """ with open(filepath, 'rt') as f: lines = f.readlines() lines = map(str.strip, lines) lines = [l for l in lines if l] return lines
1aa16c944947be026223b5976000ac38556983c3
944
def n_tuple(n): """Factory for n-tuples.""" def custom_tuple(data): if len(data) != n: raise TypeError( f'{n}-tuple requires exactly {n} items ' f'({len(data)} received).' ) return tuple(data) return custom_tuple
0c5d8f0f277e07f73c4909895c8215427fb5e705
946
def calc_dof(model): """ Calculate degrees of freedom. Parameters ---------- model : Model Model. Returns ------- int DoF. """ p = len(model.vars['observed']) return p * (p + 1) // 2 - len(model.param_vals)
ccff8f5a7624b75141400747ec7444ec55eb492d
947
def _level2partition(A, j): """Return views into A used by the unblocked algorithms""" # diagonal element d is A[j,j] # we access [j, j:j+1] to get a view instead of a copy. rr = A[j, :j] # row dd = A[j, j:j+1] # scalar on diagonal / \ B = A[j+1:, :j] # Block in corner | r d | cc = A[j+1:, j] # column \ B c / return rr, dd, B, cc
16ba7715cc28c69ad35cdf3ce6b542c14d5aa195
948
def bisect_jump_time(tween, value, b, c, d): """ **** Not working yet return t for given value using bisect does not work for whacky curves """ max_iter = 20 resolution = 0.01 iter = 1 lower = 0 upper = d while iter < max_iter: t = (upper - lower) / 2 if tween(t, b, c, d) - value < resolution: return t else: upper = t
f7e1dbeb000ef60a5bd79567dc88d66be9235a75
950
import math def getDist_P2L(PointP,Pointa,Pointb): """计算点到直线的距离 PointP:定点坐标 Pointa:直线a点坐标 Pointb:直线b点坐标 """ #求直线方程 A=0 B=0 C=0 A=Pointa[1]-Pointb[1] B=Pointb[0]-Pointa[0] C=Pointa[0]*Pointb[1]-Pointa[1]*Pointb[0] #代入点到直线距离公式 distance=0 distance=(A*PointP[0]+B*PointP[1]+C)/math.sqrt(A*A+B*B) return distance
ca0ec1fc25183a240179faef7473d7b86758a92b
953
import functools def skip_if_disabled(func): """Decorator that skips a test if test case is disabled.""" @functools.wraps(func) def wrapped(*a, **kwargs): func.__test__ = False test_obj = a[0] message = getattr(test_obj, 'disabled_message', 'Test disabled') if getattr(test_obj, 'disabled', False): test_obj.skipTest(message) func(*a, **kwargs) return wrapped
56d42a1e0418f4edf3d4e8478358495b1353f57a
956
from typing import Any import itertools def _compare_keys(target: Any, key: Any) -> bool: """ Compare `key` to `target`. Return True if each value in `key` == corresponding value in `target`. If any value in `key` is slice(None), it is considered equal to the corresponding value in `target`. """ if not isinstance(target, tuple): return target == key for k1, k2 in itertools.zip_longest(target, key, fillvalue=None): if k2 == slice(None): continue if k1 != k2: return False return True
ff5c60fab8ac0cbfe02a816ec78ec4142e32cfbf
957
import inspect def filter_safe_dict(data, attrs=None, exclude=None): """ Returns current names and values for valid writeable attributes. If ``attrs`` is given, the returned dict will contain only items named in that iterable. """ def is_member(cls, k): v = getattr(cls, k) checks = [ not k.startswith("_"), not inspect.ismethod(v) or getattr(v, "im_self", True), not inspect.isfunction(v), not isinstance(v, (classmethod, staticmethod, property)), ] return all(checks) cls = None if inspect.isclass(data): cls = data data = {k: getattr(cls, k) for k in dir(cls) if is_member(cls, k)} ret = {} for k, v in data.items(): checks = [ not k.startswith("_"), not inspect.ismethod(v) or getattr(v, "im_self", True), not isinstance(v, (classmethod, staticmethod, property)), not attrs or (k in attrs), not exclude or (k not in exclude), ] if all(checks): ret[k] = v return ret
ce457615ba8e360243912c3bba532e8327b8def4
959
def fixture_loqus_exe(): """Return the path to a loqus executable""" return "a/path/to/loqusdb"
647b31e37854a5cbc8fd066c982e67f976100c03
960