content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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
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
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
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 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 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 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
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
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 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
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
def download_image(url): """Downloads ipg, jpeg fils from given URL""" response = request.urlopen(url) return ContentFile(response.read())
6a96efe321dcbd84134400dce34de5484d7aa53f
3,613,900
from typing import Tuple def _evaluate(dataset: tf.data.Dataset, model: tf.keras.Model, loss_fn: tf.keras.losses.Loss) -> Tuple[float, float]: """Evaluates the given model for the whole dataset once.""" loss_sum = 0 correct_item_count = 0 item_count = 0 for (x, y) in dataset: ...
ba950cea2b5bee509d0b4392f762bbb0f9a3ab1f
3,613,901
def tab(column) -> str: """Emulates the TAB command in BASIC. Returns a string with ASCII codes for setting the cursor to the specified column.""" return f"\r\33[{column}C"
d57e0d6840c9f446b2832bbe725bc986aaabf13e
3,613,902
def _make_laplace_numba_2d(grid: CartesianGrid) -> OperatorType: """make a 2d laplace operator using numba compilation Args: grid (:class:`~pde.grids.cartesian.CartesianGrid`): The grid for which the operator is created Returns: A function that can be applied to an array of val...
5e34b9fadcd9a8f8304409f00e744e49645cc89a
3,613,903
def preview(slug): """Show the preview of a newly created or edited post. Parameters ---------- slug : str The slug is the part of the URL which identifies a particular post on our blog in an easy to read form. """ post = session['post'] # When I put the post object for the ...
d2116c426ec7bf657e5fb596cbb257c690f411b4
3,613,904
def get_longest_streak_of_all_habits(session): """ :return: the value of the largest value in the streak column. """ try: longest_streak_for_all_habits = (max(session.query(HabitHistory.streak) .all())) except ValueError: raise NoHabitsInHisto...
3be2a0b2e458663e90a810c49cd41f3fda6a98ad
3,613,905
import tokenize def eye(N, chunks="auto", M=None, k=0, dtype=float): """ Return a 2-D Array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. chunks : int, str How to chunk the array. Must be one of the following forms: ...
0882c19f3abd5d9c6936fb704664b129c2b16d0e
3,613,907
def calc_num_walls(side_length, room_positions, ap_positions): """ Calculate the number of walls between each room to each AP. This is used to calculated the wall losses as well as the indoor pathloss. Parameters ---------- side_length : float The side length of the square room. ...
cc1fc51189e614b353810b2f76421aa6951fa84e
3,613,908
import binascii def x(h): """Convert a hex string to bytes""" return binascii.unhexlify(h.encode('utf8'))
0cbba146b22419f9e67f0a2ea46851a47826d4f8
3,613,910
def get_new_goal(current_pos, current_dest, home_pos, rally_point, batt_level, blocking_time=10, speed=5, energy_consumption=1): """ Function for deciding the new goal All the input coordinates are in the format [LAT, LON] (deg). returns a [int, int] list with [X, Y] coordinates of n...
da8a22da63d518935a1d1cd2b9aa9515abc301e5
3,613,911
def is_cuda_consistent(*args): """ See if the cuda states are consistent among variables (of type either tensors or torch.autograd.Variable). For example, import torch from torch.autograd import Variable import torch.nn as nn net = nn.Linear(512, 10) tensor = torch....
6554bd61956ae08080cf3d4564387cddc7ad0cb7
3,613,912
def create_nginx_config(server, port): """Create NGINX config in sites-enabled directory""" if config_count() >= config_limit: abort(400) ip = request.remote_addr nginx_config = nginx_sites_enabled + '/' + server temp = sys.stdout sys.stdout = open(nginx_config, 'w') print template...
b998c0dcd27f8578da76ba6fa24cd11c4ed76940
3,613,914
def elbo_batch_loss(model, X, y, inds, samples): """Compute an estimate of the negative ELBO loss from a single batch. Args: X ([N, input_dim] numpy array): Train inputs. y ([N, output_dim] numpy array): Train outputs. inds ([batch_size] torch tensor): Indices for the batch. samp...
8fc4fa1447607ab7d2190d226df606637b6d98e5
3,613,915
def to_epoch(str_time): """Take in string time(yyyy-mm-dd) and convert to epoch time.""" return int(dt.datetime.strptime(str_time, "%Y-%m-%d").timestamp())
c085f379399ad7257cf2a1d190ff3360bccda821
3,613,917
def _rpn_loss_regr(y_true, y_pred): """ smooth L1 loss y_ture [1][HXWX10][3] (class,regr) y_pred [1][HXWX10][2] (reger) """ sigma = 9.0 cls = y_true[0, :, 0] regr = y_true[0, :, 1:3] regr_keep = tf.where(K.equal(cls, 1))[:, 0] regr_true = tf.gather(regr, regr_keep) regr_pr...
52cdfc439af2a91a3d638bff5ba46925c90c2063
3,613,918
def create_markdown_file_from_filename(markdown_filename:str) -> SuccessErrors: """Creates a markdown file based on incoming filename suggestion If already exists, returns false, If other os.file issue, returns false, If successful, returns true Args: markdown_filename (str), ...
c02f1de1d0f749e60268a56537b10ff4e15544ad
3,613,919
def fit_msm(trajectory, prefix=None, save_path=None): """Function to fit the msm to a given trajectory and save the vizualization Args: trajectory ([type]): Time series to be discretized prefix ([type], optional): Name to save a file. save_path ([type], optional): Wheree to save a fil...
2f7454f597a9cc3b0daa54c71c7a1e0dba455af5
3,613,920
def dataclass( _cls = None, *arg, init = True, repr = True, eq = True, order = False, unsafe_hash = False, ): """ Modification of dataclasses.dataclass that adds the following methods: 1. dataclass.from_tuple(data_tuple: Tuple[Any]) 2. data...
5c5315d089496d27554e72f87f67bad85ec45ba1
3,613,921
def get_quiz_info(random_words): """ get examples and random answers for each test word in random_words :param random_words: a list of random test words :return: a list of quiz information """ db_session = DB_Session() allrows = db_session.query(TestWords) quiz_info = [] for word in ...
3a3d994dc7ba77d6a2a1f1ed36ef0c94244f4baa
3,613,922
def parse_dependencies(file_names): """Program logic: read files, verify dependencies. For each input file, read lines and create dependencies. Verify each dependency. :param file_names: files to read dependencies from. :return: The list of dependencies, each verified. """ # type: (List[Text])...
2b34060b79e673b84b5c29114407a7d0e876463d
3,613,923
def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / '__init__.py' try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(...
9b640bcb621874fcc37bf64853d37dd57add4fe0
3,613,924
import requests def tencent_resolve(url_like): """根据输入的url_like,查询其腾讯安全接口查询结果 :url_like: 可能有几种形式:url: http://www.baidu.com,domain: www.baidu.com,ip: 14.15.15.17,甚至可能是:http://14.15.16.17:80 :returns: {url_like: tencent} """ url = TENCENT_URL payload = { 'dname': url_like } hea...
89f5f4eb20dfa3a503312eace80bd900acff6146
3,613,925
def host_create(context, values): """Create a host. :param context: context to query under :param values: dictionary of host attributes to create :returns: dictionary-like object containing created host """ return IMPL.host_create(context, values)
d7285795b42b4eca9c9bc19f72d18cad8e36d464
3,613,926
def __dispatch_remove_command(arguments: list) -> str: """ Dispatches command to remove file/folder Returns command that was run """ command = "" if arguments["file"]: command = "remove-file" library.remove_file(arguments["file"]) elif arguments["folder"]: command = "...
fd94f3fcd929b9aa220f99684282b439023b728b
3,613,927