text
string
size
int64
token_count
int64
""" 1375. Substring With At Least K Distinct Characters """ class Solution: """ @param s: a string @param k: an integer @return: the number of substrings there are that contain at least k distinct characters """ def kDistinctCharacters(self, s, k): # Write your code here n = len...
855
254
people = 20 cats = 30 dogs = 15 if people < cats: print("고양이가 너무 많아요! 세상은 멸망합니다!") if people > cats: print("고양이가 많지 않아요! 세상은 지속됩니다!") if people < dogs: print("세상은 침에 젖습니다!") if people > dogs: print("세상은 말랐습니다!") dogs += 5 if people >= dogs: print("사람은 개보다 많거나 같습니다") if people <= dogs: p...
390
281
""" Tests for the import manager. """ from traits.util.api import import_symbol from traits.testing.unittest_tools import unittest class TestImportSymbol(unittest.TestCase): """ Tests for the import manager. """ def test_import_dotted_symbol(self): """ import dotted symbol """ import tarfi...
1,019
291
# ################ A simple graphical interface which communicates with the server ##################################### from tkinter import * import socket import face import cubie # ################################## some global variables and constants ############################################### DEFAULT_HOST =...
7,692
2,425
"""Abstraction layer to deal with Django related changes in order to keep compatibility with several Django versions simultaneously.""" from __future__ import unicode_literals from django.conf import settings as django_settings USER_MODEL = getattr(django_settings, 'AUTH_USER_MODEL', 'auth.User') # Django 1.11 Widg...
1,159
320
""" ethereum.py ethereum.py contains an EthereumClient class that provides functions for interacting with the Coverage.sol solidity contract on an Ethereum blockchain network. """ import asyncio import datetime import json import logging import os from ethereum.clients.nats import get_nats_client from ethereum.config ...
10,649
2,862
from argparse import Namespace from .action import Action from symengine.lib.symengine_wrapper import sympify from termcolor import colored from program.mc_comb_finder import MCCombFinder from cli.common import prepare_program class MCCombinationAction(Action): cli_args: Namespace def __init__(self, cli_args...
1,759
490
import gunicorn accesslog = "-" errorlog = "-" access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Forwarded-For}i)s"' capture_output = True forwarded_allow_ips = "*" secure_scheme_headers = {"X-CLOUDFRONT": "yes"} workers = 2 worker_class = "gthread" worker_connections = 5 bind = ":...
494
246
# -- encoding:utf-8 -- # ''' Crie uma variável com a string “ instituto de ciências matemáticas e de computação” e faça: a. Concatene (adicione) uma outra string chamada “usp” b. Concatene (adicione) uma outra informação: 2021 c. Verifique o tamanho da nova string (com as informações adicionadas das questões a e b), co...
1,596
613
# -*- coding: utf-8 -*- from django.shortcuts import resolve_url from django.template.loader import render_to_string from django_jinja import library from jinja2 import contextfunction @contextfunction @library.global_function def breadcrumb(context, contents, *args, **kwargs): class_name = kwargs.pop('class', False...
753
275
import platform import requests class DDTransport(object): """ DDTransport contains all the logic for sending Traces to Datadog :type trace_addr: str :param trace_addr: trace_addr specifies the host[:port] address of the Datadog Trace Agent. """ def __init__(self, trace_addr): self._...
1,334
381
from typing import List class AnalysisTarget: def __init__(self, line: str, line_num: int, lines: List[str], file_path: str): self.line = line self.line_num = line_num self.lines = lines self.file_path = file_path
252
79
import torchvision import torch import torch.nn as nn import torch.nn.functional as F class Vgg_Deeplab(nn.Module): def __init__(self,*args, **kwargs): super(Vgg_Deeplab, self).__init__() vgg16 = torchvision.models.vgg16() layers = [] layers.append(nn.Conv2d(3, 64, kernel_size=3, ...
5,558
1,916
# -*- coding: utf-8 -*- """ This module defines a connexion app object and configures the API endpoints based the swagger.yml configuration file. copyright: © 2019 by Erik R Berlin. license: MIT, see LICENSE for more details. """ import connexion app = connexion.App(__name__, specification_dir="./") app.app.url_map...
510
188
# -*- coding: utf-8 -*- """ 17 June 2020 Author: Xiandi Ooi Visualizing the types of pollutants. """ import pandas as pd from plotly.offline import plot import plotly.graph_objects as go # Get the file from us df = pd.read_csv(https://www.dropbox.com/s/u0ymg0ufne0an60/api-20200713.csv?dl=1", sep = ";") # Make the ...
2,341
881
from django import forms from django.test import TestCase from template_forms import bs3 def startswith_a(value): if value.startswith('a'): return value raise forms.ValidationError('Value must start with "a".') def not_now(value): if value: raise forms.ValidationError('I cannot let you...
3,977
1,164
""" Copyright 2017 BlazeMeter Inc. 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, software...
19,463
6,135
""" Maybe not so relevant in Python due to the possibility to use multiple inheritance... """ from abc import ABC, abstractmethod class CloudHostingProvider(ABC): @abstractmethod def create_server(region): ... @abstractmethod def list_servers(region): ... class CDNProvider(ABC): ...
1,434
446
# MIT License # # Copyright The SCons Foundation # # 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, ...
3,536
1,133
# # This source file is part of the EdgeDB open source project. # # Copyright 2020-present MagicStack Inc. and the EdgeDB authors. # # 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...
8,351
2,124
import re RE_NUMBER_VALIDATOR = re.compile(r'^\d+[.,]\d+$') def number_is_valid(number): return RE_NUMBER_VALIDATOR.match(number) assert number_is_valid('1.32') assert number_is_valid('1,32') assert not number_is_valid('asdasd1234') assert not number_is_valid('22,a44')
278
116
""" prec_reformat.py Taking state data and having each line be a precinct's voting results and candidate cf-scores (rather than each line be each candidate per precinct. | prec_id | cf_score_0 | num_votes_0 | cf_score_1 | num_votes_1 | """ import math import numpy as np import pandas as pd from prec_cd import prec_...
3,529
1,334
from snakemake import shell input, output, params, threads, w, config = snakemake.input, snakemake.output, snakemake.params, snakemake.threads, snakemake.wildcards, snakemake.config genome = w.genome params.hybrid = config['x'][genome]['hybrid'] opt = params.opt shell(""" rm -rf {output.fna}* {output.fai}* rm...
1,668
649
# -*- coding: utf-8 -*- import time import xlrd import Register_aidaiwangApp import LogOut_aidiawangApp def start_to_login(filename): print(u'login') driver = Register_aidaiwangApp.driver driver.launch_app() time.sleep(3) try: driver.find_element_by_id('cn.phaidai.loan:id/rb_mine') ...
2,358
809
from sys import argv script, user_name = argv prompt = '>' print(user_name, script) print("Do you like me " + user_name + "?") likes = input(prompt) print("Where do you live " + user_name + "?") lives = input(prompt) print(""" So you said {:s} about liking me. You live in {:s}. """.format(likes, lives)) print("Scr...
389
153
import io import pytest from requests import get from urllib.parse import urljoin def test_my_uploads_page(wait_for_api, login_user): """ GIVEN a user has logged in (login_user) WHEN the '/my/uploads' page is navigated to (GET) THEN check the response is valid and page title is correct """ requ...
2,565
817
#!/usr/bin/env python import sys from shotgun import * try: if len(sys.argv) > 1: sg = Shotgun(sys.argv[1]) else: sg = Shotgun() ################################################################# # Find CustomEntity01 entities #######################################################...
1,107
332
import word2vec_np.utils.checks as checks import collections import numpy as np import math import time import logging def get_sentences_from_file(train_file): """ Returns a list of sentences from an input file. Args: train_file: A path to a file Returns: A list of sentence...
24,955
7,515
import justpy as jp from .group import Group class Row(Group): def __init__(self): '''Row Element Provides a container which arranges its child in a row. ''' view = jp.QDiv(classes='row items-start', style='gap: 1em', delete_flag=False) super().__init__(view)
307
95
# -*- coding: utf-8 -*- import pkg_resources __version__ = pkg_resources.require("mtvs")[0].version
102
41
# coding=utf-8 import sys from teamcity.unittestpy import TeamcityTestRunner if sys.version_info < (2, 7): from unittest2 import main, TestCase, expectedFailure else: from unittest import main, TestCase, expectedFailure class TestSkip(TestCase): def test_expected_failure(self): self.fail("this sh...
452
134
import uvicorn from fastapi import FastAPI from database import Base, engine from routers.user import router as router_user from routers.product import router as router_product from routers.authentication import router as router_auth app = FastAPI( title="Wish List", description="Permita que seus clientes acompan...
877
355
# encoding: utf-8 import torch import cv2 import numpy as np import pdb def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists...
1,605
523
# Copyright (c) 2018 Copyright holder of the paper Generative Adversarial Model Learning # submitted to NeurIPS 2019 for review # All rights reserved. import numpy as np import torch class Optimizer(object): def __init__(self, policy, use_gpu=False): self.networks = self._init_networks(policy.input_dim, ...
2,273
740
#!/usr/bin/python3 import boto3 source_ddb = boto3.resource('dynamodb', 'us-east-1') dest_ddb = boto3.client('dynamodb', 'us-west-2') def sync(source_ddb, dest_ddb): table = source_ddb.Table("CodeGuru-MusicCollection") scan_kwargs = { 'ProjectionExpression': "Artist, SongTitle" } done = False ...
915
306
""" """ import json from django.views.decorators.cache import never_cache from django.http import HttpResponse from django.shortcuts import render_to_response from core.views import initRequest, DateEncoder from core.reports import MC16aCPReport, ObsoletedTasksReport, TitanProgressReport @never_cache def report(r...
2,492
702
from typing import Dict, List, Tuple import numpy as np import tensorflow as tf from absl import logging from xain.datasets import prep from xain.types import History, Metrics, Partition, Theta, VolumeByClass from .model_provider import ModelProvider class Participant: # pylint: disable-msg=too-many-arguments ...
4,594
1,523
#!/usr/bin/env python3 """! QR code generator animation script.""" import numpy as np import qrcode from src.animate import Animate class QRCode(Animate): """! QR code generator animation class. @image html qr_code.QRCode.png width=256px Animation displaying a static QR-code-encoded-text. """ __C...
1,380
502
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 基地址是本项目根目录 sys.path.append(BASE_DIR) import datetime from yxf_yixue.xiaochengtu import XiaochengtuApi if __name__ == '__main__': string = '1996/02/29 23:16' obj = datetime....
483
228
import numpy as np from sklearn.preprocessing import OneHotEncoder class MultinomialNB: """ Naive Bayes algorithm with discrete inputs Parameters ---------- alpha : float, optional (default=1.) Smooth parameter used in Naive Bayes, default is 1 (which indicates a laplace smoothing) Attri...
3,662
1,101
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/graph_debug_info.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as...
9,362
3,529
import pytest from tests.test_data.lists import LIST from tests.test_data.people import MOVIE_CREDITS, PERSON, SHOW_CREDITS from tests.utils import mk_mock_client from trakt.core.exceptions import ArgumentError from trakt.core.json_parser import parse_tree from trakt.core.models import Person def test_get_person(): ...
1,376
511
#!/usr/bin/env python3 import argparse import os import sys import traceback from lib import core, utilities, run from lib.attributes import Attributes from lib.database import Database def process_arguments(): """ Uses the argparse module to parse commandline arguments. Returns: Dictionary of ...
3,717
1,048
# -*- coding: UTF-8 -*- """ Provides a summary after each test run. """ from __future__ import absolute_import, division, print_function import sys from time import time as time_now from behave.model import Rule, ScenarioOutline # MAYBE: Scenario from behave.model_core import Status from behave.reporter.base import R...
8,423
2,499
from typing import Dict, Any import pytest from checkov.common.bridgecrew.bc_source import SourceType from checkov.common.bridgecrew.platform_integration import BcPlatformIntegration, bc_integration @pytest.fixture() def mock_bc_integration() -> BcPlatformIntegration: bc_integration.bc_api_key = "abcd1234-abcd-...
2,109
809
import argparse from pathlib import Path from cv2 import cv2 from trimap import generate_trimap from trimap_output_utils import save_trimap_output def main(): args = parse_args() image_path = args.image output_directory_path = args.output image_path = Path(image_path) if not image_path.is_file(...
1,038
328
#!/usr/bin/env python # -*- coding: utf-8 -*- from http.client import OK from unittest.mock import MagicMock, patch from urllib.parse import urlencode import graphene_django.views as views from django.urls import reverse from graphql import GraphQLError from graphql.error import GraphQLLocatedError class CustomExce...
2,102
699
# coding: utf8 from __future__ import unicode_literals # The original stop words list (added in f46ffe3) was taken from # http://www.damienvanholten.com/downloads/dutch-stop-words.txt # and consisted of about 100 tokens. # In order to achieve parity with some of the better-supported # languages, e.g., English, French,...
3,137
996
''' (c) University of Liverpool 2020 Licensed under the MIT License. To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.. @author: neilswainston ''' # pylint: disable=broad-except import os.path import tempfile from liv_covid19.web.artic import opentrons from liv_covid19.web.job import JobT...
1,858
547
import logging from datetime import datetime import os logger = logging.getLogger('FT') log_level = logging.INFO is_file_log = True # 设置logger的level为DEBUG logger.setLevel(log_level) # 创建一个输出日志到控制台的StreamHandler hdr = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s [%(filename)s] %(funcName)s:...
838
313
# Copyright 2018 Esteban Collado. # # Licensed under the MIT License import tensorflow as tf DEFAULT_VARIABLE_NAMES = ['conv1', 'conv2', 'conv3', 'conv4', 'fc1', 'fc2', 'softmax_linear'] BATCH_SIZE = 200 IMAGE_WIDTH = 32 IMAGE_HEIGHT = 32 IMAGE_DEPTH = 3 NUM_CLASSES = 10 INPUT_PLACEHOLDER = 'X_INPUT' LABELS_PLACEHO...
3,946
1,536
""" The LibRoadRunner SBML Simulation Engine, (c) 2009-2014 Andy Somogyi and Herbert Sauro LibRoadRunner is an SBML JIT compiler and simulation engine with a variety of analysis functions. LibRoadRunner is a self contained library which is designed to be integrated into existing simulation platforms or may be used a s...
425
117
from classification.models import EvidenceMixin from classification.models.evidence_mixin import VCStore class BasicEvidence(EvidenceMixin): def __init__(self, evidence: VCStore): self.evidence = evidence @property def _evidence(self) -> VCStore: return self.evidence # doesn't work with...
1,573
606
import urwid from scronsole.config_manager import ConfigManager from scronsole.plugin_manager import PluginManager from scronsole.widgets.main_menu import MainMenu from scronsole.widgets.server_screen import ServerScreen class MainScreen(urwid.WidgetPlaceholder): def __init__(self): super().__init__(urwi...
674
200
import re from csv import reader def splitEscaped(str, by, escapeChar): infile = [str] return reader(infile, delimiter=by, quotechar=escapeChar) def removeComments(text): p = r'/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|\'(\\.|[^\'\\])*\'|.[^/"\'\\]*)' return ''.join(m.group(2) for m in re.finditer...
436
191
import itertools ################################################# # This function will see if there is any # # possible combination of the numbers in # # the array that will give the largest number # ################################################# def ArrayAdditionI(arr): #sort, remove last ele...
659
184
import numpy as np import quadprog def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None): """ Solve a QP of the form min 1/2xTPx + qTx st Gx < h st Ax=b""" #qp_G = .5 * (P + P.T) # make sure P is symmetric qp_G = P qp_a = -q if A is not None: qp_C = -np.vstack([A, G]).T qp_...
1,994
887
#!/usr/bin/python from ConfigUtils import getBaseConfig from LogUtils import getModuleLogger from StringUtils import isValidUrl, randomString from urlparse import urlparse import json import os import requests import sys cDir = os.path.dirname(os.path.realpath(__file__)) rootDir = os.path.abspath(os.path.join(cDir,...
1,547
443
from attempt.ddpg import HERDDPG, DDPG import gym import os import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm if __name__ == "__main__": os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' env = gym.make('FetchReach-v1') agent = HERDDPG(env) for epoch in range(2): for cycle in tq...
705
276
#!/usr/bin/env python # 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 # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # Written (W) 2008-2009 Soeren Sonnenburg # Cop...
8,187
3,524
#!/usr/bin/env python # -*- coding: utf-8 -*- # project = https://github.com/Xyntax/POC-T # author = i@cdxy.me """ Apache Solr 未授权访问PoC (iterate_path函数使用场景示例) Usage python POC-T.py -s solr-unauth -iF target.txt python POC-T.py -s solr-unauth -aZ "solr country:cn" """ from lib.verify import verify from lib.rand...
771
297
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, tools import os class RapiXMLConan(ConanFile): name = "rapidxml" version = "1.13" description = "RapidXml is an attempt to create the fastest XML parser possible" url = "https://github.com/bincrafters/conan-rapidxml" home...
1,248
440
""" Compute Dice between test ground truth and predictions from groupwise registration. """ import os import nibabel as nib import glob import numpy as np from core import utils_2d from core.metrics_2d import OverlapMetrics def one_hot_label(label, label_intensity): gt = np.around(label) n_cl...
2,772
1,184
"""Main farm access.""" from __future__ import annotations import os from datetime import datetime from typing import Dict, Iterable, Iterator, List, Type, Union from farmos_ext.area import Area from farmos_ext.asset import Asset, Equipment, Planting from farmos_ext.log import (Activity, Birth, Harvest, Input, Log, ...
14,359
4,070
''' Testing the CSV iterators ''' import responses from tenable.io.v3.base.iterators.explore_iterator import CSVChunkIterator USERS_BASE_URL = r'https://cloud.tenable.com/api/v3/assets/search' CSV_TEXT = ( 'created,display_ipv4_address,first_observed,id,' 'ipv4_addresses,ipv6_addresses,is_deleted,is_license...
2,768
1,445
def extract_stack_from_seat_line(seat_line: str) -> float or None: # Seat 3: PokerPete24 (40518.00) if 'will be allowed to play after the button' in seat_line: return None return float(seat_line.split(' (')[1].split(')')[0])
246
95
from telegram.ext import * from telegram import * import time def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="Hi 👋 I'm Rinkoglionito and I'm here because @OnyyTheBest had nothing to do ;-;. \n that said do the /cmds command to see the available commands") cha...
3,716
1,496
import os class Configuration: APPLICATION_DIR = os.path.dirname(os.path.realpath(__file__)) DEBUG = True SECRET_KEY = 'thisissecretkeyforcrypton' # change it in production !!! MONGO_DBNAME = 'cryptondb'
222
79
import nbviewerbot if __name__ == "__main__": nbviewerbot.cli()
69
30
import json import math import requests import pandas as pd def fetch_data(ids): ''' A function to fetch data from the API. Parameters: ids (list): A list of ids (integrs) to fetch Returns: text (dict): A dictionary where keys are the ids and values are the...
1,571
484
# tests/test.py from rw_data_proc.core import * import unittest def _dummyModifierFunction(row): row['adr'] = 'modified' return row['adr'] class TableTest(unittest.TestCase): def test_init(self): tb = Table('tests/test_file.csv') self.assertIsNotNone(tb) def test_add_modifier(self)...
2,305
768
from booking.models import Schedule, ParkingSpace from datetime import datetime as dt from django import forms class ReservingForm(forms.ModelForm): reserving_dates = forms.ModelMultipleChoiceField( queryset=Schedule.objects.filter(reserving_date__gte=dt.today()), widget=forms.CheckboxSelectMult...
1,496
436
# -*- coding: utf-8 -*- # Copyright 2022 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 o...
20,793
7,252
import glob import os import re import sys import time import yaml def tail(thefile, past): if not past: thefile.seek(0, 2) while True: line = thefile.readline() if not line: time.sleep(0.5) continue line = line.rstrip("\n").rstrip("\r") if line ...
1,440
458
def infer_from_clause(table_names, graph, columns): tables = list(table_names.keys()) if len(tables) == 1: # no JOINS needed - just return the simple "FROM" clause. return f"FROM {tables[0]} " else: # we have to deal with multiple tables - and find the shortest path between them join_clau...
9,032
2,729
print('Test script')
21
7
import os from .exceptions import MarkdownError, MetadataError from .file import ContentFile class ContentFolder(object): def __init__(self, path): path = os.path.abspath(path) self._path = path self._files = [] self._folders = [] for filename in os.listdir(self._path): ...
2,208
693
#! /usr/bin/python ''' Test for session module ''' import unittest import uestc_eams from .mock_server import LoginMockServer from .utils import HookedMethod, MakeResponse mock_login = LoginMockServer() class TestSession(unittest.TestCase): @mock_login.Patch def test_Session(self): self.__s...
2,327
763
from App.numeros import numeros if __name__ == "__main__": x = int(input("Ingrese el número que desea evaluar: \n")) pi = numeros(x) pi.parImpar()
159
60
# Copyright 2020 The TensorFlow Authors. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
6,950
2,166
import csv class ExperimentDataCannotBeParsedError(Exception): """ Defining custom exception type that will be thrown when something fails here """ def __init__(self, msg: str = "ERROR"): self.message = msg def __str__(self): """ Defines what to show when exception is pri...
3,928
1,073
import sys import numpy as np import scipy.integrate import scipy.special from ._dblquad import dblquad HAVE_PYGSL = False try: import pygsl.integrate import pygsl.sf HAVE_PYGSL = True except ImportError: pass class BinEB(object): def __init__( self, tmin, tmax, Nb, windows=None, linear...
23,457
7,217
import numpy as np from numpy.testing import assert_allclose, run_module_suite from fast_ndimage import ( median_filter, sobel, convolve, correlate, gaussian_filter, gaussian_filter1d, uniform_filter, uniform_filter1d) def test_median_filter(): rtol = atol = 1e-7 shape = (63, 64) rstate = np.rando...
9,945
3,578
import sys from itertools import count, islice def sequence(): """Generate Recaman's sequence""" seen = set() a = 0 for n in count(1): yield a seen.add(a) c = a - n if c < 0 or c in seen: c = a + n a = c def write_sequence(num): """Write Recama...
628
225
import unittest from unittest.mock import mock_open, patch from aoc.d8.main import metadata_sum, supervalue DATA = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2\n" class TestCase(unittest.TestCase): def test_metadata_sum(self): with patch("builtins.open", mock_open(read_data=DATA)): self.assertEqual(...
533
200
import stko import pytest try: from openbabel import openbabel except ImportError: openbabel = None def test_open_babel_energy(unoptimized_mol): if openbabel is None: with pytest.raises(stko.WrapperNotInstalledException): calculator = stko.OpenBabelEnergy('uff') else: ca...
955
358
from rest_framework import status from rest_framework.response import Response from rest_framework.generics import GenericAPIView from ..permissions import IsAuthenticated from django.core.cache import cache from django.conf import settings from ..authentication import TokenAuthentication from ..app_settings import (...
1,773
528
from allennlp.common import Params from allennlp.data import Instance, Token, Batch from allennlp.data.fields import TextField from allennlp.data.samplers import BucketBatchSampler from allennlp.data.data_loaders import MultiProcessDataLoader from .sampler_test import SamplerTest class TestBucketSampler(SamplerTest)...
5,350
1,597
import batoid import numpy as np import math from test_helpers import timer, do_pickle, all_obj_diff @timer def test_properties(): import random random.seed(5) for i in range(100): R = random.gauss(0.7, 0.8) sphere = batoid.Sphere(R) assert sphere.R == R do_pickle(sphere) ...
3,332
1,361
from django.http.response import HttpResponseForbidden from .models import Counter, VisitLog from .utils import get_client_ip class SiteStatistics(object): visit_log = None def process_request(self, request): if request.path_info.startswith('/admin/'): return counter = Counter.o...
2,678
838
# # Copyright (c) 2019-2022, NVIDIA CORPORATION. # # 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 ag...
1,753
612
from .utils import TestCase from .utils import build_and_test_module from .utils import transpile_source class Test(TestCase): def test_compare(self): with self.assertRaises(SystemExit): build_and_test_module('compare') def test_assert_between(self): self.assert_transpile_raises(...
8,175
2,807
from epidemioptim.environments.cost_functions.costs.death_toll_cost import DeathToll from epidemioptim.environments.cost_functions.costs.gdp_recess_cost import GdpRecess
170
62
"""70 · Binary Tree Level Order Traversal II""" """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A tree @return: buttom-up level order a list of lists of integer """ def le...
1,587
448
import typing import requests from urllib.parse import urlencode from .abstract_client import AbstractClient from yuque_py.exceptions.request_error import RequestError class Client(AbstractClient): api_host: str user_token: str def __init__(self, api_host: str, user_token: str) -> None: self.ap...
2,554
743
from dry_rest_permissions.generics import DRYPermissions from rest_framework import viewsets from results.models.sports import Sport from results.serializers.sports import SportSerializer class SportViewSet(viewsets.ModelViewSet): """API endpoint for sports. list: Returns a list of all the existing spor...
671
191
import unittest import os from pathlib import Path import numpy as np path = Path.cwd().parent.parent os.chdir(path) from pvsystemprofiler.utilities.equation_of_time import eot_da_rosa, eot_duffie class TestEquationOfTime(unittest.TestCase): # importing input for both eot tests filepath = Path(__file__).pare...
1,332
463
from raiden.constants import EMPTY_MERKLE_ROOT from raiden.tests.utils.factories import HOP1, HOP2, UNIT_SECRETHASH, make_block_hash from raiden.transfer.events import ContractSendChannelBatchUnlock from raiden.transfer.node import is_transaction_effect_satisfied from raiden.transfer.state_change import ContractReceive...
1,942
573
# Copyright 2019 Google LLC. 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
2,826
905
import configparser import requests from bs4 import BeautifulSoup def getAccessToken(): config = configparser.ConfigParser() config.read('config.ini') return config['Client_Access_Token']['token'] token = getAccessToken() def searchMusicArtist(name): api_url = "https://api.genius.com/search?q={}".for...
1,870
643