text
string
size
int64
token_count
int64
# Update the working patch and champions list from __future__ import print_function import configparser import json import os import urllib.request from datetime import datetime from slugify import slugify from collections import OrderedDict from InterfaceAPI import InterfaceAPI def run(): config = configparser...
6,110
1,975
# Generated by Django 3.0.7 on 2020-07-09 22:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0009_auto_20200709_1430'), ] operations = [ migrations.AlterField( model_name='location', name='lat', ...
555
187
import unittest import csv import numpy as np from viroconcom.fitting import Fit def read_benchmark_dataset(path='tests/testfiles/1year_dataset_A.txt'): """ Reads a datasets provided for the environmental contour benchmark. Parameters ---------- path : string Path to dataset including the...
28,078
8,698
# Zed Attack Proxy (ZAP) and its related class files. # # ZAP is an HTTP/HTTPS proxy for assessing web application security. # # Copyright 2012 ZAP Development Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a c...
22,100
9,016
def LeiaInt(msg1): pronto = False while True: valor1 = input(msg1) if valor1.isnumeric(): pronto = True else: print('\033[1;31mERRO! FAVOR DIGITAR UM NÚMERO INTEIRO VÁLIDO\033[m') if pronto: break return valor1 def linha(tamanho=42): ...
665
290
# coding: utf-8 """ PocketSmith The public PocketSmith API # noqa: E501 The version of the OpenAPI document: 2.0 Contact: api@pocketsmith.com Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from pocketsmith.configuration import Configuration ...
10,439
3,203
""" high-level NSQ reader class built on top of a Tornado IOLoop supporting both sync and async modes of operation. supports various hooks to modify behavior when heartbeats are received, temporarily disable the reader, and pre-process/validate messages. when supplied a list of nsqlookupd addresses, a reader instance...
16,476
4,672
#!/usr/bin/env python3 # -*- coding:utf-8 -*- u""" Created at 2020.09.04 by Zhang Yiming """ import warnings warnings.filterwarnings("ignore") import click from cli.climb import climb from cli.diff import diff @click.group() def main(): pass main.add_command(climb) main.add_command(diff) if __name__ == '__mai...
337
135
import os from data.raw_data_loader.base.base_raw_data_loader import Seq2SeqRawDataLoader class RawDataLoader(Seq2SeqRawDataLoader): def __init__(self, data_path): super().__init__(data_path) self.cnn_path = "cnn/stories" self.dailymail_path = "dailymail/stories" def load_data(self)...
2,023
604
#!/usr/bin/env python # Copyright 2014 Open Connectome Project (http://openconnecto.me) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #...
4,098
1,358
import pytest import server @pytest.fixture(scope="session") def authorship_grammar(): with open("test_grammars/Authorship.gf", "r") as f: abstract = {"content": f.read()} with open("test_grammars/AuthorshipEng.gf", "r") as f: inst = {"content": f.read(), "key": "Eng"} return serv...
1,384
457
# Copyright (c) 2012-2022, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .. import AWSHelperFn, If def attribute_type_validator(x): """ Property: AttributeDefinition.AttributeType """ valid_types = ["S", "N", "B"] if x not in valid_types: ra...
3,126
989
import time from misty2py.robot import Misty from misty2py.utils.env_loader import EnvLoader from misty2py_skills.utils.utils import get_abs_path env_loader = EnvLoader(get_abs_path(".env")) m = Misty(env_loader.get_ip()) d = m.event("subscribe", type="BatteryCharge") e_name = d.get("event_name") time.sleep(1) d...
430
169
#Map incorrect and abbreviated street names with correct/better ones import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint OSMFILE = "albany.osm" street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) # UPDATE THIS VARIABLE mapping = {"rd": "Road", "Rd": "Road", ...
2,302
771
from io import TextIOWrapper import os from typing import List OUTPUT = "files/output.csv" FOLDER = "modules/week2/folders" def get_file_names(folderpath, out=OUTPUT): """takes a path to a folder and writes all filenames in the folder to a specified output file""" dir_list = os.listdir(folderpath) with o...
1,943
610
import json from sanic import response from sanic_openapi import doc from src.plugins.authorization import authorized from src.plugins.validator import validated from src.request_models.providers import Provider from src.request_models.query_model import Query from src.resources.generic import ensure_membership_is_ex...
4,480
1,356
# -*- coding: utf-8 -*- #Lista de Exercícios 08 (Pesquisa) - Questão 02 #Mayara Rysia from time import time from time import sleep from random import randint """ 2. Use as duas funções de busca binária apresentadas (iterativa e recursiva). Gere uma lista de números aleatórios, ordene-os e verifique o desempenho delas....
3,078
1,195
import codecs import markdown import os import logging from pyramid.view import view_config from pyramid.httpexceptions import HTTPOk, HTTPNotFound from sqlalchemy import func from mako.lookup import TemplateLookup import mako.exceptions logger = logging.getLogger(__name__) from ccvpn.models import DBSession, User, Ic...
3,290
1,073
import threading from typing import Any, List, Optional from rx.disposable import Disposable from rx.core.typing import Observer, Scheduler from rx.core import Observable, typing from rx.internal import DisposedException from .anonymoussubject import AnonymousSubject from .innersubscription import InnerSubscription ...
3,142
839
import os import hydra import subprocess import logging from omegaconf import DictConfig from hydra import slurm_utils log = logging.getLogger(__name__) @hydra.main(config_path='/h/nng/conf/robust/config.yaml', strict=False) def launch(cfg: DictConfig): os.environ['NCCL_DEBUG'] = 'INFO' if cfg.data.task in [...
931
352
from flask import Flask, request, jsonify, session, url_for, redirect, render_template import joblib from flower_form import FlowerForm classifier_loaded = joblib.load("application_iris/saved_models/knn_iris_dataset.pkl") encoder_loaded = joblib.load("application_iris/saved_models/iris_label_encoder.pkl") # predict...
2,062
719
import math import re import unittest import urllib.error import urllib.request from .core import Quantity from .define import defined_systems si = defined_systems['si'] esu = defined_systems['esu'] emu = defined_systems['emu'] gauss = defined_systems['gauss'] class PhysicalQuantitiesTest(unittest.TestCase): def a...
8,522
3,582
import unittest import sys import os sys.path.append(os.getcwd().replace("test", "src")) import cirrus_ngs.cfnCluster.ConnectionManager as ConnectionManager import paramiko import tempfile import re ##THIS TEST WILL NOT WORK## class test_ConnectionManager(unittest.TestCase): def test_paramiko(self): key_f...
3,828
1,112
# -*- coding: utf-8 -*- ''' Commands for launching processes with or without OPUS interposition. ''' from __future__ import absolute_import, division, print_function import argparse import os import psutil from .. import config, server_start, utils def get_current_shell(): ppid = os.getppid() parent = psuti...
3,166
1,031
import pytest from ansible_self_service.l2_infrastructure.app_collection_config_parser import AppCollectionConfigValidationException, \ YamlAppCollectionConfigParser from ansible_self_service.l4_core.models import AppCategory, App VALID_CATEGORY_NAME = 'Misc' VALID_ITEM_NAME = 'Cowsay' VALID_ITEM_DESCRIPTION = 'L...
1,718
558
""" Run a simple HTTP server which provides API endpoint for SFTPPlus. Usage: server.py [options] -h --help Show this help. -p --port=8000 Listen to a specific port. [default: 8080] -a --address=127.0.0.1 Listen on specific address. [default: 0.0.0.0] -c --certificate=PATH Enable HTTPS by defin...
6,088
1,923
from .base import Flow from .view_flow import ViewFlow
55
16
from config.constant import ExportItemConstant, ExportItemTypeConstant, EventConstant, TransactionConstant from ethereumetl.service.eth_event_service import EthEvent class EthEventMapper(object): def eth_event_to_dict(self, eth_event: EthEvent): d1 = { ExportItemConstant.type: ExportItemTypeCo...
740
220
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # ...
5,934
1,835
import tensorflow as tf from tensorflow.keras.losses import binary_crossentropy,sparse_categorical_crossentropy from config import Configuration cfg = Configuration() class YOLOLoss(tf.losses.Loss): def __init__(self, anchors): super(YOLOLoss, self).__init__(reduction="none", name="YOLOLoss") self....
5,033
2,042
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
2,235
694
#! /usr/bin/env python3 import sys import math import glob from mule_local.postprocessing.pickle_SphereDataSpectralDiff import * from mule.exec_program import * # Ugly hack! #output, retval = exec_program('ls *benchref*/*prog_h* | sort | tail -n 1 | sed "s/.*prog_h//"') #if retval != 0: # print(output) # raise Excep...
500
185
"""This module contains a base runnable item.""" # ============================================================================= # IMPORTS # ============================================================================= # Future from __future__ import annotations # Standard Library from abc import ABC, abstractmethod...
4,355
1,084
from graph.graph_server import GraphServer __all__ = ['GraphServer']
71
23
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-08-15 16:23 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import djangoplicity.archives.base import djangoplicity.archives.fields class Migratio...
4,485
1,282
''' Created on 20.07.2015 @author: stefan ''' import unittest import pickle import picklesize import copy_reg class TestEstimator(unittest.TestCase): def setUp(self): self.target = picklesize.PickleSize() def compare(self, obj): data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)...
4,386
1,559
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Setup process.""" from io import open from os import path from setuptools import find_packages, setup with open( path.join(path.abspath(path.dirname(__file__)), "README.md"), encoding="utf-8" ) as f: long_description = f.read() setup( # Basic project inf...
1,691
590
# flake8: noqa from .core import Fitness from .kernel_based import GlobalMinimum from .observation_based import ObservationBasedFitness, MultipleLinearRegression, SimplePolynomialRegression, MultipleLinearRegression
216
58
# Copyright (c) 2019-2020 steelpy # Python stdlib imports # package imports #from steelpy.codes.aisc.aisc360 import AISC_360_16 #from steelpy.codes.aisc.aisc335 import AISC_335_89 #from steelpy.codes.iso.ISO19902 import ISOCodeCheck from steelpy.codes.piping.pipeline import Pipeline_Assessment #from steelpy.codes.api...
1,071
376
import os os.system("pip install pytorch_transformers") import nsml print(nsml.DATASET_PATH) os.system('python ./code/train.py --n-labeled 10 --data-path '+ nsml.DATASET_PATH + '/train/ --batch-size 4 --batch-size-u 8 --epochs 20 --val-iteration 1000 --lambda-u 1 --T 0.5 --alpha 16 --mix-layers-set 7 9 12 --lrmain 0.0...
347
163
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import math from selenium.webdriver.support.ui import Select import os import time from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC link = "http://...
1,126
397
# Generated by Django 3.2.7 on 2021-09-01 17:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('product', '0001_initial'), ] operations = [ migrations.CreateModel( name='Product', ...
1,224
363
# -*- coding: utf-8 -*- # # Copyright 2015 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
40,400
12,292
from os.path import * import glob import json import numpy as np from util.plot_utils import plot_curves, plot_multi_loss_distribution TMPJPG = expanduser("~/Pictures/") def plot_multi_logs(exp_name, keys, save_name, epoch, addition_len): root_path = expanduser("/raid/dataset/detection/detr_exp") folder_cand...
2,728
939
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
12,616
3,379
from dataclasses import dataclass from typing import Any from expungeservice.models.charge import ChargeType from expungeservice.models.charge import ChargeUtil from expungeservice.models.expungement_result import TypeEligibility, EligibilityStatus @dataclass(frozen=True) class TrafficOffense(ChargeType): type_n...
1,643
462
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: import_workload_create_instance short_description: Create NBD ex...
8,918
2,956
valores = [] while True: num = int(input('Digite um valor: ')) valores.append(num) cont = str(input('Quer continuar? [S/N] ')).upper() if cont == 'N': break print(f'Você digitou {len(valores)} elememtos.') valores.sort(reverse=True) print(f'Os valores em ordem decrescente são {valores}') if 5 ...
427
160
from huobi.utils.input_checker import * class MarginClient(object): def __init__(self, **kwargs): """ Create the request client instance. :param kwargs: The option of request connection. api_key: The public key applied from Huobi. secret_key: The private key appli...
10,670
3,018
import os import option import grapeGit as git import grapeConfig import utility class Commit(option.Option): """ Usage: grape-commit [-m <message>] [-a | <filetree>] Options: -m <message> The commit message. -a Commit modified files that have not been staged. Arguments...
2,297
670
from abc import ABC from typing import List, Optional, Union import numpy as np from allopy import OptData from allopy.penalty import NoPenalty, Penalty __all__ = ["AbstractObjectiveBuilder", "AbstractConstraintBuilder"] class AbstractObjectiveBuilder(ABC): def __init__(self, data: List[OptData], cvar_data: Li...
2,743
883
import os import pandas as pd import matplotlib.pyplot as plt wine_df = pd.read_csv(filepath_or_buffer='~/class5-homework/wine.data', sep=',', header=None) wine_df.columns = ['Class','Alcohol','Malic_Acid','Ash','Alcalinity_of_Ash','Magnesium', 'Total_Phenols','Flavanoid...
3,786
1,706
import tensorflow as tf import numpy as np from ares.attack.base import BatchAttack from ares.attack.utils import get_xs_ph, get_ys_ph, maybe_to_array, get_unit class BIM(BatchAttack): ''' Basic Iterative Method (BIM). A white-box iterative constraint-based method. Require a differentiable loss function and ...
7,451
2,307
import numpy as np from functools import lru_cache from typing import Tuple class DynamicResolver: def __init__(self, matrix: np.ndarray, *, num_src_lines: int = None, num_tgt_lines: int = None, max_k: int = 3, ...
3,148
971
import numpy as np """ Contains preprocessing code for creating additional information based on MRI volumes and true segmentation maps (asegs). Eg. weight masks for median frequency class weighing, edge weighing etc. """ def create_weight_mask(aseg): """ Main function for calculating weight mask of segmentati...
3,864
1,612
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2020) Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licen...
4,381
1,410
import os import scipy import numpy as np import pandas as pd import torch from torch.autograd import Variable def predict_batch(net, inputs): v = Variable(inputs.cuda(), volatile=True) return net(v).data.cpu().numpy() def get_probabilities(model, loader): model.eval() return np.vstack(predict_batch...
1,339
456
# Licensed under a 3-clause BSD style license - see LICENSE.rst from numpy.testing import assert_allclose from astropy.time import Time from gammapy.data import FixedPointingInfo, PointingInfo from gammapy.utils.testing import assert_time_allclose, requires_data @requires_data() class TestFixedPointingInfo: @clas...
3,806
1,558
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # from src.commands import * # import src.commands as command_modules secret_token = None db_user = None db_pass = None sessions = {} try: lines = [line.rstrip('\n') for line in open('.secret_token')] secret_token = lines[0] db_u...
1,183
370
import click import logging import matplotlib import matplotlib.pyplot as plt import joblib import fact.io from ..configuration import AICTConfig from ..plotting import ( plot_regressor_confusion, plot_bias_resolution, plot_feature_importances, ) if matplotlib.get_backend() == 'pgf': from matplotlib.b...
2,876
931
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import time from typing import Dict, Optional import sacremoses # type: ignore from cc_net import jsonql, text_normalizer class RobustT...
2,426
756
cont = 3 t1 = 0 t2 = 1 print('-----' * 12) print('Sequência de Fibonacci') print('-----' * 12) valor = int(input('Quantos termos você quer mostrar ? ')) print('~~~~~' * 12) print(f'{t1} ➙ {t2} ' , end='➙ ') while cont <= valor: t3 = t1 + t2 print(f' {t3}', end=' ➙ ') t1 = t2 t2 = t3 t3 = t1 co...
346
176
########################################################################## # # MRC FGU Computational Genomics Group # # $Id$ # # Copyright (C) 2009 Andreas Heger # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by ...
3,991
1,292
# Copyright (c) 2019 J. Alvarez-Jarreta and C.J. Brasher # # This file is part of the LipidFinder software tool and governed by the # 'MIT License'. Please see the LICENSE file that should have been # included as part of this software. """Represent a DataFrame to be processed with LipidFinder's workflow.""" import glo...
11,902
3,054
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import variables from tensorflow.python.ops import array_ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.o...
4,836
1,570
# -*- coding: utf-8 -*- import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', # 'sphinx.ext.intersphinx', # 'sphinx.ext.autosummary', # 'sphinx.ext.viewcode', # 'jupyter_sphinx.embed_widgets', ] templates_path = ['_templates'] master_doc = 'index' source_suffix ...
705
283
#!/usr/bin/env python3 # # Author: Yipeng Sun # License: BSD 2-clause # Last Change: Sun May 09, 2021 at 02:52 AM +0200 import numpy as np ARRAY_TYPE = 'np' def read_branch(ntp, tree, branch, idx=None): data = ntp[tree][branch].array(library=ARRAY_TYPE) return data if not idx else data[idx] def read_bran...
672
258
from django import forms from .models import Reminder from clinnotes.users.models import EpisodeOfCare class ReminderForm(forms.ModelForm): class Meta: model = Reminder fields = ['category', 'title', 'details', 'episode_of_care'] def __init__(self, *args, **kwargs): user = kwargs.pop...
483
151
import pygame as pg from shapely.geometry import Point, Polygon from time import perf_counter # Vars A = [(100, 600), (700, 600), (400, 80)] triangles = [[(100, 600), (700, 600), (400, 80)]] SQRT_3 = 3 ** (1 / 2) WHITE = (255, 255, 255) # Graphics part pg.init() screen = pg.display.set_mode((800, 800)) ...
3,583
1,646
from copy import deepcopy from functools import partial import sys import types # Global import of predefinedentities will cause an import loop import instanceactions from validator.constants import (BUGZILLA_BUG, DESCRIPTION_TYPES, FENNEC_GUID, FIREFOX_GUID, MAX_STR_SIZE, MDN_DOC) fro...
39,839
11,185
#!/usr/bin/env python """ Test code for the BBox Object """ import numpy as np import pytest from geometry_utils.bound_box import (BBox, asBBox, NullBBox, InfBBox, f...
14,588
6,362
import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import numpy as np import math from functools import wraps def clip(img, dtype, maxval): return np.clip(img, 0, maxval).astype(dtype) def clipped(func): """ wrapper to clip results of transform to image dtype value range """ ...
4,789
1,990
# -*- coding: utf-8 -*- """ Created on Mon Aug 14 09:49:13 2017 @author: vmg """ import os import buildingspy.development.regressiontest as r rt = r.Tester(check_html=False)#,tool="dymola") LibPath = os.path.join("TRANSFORM") ResPath = LibPath rt.showGUI(True) rt.setLibraryRoot(LibPath, ResPath) rt.setNumberOfThread...
417
177
# -*- coding: utf-8 -*- __author__ = "Ngoc Huynh Bao" __email__ = "ngoc.huynh.bao@nmbu.no" from ..keras.layers import Activation from ..keras.activations import deserialize from ..utils import Singleton class Activations(metaclass=Singleton): """ A singleton that contains all the registered customized acti...
2,039
552
""" Module to take a water_level reading.""" # Raspi-sump, a sump pump monitoring system. # Al Audet # http://www.linuxnorth.org/raspi-sump/ # # All configuration changes should be done in raspisump.conf # MIT License -- http://www.linuxnorth.org/raspi-sump/license.html try: import ConfigParser as configparser #...
2,618
878
''' Configuration generation for running Pancreas datasets ''' import os, argparse from pipelines import method_utils, dataloading_utils from preprocess.process_train_test_data import * if __name__ == "__main__": data_dir = "~/gpu/data" ## parse arguments import argparse parser = argparse.ArgumentPa...
2,830
900
import pandas as pd from sklearn.preprocessing import StandardScaler def stand_demo(): data = pd.read_csv("dating.txt") print(data) transfer = StandardScaler() data = transfer.fit_transform(data[['milage', 'Liters', 'Consumtime']]) print("Standardization result: \n", data) print("Mean of each ...
436
138
from prng.util.util import primitive_roots import pytest def test_primitive_roots(): prim_roots_sets = [ [3, [2]], [7, [3,5]], [13, [2,6,7,11]], [17, [3,5,6,7,10,11,12,14]], [19, [2,3,10,13,14,15]], [31, [3,11,12,13,17,21,22,24]], [53, [2,3,5,8,12,14,18,19,20...
716
494
# https://www.hackerrank.com/challenges/xml-1-find-the-score/problem import sys import xml.etree.ElementTree as etree def get_attr_number(node): return etree.tostring(node).count(b'=') if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() tree = etree.ElementTree(etree.fromstring(xm...
383
146
test = int(input()) while test > 0 : n,k = map(int,input().split()) p = list(map(int,input().split())) original = 0 later = 0 for i in p : if i > k : later += k original += i else : later += i original += i print(orig...
347
121
# -*- coding: utf-8 -*- """ Created on Mon Aug 18 22:20:01 2014 @author: baki """ import shlex from subprocess import Popen, PIPE from .Log import Log class Shell: def __init__(self, TAG=""): self.log = Log(TAG=TAG) self.current_process = None self.process_output = None def setTag(s...
2,948
953
import os import six import copy import pickle import random import logging from scrapy.http import Request from scrapy.exceptions import NotConfigured from scrapy.commands.genspider import sanitize_module_name from scrapy.spiders import CrawlSpider from .utils import ( add_sample, response_to_dict, get_o...
4,458
1,357
######################################################################### # _________ ___. ______________________ ___ # \_ ___ \___.__.\_ |__ ___________ / _____/\______ \ \/ / # / \ \< | | | __ \_/ __ \_ __ \/ \ ___ | _/\ / # \ \___\___ | | \_\...
2,735
766
#!/usr/bin/env python3 import torch from .lazy_tensor import LazyTensor class NonLazyTensor(LazyTensor): def _check_args(self, tsr): if not torch.is_tensor(tsr): return "NonLazyTensor must take a torch.Tensor; got {}".format(tsr.__class__.__name__) if tsr.dim() < 2: retur...
3,104
1,035
""" --- Day 19: Tractor Beam --- https://adventofcode.com/2019/day/19 """ from aocd import data from aoc_wim.aoc2019 import IntComputer from aoc_wim.zgrid import ZGrid from aoc_wim.search import Bisect import functools @functools.lru_cache(maxsize=100**2) def beam(z): comp = IntComputer(data, inputs=[int(z.imag),...
1,956
756
import cv2 def variance_of_laplacian(image): return cv2.Laplacian(image, cv2.CV_64F).var() """ checks if an image is blurry returns True if blurry, False otherwise """ def detect_blurry_image(image, threshold): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = variance_of_laplacian(image) i...
378
144
def main(): # Arithmetic operators a = 7 b = 2 print(f'{a} + {b} = {a+b}') print(f'{a} - {b} = {a-b}') print(f'{a} * {b} = {a*b}') print(f'{a} / {b} = {a/b}') print(f'{a} // {b} = {a//b}') print(f'{a} % {b} = {a%b}') print(f'{a} ^ {b} = {a**b}') # Bitwise ...
894
440
""" Helper functions and utilities """ from datetime import datetime as dt from mrcnn import visualize import numpy as np import os import cv2 TIMESTAMP_FORMAT = "%d/%m/%Y %H:%M:%S" class Logger(object): """ Log events and information to a file """ def __init__(self, savePath): self.savePa...
2,689
964
import abc class Mutator(abc.ABC): def apply(self, original_content): return original_content
108
32
import django.conf class Settings: """ This is a simple class to take the place of the global settings object. An instance will contain all of our settings as attributes, with default values if they are not specified by the configuration. """ defaults = { 'OTP_LOGIN_URL': django.conf.s...
630
182
import asyncio import discord from discord.ext import commands from discord.ext.commands.core import has_permissions class cog(commands.Cog): def __init__(self, client): self.client = client @commands.command(aliases=["clear"]) @has_permissions(ban_members=True) async def purge(self, ctx, cou...
544
176
from .test_tensorboard_rest_api import TestTensorboardRestAPI from .test_tensorboard_server import TestTensorboardServer from .test_tensorboard_endpoints import TestTensorboardEndpoint
184
49
from unittest import TestCase from ..helpers import ( create_web3, create_contract, get_future_execution_start_at_timestamp, proceed_time, get_prediction_time_shift, get_purchase_time_shift, get_shipping_time_shift, get_publication_time_shift, get_tournament_id, get_chain_id, ...
3,988
1,280
from loguru import logger # See "test_catch_exceptions.py" for extended testing def test_backtrace(writer): logger.add(writer, format="{message}", backtrace=True) try: 1 / 0 except Exception: logger.exception("") result_with = writer.read().strip() logger.remove() writer.clea...
579
174
class Employee: #Initializaing def __init__(self): print('Employee created ') #Deleting (Calling destructor) def __del__(self): print('Destructor called,Employee deleted') obj=Employee() del obj
251
67
""" Similar to the memory subsystem, this is a unified way to access information about objects which contain registers """ import envi.bits as e_bits from envi.const import * class InvalidRegisterName(Exception): pass class RegisterContext: def __init__(self, regdef=(), metas=(), pcindex=None, spindex=None,...
13,670
3,968
from flask_caching import Cache from flask_jwt_oidc import JwtManager from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate, MigrateCommand from flask import current_app from elasticapm.contrib.flask import ElasticAPM from .config import Config from .helper import Api apm = ElasticAPM() db = SQLA...
531
181
# Copyright 2017 by MPI-SWS and Data-Ken Research. # Licensed under the Apache 2.0 License. """Test async version of mqtt libraries. Depends on hbmqtt (https://github.com/beerfactory/hbmqtt) """ import unittest import sys import asyncio import string from random import choice, seed from antevents.base import Schedule...
3,510
1,283
# -*- coding: utf8 -*- import os from flask import Flask, request, render_template, request, redirect, url_for, jsonify from flask_discord import DiscordOAuth2Session, requires_authorization from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.partial(814742019489660939, "rvSBVHtGPflSASjeGEEKdZxC5Z_w1U...
7,407
4,162
from scapy.fields import ByteField, ShortField from scapy.packet import Packet class TPKT(Packet): name = "TPKT" fields_desc = [ByteField("version", 3), ByteField("reserved", 0), ShortField("length", 0x0000)]
257
86