content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def delete_event(id): """Deletes an event :param id: the id of the event :returns: a dictionary with a response of success or failure """ response = db(db.events.id==id).delete() return dict(response=response)
c28183511846ca7c7fe53cee32af1d0d840969b1
46,415
def parametric(Class=None, runtime_type_of=False, metaclass=CovariantMeta): """A decorator for parametric classes. When the constructor of this parametric type is called before the type parameter has been specified, the type parameters are inferred from the arguments of the constructor by calling the f...
03862e507a43a08f8f65d781974fe06341659336
46,416
def add_qartod_ident(qartod_id, qartod_test_name): """ Adds attributes to the QARTOD functions corresponding to database fields. Mostly for internal use :param qartod_id: The QARTOD test identifier, as represented by an integer :param qartod_test_name: The test name as stored in the database. "...
7ad196388861491bc5d8ff554a30dd6476042674
46,417
from typing import Optional async def get_balance( user_id: int, db_con: Connection, convert_to: Optional[str] = None, ) -> Decimal: """Get user account balance. Args: user_id: user id db_con: database connection convert_to: currency for convertation Returns: ...
9fd8de687b96bd5e5e90f60e386e7972ea269264
46,418
def output_factory(writer_format: str = "pqr") -> Writer: """Provides the writer based on the output format. :param writer_format: Format indicating with writer to use :type writer_format: str :return: Writer object for a given output factory :rtype: Writer """ writer_type = writer_forma...
03023f9bb0d2ef9e98368fd9e75fbbbb5316ef76
46,419
def handlerInit(service,node): """pyvel initialization.. This is where we load our modules and setup the state objects""" if not service.state.has_key("groups"): service.state["groups"]={'/':{}} if not service.state.has_key("games"): service.state["games"]={} rdict={} for n in no...
fb54232b205e04239c4a5f2dda1bdb21bcce5eec
46,420
def unflatten_wave(y, shape): """ Unflatten a flattened array. Parameters ---------- y: ndarray 1D a flattened input array. shape: list of dict the output structure information. Returns ------- x: list of ndarray the unflattened dataset. """ # Unflatten ...
48618aaf5b1df7bd154d7f892158393e2ff34e0b
46,421
import typing def load_all_dicts(gs_files: list = None, GLMDIR: str = None, norm: typing.Union[str, bool] = 'bySessVoxZ', roi: str = 'lang_LH_netw'): """Return df of rows = sentence, cols = gs single response for ROI of interest""" # Load, extract the ROI of interest lst_responses = [] lst_...
bbd2433a43cc3618c5f3a1f5d42a74602c4245bb
46,422
import scipy def compute_range_table( stepsize = 0.001, maxextent = 10 ): """Compute integrals of the unit normal distribution and return these tabulated. Returns: - range: NumPy array giving integration range (x) where integration range runs -x to +x - integral: NumPy arrange giving integrals over specified int...
45e91d790393c2b03b7c1e98b5964daf0e4c24c5
46,423
def phred(q): """Convert 0...1 to 0...30 No ":". No "@". No "+". """ n = int(q * 30 + 33) if n == 43: n += 1 if n == 58: n += 1 return chr(n)
29a61010b1813afc6d32e640bb6865a9e18ac3a0
46,424
def lemmatize(word): """ Out of all the related word forms of ``word``, return the smallest form that appears first in the dictionary """ forms = [word for pos_form in get_word_forms(word).values() for word in pos_form] forms.sort() forms.sort(key=len) try: return forms[0] except...
078c90537697c3863542ef6a483561866cdd3a9b
46,425
def write_k(version, internal, boundaries, location=None, file=None): """ Write a turbulent kinetic energy (TKE) field file. See :func:`~dafi.random_field.foam_utilities.write` for more information. """ return write(version, 'k', internal, boundaries, location, file)
fd95a2f27529370a1a451f120ba5e75f8f9fa15b
46,426
def HLRBRep_BCurveTool_IsRational(*args): """ :param C: :type C: BRepAdaptor_Curve & :rtype: bool """ return _HLRBRep.HLRBRep_BCurveTool_IsRational(*args)
8065ef84e294c0b61ffd9a7a66df19829fb15d23
46,427
def has_footer_comments(content): """Determine if the FOOTER_COMMENTS are already present. """ for comment in FOOTER_COMMENTS: if content.find(comment) == -1: return False return True
1a355ee32f8bc21b3c286e1150532057ca6bde9e
46,428
def get_directory_content_ajax(request, region_slug=None): """ View provides the frontend with the content of a directory via AJAX. :param request: The current request :type request: ~django.http.HttpRequest :param region_slug: The slug of the current region :type region_slug: str :return...
97c3c512d0f60cfb134e2b9161229505ebc4bf8c
46,429
from typing import Optional def int(val: 'Optional[b_int]' = None) -> PythonValue: """Returns an Int wrapped into a PythonValue""" return PythonValue(Int(val))
df8c31966b6d39897440d91ae7281ae7d1fa30cd
46,430
import csv def compare_files_pr(file1, file2): """ Calculate simple P/R . Compare lists of cells, left to right , top to bottom. """ cells = [[], []] for i, fname in enumerate([file1, file2]): with file(fname) as csvfile: rd = csv.reader(csvfile, delimiter=',', quotechar='"...
d727fdbb25a60d75616aff41cb408a5395c46b4b
46,431
def read(filename, flags=0): """Read an image to a numpy array of shape (height, width) for greyscale images, or shape (height, width, nchannels) for RGB or RGBA images. The `flags` parameter should be one or more values from the IoFlags class defined in this module, or-ed together with | as appropr...
30e662ce6d2a38d114cfc9898f970fbb7a708910
46,432
def _call_with_frames_removed(func, *args, **kwds): """ remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceba...
a4b3d05879c29efc51e07aec9d9fba02254d4504
46,433
import random def generate_pose(): """ generate pose from hemisphere-distributed viewpoints """ # y axis(yr): -pi - pi # x axis(xr): 0 - 0.5pi # view_direction(ar): -0.1pi - 0.1pi yr = (random.random()*2.0*np.pi)-np.pi xr = (random.random()*0.5*np.pi) ar = (random.random()*0.2*np...
c9909e0b4f944410b939a56038a85e089ae02adf
46,434
def _flop_count(idx_contraction, inner, num_terms, size_dictionary): """Copied from _flop_count in numpy/core/einsumfunc.py Computes the number of FLOPS in the contraction. Parameters ---------- idx_contraction : iterable The indices involved in the contraction inner : bool Doe...
a7fb1d68d36770a69400932fc4f1a3a2461afaf6
46,435
import pandas def process_track_data(dataframe_name, concatenated_filepath, concatenated_filename, input_filepath, input_filename, device_id, output_create_files_filepath, output_create_files_filename, invalid_position_filepath, output_flagging_filepath, output_flagging_filename): """Proces...
0ea89083e95a315e8dc47025be1b4beadef28da9
46,436
def margin_mortality(t): """Mortality margin Mortality margin is defined :func:`coi` net of :func:`claims_over_av`. The sum of the expense margin and mortality margin add up to the net cashflow. .. seealso:: * :func:`coi` * :func:`claims_over_av` """ return coi(t) - clai...
72a0b4b795076bd865479bbce7f8f02843460f47
46,437
from typing import Optional def getPrintLengthError(printHours: float) -> Optional[str]: """Returns a warning message if the print is too long. :param printHours: Total hours the print will take. :return: The message to display if the print is too long. """ currentLimit, limitEnds = getCurrentTi...
5a03f3f18790558258e9804b4a8354df827e772b
46,438
def insert_combos(lst, vertical_sudoku, blockified_sudoku, row_index): """ Tries all combinations of missing elements and inserts to a list and returns it args: -lst - list containing missing elements -vertical_sudoku - List containing lists of columns of the sudoku (Will be ...
a2fbe9c003c9611727096500bb8079f68d1aa34a
46,439
import optparse def options_from(**kwargs): """Generate a Values instances with our kwargs.""" kwargs.setdefault('hang_closing', True) kwargs.setdefault('max_line_length', 79) kwargs.setdefault('verbose', False) kwargs.setdefault('stdin_display_name', 'stdin') return optparse.Values(kwargs)
1a82c3a2d76ae3aba8cec81ccb01fd976b2ab4c4
46,440
def connect(server, username, password): """ Connect to Seafile server :param server: address of the seafile server :param username: username :param password: password :return: :class:`SeafileApiClient`. """ seafile_client = SeafileApiClient(server, username, password) return seafile...
a5f3f0d1d68a34cd8d659f802538c647c9f2296b
46,441
def lsolve(A, b): """Gaussian elimination with partial pivoting. This is implemented here to avoid a dependency on numpy. This could be replaced by :code:`(x, _, _, _) = lstsq(A, b)`, but we prefer the pure Python implementation here. """ N = len(b) for p in range(N): # f...
751300dcca2bdad7c0b8c8618d95ad97092d16a8
46,442
def show_user(): """ function to show existing users :return: existing users """ return User.display_all_users()
ee2912a1202dee17ed91f668e2f59e236fc47800
46,443
from functools import reduce def sum(l): """ Returns the sum of the items in the container class. This is more general than the build-in 'sum' function, because it is not specific for numbers. This function uses the '+' operator repeatedly on the items in the contrainer class. For ...
c64bc8aec1af669af69494aa37fd515d3d7efad5
46,444
def main(args): """Process Glicko2 ratings.""" scrape = args.scrape tournaments = args.tournaments output_format = args.output_format game = args.game top_amount = int(args.top_amount) sort = args.sort if scrape: scrape_all_tournaments() if tournaments: tournaments ...
251fb57cbfbbccd93d4d717b1f350ff80a5bf14f
46,445
from operator import ne def extract_z_dec(model, sample_layer_name, vis=False, wt_chk=False): """ extract the z_decoder [z = p(x)] and return it as a keras model Example Layer name: sample_layer_name = 'img-img-dense-vae_ae_dense_sample' """ # need to make new model to avoid mu, sigma output...
d9fa1f16c68ea41d0c8ae8ef2d202c431a4d7a68
46,446
import webbrowser def acquire_new_oauth2_credentials(secrets_file): """ Args: secrets_file. The file path to a JSON file of client secrets, containing: client_id; client_secret; redirect_uris; auth_uri; token_uri. Returns: credentials for use with Google APIs """ flow =...
3515eca1fb1795ed8db876a25b0820dd8056f7fc
46,447
def checkValues_coordinate0(coordinate0, reference_point): """Function that check the range of the input coordinates to be rigth""" # AP if 90 > coordinate0[0] > -90: pass # Entry in correct range else: raise Exception( "Coordinate AP ({}) out of range for lambda, should be...
d55cbce8cff1fa47b4c958cfcad41c0d0c9a338f
46,449
from typing import List from typing import cast def correct_task_suggestions_in_loop_body(pet: PETGraphX, suggestions: List[PatternInfo]) -> List[PatternInfo]: """Separate treatment of task suggestions at loop increment CUs. If regular loop: move taskwait suggested at loop increment line to end of loop body. ...
0d4349d2afa799919670845cb1ca8c8adf63454a
46,450
def compare(isamAppliance1, isamAppliance2): """ Compare user name mapping """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) for obj in ret_obj1['data']: ret_obj = get(isamAppliance1, obj['id'])['data'] del obj['version'] obj['contents'] = ret_ob...
431b099339fe8bdcacc77d9c71bcb6edb41c2d5a
46,452
import re def get_keyword(title): """ :param title: policy title (str) :return: keyword (str) """ matchObj = re.match('(.*)关于(.*)的(.*)', title) if matchObj: title = matchObj.group(2) matchObj2 = re.match(r'(.*)“(.*)”(.*)', title) if matchObj2: title = matchObj2.group(2...
da9a5f5ff9fbc0d9c77057301bb16b578476b9a7
46,453
def Rotation_calcNForBodyXYZInBodyFrame(*args): """ calcNForBodyXYZInBodyFrame(Vec3 q) -> Mat33 Parameters ---------- q: SimTK::Vec3 const & Rotation_calcNForBodyXYZInBodyFrame(Vec3 cq, Vec3 sq) -> Mat33 Parameters ---------- cq: SimTK::Vec3 const & sq: SimTK::Vec3 const & ...
aa5886cd5036b1c8f0452524375ab1466dc68a5a
46,454
import re def get_version(versionfile): """Extract the __version__ from a given Python module.""" match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(versionfile).read(), re.M) if match: return match.group(1) else: raise RuntimeError("Unable to find version string in {file}."...
f319b575d74e3ecea3895785e1101f72913488ec
46,455
import random def create_push_down(target_path, arena_name, time=1000, is_train=True): """ The reward is on top of a box. agent must push box in the right position to be able to acces the reward platform.""" coin = random.choice([0,1]) if coin == 1: box_pos = (random.randint(25, 140) / 10., 1.,...
46e1c1a19ee2285d8aa13735b165275513e9e51b
46,456
import logging def read_ap_custom_resource(custom_objects: CustomObjectsApi, namespace, plural, name) -> object: """ Get AppProtect CRD information (kubectl describe output) :param custom_objects: CustomObjectsApi :param namespace: The custom resource's namespace :param plural: the custom resourc...
e23b6c657aae46f2242b153becf25f91871564b3
46,457
from typing import List def _filter_messages(msgs: List[Message]) -> List[Message]: """Filter messages removing those that start with INTENT_MESSAGE_PREFIX""" filtered_messages = [] for msg in msgs: if not msg.text.startswith(INTENT_MESSAGE_PREFIX): filtered_messages.append(msg) r...
99ea45a231cdf710ede1df5431776a6bad4fef6a
46,460
import socket def hostname_resolves(hostname): """Checks to see if hostname is DNS resolvable""" try: socket.gethostbyname(hostname) return 1 except socket.error: return 0
7339b03da62863d109c543e85f04eace1261a31e
46,461
def descale_fields(clip: vs.VideoNode, tff: bool = True, width: int | None = None, height: int = 720, kernel: Kernel = Catrom(), src_top: float = 0.0) -> vs.VideoNode: """ Simple descaling wrapper for interwoven upscaled fields. This function also sets a frameprop with ...
20da2724ed701a2c14cb87d96d4636e6f30ed6b1
46,462
import math def _gain2db(gain): """ Convert linear gain in range [0.0, 1.0] to 100ths of dB. Power gain = P1/P2 dB = 10 log(P1/P2) dB * 100 = 1000 * log(power gain) """ if gain <= 0: return -10000 return max(-10000, min(int(1000 * math.log10(min(gain, 1))), 0))
1bd602e0db397b3730c4f2b3439aeb351e6bd854
46,463
def build_aggregation_layer(aggregation_input_layer, model_config, calibrated_lattice_models, layer_output_range, submodel_index, dtype): """Creates an aggregation layer using the given calibrated lattice models. Args: aggregation_input_layer: A list or a...
dd355b75d13b91d9cfd426a53edc7a45761e76f8
46,464
import random def generate_int(data_format): """ Generate an integer based on the given data width and sign. """ is_signed = data_format['is_signed'] width = data_format['width'] if is_signed: result = random.randrange(-2 ** (width - 1) + 1, 2 ** (width - 1) - 1) else: res...
644d8e71b949ff01290d357732509d1f0a62db08
46,465
def load(filep): """ Read an V_sim .ascii file and returns a pychemia Structure object Args: filep: (string) Path to a .ascii file or an actual file-like object Returns: struct: (object) A pychemia Structure object """ if isinstance(filep, str): f = open...
4c9127b7ba8f5b6aa553615152ba441d92898397
46,466
def mock_run_applescript(script): """Don't actually run any applescript in the unit tests, ya dingbat. This function should return whatever type of object dialogs._run_applescript returns. Returns: tuple """ return (1, "", "")
fdcb8e1e0e283963cec55c8fa1d98e745bd5e784
46,467
import numpy as np import pdb import astropy.constants as const import numpy as np import lib.test as test def blur_spec(wl,spec,dv,truncsize = 20.0): """This function takes a spectrum, and blurs it using either a Gaussian kernel or a box kernel, which have a FWHM width of dv km/s everywhere. Meaning that...
6e3530ab7db573ae0c488d285407db0216166be2
46,468
import torch def channel_last_to_first(img: torch.Tensor) -> torch.Tensor: """ Converts an image of shape batch_size, height, width, channels into an image of shape batch_size, channels, height, width. Parameters ---------- img: Image with shape batch_size, height, width, channels. Retur...
b5e948e7eb6ba2ac211e8f5d89601f194d391c32
46,469
def _projector_on_tvl1_dual(grad, l1_ratio): """Function to compute TV-l1 duality gap. Modifies IN PLACE the gradient + id to project it on the l21 unit ball in the gradient direction and the L1 ball in the identity direction. """ # The l21 ball for the gradient direction if l1_ratio < 1.:...
28bb9f8c6cc9c65cb370442c878ef8e0d81ebd05
46,470
def get_id(psco): """ Retrieve the persistent object identifier. :param psco: Persistent object :return: <String> Id """ return psco.getID()
84fdf24633adb301411d8c4ad2d6344cd09a63b7
46,471
def rotate_image(img, angle): """ Rotate image by given angle. Adapted from https://stackoverflow.com/a/23316542. """ row, col, _ = img.shape center = tuple(np.array([row, col]) / 2) rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0) new_img = cv2.warpAffine(img, rot_mat, (col, row)) ...
f492ad345b0f61a463fa29cdd07e821156657816
46,472
import re def _defaults_to_code(val): """ Make sure that any defaults that are surrounded by << >> are in code quotes so that they render properly. e.g.: <<display_name>> converts to '<<display_name>>' """ return re.sub(r"(<{2}.*>{2})", r"`\1`", val)
f98aa716fab13143a29659ff746336913d9d4ee7
46,473
def do_label_encoding( source_train_df, source_test_df, target_train_df, target_test_df, categorical_features, feature_name_suffix=None, ): """ Label encode the categorical features. After encdoing, it appends a new set of features with name <original_feature_name>_label to the t...
8ed75c13d8c31e5d5b297631d8e69483d0370403
46,474
from ..tibble import tibble def sprintf(fmt, *args): """C-style String Formatting Args: fmt: The formats *args: The values Returns: A scalar string if all fmt, *args are scalar strings, otherwise an array of formatted strings """ if is_scalar(fmt) and all(is_scala...
92b381ac13fd6bf8089ff820bbc332c384bb114c
46,475
def morphological_process(image, kernel_size=5, func_type=cv2.MORPH_CLOSE): """ morphological process to fill the hole in the binary segmentation result :param image: :param kernel_size: :return: """ if len(image.shape) == 3: raise ValueError('Binary segmentation result image should ...
dad5f0205c4728feb0472869210beed7bf39aad0
46,476
def warm_restart(scheduler, T_mult=2): """warm restart policy Parameters: ---------- T_mult: int default is 2, Stochastic Gradient Descent with Warm Restarts(SGDR): https://arxiv.org/abs/1608.03983. Examples: -------- >>> # some other operations(note the order of operations) >>...
2c7fabac807fb9237775a406e8ba9fb0cf6feb76
46,477
def main() -> None: """Start the bot""" bot_token = get_bot_token() load_stats() # Get the updater updater = Updater(bot_token, use_context=True) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Command Handlers dispatcher.add_handler(CommandHandler("star...
2da7fe1718e643b0ea03e630ee55b5863f91ff9b
46,478
def checkNull(df): """ checkNull is a simple function that returns the sum of the number of nulls you have in each column of your dataframe. """ assert isinstance(df, pd.DataFrame), "Please submit a dataframe when using this function." return df.isnull().sum()
3bdb380bf4a1710331182796886ad5d14c447fb3
46,479
def send_action(action=ChatAction.TYPING): """Sends `action` while processing func command.""" def decorator(func): @wraps(func) def command_func(update, context, *args, **kwargs): context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action) retur...
9ceb66c62aee9eb61fe780cdd6e41bfb4f69c799
46,480
def split_dates(dataframe, date_column): """Converts date features into pandas datetime objects. Args: dataframe (pandas dataframe) date_column (dataframe column) """ copy_of_df = dataframe.copy() copy_of_df["Year"] = pd.DatetimeIndex(copy_of_df[date_column]).year copy_of_df["M...
59a5dda3c921a12e20ab981559df97b48fcc91b2
46,481
def total_schedule(schedule): """Return the total number of 15 minute windows in which the schedule is set to replicate in a week. If the schedule is None it is assumed that the replication will happen in every 15 minute window. This is essentially a bit population count. """ if schedule i...
9c0231a0f6e2e4617b5c958ea337420f73811309
46,482
def diff_mark(m, t): """ Subtract from a marking the postset of t and adds the preset Parameters ------------ m Marking t Transition Returns ------------ diff_mark Difference marking """ for a in t.out_arcs: p = a.target w = a.weight ...
164480506364779ea562e7e276e2b6ebe3a2f1c6
46,483
def vatm(model, x, logits, eps, num_iterations=1, xi=1e-6, clip_min=None, clip_max=None, scope=None): """ Tensorflow implementation of the perturbation method used for virtual adversarial training: https://arxiv.org/abs/1507.00677 :param model: the model which returns the network unnormalized l...
89faf3f5c4a88ccc77e1b1185ad6c1ea5e5dfafe
46,484
def get_session(): """ 获取数据库回话对象 如果当前存在事务,则使用最后一个事务的回话对象 否则,新建一个 """ if hasattr(threadLocal, "sessions") and len(threadLocal.sessions) > 0: return threadLocal.sessions[-1].session return _create_session(True)
641089b48694503b2fae09f5e907e7873b5fd627
46,486
def recherche_motif_naive(texte, motif): """Retourne la position où le motif a été trouvé par fenetre glissante ou -1 si le motif ne se trouve pas dans le texte Si n = len(texte) et m = len(motif), la complexité est en O((n-m)*m)""" for i in range(len(texte) - len(motif) + 1): if correspondance_...
89fee413026893dc1f10faa05f159325e34e077e
46,487
def remap_instruction_position(position, mtext_src, mtext_dst): """ Remap an instruction position from one mtext to a *similar* position in another. """ line_num, x, y = position line = mtext_src.lines[line_num] # the block in the source mtext where the given position resides blk_token_src ...
4699c63ef88dea8cc8fc487cfe39338f5aa52101
46,488
import json def load_hparams(hparams_file, out_dir): """Load hparams from an json file. Partial hparams are augmented using default values for parameters that were added after the hparams file was written. Args: hparams_file: Filename of the hparams file. out_dir: Directory where the model output wi...
74fa3d0345ff604e09f2baa7c7556ecfd5660b24
46,489
import json import urllib def get_access_token(tenant_id, resource): """ Retrieve an OAuth token by sending an OAuth2 token exchange request to the local URL that the ManagedIdentity extension is listening to """ # Extract the endpoint that the ManagedIdentity extension is listening on wit...
ee871be3000fbb01cfb352578c43a60e31623b68
46,490
from typing import Callable def f_docstring(docstring: str) -> Callable: """Bypass for f formatted docstrings.""" def decorator_doc(func: Callable) -> Callable: @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.__doc__ = docstring ret...
a2d99980d071cf7f5c37a1ac4fdc9cc0f996d50e
46,491
def permutation_cluster_1samp_test( X, threshold=None, n_permutations=1024, tail=0, stat_fun=None, connectivity=None, verbose=None, n_jobs=1, seed=None, max_step=1, exclude=None, step_down_p=0, t_power=1, out_type='mask', check_disjoint=False, buffer_size=1000): """Non-parametric clu...
77f3c73e2da2baec108e41c5ecbbf6dc0f76444e
46,492
def getOrigShape(transform): """ Creates the Orig Shape used by deformers. Args: transform (pm.nodetypes.Transform): Transform to create orig shape of. Returns: (pm.nodetypes.Mesh): Shape created. """ shape = pm.deformableShape(transform, og=True) shape = list(filter(None, ...
24a5bf6257fc6081d5d3e1f444c9e29c643b9bc0
46,493
def get_input(): """ Ask user for inputs about event: Title, Main Topic, Distance to Location. Checks for correct types and value ranges. If not correct, restarts asking 5 times. :return: Tuple(Str, Int, Int) => "Title", [0|1], [0,infinity[ OR None (to quit App) """ attempt = 0 title, topic,...
4c5ef7eea691a5080b61686173faf2530f4586c3
46,494
import datasets def get_dataset(args): """ Returns train and test datasets and a user group which is a dict where the keys are the user index and the values are the corresponding data for each of those users. """ if args.dataset == 'cifar': data_dir = '../data/cifar/' apply_transf...
1e1edd193e41135b7eda38417073f14c2b96a784
46,495
from typing import Optional from typing import Any def get_roulette(archive: utils.Archive[utils.Value], num: Optional[int] = None) -> Any: """Apply a roulette tournament selection. """ if num is None: num = int(.999 + np.sqrt(len(archive))) # the following sort makes the line deterministic, a...
03829327d087270083730b1acb48823b39c083a3
46,496
def process_puzzle_input(ext=".txt"): """ Process puzzle input """ puzzle_data = [] with open("puzzle_data_" + DAY + "_" + YEAR + ext) as f: for line in f: puzzle_data.append([x for x in line.strip()]) return puzzle_data
cb937199a99c7667ac078e332e9330432df7bdb8
46,497
def minimum_bounding_rectangle(points): """ Find the smallest bounding rectangle for a set of points. Returns a set of points representing the corners of the bounding box. :param points: an nx2 matrix of coordinates :rval: an nx2 matrix of coordinates """ pi2 = np.pi/2. # get the conve...
3cc5b2e59aa54ebf5f78668a029d18c55df97b47
46,499
def get_mentornet_network_hyperparameter(checkpoint_path): """Get MentorNet network configuration from the checkpoint file. Args: checkpoint_path: the file path to restore MentorNet. Returns: a named tuple MentorNetNetHParams. """ if checkpoint_path and tf.gfile.IsDirectory(checkpoint_path): che...
3f7c8f056cec574e11027178b82652e5daa25989
46,500
def densenet(images, num_classes=1001, is_training=False, dropout_keep_prob=0.8, scope='densenet'): """Creates a variant of the densenet model. images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. is_training: specifies whether or not ...
7b444de908bb13c0403082895451f87211c2793a
46,501
from typing import List from functools import reduce def product(li: List[int]) -> int: """Calculates the product of all the numbers in a list. doctests: >>> product([2, 1, 4]) 8 >>> product([3, 1, 4, 2, 5, 8]) 960 """ x = reduce(lambda a, b: a * b, li) return x
8afe00bb6056accc694ab955a48b6be85d8a30bf
46,502
def CDLDOJI(data: xr.DataArray) -> xr.DataArray: """ Doji (Pattern Recognition) Inputs: data:['open', 'high', 'low', 'close'] Outputs: double series (values are -1, 0 or 1) """ return multiple_series_call(talib.CDLDOJI, data, ds.TIME, ds.FIELD, [f.OPEN, f.HIGH, f.LOW, f.CLOSE], ...
73130fe5309c279b79e12738acee0433a4f78aee
46,503
def filename(N, epsilon, v0, D, Dr, phi, launch): """ Name of simulation output files. Parameters ---------- N : int Number of particles in the system. epsilon : float Coefficient parameter of potential. v0 : float Self-propulsion velocity. D : float Tran...
7fb6c9cfc081caaacc447c4e1869030ef2b00ff3
46,504
def g2c(coordinate:tuple, pixel_unit:int) -> tuple: """ Convert pygame coordinate to cartesian coordinate. x pixel unit refers to 1 unit in cartesian coordinate system. For example: if pixel unit is 100 then 100 pixel is one unit in cartesian system coordinate: game coordinate (x,...
16c93158145edf1454c31aaede426f99639f34a7
46,505
async def site_base(): """Return the configured site prefix. Useful for correct client-side routing.""" return conf().metador.site
729c72428baf914a91e5970f3d7c931283690986
46,506
from typing import Dict from typing import List def filter_labels( label_dict: Dict[str, np.ndarray], filter_dict: Dict[str, List[int]] ) -> Dict[str, np.ndarray]: """Filter out examples from arrays based on specified labels to filter. The most common use of this method is to remove examples whose gold l...
f5d0402bee3947d4c248320842750ec3613c5b30
46,507
from typing import Sequence from typing import Dict from typing import Any def get_view_report_fields_list(report: str) -> Sequence[Dict[str, Any]]: """Gets the fields in the report month view :param report: the kind of the report :returns: list of fields in this report's month view""" report_fields ...
af6d96acaec6d7b7d44f402b8edd09f354bdfa91
46,508
def parse_options() -> Namespace: """ Parse command line arguments and liftoff configuration. """ opt_parser = OptionParser( "liftoff-status", ["experiment", "all", "timestamp_fmt", "results_path"] ) return opt_parser.parse_args()
cff274096dd9a74bce62867f2519e93b11c4521b
46,509
def generate_betas_inertia(time_periods: int) -> np.ndarray: """ Generate an array of beta_inertia values for t time periods """ betas = np.empty(time_periods) taste_shocks = np.random.normal(loc=0, scale=src.const.taste_shock_std, size=time_periods) b0 = np.clip(np.random.normal(loc=src.const....
1bbc2a9f29206f7086874e9bb0992a8ee3ce7927
46,510
def create_graph_hac(env, n_layers, n_steps, subtask_specs, level_algo_kwargs_list): """Create and return HAC graph.""" # If buffer size not specified, set it such that all transitions will fit into buffer # (assuming that the episodes always last for env.max_episode_length which is not the # case in ...
c0b8ac527bc03d2b30c1eb0709985c2365528a78
46,511
def add_cartesian_dummy(odf: dc_dd) -> dc_dd: """create a dummy dataframe with a column "cartesian" with the value 0 to force a cartesian join using merge. Args: odf (dc_dd): original dask_cudf or dd Returns: dc_dd: dummy dask_cudf or dd """ odf["cartesian"] = 0 odf = du.sh...
406d58869b2a49b7cbcb6528b9746b2320e8a8e0
46,512
def get_etl_pipeline_ids(client): """Return a dict mapping pipeline ids to their names, filtering on ETL pipelines.""" paginator = client.get_paginator("list_pipelines") response_iterator = paginator.paginate() filtered_iterator = response_iterator.search("pipelineIdList[?contains(@.name, 'ETL') == `tru...
10dcd1d933ed8adabd75740a55d567cf786fffbb
46,514
from typing import Optional from typing import Dict def GCBucket(bucket: str, prefix: Optional[str] = None, identifier: Optional[str] = None) -> Dict: """Get configuration object for Google Cloud storage volume. Parameters ---------- bucket: string Google Cloud Storage bucket identifier. ...
e93f2bab567a32a15b76278b18da3a7f001263cc
46,515
import tqdm def segment_threshold(eventfile,segment_length,demod,tbin_size,threshold,PI1,PI2,t1,t2): """ Using the .dat files, rebin them into 1s bins, to weed out the segments below some desired threshold. Will return a *list* of *indices*! This is so that I can filter out the *sorted* array of .dat ...
d9bbf34b6230df4257ed5a99d46292603d7f54f8
46,516
import tokenize def build_model(): """ Making a pipeline and using grid-search to optimize it. Input: None Output: Returns a model """ pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestClassifier())) ]) para...
4e27d35ce612a5bdea6ff2175db956d121777362
46,517
import json def load_remote_settings_cache(): """Load cached remote skill settings. Returns: (dict) Loaded remote settings cache or None of none exists. """ remote_settings = {} if REMOTE_CACHE.exists(): try: with open(str(REMOTE_CACHE)) as cache: remot...
f2a58a5185a8b9d670489d6ad9eaa21abcb2e5d9
46,518
def get_blogroll(parser, token): """ {% get_blogroll %} """ return BlogRoll()
9ebd58021e048f1d9d4610daadba4f98d427b76f
46,519
def otsu(data, num=400): """ Generate threshold value based on Otsu. :param data: cluster data :param num: intensity number :return: selected threshold """ max_value = np.max(data) min_value = np.min(data) total_num = data.shape[1] best_threshold = min_value best_in...
1d3c264ff059b4205dc8bbe02e45b1f267ba52d4
46,520
import zipfile def read_data(filename): """Extract the first file enclosed in a zip file as a list of words.""" with zipfile.ZipFile(filename) as f: data = tf.compat.as_str(f.read(f.namelist()[0])).split() return data
e1b06f067cb22b71483033d32dddf454ce1c22ab
46,523