text
string
size
int64
token_count
int64
import os class Credentials: API_KEY = os.getenv('API_KEY') API_SECRET_KEY = os.getenv('API_SECRET_KEY') #tokens ACCESS_TOKEN = os.getenv('ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.getenv('ACCESS_SECRET_TOKEN') class Settings: TRACK_WORDS = 'Technology' TABLE_NAME = "twttechnology" TABLE...
1,581
592
from .library import * from .differentiation import * from .sindy_ball import SINDyBall from .tests import * from .utils import *
130
42
from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): ADMIN = 'admin' PLAYER = 'player' TYPE_CHOICES = ( (ADMIN, "Admin"), (PLAYER, "Player") ) type = models.CharField(choices=TYPE_CHOICES, max_length=6, ...
341
114
#!/usr/bin/python import glob def main(): pyfiles = glob.glob("../*/*.py") for pyfile in pyfiles: print "pyfile %s" % pyfile main()
151
56
import base64 import datetime import email import logging import os import typing from email.message import Message from googleapiclient import errors from email_scrapper.models import Stores from email_scrapper.readers.base_reader import BaseReader logger = logging.getLogger(__name__) class GmailReader(BaseReader...
4,073
1,102
class Rails: def __init__(self, num_rails): self.num_rails = num_rails self.rails = [[] for _ in range(num_rails)] def populate_rails_linear(self, message, rail_lengths): message_list = list(message) for rail in self.linear_iterator(rail_lengths): rail.append(messag...
2,026
615
a=[1,2,3] b=[1,1,1] #d={1:"ONE", 2:"TWO", 3:"THREE", 4:"FOUR", 5:"FIVE", 6:"SIX"} f=[a[0]+b[0],a[1]+b[1],a[2]+b[2]] if f[0]==1: f[0]="ONE" elif f[0]==2: f[0]="TWO" print(f)
187
130
''' A+B for Input-Output Practice (IV) 描述 Your task is to Calculate the sum of some integers. 输入 Input contains multiple test cases. Each test case contains a integer N, and then N integers follow in the same line. A test case starting with 0 terminates the input and this test case is not to be processed. 输出 For each g...
748
288
import multiprocessing import os import os.path import pickle import librosa import numpy as np from scipy import signal def audio_extract(path, audio_name, audio_path, sr=16000): save_path = path samples, samplerate = librosa.load(audio_path) resamples = np.tile(samples, 10)[:160000] resamples[resam...
2,421
841
import inspect import logging from protean.container import Element, OptionsMixin from protean.core.event import BaseEvent from protean.exceptions import IncorrectUsageError from protean.utils import DomainObjects, derive_element_class, fully_qualified_name from protean.utils.mixins import HandlerMixin logger = loggi...
3,317
865
# -*- coding: utf-8 -*- """ Created on Fri Sep 17 10:12:26 2021 @author: Florian Jehn """ import os import pandas as pd import numpy as np def read_ipcc_counts_temp(): """reads all counts of temperatures for all reports and makes on df""" files = os.listdir(os.getcwd()+os.sep+"Results"+ os.sep + "temperature...
7,508
3,073
from pytest import fixture from zev.get_filesize import get_filesize def test_get_filesize(empty_filepath): assert get_filesize(empty_filepath) == 0
156
55
def main(): quote = input("What is the quote?\n") person = input("Who said it?\n") speech = "\n" + person + " says, " + '"' + quote + '"' print(speech) main()
179
68
#This program calculates the successive values of the following # calculation: Next value by taking the positive integer added by user # and if it is even divide it by 2, if it is odd, multiply by #3 and add 1.Program ends if current value is 1. #First: I created variable "pnumber" which will be the positive integer ...
1,151
328
# main function def has33(nums): # iterates through the list and tries to find two 3s next to each other for i in range(0, len(nums) - 1): # if indice i has a 3 and the indice next to it has a 3, print true if nums[i] == 3 and nums[i + 1] == 3: return print('True') return prin...
404
175
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from products.views import (products, index, products_detail) from rest_framework_jwt.views import refresh_jwt_token from users.views import Obta...
914
277
from survos2.config import Config import numpy as np from numpy.lib.function_base import flip from qtpy import QtWidgets from qtpy.QtWidgets import QPushButton, QRadioButton from survos2.frontend.components.base import * from survos2.frontend.components.entity import ( SmallVolWidget, TableWidget, setup_en...
17,692
5,361
import sys import gzip import numpy as np if __name__ == "__main__": f_names = sys.argv[1:] max_value = 100000 bin_size = 50 threshold = 0.01 data = [] total_bins = (max_value/bin_size)+1 for no, f_name in enumerate(f_names): #prefix = f_name.split("/")[-1].replace(".tx...
1,248
451
from tqdm import tqdm import os import glob import pickle import numpy as np from imageio import imread, imwrite import astimp from multiprocessing import Pool, cpu_count from functools import partial class ErrorInPreproc(Exception): pass class Dataset(): """Datasets consisting of several files in a given in...
5,459
1,713
from clustering_algorithms import CLARA, PAM, get_initial_points from data_loaders import load_data from timer import Timer from visualizers import plot_data # FILENAME = "datasets/artificial/sizes3.arff" FILENAME = "datasets/artificial/zelnik4.arff" # FILENAME = "datasets/artificial/xclara.arff" # FILENAME = "dataset...
1,024
356
from module import support from module import fibo import sys support.print_func("Runoob") fibo.fib(1000) print(fibo.fib2(100)) print(fibo.__name__) # 把模块中的一个函数赋给一个本地的名称 fib = fibo.fib fib(10) """ from…import 语句 Python的from语句让你从模块中导入一个指定的部分到当前命名空间中,语法如下: from modname import name1[, name2[, ... nameN]] 例如,要导入模块 fib...
1,143
828
import torch from einops import rearrange import svgwrite ########################################### # Normalization / Standardization functions ########################################### def normalize_functional(tensor: torch.Tensor, mean: list, std: list): """ Standardizes tensor in the channel dimension...
4,459
1,510
import cv2 import numpy as np from skimage import draw from skimage import io # Read image im_in = cv2.imread("analyses/MDA231_stopper_1_c3.tif", cv2.IMREAD_GRAYSCALE); # Threshold. # Set values equal to or above 220 to 0. # Set values below 220 to 255. th, im_th = cv2.threshold(im_in, 20, 255, cv2.THRESH_BINARY_...
3,742
1,649
from bxcommon.test_utils.abstract_test_case import AbstractTestCase from bxcommon.messages.bloxroute.txs_message import TxsMessage from bxcommon.models.transaction_info import TransactionInfo from bxcommon.test_utils import helpers from bxcommon.utils.object_hash import Sha256Hash class TxsMessageTests(AbstractTestCa...
1,344
469
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') # Tuplas são imutáveis # lanche[1] = 'Refrigerante' - Esse comando não vai funcionar print(len(lanche)) print(sorted(lanche)) print(lanche) print(lanche[-3:]) for comida in lanche: print(f'Eu vou comer {comida}') for cont in range(0, len(lanche)):...
712
333
import yaml import os config_file = os.path.join(os.path.dirname(__file__), "config/config.yml") with open(config_file, 'r') as stream: CONFIG = yaml.load(stream)
167
61
import xml.etree.ElementTree as ET tree = ET.parse('/Users/zhaoli/workspace/splunk/playground/var/lib/jenkins/jobs/Splunk/jobs/develop/jobs/platform/jobs/cli/jobs/trigger_cli_linux/config.xml') root = tree.getroot() # SPs = root.findall("properties/hudson.model.ParametersDefinitionProperty/parameterDefinitions/[huds...
921
328
import random def format_fasta(title, sequence): """ This formats a fasta sequence Input: title - String - Title of the sequence sequence - String - Actual sequence Output: String - Fully formatted fasta sequence """ fasta_width = 70 # Number of characters in one line n...
986
307
import sublime import os class OutputPanel: def __init__( self, name, file_regex='', line_regex='', base_dir=None, word_wrap=False, line_numbers=False, gutter=False, scroll_past_end=False, syntax='Packages/Text/Plain text.tmLanguage' ): self.name = name self.window = s...
1,604
499
from flask import Flask, render_template app = Flask(__name__) app.config['DEBUG'] = True # Note: We don't need to call run() since our application is embedded within # the App Engine WSGI application server. @app.route('/') def hello(name=None): """Return a friendly HTTP greeting.""" return render_template(...
673
220
from unittest.mock import Mock, patch import pytest import patterns.echo_server_contextvar as main @patch.object(main, "client_addr_var", Mock()) def test_render_goodbye(capsys): # Call 'render_goodbye' goodbye_string = main.render_goodbye() print(goodbye_string) # Assert. out, err = capsys.re...
903
328
#!/usr/bin/env python # -*- coding: utf-8 -*- # Autor: rique_dev (rique_dev@hotmail.com) from SSLProxies24.Feed import Feed from SSLProxies24.Check import CheckProxy import time import gc # Recupera a listagem prx = Feed().PROXY_LIST # Inicia classe chk = CheckProxy() # Começa validação chk.validatelist(prx) # At...
693
273
import math as m def yakobi(a, n, k): if a < 0: k *= pow(-1, (n - 1) // 2) yakobi(-a, n, k) if a % 2 == 0: k *= (-1) ** ((pow(n, 2) - 1) / 8) yakobi(a / 2, n, k) if a == 1: return k if a < n: k *= pow(-1, ((n - 1)(a - 1)) / 4) yakobi(n % a, a, k) ...
577
275
## ========================================================================= ## ## Copyright (c) 2019 Agustin Durand Diaz. ## ## This code is licensed under the MIT license. ## ## hud_b2d.py ...
3,787
1,369
def get_final_txt(grb, tables, sentences, output_path): """ Combine the data from [grb]_final_sentences.txt and [grb]_final_tables.txt. If a piece of data in tables and another piece in sentecnes are originially from the same GCN. Put them in the same GCN in [grb]_final.txt. """ # Avoid modifyi...
1,958
625
from solid import * from solid.utils import * import util from util import * from math import pi def headband(r1=64.0, r2=85.0, t=3.0, w=12.0): combe = right(r1-t/2)(linear_extrude(1)(square([1,1], center=True) + left(0.5)(circle(d=1)))) combe_spacing = 3.0 # mm combe_count = pi*r1/combe_spacing c...
972
411
from django.apps import AppConfig class NativeShortuuidConfig(AppConfig): name = 'native_shortuuid'
106
31
r"""General solver of the 1D meridional advection-diffusion equation on the sphere: .. math:: \frac{\partial}{\partial t} \psi(\phi,t) &= -\frac{1}{a \cos\phi} \frac{\partial}{\partial \phi} \left[ \cos\phi ~ F(\phi,t) \right] \\ F &= U(\phi) \psi(\phi) -\frac{K(\phi)}{a} ~ \frac{\partial \psi}{\partial \phi}...
3,482
1,080
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. # 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...
1,624
519
import uuid from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils import timezone from django.utils.timesince import timesince from django.utils.translation import gettext_lazy as _ from dhost.dapps.models import Dapp def get_obj_m...
3,508
1,140
data = open("input.txt", "r").readlines() polymer = data[0] pair_insertion = {} for line in data[2:]: [token, replacement] = line.strip().split(" -> ") pair_insertion[token] = replacement result = [i for i in polymer.strip()] for step in range(0, 10): next = [] for i, si in enumerate(result): ...
620
217
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('raster', '0005_auto_20141014_0955'), ] operations = [ migrations.AddField( model_name='rastertile', ...
1,199
442
''' Tests for utils submodule of the analysis module. ''' from nose.tools import assert_equal, assert_raises from coral import analysis, DNA, RNA, Peptide def test_utils(): test_DNA = DNA('ATAGCGATACGAT') test_RNA = RNA('AUGCGAUAGCGAU') test_peptide = Peptide('msvkkkpvqg') test_str = 'msvkkkpvgq' ...
588
222
""" Carry out template-based replacements in project files """ import os import sys from string import Template def replace_name(path, mapping): """ Handles replacement strings in the file or directory name """ # look for replacement strings in filename f_split = list(os.path.spli...
1,765
580
import hashlib import os # 生成字符串的MD5值 def str2md5(content=None): if not content: return '' md5gen = hashlib.md5() md5gen.update(content.encode()) return md5gen.hexdigest() # 生成字符串的SHA256值 def str2sha256(content=None): if not content: return '' sha256gen = hashlib.sha256() ...
1,747
610
import os import sys from dotenv import load_dotenv from facebook_scraper import get_posts load_dotenv() print ("hi") result = [] for post in get_posts(group=os.environ.get("FacebookGroupId"), pages=1, credentials=(os.environ.get("FacebookUser"), os.environ.get("FacebookPassword"))): result....
609
199
import os #github login SITE = 'https://api.github.com' CALLBACK = 'https://oneliner.sh/oauth2' AUTHORIZE_URL = 'https://github.com/login/oauth/authorize' TOKEN_URL = 'https://github.com/login/oauth/access_token' SCOPE = 'user' #redis config REDIS_HOST = os.environ['REDIS_HOST'] #REDIS_HOST = ...
442
175
import json from npt import log from . import tmpdir def read_geojson(filename): """ Return JSON object from GeoJSON """ with open(filename, 'r') as fp: js = json.load(fp) return js
214
72
""" Prueba creacion de usuarios """ # import json from typing import Any, Dict import pytest from django.contrib.auth import get_user_model from apps.user.serializers import UserHeavySerializer # from django.contrib.auth.models import User User = get_user_model() pytestmark = [pytest.mark.django_db, pytest.mark...
6,351
2,211
import pybullet as p import pybullet import time p.connect(p.GUI) p.loadURDF("toys/concave_box.urdf") p.setGravity(0,0,-10) for i in range (10): p.loadURDF("sphere_1cm.urdf",[i*0.02,0,0.5]) p.loadURDF("duck_vhacd.urdf") timeStep = 1./240. p.setTimeStep(timeStep) while (1): p.stepSimulation() time.sleep(timeStep)
319
161
from pylatex import Document, Tabular, Section, NoEscape, Command, MultiRow from Old.BioCatHubDatenmodell import DataModel first_name = "some firstname" last_name = "some lastname" e_mail = "some@adress.com" institution = "some institution" vessel_type = "some vessel" volume = int(42) vol_unit = "mol/l" add_attributes...
2,472
769
import cv2 import numpy as np import matplotlib.pyplot as plt pic = cv2.imread('image2.png',0) #pic = imageio.imread('img/parrot.jpg') gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114]) gray = gray(pic) ''' log transform -> s = c*log(1+r) So, we calculate constant c to estimate s -> c = (L-1)/log(1+|...
535
243
#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True) message = ''.join(sys.argv[1:]) or 'Hello World!' for i in range(30): message = str(i)+' '+i*'.' ch...
493
164
from ConfigParser import SafeConfigParser from cStringIO import StringIO import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import MetaData from sqlalchemy.orm import sessionmaker from os.path import sep from hashlib import md5 from datetime import datetime, timedelta import re import logging impo...
4,100
1,286
from pathlib import Path from typing import Union import yaml class Config(object): """Basic Config Class""" def __init__(self, cfg_yaml_path:str, root:str=".", data_path:str="./data"): r""" Configuration of Settings Args: root: root path of project, default="." ...
3,067
887
""" List Comprehension Aninhada OBJ: Encontrar o maior ou os maiores números de uma lista e imprimir outra lista """ listaGenerica = [1, 2, 3, 4, 1, 2, 3, 4, 10, 10, 10, 5, 3, -4] listaMaior = [x for x in listaGenerica if not False in [True if x >= y else False for y in listaGenerica]] print(listaMaior)
307
132
def main(): # age = input("How old are you?") # print("I am %s year old" % age) file = open("demo1") lines = file.readlines() print("lines",lines) for i in range(len(lines)): print(lines[i]) file.close() c,d = addOne(1,2) print(c,d) def addOne(a,b): return a+1, b+1 i...
357
144
#!/usr/bin/python3 def nbracines(a, b, c): if a == 0: print("Le coefficient dominant est nul, ce n'est pas un trinome !") return d = b*b - 4*a*c k = 2 if abs(d) < 1e-10: k = 1 d = 0 elif d < 0: k = 0 print("Le polynome " + str(a) + "X^2 + " + str(b) + "X ...
651
286
# Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, m...
2,641
874
class Solution: def uniqueLetterString(self, S: str) -> int:
74
24
import sys import numpy as np class PiezoTransducer(object): """Piezoelectric transducer data structure """ def __init__(self,Glob,(zMin,zMax),h=1.): """initial instance of PiezoTransducer class Args: Glob (data structure): data structure holding domain configuration ...
3,187
1,009
number_int = int("32"); number_float= float(32); number_complex = complex(3222342332432435435345324435324523423); print(type(number_int),": ",number_int); print(type(number_float),": ",number_float); print(type(number_complex),": ",number_complex);
249
111
#!/usr/bin/env python3 import unittest import kitty from kitty import uncomfy_checker import mock class TestProgram(unittest.TestCase): def test_comfy(self): kitty.uncomfy_checker = mock.Mock(return_value='comfortable') self.assertIn(uncomfy_checker(), 'comfortable') if __name__ == '__main__': ...
338
124
from sympy.abc import s from sympy.physics.control.lti import TransferFunction from sympy.physics.control.control_plots import ramp_response_plot tf1 = TransferFunction(s, (s+4)*(s+8), s) ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
251
93
""" Main command line interface to the pynorare package. """ import sys import pathlib import contextlib from cldfcatalog import Config, Catalog from clldutils.clilib import register_subcommands, get_parser_and_subparsers, ParserError, PathType from clldutils.loglib import Logging from pyconcepticon import Concepticon...
2,309
720
from django.apps import AppConfig class AppKasirConfig(AppConfig): name = 'app_kasir'
92
33
""" Evaluate recommendations. """ import config from collections import defaultdict class ConfusionMatrixEvaluator(object): """Evaluate result's precision and recall.""" def __init__(self): self.experiment_reset() self.reset() def experiment_reset(self): self.exp_results = default...
2,472
763
import os import cv2 import time import argparse import torch import warnings import numpy as np from detector import build_detector from deep_sort import build_tracker from utils.draw import draw_boxes from utils.parser import get_config from utils.log import get_logger from utils.io import write_results from numpy ...
12,263
4,463
import numpy as onp import casadi as cas def array(object, dtype=None): try: a = onp.array(object, dtype=dtype) if a.dtype == "O": raise Exception return a except (AttributeError, Exception): # If this occurs, it needs to be a CasADi type. # First, determine the dim...
1,172
325
# -*- coding: utf-8 -*- __author__ = 'eeneku' from main_menu import MainMenu from world_map import WorldMap from local_map import LocalMap __all__ = [MainMenu, WorldMap, LocalMap]
181
64
# Generated by Django 2.2.5 on 2019-10-22 07:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUT...
2,502
706
""" Payin API """ from dataclasses import dataclass from typing import Union from api_payin_model import ( PayinAdjustPaymentRequest, PayinCancelRequest, PayinCancelResponse, PayinCaptureRequest, PayinCaptureResponse, PayinMandateRequest, PayinMandateResponse, PayinOrderDetailsRequest,...
3,283
925
from rest_framework.reverse import reverse from rest_framework.test import APITestCase from fdadb.models import MedicationName, MedicationNDC, MedicationStrength class APITests(APITestCase): def setUp(self): for name in ("DrugName", "OtherDrugName", "DruuuugName", "NamedDrug"): medication_nam...
5,516
1,765
#!/usr/bin/env python """ Copyright 2020 Zhao HG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
3,626
1,209
from flask import Flask, request from twilio.twiml.voice_response import VoiceResponse, Gather import datetime import os import json import http.client app = Flask(__name__) allowUntil = datetime.datetime.now() # Fetch env vars whitelisted_numbers = os.environ['WHITELISTED_NUMBERS'].split(",") # Numbers allowed to d...
3,676
1,102
import tkinter as tk from tkinter import font as tkfont, ttk import logging as log import sys from cx_Oracle import DatabaseError from GUI_Pages.BasicPage import TitlePage from Utilities.Cipher import Cipher, get_hash FORMAT = '[%(asctime)s] [%(levelname)s] : %(message)s' log.basicConfig(stream=sys.stdout, level=lo...
5,738
1,733
from bert_hierarchy_extractor.datasets.train_dataset import TrainHierarchyExtractionDataset from bert_hierarchy_extractor.datasets.utils import cudafy from bert_hierarchy_extractor.logging.utils import log_metrics import numpy as np from torch.utils.data import DataLoader from transformers import AdamW, get_linear_sche...
8,151
2,358
# Level 2 of pythonchallenge.com! # Challenge: within the source code of this level, there is a # set of jumbled characters. Within these characters, find the # letters and join them together to find the correct url. from solution_framework import Solution import requests # to view source code import re ...
786
254
# Generated by Django 3.1.7 on 2021-05-10 07:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import saleor.core.utils.json_serializer class Migration(migrations.Migration): initial = True dependencies = [ ('store', '0001_initial'), ...
1,444
440
import cv2 import os import sqlite3 import dlib import re,time from playsound import playsound import pyttsx3 cam = cv2.VideoCapture(0) cam.set(3, 640) # set video width cam.set(4, 480) # set video height face_detector = cv2.CascadeClassifier('C:/Users/ACER/Desktop/PROJECT ALL RESOURCE/PROJECT ALL RESOURCE/F...
2,900
1,028
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * from sqlalchemy import * from sqlalchemy.sql import func, or_ from sqlalchemy.types import TIMESTAMP from sqlalchemy.ext.hybrid import hybrid_property from time import time import markupsafe from sqlalchemy.ext.associationproxy import ...
4,847
1,460
import multiprocessing as mp # mp.set_start_method('spawn') import math import os import pickle import random from glob import glob from os import path import albumentations as alb import cv2 import numpy as np import skimage import torch import imageio from albumentations.pytorch import ToTensorV2 from skimage.color...
8,753
3,280
from fractions import Fraction num1 = Fraction(1, 3) num2 = Fraction(1, 7) num1 * num2 # Fraction(1, 21)
107
51
from io import StringIO from pathlib import Path import pytest from toxn.config import from_toml @pytest.mark.asyncio async def test_load_from_io(): content = StringIO(""" [build-system] requires = ['setuptools >= 38.2.4'] build-backend = 'setuptools:build_meta' [tool.toxn] default_tasks = ['py36'] """) ...
1,109
404
from constantMonthlyModel import ConstantMonthlyModel from constantModel import ConstantModel from twoParameterModel import TwoParameterModel from threeParameterModel import ThreeParameterModel from anyModel import AnyModelFactory from schoolModel import SchoolModel, SchoolModelFactory from recurrentModel import Recurr...
536
112
host = 'https://api.gotinder.com' #leave tinder_token empty if you don't use phone verification tinder_token = "0bb19e55-5f12-4a23-99df-8e258631105b" # Your real config file should simply be named "config.py" # Just insert your fb_username and fb_password in string format # and the fb_auth_token.py module will do the ...
326
125
from django.test.runner import DiscoverRunner from io import StringIO from logging import StreamHandler, getLogger from unittest import TextTestRunner, TextTestResult class SimoneTestRunner(TextTestRunner): def __init__(self, *args, **kwargs): kwargs['buffer'] = True super().__init__(*args, **kwar...
1,958
569
__all__ = ["fibo"]
18
10
row = [-1, -1, -1, 0, 0, 1, 1, 1] col = [-1, 0, 1, -1, 1, -1, 0, 1] def isValid(x, y, mat): return 0 <= x < len(mat) and 0 <= y < len(mat[0]) def findMaxLength(mat, x, y, previous): if not isValid(x, y, mat) or chr(ord(previous) + 1) != mat[x][y]: return 0 max_len = 0 for k in ran...
1,340
558
__all__ = ('get_session_list', 'get_animal_list', 'get_event', 'get_tag_pattern', 'get_pattern_animalList', 'get_current_animals') import datetime import logging from .. import Root from .. import File from .. import Profile from ..Profile import EventProfile from...
4,653
1,314
from random import choice from copy import deepcopy from game_data import GameData from agents import Agent import numpy as np import random import pickle import pandas as pd class IsaacAgent(Agent): def __init__(self, max_time=2, max_depth=300): self.max_time = max_time self.max_depth = max_dept...
10,747
3,767
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn from os import curdir, sep import threading import urlparse import mimetypes PORT_NUMBER = 8080 VERSION_NUMBER = '1.0.0' class Handler(BaseHTTPRequestHandler): def do_GET(self): #Parse path into dictionary and...
1,288
494
from pyteal import * ADMIN_KEY = Bytes("admin") WHITELISTED_KEY = Bytes("whitelisted") REQUESTS_BALANCE_KEY = Bytes("requests_balance") MAX_BUY_AMOUNT = Int(1000000000) MIN_BUY_AMOUNT = Int(10000000) REQUESTS_SELLER = Addr("N5ICVTFKS7RJJHGWWM5QXG2L3BV3GEF6N37D2ZF73O4PCBZCXP4HV3K7CY") MARKET_EXCHANGE_NOTE = Bytes("alg...
5,872
1,885
""" Support for Shelly smart home devices. For more details about this component, please refer to the documentation at https://home-assistant.io/components/shelly/ """ # pylint: disable=broad-except, bare-except, invalid-name, import-error from datetime import timedelta import logging import time import as...
20,198
6,720
"""remove unique constraint Revision ID: 36745fa33987 Revises: 6b7ad8fd60f9 Create Date: 2022-01-06 08:31:55.141039 """ from alembic import op # revision identifiers, used by Alembic. revision = "36745fa33987" down_revision = "6b7ad8fd60f9" branch_labels = None depends_on = None def upgrade(): # ### commands a...
664
257
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.website_event_track_live.controllers.track_live import EventTrackLiveController class EventTrackLiveQuizController(EventTrackLiveController): def _prepare_track_suggestion_values(self, track, trac...
564
180
embed <drac2> GVARS = load_json(get_gvar("c1ee7d0f-750d-4f92-8d87-70fa22c07a81")) CLASSES = [load_json(get_gvar(gvar)) for gvar in GVARS] DISPLAY = { "acrobatics": "Acrobatics", "animalhandling": "Animal Handling", "athletics": "Athletics", "arcana": "Arcana", "deception": "Deception", "dex": "Dex...
2,640
1,080
################################################################################ ##### For Bloomberg ------------------------------------------------------------ ##### Can't use this if you're on a Mac :( ################################################################################ from __future__ import print_f...
8,351
2,414
import os from typing import Sequence, Union import numpy as np import tifffile from deepcell.applications import Mesmer from imctools.io.ometiff.ometiffparser import OmeTiffParser from skimage import measure from sqlalchemy.orm import Session from histocat.core.acquisition import service as acquisition_service from ...
3,767
1,269
import math import numpy as np import random import os from PIL import Image import pyttsx3 class TopError(Exception): pass class OddResolutionError(Exception): pass class Fractal: ''' Makes images of the Mandelbrot set given a center coordinate and the imaginary coordinate of the top row of pi...
9,800
2,802