content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_nearest_point_distance(points, wire1, wire2): """ >>> get_nearest_point_distance([(0, 0), (158, -12), (146, 46), (155, 4), (155, 11)], [((0, 0), (75, 0)), ((75, 0), (75, -30)), ((75, -30), (158, -30)), ((158, -30), (158, 53)), ((158, 53), (146, 53)), ((146, 53), (146, 4)), ((146, 4), (217, 4)), ((217, 4...
917ae2370497ec4ea753daed89a2ee82724887fc
22,383
def strip_tokens(tokenized: str) -> str: """Replaces all tokens with the token's arguments.""" result = [] pos = 0 match = RX_TOKEN.search(tokenized, pos) while match: start, end = match.span() result.append(tokenized[pos:start]) result.append(match.groupdict()['argument']) ...
b70c58ee45fc24e88269c99067a2f161b2b37e75
22,384
def circular(P=365, K=0.1, T=0, gamma=0, t=None): """ circular() simulates the radial velocity signal of a planet in a circular orbit around a star. The algorithm needs improvements. Parameters: P = period in days K = semi-amplitude of the signal T = velocity at zero phase...
33d3ea97d21ce1a14b07d02216597fe8977b2400
22,385
def set(isamAppliance, dsc, check_mode=False, force=False): """ Updating the tracing levels """ check_value,warnings = _check(isamAppliance, dsc) if force is True or check_value is False: if check_mode is True: return isamAppliance.create_return_object(changed=True, warnings=war...
1451ace2ed5ef6820e34ebb05d0879e3d5e3917b
22,386
from astropy.table import Table from astropy.time import Time def parse_logfile(logfile): """ Read iotime log entries from logfile Return Table with columns function duration readwrite filename timestamp datetime """ rows = list() with open(logfile) as fx: for line in fx: ...
8fb27648694df32e9035d0d24cae80f9ff9e654a
22,388
def histogram2d(x,y,n=10,range=None,density=False,keep_outliers=False,out=None): """2D histogram with uniform bins. Accelerated by numba x, y: array_like x and y coordinates of each point. x and y will be flattened n : scalar or (nx, ny) number of bins in x and y range : None or ((xmin,xmax)...
8faf591e769630540345565ff3a34f33e83f70ce
22,389
def _anatomical_swaps(pd): """Return swap and flip arrays for data transform to anatomical use_hardcoded: no-brain implementation for 90deg rots """ use_hardcoded = True # hardcoded for 90degs if use_hardcoded: if _check90deg(pd) != True: raise(Exception('Not implemented')) ...
2b958571597b72ca38de1310ca9a9e6a2caa69ac
22,391
from typing import List from typing import Dict def block_variants_and_samples(variant_df: DataFrame, sample_ids: List[str], variants_per_block: int, sample_block_count: int) -> (DataFrame, Dict[str, List[str]]): """ Creates a blocked GT matrix and...
4cf50f74b235adf5ef92ebde3a4a9259a3a49d87
22,392
def sparql_service_update(service, update_query): """ Helper function to update (DELETE DATA, INSERT DATA, DELETE/INSERT) data. """ sparql = SPARQLWrapper(service) sparql.setMethod(POST) sparql.setRequestMethod(POSTDIRECTLY) sparql.setQuery(update_query) result = sparql.query() ...
8e68c6672222a831203e457deaaac1ed73169fbf
22,393
def filtered_events(request): """Get the most recent year of stocking and pass the information onto our annual_events view. """ dataUrl = reverse("api:api-get-stocking-events") maxEvents = settings.MAX_FILTERED_EVENT_COUNT return render( request, "stocking/found_events.html", ...
b99d772656bab246b9f412f50674e402b7ca7476
22,394
import requests from datetime import datetime def track_user_session(user=None, request=None): """Creates, filters and updates UserSessions on the core and sends UserSessions to the hub on next login Filter the local UserSession objects per user and get their most recent user_session object If its a LOG...
f5733eed845d23dac945c7d23d09a4cccb2f4e14
22,395
def score(string, goal): """ Compare randomly generated string to the goal, check how many letters are correct and return """ check_counter = 0 string = generate(values) for i in range(len(string)): if string[i] == goal[i]: check_counter += 1 return check_counter
afcfcc565a898b2cdd22e05793144c710fb58e26
22,396
from datetime import datetime def validate_parent(): """ This api validates a parent in the DB. """ parent_id = request.json.get('parent_id', None) decision = request.json.get('decision', 0) parent = query_existing_user(parent_id) if parent: parent.validated = decision par...
3fe52863b4de24705c96aeaa67ee264916b37dbe
22,397
def parse_pdu(data, **kwargs): """Parse binary PDU""" command = pdu.extract_command(data) if command is None: return None new_pdu = make_pdu(command, **kwargs) new_pdu.parse(data) return new_pdu
0a5a84368793f8d5983b08bc2123bd0adb994be6
22,398
def alchemy_nodes(mol): """Featurization for all atoms in a molecule. The atom indices will be preserved. Parameters ---------- mol : rdkit.Chem.rdchem.Mol RDKit molecule object Returns ------- atom_feats_dict : dict Dictionary for atom features """ atom_feats_d...
8bccd62bafa77f6dc95bfba8992df48756b9ac0e
22,399
def generate(*, artifacts: artifacts_types.ModelArtifacts, name: str) -> str: """ Generate the class source from the schema. Args: schema: The schema of the model. name: The name of the model. Returns: The source code for the model class. """ model_artifacts = models_f...
6a510f031a9971a49057e114cc129f05737226df
22,400
def get_rot_mat_kabsch(p_matrix, q_matrix): """ Get the optimal rotation matrix with the Kabsch algorithm. Notation is from https://en.wikipedia.org/wiki/Kabsch_algorithm Arguments: p_matrix: (np.ndarray) q_matrix: (np.ndarray) Returns: (np.ndarray) rotation matrix """ ...
2cdd46af7f6f05acec23a6cf20e8ca561126c4f2
22,401
def _msrest_next(iterator): """"To avoid: TypeError: StopIteration interacts badly with generators and cannot be raised into a Future """ try: return next(iterator) except StopIteration: raise _MsrestStopIteration()
fe1877cfe4c05adb8bc082ea6a7d1ef54e324386
22,402
def record_export(record=None, export_format=None, pid_value=None, permissions=None): """Export marc21 record page view.""" exporter = current_app.config.get("INVENIO_MARC21_RECORD_EXPORTERS", {}).get( export_format ) if exporter is None: abort(404) options = current_app.config.get(...
2875c0fb019d5b8851c7cdcc31ac6ccd8e6b4002
22,403
from typing import List from typing import Tuple from typing import Optional def body_range( operators: List[str], font_changes: List[Tuple]) -> Tuple[Optional[int], Optional[int]]: """given some assumptions about how headers and footers are formatted, find the operations describing the body ...
aac320631a53653a770ba362c4826fca9f8fe673
22,404
import math def sine(value, default=_SENTINEL): """Filter and function to get sine of the value.""" try: return math.sin(float(value)) except (ValueError, TypeError): if default is _SENTINEL: warn_no_default("sin", value, value) return value return default
48cfcdef750ce497f8f36acee74c440ec244d31f
22,405
def wmt_affine_base_1e4(): """Set of hyperparameters.""" hparams = wmt_affine_base() hparams.kl_reg = 1e-4 hparams.learning_rate_constant = 2.0 hparams.learning_rate_warmup_steps = 8000 return hparams
f6d047737846aa0d4518045709f87b7b5f66d6fa
22,406
import random def random_crop_with_constraints(bbox, size, height, width, min_scale=0.3, max_scale=1, max_aspect_ratio=2, constraints=None, max_trial=1000): """Crop an image randomly with bounding box constraints. This data augmentation is used...
787c341f3f496eeedce18c42462efa5f5ba6515b
22,407
import re def unravelContent(originalData): """ This is the primary function responsible for creating an alternate data stream of unraveled data. Args: contentData: Script content Returns: contentData: Unraveled additional content """ contentData = normalize(originalData) ...
16c5c5b0bc1de026aa4ed8f931e171e11d3ecacc
22,408
import hashlib import struct def quote_verify(data, validation, aik, pcrvalues): """Verify that a generated quote came from a trusted TPM and matches the previously obtained PCR values :param data: The TPM_QUOTE_INFO structure provided by the TPM :param validation: The validation information provided...
bf23af17310252ff4a6fe73d16fbd2fffbc49618
22,410
def _rectify_base(base): """ transforms base shorthand into the full list representation Example: >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET >>> assert _rectify_base('hex') is _ALPHABET_16 >>> assert _rectify_base('abc') is _ALPHABET_26 >>> assert _rectify_base(10...
d88ce9edc3a4e134d04b97c6e5804590da90eb67
22,411
import gzip import json def loadjson(filename): """ Load a python object saved with savejson.""" if filename.endswith('.gz'): with gzip.open(filename, "rb") as f: obj = json.loads(f.read().decode("ascii")) else: with open(filename, 'rt') as fh: obj = json.load(fh) ...
5c8bc1446c5d48ebee51f11711b38ddce74835d2
22,412
def _write_ffxml(xml_compiler, filename=None): """Generate an ffxml file from a compiler object. Parameters ---------- xml_compiler : _TitratableForceFieldCompiler The object that contains all the ffxml template data filename : str, optional Location and name of the file to save. If...
b74434aeb481b11b7a9537932778fb596be205e7
22,413
from typing import List from typing import Union from datetime import datetime import pytz def get_utctime( md_keys: List[str], md: Union[pyexiv2.metadata.ImageMetadata, None] ) -> Union[datetime, None]: """Extract the datetime (to the nearest millisecond)""" utctime = None dt_key = "Exif.Image.DateT...
6f95e50725e865b36a31be48722376301cca4cc1
22,414
def find_file_recursively(file_name, start_dir=getcwd(), stop_dir=None): """ This method will walk trough the directory tree upwards starting at the given directory searching for a file with the given name. :param file_name: The name of the file of interest. Make sure it does ...
a7100e37a4f6244090c8b4363cda2b9893d27768
22,415
def text_cleaning(any_text, nlp): """ The function filters out stop words from any text and returns tokenized and lemmatized words """ doc = nlp(any_text.lower()) result = [] for token in doc: if token.text in nlp.Defaults.stop_words: continue # if token.is_punct: ...
7383f075a501c7c11565eac2c825c55f37e2a637
22,416
def shave(q,options,undef=MISSING,has_undef=1,nbits=12): """ Shave variable. On input, nbits is the number of mantissa bits to keep out of maximum of 24. """ # no compression, no shave # ------------------------ if not options.zlib: return q # Determine shaving parameters # ...
7d5f907f46a703c49f02f9cff3107d67ecc8c2a6
22,417
from typing import Union from typing import List from typing import Sized from typing import Iterable def any_none_nan(values: Union[List, np.ndarray, pd.Series, pd.DataFrame, object]) -> bool: """Can be used with a single value or a collection of values. Returns `True` if any item in `values` are `None`, `np...
659e3d90fe02487820a3cdc711422a7054500b89
22,418
def get_or_create_package(name, epoch, version, release, arch, p_type): """ Get or create a Package object. Returns the object. Returns None if the package is the pseudo package gpg-pubkey, or if it cannot create it """ package = None name = name.lower() if name == 'gpg-pubkey': retu...
e8a13b1a34e16c5f4e6de96bb66fb314fd301c10
22,419
def sort_dict(value, case_sensitive=False, by='key', reverse=False, index=0): """ 字典排序 :param value: 字典对象 :param case_sensitive: 是否大小写敏感 :param by: 排序对象 :param reverse: 排序方式(正序:True、倒序:False) :param index: 索引号(此处针对 value 为 list 情况下可根据 list 的某一 index 排序) :return: """ if by == 'key...
a41034cbd9ebd35cddcd0b4f321ffe8dc2613791
22,420
def initialize_system(name=None): """Initializes a distributed NPU system for use with TensorFlow. Args: name: Name of ops. Returns: The npu init ops which will open the NPU system using `Session.run`. """ return NPUInit(name)
3b1d50862954e57c8206af974412f79492982e23
22,421
def zmap_1perm_2samp(X, cat1, cat2=None, rand_seed=-1, fstat=None, name=None): """ une permutation X (D, N, P) K points, N subjects, D dim return: Y (D,) zvalue at each point """ if fstat is None: fstat = hotelling_2samples #name = "MP-Hotelling" if cat2 is None: cat...
87ffc6a0c49750e9a39295c2775483c4812d0205
22,422
def grids_have_same_coords(grid0, grid1): """Whether two `ESMF.Grid` instances have identical coordinates. :Parameters: grid0, grid1: `ESMF.Grid`, `ESMF.Grid` The `ESMF` Grid instances to be compared :Returns: `bool` Whether or not the Grids have identical coordin...
2fc5001a85694ac9b7b31a383436cc8792b665a4
22,423
def get_mwa_eor_spec(nu_obs=150.0, nu_emit=1420.40575, bw=8.0, tint=1000.0, area_eff=21.5, n_stations=50, bmax=100.0): """ Parameters ---------- nu_obs : float or array-like, optional observed frequency [MHz] nu_emit : float or array-like, optional rest frequency...
5bc97d666df938c4e5f42d2d429505e2b7f74004
22,425
def baseModel(data): """ 原有模型 """ formula = "label_code ~ education_num + capital_gain + capital_loss + hours_per_week" model = sm.Logit.from_formula(formula, data=data) re = model.fit() return re
7d66020dc2b527198c0b432b8c8fa9b703335d72
22,426
def load_screen(options: list) -> int: """Callback for loading a screen.""" return get_selection(options)
2c48fad6a644dad3ccf9ce1d2b4cbff8b841b043
22,427
def count_cells(notebook): """ The function takes a notebook and returns the number of cells Args: notebook(Notebook): python object representing the notebook Returns: len(nb_dict["cells"]): integer value representing the number of cells into the notebook A way ...
19ec2631888ecbba51fa51870694a7217024e5ae
22,429
from typing import OrderedDict def assignments(): """ This is called for the assignments tab on the instructor interface When an assignment is selected get_assignment is called to gather the details for that assignment. """ response.title = "Assignments" cur_assignments = db(db.assignments...
ac7834a96b876cadbcc91a7df9b59b9e51794142
22,430
from typing import Iterable from typing import Dict def get_sentences(data: Iterable[JSON_Object], match_by: str) -> Dict[Hash, JSON_Object]: """ Collect sentence objects w.r.t. matching criteria. :param data: Iterable of sentence objects :param match_by: Matching criteria / method ...
53430fcd65315dc98bd4bd0ac0c8a4d51dcef651
22,431
def str2bool(value): """ Args: value - text to be converted to boolean True values: y, yes, true, t, on, 1 False values: n, no, false, off, 0 """ return value in ['y', 'yes', 'true', 't', '1']
876a58c86b449ba3fac668a4ef2124ea31fda350
22,433
def numeric_float(max_abs: float = 1e3) -> st.SearchStrategy: """Search strategy for numeric (non-inf, non-NaN) floats with bounded absolute value.""" return st.floats(min_value=-max_abs, max_value=max_abs, allow_nan=False, allow_infinity=False)
b44764d88147793792ef90d96c17ec9770737fde
22,434
def add2dict(dict, parent_list, key, value): """ Add a key/value pair to a dictionary; the pair is added following the hierarchy of 'parents' as define in the parent_list list. That is if parent list is: ['5', '1'], and key='k', value='v', then the new, returned dictionary will have a value: ...
32252d3253283110eee2edb2eb216cfd777a710f
22,435
def transform(x): """ transform x1 x2 ---> 1 x1 x2 x1**2 x2**2 x1x2 |x1 - x2| |x1 + x2| """ ones = np.ones(len(x)) x1 = x[:,0] x2 = x[:,1] x1_sqr = x1**2 x2_sqr = x2**2 x1x2 = x1 * x2 abs_x1_minus_x2 = abs(x1-x2) abs_x1_plus_x2 = abs(x1+x2) return np.stack([ones, x...
380cc6e8f181cc192b11e3fd466526093a75e74b
22,436
import json def gen_new_contact_json(csv_data): """ Generate json with data about Subnets and theirs Contacts :param csv_data: entry data :return: Stats about created subnets """ dist = {"subnets": csv_data} with open(f'{PATH}{CONTACTS_SUFIX}', 'w') as out_file: out_file.write(json...
7615c76ea1c9fe392bd6d6d689b2b33a53beaa22
22,437
def resize(a, shape): """ if array a is larger than shape, crop a; if a is smaller than shape, pad a with zeros Args: a (numpy array): 2D array to resize shape: desired shape of the return Returns: numpy array: array a resized according to shape """ if...
40e0829b8680ea5753b12b4bd24e591b9b222bcf
22,438
def _Run(args, holder, url_map_arg, release_track): """Issues requests necessary to import URL maps.""" client = holder.client url_map_ref = url_map_arg.ResolveAsResource( args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL, scope_lister=compute_flags.GetDefaultScopeListe...
a04b277fa704e3cc8889a7a1feb7cf16b6040e91
22,439
import logging def resolve_function(module, function): """ Locate specified Python function in the specified Python package. :param module: A Python module :type module: ``types.ModuleType.`` :param function: Name of Python function :type ``str`` :return: Function or None if not found. ...
5885755f485d4dc243075aa9df6677cd52f3ebf8
22,440
import select def from_table(table, engine, limit=None): """ Select data in a database table and put into prettytable. Create a :class:`prettytable.PrettyTable` from :class:`sqlalchemy.Table`. **中文文档** 将数据表中的数据放入prettytable中. """ sql = select([table]) if limit is not None: s...
df66b3f179d3bde600786b3bc590810ac410b6eb
22,441
import tqdm import requests import zipfile from io import StringIO def futures_sgx_daily(trade_date: str = "2020/03/06", recent_day: str = "3") -> pd.DataFrame: """ Futures daily data from sgx P.S. it will be slowly if you do not use VPN :param trade_date: it means the specific trade day you want to f...
4b2aba7adb48066db1343469541b2007caa82d37
22,442
def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The ...
03344230339e66ac03ffa0ac2d5744475c311591
22,443
def get_response( schema, # type: GraphQLSchema params, # type: RequestParams catch_exc, # type: Type[BaseException] allow_only_query=False, # type: bool **kwargs # type: Any ): # type: (...) -> Optional[ExecutionResult] """Get an individual execution result as response, with option to ...
c451514b588956c59046140c42c18d79bb151170
22,444
def _get_status_arrays(): """ Get status for all arrays. """ results = [] try: # Get array(s) status for a site. result = get_status_arrays() if result is not None: results = result return results except Exception as err: message = str(err) ...
911a418f728e10949e756098414b7e0809fc2108
22,445
def get_cycle_amplitude(data, cycle, metric_to_use, hourly_period_to_exclude): """ given data (eg results[opposite_pair] [substratification][ substratification_level] ['take_simple_means_by_group_no_individual_mean']) and a cycle and a metric to use (max_minus_min or average_absolute_difference_...
bbbb3a0e7d97da4710319135deb583705fbb5a55
22,446
import requests import tqdm def _download(url: str, dst: str) -> int: """ @param: url to download file @param: dst place to put the file """ file_size = int(urlopen(url).info().get("Content-Length", -1)) r = requests.get(url, stream=True) with open(get_full_data_path(dst), "wb") as f: ...
55d748465d83d9d2a5408d4995c2363cf88090b2
22,448
def target2line(target, img_size, k, eval=False): """ target: line representetitve in grid [L, grid_h, grid_w] img_size: (width, height): Input image size, PIL Image size eval=False : Default. For inference. Line width not big. eval=True : For iou. Line width is bigger. return line_img """...
ca0ad3938261cdb31de5c1ad502bef2d16d3e6cb
22,449
import types def unmarshal(raw, signature): """Unmarshal objects. The elements of the returned tuple will be of types according to the column *Python OUT* in the :ref:`types summary <ref-types-table>`. :param RawData raw: raw message data :param signature: see :class:`~dcar.signature.Signature` ...
958761030418450cb65aeef2d966ef3d9157167c
22,450
def remove_keys(d, to_remove): """ This function removes the given keys from the dictionary d. N.B., "not in" is used to match the keys. Args: d (dict): a dictionary to_remove (list): a list of keys to remove from d Returns: dict: a copy of d, excluding...
94146bb19e8d39ea28c0940307c4c998fe5b7063
22,451
def get_crypto_quotes(**kwargs): """ Top-level function for obtaining all available cryptocurrency quotes """ return CryptoReader(**kwargs).fetch()
1eb94bf698e10b43e0cb4c794d7fb66a823295c3
22,453
def mutual_information(y_true, y_pred): """Mutual information score. """ # This is a simple wrapper for returning the score as given in y_pred return y_pred
fae45b40fb3ca285bef57e06b30c42d7f87b5286
22,454
from typing import Sequence from typing import Optional def AvgPool(window_shape: Sequence[int], strides: Optional[Sequence[int]] = None, padding: str = Padding.VALID.name, normalize_edges: bool = False, batch_axis: int = 0, channel_axis: int = -1) -> Intern...
17e523a6092db0d90eb6960e76a3f8fece94d57a
22,455
def pairwise_distances(x, y): """Computes pairwise squared l2 distances between tensors x and y. Args: x: Tensor of shape [n, feature_dim]. y: Tensor of shape [m, feature_dim]. Returns: Float32 distances tensor of shape [n, m]. """ # d[i,j] = (x[i] - y[j]) * (x[i] - y[j])' # = sum(x[i]^2, 1) +...
4928e02c0580f97b4a97db48c6d67f8e15000d46
22,456
import re def timerange(rstring): """ range from string specifier | 2010-M08 -> range of August 2010 | 2009-Q1 -> range of first quarter, 2009 | 2001-S1 -> range of first "semi" 2001 | 2008 -> range of year 2008 :param rstring: range string :rtype: timerange dictionary """ ...
d623e28ad4b040f833d96fed932117b8873f28ac
22,457
def comp_height_wire(self): """Return bar height Parameters ---------- self : CondType21 A CondType21 object Returns ------- H: float Height of the bar [m] """ return self.Hbar
98f98d021774166aa960080f353b6fbc01229eab
22,458
from datetime import datetime import logging def get_update_seconds(str_time: str) -> int: """This function calculates the seconds between the current time and the scheduled time utelising the datetime module. Args: str_time (str): Time of scheduled event taken from user input as a string...
0440ac847bc6c19290bdfa231971d33236335904
22,459
def full_name(decl, with_defaults=True): """ Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. :param decl: :class:`declaration_t` :type decl: :class:`declaration_t` :rtype: full name of declarati...
b9828bf4045baa2edbec0c5007406309d90391c5
22,460
def zero_pad(data, window_size): """ Pads with window_size / 2 zeros the given input. Args: data (numpy.ndarray): data to be padded. window_size (int): parameter that controls the size of padding. Returns: numpy.ndarray: padded data. """ pad_width = ceil(window_size / 2) padded = np.pad(data...
234f27f06bba9dff3a38292e1190b01a767bd56b
22,462
import requests def get_results(url_id): """Get the scanned results of a URL""" r = requests.get('https://webcookies.org/api2/urls/%s' % url_id, headers=headers) return r.json()
be5b660acd847066ec4c476dfe25d2fe21f8e2c4
22,463
def build_dense_constraint(base_name, v_vars, u_exprs, pos, ap_x): """Alias for :func:`same_act`""" return same_act (base_name, v_vars, u_exprs, pos, ap_x)
b35b07c3825a76ac046d8b32490cb5836ae6176a
22,464
from typing import Tuple from typing import Union def list_snapshots(client, data_args) -> Tuple[str, dict, Union[list, dict]]: """ List all snapshots at the system. :type client: ``Client`` :param client: client which connects to api. :type data_args: ``dict`` :param data_args: r...
5452b162d372a016fc63fded510e9361869581b8
22,465
def data_context_path_computation_context_pathuuid_linktopology_uuidlink_uuid_get(uuid, topology_uuid, link_uuid): # noqa: E501 """data_context_path_computation_context_pathuuid_linktopology_uuidlink_uuid_get returns tapi.topology.LinkRef # noqa: E501 :param uuid: Id of path :type uuid: str :para...
98c1b8721fb3edcc8cb3acc196e8c5aa8eb8a4f6
22,466
def ipfs_qm_hash_to_32_bytes(ipfs_qm: str) -> str: """ Transform IPFS base58 Qm... hash to a 32 bytes sting (without 2 heading '0x' bytes). :param ipfs_qm: IPFS base58 Qm... hash. :return: 32 bytes sting (without 2 heading bytes). """ return f"0x{b58decode(ipfs_qm).hex()[4:]}"
e60386928c3836edcd3ebef3740e1bbc8b095724
22,467
def get_service_state(scheduler): """Return the current state of the job service.""" return {"state": get_service_state_str(scheduler)}, 200
e18f66a2d2a2a97a37aed427178b65c2a9c8d919
22,468
def determine_file_type(filename): """ :param filename: str :rtype: FileType """ if filename.endswith('.cls'): return FileType.CLS elif filename.endswith('.java'): return FileType.JAVA elif filename.endswith('.js'): return FileType.JAVASCRIPT elif filename.endswi...
030d11266a8b93056c1d82778ba95a67fea7a799
22,469
def sanitise_text(text): """When we process text before saving or executing, we sanitise it by changing all CR/LF pairs into LF, and then nuking all remaining CRs. This consistency also ensures that the files we save have the correct line-endings depending on the operating system we are running on. ...
1d7d047fba7c8697748d0cf115e0f74fcad8c1c4
22,470
import string def create_regression( n_samples=settings["make_regression"]["n_samples"] ) -> pd.DataFrame: """Creates a fake regression dataset with 20 features Parameters ---------- n_samples : int number of samples to generate Returns ------- pd.DataFrame of features and ta...
b1d91b5e56366a8a2df7731550baedcf154e8c9a
22,471
def _divide_no_nan(x, y, epsilon=1e-8): """Equivalent to tf.math.divide_no_nan but supports bfloat16.""" # need manual broadcast... safe_y = tf.where( tf.logical_and(tf.greater_equal(y, -epsilon), tf.less_equal(y, epsilon)), tf.ones_like(y), y) return tf.where( tf.logical_and( tf.gre...
c7dc806bbdd7968fe61a9c7be76369b5608d9636
22,472
def make_release(t, **params_or_funcs): """Create particle release table to be used for testing""" t = np.array(t) i = np.arange(len(t)) params = { k: (p(i, t) if callable(p) else p) + np.zeros_like(t) for k, p in params_or_funcs.items() } start_date = np.datetime64("2000-01-0...
3dd2778dcf6962171d585244fc276832a300557c
22,473
import re def get_apartment_divs(driver): """Scrapes the url the driver is pointing at and extract any divs with "listitems". Those divs are used as apartment objects at Immowelt. Args: driver (Webdriver): A Webdriver instance. Returns: list: returns a list of all divs of class l...
ccef9159d7731ce78d5deeff92364e4bc43f5f3e
22,474
def smart_apply(tensor, static_fn, dynamic_fn): """ Apply transformation on `tensor`, with either `static_fn` for static tensors (e.g., Numpy arrays, numbers) or `dynamic_fn` for dynamic tensors. Args: tensor: The tensor to be transformed. static_fn: Static transformation function. ...
e2798377891ff6fc0ba4440357b83f927760bc59
22,475
import time def new_scan(host, publish = "off", start_new = "on", all = "done", ignoreMismatch = "on"): """This function requests SSL Labs to run new scan for the target domain.""" if helpers.is_ip(host): print(red("[!] Your target host must be a domain, not an IP address! \ SSL Labs will onyl scan do...
7c7341778028fac5d7c7829f9b57174f0fdb251c
22,476
def removeBubbles(I, kernelSize = (11,11)): """remove bright spots (mostly bubbles) in retardance images. Need to add a size filter Parameters ---------- I kernelSize Returns ------- """ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernelSize) Bg = cv2.morphologyEx(I...
193863cb63ed3a1a785aa2c64367eb7a3518c671
22,477
import operator import json def assert_json_response(response, status_code, body, headers=None, body_cmp=operator.eq): """Assert JSON response has the expected status_code, body, and headers. Asserts that the response's content-type is application/json. body_cmp is a callable that takes the JSON-decoded...
db910cb0cb68bdbf9ad4b9490f3bbc6a87d1545d
22,478
def variable(value, dtype=None, name=None, constraint=None): """Instantiates a variable and returns it. # Arguments value: Numpy array, initial value of the tensor. dtype: Tensor type. name: Optional name string for the tensor. constraint: Optional projection function to be ...
3dbb67493e4529469ca0da73159ec495b1d30f07
22,479
from typing import Protocol import json def autoprotocol_protocol(protocol_id): """Get autoprotocol-python representation of a protocol.""" current_protocol = Protocol.query.filter_by(id=protocol_id).first() if not current_protocol: flash('No such specification!', 'danger') return redirec...
85d0a3d5a215c50124c86b17114c82c60b07fae5
22,480
from re import T def tensor_to_P(tensor, wig3j = None): """ Transform an arbitray SO(3) tensor into real P which transforms under the irreducible representation with l = 1. Wigner-3j symbols can be provided or calculated on the fly for faster evaluation. If providedn, wig3j should be an array with...
c4cf2746ac0376b29df437e1938644c9df8e1dd2
22,481
from soc.modules.ghop.logic.helper import notifications as ghop_notifications from soc.modules.ghop.logic.models import comment as ghop_comment_logic from soc.modules.ghop.logic.models import task_subscription as \ def createNotificationMail(request, *args, **kwargs): """Appengine task that sends mail to the subscr...
859372c83fb37d440456c380cf313a27b029f018
22,482
def mergediscnodes(tree): """Reverse transformation of ``splitdiscnodes()``.""" treeclass = tree.__class__ for node in tree.subtrees(): merge = defaultdict(list) # a series of queues of nodes # e.g. merge['VP_2*'] = [Tree('VP_2', []), ...] # when origin is present (index after *), the node is moved to where ...
300aaebe95604c611ecf1f65373ba83f97361438
22,483
def count_go_nogo_trials(eventcode): """ :param eventcode: list of event codes from operant conditioning file :return: number of go and no go trials in the go/no go tasks """ lever_on = get_events_indices(eventcode, ['RLeverOn', 'LLeverOn']) (go_trials, nogo_trials) = (0, 0) for lever in le...
2de71a663f158a0942d2c3f01973ed5dc999b3d7
22,485
def getScriptExecutionContext(): """ Returns the repository description instance and the set of items selected on script action execution. @return: Script execution context. @rtype: L{ScriptExecutionContext<datafinder.gui.user.script_api.ScriptExecutionContext>} """ scriptExecution...
e49e8cfd140f967859cf0e0c75bfe69fac87835f
22,486
import copy import numpy def electrondensity_spin(ccdata, volume, mocoeffslist): """Calculate the magnitude of the electron density at every point in a volume for either up or down spin Inputs: ccdata -- ccData object volume -- Volume object (will not be altered) mocoeffslist -- list ...
7a232f2dbae8ff7905b2eff680a44521b010334e
22,487
def create_missing_dataframe(nrows, ncols, density=.9, random_state=None, index_type=None, freq=None): """Create a Pandas dataframe with random missingness. Parameters ---------- nrows : int Number of rows ncols : int Number of columns density: float Amount of availa...
e3c7f44f5238f929928ee5ec65c33bdb91fd8705
22,488
def decode_name_value_pairs(buffer): """ Decode a name-value pair list from a buffer. :param bytearray buffer: a buffer containing a FastCGI name-value pair list :raise ProtocolError: if the buffer contains incomplete data :return: a list of (name, value) tuples where both elements are unicode stri...
ef302eb2c6c55605fdc9b4a9ef06f59782ba1d94
22,489
def host_is_local(host: str) -> bool: """ Tells whether given host is local. :param host: host name or address :return: True if host is local otherwise False """ local_names = { "localhost", "127.0.0.1", } is_local = any(local_name in host for local_name in local_names...
ce823b8c309ec842ed1dd5bb04e41356db500658
22,490
def sigma_function(coeff_matU, coeff_matX, order, V_slack): """ :param coeff_matU: array with voltage coefficients :param coeff_matX: array with inverse conjugated voltage coefficients :param order: should be prof - 1 :param V_slack: slack bus voltage vector. Must contain only 1 slack bus :retu...
1accad7b95360a0652143ca367c54bca372662a7
22,492
from typing import List def get_dbs(db_names: List[str], db_file: str = "./db_info.pub.json") -> List: """Read the db_file and get the databases corresponding to <<db_name>> Args: db_name (List[str]): A list of names of the database we want db_file (str): The db_file we are reading from ...
ab0074f3cc5d846f7c24bf4bca6b348bfa3d6bf3
22,494