text string | size int64 | token_count int64 |
|---|---|---|
import moonleap.resource.props as P
from moonleap import create, extend
from moonleap.utils.case import kebab_to_camel, sn
from moonleap.verbs import has
from titan.django_pkg.djangoapp import DjangoApp
from .resources import AppModule # noqa
@create("app:module")
def create_app_module(term):
module = AppModule... | 515 | 176 |
# Copyright 2020 Cisco Systems, Inc.
# 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 la... | 11,437 | 3,577 |
import pytest
from principal import somar
from principal import sub
def test_somar():
assert somar(2,4) == 6
def test_sub():
assert sub(3,2) == 20 ... | 23,041 | 1,493 |
from PIL import Image
from PIL import ImageChops
import pathlib
import sys
sys.path.append(str(pathlib.Path(__file__).parent.absolute()))
import TextureConversionMain as tcm
def Convert(normPath):
# setup
ogNorm = Image.open(normPath)
normTuple = tcm.SplitImg(ogNorm)
print("Images Loaded... | 1,042 | 397 |
__author__ = 'Ehsan'
from mininet.node import CPULimitedHost
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel, info
from mininet.node import RemoteController
from mininet.cli import CLI
"""
Instructions to run the topo:
1. Go to directory where this fil is.
2. ru... | 1,695 | 651 |
#!/usr/bin/python3
# INTEL CONFIDENTIAL
# Copyright 2018-2020 Intel Corporation
# The source code contained or described herein and all documents related to the
# source code ("Material") are owned by Intel Corporation or its suppliers or
# licensors. Title to the Material remains with Intel Corporation or its
# suppl... | 5,806 | 1,484 |
"""Create wave training data.
Automatically annotate data by identifying waves. The begining,
middle and ending are obtained. Windows around these points are
collected as training data. They are organized in years.
"""
import sys, glob, os
path = os.getcwd()
sys.path.insert(0, ".")
from datetime import datetime
from v... | 4,301 | 1,623 |
import time
from neopixel import Adafruit_NeoPixel
import argparse
# Pixel class corresponds to a light strip
# It stores the strip, characteristics, and state
class Pix:
# LED strip configuration:
LED_COUNT = 594 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 ... | 1,087 | 398 |
__version__ = '3.6.0.1'
| 24 | 15 |
import sublime
from ..SublimeCscope import PACKAGE_NAME
SETTING_DEFAULTS = {
'index_file_extensions': [
".c",
".cc",
".cpp",
... | 1,730 | 417 |
import os
import re
from string import letters
import random
import hashlib
import hmac
import webapp2
import jinja2
from jinja2 import Environment
from google.appengine.ext import db
from utils.Utils import Utils
from models.Comment import Comment
from models.Post import Post
from models.User import User
from han... | 1,393 | 428 |
import ast, _ast, subprocess, os, argparse
def write_files(app_name):
models = {}
# parse models.py
with open('%s/models.py' % app_name) as models_file:
m = ast.parse(models_file.read())
for i in m.body:
if type(i) == _ast.ClassDef:
models[i.name] = {}
... | 5,784 | 1,768 |
from abc import ABC, abstractmethod
from typing import Callable
class PluginBase(ABC):
def __init__(self, *, name: str, port: int) -> None:
self._name = name
self._port = port
self._latest_action = "off"
def __getattribute__(self, name: str) -> Callable:
if name in ("on", "off... | 1,188 | 361 |
import sys
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from .forms import SearchForm
from .models import Search
def home(request):
if request.POST:
arrTweets = getTweets(request.POST['search'])
print arrTwe... | 2,038 | 920 |
from datetime import datetime
from calendar import timegm
from rest_framework_jwt.compat import get_username, get_username_field
from rest_framework_jwt.settings import api_settings
def jwt_otp_payload(user, device = None):
"""
Opcionalmente inclui o Device TOP no payload do JWT
"""
username_field = ... | 975 | 315 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 15 18:36:44 2021
@author: aiswarya
"""
#import sys
#sys.path.append('/home/aiswarya/bayesvp')
from bayesvp.scripts import bvp_write_config as wc
from bayesvp.scripts import bvp_process_model as pm
from bayesvp.scripts import bvpfit as fit
from baye... | 1,361 | 507 |
"""
This script load and tally the result of UCF24 dataset in latex format.
"""
import os
import json
def run_exp(cmd):
return os.system(cmd)
if __name__ == '__main__':
base = '/mnt/mercury-alpha/ucf24/cache/resnet50'
modes = [['frames',['frame_actions', 'action_ness', 'action']],
['video',... | 3,781 | 1,123 |
# -*- coding: utf-8 -*-
"""
author:wnl
date: 2018-12-7
"""
import os
from sayhello import app
dev_db = 'mysql+pymysql://root:root.123@192.168.100.105:3306/sayhello2'
SECRET_KEY = os.getenv('SECRRET','secret string')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI',dev_db)... | 322 | 162 |
"""
===============
=== Purpose ===
===============
Downloads wiki access logs and stores unprocessed article counts
See also: wiki.py
Note: for maximum portability, this program is compatible with both Python2 and
Python3 and has no external dependencies (e.g. running on AWS)
=================
=== Changelog ===
=... | 10,325 | 3,421 |
# write_results_to_file
def test_write_results_to_file_interface():
"""
is the basic file writter wraper working as indended
"""
from aiida_fleur.tools.io_routines import write_results_to_file
from os.path import isfile, abspath
from os import remove
#import os
from numpy import array... | 1,166 | 408 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app import db, viz, eligibility, metrics, geocode
app = FastAPI(
title='DS API - Family Promise',
docs_url='/',
version='0.39.6',
)
app.include_router(db.router, tags=['Database'])
app.include_router(viz.router, tags=['V... | 851 | 296 |
"""
Take a directory of images and their segmentation masks (which only contain two classes - inside and outside)
and split the inside class into black and white. Save the resulting masks.
"""
import argparse
import os
import numpy as np
import cv2
def show(img):
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
c... | 2,033 | 781 |
import uuid
import unittest
import warnings
import json
from syngenta_digital_dta.elasticsearch.es_connector import ESConnector
from tests.syngenta_digital_dta.elasticsearch.mocks import MockESAdapter
class ESConnectorTest(unittest.TestCase):
def setUp(self, *args, **kwargs):
warnings.simplefilter('ignor... | 1,097 | 326 |
from typing import List, Dict
from collections import defaultdict
from pathlib import Path
from util import save_dataset, save_word_dict, save_embedding
import torch
import argparse
import nltk
import re
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(level... | 6,293 | 2,235 |
#!/usr/bin/env python
# Convert text and standoff annotations into CoNLL format.
import re
import sys
from pathlib import Path
# assume script in brat tools/ directory, extend path to find sentencesplit.py
sys.path.append(str(Path(__file__).parent))
sys.path.append('.')
from sentencesplit import sentencebreaks_to_... | 9,422 | 2,997 |
import pandas as pd
import numpy as np
import warnings
import os
from torch.utils.data.dataset import Dataset
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
warnings.simplefilter('ignore', Image.DecompressionBombWarning)
class CustomDatasetFromImages(Dataset):
def __init__(self, fine_data, coarse_data, tran... | 5,509 | 1,791 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
import unittest
import yaml
from datemike import ansible, base, utils
from datemike.providers import rackspace
desired_task_yaml = """name: Create Cloud Server(s)
rax:
exact_count: true
flavor: performance1-1
image: image-ubuntu-... | 6,236 | 1,974 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import re
import json
import requests
def get_number_of_citations(url):
r = requests.get(url)
try:
r.raise_for_status()
except Exception as e:
print(e)
return None
results = re.finda... | 1,100 | 362 |
import sqlalchemy as sa
import datetime
from haminfo.db.models.modelbase import ModelBase
class Request(ModelBase):
__tablename__ = 'request'
id = sa.Column(sa.Integer, sa.Sequence('request_id_seq'), primary_key=True)
created = sa.Column(sa.Date)
latitude = sa.Column(sa.Float)
longitude = sa.Col... | 1,451 | 468 |
# Created by Kelvin_Clark on 3/3/2022, 4:58 PM
from src import database as db
class User(db.Model):
__tablename__ = "users"
username: str = db.Column(db.String(200).with_variant(db.Text, "sqlite"), unique=True, primary_key=True)
email: str = db.Column(db.String(200).with_variant(db.Text, "sqlite"), unique... | 720 | 246 |
# 2019-04-24
# John Dunne
# Box plot of the data set
# pandas box plot documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html
print("The box plot will appear on the screen momentarily")
import matplotlib.pyplot as pl
import pandas as pd
# imported the libraries needed an... | 1,166 | 368 |
# Generated by Django 2.1.7 on 2019-06-08 21:37
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Player',
fields=[
('id', models.AutoField(a... | 2,677 | 667 |
import asyncio as _asyncio
import os as _os
from unittest import SkipTest, expectedFailure, skip, skipIf, skipUnless # noqa
from asynctest import TestCase as _TestCase
from asynctest import _fail_on
from tortoise import Tortoise as _Tortoise
from tortoise.backends.base.client import BaseDBAsyncClient as _BaseDBAsync... | 3,921 | 1,203 |
"""
Common elements for both client and server
==========================================
"""
import enum
import json
class ProtocolError(RuntimeError):
"""Raised when some low-level error in the network protocol has been
detected.
"""
class EndpointType(enum.Enum):
"""
Enumeration of endpoints e... | 1,129 | 358 |
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import os
import sys
def export_sample_images(amount:int, export_dir:str, dataset, shuffle=True):
os.makedirs(export_dir, exist_ok=True)
loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=amount, shuf... | 1,639 | 555 |
from unittest import TestCase
from bloock.infrastructure.hashing.blake2b import Blake2b
from bloock.infrastructure.hashing.keccak import Keccak
class Blake2bTestCase(TestCase):
def setUp(self):
self.blake = Blake2b()
def test_blake_generate_hash_64_zeros_string(self):
data = b'00000000000000... | 1,791 | 904 |
# coding: utf-8
"""
SimScale API
The version of the OpenAPI document: 0.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from simscale_sdk.configuration import Configuration
class TimeStepAnimationOutputSettingsAllOf(object):
"""NOTE: This cla... | 7,395 | 2,222 |
'''
Repository configuration model.
'''
from typing import Dict, List, Literal, Optional
from .. import types
from .configuration import Configuration
class RepositoryConfiguration(Configuration):
'''
Repository configuration model.
'''
#: Configuration type.
type: Optional[Literal['repository'... | 1,143 | 312 |
#!/usr/bin/env python
def modpow(a,n,m):
ret=1
while n:
if n&1: ret=(ret*a)%m
n>>=1
a = (a*a)%m
return ret
def check(a1):
checkstr=''
for i in xrange(len(moves)):
if a1%3==0:
checkstr+='D'
a1/=3
elif a1%3==1:
checkstr+='U'... | 970 | 496 |
"""Represent a Wavelet Coefficient Set.
.. module::wave
:platform: Unix, Windows
.. modelauthor:: Juan C Galan-Hernandez <jcgalanh@gmail.com>
"""
import numpy as np
import waveletcodec.tools as tools
import waveletcodec.lwt as lwt
import cv2
import math
#Constant Section
CDF97 = 1
#End
class WCSet(np.ndarray... | 4,708 | 1,588 |
"""
Paint costs
You are getting ready to paint a piece of art. The canvas and brushes that you want to use will cost 40.00. Each color of paint that you buy is an additional 5.00. Determine how much money you will need based on the number of colors that you want to buy if tax at this store is 10%.
Task
Given the to... | 972 | 297 |
from __future__ import division
from .curve import Curve
from numpy import min, max, seterr
seterr(all='raise')
class PRCurve(Curve):
def __init__(self, points, pos_neg_ratio, label=None):
Curve.__init__(self, points, label)
self.pos_neg_ratio = pos_neg_ratio
if max([self.x_vals, self.y_v... | 1,598 | 569 |
""" Utilities for homework 2.
Function "log_progress" is adapted from:
https://github.com/kuk/log-progress
"""
import matplotlib.pyplot as plt
import numpy as np
import torch
from ipywidgets import IntProgress, HTML, VBox
from IPython.display import display
from blg604ehw2.atari_wrapper import LazyFrames
de... | 3,384 | 1,032 |
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from bes.testing.unit_test import unit_test
from bes.archive.archive_util import archive_util
from bes.archive.archiver import archiver
from bes.archive.temp_archive import temp_archive
class test_archive_... | 17,982 | 7,428 |
# -*- coding: utf-8 -*-
import argparse
import os
from .client import YaleClient
class EnvDefault(argparse.Action):
def __init__(self, envvar, help, required=True, default=None, **kwargs):
if envvar:
if envvar in os.environ:
value_default = os.getenv(key=envvar, default=default... | 3,625 | 993 |
from .. import models
from django_filters import rest_framework as filters
class MajorFilterSet(filters.FilterSet):
name = filters.CharFilter(field_name="name", lookup_expr="contains")
description = filters.CharFilter(field_name="description", lookup_expr="contains")
id = filters.NumberFilter(field_name="... | 1,376 | 403 |
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from django.conf import settings
from django.views.i18n import set_language
from proposals.utils.statistics_utils import get_average_turnaround_time, \
get_qs_for_long_route_reviews, get_qs_for_short_route_reviews, \
... | 2,189 | 653 |
"""Scraper to get info on the latest Dilbert comic."""
from datetime import timedelta
from typing import Optional
from constants import LATEST_DATE_REFRESH, SRC_PREFIX
from scraper import Scraper, ScrapingException
from utils import curr_date, date_to_str, str_to_date
class LatestDateScraper(Scraper[str, None]):
... | 4,299 | 1,197 |
from montag.domain.entities import Provider
from montag.use_cases.fetch_playlists import FetchPlaylists
from montag.use_cases.support import Failure, Success
from tests import factory
def test_fetch_playlists(repos, spotify_repo):
expected_playlists = factory.playlists(2)
spotify_repo.find_playlists.return_va... | 742 | 228 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2020 tecnovert
# Distributed under the MIT software license, see the accompanying
# file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php.
import unittest
from xmrswap.interface_btc import (
testBTCInterface
)
from xmrswap.util import... | 4,012 | 1,844 |
from Panel.master_panel import *
"""欢迎使用V2Ray云彩姬"""
if __name__ == '__main__':
V2Rayc = V2RaycSpider_Master_Panel()
try:
V2Rayc.home_menu()
except Exception as e:
V2Rayc.debug(e)
finally:
V2Rayc.kill()
| 243 | 116 |
from django.urls import path
from .views import index, supporter_index, customer_index
app_name = 'toppage'
urlpatterns = [
path('', index, name='index'),
path('supporter/', supporter_index, name='supporter_index'),
path('customer/', customer_index, name='customer_index'),
] | 289 | 90 |
from forest_constants import (LEAFY, CONIFEROUS)
def get_forest_dimensions(forest):
rows_num = len(forest)
cols_num = 0
if rows_num:
cols_num = len(forest[0])
return rows_num, cols_num
def get_tree_counts(forest):
leafy_count = 0
coniferous_count = 0
for row in forest:
l... | 443 | 171 |
"""No identified need to test model interface functionality."""
| 64 | 13 |
import sys
import h5py
import yaml
import numpy as np
from fuel.datasets import H5PYDataset
from fuel.streams import DataStream
from fuel.schemes import SequentialScheme, ShuffledScheme
from fuel.transformers import Mapping
from blocks.extensions import saveload, predicates
from blocks.extensions.training import TrackT... | 1,923 | 640 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2013 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import os
import sys
from compat import unittest
from distlib.compat import url2pathname, urlpa... | 13,580 | 4,441 |
"""AWS S3 Plugin."""
import os
from typing import List
from tempfile import NamedTemporaryFile
from netskope.integrations.cls.plugin_base import (
PluginBase,
ValidationResult,
PushResult,
)
from .utils.aws_s3_validator import (
AWSS3Validator,
)
from .utils.aws_s3_client import AWSS3Client
class AWS... | 6,946 | 1,662 |
"""Database fixtures."""
import pytest
@pytest.fixture(autouse=True)
def _auto_clean_specs_table(_clean_specs_table):
"""Autouses _clean_specs_table."""
| 160 | 62 |
import logging
import uvicorn
from fastapi_offline import FastAPIOffline as FastAPI
#from cdr_plugin_folder_to_folder.api.users import router
from osbot_utils.utils.Misc import to_int
from cdr_plugin_folder_to_folder.api.routes.Processing import router as router_processing
from cdr_plugin_folder_to_folder.api.routes... | 2,626 | 779 |
# Evaluate using Shuffle Split Cross Validation
from pandas import read_csv
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
filename = 'pima-indians-diabetes.data.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test'... | 751 | 279 |
# coding: utf-8
from __future__ import (
unicode_literals, division, print_function, absolute_import
)
import re
import pytest
from ww import s, g, f
def test_lshift():
res = s >> """
This is a long text
And it's not indented
"""
assert isinstance(res, s)
s == "This is a long text\nA... | 4,178 | 1,761 |
import ast
from sherlock.codelib.analyzer.variable import Type
from sherlock.codelib.system_function import system_function
@system_function('range', Type.LIST, Type.NUMBER, Type.NUMBER)
def system_range(g, start, end):
return '$(seq %s $(( %s - 1 )))' % (g.dispatch(start), g.dispatch(end))
@system_function('pri... | 566 | 206 |
from rest_framework.exceptions import APIException
from django.utils.translation import ugettext_lazy as _
from rest_framework.status import HTTP_423_LOCKED
# Create your errors here.
class LockedError(APIException):
status_code = HTTP_423_LOCKED
default_detail = _('You do not have permission to perform this... | 370 | 109 |
from services.volt.models import AccessDevice, VOLTDevice
from xosresource import XOSResource
class XOSAccessDevice(XOSResource):
provides = "tosca.nodes.AccessDevice"
xos_model = AccessDevice
copyin_props = ["uplink", "vlan"]
name_field = None
def get_xos_args(self, throw_exception=True):
... | 1,373 | 443 |
import pandas as pd
import math
from matplotlib import pyplot
ts = pd.read_csv("airline-passengers.csv", header=0, index_col=0)
nOfPassengers = ts["Passengers"]
values = nOfPassengers.values.tolist()
forecast = [math.nan]
for i in range(0, len(values) - 1):
forecast.append(values[i])
pyplot.plot(values)
pyplot... | 587 | 241 |
"""create exchange table
Revision ID: bfa53193d3bf
Revises: b97a89b20fa2
Create Date: 2019-09-22 01:17:06.735174
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bfa53193d3bf'
down_revision = 'b97a89b20fa2'
branch_labels = None
depends_on = None
def upgrade()... | 513 | 222 |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import time
import logging
import numpy as np
from biosppy.signals import ecg
from biosppy.storage import load_txt
import matplotlib.pyplot as plt
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
... | 2,831 | 1,341 |
from django.apps import AppConfig
class BookOutletConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'book_outlet'
| 153 | 49 |
from app import db
from app.models.base_model import BaseModel
class File(BaseModel):
__tablename__ = "files"
filename = db.Column(db.String(300)) # includes path!
status = db.Column(db.Integer())
size = db.Column(db.Integer())
position = db.Column(db.Integer())
# foreign keys
package_i... | 1,076 | 370 |
import time
import json
from copy import deepcopy
class Task(object):
"""Defines task objects that can be handled by the task manager."""
def __init__(self, t_id=None, user_id=None, product_id=None,
tag=None, data=None,
timestamp=None, update_timestamp=None, error=None):
... | 3,126 | 903 |
import math
import torch
from .Module import Module
from .utils import clear
class Linear(Module):
def __init__(self, inputSize, outputSize, bias=True):
super(Linear, self).__init__()
self.weight = torch.Tensor(outputSize, inputSize)
self.gradWeight = torch.Tensor(outputSize, inputSize)
... | 2,791 | 864 |
"""
Utilities for testing
"""
import numpy as np
from astropy.table import Table as apTable
from astropy.utils.diff import report_diff_values
def compare_tables(t1, t2):
""" Compare all the tables in two `astropy.table.Table`)
Parameters
----------
t1 : `astropy.table.Table`
One table
t2 ... | 2,349 | 793 |
__author__ = '__knh4vu__'
from helper import greeting
from helper3 import greeting3
from helper2 import greeting2
if __name__ == '__main__':
greeting('hello')
greeting2('There')
| 185 | 69 |
from textwrap import dedent
import pytest
from pylox.lox import Lox
# Base cases from https://github.com/munificent/craftinginterpreters/blob/master/test/inheritance/constructor.lox
TEST_SRC = dedent(
"""\
class A {
init(param) {
this.field = param;
}
test() {
print this.fi... | 746 | 261 |
#! -*- coding:utf-8 -*-
"""Shortcuts for yuqing trials
.. moduleauthor:: Huan Di <hd@iamhd.top>
"""
from byq_trial.auth import SimpleAuth
from byq_trial.call import APICall
__all__ = [SimpleAuth, APICall]
| 209 | 87 |
#!/usr/bin/env python3
""" Import comunity modules. """
import os
import sys
import jinja2
import re
HERE = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, f"{HERE}")
def string_is_latest_or_version(check_string):
prog = re.compile("^(\d+\.)?(\d+\.)?(\*|\d+)$")
result = prog.match(check_stri... | 1,196 | 392 |
lista_filmes = ['vingadores ultimato', 'star wars', 'as branquelas', 'vovó... zona']#Criando as 4 listas
print("lista filmes: " ,lista_filmes)
print("\n")
lista_jogos = ['genshin impact', 'the witcher 3', 'dying light', 'destiny']#Criando as 4 listas
print("lista jogos: " ,lista_jogos)
print("\n")
lista_livros = ['o ul... | 1,988 | 737 |
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from ipaymu.forms import IpaymuForm
from ipaymu.models import IpaymuSessionID
from ipaymu.utils import save_session, verify_session, IpaymuParamsBuilder
class IpaymuTest(TestCase):
fixtures = ['ip... | 2,770 | 973 |
# ---
# jupyter:
# jupytext:
# formats: ipynb,md
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.10.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # Eppy is ... | 10,643 | 5,090 |
# MINUTES
IT_IS = [[0,0],[0,1],[0,3],[0,4]]
FIVE = [[3,i] for i in range(7,11)]
TEN = [[1,i] for i in range(6,9)]
QUARTER = [[2,i] for i in range(2,9)]
TWENTY = [[3,i] for i in range(1,7)]
HALF = [[1,i] for i in range(2,6)]
TO = [[4,i] for i in range(1,3)]
PAST = [[4,i] for i in range(3,7)]
MINUTES = [
[],
FI... | 2,535 | 1,165 |
# TCE CCSD(T) and CCSD[T] calculations
import os
import sys
import qcdb
from ..utils import *
def check_ccsd_t_pr_br(return_value):
ccsd_tot = -76.240077811301250
ccsd_corl = -0.213269954065481
t_br_corr = -0.003139909173705
t_br_corl = -0.216409863239186
ccsd_t_br = -76.243217720474960
t_pr... | 1,884 | 967 |
#!/usr/bin/env python3
import time
import multiprocessing
import os
import vim
from async_worker import AsyncWorker
import utils
# Global map for host (source code) window ID -> Squeezer instance
squeezers = {}
# set of Squeezer instances that are waiting for updates
polling_squeezers = set()
def create_window(b... | 6,246 | 2,101 |
# python code to demonstrate working of enumerate()
for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']):
print(key, value)
print('\n')
# python code to demonstrate working of enumerate()
for key, value in enumerate(['Geeks', 'for', 'Geeks', 'is', 'the', 'Best', 'Coding', 'Platform']):
print(value, e... | 1,781 | 567 |
# -*- coding: utf-8 -*-
from sandbox_python_structure import f
def test_parse_no_subarg():
ret = f()
assert ret == 'hi'
| 131 | 52 |
"""initial tables
Revision ID: 9e7ee952f6ae
Revises:
Create Date: 2016-10-21 17:20:27.709284
"""
# revision identifiers, used by Alembic.
revision = '9e7ee952f6ae'
down_revision = None
branch_labels = None
depends_on = None
from alembic import op
from sqlalchemy.types import Text
import sqlalchemy as sa
from sqlalc... | 18,063 | 5,877 |
#!/usr/bin/env python3
try:
import os
import json
import argparse
import shutil
from git import Repo
from jinja2 import Template, Environment, FileSystemLoader
except ImportError as ie:
print("Import failed for " + ie.name)
exit(1)
NAME_TAG = 'name'
TABLES_TAG = 'tables'
BITWIDTH_TAG =... | 14,233 | 5,168 |
from setuptools import setup
def readme():
with open('./README.md') as f:
return f.read()
setup(
name='event_loop',
version='0.1',
author='mapogolions',
author_email='ivanovpavelalex45@gmail.com',
description='Simple event loop',
license='LICENSE.txt',
long_description=readme... | 399 | 141 |
class Person:
"""
Representation of a person, which includes name, gender, date of birth
"""
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
def __str__(self):
return f'Name: {self.name}, Gender: {self.gender}, Age: {s... | 382 | 126 |
#a = raw_input()
num = input()
def addone():
global t, qq
t[qq-1] += 1
carry = 0
c = 0
ss = ""
for j in range(qq):
t[qq-1-j] += carry
if (t[qq-1-j] > 1):
t[qq-1-j] = 0
carry = 1
else:
carry = 0
c += 1
ss += str(t[qq-1-j])
return ss
def makestring():
s = ""
ends = ""
global t, b, l, qq
... | 1,121 | 607 |
#!/usr/bin/env python
import sys,os,re,fileinput,argparse
import csv
import random
parser = argparse.ArgumentParser(description="takes a file of CYC data, and produces pairwise info for cytoscape network viewing" )
parser.add_argument("--fi",help="the file, must be headered as \"Pathway-id Pathway-name Gene-id Gene-nam... | 1,658 | 592 |
import os
def makedirs(path):
try:
os.makedirs(path)
except OSError:
pass
def readfile(path):
with open(path, 'r') as file:
return file.read()
def writefile(path, content):
with open(path, 'w') as file:
return file.write(content)
def copyfile(_from, to... | 564 | 208 |
from .exceptions import UnexpectedValue
from .constants import *
import socket, struct, threading, time
class Tools:
atype2AF = {
ATYP_IPV4:socket.AF_INET,
ATYP_IPV6:socket.AF_INET6,
ATYP_DOMAINNAME:socket.AF_INET
}
def recv2(conn:socket.socket, *args):
... | 7,873 | 2,545 |
def binary_search(search_num, sorted_arr):
"""
https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheBinarySearch.html
First Q at https://dev.to/javinpaul/20-basic-algorithms-problems-from-coding-interviews-4o76
"""
if sorted_arr[0] == search_num:
return True
arr_l... | 1,402 | 501 |
import unittest
import axelrod
class TestResultSet(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.players = ('Player1', 'Player2', 'Player3')
cls.test_results = [
[[0, 0], [10, 10], [21, 21]],
[[10, 8], [0, 0], [16, 20]],
[[16, 16], [16, 16], [0... | 3,292 | 1,269 |
#There is a collection of
#input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings
def f():
strings = ['aba', 'baba', 'aba', 'xzxb']
queries = ['aba', 'xzxb', 'ab']
res = []
'''
for q in queries:
tota... | 814 | 247 |
# Generated by Django 3.2.4 on 2021-06-30 14:10
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('home', '0001_initial'),
migrations.swappable_dependency(setting... | 1,494 | 483 |
'''Ref: https://arxiv.org/pdf/2003.00295.pdf'''
from typing import Callable, Dict, List, Optional, Tuple
import numpy as np
from flwr.common import (
EvaluateIns,
EvaluateRes,
FitIns,
FitRes,
Weights,
parameters_to_weights,
weights_to_parameters,
)
from flwr.server.strategy.aggregate imp... | 4,658 | 1,535 |
# also update in setup.py
__version__ = '0.6.9'
| 48 | 21 |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
long_description = """
Short description...
"""
setuptools.setup(
name='test_package_kthdesa',
version='1.0.0',
author='Alexandros Korkovelos',
author_email='alekor@desa.kth.se',
description='This is a test pack... | 786 | 266 |
import torch
from torch.nn import LeakyReLU
from torch.nn.functional import interpolate
from gan.EqualizedLayers import EqualizedConv2d, EqualizedDeconv2d
class PixelwiseNormalization(torch.nn.Module):
"""
Normalize feature vectors per pixel as suggested in section 4.2 of
https://research.nvidia.com/site... | 5,801 | 1,891 |