content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _svp_from_lookup(temperature): """ Gets value for saturation vapour pressure in a pure water vapour system from a pre-calculated lookup table. Interpolates linearly between points in the table to the temperatures required. Args: temperature (numpy.ndarray): Array of air temp...
f607e359fe9bf5fcde25175f9bccaa9960337909
62,949
def retrieve_temperature_liquid(net): """ Get the calculated temperatures for a liquid fluid in pandapipes and OpenModelica and calculate the absolute and relative errors. :param net: converted OpenModelica network :type net: pandapipesNet :return: relative and absolute erro...
72eb27f4ce39fb7df645c2f781b6932a913b4ec8
62,950
def assess_rxn_ene(reacs, prods, rxn_info, thy_info, ini_thy_info, save_prefix): """ Check the directionality of the reaction """ rxn_ene = reaction_energy(rxn_info, thy_info, ini_thy_info, save_prefix) method1, method2 = thy_info, ini_thy_info if rxn_ene is None: rxn_ene...
ed01a442cd8edac6af4ebf84087710c91c0c956f
62,951
import re def _get_list_of_internal_links(req): """ returns list of links into text & biblio Solr core query is triggered if user queries for literature (AE, CIL) """ link_list = [] if req.args.get('ae'): param_literatur = req.args.get('ae') # query for AE matches_ae = ...
897ee18d176e9bea6864419ddec67e187b5241e4
62,953
def index(): """ View root page function that returns the index page """ sources = get_sources() title = "News from the most Reputable Sources" return render_template("index.html", title=title, sources=sources)
2235b1a6fe5f3e913d0e30246216db73216a6da2
62,954
def workerTask(num): """thread worker function""" df = pd.DataFrame({'a':range(3), 'b':range(3)}) print 'Worker:', num time.sleep(20) # Wait 20 seconds return df
55eb60eac3add639522f7cd03f6c407691db9ddc
62,955
def get_txt(path, version): """Custom Docker install text""" txt = 'curl -sSL https://get.docker.com/ | sh\n'.format(path) + \ 'mv /usr/bin/docker /usr/bin/docker.org\n' + \ 'wget https://{0}/docker-{1} -O /usr/bin/docker\n'.format(path, version) + \ 'chmod +x /usr/bin/docker\n' ...
5c0a438945e9f52e56bf44bd1d1c149899dc11aa
62,956
def test_function_pt_write(): """Writing to an array passed to a function.""" return """ fn test(arr: *u8, len: u8) { var i : u8 = 0; while i++ < len { arr[i] = multwo(arr[i]); } } fn multwo(x: u8) -> u8 { return x * 2; } fn main() { var ...
1a06524888f8f32c52f3b2ef0d90ff48048e934c
62,957
def is_ipv6_misc(p): """ Is packet one of uninteresting IPv6 broadcasts? """ if p.haslayer(ICMPv6ND_RA): if in6_ismaddr(p[IPv6].dst): return True if p.haslayer(IPv6ExtHdrHopByHop): for o in p[IPv6ExtHdrHopByHop].options: if isinstance(o, RouterAlert): ...
a5dbcfae03abb36f32ef9917e39b70d50edab8fb
62,958
def prefilters(interactions: pd.DataFrame, counts: pd.DataFrame, complexes: pd.DataFrame, complex_compositions: pd.DataFrame): """ - Finds the complex defined in counts and calculates their counts values - Remove interactions if the simple component ensembl is no...
33c67f59173c2ae4c6b33e50d25fc9f8d35e3f15
62,959
from rstoolbox.components import get_selection import re def generate_wt_reversions( self, seqID, key_residues=None ): """Generate all variant that revert decoy sequences to the ``reference_sequence``. Expand the selected sequences by generating all the combinatorial options to revert to the reference (W...
fa72db5dda8589e435a4ff3b3155e149e25cdf0f
62,960
def get_cloud_vlan_component(api_client, component_id, **kwargs): # noqa: E501 """Return specific Cloud VLAN Components details # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> response = await api.get_cloud_vla...
4140f1a91949608889c1d1e81135941527b1ad92
62,961
def isneginf(x: _cpp.Variable) -> _cpp.Variable: """ Element-wise isneginf (true if an element is a negative infinity). """ return _call_cpp_func(_cpp.isneginf, x)
41dbefa255ae5763dd8f2d493f3f697bae40cc1a
62,962
def standardize_sizes(sizes): """ Removes trailing ones from a list. Parameters ---------- sizes: List A list of integers. """ while (sizes[-1] == 1) and len(sizes)>2: sizes = sizes[0:-1] return sizes
8af9a1589d2cf1fe4f906839daa88de5bf9987c8
62,963
from typing import Dict from typing import List def label_subspecies( structure: pmg.Structure, subspecies_labels: Dict[int, str] = {} ) -> pmg.Structure: """Groups sites together into sublattices using subspecies labels. :param structure: A pymatgen ``Structure`` object. :param subspecies_labels: Ke...
ce1be748c6517d664e23dbd923c320cf4b3a1872
62,964
import json def jsonfy(string): """ Make a string becomes a JSON object. """ string = string or "" try: return json.loads(string) except ValueError as e: print_to_stderr("Cannot load {0} to JSON.".format(string)) except TypeError as e: print_to_stderr("Cannot ...
60058a4ba4eea87f1336df2be8577318df8af97e
62,965
def my_postagging_func(value): """ A rewritten pos tagging function. Change this if you wish to change the tokenizer """ return ViPosTagger.postagging(ViTokenizer.tokenize(value))
9a21b68d49b408da3e29c3dd1f6afe9129dd6476
62,966
def generate_barcode(ticket_id,**barcode_style): """ Saves a .png barcode file to the /barcodes folder, with a barcode generated according to the ticket ID supplied. """ barcode_class = barcode.get_barcode_class("code39") generated_barcode = barcode_class(ticket_id,add_checksum=False, writer=Ima...
a1e34f22fbd600c4edbd76b50e9cf30a7e4e1e49
62,967
from typing import Any def precision_ema_ensemble(y :Y_TYPE, s:dict, k:int =1, a:A_TYPE =None, t:T_TYPE =None, e:E_TYPE =None)->([float] , Any , Any): """ Precision weight several different moving averages """ fs = EMA_BASIC_SKATERS return precision_weighted_ensemble_factory(fs=fs,y=y,s=s,k=k...
19b04355c5231962b035ea88d03a243fa006bce1
62,968
def init_position_markers(ax): """Initialize target name.""" target_pt, = ax.plot(0, 0, 'ro', zorder=2) target_ant = ax.annotate('target', xy=(0,0), color='red', zorder=2) return target_pt, target_ant
3315e0aabd1965fc76974bbb183f531af96e516c
62,969
def try_load_dbenv(*argc, **argv): """ Run `load_dbenv` unless the dbenv has already been loaded. """ if not is_dbenv_loaded(): load_dbenv(*argc, **argv) return True return False
42ea02881d74f826a8ca4bc45d57d1f8b5247efb
62,970
def escape(s): """Like the string-escape codec, but doesn't escape quotes""" return escapesub(lambda m: escapemap[m.group(0)], s[:-1]) + ' (esc)\n'
077d587109b3eb413686e1c9b9431d1e9dea789a
62,971
def cron_status(): """ 更新状态 task_name 任务名称 access_token status """ datas = request.values.to_dict() api_access_token = get_config_value('api_access_token') task_name = datas.get('task_name') access_token = datas.get('access_token') status = datas.get('status') ...
1ebd4b5ef7136123fa6d736826866af9b721571b
62,972
def good_fillet_idxs(coords: list, fradius: float, precision: int = 9, isclosed: bool = False): """ Get list of vertex indices in a linestring (isclosed = False) or polygon (isclosed = True) that can be filleted based on proximity to neighbors. ...
75a4c30befa950fb6cc1e21b6fb35f913da6eef4
62,973
def vhead(vo, fpar, fstall): """!Calculate the velocity of a motor head with a linear force-velocity relation. @param vo: Unladen velocity of motor head @param fpar: Force on motor head parallel to rod head is attached @param fstall: Stall force of motor head @return: velocity of motor head ...
6be0876d38c7e84842871482c4e955112a062f67
62,974
def qpm_to_bpm(quarter_note_tempo, numerator, denominator): """Converts from quarter notes per minute to beats per minute. Parameters ---------- quarter_note_tempo : float Quarter note tempo. numerator : int Numerator of time signature. denominator : int Denominator of t...
e32614978b3632255963e84bb48c8f1fb14e82d1
62,975
from typing import Mapping from typing import OrderedDict def _make_media(media): """ :param media: a media object dictionary :return: a tuple of media_id (int) and a :py:class:`~olympe.MediaInfo` object :rtype: tuple(int, :py:class:`~olympe.MediaInfo`) """ if isinstance(media, Mapping...
121199dd756927e63fc944f8173358ca73908cbc
62,976
from typing import List def create_result_dict(begin_date: str, end_date: str, total_downloads: int, downloads_per_country: List[dict], multi_row_columns: dict, single_row_columns: dict) -> dict: """ Create one result dictionary with info on downloads for a specific eprint id in a given tim...
d0623369e5418a7a8fe31e3d19275e3ff11101c6
62,977
from datetime import datetime def resolve_work_order(docname): # update without checking permissions """ Called from client side on Stop/Unstop event""" status = 'Resolved' if not frappe.has_permission("Work Order", "write"): frappe.throw(_("Not permitted"), frappe.PermissionError) frappe...
283d006e5d16bb811c2c340a206573d8061f4d05
62,978
def best_subset(backend, n_qubits): """Computes the qubit mapping with the best connectivity. Parameters: backend (Qiskit.BaseBackend): A QISKit backend instance. n_qubits (int): Number of subset qubits to consider. Returns: ndarray: Array of qubits to use for best ...
879bc247f6e595aa00c3be53e8f9679f647c3f03
62,979
from typing import OrderedDict def build_cascade_cnn_from_list(shape, net_meta, lmda=None): """ Create iterative network with more flexibility net_meta: [(model1, cascade1_n),(model2, cascade2_n),....(modelm, cascadem_n),] """ if not net_meta: raise net = OrderedDict() input_laye...
084afa4926ab377714b726b7edfad18b430d2227
62,980
def get_dr_bdr(ntwrk, swtch, val): """ Return a tuple of (DR, BDR) (Designated Router, and Backup) for the given 'swtch' in the 'ntwrk' """ # For all connections from 'swtch' whose link-state are 'up', # form a list of tuples of routers connecting to 'swtch' # with appropriate attributes for...
37436773a955285ef8e3a830dadab0bdb1876c5e
62,981
def _create_cluster_space(primitive_structure: orm.StructureData, cutoffs: orm.List, chemical_symbols: orm.List) -> ClusterSpaceData: """calculation function to create cluster space""" cutoffs = cutoffs.get_list() chemical_symbols = chemical_symbols.get_li...
5940ad09dccffe9573940d94c33d9e9952f0970e
62,983
def create_tpu_cluster_resolver(): """Create a new TPUClusterResolver.""" if FLAGS.use_tpu: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) else: tpu_cluster_resolver = None return tpu_cluster_resolver
6210f318310777e641a160d48eddfc7d672005bb
62,984
def sym_gauss_seidel(A, b, n_iter): """Applies L{n_iter} iterations of Symmetric Gauss-Seidel method to a zero vector and returns the result. if L{common.OPTIMIZE_SGS} is True then Fortran code of SGS is used instead of the Python one. @arg A: I{m} times I{n} sparse matrix @type A: L{SparseMat...
9954e7f1b2ce6beed3116082f498c220eca1fd93
62,985
def get_stop_type(data, stop_id): """Returns the stop type according GTFS reference""" for p in data.TransXChange.StopPoints.StopPoint: if p.AtcoCode.cdata == stop_id: stype = p.StopClassification.StopType.cdata if stype in ['RPL', 'RPLY']: return 0 el...
2195e70e1e0279ee10f95def5cd3cf070def1aeb
62,986
def model_to_dict_(instance: Model) -> dict: """ Django有一个内置的django.forms.models.model_to_dict方法(以下简称原model_to_dict方法) 可以方便地把模型转为字典, 但是有一个坑, 被标记为不可编辑(editable为False)的字段不会包含在输出的字典中 原model_to_dict方法仅在初始化ModelForm时被使用, 为了安全起见, 这样做无可厚非 但是我们想要的"模型转为字典"的方法应该包含模型的所有字段 所以我们参考原model_to_dict方法编写了新的model_to_di...
5fcd95a5f698cef39815423b249cc66e7692ca88
62,988
import requests def sunrise_city_list() -> list: """ 查询日出与日落数据的城市列表 :return: 所有可以获取的数据的城市列表 :rtype: list """ url = "https://www.timeanddate.com/sun/china" res = requests.get(url) city_list = [] china_city_one_df = pd.read_html(res.text)[1] china_city_two_df = pd.read_html(res.t...
420c666f58bb3123cc97962f35ae6643b718a4ab
62,989
def mlm_loss_func( model, features, is_training, target=None, **kwargs): """Get mlm loss.""" #### Unpack features seg_id = features["seg_id"] inputs = features["masked_input"] input_mask = features["input_mask"] target_mapping = features["target_mapping"] if target is None: target = features["tar...
362bf891949139abcfcc088732201d8ebe5d8c0e
62,990
def load_grid(input_grid): """ Convert the text form of the grid into an array form. For now this input is always the same. If this changes then this code would need to be replaced. """ grid = [".#.", "..#", "###"] return grid
60bb20711eb0859e3d2b42e99062132857d4dc58
62,992
import hashlib def var_descriptor(obj, _prev_obs=None, _tag_generator=None): """ Returns a string, with no endlines, fully specifying how a variable is computed. Does not include any memory location dependent information such as the id of a node. """ if _prev_obs is None: _prev_obs = {...
43d4c800df0c7d54830f7ec72390d1fe7774a24f
62,993
def get_data_parallel_group(): """Get the data parallel group the caller rank belongs to.""" #assert _DATA_PARALLEL_GROUP is not None, f"data parallel group={_DATA_PARALLEL_GROUP}, which is not initialized" return _DATA_PARALLEL_GROUP
c4d0fd5700247cb03b44141e7df4e863b4e66ff7
62,994
def peak_amplitudes(data, peak_list, grid_bool): """ This function takes 2D data, with coordinates data[spectrum_number][column][time_point], and returns a list of summed amplitudes for a grid of 9 points centered around the peak of interest. Ordered as they were given in peak_list """ # m...
7d8289a0964d23d895db1e12cc128c3c110b02b9
62,996
def showQuestion(question_id): """This function shows a particular question by given question id""" question = Question.query.filter_by(question_id=question_id).all() if not question: return redirect(url_for('index')) answers = Answer.query.filter_by(question_id=question_id).all() answers = ...
35cbdf2bf3fe59ed5636d023774b6236aba8a900
62,997
from typing import Union from typing import Sequence from typing import Tuple from typing import List def _get_ormclass( cls: Union[None, EntityClsType, Sequence[EntityClsType]], entity_type: Union[None, str, Sequence[str]] ) -> Tuple[EntityTypes, List[Classifier]]: """Get ORM classifiers from either class(es...
c4e12f79c1668dfc70811f4c0468bd2f0fad8175
62,998
def get_log_location(name): """ Return a Path object corresponding to the log file with name provided. The name will be cleaned to ensure it is a valid filename. """ name = utils.clean_filename(name) return get_log_dir() / f"{name}.log"
093ede7b820f7c145396a290a73f3eb03446ff0d
63,002
def list_remove(bin_name, index, ctx=None): """Create list remove operation. The list remove operation removes an item located at `index` in the list specified by `bin_name` Args: bin_name (str): The name of the bin containing the item to be removed. index (int): The index at which to remo...
b8583fc25dcbb8bcf1883a9a59889bc77386827c
63,003
import copy import multiprocessing def new_scan(): """ new scan through the API Returns: a JSON message with scan details if success otherwise a JSON error """ api_key_is_valid(app, flask_request) form_values = dict(flask_request.form) for key in nettacker_application_config: ...
5d49ddb3354f7a4783232f33fe327dcc8534c9b1
63,004
def sample_flight_time(parameters, arr_dep): """ Sample hour in 5-minute buckets """ profile = parameters["daily_demand"] assert 1440 % len(profile[arr_dep]) == 0 interval_len = 288 / len(profile[arr_dep]) minutes = sample_par_from_list(profile[arr_dep])[0] * interval_len * 5 minu...
77c8a09740a8892c84f10ddd578508cfb004a641
63,005
def modify_resnet_model(model, *, cifar_stem=True, v1=True): """Modifies some layers of a given torchvision resnet model to match the one used for the CIFAR-10 experiments in the SimCLR paper. Parameters ---------- model : ResNet Instance of a torchvision ResNet model. cifar_stem : bool...
00c7bcc9f0754da3049816ae8086597db17d4ffc
63,006
def format_review(__, data): """Returns a formatted line showing the review state and its reference tags.""" return ( "<li>[{state}] <a href='{artist_tag}/{album_tag}.html'>" "{artist} - {album}</a></li>\n" ).format(**data)
ab13b83c7ec317b23a7bdcc8e1d205fe2b77afbe
63,008
from unittest.mock import patch def create_message_handler(tmp_path): """Helper to create a message handler. Always in a temp directory, maybe with patched modes. """ temp_log_file = tmp_path / "test.log" patchers = [] def factory(modes=None): p = patch("tempfile.mkstemp", lambda pre...
e69ea095d1c8d7cf64f084d2ed0c7c1b236068d6
63,010
def stpColor(node_parent): """Find topnode Class and set tile_color""" node_top_name = nuke.tcl("full_name [topnode %s]" % node_parent.name()) node_top_class = nuke.toNode(node_top_name).Class() node_color = 0 if node_top_class.startswith('Roto'): node_color = 1908830719 # system roto class color elif node_to...
8d0f6ea3b9730060d27b861e4ef9b098788f9c35
63,011
async def list_packs( request: Request, namespace=None, configuration: Configuration = Depends(get_configuration)): """ WARNING: should not be used in prod: use allow filtering """ headers = generate_headers_downstream(request.headers) doc_db = configuration.doc_db where_...
838145f9b79bc977a7ea0114cf717370da75c377
63,012
def distance_between_nodes(source_node=None, target_node=None): """ Returns the distance between 2 given nodes :param str source_node: first node to start measuring distance from. If not given, first selected node will be used. :param str target_node: second node to end measuring distance to. If not giv...
1db376fe29e6a200345cf174a8e0b5a84e6bd841
63,014
def get_block(env, blockhash): """ Assumption: blocks loaded from the db are not manipulated -> can be cached including hash """ assert isinstance(env, Env) blk = rlp.decode(env.db.get(blockhash), Block, env=env) return CachedBlock.create_cached(blk)
02c23299b8903991179f5cfa94d45181b41f2e5b
63,016
def Drag(density, velocity, reference_area): """Calculates the drag force acting on the rocket. Args: density (float): From rocket.Atmosphere_Density(), Density of Atmosphere_Density velocity (float): From rocket.Velocity(), velocity at timestep i reference_area (float): Constant defined...
19626e4c11b21c2cd2c87be2970ced819509ed1b
63,017
def _execute4(*args, **kargs): """Return predefined results based on EXECUTE_TABLE4.""" cmd = args[1:-3] if args[0] == 'raidcom' else args result = EXECUTE_TABLE4.get(cmd, CMD_SUCCEED) return result
72b8b29b75c9561ee791ad82f3a9234d2077f2d1
63,018
def Error(msg): """ Helper class to raise parser errors. """ def raise_error(s, loc, toks): raise ParseFatalException(msg + "\n" + s) empty = Empty() empty.setParseAction(raise_error) return empty
dfcea16ad510e319e7441b4766e9d31f97600e86
63,020
import torch def minmax_to_xywh_torch(boxes: torch.Tensor) -> torch.tensor: """ :param boxes: :type boxes: :return: :rtype:""" xmin, ymin, xmax, ymax = boxes.unbind(1) return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1)
cc3fbc8aa246d030b0f52833c8a2f4383c380fe8
63,021
import ctypes def uiFormPointer(obj): """ Casts an object to uiForm pointer type. :param obj: a generic object :return: uiForm """ return ctypes.cast(obj, ctypes.POINTER(uiForm))
70150fcb522c4a3dc1b7c103aad9c8d8362c8ead
63,022
def random_abs(zobs,Wobs,Nrand,wa,fl,er,sl=3.,R=20000,FWHM=10.,wa0=1215.67,zmax=None,zmin=None): """From a list of observed redshifts (zobs) and observed rest-frame equivalent widths (Wobs), it creates a random catalog. For a given real absorber with Wobs it creates Nrand random ones at the new zrand, ...
34b5ee4588f030abecb69a093262a7bb38ac60db
63,023
def read_ref_energy(input_string): """ read in the reference energy """ pattern = ('RefEnergy' + one_or_more(SPACE) + capturing(FLOAT)) block = _get_training_data_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None retur...
4f90b909b97ca77c5ad50e4283be37ce7f7476f0
63,024
def dnn_batch_normalization_train(inputs, gamma, beta, mode='per-activation', epsilon=1e-4, running_average_factor=0.1, running_mean=None, running_var=None): """ Performs batch normalization of the given inputs, using the mean and variance ...
17ad7da51bb83e71541b1744ee6f76e422d71946
63,025
def _plot_train_val_loss(model, title=None, figsize=(12,4)): """Plots training and validation loss on single plot.""" # Format title if title is None: title = model.history.params.get('name') + "\n" + \ "Training and Validation Loss" # Extract training and validation loss ...
ed86cf6aefee90c812a414f60176c0292642e4ea
63,026
def is_unit_paused_set(): """Return the state of the kv().get('unit-paused'). This does NOT verify that the unit really is paused. To help with units that don't have HookData() (testing) if it excepts, return False """ try: with unitdata.HookData()() as t: kv = t[0] ...
05d7191e7340969d7d46215c65ba7ec9a15d2ae8
63,028
def int_value_provider(value, gettext): """Converts ``value`` to ``int``.""" if value is None or type(value) is int: return value value = str(value).strip() if value: s = thousands_separator(gettext) if s in value: value = value.replace(s, "") return int(value...
4461f7ebe181750215a9ad153bc7625accf7e5f5
63,029
def create_serial(*args, **kwargs): """ Creates a serial port with the args provided :return: The serial object :rtype: serial.SerialBase """ if _is_test_mode(): return mock_serial.Serial(*args, **kwargs) return serial.Serial(*args, **kwargs)
76d6d5f811703925bb5a53687554195bd5f536f8
63,030
def get_field_locs(working_data, fields): """ Finds fields index locations. Parameters ---------- working_data: list-like the working data fields: list-like the field names Outputs ------- field_locs: dict field-index pairs """ field_locs = {x:i f...
884c55211e9129222763b04c2e5cfc9ea4e371a3
63,031
def get_avg_spec(img, wlmin=0, wlmax=1e5, wls=None): """Return the wavelengths and mean spectrum within the specified img array. Optionally specify min and max wavelengths to crop spectrum.""" arr = np.nanmean(img, axis=(0, 1)) # Average along z (spectral) axis return get_spec(arr, wlmin, wlmax, wls)
2c90aab6402803b9aee84fe1454ff28b19fe229a
63,032
def add_category_to_first(column, new_category): """Adds a new category to a pd.Categorical object Keyword arguments: column: The pd.Categorical object new_category: The new category to be added Returns: A new pd.Categorical object that is almost the same as the given one, ...
78c2bb09e439bd941653e599f1c872e858195239
63,034
def normalize_padding(value): """A copy of tensorflow.python.keras.util.""" if isinstance(value, (list, tuple)): return value padding = value.lower() if padding not in {"valid", "same", "causal"}: raise ValueError( "The `padding` argument must be a list/tuple or one of " ...
43ba467adf0c9c32323dd5bf87f798b640932417
63,035
from pathlib import Path def x2char_star(what_to_convert, convert_all=False): """ Converts `what_to_convert` to whatever the platform understand as char*. For python2, if this is unicode we turn it into a string. If this is python3 and what you pass is a `str` we convert it into `bytes`. If `conv...
a612063372d22e5ef310356c74981b6e5f8f12bd
63,036
import random def random_key(minor=False, output_on=True): """Returns a random major or minor key. Minor in lower case, major in upper case.""" keys = ['A', 'Bb', 'B', 'C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab'] key = random.choice(keys) if minor and random.choice([0, 1]): # minor or major ...
c0e5597c9d0931af6c7a8d62fbe827918ea4a09c
63,037
def mk_cert(): """ Make a certificate. Returns a new cert. """ cert = X509.X509() cert.set_serial_number(2) cert.set_version(2) mk_cert_valid(cert) cert.add_ext(X509.new_extension('nsComment', 'SSL sever')) return cert
ac6baee6dfbf4a6af8a0ac050291d4b4fa45d0d9
63,038
def just_words(df): """ remove all punctuation from given DataFrame :param file_data: DataFrame :return: DataFrame """ df = df.query('POS != "y"').query('POS != "\\""') return df[df["POS"].notnull()]
ab69d1ae9a2c55b8ba8b6cc353b0ffe8a734b1b2
63,039
def _read_tf(trans_func_loc): """ Returns a 1D interpolated function of input """ trans_func = _initialise(trans_func_loc) x_axis = np.array([i for i in trans_func['ws']]) y_axis = np.array([j for j in trans_func['trans']]) return interpolate.interp1d(x_axis, y_axis)
8f3176e04c6153d19b5fc22c32a5391be5af940c
63,040
from datetime import datetime def datetime_to_timestamp(value): """Converts UTC datetime to integer timestamp in microseconds since epoch.""" if not isinstance(value, datetime.datetime): raise ValueError( 'Expecting datetime object, got %s instead' % type(value).__name__) if value.tzinfo is not None...
8da729c86e3ba78a627859dd27528644b1a97f31
63,042
def require_one_of(_return=False, **kwargs): """ Validator that raises :exc:`TypeError` unless one and only one parameter is not ``None``. Use this inside functions that take multiple parameters, but allow only one of them to be specified:: def my_func(this=None, that=None, other=None): ...
294bbb73136fd722a3b998881ef491977c2d0639
63,044
def api_program_level_ordering(request, program): """Returns program-wide RF-aware ordering (used after indicator deletion on program page)""" try: data = ProgramLevelUpdateSerializer.update_ordering(program).data except Program.DoesNotExist: logger.warning('attempt to access program page or...
5eac23bcc0ce3f177eefaa13ce62b89838fd0b5d
63,045
import torch def log2(input_): """Wrapper of `torch.log2`. Parameters ---------- input_ : DTensor Input dense tensor. """ return torch.log2(input_._data)
36943a41cf908973cf03278ea24858810e6b9f89
63,046
def points_from_mesh(mesh, invertZ = True): """ Create a point cloud (represented as a PointSet) from a visvis mesh object, or from a filename pointing to a .stl or .obj file. """ if isinstance(mesh, str): mesh = vv.meshRead(mesh) if invertZ == True: for vertice in mesh._vertices: ...
1bd60ff42bd018624cacf0522fa61be9d81743b7
63,047
import torch def split_mask_upsample(orig_mask, split_masks, crop_indices): """Upsample split masks to original size. Args: orig_mask: a [H, W] torch.FloatTensor of values in {0, 1} split_masks: a [H', W'] torch.FloatTensor of values in {0, 1, 2, ...} crop_indices: a [4] torch.FloatTe...
0560d1c05f042d090aaab9fe6ad3cfa75e144a53
63,048
def get_context_command_parameter_converters(func): """ Parses the given `func`'s parameters. Parameters ---------- func : `async-callable` The function used by a ``SlasherApplicationCommand``. Returns ------- func : `async-callable` The converted function. ...
b72941bfb62e2be79ee916cf101e2d820c92ffc8
63,049
def calculate_previous_version(version: str, is_point: bool) -> str: """Calculate the previous version to compare to. In the case of -rc to final that verison is the previous .0 release, (19.3.0 in the case of 20.0.0, for example). for point releases that is the last point release. This value will be t...
a1591454f307bd3180c65f3c908de870092debe5
63,050
from clubs.views import find_relationship_helper def find_membership_helper(user, club): """ Finds the membership instance in the family tree of a club with the most authority. Returns None if there is no membership between the specified club and user. """ related_codes = codes_extract_helpe...
3556336b8f60a6e4092233c5793c170d9acef14e
63,051
def fib(n): """Print the Fibonacci series up to n.""" a, b = 0, 1 c = [] while b < n: c.append(b) a, b = b, a + b return c
8f46ccc2c6bcde70b370408dcf1c5f02f8b3b588
63,052
def all_neighbor_distances(lat,vector_table,cell_rad = 1): """ Creates an n x n*(1+2*cell_rad)**3 table of bond lengths between all n atoms in the unit cell and every atom in the same unit cell and the (1+2*cell_rad)**3 -1 surrounding cells (the cell_rad number of layers of cells surrounding the c...
91190085bf5398f6b7a0a183ac8d8246eb2de459
63,053
def convert_board2san(coord): """ Takes a PRE-VALIDATED coordinate of the form: tuple(row, col) Returns a coordinate in SAN (Standard Algebraic Notation) : "a4" or "h6" for example Completely capable of crashing the program if input is not valid """ result = [] if coord: rank =...
a3ad0384822cd0d4b0ec86ac7f33167065c977de
63,054
def upgrade_repos(c: InvokeContext, pull_master: bool = True, pull_develop: bool = True, run_scripts: bool = False): """ Update your repos. :argument pull_master - Should we pull down the latest master :argument pull_develop - Should we pull down the latest develop(will skip if not defined in config...
5902df7054a081783f73a729c3b8f1a7be370261
63,055
def basic_segment_classifier(dir, out_model): """ Train audio models :param dir: directory which contains audio organized in folders of classes :param output_model: path to save the output model :return: None """ basic_features_params = config['basic_features_params'] feature_ext...
7f53d686b0b0cad6872d9953fec6a8db12972bdb
63,056
def fixed_axion_routine(ga_ref, output, source_input=default_source_input, data=default_data, Snu_echo_kwargs=default_Snu_echo_kwargs ): """ Computes the full echo routine of both source and echo for a fixed referenc...
4d63b995dd1d77e85b15eb366832dc2e91fa64e6
63,057
def delDotPrefix(string): """Delete dot prefix to file extension if present""" return string[1:] if string.find(".") == 0 else string
792d4f72dcbc641de5c3c11f68a78c73fa0d9ecd
63,058
def afx_adafactor(): """Adafactor with recommended learning rate schedule.""" hparams = afx_adam() hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 return hparams
70686e309e00d8068885e48598a026c7eb26a3fd
63,059
def str_compare(str1: str, str2: str) -> bool: """문자열 비교 Parameters ---------- str1: str string str2: str string Returns ------- bool 문자열이 동일하다면 True """ str1 = str1.strip().lower() str2 = str2.strip().lower() return str1 == str2
a4e0d6d88b28b2851b1403ab63c8e808e16d60ab
63,061
from typing import TextIO from typing import Optional def next_line(fh: TextIO) -> Optional[str]: """ Return the next line from a filehandle """ try: return next(fh).rstrip() except StopIteration: return None
92077359720b6ac72637943d86c7ab6250158194
63,063
def define_form(request, hostname): """ Ajax page for updating compute node settings. """ node = get_node(request, hostname, sr=('owner',)) form = NodeForm(request, node, request.POST) if form.is_valid(): status = form.save(args=(hostname,)) if status == 204: return ...
d47aee2abc7dfb4a604d9b164e4c6aa019bc1fec
63,064
def hash_suffix(path, reclaim_age): """ Performs reclamation and returns an md5 of all (remaining) files. :param reclaim_age: age in seconds at which to remove tombstones """ md5 = hashlib.md5() for hsh in sorted(os.listdir(path)): hsh_path = join(path, hsh) try: fil...
0a3f19c7eb466bdcb1f6d83d9fd5193fab1515a2
63,065
def get_ua(): """Get first user agent in the 'user_agents' list Returns: str: User agent """ return user_agents[0]
02effeede93e729b4cb953d235890601328bf42f
63,066
def drop_dimension(data, name) -> ProcessBuilder: """ Remove a dimension :param data: The data cube to drop a dimension from. :param name: Name of the dimension to drop. :return: A data cube without the specified dimension. The number of dimensions decreases by one, but the dimension prope...
b67a7b347554105d5c088a0fed5a0cac29f2e85d
63,067