content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_challenge_phase_by_slug(request, slug): """ Returns a particular challenge phase details by pk """ try: challenge_phase = ChallengePhase.objects.get(slug=slug) except ChallengePhase.DoesNotExist: response_data = { "error": "Challenge phase with slug {} does not ex...
169902fa80f1a02b21bf8902f2888f2a0d73624a
3,620,000
import re def parse_multiline(element, poe_implicit_split = False): """ Get data from a row & regroup tag-separated string (<br/>) in a list poe_implicit_split: <number>( to )<number> for Implicit Mods extraction (optional) """ res = [] for data in element: content = [] for x in data.strings: ...
ef59fe17a3b221086276baa67448d0870b838f71
3,620,001
def pil_to_cv(pil): """ Convert an image loaded from PIL to opencv format The main difference is that PIL uses [R, G, B] and opencv uses [B, G, R]. Args: pil: An image loaded from PIL function Returns: cv_img: The corresponding image in opencv format """ pil...
242eb812aae3eb8fa77cbc21bc4b351268e21393
3,620,002
def get_characteristics(trajectory, dim): """ Function return characteristics for given scenario :param char_set: enum, information about characteristic set scenario :param path_to_file: str, path to file with trajectory :param typ: str, type of diffusion i.e sub, super, rand :param motion: str,...
ca0a56279034cc8b6fde8802b49d75b22466696e
3,620,003
from typing import List from typing import Any from typing import Optional def binary_search(sorted_list: List[Any], value: Any, list_size: Optional[int] = None) -> int: # todo: remove? """ Performs binary search. :param sorted_list: List with values in ascending order. :param value: Value for which...
1d6a39c4d2d0126d3f822354a3d3e348fe7b7c96
3,620,004
import logging def uncompress_file(infile, uncompressed, typeinfo=None): """ infile: input filename. uncompressed: output filename. typeinfo: output from the 'file' command; if None we'll run 'file'. Returns: comptype comptype: None if the file wasn't compressed, or 'gz' or 'bz2'. """ if typeinfo is None: ...
75cbb82163ee49fce8c4426d47c79ffacff4a468
3,620,005
def introspection(): """Gets the base class for the introspection class. We have to use the configured base back-end's introspection class for this. """ return base_backend_instance().introspection.__class__
283d36ec9ff12bb1e1372fba4f4ee5b9c4a30027
3,620,006
def _kickoff_df(fpl_data_dict, pos, footballer_func): """ return kickoff from week df based on position""" return _fetch_history_df(fpl_data_dict, pos, footballer_func, {"kickoff_time": "kickoff_time"})
12c983af1012067f6c767d9de2c899b5d057933f
3,620,007
import os import json def read_json(file_path): """ Read a json file. return: Dictionary or empty dictionary. """ if os.path.isfile(file_path): with open(file_path, "r") as f: try: return json.load(f, object_hook=jsonKeys2int) except json.decoder.JSO...
7ea0e0141d89f3ef13ae2c4f6533e246ea6692d2
3,620,008
def score_sig_1D_base(true_signatures, pred_signatures): """ percent of mutations with the right signature Parameters ---------- true_signatures: iterable array-like of length N (number of mutations), with the true signature for each mutation pred_signat...
cd04cef1c7eecea8da804fe631fedc18c33b4d11
3,620,009
def compute_apparent_power(f, j, seconds_per_file, values): """ Apparent power is the product of the voltage RMS and the current RMS. """ cs = [n for n in list(f) if 'current' in n] apparent_power = dict() for cs_i, _ in enumerate(cs): if 'voltage' in list(f): voltage_name ...
76f7b903bce2f340d0494524f3d0d2ad40e6422e
3,620,010
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') Session.configure(bind=engine) MailboxManager.init(settings['maildir_path']) config = Configurator(settings=settings) config.add_renderer( ...
28330cd67b4be3f49ef930f8d2a9b50749a623c1
3,620,011
def charge_density(location, rho_bulk, charge, surface_potential, temperature=300, permittivity=80, species='Na'): """The density of ions near a charged surface. Calculates the number density of ions of a species, at a distance of "location" away from a metal/solution interface. The metal is charged, and thus the d...
1cc9717fd28d2d4ce040a1b960e08e4ba9236371
3,620,012
import decimal def _dict_decimal_to_float(my_dict): """If any values in dictionary are of dtype 'Decimal', cast to float so can be JSONified. """ for key, val in my_dict.items(): if isinstance(val, decimal.Decimal): my_dict[key] = float(val) return my_dict
7d1741322782c49b9b8a6a7369344797439ff00b
3,620,013
from typing import Optional from typing import Callable from typing import Dict def get_augment_preprocess( augment_params: ml_collections.ConfigDict, *, colorjitter_params: Optional[ml_collections.ConfigDict] = None, randerasing_params: Optional[ml_collections.ConfigDict] = None, mean: Optional[t...
1ae9633d09c0f12dbeedfc34dcce5779623110f1
3,620,014
import random def cutmixup(img1, img2, mixup_prob=1.0, mixup_alpha=1.0, cutmix_prob=1.0, cutmix_alpha=1.0): # (α1 / α2) -> 0.7 / 1.2 """ CutMix with the Mixup-ed image. CutMix and Mixup procedure use hyper-parameter α1 and α2 respectively. """ c = _cutmix(img2, cutmix_prob, cutmix_alpha) if c...
0868e16c2a99278368ab68c3894c1bd11194a248
3,620,015
def is_pattern_match(s, exclude, include): """check if pattern match with 'include' and 'exclude' option """ if is_windows: exclude = to_unix_path(exclude) include = to_unix_path(include) if exclude == None: return True elif include == None: return (not pattern_match(...
63e008b9332fc0708b8155b27da7be858ba8e5ea
3,620,016
def translate_filter_titles(filters): """ Translates filter titles according to the selected language Args: filters (dict): Contains the filters that shall be translated Returns: Returns the modified filters """ if filters.get("searchText", {}).get("title", "") != "": filter...
a9cf454dc21c3d3f7206902a83d847a6b8bb0e30
3,620,017
def print_available(key): """Return available models for certain parameter space Parameters ---------- key : str available parameters are [cloud, distance, gravity, metallicity, phase, temp] Returns ------- str, list input key and list of available values """ return key, header[key].unique()
c564a6d5b7c1fd4cfeb98dab7fc5d2e52dcbbb7c
3,620,018
def search(endpoint, query, sort=None, order=None, page=1, per_page=100, strict=False): """ `endpoint:str = 'users','repositories','commits'` `query:str` - users: ------ https://developer.github.com/v3/search/#search-users https://help.github.com/en/github/searching-for-information-on-gith...
fa71616cbca39cc76295340249f9a2801ec657b0
3,620,019
def augment_Q(Q): """Augment the transition matrix Q such that it is in the from required in order to solve. In essence this function gets M and b where: - M = the transpose of {the transition matrix Q with the last column replaced with a column of ones} - b = a vector of the...
09e63368f22152f03d22d4e21c2bf370754ebe8d
3,620,020
def string2cycles(string): """ Convert string from user input to permutation in cycle notation as list :param string: Permutation as string :type string: string :return: Returns permutation in cycle notation as list :rtype: list """ groups = string.split(')(') items = [] for i...
5a10f270fb934a1b22f61e84e61f679f2cad5f79
3,620,021
import os import logging import subprocess def ddecal(msin, srcdb, msout=None, h5out=None, solint=120, nfreq=30, startchan=0, nchan=0, minvisratio=0.6, mode='diagonal', uvlambdamin=500, subtract=True): """ Perform direction dependent calibration with DPPP """ h5out = h5out or os.path.split(msin)[0]...
cd0dd1ebe46462c9839e88b52187a0cf086fb251
3,620,022
def gram_schmidt(basis): """ Performs Gram Schmidt Orthogonlization of a basis_o :param basis: list of numpy ndarray of shape (2,M) of M samples :rtype: list of numpy ndarray :return basis_o: orthogonlized basis """ b1 = basis[0] b2 = basis[1] basis1 = b1 / sqrt(innerprod_q2(b1, b...
403b5bd86bcf893268cb28752b7c0fd58520bb6a
3,620,023
import json def fetch_joke(): """Fetch jokes""" request = Request('http://api.icndb.com/jokes/random?limitTo=[nerdy]') response = urlopen(request) joke = json.loads(response.read())['value']['joke'] return joke
46fc2816386103b78a9251747819d721f0f0297f
3,620,024
import os import re def BuildAUTestTarball(buildroot, board, work_dir, version, archive_url): """Tar up the au test artifacts into the tarball_dir. Args: buildroot: Root directory where build occurs. board: Board type that was built on this machine. work_dir: Location for doing work. version: Bas...
b346ffc7a77e5da252471bc4751dcfa264b06744
3,620,025
def create(reference_set_dict, monotone_relationship, minval=None, maxval=None): """ Create a scoring function that maps objects with N attributes to scores. Required arguments: reference_set_dict -- A reference set mapping objects to scores. monotone_relationship -- A length-N vector with +1/-1 entries. +1 ...
2e7fc4bade833bf1cd4c69d370f5e0c1ebcfe959
3,620,026
import re def split_at_whitespace(string): """Like string.split(), but keeps empty words as empty words.""" return re.split(__WHITESPACE_SPLIT, string)
1862c955b02d648c8b43a31b8e92e2cdda395363
3,620,027
def _make_list_value_pb(values): """Construct of ListValue protobufs. :type values: list of scalar :param values: Row data :rtype: :class:`~google.protobuf.struct_pb2.ListValue` :returns: protobuf """ return ListValue(values=[_make_value_pb(value) for value in values])
a7028b695fe8fe7ba46304d4f03ae8a91b6be85c
3,620,028
def sciper2name(sciper): """Convert a sciper to a name, using EPFL's LDAP""" return search_attr_in_ldap(sciper, 'cn') or _("Unknown name")
cb991b80e03164b0536dd8dea527b5421f5c2461
3,620,029
from datetime import datetime def title1(): """ Ученое звание """ title = Person.Title() title.date = datetime(2010, 1, 1) title.title = 'доц.' return title
f7aeb02bc98379d4f94278185898cf887834ad2d
3,620,030
def from_args(it, key, lo, hi, prefix, reverse, max_, include, max_phys): """This function is a stand-in until the core.py API is refurbished.""" if key: it.set_exact(key) return it.forward() elif prefix: it.set_prefix(prefix) else: if lo: it.set_lo(lo) ...
859e716e5eb32be10806de400b97fdf0e4770ed4
3,620,031
def bump_version(version_array, level): """ Perform ++1 action on the array [x, y, z] cell, Input values are assumed to be validated :param version_array: int array of [x, y, z] validated array :param level: string represents major|minor|patch :return: int array with new value """ if typ...
8a26db1694cf777915cc8c170355fd77ea4e9e66
3,620,032
def all_event_tweets(request): """Summary of tweets and submission of tweets""" return render(request, 'manage/all_event_tweets.html')
7ae215dd6a6ca1576af0cfd9af60dc9286a33370
3,620,033
def map_persons_to_known_ldap_user(person_record, session): """ Since the exported persons table contains records without email from various sources, we have to try to map it to an existing record or create a new one. The ldap fetched users have an attendee created with first_name, last_name an...
9638adb1aed2a46ed6267c00b9020dd989d04b4c
3,620,034
def print_usage(): """ Print commandline usage :return: returns 1 for for exit code purposes :rtype: int """ print(""" Usage: {0} --help-info {0} [options] input.json output.json Options: --overwrite Overwrite output file -a field=val Only add a field if it doesn't exi...
5ef1e795b3a3fa6037750d2d63b1ac8989f20e20
3,620,035
from typing import Dict from typing import Any async def list_of_speakers_slide( all_data: AllData, element: Dict[str, Any], projector_id: int ) -> Dict[str, Any]: """ List of speakers slide. Returns all usernames, that are on the list of speaker of a slide. """ list_of_speakers_id = element....
90bddfe2a6401c4e0f1bdbd0a6d6eb624423f93b
3,620,036
from typing import Tuple def calculate_intervals(values: np.array) -> Tuple[int]: """Calculate intervals between the provided note values.""" return tuple( [(next_note - note) % 12 for note, next_note in zip(values, values[1:])] )
0a3103db568c5b418f2c78f3ba1f216d6c8fb914
3,620,037
from datetime import datetime def get_time_with_timezone(time_delta): """Parameter is timezone offset from UTC in seconds. Returns a string H:M:S.""" return (datetime.datetime.now() + datetime.timedelta(seconds=time_delta)).strftime("%H:%M") + " UTC" + str(time_delta / 3600)
1b0381234c2cdeb5e7738df7303538083f873ba0
3,620,038
def shallFreezeAllStdlib(): """*bool* = **not** shallFollowStandardLibrary""" return not shallFollowStandardLibrary()
0cd50ffb7b0eb1a9aa5e411187c373ee1002c03e
3,620,039
def _get_timestep_lookup_function(control_loop_period, memory_loc, rtf_key): """ Creates a customized timestep lookup function for a SynchronizedTimedLoop :param control_loop_period: duration in [s] of each timed loop :param memory_loc: location in shared memory to get() data from :param rtf_key: ke...
500e61c0cbb38012bbce18dfc6f648c78a4b3f36
3,620,040
import re def finditer(pattern, string, flags=0): """Finditer after applying backrefs.""" return re.finditer(_apply_search_backrefs(pattern, flags), string, flags)
ee472668784ebcb80d78ccf4b71fba4121691908
3,620,041
def stretched_exponential_series(Lambda = 1.0, Beta = 1.0, n = 1, xmin = 1.0, discrete = False): """ Generator to generate a stream of numbers taken from stretched exponential distribution. **Parameters** Lambda : Float/Integer, Lambda constant for the distribution. Default value is 1...
53ca7792e03e0dac88a257618d637dd115f37bd1
3,620,042
def decode_mint_to(instruction: TransactionInstruction) -> MintToParams: """Decode a mint to token transaction and retrieve the instruction params.""" parsed_data = __parse_and_validate_instruction(instruction, 3, InstructionType.MINT_TO) return MintToParams( program_id=instruction.program_id, ...
4a42f57184066e5e420ec189c72c9868aab68ec0
3,620,043
def daemonize(func): """ A function wrapper that checks daemon flags. This wrapper as it is assumes that the calling class has a daemon attribute. """ def _wrapper(self, *args, d_init=False, **kwargs): if d_init: self.daemon.d_init.append((func, self, args, kwargs)) retur...
3f7b52c319be0a570e8c4843d061e1d0387982af
3,620,044
import torch import sys def train(epoch,trainset,inputs,net,batch_size,trainloader,resize,num_epochs,use_cuda,criterion,logfile): """ This is a javadoc style. @param epoch: the current epoch to be run on top of existing net global variable @param trainset: Dataset for training @param inputs: the n...
f5c09ca48fc0c4b48559052ba5631face47ce0fb
3,620,045
import functools def authenticated_user(method): """Decorate methods with this to require that the user be logged in.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_logi...
f287b3a1f5e364c03dbf41316e9e37577163caf3
3,620,046
import base64 import re def make_string_to_dict(base64_headers: str) -> dict: """分割: """ d = {} s = base64.decodebytes(base64_headers.encode('utf-8')).decode('utf-8') string_list_by_line = s.strip().split('\n') for each in string_list_by_line: each = each.strip() # 去除:开头的 ...
b00eb4b1c69031882b6eacf6d97f67ef4d620f1b
3,620,047
def _find_converter(type_: type, /) -> MaybeNone[ConverterT]: """ !!! note: This is a Future object that will be relevant in future versions of petuhlang. There is no point in using it right now. """ for types in __converters__.keys(): if type_ in types or type_ is types:...
a92aadb9d63c9e947abac018796246ad71ba6061
3,620,048
def proccess_host(host): """ :param host: This should be a dict where host['host'] is an ip address :return: """ host['country_code'] = gi_country.country_code_by_addr(host['host']) host['country_name'] = gi_country.country_name_by_addr(host['host']) host['asn'] = gi_asn.asn_by_addr(host['h...
990d2bf96700ee2f75331ca009ac422126b15809
3,620,049
import os def open_graph(directory, graph_name, wf_filename=WORKFLOW_DEFAULT_FILENAME): """Opens an existing workflow and return the specified graph instance. Args: directory (str): A directory containg a `workflow.py` file, or a file named by the `wf_filename` argument. graph_name...
6467665779bfaf0e9a99c7bb7d3bb35c7bd9f17d
3,620,050
def trajectory_2d( tracks, image=None, labels=None, color=None, xlim=None, ylim=None, cmap=None, cbar=False, cbar_width=30, show_points=False, line_kws=None, scat_kws=None, im_kws=None, dpi=None, scale=1., margin=None ): """ 2d plot of trajectories. ...
7cf737cf96dcb2b60764914ababf6600c22038e0
3,620,051
import os def get_cpachecker_executable(): """Return the path to the CPAchecker executable 'cpa.sh'. If the executable is available in the systeme PATH, this executable is used. Otherwise, it is checked whether an executable 'cpa.sh' is available in the current directory './' or the './scripts' direct...
036eef44a2121ce36c1fd19c075028b0b669d372
3,620,052
def plan_validation(user, plan=None, on_activation=False): """ Validates validator that represents quotas in a given system :param user: :param plan: :return: """ if plan is None: # if plan is not given, the default is to use current plan of the user plan = user.userplan.plan...
94ad3a1b2d49ac519706781a62084928826bb4e6
3,620,053
from re import A from re import M from re import T from re import S from re import I from re import L from re import U from re import X def flairgen(submission): """Convert letters in string to inline flair codes - regular mode. Input string -> converts as list -> output string Iterates through tuples of ...
11eade517eecbda42dffe3db18bedab2052c396e
3,620,054
def vm_modify(vm_uuid): """ Render the details of the VM """ run=libvirt_test() form=ModifyVMForm() _,vm_detail=run.api_get_domain_detail(vm_uuid) if form.validate_on_submit(): #department.name = form.name.data #department.description = form.description.data #db.sessi...
4af36f4132a9defa3bc96dd653a5f32cfb9fa793
3,620,055
def edit_on_keypress_seq_corr(word): """ #### this is the BALL of the @word ### """ word = word.encode('ascii', 'ignore') keypress_w = KB.word_to_keyseq(word) return list(KB.keyseq_insert_edits(keypress_w, allowed_keys, allowed_keys)) # for i, c in enumerate(keypress_w): # f...
b6c46efe4effcb1d8998205d7d31edd86578b17d
3,620,056
from typing import Optional from typing import Set def marker_algorithm(psi: HornFormulaSet) -> Optional[Set[Variable]]: """ Applies Marker Algorithm to given Horn Formula and returns either minimal model (if satisfiable) or None :param psi: Horn Formula represented as HornFormulaSet :return: Minimal ...
e25e060e1c1b9d81931a50a009a36d1055c5640e
3,620,057
import os def convert_to_grayscale(img, file_name, output_gray): """ This function converts the original image in a grayscale image. Then shows and saves the gray scale image. :param img: path to image of interest :param output_path: path for the output image """ # reads the image img in grays...
b286678fc6a84e6fa3a6c72834219ddb7f3862f1
3,620,058
def read_toc(toc_file): """Reads Table of Contents from the given file object 'f'. Each line in file should be in form <'*' x level> <page number> <description> 'level' of the next line should be at most one '*' larger than that of previous line. First line should contain encoding name. Exam...
3e2fc5fa334cf6c91c3a1436ae315561daab5578
3,620,059
def register(): """ Register a user to the application :rtype: flask.wrappers.Response :return: Registration status """ account_json = request.get_json() username = account_json.get('username', None) password = account_json.get('password', None) db = get_db() error = None i...
3dc1fe2f50e8d89dc7c16be67f9b248c3b2dd380
3,620,060
import struct def make_error(error_code): """ Makes and returns Error message.""" temp_payload = struct.pack('<B', error_code) payload = bytearray(temp_payload) message = HibikeMessage(MESSAGE_TYPES["Error"], payload) return message
226a5bb557503eadbe3fb34c4938fda55d5e8fe0
3,620,061
from sage.rings.infinity import Infinity def solve_ineq_fourier(ineq,vars=None): """ Solves sytem of inequalities using Maxima and fourier elimination Can be used for system of linear inequalities and for some types of nonlinear inequalities. For examples see the section EXAMPLES below and http:/...
944f23551c220b3b9fe9f0e139454c6ca36eabcb
3,620,062
def get_cursor(connection): """ Gets a cursor from a given connection. :type MySQLdb.connections.Connection :param connection: A mysql connection :rtype MySQLdb.cursors.SSDictCursor :return A mysql cursor """ return connection.cursor()
dc1e9b99bff6b43eb324161026196358d318f59c
3,620,063
def make_pes_mess_str(spc_dct, rxn_lst, pes_idx, pesgrp_num, unstable_chnls, run_prefix, save_prefix, label_dct, tsk_key_dct, pes_param_dct, thy_dct, pes_model_dct_i, spc_model_dct_i, spc_model): """ Write ...
ca38381481d8d43aafb65dfb71e61d21e436b9ca
3,620,064
def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False, longtable=False, output_dir_path='.', input_dir_path='', latex=False): """ Extracts specimen results from a MagIC 3.0 format specimens.txt file. Default output format is an Excel file. t...
ee55ff511ac4d8b2b26ba5ddf3d14d1d018bd60a
3,620,065
def get_distances_matrix(hotels, workers): """Compute the distance matrix (distance between each hotels). Returns a triangular matrix and the labels of the hotels. Note: 1) That the first address shall be the address of the depot. 2) If the API doesn't returna a match for the address, we dr...
9f7cf3cab62da0b3e36475eb1c5e5ebe5e36cd54
3,620,066
def _get_flim(flim, fscale, freq, sfreq=None): """Get reasonable frequency limits.""" if flim is None: if freq is None: flim = [0.1 if fscale == 'log' else 0., sfreq / 2.] else: if fscale == 'linear': flim = [freq[0]] else: flim...
5424e6b43b20ec95127e5bed941f44bfbede1731
3,620,067
def load(config_raw: t.Dict[str, t.Any]) -> bool: """ This function runs on the main process after the module is imported. It should parse and validate the configuration and do other basic setup of the module. Do not start any threads or long running tasks here, they should go in the ``start`` function....
c8b453f0021bde526df040fec31f68365c2aa121
3,620,068
import collections def get_programs(): """Get the counts of how many users belong to each program.""" users = m.User.objects().only('program_name') programs_names = [user.short_program_name for user in users] program_frequencies = collections.Counter(programs_names) programs = [] for program...
8ab828e3b96b3672d99f0fd5f706d865b0d840cd
3,620,069
def halt(sending=False, removing=False): """ READ for the HALT command, SEND it, or CLEAN the HALT file. IMPORTANT: In order to prevents the system from ignoring your halt commands, please don't forget to include this test in your (heavy) loops! Examples: ...
f86bc23e85da8944e9b66b10be07330703530c72
3,620,070
def _popup_footer(view, details): """ Generate a footer for the package popup that indicates how the package is installed. """ return """ {shipped} <span class="status">Ships with Sublime</span> &nbsp; &nbsp; {installed} <span class="status">In Installed Packages Folder</span> &nbsp;...
8f159f75990e87c8d431bb2dd1d01e648079ac96
3,620,071
def process_chunk( archive: ZipFile, layer_id: str, chunk_name: str, imagesize: list[int], tilesize: int, columns: int, rows: int, difference_x: int, difference_y: int, strict: bool ) -> tuple[Image.Image, tuple[int, int]]: """iterate through chunks, decompress them, create images""" # G...
ffe289d13ddd87bcb744c11cb7ef20c9d5c1de9e
3,620,072
def testForUnevenHandles(glyph): """ Handles should share the workload as evenly as possible. """ unevenHandles = {} for index, contour in enumerate(glyph): prevPoint = contour[-1].onCurve for segment in contour: if segment.type == "curve": # create rays p...
41c44d741305de4e5c7174c7b2f5bac7a70107ad
3,620,073
def get_all_pages_url(ptt_index_url): """accroding get_max_pages, generate each page url index, index0, index1, ... , index == indexMax """ max_page = get_max_pages(ptt_index_url) url_head = ptt_index_url.split('index')[0] all_urls = ["{}index{}.html".format(url_head, i) for i in range(1...
1b94d7f0cfdd9a2ee35e35fd9544136024f819c6
3,620,074
import logging def query_tweets_once(query, limit=None, num_tweets=0): """ Queries twitter for all the tweets you want! It will load all pages it gets from twitter. However, twitter might out of a sudden stop serving new pages, in that case, use the `query_tweets` method. Note that this function ...
834ea5536f53e3659cd3ca5142e3ae3b410b1d35
3,620,075
def trycast(new_type, value, default=None): """ Attempt to cast `value` as `new_type` or `default` if conversion fails """ try: default = new_type(value) finally: return default
d670f545fb1853dfd95da1de961e44ee5a477c5f
3,620,076
import sys import functools import time import codecs def time_function(out=sys.stdout, is_classmethod=False, return_time=False): """ Time run time of a function and write to stdout or a log file. Also has some extra functions in case you want to apply it to a ArticleProcessingMixin. :param out: Outp...
b644d91af7edd0a8c7a8ac9b1bc1da7205f1052c
3,620,077
def unwrap(*args, **kwargs): """Unwraps the tuple into function parameters before calling the function. This is not implemented on the Java side yet. """ return _function_decorator(args, kwargs, { 'parameters' : 'unwrap' })
7b16d71c58ea3922b1b30f7c9f5623dc47696a37
3,620,078
def newSTTEngine(stt_engine, **kwargs): """ Returns a Speech-To-Text engine. Currently, the supported implementations are the default Pocket Sphinx and the Google Speech API Arguments: engine_type -- one of "sphinx" or "google" kwargs -- keyword arguments passed to the constructor ...
078e0c9dbe549b80bf10c706e52161dfb3c6b5e2
3,620,079
from re import I def msigma(i): """Returns a Pauli matrix sigma_i. i=1,2,3 See Also ======== http://en.wikipedia.org/wiki/Pauli_matrices Examples ======== >>> from sympy.physics.matrices import msigma >>> msigma(1) [0, 1] [1, 0] """ if i == 1: mat = ( ( ...
d23aec2d1f60bd82ee19ac40b22e6923c064df31
3,620,080
def _generate_wireless_settings_data(settings): """Generates a wireless settings data array to push to the router from the given wireless settings.""" settings.ensure_valid() data = {'ssid1': settings.ssid, 'channel': settings.channel, 'Save': 'Save'} if settings.is_enabled: data['ap'] = 1...
d41d13f56ecd813d01d2c9223db0b69ad26af5ae
3,620,081
import json def load(tfrecord_file, meta_data_file, model_spec): """Loads data from tfrecord file and metada file.""" dataset = input_pipeline.single_file_dataset( tfrecord_file, model_spec.get_name_to_features()) dataset = dataset.map( model_spec.select_data_from_record, num_parallel_calls=t...
ee25b910f6868dc5def5d9699b7a5cd03f5abb0d
3,620,082
def dummy_house(): """ Sample dataset that will be used to alter and make prediction on """ return { "Id": 34, "MSSubClass": 20, # Identifies the type of dwelling involved in the sale. "LotFrontage": 70.0, # Linear feet of street connected to property "LotArea": 10552, ...
d1360a8709712746f07f92df85a8d704bccd797c
3,620,083
def create_instances(region='us-east-1', count=1): """Create some dummy instances and return the instance ids""" client = boto3.client('ec2', region_name=region) ids = [] create_results = client.run_instances(ImageId='ami-123abc', MinCount=count, MaxCount=count) for created_instance in create_resu...
57a70545e3e6e3d2108c380794cc072f1723d3fe
3,620,084
def get_subsystem_other_info(dut, map_key): """Get the value from subsystem table other_info column.""" subsystem_uuid = dut(ovs_vsctl + "list subsystem | grep -i uuid|cut -d :" " -f 2", shell="bash") uuid = subsystem_uuid.replace('\r\n', '') c = ovs_vsctl + "get subsystem " + u...
30069642b985d92e2a83e83ae04d918db412ca70
3,620,085
def vg(P): """ Specific volume [m^3 / kg] of saturated vapor""" return region4.vg(P)
5febea48babd41eec73c85023c59f7723a8f5d05
3,620,086
def is_gray(img): """Checks if the image is grayscale, i.e., has exactly two channels. Args: img: an image Returns: True/False """ return img.ndim == 2 or (img.ndim == 3 and img.shape[2] == 1)
c9fc884416b12e3fcfb451c6b4c3f16dc1cfb422
3,620,087
def __process_nasa_data(name, file): """Helper function to process NASA data""" if name == 'nasa_carbon_dioxide_levels': ret = __process_nasa_co2_data(file) elif name == 'nasa_sea_level': ret = __process_nasa_sea_level_data(file) elif name == 'nasa_temperature_anomaly': ret = __p...
debb141c59b6d4da541b7e2f8bd9b225f8ef7f2f
3,620,088
from typing import Union def parse_year(x: pd.Series) -> Union[pd.Series, ValueTypeError]: """ Parse strings as years. Per XML Schema, permits negative years and years greater than 9999. However, time zones are not supported (https://www.w3.org/TR/xmlschema-2/#timeZonePermited). Arguments: ...
22544efa086077cc85bd088a82948ab25131c638
3,620,089
def heatmaps_to_coordinates(heatmaps): """ Heatmaps is a numpy array Its size - (batch_size, n_keypoints, img_size, img_size) """ batch_size = heatmaps.shape[0] sums = heatmaps.sum(axis=-1).sum(axis=-1) sums = np.expand_dims(sums, [2, 3]) normalized = heatmaps / sums x_prob = normali...
bae5eddcda8a19310a2cc29cbd57b2e6bc416972
3,620,090
from pathlib import Path def setup(query) -> list: """Setup is successful if an empty list is returned. Use this function if you need the user to provide you data """ results = [] query_str = query.string # abbreviations file if not abbr_store_fname.is_file(): results.append( ...
62e4e33761dd1a288922d8d0d12cd8c4550636c3
3,620,091
def construct_description(prefix: str, suffix: str, items: list): """Construction of complete description with prefix and suffixx. Args: prefix (str): prefix suffix (str): suffix items (list): itesm Returns: str: complete description string """ item_str = ','.join(...
61eec7c2f40bf3b4857cdd682e52aabac1f2ec76
3,620,092
def read_cookies_file(filename): """read cookie txt file :param filename: (str) cookies file path :return: (dict) cookies """ with open(filename, 'r') as fp: cookies = fp.read() return cookies
79ce16fabdec49a7b7b60b4d8bd5346798f03edf
3,620,093
def xlinregress(da_y, da_x, dim=None, ess_on=False, alpha=0.05): """xarray-version linregress (accept xr.DataArray as input)""" if dim is None: dim = [d for d in da_y.dims if d in da_x.dims][0] slope, intercept, r, dof, tvalue, slope_stderr, intercept_stderr, predict_stderr, pvalue, t_alpha = xr.app...
5dfd7002c60db0e4dfca64eceffff55451a21f0b
3,620,094
def outer_prod(mat1: tf.Tensor, mat2: tf.Tensor): """ Parameters ---------- mat1: torch.Tensor[nBatch, mat1_dim1, mat1_dim2, mat1_dim3, ...] mat2: torch.Tensor[nBatch, mat2_dim1, mat2_dim2, mat2_dim3, ...] Returns ------- res : torch.Tensor[nBatch, mat1_dim1, ..., mat2_dim1, ...] ""...
29b3df7c4a770219bfb04c5035af4ee621409f94
3,620,095
import re import gzip def open_or_fd(file, mode='rb'): """ fd = open_or_fd(file) Open file, gzipped file, pipe, or forward the file-descriptor. Eventually seeks in the 'file' argument contains ':offset' suffix. """ offset = None try: # strip 'ark:' prefix from r{x,w}filename (optional), if re.se...
73d09ac1092231484b060f989090c98f06eeb09c
3,620,096
from typing import List def discover(directory: str = '.') -> List[Module]: """ Discover all modules in the given directory recursively and import them. :param directory: the directory in which modules are to be discovered. :return: a ``list`` of all discovered modules. """ paths = _find_paths...
82ef625aca47f3155ac614156de9188e635f8419
3,620,097
def replace_functions_in_pdata(pdata, attributes, function_keys): """ :param pdata: container of which some attributes are sympy expressions (will be altered) :param attributes: relevant attribute-dict, in which the functions have to be replaced :param function_keys: dict like {x1(t): ...
ae2108e2287c7f2a1a77fc18ca2d3e819c60ad1d
3,620,098
def sec(arg): """Secant""" return 1 / np.cos(arg)
8a8a01990ed2a3d39adc3c1fbf98b2a612ad809f
3,620,099