content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def char_floats(floats): """Pretty printing of floats. Args: floats (list or float): if float it gets converted to a list with one entry. Returns: line (list): list of strings. """ if isinstance(floats, float): floats = [floats] line = [] for value in ...
b1cb0eaa7408e3b040504cf115159a4115ed240b
64,941
def create_matrix(PBC=[1, 1, 1], omit=False): """ Used for calculating distances in lattices with periodic boundary conditions. When multiplied with a set of points, generates additional points in cells adjacent to and diagonal to the original cell Args: PBC: A periodic boundary condition l...
66ed835fbf7a35b4056b5c3eaa2e1d4322a44c84
64,942
def h5py_read_dataset(dset, index=tuple(), decode_ascii=False): """Read data from dataset object. UTF-8 strings will be decoded while ASCII strings will only be decoded when `decode_ascii=True`. :param h5py.Dataset dset: :param index: slicing (all by default) :param bool decode_ascii: """ ...
4d96386cf96487fdc0775c1a0a92594e27790984
64,943
def sample(data, labels, sizes, seed=None, verbose=0): """ Sample from the dataset. Model a generative algorithm over each of the desired labelled data to sample more data from the resulting distributions. Parameters ---------- data : array-like, shape=(n_samples, n_features) Data. labels : array-like, sh...
831683df272082808cf4d988fc85f17be3d50c3c
64,944
def eidas_crypto_hash_hex(hex_data: str) -> str: """ Generates a 256-hash hex string from a given hex string data (using cryptography module) """ return eidas_crypto_hash_byte(bytes.fromhex(hex_data))
45296ad57fe26cf1ba8e7fcc5c400dc97e320ec7
64,945
from io import StringIO def truncateToMultiLine(line, length = 60, prefix = '', indentPrefix = None): """ Parse a one line message into multiple lines of the specified length """ multiLine = StringIO() numLines = ((len(line) - 1) / length) + 1 offset = 0 for i in range(numLines): if indent...
0d88406974b77a109f0082d28a3a4070a9a8e082
64,946
def _shift_and_fix_registers(registers, offset, addresses, min_address): """Shift register contents.""" sregisters = [] for register in registers: register = register.copy() if not register.name.startswith("GPR"): # Do not shift not GPR registers sregisters.append(reg...
c1d13a72ae77073ed0837d681bbdcca0435c3d17
64,947
def pandas2markdown(dataframe: pd.DataFrame) -> str: """ translate the Dataframe in pandas into Markdown table :type dataframe: object """ if not hasattr(pandas2markdown,'writer'): pandas2markdown.writer: MarkdownTableWriter = MarkdownTableWriter() pandas2markdown.writer.from_dataframe( ...
763b0be9feb64ce3259254bf85b35ed5141566b2
64,949
def image_preprocessing(image, train, crop_size, im_size=None, thread_id=0, bbox=None): """Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate ...
2e77a32c363a667d64258b0a81d9a03311914b2d
64,950
from typing import Container from typing import Iterable def match_tags(search: Container[str], tags: Iterable[str]): """Check if the search constraints satisfy tags. The search tags should be uppercased. All !tags or -tags cannot be present, all +tags must be present, and at lest one normal tag mus...
0a6ee5f233900eb50ad72613aa73f227a836b4dd
64,951
def view_2dmol(option, maps=None, out_put=None, target_id=None, legends=None, extra=None): """Function to render a mol image from a smiles. The input (option) could be 1) a list of smiles 2) a smiles 3) pdb_code Returns a molecule image as data""" option = str(option) print option try: o...
d609d38b36058627551397902d070ee8594a9ead
64,952
def time_parse(s, format='%H:%M:%S'): """ Parse a time string in a IIS extended log format file. :param str s: The string containing the time to parse (HH:MM:SS format) :param str format: The optional strftime(3) format string :returns: A :class:`~lars.datatypes.Time` object representing the time ...
c947631730108339e10d8cda8c79dbdb92b1cd12
64,953
def dws_branch_k7_s2_p3(in_channels, out_channels, extra_padding=False, stem=False, data_format="channels_last", **kwargs): """ 7x7/2/3 version of the NASNet specific depthwise separable convo...
0016fa4b75a71af07339aceae1d7ae2c77e746d4
64,955
def findVariablesInFile(filepath): """Lists variables parsed from the given file Args: filepath: A path to a file containing Python code to be parsed Returns: A set of 4-tuples describing found variables {(str file, ast.stmt function_or_class, str variable, ...
df0347dd6511836cde2ba556d3f0cf5cae4ef4e9
64,957
def correct_slopes(X: np.array, vivo=False) -> np.array: """ Change Learning data to shape of series instead of series """ if not vivo: for i in range(0, X.shape[1], 3): X[:, i + 2] = X[:, i + 2] - X[:, i + 1] X[:, i + 1] = X[:, i + 1] - X[:, i + 0] else: for i in ran...
b92c21099d4b4aadf92392a157d6f6d23b471680
64,959
def tensor_to_ndarray(tensor): """ Convert float tensor into numpy image :param tensor: input tensor :type tensor: torch.Tensor :return: numpy image :rtype: np.ndarray """ tensor_np = tensor.permute(1, 2, 0).cpu().numpy() tensor_np = tensor_np.astype(np.float32) tensor_np = (ten...
b2c173f55b24c0bb998e447c80a8df7787b0b127
64,960
from typing import Tuple from typing import cast def ks_2samp(data1: np.ndarray, data2: np.ndarray) -> Tuple[float, float]: """Delayed version of scipy ks_2samp.""" return cast(Tuple[float, float], ks_2samp_(data1, data2))
7e745848c90a375a6c34dcba7817aa7e86c8fa79
64,961
def parse_indicators_command(sh, area): """ :param sh: :param area: :return: """ some_error = False issues = [] """ self._name = name self._formula = formula self._from_indicator = from_indicator self._benchmark = benchmark self._indicator_catego...
2a98272bfb06fb09328d3b1bad6163946b1e0cc7
64,963
def coordinate_generator(): """Return a generator which returns `count` randomly-generated coordinates in the range [-1000, 1000], in a mixture of floats and ints""" def wrapped(count=COUNT, seed=SEED): twister = Random(seed) def rand(is_int=False): n = (twister.random() - 0.5)...
7b4a250a5724d327cb308d0a25960d922b86f027
64,965
def get_data_path(data_path): """Return Blender data path.""" index = data_path.rfind('.') if index == -1: return data_path return data_path[(index + 1):]
b32b32cb624e87e278f72490e23fe5ccb7ae1206
64,966
from typing import Union from typing import List from typing import Tuple def get_members_from_args(guild: discord.Guild, potential_members: Union[List[str], Tuple[str]]) -> List[discord.Member]: """ Iterate over list and try :param guild: guild to search in :param potential_members: tuple or list wit...
3bc8c0ebb9c2797f4f9989ee8bcb37ccd8d66d73
64,967
def de2bi(decimals, n=None): """ Parameters ---------- decimals : ndarray vector of decimals n : int number of binary digits """ decimals = np.array(decimals) try: nd = np.ceil(np.log2(np.max(decimals))) except RuntimeWarning: print('{0}:{1}'.format(de...
25a07a2b86792f250fc86114d8a182a4586094d2
64,968
def text_node_for(context, text): """Outputs the text node with the forloop.counter incremented""" return ('<text id="%d">%s</text>' %(context["forloop"]["counter"]+1, text))
4fbf40884ed19e326ce7e1fdc6a9773ed14a40fc
64,969
def check_created_resource(db_output, resource_type): """Validation Checks for values and existence and responses """ if 'Invalid Data' in db_output: return make_response(jsonify({"status": 400, "error": "Check Input Values"}), 400) elif 'party' not in resource_type and 'Office Exists' in db_output:...
1726d7f7a4704c3f640379ddc68a1b5a9d6f9d40
64,970
import requests def get_base_info_single(bond_code: str) -> pd.Series: """ 获取单只债券基本信息 Parameters ---------- bond_code : str 债券代码 Returns ------- Series 债券的一些基本信息 """ columns = EASTMONEY_BOND_BASE_INFO_FIELDS params = ( ('reportName', 'RPT_BOND_CB_L...
7010b3ea4ac871ff2b370192f951f0b964b0e8bb
64,971
import aiohttp import async_timeout async def get_html(url): """ Retrieves HTML of a webpage """ async with aiohttp.ClientSession() as session: async with async_timeout.timeout(10): async with session.get(url) as response: return await response.text()
5a27c417b5ff1cbd0561fc38504f12e0ea4a5418
64,972
def GUI_Safe(func): """ Decorator to execute func into the GUI thread """ S = SignalCaller(func) return S.run
d23b21e973c3ac176ac1f540bc5b3fc261c2994d
64,973
def marg_dist(msgs, i, use_log=True): """ Calculate the marginal distribution of a variable node from the messages of a factor graph :param msgs: messages :param i: :param use_log: True if operations should be done in log space, False otherwise :return: marginal distribution of variable node i ...
bc2ae58728e69a8ed1e9745524d25c7e4a498492
64,974
def install_openssh_server(instance, args, verbose=True): """ Install and launch ssh server. Returns: int: Return 1 if the function works successfully, otherwise 0. """ install(instance, {"module":"openssh-server"}, verbose=False) instance.execute(["systemctl","start","ssh"]) return 0
4089e289fa2e2c70e6f2afffbe1579745c182b71
64,975
from typing import Dict from typing import Any from typing import Iterator from typing import Tuple def flatten(dictionary: Dict[str, Any]) -> Dict[str, Any]: """ >>> flatten({'foo':{'bar':{'baz': 0}, 'deadbeef': 1}, '42': 3}) {'foo.bar.baz': 0, 'foo.deadbeef': 1, '42': 3} """ def iterate(data: Di...
401f2f8894690a0c1171d26378ac4a5178dd705a
64,976
from typing import Optional def make_object_schema( var_schema: Optional[dict] = None, type_enum: Optional[list] = None) -> dict: """jsonschema of an encoded object. :param var_schema: Json schema of variable :param type_enum: Used to restrict a value to a fixed set of values. """ schema =...
6cd30e39f210e81f08132677637322e33631b7fd
64,977
def offline_validator_address(): """Ethereum address of the offline validator. The offline validator is the third positioned validator at the e2e_test_chain. He is meant to be not started at all and therefore becomes reported as offline. """ return "0xe7a664509027ff348d379bb5d3a8340aaecb56eb"
e89238a3a9d0bc938e60bdf8f52e0416a4a81987
64,978
def lstm_luong_attention_multi(): """Multi-head Luong attention.""" hparams = lstm_luong_attention() hparams.num_heads = 4 return hparams
d03d0f1f0aece05cfb17424579a309340a87f58b
64,980
def encode_label(dataframe, column, column_encoded, encoding_dictionary=None): """Encode ``column`` label in ``dataframe`` with ``encoding_dictionary`` provided. Parameters ---------- dataframe : pandas.DataFrame The DataFrame to read and to write to. column : str Name of the column...
223e61455493ea75247258c32ad87343ae609dbd
64,981
def effective_neighbor(G: nx.Graph, infected: int, target: list, compliance_edge_known:bool = False): """ Filters out edges of no transmission for G.neighbors """ effective_neighbors = set() for v in target: if check_edge_transmission(G, infected, v): effective_neighbors.add(v) ...
f6c12e832944663f55330a4e1ccc847364b50700
64,982
def xyz_there(s): """ Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. xyz_there('abcxyz') → True xyz_there('abc.xyz') → False xyz_there('xyz.abc') → True """ return False
16a882ac081e7b5cc7f75d66ce7d78c1efcc92b7
64,983
def stack_obs_space(obs_space, stack_size, stack_dim=-1): """ obs_space_dict: Dictionary of observations spaces of agents stack_size: Number of frames in the observation stack Returns: New obs_space_dict """ if isinstance(obs_space, Box): dtype = obs_space.dtype # stack 1...
0182301bdb2170752b477892f1a8dfa8c437c02a
64,984
def get_page_format(format, k=None): """Return page width and height size in points. Throws FPDFPageFormatException `format` can be either a 2-tuple or one of 'a3', 'a4', 'a5', 'letter', or 'legal'. If format is a tuple, then the return value is the tuple's values given in the units specified...
490a1a3c189121fd58d9e74ce483726e9284795d
64,986
def fromobject(thrift, tcls, obj): """Create thrift object with type `tcls` from a Python object. """ if isinstance(obj, tcls): return obj return globals().get(tcls.__name__, tcls)(thrift, obj)
fcb868dc460db835a4ec77fc08e8ed944fb8296b
64,987
def describe_zones(): """ Describe a specific zone or all zones. @return: Response. """ args = {'command': 'listZones'} response = cloudstack.describe_item( args, 'zone', errors.invalid_zone, 'ZoneName' ) return _describe_zones_response( response )
21e85162cba67030c0a093af0a6308aa6466c1f0
64,988
def restore_codebook(codebook_filename): """ reads the cluster_centers from the codebook file and restores a kmeans model to use for prediction """ cluster_centers = np.fromfile(codebook_filename) cluster_centers = cluster_centers.reshape(-1, int(cluster_centers[0])) # do this because the first ...
e6cb18d07fde2b54498ff08d789c620b8b5197ba
64,989
def Predict_serpent_isotope_response(serpent_filename, response_filename): """This function makes a Cherenkov light intensity prediction based on the isotope contents read from a Serpent output file and a isotope response function. Parameters ---------- serpent_filename : string Path ...
66e4db08ff6cb11597f58cbb0c9feb1962e8fa07
64,990
def subdivide_stats(data): """ If a key contains a ., create a sub-dict with the first part as parent key """ ret = {} for key, value in data.items(): if '.' in key: parent, subkey = key.split('.', 2) if parent not in ret: ret[parent] = {} ...
65e47db5c75118c1939a8ecdd3ad581a053da893
64,991
def delete_ip(request): """API delete_ip""" if request.method == 'POST': id = request.POST['id'] ip = get_object_or_404(IP, pk=id) ip.delete() ips = IP.objects.all() return render_to_response( 'spams/show_ips.html', { 'ips': ips, ...
0778f565e642a56d673e63498ce52b7e54f5847f
64,993
def tdig(tombfile, size, force=False): """ Dig a tomb of given size """ cmd = ['tomb', 'dig', tombfile, '-s', str(size), '--no-color'] if force: cmd += ["-f"] return execute(cmd)
3f0a5524f6554d73a0bb4c7f0af483c58eeab4bf
64,994
def cancel(f, *gens, **args): """ Cancel common factors in a rational function ``f``. **Examples** >>> from sympy import cancel >>> from sympy.abc import x >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) -(2 + 2*x)/(1 - x) """ options.allowed_flags(args, ['polys']) f = sympify(f) ...
af6cc6c694a0e3e484cffbd5bfdce64a96310cc6
64,995
import collections def run_parametrised_hmc(model_config, interceptor, num_samples=2000, burnin=1000, num_leapfrog_steps=4, num_adaptation_steps=500, num_optimization_s...
f06ac8e26f63a49d0eb12b82b69551f793d0f0c8
64,996
from typing import Optional def existing_external_event(external_id, events) -> Optional[CalendarEntry]: """Return existing external event or None.""" events = tuple(e for e in events if e.external_id == external_id) if len(events): return events[0] return None
0bc38241032654a584f7588d3cc3d794880c7a33
64,997
def get_ecg_path_example() -> path_t: """Return folder path to ECG example data. Returns ------- :class:`~pathlib.Path` or str path to folder with ECG raw files """ subject_ids = ["Vp01", "Vp02"] file_path = None # ensure that folder exists and data in folder is available f...
e2b4af3fbcfbd6bd075583c5c6e79854012d4599
64,998
def complete(request): """ Complete the authentication flow for the configured authenticator. """ def handle_request(request): # The auth_complete method of the authenticator should return a token or null # depending on whether authentication was successful token = auth_settings....
05038a21dff458f0aae66c1d5413f1c159c6f3d1
64,999
def conv1d(x, k, out_ch, dilation, init, scope, mask_type=None): """ 1-dimensional convolution x: batch_size x length x n_channels """ with tf.variable_scope(scope): in_ch = x.get_shape()[2].value w_shape = [k, in_ch, out_ch] strides = [1] dilation = [dilation] ...
4c72409997ea5c32b228e44ceb6d3b3b1f1bcaf6
65,000
def get_memory(isdsAppliance, statistics_duration, check_mode=False, force=False): """ Retrieving the Storage Usage Statistics """ return isdsAppliance.invoke_get( "Retrieving the Memory Usage Statistics", "/analysis/system_memory{0}".format( tools.create_query_string( ...
aa63aa5029b684960ccb57e6d3730a760ba94c69
65,001
def start_client(daemon, host, port, **kwargs): """Return a socket to an existing "remote" pydevd-handling daemon. The daemon supports the pydevd client wire protocol, sending requests and handling responses (and events). This is a replacement for _pydevd_bundle.pydevd_comm.start_client. """ s...
26b4e5e79a4b8aaf602cb5b713514358b4951fdc
65,002
import requests def get_specific_device_summary(device_id=DEVICE_ID): """Get an Operating System or Application Vulnerability Summary for a specific device.""" url = GET_DEVICE_VULN_SUMMARY.format(HOSTNAME, ORG_KEY, device_id) return requests.get(url, headers=HEADERS).json()
a15f559194a32ee2bed917f5658f11cb9f187f67
65,003
def remove_not_allowed_signs(string) -> str: """ :returns: String (eg. from object name) without all signs not allowed in file names and paths. """ for s in NOT_ALLOWED_SIGNS: string = string.replace(s, "") return string
a639b2965f5a717547a0bba746f0aea5918e4f35
65,004
from typing import Dict def event_device(user: User, device: Device, event_type: str = "decommission") -> Dict: """Prepare test device decommission event dictionary with user and device data.""" return { "action": event_type, "actor": {"id": user.id, "type": "user", "email": user.name}, ...
3a5d880a3f4758609b609ceaf7d4f1cf1ec67daa
65,005
import re def parentdir(file_path): """ Get the parent directory of a file or directory. Goes by the path alone, so it doesn't follow symlinks. On Windows, paths must be converted to use / before passing. This function is not the same as os.path.dirname(); for example, dirname will not giv...
baec28e9b6f0017566b91cd2b442a9eb783a144f
65,006
from datetime import datetime def check_params(args): """Check/cleanup parameter values in `args` and convert to a `dict`. """ params = {} params.update(args) input_ = params['input'] camera = False try: input_ = int(input_) camera = True except ValueError: ass...
85812ead40bb169a60e2c3dab41418588ce322e8
65,007
def calc_freefree_snu_ujy(ne, t, width, elongation, dist, ghz): """Calculate a flux density from pure free-free emission. """ hz = ghz * 1e9 eta = calc_freefree_eta(ne, t, hz) kappa = calc_freefree_kappa(ne, t, hz) snu = calc_snu(eta, kappa, width, elongation, dist) ujy = snu * cgs.jypercgs...
c595792646629e45dba6d6a6ae2dee586f9f83c9
65,008
def _Int(s): """Try to convert s to an int. If we can't, just return s.""" try: return int(s) except ValueError: assert '.' not in s # dots aren't allowed in individual element names return s
8f7fcf70717fe30ba991c8cff63cecefe5c01daf
65,009
def em(m, t, Omega, M): """ Trigonometric polynomial basis function. Parameters ---------- m : int Order of basis function. t : numpy.ndarray Times over which to compute the function. Omega : float Bandwidth (in rad/s). M : int Trigonometric polynomial or...
9d95aa622031262a550afbeb5fcab96545249514
65,010
def strlist_with_or (alist): """Return comma separated string, and last entry appended with ' or '.""" if len(alist) > 1: return "%s or %s" % (", ".join(alist[:-1]), alist[-1]) return ", ".join(alist)
1202e76d34f84618bb6b310bbc43c835f3c94104
65,011
def compare_authors_or_editors(db_entry, dqm_entry, datatype): # noqa: C901 """ Authors and Editors are in a hash with order of 'order' from db and 'authorRank' from dqm. They have to be sorted by the order, and for updates the db 'author_id' is used to patch. Currently we don't want to remove any authors, ...
01f8256da5728fdc6ab8595d59ab10ebe7e3827d
65,012
import awkward import vector import vector._backends.awkward_ import typing def zip( arrays: typing.Dict[str, typing.Any], depth_limit: typing.Optional[int] = None ) -> typing.Any: """ Constructs an Awkward Array of vectors, whose type is determined by the fields of the record array (which may be nest...
a04ae0e20dbb3f09ad375dd6229a61d2a5e6565a
65,013
def _tc_invert_ ( c ) : """Invert the cut >>> cut = >>> new_cut = ~cut """ nc = ROOT.TCut ( c .strip() ) tit = nc.GetTitle() if tit : return ROOT.TCut( '!(%s)' % tit ) ## return ROOT.TCut
c4d44e9f5d99dc8570bd398f9755c81bf3a3dd68
65,014
def main_covariance_estimation_SR( data_stack, cov_est_window_size, pixel_spacing_slant_rg, pixel_spacing_az, incidence_angle_rad, carrier_frequency_hz, range_bandwidth_hz, ): """Covariance estimation: inputs are in Slant Range radar coordinates see also main_covariance_estimation_G...
0c973bb9f0e88628882ecd188d687cbb5f5d0cfd
65,015
from typing import Optional from typing import Dict from typing import Type def ghidra_struct_to_strud( is_big_endian: bool, name: str, length: int, string_repr: str, all_struds: Optional[Dict[str, Type[AbStrud]]] = None, ) -> Type[AbStrud]: """ Make an strudra internal struct out of a ghi...
19a2b03ca6d30322e9bc912c5653c125137b7354
65,016
def program_marketing(request, program_uuid): """ Display the program marketing page. """ program_data = get_programs(uuid=program_uuid) if not program_data: raise Http404 program = ProgramMarketingDataExtender(program_data, request.user).extend() program['type_slug'] = slugify(pro...
a0cab850aae3a041cc697a5ebc7bf9112890176d
65,017
import torch def ensure_torch_random_state(random_state: TorchRandomHint) -> torch.Generator: """Prepare a random state for PyTorch.""" if random_state is None: random_state = random_non_negative_int() logger.warning(f"using automatically assigned random_state={random_state}") if isinstanc...
6dccbfc5e66ad792194139eb1f91aa7aa66f5327
65,018
import re def parse_jinja_comment(path): """ Parses jinja comment :param path: Path to jinja template :type path: str :returns: Jinja comment docstring :rtype: str """ f= open(path, 'r') contents= f.read() res=re.match(r"\{\#(.+?)\#\}", contents, flags=re.MULTILINE|re.DOTALL...
bfdfe73c1b7307c6c57e3539697a2f9eeb62d84a
65,019
import numbers def get_tstats_betsize(probs, N, num_classes=2, eps=1e-4): """Translate probability to bettingsize Args: probs (array-like) N (int): The number of estimators used for generating probs num_classes (int, optional): Defaults to 2 Returns: array-like: Signals a...
256b7cdea18c971b053f0614041ea9e881a4c027
65,020
def normalise(word): """Normalises words to lowercase and stems and lemmatizes it.""" word = word.lower() #word = stemmer.stem_word(word) #word = lemmatizer.lemmatize(word) return word
b1b158960bf6fc3a1fcc34d55dd25b9496ff9069
65,021
import array def errors(node_influence: array, byzantine_rate=0.0) -> array: """ Returns a stake-weighted population of adversarial members, with `byzantine_rate` being the *percentage* of the total weights. """ return node_influence.cumsum() < byzantine_rate
ed7efcae7c50a57b07b49d121002221e411db2ff
65,022
def FISTA(obs, psf, rho, max_iter=500): """Wrapper around FISTA :py:func:`FISTA_core` for a set of images :param obs: 3D set of images to deconvolve. :param psf: associated 3D set of point spread functions :param rho: hyperparameter of the augmented lagrangian. :param max_iter: maximal number o...
f1afec8a295a69d8abdc0184795f1be201697cb0
65,023
import math def getAngle(Gy, Gx, height, width): """ Computes the edge angle by taking the tan inverse of yGradient/xGradient :param Gx: :param Gy: :param height: :param width: :return: integer array representing the edge angle """ gradientData = np.empty(shape=(height, width)) ...
0f6cd641d7eb79ee3c793ee7764875993e97d6da
65,024
def generate_gate_swap( c_sys: "CompositeSystem", is_physicality_required: bool = True ) -> Gate: """Return the Gate class for the SWAP gate on the composite system. Parameters ---------- c_sys: CompositeSystem is_physicality_required: bool = True whether the generated object is physic...
fda4f5b3bd2ebf8fc599b949679cd7d8f6bff12f
65,026
def reformatPermissionErrors(function): """This function decorator will trap any permission error exceptions and raise a different exception with a nicer message.""" def new_func(*args, **kwargs): pass return new_func
e3482a6e93ea1d759ddb19ac8b8de90be1fd6651
65,027
def GetStagesToIgnoreForChange(build_root, change): """Get a list of stages that the CQ should ignore for a given |change|. The list of stage name prefixes to ignore for each project is specified in a config file inside the project, named COMMIT-QUEUE.ini. The file would look like this: [GENERAL] ignore...
d8546642b21c12a87f0dfebd9cbc28912cd9ed0a
65,028
import re def split_assignment_options(args): """ replace -a=b with -a b and --arg=b with --arg b :param args: :return: returns the updated arg list """ i = 0 p = re.compile('((-[a-zA-Z]=)|(--[a-zA-Z\-]+=))') while i < args.__len__(): m = p.match(args[i]) if m: ...
07d829c20383a0b6e6f27944b9cd7cc21ff420c1
65,030
def allInstalledPackages(allInstalledPackages): """ All installed packages in system """ osType = OSCheck.get_os_family() if OSCheck.is_suse_family(): return _lookUpZypperPackages( ["sudo", "zypper", "--no-gpg-checks", "search", "--installed-only", "--details"], allInstalledPackages) elif O...
e00c7aad3b2ce3ca0128bc1c01abe48adae9039c
65,031
def get_contact_emails(): """ returns email address of each contact """ return [contact.email[0].address for contact in contacts]
6a818d663c17529dc8d384ddf458be00aaa0ac50
65,032
def unique_slug_generator(instance, new_slug=None): """Generate new slug if current slug already exists""" if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: ...
2101b687e3a1ac59ba5180bae96307b488229fb2
65,034
def create_update(title:str,time:str,repeat:bool,covid_data:bool,news:bool) -> dict: """This method takes elements of an update and formats the update description shown to the user, and also assesses the update type. Args: title (str): Title of update given by user time (str): Time of updat...
f2ca2df838eb60f59d422b94c4723a68b9ab7197
65,035
async def what_status(status: str): """Checks what `status` the input may be. `status` subcommands are defined to be `died` and `anchored`. Args: status (str): the string to check for `status` Returns: str: the correct "status" if successful None: if invalid """ if re...
de8c0ecb76acfa43b7bf143b4914822595d58134
65,036
def values_dict(items): """Given a list of (key, list) values returns a dictionary where single-element lists have been replaced by their sole value. """ return {k: v[0] if len(v) == 1 else v for k, v in items}
7abcf62ab334cecc6e6996bad73ff10e5eecdf89
65,037
def filter_data(df, city, month, day): """ Filters by month and day if applicable. Args: (dataframe) df - the original raw data (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the da...
8844ee1b057af2cad5d81ad4f6824917487c7e16
65,038
def splitCubic(t, cubic): """Splits a cubic Bezier into two cubic Bezier at the given parameter t. Uses de Casteljau algorithm.""" a0 = lerp(t, cubic[0], cubic[1]) a1 = lerp(t, cubic[1], cubic[2]) a2 = lerp(t, cubic[2], cubic[3]) b0 = lerp(t, a0, a1) b1 = lerp(t, a1, a2) c0 = lerp(t, b0, b1) return (cubic[0],...
4d651cc49eea1fc4ec3bb3d5071fe97249016a21
65,039
def deleteAccount(user): """ Deletes the user's account. """ try: # delete the user from Firebase auth.delete_user(user.firebase_uid) # clear PII user.firebase_uid = None user.email = None user.phone_number = None user.service_provider_id = None # clear preferences user.em...
601b3b44078496ff13d5812754b0331e3fec9bea
65,041
def ssd_unsupported_nodes_to_plugin_nodes(ssd_graph, n_classes, input_dims, feature_dims): """Makes ssd_graph TensorRT comparible using graphsurgeon. This function takes ssd_graph, which contains graphsurgeon DynamicGraph data structure. This structure describes frozen Tensorflow graph, that can be mod...
9f8d49ca0e68515ea559e32dfcebaeda05dfc62b
65,043
def fibonacci_iterative(n): """ Compute the Fibonacci numbers with given number by iterative method :param n: given number :type n: int :return: the Fibonacci numbers :rtype: int """ if n == 0: return 0 elif n == 1: return 1 elif n < 0: return -1 fn,...
d3fd6a2977c145c2624c1c3fdbd527bab502bfe9
65,044
def generate_ignore_database_table(ignore_tables, table): """ :param ignore_tables: Dictionary :param table: String :return: Dictionary """ ignore_tables.append('--ignore-table=' + system.config['origin']['db']['name'] + '.' + table) return ignore_tables
b0f5ca4a7eb32bd93e9566967367ae8366b453ef
65,045
from typing import Tuple from typing import List def _make_line_buses(dss: win32com.client.CDispatch) -> Tuple[List[str], List[str]]: """ Make the bus names for all of the lines in the circuit. Parameters ---------- dss : win32com.client.CDispatch The OpenDSSEngine object. Returns ...
de2799ec4ea4752518574dbcb51f3f6ffe99b20c
65,046
def getmaskarray(arr): """ Return the mask of a masked array, or full boolean array of False. Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and the mask is not `nomask`, else return a full boolean array of False of the same shape as `arr`. Parameters ---------- arr...
bf1075d4e6c0105b699da608d649aba7220d1e99
65,048
def ghostnet(**kwargs): """ Constructs a GhostNet model """ cfgs = [ # k, t, c, SE, s [[3, 16, 16, 0, 1]], [[3, 72, 24, 0, 1]], [[3, 88, 24, 0, 1]], [[3, 96, 24, 0, 2]], [[3, 240, 40, 0, 1]], [[3, 240, 40, 1, 1]], [[3, 120, 40, 1, 1], ...
f4826d83363bac40d6543fa752b69294fcebca75
65,049
import click def describe_chute_network_client(ctx, chute, network, client): """ Display information about a network client. CHUTE must be the name of an installed chute. NETWORK must be the name of one of the chute's configured networks. Typically, this will be "wifi". CLIENT identifies the ne...
03c2802c454405c370970829228fcd6f7911817b
65,050
def get_root(): """ Returns the root folder. """ return 'data/simulators/lotka_volterra'
51351a55f678594707329fcf4fb3aa37e7340b31
65,051
def transform_to_normal(data_extremes, imin, imax): """ Transforming a random distribution to a normal distribution can be done in the following way: 1. Compute the values of the CDF. These values are the percentiles. These are (always) uniformly distributed. 2. Use the percent point function (inverse...
80775cb8b44188f1602713dc8b4da7410a22fe57
65,052
from base64 import encodestring from base64 import encodebytes as encodestring def uu_encode(binData, width = 64): """ uu encoding >>> print(uu_encode(b"12345678")) MTIzNDU2Nzg= >>> print(uu_encode("12345678")) MTIzNDU2Nzg= """ if is_python2(): else: if is_python3(): if is_string(binData): binData = bi...
b137cc343f45ca5abddb604c0c4de04975e08f22
65,053
def is_same_function(f1, f2): """returns true if f1 and f2 is same function Use case: sometimes when user defines some virtual function in base class, it overrides it in a derived one. Sometimes we need to know whether two member functions is actually same function. """ if f1 is f2: ret...
713a62b3453f00cffa0eea6d1f42dfe68860b094
65,054
def sameopenfile(fp1, fp2): """Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.""" return True
c6943dc157d19208e52a201adff563404ae221f7
65,055