content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def alpha(flux1, flux2, freq1=ufloat(144e6, 24e6), freq2=ufloat(1400e6, 0)): """Get spectral index with error. Default is LDR2 and FIRST. """ return log(flux1 / flux2) / log(freq1 / freq2)
f026a77697265194136a222a0ea8825d63fc0ebe
3,613,800
def decline_pr(script, project_key, repo_slug, pr_id, pr_version=0): """ Decline a PR :param script: a TestScript instance :type script: TestScript :param project_key: The project key :type project_key: str :param repo_slug: The repo slug :type repo_slug: str :param pr_id: The PR id ...
92b5c280e029090f6129dc1c420d8207e77dd2a0
3,613,801
from ostap.fitting.pyselectors import SelectorWithCuts def test_selector_with_cuts () : """Use selector-with-cuts to loop over good entries in the chain - loop over the good entries in the chain using selector - fill dataset """ logger = getLogger("test_selector_with_cuts") cla...
b3f4dba0976d333a2ff2580f610fc32780dc1cea
3,613,802
import torch def register(fixed=None, moving=None, dim=None, lam=1., loss='mse', optim='ogm', hilbert=None, max_iter=500, sub_iter=16, lr=1, ls=6, steps=8, plot=False, klosure=RegisterStep, velocity=None, kernel=None, verbose=True, **prm): """Diffeomorphic registration betwe...
8f376b717a60ed6dc1431aec151c5c23ab39f6bd
3,613,803
import csv from re import VERBOSE def geocode_addr(in_path, type, start, end, geo_coords): """ geocode_addr Input: <str> in_path, relative path to data file <str> type, "AG" for allGas, otherwise gasBuddy <int> start, line number of data file to start reading ...
d55d43545102914d1d9cd2d1795177c2dce951c6
3,613,804
def get_nodes(api_url=None, verify=False, cert=list()): """ Returns info for all Nodes :param api_url: Base PuppetDB API url """ return utils._make_api_request(api_url, '/nodes', verify, cert)
6b6974790375cab3598ffa03b61906e2b3aa901f
3,613,805
def git_untracked_files(path='', debug=False, timeout=None, exception=True, show=False): """Return a list of any local files that are not tracked in the git repo - path: path to git repo, if not using current working directory - debug: if True, insert breakpoint right before subproc...
a195101ebf235c342847b8f2ad129370677333cf
3,613,806
import subprocess def main(): """Will ask you about yellow and green letters""" # query yellow letters and their positions yel = {} for i in range(1, 6): if input(f"Yellow letter(s) on position {i}? y/n ").lower() == "y": yel[i] = cln(input(f"Which letter(s)? ")) # query gree...
c18a582cdc214e5a73d52dc5dcc0ca1fedb49934
3,613,807
import sys def read_sm_def ( sm_def_file: str ) -> dict: """ Reads state machine definition from a file and returns it as a dictionary. Parameters: sm_def_file (str) = the name of the state machine definition file. Returns: sm_def_dict (dict) = the state machine definition as a d...
648f7281fb27047287d41c6155f8fb05e048106d
3,613,808
import itertools def _fit_coil_order_dev_head_trans(dev_pnts, head_pnts): """Compute Device to Head transform allowing for permutiatons of points.""" id_quat = np.concatenate([rot_to_quat(np.eye(3)), [0.0, 0.0, 0.0]]) best_order = None best_g = -999 best_quat = id_quat for this_order in iterto...
80cf4040c8f4946706f5779530e8042f8d890b53
3,613,809
import struct import time def test_eap_proto_gpsk(dev, apdev): """EAP-GPSK protocol tests""" def gpsk_handler(ctx, req): logger.info("gpsk_handler - RX " + req.encode("hex")) if 'num' not in ctx: ctx['num'] = 0 ctx['num'] = ctx['num'] + 1 if 'id' not in ctx: ...
3114b91d380de7f78d6a36e3e3973e3e9fba854e
3,613,810
from typing import Dict def render_into_template( screenshots: Dict[str, Image.Image], template: Image.Image, ) -> Image.Image: """Place all the screenshots, into the correct place.""" # Place all the screenshots for device, screenshot in screenshots.items(): template.paste(screenshot, SCR...
67313b0005bb2c1dee9650a555731de0b4b6f569
3,613,811
import unicodedata import re from bs4 import BeautifulSoup def _process_text(text): """ Pre-process Text """ text = unicodedata.normalize("NFKD", text) # Normalize text = '\n'.join(text.splitlines()) # Let python take care of unicode break lines # Take care of breaklines & whitespaces c...
e593a8450d92d8c59c8ae20c6889b678c78b886d
3,613,812
def get_model_effectors(file_path, sheet_name): """ Gets the effectors and respective references for each reaction on the kinetics1 sheet and returns a dictionary {rxn_id : ([effector_list], [effector_references])}. Entry i in effector_references contains all references as a string for effector i in...
b0f49bf8ae7e5339653440ab6ea036914762cff0
3,613,813
def account(request, user_id): """ :param request: :return: """ if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) error_messages = [] user = User.objects.get(id=user_id) user_insts = UserInstance.objects.filter(user_id=user_id) instances = Inst...
7390b1f326123f9c05b7f4b83fa4fe2e491466de
3,613,814
import hashlib def create_hash_key(index: str, params: str) -> str: """ :param index: индекс в elasticsearch :param params: параметры запроса :return: хешированый ключ в md5 """ hash_key = hashlib.md5(params.encode()).hexdigest() return f"{index}:{hash_key}"
1762d3d089cd26c6c7e9423fd37e782b61be1235
3,613,815
def _estimate_mmd2_linear_time(latent, i1, i2, sigma=None): """From Gretton et. al. 2012""" if sigma is None: sigma = estimate_median_sigma(latent) A = -0.5 / sigma n = min(len(i1), len(i2)) m = n // 2 assert m > 0 k = lambda x,y: np.exp(A * np.sum(np.power(x-y,2))) h = lambda x1,y1,x2,y2: k(x1,x2)+k(y1,y2)-k...
f8ded845b3d2b14faa814ade8a14c13252cd1630
3,613,816
def CreateVotes(blockable, count, **kwargs): """Creates multiple Vote entites for the given Blockable. Args: blockable: The Blockable to create Votes for. count: int, The number of Votes to create. **kwargs: dict, Any Vote properties to customize. Returns: The newly-created Vote entities. """ ...
e925da1638779d61b0b2745b9ad9f22e837fe1d1
3,613,817
import os def check_paths(import_path, export_path): """ Inspects for file errors in import and export paths. Args: import_path (string): path to input file. export_path (string): path to output file. Returns: None. Raises: FileNotFoundError: file does not exist ...
c65fcc16643a5a40417a2312a5d7820f67d2a543
3,613,818
def compute_codes_requiring_type(handle_data, types_to_codes, registry=None): """Compute a DictOfStringSets of return codes to a set of input types able to provide the ability to generate that code. handle_data is a HandleData instance. d is a dictionary of input types to associated return codes(same f...
e10cff2df26baef6f68b52ec0de9987c8f938ec3
3,613,819
def delta_disk_neighbors( poses: np.ndarray, agent: int, delta: float) -> np.ndarray: """Return the agents within the 2-norm of the supplied agent. NOTE: The does not including the agent itself! Parameters ---------- poses : np.ndarray A `3xN` numpy array representi...
69735dbac90547d89eebb65ef524e570872c30f1
3,613,820
def categorize_answers(df, question, answer_column): """ Extract a question answered and count different answers. Parameters ---------- df : Pandas Dataframe Dataframe containing questionnaire data question : str question id answer_column : str column containing the an...
66af22d0e0a3af854f3e083186cff094e8420f1c
3,613,821
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool: """Set up Verisure from a config entry.""" coordinator = VerisureDataUpdateCoordinator(opp, entry=entry) if not await coordinator.async_login(): raise ConfigEntryAuthFailed entry.async_on_unload( opp.bus.async...
81f5edeaaeec7cb03496e3bd9fcde130f23c8ff1
3,613,822
import os def get_config_path(): """ Return the full path to the config file. """ # first priority: config file at ~/cadgan_resources/settings.ini home_dir = os.path.expanduser("~") config_dir = os.path.join(home_dir, 'cadgan_resources') at_home_config = os.path.join(config_dir, "settings....
e3367ad6c2cfe6ca4668de30dfc203ecca8a78ff
3,613,823
def get_spreadsheet(user, spreadsheet_id): """ Get spreadsheet :type user: django.contrib.auth.models.User :param user: User of spreadsheet :type spreadsheet_id: str :param spreadsheet_id: Spreadsheet ID of spreadsheet to get :rtype: Google `Spreadsheet` resource, int :return: Spread sh...
8d3ef4ac7bb31761e40e4f5d1d721acee5407dd4
3,613,824
import base64 def GetFileSha1(file_path): """Returns the SHA1 checksum of the file given (base64 encoded).""" return base64.b64encode(GetFileHashes(file_path, do_sha1=True)['sha1'])
5c6fd72de791f835731a966df419bbfb11b7214a
3,613,825
def quarterly_visits(customer_logins): """ Small subroutine to return quarterly visits from an amount of customer login data. """ visits = np.zeros(4) customer_visits = len(customer_logins.index) # 6 is the size of a part of day, integer division gives a # number between 0 and 3 vi...
afcad1111a6b98134d9aaed56e9570581053b478
3,613,826
def connect_UDP(host, port, waitTimeout=None): """ Connect RPC server via UDP. Returns C{t.i.d.Deferred} that will callback with C{protocol.MsgpackDatagramProtocol} object. @param host: IP address of host. @type host: C{str} @param port: port number. @type port: C{int} @param waitTimeou...
68c6d35f6970d7b4cf3cef5ab651e3f7c809d84d
3,613,827
def get_root_url(): """Return the root URL for this resource.""" # path = request.path # path = path[1:].split('/') # path = '/'.join(path[:2]) # return request.url_root + path return request.url_root
136e37f2768f7c6dd2bb1e95940d2768a68e970b
3,613,828
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/2017-07-01<br/>" f"/api/v1.0/2017-07-01/2017-07-10<br/>" )
b1ee7659f4eb778559cdaa9a2afbbb4e36563ed1
3,613,829
import hashlib def HashFileContents(filename): """Return the hash (sha1) of tthe contents of a file. Args: filename: Filename to read. Returns: The sha1 of a file. """ hasher = hashlib.sha1() fh = open(filename, 'rb') try: while True: data = fh.read(4096) if not data: br...
930ecd76dac76c09a17cddeeb52229189098553a
3,613,830
import pprint def hello_airflow(execution_date: dt.datetime, argument=None, **kwargs): """ Print the execution date (and other variables passed from airflow). Args: execution_date (dt.datetime): the time of the dag's execution (passed by airflow) argument: an example argument **kw...
8c34d614f7ce476d65dc66f6d17a1536620670a4
3,613,831
def get_moyenne(points_3D, indice): """Calcul la moyenne d'une coordonnée des points, la profondeur est le 3 ème = z, le y est la verticale indice = 0 pour x, 1 pour y, 2 pour z """ somme = 0 n = 0 for i in range(17): if points_3D[i]: n += 1 somme += points_3...
739548f93b2361e5f7e442dd0504e6b619ded1f9
3,613,832
def simplify_list_item_mathematical(list_item_mathematical: list) -> Real: """ Apply mathematical operations on the operands and reduce to 1 value Not Used :param list_item_mathematical: list of mathematical items :return: value """ # Current value value = None # Current Operator...
c28fd34970eeb3f97da101483843071f2429d299
3,613,833
from typing import cast def ca_authorize_key(h_session, h_object, auth_data): """ User authorizes key within session or access for use :param h_session: session handle :param object: key handle to authorize :param auth_data: authorization byte list, e.g. [11, 12, 13, ..] :return: Ret code ...
c84ca52e080c4b9a15505e89d9e8cc89a163c31b
3,613,834
def code_to_md(source, metadata, language): """ Represent a code cell with given source and metadata as a md cell :param source: :param metadata: :param language: :return: """ options = [] if language: options.append(language) if 'name' in metadata: options.append...
aa51b274d4aacd1bc5dce5bf9ee638429f0f9370
3,613,835
def get_schema(is_ipv6, octet): """Get the template with word slots""" new_line = '\n' period = '.' space = ' ' non_words = [new_line, period, space] if is_ipv6: schema = [octet, octet, 'and', octet, octet, new_line, octet, octet, octet, octet, octet, octet, octet, peri...
039e8a623be8e37acea7f2a4373a3b5f9bdaf53c
3,613,836
def zone_from_longitude(phi): """Return the difference between UT and local mean time at longitude 'phi' as a fraction of a day.""" return phi / deg(360)
690b965b13d1dad9d86fb0f6f41b55f32e3ed20d
3,613,837
def get_version(arg): """ Get version. """ if isinstance(arg, pymongo.MongoClient): return arg.server_info()['version'] elif isinstance(arg, str) or isinstance(arg, unicode): host, port = parse_hostportstr(arg) with pymongo.MongoClient(host, port, connect=True, serverSelectionTim...
c208fcfb93d8bda61e7bdcd3aee55bf84b4b51bd
3,613,838
def impute_features(feature_df): """Imputes data using the following methods: - `smoothed_ssn`: forward fill - `solar_wind`: interpolation """ # forward fill sunspot data for the rest of the month feature_df.smoothed_ssn = feature_df.smoothed_ssn.fillna(method="ffill") # interpolate between ...
3b61e29b30a011f86a8f18f649b77e72f3f87878
3,613,839
def module_fixture(): """Mock a module.""" return MockModule("test")
ec32830f43cbeb3330ffc4d95be115a403aab521
3,613,840
import umap import torch import tqdm def visualize(model, # type: thelper.typedefs.ModelType task, # type: thelper.typedefs.TaskType loader, # type: thelper.typedefs.LoaderType draw=False, # type: bool color_map=Non...
06149b1ef079b677a072c8704946bf1674befbc9
3,613,841
def update_user(username): """ Update attributes for a single user. Only users with 'role' admin can update users. Args: password(str): user's password role(int): user's role Returns: success(bool): successfully updated """ if not g.user.is_authe...
a1005d0eebe6263fc437edfd5791b404846094f8
3,613,842
import torch def loss_calc_pose(out, label, gpu0): """ This function returns loss for the pose auxilary task """ # out shape batch_size x channels x h x w -> batch_size x channels x h x w # label shape h x w x 1 x batch_size -> batch_size x 1 x h x w label = torch.from_numpy(label).long() ...
77f5a8b15307eeb729599f75843bdb4ab45ae8dd
3,613,843
from typing import Tuple def get_user_input() -> Tuple[str, float]: """Ask the user for a ticker and the number of years backward to go, then return the user's answers. Returns: Tuple[str, float]: the ticker and number of years backward to go """ ticker = input('Ticker: ').upper() ye...
31e6d002f20ac7fe6033c5934f027962428e38ee
3,613,844
def retrieve_text_document(image, default_lang=ALL_LANGUAGE) -> TextDocument: """ Retrieves text with all possible languages, detects the exact language and retrieves the text again, but with the correct language. Should only be used for medium or large images """ text = pytesseract.image_to_s...
6ebc5359f46df4a88be98b800e6a9c441a520d23
3,613,845
def flow_convolve_nearest(data, flow_func, structure=None, wrap=False, function=None, dtype=None, debug=False, **kwargs): """ A function to compute a Semi-Lagrangian convolution using the nearest neighbour method. This can be performed faster as no interpolation is required. Input: data: ...
dd51014c2dabcc39bac77b6b938f7d22c07cf7ca
3,613,846
def login_view(request): """Provide the login view and functionality.""" if request.user.is_authenticated(): return redirect(reverse('index')) form = UserLoginForm(request.POST or None, request=request) next_page = request.GET.get('next', reverse('index')) if form.is_valid(): if re...
b4e18a81dda4d11b1840ed3ce129f79a39d5f549
3,613,847
import time def chi2_bin(df: pd.DataFrame, x: str, y: str, bins=5, init_bins=100, init_method='qcut', init_precision=3, print_process=True): """ 卡方分箱 :param df: 数据集 :param x: 待分箱特征名称 :param y: 目标变量的名称 :param bins: 最终的分箱数量 :param init_bins: 初始化分箱的数量,若为空则钚进行初始化的分箱 :param in...
9ae231a8bdacc262fef9b18540bb3e3e2e08e339
3,613,848
def cache_control_expires(num_hours): """ Set the appropriate Cache-Control and Expires headers for the given number of hours. """ num_seconds = int(num_hours * 60 * 60) def decorator(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *...
b6f726e84b9d9e43775e130effeb023ccd86c7af
3,613,849
def get_widget_at_mouse(): """ Get the widget under the mouse :return: variant, QWidget || None """ current_pos = QtGui.QCursor().pos() widget = QApplication.widgetAt(current_pos) return widget
52e11f16d34723170cbeb76e8f3c36c1ba5a022a
3,613,850
from typing import Dict from typing import List from typing import Union from typing import Iterable from datetime import datetime def build_can_scraper_dataframe( data_by_variable: Dict[ccd_helpers.ScraperVariable, List[float]], location=DEFAULT_LOCATION, location_type=DEFAULT_LOCATION_TYPE, location...
80c4f3c4f3a8b443f4291c89f9e08afe07926e68
3,613,851
import subprocess def getNetWorkTXRXValue(networkCardNum, valueType): """ function : Check Bond mode input : int, String output : int """ cmd = "/sbin/ethtool -g %s | grep '%s:' | tail -n 2" % (networkCardNum, valueType) (status,...
de22001ebd152220e923e885993558cbb87832e5
3,613,852
import re def process_text(): """Remove emoticons, numbers etc. and returns list of cleaned tweets.""" data = pull_tweets() regex_remove = "(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^RT|http.+?" stripped_text = [ re.sub(regex_remove, '', tweets).strip() for tweets in data ...
667ed53c3f23c4d280c389692feea12e3b309e91
3,613,853
import copy def concat(input_op_nodes: list, output_name: str, column_names: [list, None] = None): """ Define Concat operation. :param input_op_nodes: List of parent nodes for the node returned by this method. :param output_name: Name of returned Concat node. :param column_names: List of output r...
03da1af22d5edc44e5a4de2be167f474d603bfdf
3,613,854
def _GetVgInfo( name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo): """Retrieves information about a LVM volume group. """ # TODO: GetVGInfo supports returning information for multiple VGs at once vginfo = info_fn([name], excl_stor) if vginfo: vg_free = int(round(vginfo[0][0], 0)) vg_size = i...
b44a9fc57689a68fb65261dbfd57ae5199cb7c52
3,613,855
def ca_set_container_policy(h_session, h_containerber, policy_id, policy_val): """Sets a policy on the container. NOTE: With per partition SO this method should generally not be used. Instead ca_set_partition_policies should be used :param int h_session: Session handle :param h_containerber: The c...
d697965035ce173f9c119498d2923c0f81187894
3,613,856
def crop_xyz_grid_by_extents(xyzgrid,extents): """ crop grid in xy plane xyzgrid: Dataframe with x,y,z columns or ARRAY with first 3 columns being x,y,z coordinates extents: (xmin,ymin,xmax,ymax) returns: cropped Dataframe """ if type(xyzgrid) == np.array: xyzgridnew = pd.DataFrame(xyzgrid,columns=...
52e456f2d63b87727a6871a2d9404558edbd8da1
3,613,857
def _bytes_through_tmp_image(arr): """Retrieve binary blob for a numpy array image""" mimetype = 'tiff' arr_min = numpy.min(arr) arr_max = numpy.max(arr) # if (arr_max > 1) & (arr_max <= 255): # arr = arr / 255 # numpy.uint8(arr) print "MIN:" print numpy.min(arr) print "MAX:" ...
fb4a704ae331a5f2e807d1d6ad65df52c420fed2
3,613,858
def _create_machine_onapp(conn, public_key, machine_name, image, size_ram, size_cpu, size_disk_primary, size_disk_swap, boot, build, cpu_priority, cpu_sockets, cpu_threads, port_speed, locat...
3385f16f2548412f28b15f67809bdac1e1205a64
3,613,859
import random def rand_5() -> int: """ Generates a single, randomly generated 5-digit number. Returns: The generated 5-digit number. """ return random.randrange(100000)
b6abb4ecbd4397548e35c386a4e653df205282ea
3,613,860
def GVizGetLayoutStr(*args): """ GVizGetLayoutStr(TGVizLayout const & Layout) -> TStr Parameters: Layout: TGVizLayout const & """ return _snap.GVizGetLayoutStr(*args)
e0c40ff6d0f74c9d4c423abd5c41b2507481242c
3,613,861
def discard_and_merge_types_select_most_common_n(dataset: pd.DataFrame, most_common_n: int = 20) -> pd.DataFrame: """ It is possible that the negative example creation suffers due to a long tail distribution of types. - Can we merge some of the types? - Using name based matching? Eg. ...
7bf7c4b14ae8ceadb40c8fe92adb06b8fd4837b6
3,613,862
def iou(box_group1, box_group2): """ Calculates the intersection over union (aka. Jaccard Index) between two boxes. Boxes are assumed to be in corners format (xmin, ymin, xmax, ymax) Args: - box_group1: boxes in group 1 - box_group2: boxes in group 2 Returns: - A numpy array of shape (len(...
4a547c0b623cac4b58eb90ec71a58c18ad6c0a4a
3,613,863
import random def perform_DQN(agent, episodes, iterations, path, batch_size=4, C=30, randomize_theta=False): """ :param agent: the RL agent :param batch_size: size of minibatch sampled from replay buffer :param C: network update frequency :return: agent, and other information about DQN """ ...
7c1404d2266472300127d54212e09220b8d119cc
3,613,864
def parse(davartext: str, debug: bool = False) -> arpeggio.NonTerminal: """Parses a text string in davar into a list of davar Statements Parameters ---------- davartext : str A text string written in davar debug : bool, optional If true, prints debug statements as davartext is parse...
c9c4b88323469a16068925d1b7bbf42d9cfcf93b
3,613,865
from typing import Mapping from typing import Sequence def freeze(data): """ :param data: Anything serializable as JSON :return: An immutable and hashable version of `data`. Mappings are replaced by `frozendict` instances, sequences are replaced by tuples, and everything else is returned uncha...
d69bbd43c466ec50d3f915cb9d97b4eeb0de1d21
3,613,866
def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" assert hasattr(value, str(arg)), "Invalid %s in %s" % (arg, value) return getattr(value, str(arg))
e7cac978986448784f4b9f841e7126eca78236fa
3,613,867
def task_project(): """ RESTful CRUD controller for options.s3json lookups """ if auth.permission.format != "s3json": return "" # Pre-process def prep(r): if r.method != "options": return False return True s3.prep = prep return s3_rest_controller()
7afffb382e7ecf1bc1f5f398a94227a8722c7c90
3,613,868
import re import click def validate_memory(_ctx, _param, value): """Validate memory string.""" if value is None: return if not re.search(r'\d+[KkMmGg]$', value): raise click.BadParameter('Memory format: nnn[K|M|G].') return value
105035f338138ff47b6505868c8bf9d2bf37fa91
3,613,869
import argparse def cmd_arguments(): """ taking CMD arguments and sending them through the argument parser. """ parser = argparse.ArgumentParser() parser.add_argument("-i", "--image", help="Full image path can be optionally supplied.") args = parser.parse_ar...
ce64792de04ab054959380c5089e47277343bce3
3,613,870
from typing import Dict from typing import Any from typing import Optional from typing import List import inspect def get_table_columns( uri: str, extra_params: Dict[str, Any], schema: Optional[str], table: str, ) -> List[Column]: """ Return all columns in a given table. """ engine = c...
1518b79bf248282c2947eb7b748d7c653f313421
3,613,871
def page (result = ''): """Return the main form""" return CGISH_HTML % {'SHELL_OUTPUT':result}
72ab545440b2ed2d4151202ad91c58a68f3b582e
3,613,872
def forge_formats( token, verbose ): """Retrieve and return the file formats currently supported by the translation processes.""" headers = {'Authorization': 'Bearer ' + token} r = requests.get(url_formats, headers=headers) if verbose: print '\nForge formats call:' print ' Status:', r.status_code ...
e2ad74334486c9e4982b5d3e9003aebe6af21f76
3,613,873
import math def pad_1dconv_input(input, kernel_size, mode="same"): """ This method pads the input for "same" and "full" convolutions. Currently just Same and full padding modes have been implemented :param input: Input Tensor with shape BATCH_SIZE X TIME_STEPS X FEATURES :param mode: ...
60baf28bcca653e0df098604ed12013456cf12a2
3,613,874
def create_dates_list(start_date, end_date): """ Return list of days in range of start and end date for itinerary.""" delta = end_date - start_date dates = [] for d in range(delta.days + 1): dates.append(start_date + timedelta(days = d)) return dates
9240852b3e0b9f4d54ef547d0c35f63d4d2235ea
3,613,875
def directory_indexing(): """ This function search for indexing in all directories already found and stored in directories. """ global directories global directories_with_indexing global debug global crawl_results global URL global host_name global main_domain global error_...
abed5d9a039736555cbbd7b2a61bf7e553bcd9f1
3,613,876
import re def run_name_to_flags(checkpoint_path: Text): """Extracts flag settings from a saved checkpoint path name. TODO: Consider making a single class that converts flags to run names and run names to flags. Or find some existing code that does this. Args: checkpoint_path: Path where checkpoint is sa...
f9c2a6439b991de2ac0544775d65cab80d43eb0a
3,613,877
def viterbi(observations, states, priors, transitions, emissions, probabilistic=False): """Perform HMM smoothing over observations via Viteri algorithm :param list(str) observations: List/sequence of activity states :param numpy.array states: List of unique activity state labels :param numpy...
6fd74e9968dc10779bf2ac64595003b66598d5b6
3,613,878
def build_analysis_data(analyses): """ Args: analyses: (dict) of analysis Returns: dict: formatted entry context """ entry_context = dict() entry_context['VMRay.Analysis(val.AnalysisID === obj.AnalysisID)'] = [ { 'AnalysisID': analysis.get('analysis_id'), ...
6a4d52966ca2cac22e74574110e7da6b5882bb64
3,613,879
def CurveFilletPoints(curve_id_0, curve_id_1, radius=1.0, base_point_0=None, base_point_1=None, return_points=True): """Find points at which to cut a pair of curves so that a fillet of a specified radius fits. A fillet point is a pair of points (point0, point1) such that there is a circle of radius tangent ...
f770b62804be7ced30abcbfdee664348c83a9167
3,613,880
from datetime import datetime def get_today(): """ Returns the datetime.date for today. Needed since tests cannot mock a builtin type: http://stackoverflow.com/a/24005764/4651668 """ return datetime.date.today()
c03ccfd7ab55036c83d9b2fb2b02386ab61e92b2
3,613,881
def template_model1(): """ -------------------------------------------------------------------------- template_model1: Variables / RHS / AUX -------------------------------------------------------------------------- """ model_type = 'continuous' # either 'discrete' or 'continuous' model1 = d...
3095e6093a04572ebc32a4d35d0579d379ee3464
3,613,882
def flags(flags): """Hard-code KZC flags""" def f(test, way): test.way = None test.args += flags return f
4257fd66abc036af0d9ef9f971fcc834c735460a
3,613,883
def indexColumnPivot(Z, minOrMax, tableaux, _colPivot): # seach the value that'll come to base (index column) """ [seach the index of pivot column. That is a value that'll come to base] Arguments: Z {[list]} -- [list from Z line] minOrMax {[int]} -- [description] tableaux {[matr...
b47ac8f8ba3661e193cf9b687d5e0ff6a4bd1d7e
3,613,884
from typing import Callable def register_model( name: str, build_function: Callable, model_type=None, convex=None, best_value=None, best_dual=None, opt_value=None, bigM=None) -> None: """ Registers the model in the model library. Parameters ---------- name ...
9c6c5d53b06968712ce648880d7a0ce443b7229e
3,613,885
from re import T def cim_size(estimated: T.FloatTensor, target: T.FloatTensor) -> float: """ Empirically estimated kernel size for CIM taken as the average reconstruction error based on Eq. 25 in https://lcs.ios.ac.cn/~ydshen/ICDM-12.pdf. Parameters: estimated (list): current Q-values ...
767237a433757943defc4fe74af4a2a7f1812d7d
3,613,886
import logging import requests import sys import re def poll_transloadit(args, upload_url): """ Polls Transloadit's API to determine the status of the upload. Outputs information to stdout (unless suppressed). Raises an exception if there is an error, returns tuple of response information when complet...
5b0701eb26abbe6e01e902bd87e04151fe487aaf
3,613,887
import traceback import logging import sys def call_cmd(cmd): """ Call a command line and return the result as a string. """ try: child = Popen(list(str(cmd).split(' ')), stdout=PIPE) string = child.communicate()[0] child.stdout.close() except OSError: message = str("Error...
11956adf517dd050077f9445439e93b12734f68d
3,613,888
def send_message(service, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Messa...
18ec4cf6e72800505860b8d202ad7f5ffa46839f
3,613,889
import re def rgb2hex(rgb_string, drop_alpha=False) -> str: """Convert an RGB string to HEX. Args: rgb_string (str): This is the RGB or RGBA string to convert. drop_alpha (bool): ``True`` will **drop the alpha value** from the HEX string. This is useful for colour maps that ...
ac673d7ea668a516372650677374ccc81b304b60
3,613,890
import time import torch def train_cn_consistency(net, train_loader, optimizer, scheduler): """Train for one epoch.""" print('running train_cn_consistency') batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() s_losses = AverageMeter() c_losses = AverageMeter() ...
ddcff494475915f0f657c1127e83cf53d96bd875
3,613,891
def getLink(node, attr, destination=False, source=False): """ :param node: :param attr: :return: Linked node :rtype: str/None """ # validate plug plug = getPlug(node, attr) if not cmds.objExists(plug): return # get connections connections = cmds.listConnections( ...
65f23c12b10e22b2d81b984521eac2ead6fb291d
3,613,892
def _reset_pk(query, pk = 'id', num = 0): """ 找出需要重新排列的主键 """ last_diff, changes = 0, [] start, stop = 0, 0 if num > 0: query = query.filter(Expr(pk)>num) for row in query.order_by(pk).iter(pk): id, num = row[pk], num + 1 curr_diff = id - num if curr_diff == 0: ...
967da338f9e2da362b452fee70bfac461a5db63d
3,613,893
def batch(data, batch_size, batch_size_fn=None): """Yield elements from data in chunks of batch_size.""" if batch_size_fn is None: def batch_size_fn(new, count, sofar): return count minibatch, size_so_far = [], 0 for ex in data: minibatch.append(ex) size_so_far = batc...
eab78d22bba1b0575dcb5fedc2820f2115a6a9f5
3,613,894
def interpolate_lightcurve(lc_table=None, lc_array=None): """Returns linear interpolator of epoch lightcurve """ if lc_array is None: if lc_table is None: raise ValueError('Must provide one of [lc_table, lc_array]') else: lc_array = extract_lightcurve_array(lc_table) ...
3897b8a5cd836d8ecbc540eb841ab33ca0eb8277
3,613,895
def get_account_user_id(**kwargs): """ Returns account_user_id from arguments Keyword arguments: :param vm_login_id: user's VM login ID like p100 :param email: user's E-Mail address :returns: account_user_id :rtype: int """ if 'vm_login_id' in kwargs: users = User.all() ...
93669b081cd5535be7a805aa6961da59fd9f4127
3,613,896
def lnZ_PEB(time: np.ndarray, flux: np.ndarray, sigma: float, P_orb: float, M_s: float, R_s: float, Teff: float, Z: float, plx: float, contrast_curve_file: str = None, N: int = 1000000): """ Calculates the marginal likelihood of the PEB scenario. Args: time (numpy...
b6c6a0c5f31ee44900280f36c3e91bdbd351e238
3,613,897
def interval2string_m(i: float) -> str: """Convert a time interval to a string or to NA if it is does not have a value Arguments: i: is a number of seconds Returns: a string of the number of minutes represented or NA if i is not a float """ if type(i) == float: ...
e7d710d10fb8a3393ca2fad4d99e7acc5f4b45eb
3,613,898
def ldns_sign_public_buffer(*args): """LDNS buffer.""" return _ldns.ldns_sign_public_buffer(*args)
a81f529c8b735403279b49bd5f253411b50c01fa
3,613,899