text
string
size
int64
token_count
int64
from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.test import APIClient from api.models import Category category_URL = reverse('api:category-list') class PublicTestCase(TestCase): """ Test fo...
1,677
465
# -*- coding: utf-8 -*- import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import unittest from config import * from youku import YoukuUsers class UserTest(unittest.TestCase): def setUp(self): self.youku = YoukuUsers(CLIENT_ID) def test_my_info(self)...
1,989
774
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 13 12:12:25 2021 @author: Jordan """ import sys import os import numpy as np import pandas as pd import seaborn as sns import tempfile import gc import re import collections import gzip import bisect import pickle import itertools import math sns....
26,044
8,277
from rest_framework.routers import DefaultRouter from .views import UserViewSet router = DefaultRouter() router.register('users', UserViewSet) urlpatterns = router.urls
173
50
from donkeycar.parts.model_wrappers.Angle5FlipSharpThrottleOn import Angle5FlipSharpThrottleOn from donkeycar.parts.model_wrappers.Angle5ifelse import Angle5ifelse from donkeycar.parts.model_wrappers.Angle3ifelse import Angle3ifelse from donkeycar.parts.model_wrappers.Angle3speedy import SpeedyFranklin3choices from don...
430
156
my_list = ['banana', 'strawberry', 'apple', 'watermelon', 'peach'] #a simple list sorted_list = sorted(my_list) #python includes powerful sorting algorithms for x in range(1,11,1): #a for loop which counts to ten """range takes up to three arguments: the start, which is inclusive, the end, which is exclusive and th...
589
185
# Dictionaries for base64 encoding and decoding. encode_dict = {0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J',10:'K',11:'L',12:'M',13:'N',14:'O',15:'P',16:'Q',17:'R',18:'S',19:'T',20:'U',21:'V',22:'W', 23:'X',24:'Y',25:'Z',26:'a',27:'b',28:'c',29:'d',30:'e',31:'f',32:'g',33:'h',34:'i',35:'j',36:'k',...
2,146
1,147
import tkinter as tk class BaseWindow(tk.Toplevel): def __init__(self): super().__init__() self.base_frame = tk.Frame(self) self.base_frame.pack(fill="both", expand="true") self.base_frame.pack_propagate(0) self.frame_styles = { "relief": "groove", ...
590
205
import os from typing import NamedTuple from google.oauth2.service_account import Credentials as OAuthCredentials from .constants import OAUTH_CONFIG_PATH, OAUTH_SCOPES class PostgresCredentials: def __init__(self): self.host = os.environ.get("SYNC_DB_HOST") self.dbname = os.environ.get("SYNC_DB...
963
295
#!/usr/bin/python import requests import json import re import mechanize import cookielib import sys from BeautifulSoup import BeautifulSoup # Variables engaged = False #topic_url="https://www.kvraudio.com/forum/viewtopic.php?f=1&t=470835" topic_url = "http://www.kvraudio.com/forum/viewtopic.php?f=1&t=492028" #topic...
9,993
3,509
from django.apps import AppConfig from django.db.models.signals import post_save from django.apps import apps from .signals import assign_season_to_all_user class LeaveTrackerConfig(AppConfig): name = 'leave_tracker' def ready(self): Season = apps.get_model('leave_tracker', 'Season') post_save...
371
119
import datetime import numpy as np import pandas as pd from google.oauth2 import service_account from googleapiclient import discovery SPREADSHEET_ID = "1otVI0JgfuBDJw8jlW_l8vHXyfo5ufJiXOqshDixazZA" # ALL-IN-ONE-LOG-2021 class Spreadsheet: def __init__(self, spreadsheetId): self.spreadsheetId = spreads...
5,970
2,075
import telebot import settings import helpers from models import User bot = telebot.TeleBot(settings.token, parse_mode=None) users = dict() @bot.message_handler(commands=['start', 'help']) def send_help(message): if not message.chat.id in users: users[message.chat.id] = User() bot.reply_to(message, settings.help...
1,513
551
# Generated by Django 3.0.7 on 2020-07-08 15:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('roles', '0001_initial'), ('users', '0007_auto_20200706_0436'), ] operations = [ migrations.AddField( model_name='user', ...
422
158
import json from datetime import date, datetime import pytest import responses from fastapi.testclient import TestClient from .brandnewday import funds_cache, quote_cache from ..main import app from ..models import Quote client = TestClient(app) prefix = '/brandnewday/' @pytest.fixture(autouse=True) def clear_cac...
7,158
2,981
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'preferencesDialogUi.ui' # # Created by: PyQt5 UI code generator 5.12.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_DialogPreferences(object): def setupUi(self, DialogPr...
5,385
1,652
import threading import random import time from eqsn import EQSN def test_measure_from_threads(): q_sim = EQSN() def measure_or_hadamard(_id): n = random.randrange(10, 20, 1) for _ in range(n): time.sleep(0.1) q_sim.H_gate(_id) nr_threads = 10 ids = [str(x) f...
787
308
import unittest from unittest import TestCase from utility_functions.stats_functions import permute_columns from utility_functions.databricks_uf import has_column from connect2Databricks.spark_init import spark_init if 'spark' not in locals(): spark, sqlContext, setting = spark_init() sc = spark.sparkContext cla...
1,464
420
"""Fun commands that don't do anything really productive night, thank, shipname, shipcount, ship, hug, pecan, fortune""" # -*- coding: utf-8 -*- import pickle import random import sqlite3 as lite import subprocess import discord from discord.ext import commands from lib import shipname_module as improved_shipname, ...
24,857
7,159
import os import re import shutil import attr import click import subprocess32 as subprocess import yaml from kross.utils import echo, get_std @attr.s class BasePush(object): push_args = attr.ib(type=tuple) registry_target = attr.ib() manifest_directory = attr.ib() qemu_archs = attr...
3,151
977
from comm.telegram import TelegramCommunicationBot from telegram import Message from util.misc import wlog, die, enumerate_2d_array import traceback class MessageResponse: def __init__(self, text, user_id): self.user_id = user_id self.text = str(text).strip() class MessageRequest: pass cla...
5,655
1,639
import logging import ipaddress import os from . import utils from . import ymodem # ------------------------------------------------------------------------------------------------- class Action: @classmethod def _run(cls, client, config, args): return cls(client, config).run(args) def __init__(...
10,358
3,051
""" 中序遍历:DFS或者栈来实现。 leetcode No.94 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # dfs 递归实现 def inorderTraversal(self, root: TreeNode) -> List[in...
955
375
from common.permissions import IsOwner from rest_framework.permissions import IsAuthenticated class IsHostAuthenticated(IsOwner): def has_permission(self, request, view): if IsAuthenticated(request, view): host = request.user # if host.is_auth is True: # return Tru...
412
106
from AppKit import * from PyObjCTools.TestSupport import * class TestNSNibLoading (TestCase): def testMethods(self): self.assertResultIsBOOL(NSBundle.loadNibFile_externalNameTable_withZone_) self.assertResultIsBOOL(NSBundle.loadNibNamed_owner_) self.assertResultIsBOOL(NSBundle.loadNibFile_...
602
204
#-*- coding:utf-8 -*- import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei']# 用于显示plt的中文标签 pd.set_option('display.max_columns', None)#显示所有列 pd.set_option('display.max_rows', None)#显示所有行 data = pd.read_csv('C:\User\dell\Desktop\大众点评\dazhong.csv',encoding='gbk') #print(data.head()...
2,956
1,428
import pytest import graphene from gtmcore.inventory.inventory import InventoryManager from gtmcore.fixtures import ENV_UNIT_TEST_REPO, ENV_UNIT_TEST_BASE, ENV_UNIT_TEST_REV from gtmcore.environment import ComponentManager from gtmcore.environment.bundledapp import BundledAppManager import gtmcore from lmsrvlabbook.t...
19,773
4,782
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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...
1,705
575
from typing import List class StatisticGenerator(object): def __init__(self, column_names): self.column_names = column_names ''' Function which returns two arrays: 1. Statistic column names 2. Statistic column values for each column name ''' def generate_statis...
379
101
from flask import render_template from app import db from app.errors import bp @bp.app_errorhandler(400) def not_found_error(error): return render_template('errors/400.html'), 400 @bp.app_errorhandler(401) def not_found_error(error): return render_template('errors/401.html'), 401 @bp.app_errorhandler(403) ...
741
288
import random import uuid from locust import HttpUser, task, between apiUrl = "/webhooks/rest/webhook" # Rasa Core REST API endpoint # apiUrl = "/core/webhooks/rest/webhook" # Rasa X REST API endpoint class RasaRestExplodeBrainUser(HttpUser): wait_time = between(3, 10) def on_start(self): self.nam...
1,199
375
# -*- coding:utf-8 -*- from yepes.apps import apps AbstractCountry = apps.get_class('standards.abstract_models', 'AbstractCountry') AbstractCountrySubdivision = apps.get_class('standards.abstract_models', 'AbstractCountrySubdivision') AbstractCurrency = apps.get_class('standards.abstract_models', 'AbstractCurrency') ...
869
242
from .randomForestRules import RandomForestRules
48
14
#!/usr/bin/env python3 """quotery.py This script is part of a daily celery task to fetch a quote from a JSON file and save it to the database. There should only be one quote at a time in the database. On the template, we simply retrieve the quote and display it on the website as "Quote of the Day". The idea is to ...
2,545
802
# !/usr/bin/env python # -*- coding: utf-8 -*- """Entry point for the server application.""" import json import logging import traceback from datetime import datetime from flask import Response, request, jsonify, current_app from gevent.wsgi import WSGIServer from flask_jwt_simple import ( JWTManager, jwt_required...
7,718
2,636
import random import string from django.test import TestCase from bumblebee.users.models import CustomUser class UserProfileTest(TestCase): def random_string(self): return "".join(random.choice(string.ascii_lowercase) for i in range(10)) def test_user_has_profile(self): user = CustomUser( ...
1,409
435
# No shebang line, this module is meant to be imported # # Copyright 2014 Oliver Palmer # Copyright 2014 Ambient Entertainment GmbH & Co. KG # # 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 # ...
16,481
4,294
# Zed Attack Proxy (ZAP) and its related class files. # # ZAP is an HTTP/HTTPS proxy for assessing web application security. # # Copyright 2013 ZAP development team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a c...
3,044
1,007
#!/usr/bin/env python # Please ensure that you have two Minecraft clients running on port 10000 and # port 10001 by doing : # $MALMO_MINECRAFT_ROOT/launchClient.sh -port 10000 # $MALMO_MINECRAFT_ROOT/launchClient.sh -port 10001 import marlo client_pool = [('127.0.0.1', 10000),('127.0.0.1', 10001)] join_tokens = marl...
1,387
465
# -*- coding: utf-8 -*- import re import random from semantic3.units import ConversionService from hal.library import HalLibrary class ConvLib(HalLibrary): """ Conversion library """ name = "Converter" keywords = ["convert", "converter", "conversion"] convregex = re.compile( "(con...
1,349
356
""" Ory APIs Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.3 Contact: support@ory.sh Generated by: http...
933
278
from collections import deque import pickle from . import Pyraminx, PYRAMINX_CASE_PATH from multiprocessing import Pool, cpu_count def setup(): graph = create_graph() with open(PYRAMINX_CASE_PATH, 'wb') as f: pickle.dump(graph, f, pickle.HIGHEST_PROTOCOL) def create_graph(): with Pool(cpu_count...
1,191
435
from torch import nn def get_default_fc(num_ftrs,adjusted_classes, params): return nn.Sequential( nn.Linear(num_ftrs, 1024),nn.ReLU(),nn.Dropout(p=params.fc_drop_out_0), nn.Linear(1024, 1024),nn.ReLU(),nn.Dropout(p=params.fc_drop_out_1), nn.Linear(1024, adjusted_classes) )
307
143
# Copyright 2021-2022 Toyota Research Institute. All rights reserved. import os from collections import OrderedDict from dgp.proto.ontology_pb2 import FeatureOntology as FeatureOntologyPb2 from dgp.proto.ontology_pb2 import FeatureOntologyItem from dgp.utils.protobuf import (generate_uid_from_pbobject, open_feature_o...
4,452
1,335
# Script to replace text in a designated field in a resource and post the resource back to API. # Requirements: # - ASFunctions.py # - A csv of format repo,asid # - sheetFeeder (optional, for reporting purposes) import ASFunctions as asf import json from pprint import pprint import re import csv from sheetFeeder impor...
2,321
832
from __future__ import print_function import os import sys from py2gcode import gcode_cmd from py2gcode import cnc_dxf fileName = sys.argv[1] feedrate = 120.0 prog = gcode_cmd.GCodeProg() prog.add(gcode_cmd.GenericStart()) prog.add(gcode_cmd.Space()) prog.add(gcode_cmd.FeedRate(feedrate)) prog.add(gcode_cmd.PathBl...
1,139
476
#!/usr/bin/env python # -*- coding:utf-8 -*- import utils from datetime import datetime import calendar def run(string, entities): """Sia tells time and date""" string = string.lower() now = datetime.now() day = datetime.today() if string.find("time") != -1 and string.find("date") == -1: ...
852
297
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import numpy as np from collections import namedtuple from network_modules import * State = namedtuple('State', ('visual', 'instruction')) class Model(nn.Module): def __init__(self, ...
1,477
447
from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIRequestFactory from rr.models.certificate import Certificate from rr.models.serviceprovider import ServiceProvider from rr.tests.api.api_common import APITestCase from rr.views_api.certificate import Certif...
6,939
2,943
# -*- coding: utf-8 -*- # Modified by Microsoft Corporation. # Licensed under the MIT license. """ """ import numpy as np import torch from nltk import word_tokenize from .models.Mem2Seq import Mem2Seq from .utils.config import args, USE_CUDA, UNK_token from .utils.utils_woz_mem2seq import prepare_data_seq, generate...
2,298
830
from .th import *
18
7
# wwwhisper - web access control. # Copyright (C) 2012-2018 Jan Wrobel <jan@mixedbit.org> from wwwhisper_auth.models import Site from wwwhisper_auth.tests.utils import HttpTestCase from wwwhisper_auth.tests.utils import TEST_SITE import json FAKE_UUID = '41be0192-0fcc-4a9c-935d-69243b75533c' TEST_USER_EMAIL = 'foo@b...
21,754
6,729
""" Wrapper providing a plistlib interface. Better than a patch? """ __all__ = [ "InvalidFileException", "FMT_XML", "FMT_BINARY", "FMT_TEXT", "load", "dump", "loads", "dumps", "UID", ] import plistlib as pl from enum import Enum from io import BytesIO from typing i...
2,139
870
# Make kinf # # Analyze the fuel materials from different libraries import numpy as np import openmc from openmc import mgxs import os import sys; sys.path.append("..") import materials import energy_groups def _get_fuel(library): try: fuel = library.get_material("fuel") except KeyError: fuel = library.get_mat...
3,992
1,653
import FWCore.ParameterSet.Config as cms process = cms.Process("HIGHPTSKIM") process.load('Configuration.StandardSequences.Services_cff') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.EventContent.EventContentHeavyIons_cff') process.source = cms.Source("PoolSource", fileNames ...
1,775
674
from warnings import warn warn('Deprecated: Moved to ut.util.utime (to avoid name conflict with standard lib `time`)') from ut.util.utime import * # move here
162
50
"""Runs when the `poop` alias has not been setup.""" from colorama import init from ..utils import colored from .alias import is_configured from .alias import configure init() def main(): if not is_configured(): configure() print(colored('The `poop` alias was configured successfully.\n' '...
369
107
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-12 15:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('biking', '0001_initial'), ] operations = [ migrations.AlterField( ...
443
159
# -*- coding: UTF-8 -*- from functools import reduce from operator import mul def fact_lambda(n): return reduce(lambda a, b: a * b, range(1, n+1)) def fact_mul(n): return reduce(mul, range(1, n+1))
210
83
import math from collections import OrderedDict import pytest import torch from torch import nn import continual as co from continual.module import TensorPlaceholder torch.manual_seed(42) def test_sequential(): S = 3 long_example_clip = torch.normal(mean=torch.zeros(10 * 3 * 3)).reshape( (1, 1, 10...
16,929
6,862
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_slta = models.BooleanField(default=False) is_slt = models.BooleanField(default=False) is_parent = models.BooleanField(default=False)
257
76
"""Sampling code for the parrot. Loads the trained model and samples. """ import numpy import os import cPickle import logging from blocks.serialization import load_parameters from blocks.model import Model from datasets import parrot_stream from model import Parrot from utils import ( attention_plot, sample_pa...
10,200
3,710
import socket import re from struct import pack from time import sleep def recv_until(s, string=""): text = "" while 1 : data = s.recv(4096) text+=data if not data or data.find(string) != -1: break return text def leak(s): s.send("A\n") text = recv_until(s, "Sel...
3,517
2,463
# encoding: UTF-8 from __future__ import division from datetime import datetime from math import floor import pandas as pd import numpy as np import sys sys.path.append('../') #sys.path.append('D:\\tr\\vnpy-master\\vn.trader\\DAO') sys.path.append('D:\\tr\\vnpy-1.7\\vnpy\\DAO') sys.path.append('D:\\tr\\vnpy-1.7\\vn...
9,504
3,307
from app import SlashBot from async_timeout import timeout from asyncio import TimeoutError from datetime import datetime, timedelta, timezone from hikari import ButtonStyle, CacheSettings, Member, UNDEFINED from random import choice, sample, uniform bot = SlashBot(cache_settings=CacheSettings(max_messages=1000...
2,728
805
import pytest from hamcrest import assert_that, equal_to, is_ from django.conf import settings @pytest.mark.django_db def test_user_get_absolute_url(user: settings.AUTH_USER_MODEL): expected_url = '/users/{0}/'.format(user.username) assert_that(user.get_absolute_url(), is_(equal_to(expected_url)))
310
107
from django.apps import AppConfig class ProtocolsConfig(AppConfig): name = 'protocols'
93
29
''' Threads that go to/from containers, limit data and lines, and insert data into the Data table. ''' import threading from src import tables from src.logger import logger from src.lazy_init import lazy_init class OneWayThread(threading.Thread): ''' One thread to/from container. ''' # pylint: disable=E1101, ...
2,745
786
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Version testing Don't want to run when running `pytest`, only run when something is pushed to develop branch or PR to master. """ import configparser import requests from com_server import __version__ from passive.cmp_version import Version def test_version_great...
731
230
from django.db import models from django.conf import settings from django.contrib.gis.db import models from madrona.features import register from madrona.features.models import Feature @register class Bookmark(Feature): url_hash = models.CharField(max_length=2050) class Options: verbose_name = '...
390
114
from Utility import resources as ex # noinspection PyPep8 class Levels: @staticmethod async def get_level(user_id, command): """Get the level of a command (rob/beg/daily).""" count = ex.first_result( await ex.conn.fetchrow(f"SELECT COUNT(*) FROM currency.Levels WHERE UserID = $1 AN...
1,827
554
""" Exposes an experimental mixin for each pachyderm service. These mixins should not be used directly; instead, you should use ``python_pachyderm.experimental.Client()``. The mixins exist exclusively in order to provide better code organization, because we have several mixins, rather than one giant :class:`Client <pyt...
374
104
import logging logger = logging.getLogger("Hydraslayer") def get_consensusbase(bases, mincov=3): """ :param mincov: :type bases: list """ bases = "".join(bases) a = bases.count('A') t = bases.count('T') c = bases.count('C') g = bases.count('G') n = bases.count("N") + bases.c...
1,533
549
import copy import numpy as np from collections import defaultdict import utils class DAS3HStudent: def __init__(self, time_weight, n_items, n_skills, seed): np.random.seed(seed) self.alpha = np.random.normal(loc=-1.5, scale=0.3, size=1) self.delta = np.random.normal(loc=-1.0, scale=0.5, ...
5,094
1,856
class Solution: '''第九题''' def XXX(self, s: str) -> bool: s = ''.join([i.lower() for i in s if i.strip().isalnum()]) return s == s[::-1]
163
66
for node in lst: print(node.value)
39
15
""" Miscellaneous functions regarding MS2PIP file conversions. """ import re import pandas as pd def add_fixed_mods(peprec, fixed_mods=None, n_term=None, c_term=None): """ Add 'fixed' modifications to all peptides in an MS2PIP PEPREC file. Return list with MS2PIP modifications with fixed mods added. ...
2,625
888
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- import o...
2,518
721
import pytest from martha import negabs from martha import normalise from martha import labelEncoder from martha import cleanUpString from martha import medianFrequency from martha import gini import numpy as np import pandas as pd import json from sklearn.preprocessing import LabelEncoder # import os # os.chdir("/Use...
1,547
532
# Example of CBF for research-paper domain # Nguyen Dang Quang from nltk.stem.snowball import SnowballStemmer import pandas as pd from nltk.corpus import stopwords # -------------------------------------------------------- user_input_data = "It is known that the performance of an optimal control strategy obtained fro...
7,806
2,425
import re import collections import extract_from_stata.model.common def is_beginning_of_table(line): return (line.startswith("Linear regression") or re.match(r"^ +Source \| +SS +df +MS", line) is not None or line.startswith("Negative binomial regression") or line.startswith("H...
5,625
1,685
# Copyright (c) 2013, Wayzon and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class AddRate(Document): def validate(self): b=self.brand; bt=self.brand_type; r=self.rate; q=frappe.db.sql("""selec...
1,173
472
"""Unit tests for nautobot_plugin_nornir."""
45
18
from flask_apispec import MethodResource from flask_apispec import doc from flask_jwt_extended import jwt_required, get_jwt_identity from flask_restful import Resource from db.db import DB from decorator.catch_exception import catch_exception from decorator.log_request import log_request from utils.serializer import S...
1,267
360
import math import click import dgl import numpy as np import torch from src.builder import create_graph from src.model import ConvModel from src.utils_data import DataPaths, DataLoader, FixedParameters, assign_graph_features from src.utils_inference import read_graph, fetch_uids, postprocess_recs from src.train.run ...
9,693
2,692
import numpy as np class Eval: def __init__(self, pred, gold): self.pred = pred self.gold = gold def Accuracy(self): return np.sum(np.equal(self.pred, self.gold)) / float(len(self.gold))
229
80
# coding=utf-8 from functools import partial import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from .seq_tools import aa2hot from ..tools import io_tools as io def data_it(dataset, block_size, multi_data=False): """ Iterates through a large array, yielding chunks of blo...
5,328
2,078
"""Turn time in seconds into a readable string. """ import math from typing import Union, Tuple TIME_UNITS = ( # Order matters ("days", 24 * 60 * 60), ("hours", 60 * 60), ("minutes", 60), ("seconds", 1), ("milliseconds", 1 / 1000), ("microseconds", 1 / 1000_000), ) def format_seconds(seconds...
1,894
646
""" File name: view.py Author: joeschmid Date created: 4/8/17 """ import json from collections import OrderedDict try: from textwrap import indent except ImportError: from .util import indent from .base_generator import BaseGenerator from .field import FieldType class View(BaseGenerator): """...
6,458
1,872
import os from flask import jsonify from utils import generate_text_from_model def handler(request): url = request.url prompt = request.args.get("prompt", None) n = int(request.args.get("n", 1)) print(f"{url=} {prompt=} {n=}") res = generate_text_from_model(n, prompt, min_length=25) return...
663
220
from setuptools import setup, find_packages from pip._internal.req.req_file import parse_requirements from pip._internal.download import PipSession from os import path from smsgateway import __version__ # Lists of requirements and dependency links which are needed during runtime, testing and setup install_requires =...
1,788
523
# Authors: Thierry Moudiki # # License: BSD 3 import numpy as np from ..utils import parse_request from ..utils import memoize # filtr(df, 'tip > 5') # req = "(time == 'Dinner') & (day == 'Sun') & (tip>1.5)" # filtr(df, req, limit=3, random=False) # filtr(df, req, limit=4, random=True) # # req = "(tip>1.5)" # filtr...
2,394
747
import pyspark.sql.functions as F def top_k_most_picked_skills(match_hero_names_df, ohe_heroes_df, k=5): skills_df = match_hero_names_df.join( ohe_heroes_df, on=[match_hero_names_df.hero == ohe_heroes_df.name] ).select(ohe_heroes_df.columns[3:]) skills = skills_df.columns skills_df_agg = skill...
3,310
1,322
import numpy as np import math Esubo = 8.854 * pow(10,-12) k = 8.988 * pow(10,9) def calcCharge(): faraday = float(input("Input Faraday: ")) volts = float(input("Input Volts: ")) charge = faraday * volts print(charge) calcCharge()
271
117
""" The :mod:`expert.layers.divisive_normalisation` module holds classes of layers for a network that use divisive normalisation. This includes generalised divisive normalisation. """ # Author: Alex Hepburn <alex.hepburn@bristol.ac.uk> # License: new BSD import torch import torch.nn as nn import torch.nn.functional as...
9,217
2,578
import numpy as np import argparse import scipy.linalg from mpl_toolkits.mplot3d import Axes3D from skimage.draw import polygon import matplotlib.pyplot as plt import glob from sklearn import datasets, linear_model import pdb import time parser = argparse.ArgumentParser() parser.add_argument('--folder', default = "") ...
738
261
# automatically generated by the FlatBuffers compiler, do not modify # namespace: flatbuf # /// ---------------------------------------------------------------------- # /// The possible types of a vector class VectorType(object): # /// used in List type, Dense Union and variable length primitive types (String, Binary...
579
149
MAX_INST_PARAM_COUNT = 3 def run_program(memory, input_buffer): pc = 0 while True: result_code, pc_offset = execute_instruction(memory, pc, input_buffer) if result_code == -1: # Halt instruction return if result_code == 0: # Non-jump instructions pc += pc_offs...
3,231
1,087
""" Tests for `coloripy` module. """ import numpy as np from math import isclose import coloripy as cp class TestColoripy(object): @classmethod def setup_class(cls): pass def test_skew_scale(self): modes = ['linear', 'square', 'cubic', 'power', 'sqrt'] vals = [0., 0.5, 1.] ...
2,132
1,131
#!/usr/bin/env python3 from rtmidi.midiconstants import SONG_POSITION_POINTER, TIMING_CLOCK, SONG_START, SONG_CONTINUE, SONG_STOP from .clock_abstract import ClockAbstract from .midi_input import MidiInput class ClockExternal(ClockAbstract, MidiInput): def __init__(self, name=None, port=None): ClockAb...
1,080
350