content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cosine_sim(text1, text2): """ Calcuates the cosine distance between the skills and the course description. :param text1: Phrase 1 :param text2: Phrase 2 :return: returns the probabilistic measure of similarity. """ vectorizer = TfidfVectorizer(tokenizer=normalize, stop_words='english...
abef404514d9db40ca79c04f3663f1ea062e5b12
3,617,052
def distinct(key_mapper=None): """Returns an observable sequence that contains only distinct elements according to the key_mapper. Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. The source must be a MuxObservable. ...
80f40e88ecfff69a954c82fd15f8fafe797b13f4
3,617,053
def svn_client_commit3(*args): """ svn_client_commit3(svn_commit_info_t commit_info_p, apr_array_header_t targets, svn_boolean_t recurse, svn_boolean_t keep_locks, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return apply(_client.svn_client_commit3, args)
d69ebad3d11e194a7b4bd25935e57f7b8b17362f
3,617,054
def parse_range(string): """ Parses IP range for args parser :param string: formatted string X.X.X.X-Y.Y.Y.Y :return: tuple of range """ ip_rng = string.split("-") return [(ip_rng[0], ip_rng[1])]
6f38e105284d58af2cef94275c25e02ad76acb80
3,617,055
from typing import Optional from typing import Union from typing import Sequence from typing import Literal def panas( data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None, language: Optional[Literal["english", "german"]] = None, ) -> pd.DataFrame: """Compute the **Positive and...
90933eab4a82f64c37cfee455d756218151d4e46
3,617,056
def notes(l, b, i): """!parent-command !c new !d Create a new note (use \n for newline) !a <title> <message...> !r user !c list !d List all notes available !r user !c append !d Append a line of text to a note !a <title> <message...> !r user...
c2594c2d4fb21bf5d8d1f28d7077f8a5ebd60e49
3,617,057
def measure_circuits_nondeterministic(allow_sampling=True): """"Measure test circuits with non-deterministic count output.""" circuits = [] qr = QuantumRegister(2) cr = ClassicalRegister(2) # Measure |++> state (sampled) circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr...
b7e5424c2340753d374ecc1f14fe6f65034e9661
3,617,058
from io import StringIO import gzip def _get_data(url): """Helper function to get data over http or from a local file""" if url.startswith('http://'): resp = urllib2.urlopen(url) encoding = resp.headers.dict.get('content-encoding', 'plain') data = resp.read() if encoding == 'pl...
6b7b1a803dd03d6fce25a0e679abf6110cef423a
3,617,060
import inspect def lineno(): # pragma: no cover """ Returns the current line number in our script :return: """ return str(' - line number: ' + str(inspect.currentframe().f_back.f_lineno))
ca40ae90ea44883ac40bd5524fee04c3957b2021
3,617,061
def _require_response_200_ok(response): """ Accept a requests.response object. Raise ResponseNotOK if status code is not 200. Otherwise, return True """ if response.status_code != 200: raise ResponseNotOK( status_code=response.status_code, message=response.text ) ...
4b35584eca30d7b0ac62ef51587f6f7cf03749a3
3,617,062
def pf_index(grid: Grid, grid_params: GridParams) -> PFIndex: """Ordered buses and mappings to admittances and slack factors.""" pv_idx = pv_buses(grid, grid_params) pq_idx = pq_buses(grid, grid_params) s_idx = slack_factors(grid, grid_params) y_idx = admittances(grid, grid_params) ret...
2b092b71051bb0bdbd97ed9926b310f016f88d50
3,617,064
import re def read_rdump(filename: str) -> dict: """ Read data formatted using the R dump format. """ contents = open(filename).read().strip() names = [name.strip() for name in re.findall(r'^(\w+) <-', contents, re.MULTILINE)] values = [value.strip() for value in re.split(r'\w+ +<...
3624f56d2872885c50d2d7f521730bb8a8864211
3,617,065
def selectYear(update: Update, context: CallbackContext): """ Select the yaer for which to list expenses """ year = update.message.text context.user_data['inputYear'] = year text = ("Received '"+year+"' as the selected year" +"\nSelect from below the month for which you'd like to list exp...
79c982b1591e15b9014302ca4380ec8900bad17f
3,617,066
def sort_by_field(boxlist, field, order=SortOrder.descend, scope=None): """Sort boxes and associated fields according to a scalar field. A common use case is reordering the boxes according to descending scores. Args: boxlist: BoxList holding N boxes. field: A BoxList field for sorting and reordering the...
a091e699182fe9c1b8a2bca881759004e67fc7d9
3,617,067
import json def process_frame(frame_data, d_width, d_height, features_file, images_dir, min_trajectory_len): """Save faces + features from a frame, and creating face embeddings. """ # Filter to faces with a valid trajectory (len > MIN) valid_faces = [ face for face in frame_data["faces"] ...
07be5d8fe578ca89cf56c763c3ad3c9bbe5c5986
3,617,068
from sympy.polys.polytools import degree from sympy.polys.domains import FractionField from sympy.core.basic import preorder_traversal def minimal_polynomial(ex, x=None, **args): """ Computes the minimal polynomial of an algebraic element. Parameters ========== ex : algebraic element expression ...
7f9c74d05a19858607fecf0b4f87798eafbf9534
3,617,069
import torch def calc_dihedral(v1, v2, v3, v4, x_idx=None, y_idx=None, eps=1e-6): """ Calculate the dihedral angle between 4 vectors. v1, v2, v3, v4: shape (..., 3) x_idx, y_idx: shape (...), additional information of vectors. return: (x_idx, y_idy, dihedral) """ x = v2 - v1 y = v3 - v...
4ef064aa607ff23d212b628dd5c465e13fffd9b5
3,617,071
def set_convert_inputs(flag): """ This function is a temporary workaround for reducing the overhead of operator invocations. The function `convert_inputs` is disabled if the global state `_enable_convert_inputs` is set to `False`, otherwise enabled. This function is for internal use only, and should be ...
5bf661d6aeef099b7ecdfd117cf9dfdb4fae1285
3,617,072
import ctypes def encode_flush(): """ Flush the encoding buffers and return final frames (if any). """ _lib.lame_encode_flush.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] _lib.lame_encode_flush.restype = ctypes.c_int mp3buffer = (ctypes.c_char * 7200)() mp3buffer_us...
d0f137df60020c55ab27f4b98cb4dba7bc71a60f
3,617,073
import logging import traceback from datetime import datetime async def format_stream(member: discord.Member, osu_score: dict, beatmap: dict): """ Format the stream url and a VOD button when possible. """ stream_url = None for activity in member.activities: if activity and activity.type == discord...
6814fd8329868e13baf4fd2b3d03888c211e39a5
3,617,074
def parse_city_state_zip(city_state_zip): """ Parses city_state_zip into a dict """ city_state_zip = normalize(city_state_zip.replace(",", ", ").replace(".", ". ").strip()) if city_state_zip: # normalize commas _m = " ," while _m in city_state_zip: city_state_zip = city_s...
d60cefd3ac24acae08bc2196bf1629fd1fc92e45
3,617,075
def flows_from_sff(flows): """lines is sff file lines. """ if isinstance(flows, str): flows = flows.splitlines() flows, head = parse_sff(flows) return flows_from_generic(flows)
2a917c4f6e747b388c561ef933f861eef918552b
3,617,076
def common_lens(cube_list): """ Give the common lenses of a list of pySNIFS cubes @param cube_list: input list of datacubes @return: inters: list of the lenses common to all the cubes of the list """ inters = cube_list[0].no for i in xrange(1,len(cube_list)): inters = filter(lambda x...
f8c22e76a92ae187006977e86b5483601088a98d
3,617,077
def protected(Authorize: AuthJWT = Depends()): """ We do not need to make any changes to our protected endpoints. They will all still function the exact same as they do when sending the JWT in via a headers instead of a cookies """ Authorize.jwt_required() current_user = Authorize.get_jwt_s...
a0232bd11634ccac83086733e5032c5ccca9ff73
3,617,078
from typing import Optional import torch def sin(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray: """ Compute the trigonometric sine, element-wise. Result is a ``DNDarray`` of the same shape as ``x``. Negative input elements are returned as ``NaN``. If ``out`` was provided, ``sin`` is a refer...
74a52f3a72d35eec4bbea94e3ed51abf02bc30ef
3,617,079
from typing import Optional from typing import List def list(lst: 'Optional[List_[PythonValue]]' = None) -> PythonValue: """Returns a List wrapped into a PythonValue""" return PythonValue(List(lst=lst))
08f607b4befae0393561cf6bd06f43c1029dc724
3,617,080
async def set_consumer_to_infernal_job(engine, job_id, consumer_ip): """ Update the infernal_job table to register the consumer who will run the job :param engine: params to connect to the db :param job_id: id of the job :param consumer_ip: ip address of the consumer :return: id or none """ ...
05627d52809ebf378a030e40473dcee8b9e6ecc2
3,617,081
def get_recursively(search_dict: dict, field: str) -> list: """Take a dict with nested lists and dicts, and searche all dicts for a key of the field provided. https://stackoverflow.com/a/20254842 Args: search_dict (dict): Dictionary to search field (str): Field to search for R...
5457a41116cfb58eaf6ab57918a5d87eae7196a6
3,617,082
from pathlib import Path def askDestination(): """ prompts user for backup directory and sets it to destination :returns: new destination """ location = filedialog.askdirectory() # validation p = Path(location) if not p.exists() or not p.is_dir() or location == '': return bm.d...
fe805e9ec3dbe503a2357ac6bcad4c4aa1809be5
3,617,083
def time_series_sum_of_reoccurring_values(x): """ Returns the sum of all values, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: float """ return ts_feat...
020203facf8765f292cb2f19f68dc603c8254b66
3,617,085
def promote_numeric_to_real(stage: ImportStage, value: ir.Value) -> ir.Value: """Promotes the value to RealType.""" return d.PromoteNumericOp(d.RealType.get(), value).result
d1be8cac377e34687a7b7ab680c507d9166820a7
3,617,086
import asyncio async def make_photo(): """Photo from web camera. """ loop = asyncio.get_running_loop() img, _ = await loop.run_in_executor(app.ps_executor, get_png_photo) if img: result = StreamingResponse( png_img_to_buffer(img), media_type="image/png" ) else: ...
5e243950d75a68d245d751fd6636f1416e30a31b
3,617,087
def get_adj_matr(graph): """ Function to create an adjacency matrix representation of a graph. arg: graph - (dict) of 'nodes' : [], 'edges' : [] returns: pd.DataFrame with entry i,j representing an edge from node i to node j """ n = len(graph['nodes']) adj_matr = pd.DataFrame...
81bc0673071c1afe96340039feb94ab1bd3b2393
3,617,088
import requests import re def get_title(url: str): """ Get the Title of the web page and generates markdown formated link""" html_source = requests.get(url).text title = re.findall('<title>(.*?)</title>', html_source)[0].strip() return f"[{title}]({url})"
c6b0a559e7e3369d34e6266b7636d5c4a13ed2f0
3,617,092
def pow_4_of(number): """ fourth power of number helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h """ pow2 = pow_2_of(number) return pow2 * pow2
9ae515bd8ca9e8027f6ddecd71b714010668cfa3
3,617,093
def item_cost_entry() -> float: """Return the sum of all user entries.""" print('\nENTER ITEMS (ENTER 0 TO END)') subtotal: float = 0.0 while True: cost: float = float(input('Cost of item: ')) if cost == 0: break else: subtotal += cost return subtotal
d9d5bdc53f2d37f348d477086935cba3ba6a8e7e
3,617,094
def mark_duplicates(job, config, name, input_bam): """Run Picard MarkDuplicates :param config: The configuration dictionary. :type config: dict. :param sample: sample name. :type sample: str. :param input_bam: The input_bam file name to process. :type input_bam: str. :returns: str -- Th...
d7987f74d4c12ee190e895374a062cdc140ec2d6
3,617,095
def normalize_tokens(tokens): """ The OP-1 gets confused with multiple line segments in one command. This fixes that by splitting multiple segments into separate commands. Convert from e.g.: ["l", "20", "20", "20", "-20", "10", "10"] To: ["l", "20", "20", "l", "20", "-20", "l", "10", "10"] ...
972b7b2d46ac28d5d06c559fed1878355e18774e
3,617,096
import test def full_train_and_test(filename): """ Uses the entire dataset for both training and testing. Returns the testing accuracy. """ table, cumulative, dataset, index_to_name = train(filename) preds, targets = test(table, cumulative, dataset, index_to_name) n_correct, n_total = acc...
c27a9dafa27eab2b137a6b84d8e60e34665683ad
3,617,097
import torch def mmd2_rbf(X, t, p, sig=0.1): """ Computes the l2-RBF maximum mean discrepancy (MMD) for X given t. http://www.jmlr.org/papers/volume13/gretton12a/gretton12a.pdf -- Eq3 """ it = np.where(t==1)[0] ic = np.where(t==0)[0] Xc = X[ic] Xt = X[it] if list(Xc.shape)[0] == ...
80d61470c84b2ce2c1f06930ae38bd711ff2f0bb
3,617,099
from typing import List def render(gs: game.VisibleGameState, actions: List[game.Action] = None) -> str: """ Pretty fuckin hacky... """ screen = [[" "] * WIDTH for _ in range(HEIGHT)] # Talon: talon_height_offset = 0 for i, card in enumerate(reversed(game.bitmask_to_cards(gs.talon))): ...
5708fe2cb9d84f35c2ea38e3ec10acb79ed46a83
3,617,100
import logging def evaluate_srnpdj(gt, pred, K=25): """ Parameters: gt: np.array([N, ...]) ground truth array of binary labels (integers) pred: np.array([, ...]) same shape as ground truth Returns: srnpdj_N6: np.array(shape=[N, 6]) for each paire...
77db14c4a6e0bdecd2207e9955abfd8e33bb0724
3,617,101
from datetime import datetime def ajax_delete(): """ 客户删除 :return: """ ajax_success_msg = AJAX_SUCCESS_MSG.copy() ajax_failure_msg = AJAX_FAILURE_MSG.copy() # 检查删除权限 if not permission_customer_section_del.can(): ext_msg = _('Permission Denied') ajax_failure_msg['msg'] ...
e33cbab8db34739e970c2fe5651d49487245fc9b
3,617,102
from typing import List def compute_clustering_metrics(y_true: List, y_pred: List) -> List[float]: """ Computes ARI, NMI, goldInstance, sysInstance, goldClusterNum and sysClusterNum between predicted and gold labels Args: y_true: Iterable, ground truth labels y_pred: Iterable, labels ...
289eb6d278aedd79bad83ed1140fb1656caad072
3,617,103
from bs4 import BeautifulSoup import time def _open_url(url: str): """Opens url, creates BeutifulSoup object and waits. :param url: url to get :type url: str :return: BeautifulSoup object """ opener = build_opener() opener.addheaders = [ ('User-Agent', 'Mozilla/5.0 (Windows NT 10....
255b6aaabcfc3b1be2c284e3244067b2f03265bf
3,617,104
def square(vx=1.0, vy=0, wz=0.8, t=16): """ Generate square trajectory, starting and ending at origin. """ time_points = range(t) speed_points = ( # Get set (0, 0, 0, 0), # Walk forward and then turn left (vx, 0, 0, 0), (vx, 0, 0, 0), (0, 0, 0, wz), ...
7db4f1c13cb3055b45e96b0e85934df0c6aa0389
3,617,105
def crypto_adapter(adapter): """Modify an adapter to disable non-crypto symbols. ``crypto_adapter(adapter)(name, active, section)`` is like ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols. """ def continuation(name, active, section): if not include_in_crypto(name): ...
6f1345d4266fc7a7f2391897170b08d29c57a729
3,617,106
from typing import Optional from typing import List from pathlib import Path def get_ann_dir( encoder_type: Encoder.Types, code_lang: str, query_langs: Optional[List[str]]=None, run_id : Optional[str]=None ) -> Path: """ Returns the path to the .ann index files for a specif...
8fa5b2a23cbc9dd436007299e239f39bb9e27050
3,617,107
from typing import Type from typing import cast def coerce(expr: Node, target_type: Type, source_type: Type, context: TypeInfo, is_wrapper_class: bool = False, is_java: bool = False) -> Node: """Build an expression that coerces expr from source_type to target_type. Return bare expr if the coercion...
9687fccd5fddd216f2a96f21030da8e26f8ec3f3
3,617,108
def check_surrounded(string): """ Check if the string as a whole is surrounded by brackets :param string: The string to check. :return: True if it is surrounded. """ length = len(string) if length <= 1: return False counter = 0 for idx in range(length): char = string[id...
6855cadee02c32010ea98752a35ee6d929d53925
3,617,109
def make_message(name): """Constructs a welcoming message. Input: string, Output:string.""" message = "Good morning, %s! Nice to see you."%name return message
ac5c9f845cd6779fa37758ec6b27b69dd325fb7d
3,617,110
def format_time(sec: float) -> str: """Return formatted time in seconds.""" m, s = divmod(sec, 60) h, m = divmod(m, 60) return "%d h %d m %d s" % (h, m, s)
5c825c7556c0e01d4344af8c35c0f005be69114c
3,617,111
def file_path_pair(config, section): """Return input and output file paths for a config section.""" input_obj = config[section]['input'] if isinstance(input_obj, str): input_path = get_file_path(config, input_obj) else: input_path = [] for path in input_obj: input_pat...
eea94ae41595e18a11d30002a19aa3c5f7bb6f63
3,617,112
def get_name_candidates_from_email(parsed_text): """ Gets possible combination of names from the email address :param parsed_text: (unicode string) parsed text from the resume. :return: a list of possible combination of names. """ banned = ['the', 'and'] string_list = [] list_name_data =...
afa14780861d0e024c6f91c0d593ed0440e0bf1e
3,617,113
def spot_price_difference(): """返回 DOT 火币,币安,okex,抹茶,uniswap,heco交易所现货价格的最大价差 @@@ ### description > finished ### args None ### return status code: **200** ```json [ { "dex": "huobi", "price": 100, ...
2bc563cb9e80cf73a651a80938af34fe3c3f9267
3,617,114
def view_eco(key): """View existing eco.""" eco = ECO.get_by_key(key) users = User.query.all() projects = Project.query.all() variables = { 'eco': eco, 'users': users, 'projects': projects } return render_template('eco/view_eco.html', **variables)
578993b8549bd7f5f4c39e915b13ae4173afc8fb
3,617,115
def fetch_accounts(clientCard): """ Function to return the accounts owned by the account holder that is linked to the bank card they used to login into the website, and associated information. Args: clientCard (int): Bank card used for login Returns: accounts_modified (list): List w...
e38895073aaf4c3edad0551edc94dee259a6a1d7
3,617,116
def get_classifier_training_job_from_model(classifier_training_job_model): """Gets a classifier training job domain object from a classifier training job model. Args: classifier_training_job_model: ClassifierTrainingJobModel. Classifier training job instance in datastore. Returns: ...
4297df181b9fcb747bad2f5d839aad1787c84fac
3,617,117
import requests def makeModel(filenum=FILENUM): """ :param str file_num: :return libsbml.Model: """ url = makeURL(filenum) response = requests.get(url).content document = tesbml.readSBMLFromString(response.decode("utf-8")) return document.getModel()
4a0a1c5021c138bc2f0fbddefcdd31e04b0b92ec
3,617,118
import numpy.random def random_sequences(num_seqs, average_length): """ @arg num_seqs: The number of sequences to return. @arg average_length: The expected length of each sequence. (the lengths are actually distributed according to a Poisson distribution). @return: A list of random sequences. """ ...
c778a947faba9fcd651124fcf895f3e8a3a697a2
3,617,119
def tone3_to_tone(tone3): """将 :py:attr:`~pypinyin.Style.TONE3` 风格的拼音转换为 :py:attr:`~pypinyin.Style.TONE` 风格的拼音 :param tone3: :py:attr:`~pypinyin.Style.TONE3` 风格的拼音 :return: :py:attr:`~pypinyin.Style.TONE` 风格的拼音 Usage:: >>> from pypinyin.contrib.tone_convert import tone3_to_tone >>> to...
8facc123f5a8f381dc4166e326f919591dafd1e1
3,617,120
import io def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int: """ Consider the validity of the nearby tickets you scanned. What is your ticket scanning error rate? """ fields, tickets = parse(stdin) groups = valid_groups(fields) invalid_values = [ value fo...
db8a7ce80df23ab5503b3ca37b181982d761f583
3,617,121
def image_update(client, image_id, values, purge_props=False): """ Set the given properties on an image and update it. :raises NotFound if image does not exist. """ return client.image_update(values=values, image_id=image_id, purge_props...
ddd89c57cefa2972833ce87e382572406fbb811f
3,617,122
def get_new_map(trace): """ Returns the new MAP model from exoplanet after sampling the posterior. Parameters ---------- trace : arviz.data.inference_data.InferenceData Information on the trace of all fitted parameters used in the model sampling, including the posterior values, log_likeliho...
5fec674e4ba56c0163872357a40ed32d576c20f5
3,617,123
def encodeMorse(sequence: str) -> str: """ Encodes the given string to Morse Code Morse code is case-insensitive and traditonally Capital Letters are used Lower cases are converted to Upper cases Every Character code is seperated by a single space between them A space in the se...
7fb6b631d894fe4d73d277d8a4374be581616b32
3,617,124
def brightness(image): """Change brightness of image randomly (maximum 30%)""" hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) scale = 1.0 + np.random.uniform(-0.3, 0.3) hsv[:,:,2] = hsv[:,:,2] * scale return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
0f0463039992dc3d0087bbe066776af61eb889d3
3,617,125
def _parse_vertex_tuple(s): """Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...).""" vt = [0, 0, 0] for i, c in enumerate(s.split('/')): if c: vt[i] = int(c) return tuple(vt)
e83182401b6443726660caf3688008f6209aed13
3,617,126
import random def __create_clicks_for_statements(up_votes, statement_uid, users, is_up_vote): """ :param up_votes: Int :param statement_uid: Statement.uid :param users: {Users.nickname: User} :return: [ClickedStatement] :param is_up_vote: Boolean """ tmp_firstname = list(first_names) ...
14a31bb3b594d92bc08322d6783828c92bce27f8
3,617,127
def get_pct_on_clutter_map_rhi(filename, polarization): """ get_pct_on_clutter_map_rhi grabs and returns clutter map point percentage occurrences and clutter map masks from daily HSRHI clutter maps (in either H or H and V polarizations). Parameters ---------- filename: str full path...
5cf4ea50b568744dfb39da615c1cdf1458f8d14b
3,617,128
import torch def tfidf_transform(tfidf_vectorizer, corpus_data, cuda0): """ Apply TFIDF transformation to test data. Args: vectorizer_train (object): trained tfidf vectorizer newsgroups_test (ndarray): corpus of all documents from all categories in test set Returns:...
6f18b7114579412e1442b1c6220f34b7f643a2ab
3,617,129
def or_(*args): """ Trick operator precedence. or_(foo < bar, bar < baz) """ value = DummyAttr() for elem in args: value |= elem return value
5e709f65fe2e03af2fe8e55e1638e8a012acc1c9
3,617,131
def plot_image(data=None, mode='imshow', backend='matplotlib', **kwargs): """ Overall plotter function, converting kwarg-names to match chosen backend and redirecting plotting task to one of the methods of backend-classes. """ if backend in ('matplotlib', 'plt'): return MatplotlibPlotter.plot(da...
f2a4dd4a81aafb182aefd33ffd98667e154ad2d8
3,617,132
import tqdm def project_to_ids_UNSC(Tokenizer, data, max_seq_length=512): """ Function to map data to indices in the albert vocabulary, as well as adding special bert tokens such as [CLS] and [SEP] Args: Tokenizer (bert.tokenization.albert_tokenization.FullTokenizer): tokenizer class ...
159210068640e62bd3eb66acec3131dcf8d9b75e
3,617,133
def voigtMath(x, alpha, gamma): """ Function to return the Voigt line shape centered at cent with Lorentzian component HWHM gamma and Gaussian component HWHM alpha. Creates a Voigt line profile using the scipy.special.wofz, which returns the value of the Faddeeva function. WARNING scipy.sp...
623de058a893b79d857869f8a19bc0e3194b457a
3,617,135
def get_installation_coordinates_google(dir_in, key_google, fn_out=None): """ Gets installation coordinates using googlemaps api :param dir_in: <string> path to directory with downlaoded installation data file :param key_google: <string> google api key :param fn_out: <string> name output file. If None, ...
3f33fe2fb14fb3fba92d540c4b2d405a75e53426
3,617,136
def diag_dump( enode, list='', daemon='', level='', file='', _shell='vtysh', _shell_args={ 'matches': None, 'newline': True, 'timeout': None, 'connection': None } ): """ Display diagnostics dump that supports diag-dump. This function runs the following vtysh ...
07a97e8e1dbb2a29b19b49c8b94c7e1fd2d5529f
3,617,137
def randomizeCarVelocities(nCars, vMax): """This function takes integers nCars, and vMax. It then returns an array of of random integers from 0 to vMax. The array is of length nCars. No integers in the returned array are the same.""" carVelocities = [] for i in range(nCars): randomVelocity =...
edd1d118d3b95560c4bcb85c266b63e0380c9b87
3,617,138
import time import logging def get_absl_log_prefix(record): """Returns the absl log prefix for the log record. Args: record: logging.LogRecord, the record to get prefix for. """ created_tuple = time.localtime(record.created) created_microsecond = int(record.created % 1.0 * 1e6) critical_prefix = '' ...
623c6b8966424b8168686d05f5d65c1268a1d0e1
3,617,139
def delete_zcs_container(session, zcs_container_id, return_type=None, **kwargs): """ Deletes a Zadara Container Services (ZCS) container. The container must first be stopped. This action is irreversible. :type session: zadarapy.session.Session :param session: A valid zada...
0eda96c2a07e5a0280584ba9cd323f6fa58e8190
3,617,140
def numStationsNotIgnored(observations): """ Take a list of ObservedPoints and returns the number of stations that are actually to be used and are not ignored in the solution. Arguments: observations: [list] A list of ObservedPoints objects. Return: [int] Number of stations that ...
279f4075bc1fe155e4fa8b39758997c9748f06b8
3,617,141
def jf_mcma_lb(sample: np.ndarray, ref_size=None, c=None, delta=0.05, mode=None, mc_size=10000) -> float: """ A function calculates the lower bound using Monte-Carlo M_alpha method. For more details, please check the paper: "A New Confidence Interval for the Mean of a Bounded Random Variable" ...
02791a7e22802cd50e20aa803b981111193cfd4f
3,617,143
def parse_thumbnail_requirements(thumbnail_sizes): """ Takes a list of dictionaries with "width", "height", and "method" keys and creates a map from image media types to the thumbnail size, thumnailing method, and thumbnail media type to precalculate Args: thumbnail_sizes(list): List of dicts w...
07a1e6b5eac978aa59b7a676d8f5b932367599d5
3,617,144
def get_connected_regions_light(input_flow, strict=False): """ :param input_flow: the binary mask array, with shape [x, y, z], pid_id :param strict: whether diagonal pixel is considered as adjacent. :return: a dict, with key 1, 2, 3, ... (int), value is list of location: {1: [(x1, y1, z1), (x2, y2, z2),...
58f89018e0933ac0aff29df83d1cb31f653ed70c
3,617,145
def policy_decision(): """Determines whether a request is allowed or not Args: The function uses HTTP request directly. These argument must be contained in the request: thing_id (str): identification of the thing thing_type (str): type of the thing action (str): get,delete, or c...
031446c3f212f7ecc5944ca040bc026f204fc9e3
3,617,146
def calc_num_nodes(np, ppn=1, threshold=0, name=None): """Calculate the number of required nodes with optional utilization check. :param np: Number of required processing units (e.g. CPUs, GPUs). :param ppn: Number of processing units available per node. :param threshold: (optio...
950b72248b1e4f26f8d8e2ed4c2f6c26b0faa51b
3,617,147
def get_status(req_sheet, row_num): """ Accessor for JIRA Key Args: req_sheet: A variable holding an Excel Workbook sheet in memory. row_num: A variable holding the row # of the data being accessed. Returns: A string value of the Notes """ return (req_sheet['G' + str(row_...
3e1de0013bc0efc5824f5261ff4c0b278f486ea8
3,617,148
import torch def validate(model, criterion, valset, iteration, batch_size, n_gpus, collate_fn, distributed_run, rank): """Handles all the validation scoring and printing""" model.eval() with torch.no_grad(): val_sampler = DistributedSampler(valset) if distributed_run else None ...
a71192ee93901fb1c2f10c1d7cfcd12dfbd1dfbe
3,617,149
def get_permissions(limit=None, offset=None): """Get permissions""" session = current_app.appbuilder.get_session total_entries = session.query(func.count(Permission.id)).scalar() query = session.query(Permission) actions = query.offset(offset).limit(limit).all() return action_collection_schema.d...
6fbb85696aaaafc2209d3e039f5d55c29ac726e3
3,617,150
from typing import Union from typing import Optional def extract_wikipedia_id(url: Union[str, ParseResult, None]) -> Optional[str]: """ extract Wikipedia ID from URL """ url = parse_url(url, ("en.wikipedia.org", "en.m.wikipedia.org")) return ( unquote_plus(url.path[6:]) or None if url and ...
9388db4aefc4eb08338e9ed0c6619ba2e2afa365
3,617,152
def summation(num) -> int: """This function makes numbers summation.""" return sum(range(1, num + 1))
78983a3e60be914987fd1dc91d5097e1edb326da
3,617,153
def SaveArrayWithGeo( array, src_filename, dst_filename, format ): """ SaveArrayWithGeo(): Saves an Array (array) with Georeferencing from another file (src_flnm), save it in file (dst_flnm) with format (format) SaveArrayWithGeo( self, array, src_filename, dst_filename, format ) """ #From warmerdam at p... Thu Ma...
39191b446006c652860c054a627078d3038592a5
3,617,154
def get_mapshape_from_searchmap(hashtable): """Suppose keys have the form (x, y). We want max(x), max(y) such that not necessarily the key (max(x), max(y)) exists Args: hashtable(dict): key-value pairs Returns: int, int: max values for the keys """ ks = hashtable.keys() h = max([y...
cf5cb2051fc9254d70c60a71d2c7f9e378b0a39e
3,617,155
def det(a, b): """ Calculate the determinent between two vectors @param[a] One vector represented as [x,y] @param[b] One vector represented as [x,y] """ return a[0] * b[1] - a[1] * b[0]
61dfcbf421241ac9885643554bbf0c235f698098
3,617,156
import glob def find_rar(path): """ This function is designed to find the most appropriate file to use when extracting and/or processing releases. This is designed for use with torrent clients and their various "on complete" functionality. This function will always return the largest file found under...
6d1134a276352390d677f1d7fe63328e21498a2e
3,617,157
def test_fft(): """ Kymatio, (C) 2018-present. The Kymatio developers. https://github.com/kymatio/kymatio/blob/master/kymatio/tests/scattering1d/ test_tensorflow_backend_1d.py """ if not got_tf: return None if run_without_pytest else pytest.skip() def coefficent(n): return np...
99d64eb78fd4642fe7b44e1749eb665db04436dd
3,617,158
import re def GetOSVersion(): """Retrieve the current OS version from machine. Returns: os_version: string, like '10.9.5' or '10.10'. Raises: GmacpyutilException: command failed to execute. GmacpyutilException: os_version does not match expected formatting. """ cmd = ['sw_vers', '-productVersio...
2dad46642c448b32100c692de2d9c16051dbb46d
3,617,159
def env_to_bool(environment_variable: str) -> bool: """ Translate an environment variable to a boolean value, accounting for minor variations (case, None vs. False, etc.) """ env_value = getenv(environment_variable) return bool(env_value) and str(env_value).lower() not in ["false", "none"]
69dc81884e900edd9b7849f927e8ea4387ed98a1
3,617,160
def make_var_with_poisson(infile, units, maskfile=None, gain=None, rdnoise=0., texp=None, origbkgd=0., epsilon=None, hext=0, statcent=None, statsize=None, outfile=None, outtype='var', outsnr=None, returnvar=True, ver...
1e5270fdef24d5a6d903ec64a487a2f80566d4b4
3,617,161
def dtype_limits(image, clip_negative=True): """Return intensity limits, i.e. (min, max) tuple, of the image's dtype. Parameters ---------- image : ndarray Input image. clip_negative : bool If True, clip the negative range (i.e. return 0 for min intensity) even if the image ...
a75969f0f0f7664c05ef187050cb699ab3e81fdb
3,617,162
def get_test_data(fname, as_file_obj=True, mode='rb'): """Access a file from MetPy's collection of test data.""" path = POOCH.fetch(fname) # If we want a file object, open it, trying to guess whether this should be binary mode # or not if as_file_obj: return open(path, mode) return path
cfefdda29925e24da84f96ce2365fd042080d196
3,617,163