text
string
size
int64
token_count
int64
from unittest import mock import critiquebrainz.db.users as db_users from critiquebrainz.db.user import User from critiquebrainz.frontend.testing import FrontendTestCase class UserViewsTestCase(FrontendTestCase): def setUp(self): super(UserViewsTestCase, self).setUp() self.user = User(db_users.g...
3,747
1,207
from tests.utils import W3CTestCase class TestBlockFormattingContexts(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'block-formatting-contexts-'))
168
58
DEBUG = True DB_HOST = "host" DB_USER = "user" DB_PASSWORD = "password1" DB_DATABASE = "database" SESSION_LIMIT = 5 UPLOAD_FOLDER = "static/uploads/" SECRET_KEY = "FSDFF"
171
74
#ex024: Crie um programa que leia o nome de uma cidade diga se ela comeΓ§a ou nΓ£o com o nome β€œSANTO”. cidade = str(input('Em qual cidade vocΓͺ nasceu?\n')).strip() print(cidade[:5].capitalize() == 'Santo')
205
76
# Read Total profit of all months and show it using a line plot import matplotlib.pyplot as plt # My Solution import pandas as pd data = pd.read_csv("company_sales_data.csv") plt.plot(data.month_number, data.total_profit) plt.title("Company profit per month") plt.xticks(range(1, 13)) plt.yticks([100000, 200000, 3000...
887
365
import tensorflow as tf import argparse import sys sys.path.append('../') from cnn import CNN from tensorflow.examples.tutorials.mnist import input_data def main(action, name): mnist = input_data.read_data_sets("../MNIST_data/", one_hot=True) action = [int(x) for x in action.split(",")] training_epochs = 1...
2,410
823
from thebutton.loader import load_all_challenges import os def test_all_challenges_load(): for challenge in load_all_challenges(os.path.join(os.path.dirname(os.path.dirname(__file__)), "challenges"), True): pass
226
76
# pure-python package, this can be removed when we'll support any python package from toolchain import PythonRecipe class PlyerRecipe(PythonRecipe): version = "master" url = "https://github.com/kivy/plyer/archive/{version}.zip" depends = ["python", "pyobjus"] archs = ["i386"] recipe = PlyerRecipe()
320
108
# coding=utf-8 from setuptools import find_packages from setuptools import setup setup( name="pybotic", version="0.0.1", description="pyBot", packages=find_packages(), classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Science/Research", "License :: O...
776
240
from flask import session, redirect, request import os import base64 import re import urllib.parse from flask.app import Flask import requests import hashlib from requests_oauthlib import OAuth2Session os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" def make_code_challenge(length: int = 40): code_verifier = base...
4,133
1,292
# -*- coding: utf-8 -*- # (C) Copyright Ji Liu and Luciano Bello 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or ...
5,753
2,033
from BPTK_Py import Agent from BPTK_Py import log class Task(Agent): def initialize(self): self.agent_type = "task" self.state = "open" self.set_property("remaining_effort", {"type": "Double", "value": 0}) self.register_event_handler(["open"], "task_started", self.handle_started...
758
251
import math import re from functools import reduce from collections import namedtuple from .point import Point from .meta import TILE_SIZE BaseTile = namedtuple('BaseTile', 'tms_x tms_y zoom') class Tile(BaseTile): """Immutable Tile class""" @classmethod def from_quad_tree(cls, quad_tree): """C...
4,458
1,651
import duckdb import os try: import pyarrow import pyarrow.parquet can_run = True except: can_run = False class TestArrowReads(object): def test_multiple_queries_same_relation(self, duckdb_cursor): if not can_run: return parquet_filename = os.path.join(os.path.dirname(os...
857
298
import pymongo from app import config def main(): # initialize a database db_name = config.DATABASE_NAME col_name = config.BOOK_COLLECTION client = pymongo.MongoClient("mongodb://localhost:27017/") db = client[db_name] col= db[col_name] col.insert_one({ 'title': '<seeder-bo...
899
317
import time class TimeLimitGenerator: def __init__(self, time_limit_seconds, func): self._time_limit = time_limit_seconds self._func = func def get_counter(self): return self._counter def __iter__(self): self._counter = 0 self._start_time = time.time() sel...
790
233
#!/usr/bin/env python from flask import Flask, render_template, url_for from optparse import OptionParser import os app = Flask(__name__) @app.route('/') def index(): return render_template('via.html') if __name__ == '__main__': parser = OptionParser(usage='Usage: %prog [options]') parser.add_option('-l...
932
339
import glob import itertools import os import sys from setuptools import setup, Extension from setuptools.command.build_ext import build_ext as _build_ext from setuptools.command.install import install as _install DIR = os.path.dirname(__file__) with open("README.md", "r") as fh: long_description = fh.read() ...
3,104
990
import re SERIES_SEPARATOR_GROUP_REGEX = '( ?[eE]| ?[xX])' SERIES_GROUPS_REGEX = r'([0-9]+){}([0-9]+)'.format(SERIES_SEPARATOR_GROUP_REGEX) class SeriesFilenameParser: def __init__(self, filename): pattern = re.compile(SERIES_GROUPS_REGEX) matched_pattern = pattern.search(filename) self....
546
201
##code for SMALL testcase begins here DP = [[0 for j in range(501)] for k in range(501)] DPp = [[0 for j in range(501)] for k in range(501)] #summation = 51 rbs = [] for i in range(35): for j in range(35): if i>0 or j>0: rbs.append((i,j)) for i in range(len(rbs)): red, blue = rbs[i] f...
1,159
478
class Expr(object): def accept(self, visitor): method_name = "visit_{}".format(self.__class__.__name__.lower()) visit = getattr(visitor, method_name) return visit(self) class Int(Expr): def __init__(self, value): self.value = value class Add(Expr): def __init__(self, left...
490
154
import pytest from c4cds.regridder import Regridder, GLOBAL, REGIONAL from .common import C3S_CMIP5_NC, CORDEX_NC, C3S_CMIP5_ARCHIVE_BASE, CORDEX_ARCHIVE_BASE, resource_ok def test_create_output_dir(): regridder = Regridder() assert 'out_regrid/1_deg' in regridder.create_output_dir(domain_type=GLOBAL) a...
2,083
879
# Generated from Comments.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .CommentsParser import CommentsParser else: from CommentsParser import CommentsParser # This class defines a complete generic visitor for a parse tree produced by CommentsParser. class CommentsVisi...
930
256
# MIT License # Copyright (c) 2020 Netherlands Film Academy # 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, modi...
15,345
4,195
import asyncio from userbot import CmdHelp, bot from userbot.cmdhelp import CmdHelp from userbot.utils import admin_cmd, sudo_cmd CmdHelp("detail").add_command("detailed", None, "help to get detail of plugin").add() @bot.on(sudo_cmd(pattern="detailed ?(.*)", allow_sudo=True)) @bot.on(admin_cmd(pattern="detailed ?(....
929
321
import logging import logconfig logconfig.logconfig(filename=None) logconfig.loglevel(logging.INFO) import squaregrid from discdiff import * import pytest @pytest.mark.filterwarnings("ignore:the matrix subclass") def test_discdiff(): '''Create and print finite difference derivative matrices for a small square gri...
587
179
from . import * from ..utils import * @torch.no_grad() def show_img(self, bar=None): ds = self.data[1].dataset self.model.eval() idx = np.random.randint(len(ds)) img, mask = ds[idx] pred = self.model(img.unsqueeze(0).cuda())[0].detach().cpu() pred = torch.sigmoid(pred).numpy() img_pred...
2,345
952
__version__ = '0.1.0' from kgtk.node_matcher import NodeMatcher from kgtk.graph_manager import GraphManager
110
41
import pygame from .. import utils from ..states.State import State from ..utils.Scroller import Scroller from ..utils import pygame_utils offsety = pygame_utils.Calc.centerY(utils.screen['fontsize']) offsetx = pygame_utils.Calc.centerX(10) class Confirm(State): def __init__(self, stack, question, succe...
1,408
428
import struct import cmath from array import array # DONE co.w defines if is movable, set 1 for root # DONE increase sintel scale # TODO wmtx? # TODO check if conversion to mesh is required # TODO remove tmp object HEADER_SIZE_BYTES = 160 def debug(*argv): print('[DEBUG]', ' '.join([str(x) for x in argv])) def to...
7,275
2,678
from __future__ import print_function import sys from collections import Counter from operator import itemgetter def main(): cut = 10 counter = Counter() with open(sys.argv[1], 'r') as f: for line in f: for word in line.split(): counter[word] += 1 for word, count i...
475
147
# coding=utf-8 """CIFAR 100 Dataset CNN classifier.""" from keras.datasets import cifar100 from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.optimizers import Adam...
2,258
926
def addition(x, y): result = x result += y return result def substraction(x, y): result = x result -= y return result def divisionQ(x, y): result = x result = int(result / y) return result def divisionR(x, y): result = x result = int(result % y) ...
3,292
949
import pandas as pd #Import data HDNames= ['age','sex','cp','trestbps','chol','fbs','restecg','thalach','exang','oldpeak','slope','ca','hal','HeartDisease'] Data = pd.read_excel('Ch3.ClevelandData.xlsx', names=HDNames) print(Data.head(20)) print(Data.info()) summary = Data.describe() print(summary) #Removing missi...
2,610
938
#!/usr/bin/python """ Basic usage of module for use with debugger """ from comlocal.core import Com import json import pdb pdb.set_trace() com = Com.Com() com.write(json.loads('{"type": "msg", "payload": "Hello world!"}')) print com.read()
242
85
from flask_wtf import FlaskForm from wtforms import StringField, SelectField, IntegerField, DateField, FileField, SubmitField, TextAreaField from wtforms.validators import DataRequired, Length # classe form registrazione annuncio from wtforms.widgets import TextArea class RegistrationFormAnnuncio(FlaskForm): tit...
4,935
1,654
import pytest from threading import Thread from yellowdog_client.object_store.utils import MemoryMappedFileWriterFactory class TestMemoryMappedFileWriter(object): @pytest.fixture def file_path(self, tmpdir): p = tmpdir.mkdir("sub").join("writter.txt") return str(p) def write(self, writer,...
1,213
407
from django.db import models from django.db.models import Q, QuerySet, F from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from collective_blog import settings from collective_blog.utils.errors import PermissionCheckFailed from s_markdown.models import MarkdownField, HtmlCacheF...
18,293
4,997
# coding: utf-8 """ Copyright 2016 SmartBear Software 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...
7,152
1,993
frequent_short_words_by_language = { "en": { 1: ["a", "i"], 2: ["am", "an", "as", "at", "be", "by", "do", "go", "he", "if", "in", "is", "it", "me", "mr", "my", "no", "of", "oh", "ok", "on", "or", "PM", "so", "to", "tv", "up", "us", "we"], 3: ["act", "add", "age", "ago", "air", "a...
10,828
3,754
from servers.key_value_store.store import KeyValueStoreBase NAMESPACES = dict() import re class MemoryKeyValueStore(KeyValueStoreBase): def __init__(self, name=None, namespace=None): self.name = name if namespace: self.db = NAMESPACES.setdefault(namespace, dict()) else: ...
2,453
709
# # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import numpy as np from torch import nn, Tensor import math import torch from torch.nn import functional as F from typing import Optional, Dict, Tuple, Union, Sequence from .transformer import TransformerEncoder, L...
25,611
8,741
"""Interaction with Cosmos DB through CLI.""" import os from pathlib import Path import click import pandas as pd from fpl.data.cosmos import ElementsInserter @click.group(help="Procedures to interact with Azure Cosmos DB", name="cosmos") @click.option("--uri", "-u", type=str, default=None) @click.option("--token",...
1,782
591
"""Contains functionality for interfacing with the database.""" import os import uuid import bcrypt import mysql.connector def connect_db(): """Create a connection to MariaDB.""" dbconnection = mysql.connector.connect( host=os.environ['MARIADB_IP'], user=os.environ['MARIADB_USER'], pas...
5,290
1,514
import spdx_lookup from conans.client import conan_api from conans.errors import ConanException def check_license(main, recipe_license): if spdx_lookup.by_id(recipe_license): main.output_result_check(passed=True, title="SPDX License identifier") return True else: main.output_result_che...
1,482
417
from django.db import models from django.core.validators import MinValueValidator,MaxValueValidator from django.db.models import Avg import math from cloudinary.models import CloudinaryField from account.models import Account # Create your models here. class Project(models.Model): """This defines the behaviours o...
2,160
648
from ._Administrator import _Administrator
43
13
class MongoObject: # Common base class for all mongo objects def __init__(self, id, user_name, list_name, beverages, display_name=None, image_url=None): self.id = id self.user = user_name self.list = list_name self.displayName = display_name self.imageUrl = image_url ...
416
123
import os,sys import numpy as np from .. import pg from .. import QtGui from ..lib.roislider import ROISlider class LabelingTool: """ Class holding labeling functions. This class is a state machine that modifies a ImageItem stored in a PlotItem. states: uninitiated: not yet worked with an image....
22,172
6,638
# pad.py Extension to lcd160gui providing the invisible touchpad class # Released under the MIT License (MIT). See LICENSE. # Copyright (c) 2020 Peter Hinch # Usage: import classes as required: # from gui.widgets.pad import Pad import uasyncio as asyncio from micropython_ra8875.py.ugui import Touchable from micropy...
1,750
558
from typing import List, Optional, TYPE_CHECKING from padinfo.view.materials import MaterialsViewState from padinfo.view.monster_list.monster_list import MonsterListViewState if TYPE_CHECKING: from dbcog.models.monster_model import MonsterModel class AllMatsViewState(MonsterListViewState): VIEW_STATE_TYPE =...
947
307
import importlib import inspect import numpy as np import pytest import pySOT.optimization_problems from pySOT.optimization_problems import OptimizationProblem from pySOT.utils import check_opt_prob def test_all(): module = importlib.import_module("pySOT.optimization_problems") for name, obj in inspect.getm...
988
299
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Base test case class to bootstrap application testing. Code downloaded from: http://github.com/rzajac/gaeteststarter @author: Simon Ndunda: Modified to add support for deferred tasks @author: Rafal Zajac rzajac<at>gmail<dot>com @copyright: Copyright 2007-2013 Rafal Z...
16,686
4,832
# -*- coding: utf-8 -*- """ Created on Thu Jul 25 09:35:28 2019 @author: anael """ import os import sys sys.path.insert(0, '/home/rpviz/') from smile2picture import picture,picture2 from smarts2tab import smarts2tab def csv2list2(csvfolder,path,datapath,datainf,selenzyme_table): name=str(path) ...
3,558
1,319
import numpy as np from abc import ABC, abstractmethod class QeBase(ABC): def __init__(self, vectors, ranking, config): vectors = vectors / np.expand_dims(np.linalg.norm(vectors, axis=1), axis=1) self.vectors = vectors self.ranking = ranking ...
470
136
import pytest from antidote.core import DependencyContainer from antidote.exceptions import DuplicateDependencyError from antidote.providers.factory import Build, FactoryProvider class Service: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class AnotherService(Servi...
3,981
1,154
"""Authors: Cody Baker, Ben Dichter and Luiz Tauffer.""" import inspect from datetime import datetime import numpy as np import pynwb def get_base_schema(tag=None): base_schema = dict( required=[], properties={}, type='object', additionalProperties=False ) if tag is not No...
8,384
2,346
from .checkpoint import save_best_model, save_model from .config import load_config from .jsonutil import save_json from .logger import get_logger from .meter import AverageMeter from .parser import get_parser from .seed import set_seed
237
66
from human_readable_error import HumanReadableError
52
15
num_processes_evaluate=4 midi_folder="Data/Midi" text_folder="Data/Text" random_seed_noisyuser=42
97
41
#!/usr/bin/env python3 # The Luhn algorithm https://www.geeksforgeeks.org/luhn-algorithm/ s = "543210******1234" def luhn(s): ret = 0 for i in range(len(s)-2, -1, -2): a = int(s[i]) * 2 if a > 9: a = a//10 + a%10 ret += a ret += sum([int(s[i]) for i in range(len(s)-1, ...
501
241
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @version: ?? @author: xiaoming @license: MIT Licence @contact: xiaominghe2014@gmail.com @site: @software: PyCharm @file: base_define.py @time: 2017/12/19 δΈ‹εˆ12:11 """ import const as xreg xreg.repeat_0_or_more = '*' xreg.repeat_1_or_more = '+' xreg.repeat_0_or_1 = '?' x...
1,312
575
""" legacyhalos.integrate ===================== Code to integrate the surface brightness profiles, including extrapolation. """ import os, warnings, pdb import multiprocessing import numpy as np from scipy.interpolate import interp1d from astropy.table import Table, Column, vstack, hstack import legacyhalos.io ...
9,258
3,495
from django.http import response from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework import filter...
4,251
1,185
#!/usr/bin/env python3 from v4l2 import * import logging import fcntl import mmap import select import time import cv2 import numpy logger = logging.getLogger("grabber") class Grabber(object): def __init__(self, device, fps=30, exposure=None, gain=None, saturation=None, name=None, vflip=False, hflip=False): ...
8,251
3,172
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020-2021 Alibaba Group Holding Limited. # # 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/LI...
8,430
2,559
import asyncio import os import asyncpg def pytest_configure(): # environment should be set before importing os.environ['PG_DATABASE'] = 'slogan_test' from server.client_manager import ClientManager from server.const import PG_USERNAME, PG_PASSWORD from server.slogan_manager import SloganManager...
734
224
import os import multiprocessing from multiprocessing import Pool from pathlib import Path import numpy as np from openeye import oechem, oeomega, oeshape, oequacpac from reinvent_scoring.scoring.component_parameters import ComponentParameters from reinvent_scoring.scoring.enums import ROCSSimilarityMeasuresEnum, ROC...
8,101
2,601
# coding=utf-8 # Copyright 2018 The Tensor2Tensor 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
4,214
1,265
""" An emulation module to detect SEH setup and apply structs where possible. """ import vivisect.vamp.msvc as v_msvc vs = v_msvc.VisualStudioVamp() def analyzeFunction(vw, funcva): offset, bytes = vw.getByteDef(funcva) sig = vs.getSignature(bytes, offset) if sig is not None: fname = sig.split...
445
168
from builtins import range from cosmosis.postprocessing.plots import Tweaks import pylab class ThinLabels(Tweaks): #The file to which this applies filename=["2D_cosmological_parameters--omega_b_cosmological_parameters--hubble", "2D_cosmological_parameters--yhe_cosmological_parameters--omega_b", ...
578
191
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # lock().acquire() # ____________developed by paco andres____________________ # _________collaboration with cristian vazquez____________ from node.libs.gpio.Platform import HARDWARE if HARDWARE == "RASPBERRY_PI": import RPi.GPIO as GPIO # Modes BCM = GPIO.BCM...
2,624
1,192
""" TODO """ import torch import torch.nn.functional as F def fgsm_attack(model: torch.nn.Module, image: torch.tensor, label: torch.tensor, epsilon: float, **kwargs) -> torch.tensor: """ Fast Gradient Sign Method Attack, no target class """ model.eval() image.grad = None image.requires_grad ...
3,876
1,399
#from django.conf import settings #settings.DEBUG = True from testcases import ( TestServerTestCase, get_client ) from django.core.management import call_command class ForeignkeyTestCase(TestServerTestCase): def setUp(self): self.start_test_server() self.client = get_client() call...
1,158
349
import os import sys sys.path.insert(1, "examples/multiworker") from automatic import discord def on_starting(server): print("registering commands!") discord.update_commands(guild_id=os.environ["TESTING_GUILD"])
224
74
#!/usr/bin/env python3 """ Evaluate citation extracting """ from sklearn.metrics import confusion_matrix, classification_report __author__ = "William A. Ingram" __version__ = "0.1.0" __license__ = "BSD3" def main(): """ """ filename = '../results/npc_analysis.txt' f = open(filename, 'r') labels = ...
1,042
338
from sklearn.model_selection import train_test_split def my_function(): print('hello world') def ira_split_version(X, y): X_train, X_val, y_train, y_val = train_test_split( X, y, train_size=0.5, test_size=0.5, random_state=42) print("X_train:", X_train.shape) print("X_val:", X_val.shape) ...
535
222
from datetime import datetime, timedelta import time __all__ = ['get_datetime'] def get_datetime(utc0_time, delta=0): d = datetime.fromtimestamp(utc0_time) + timedelta(seconds=int(delta)) utc8 = datetime.fromtimestamp(time.mktime(d.timetuple())) return utc8
273
97
import collections import contextlib import datetime import functools import itertools import os import unittest from unittest import mock from django.core import mail from django.core.management import call_command from faker import Faker from credit.constants import LOG_ACTIONS as CREDIT_ACTIONS from credit.models ...
14,403
4,821
import json import bson import pymongo from pymongo import MongoClient from collections import defaultdict from polygon_rest import RESTClient import datetime import pandas as pd from pandas.io.json import json_normalize import quantlplot as qplt from functools import lru_cache from PyQt5.QtWidgets import QApplication,...
3,833
1,360
from pathlib import Path import pytest from pyfcopy import index, merge from pyfcopy_test.index_assertions import assert_same_index def test_empty(tmp_path: Path): (tmp_path / "source").mkdir() (tmp_path / "target").mkdir() merge(tmp_path / "source", tmp_path / "target") assert_same_index(index(...
3,497
1,317
from typing import Any, Dict import netaddr from core.config import Configuration from core.configservice.base import ConfigService, ConfigServiceMode from core.emulator.enumerations import ConfigDataTypes GROUP_NAME = "Security" class VpnClient(ConfigService): name = "VPNClient" group = GROUP_NAME dir...
3,661
1,079
#!/usr/bin/env python # Copyright (c) 2020 Carnegie Mellon University # # 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...
4,977
1,751
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: messaging.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol...
10,585
3,935
class UserRegistry: def __init__(self): self.user_list = list() self.user_sessions = dict() def user_online(self, uuid): print('user_online: ', uuid) if not self.user_list.__contains__(uuid): self.user_list.append(uuid) def user_offline(self, uuid): pr...
1,313
411
import pkg_resources # this comes from setuptools try: __version__ = pkg_resources.get_distribution('PhiSpy').version except Exception: __version__ = 'unknown'
169
52
''' Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] EMBL-European Bioinformatics Institute 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...
1,475
421
from io import StringIO import pytest from dbeditor.loaders.csv_loader import CSVLoader ANSWER = [{"a": "a", "b": "123", "c": "b"}, {"a": "c", "b": "456", "c": "d"}] INPUT = "a,b,c\n" + "\n".join(map(lambda x: ",".join(x.values()), ANSWER)) @pytest.fixture def loader() -> CSVLoader: data = StringIO(INPUT) r...
450
187
from django.urls import path, include from rest_framework.routers import DefaultRouter from recipe.views import TagListAPI, TagCreateAPI # router = DefaultRouter() # router.register('tags', views.TagListAPI) app_name = 'recipe' urlpatterns = [ path('tag/list/', TagListAPI.as_view(), name="list-tag"), path('...
379
123
import json from constants.status import TransactionVisibility, TransactionOperation, TransactionStatus, \ ConversionTransactionStatus, ConversionStatus from infrastructure.models import BlockChainDBModel, TokenDBModel, TokenPairDBModel, ConversionFeeDBModel, \ ConversionTransactionDBModel, ConversionDBModel, ...
21,843
7,131
class WrongInputException(Exception): msg = 'Wrong trigger. This is not a {}.' def __init__(self, trigger_type): super(WrongInputException, self).__init__( self.msg.format(trigger_type) )
227
71
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import os import cython_gsl from pycodeexport.codeexport import C_Code from symneqsys.codeexport import BinarySolver, NEQSys_Code class GSL_Code(NEQSys_Code, C_Code): build_files = [ 'solvers.c', 'pre...
1,858
699
from .auth import auth_blueprint from .websockets import websockets_blueprint
77
22
# second python test # write via GNU nano MacBook Pro MMartin n = 10 for i in range(n): print(i)
101
41
""" Module containing functions to calculate routes via the Google Maps API, and return the total number of miles on the route. """ import os import googlemaps import requests from bs4 import BeautifulSoup def get_maps_data(start_point: str, end_point: str, api_key: str=None) -> str: """ """ ...
2,024
706
/home/runner/.cache/pip/pool/ef/22/d6/cd08f5efd127c77a49f15d5c0c30b378b30531df5725794afa2653ab96
96
73
# -*- coding: utf-8 -*- import re import numpy as np from qeinputparser import ( QeInputFile,parse_namelists,parse_atomic_positions, parse_atomic_species,parse_cell_parameters, RE_FLAGS ) from aiida.orm.data.array.kpoints import KpointsData from aiida.common.exceptions import ParsingError from qeinput...
1,786
532
from .Linear import Linear
27
7
import base64 import signal import subprocess import typing from io import BytesIO import PIL import cv2 import gevent import numpy as np import zerorpc from PIL import Image import predictor_module from from_internet_or_for_from_internet import PNP_solver as PNP_solver from utilities import get_world_to_camera_matri...
9,828
3,515
class EventDescriptor(MemberDescriptor): """ Provides information about an event. """ def AddEventHandler(self, component, value): """ AddEventHandler(self: EventDescriptor,component: object,value: Delegate) When overridden in a derived class,binds the event to the component. c...
2,425
729