text
string
size
int64
token_count
int64
from django import template from django.conf import settings from ..models import Bookmark register = template.Library() RESKIN_MENU_APP_ORDER = settings.RESKIN_MENU_APP_ORDER RESKIN_MENU_MODEL_ORDER = settings.RESKIN_MENU_MODEL_ORDER RESKIN_APP_ICON = settings.RESKIN_APP_ICON @register.filter def sort_apps(apps):...
1,863
639
import os import io import urllib.request import zipfile import pandas import fda def get_510k_db(root_dir=os.path.join(fda.root_db_dir, "510k"), force_download=False): if not os.path.exists(root_dir): os.makedirs(root_dir) db_urls = [ "http://www.accessdata.fda.gov/...
1,537
551
import numpy as np import matplotlib.pyplot as plt import re as r import easyocr #import os #os.environ['KMP_DUPLICATE_LIB_OK']='True' re = easyocr.Reader(['en']) #pl = [] chk = [] a = '' a1 = '' #pl = [] #sym = ['{', ']', '[', '}'] class get_number_plate: def get_bboxes_from(self, output): """ returns...
4,657
1,666
# SPDX-FileCopyrightText: 2021 Carnegie Mellon University # # SPDX-License-Identifier: Apache-2.0 import logging import cv2 from busedge_protocol import busedge_pb2 from gabriel_protocol import gabriel_pb2 from sign_filter import SignFilter logger = logging.getLogger(__name__) import argparse import multiprocessing...
3,632
1,283
import click from pathlib import Path # Local imports from .__init__ import * from .utils import parse_time, create_dir, write_file, get_profiles, compress, INVALID_PROFILE, INVALID_DATES from .lambda_log_collector import LambdaLogCollector @click.command() @click.version_option() @click.option("--function-name", "-...
3,095
1,003
import sys sys.path.append('../../../optimus') from optimus.server import app
78
24
"""Common MDPs in RL literature.""" from gym.envs.registration import register from .baird_star import BairdStar from .boyan_chain import BoyanChain from .double_chain import DoubleChainProblem from .grid_world import EasyGridWorld from .random_mdp import RandomMDP from .single_chain import SingleChainProblem from .tw...
1,068
361
import glob import pickle from shutil import copy from tqdm import tqdm class DataHelper: """ helpers to transform and move data around add more as needed. """ def copy_specific_training_data_to_new_folder(self, source_folder_path, destination_folder_path, ...
2,072
574
from faults.faultmodel import FaultModel from utils import * class FLP(FaultModel): name = 'FLP' docs = ' FLP addr significance \t flip one specific bit' nb_args = 2 def __init__(self, config, args): super().__init__(config, args) self.addr = parse_addr(args[0]) check_or_fa...
1,009
337
import pytest from traitlets import TraitError from ipygany import PolyMesh, Warp from .utils import get_test_assets def test_default_input(): vertices, triangles, data_1d, data_3d = get_test_assets() poly = PolyMesh(vertices=vertices, triangle_indices=triangles, data=[data_1d, data_3d]) warped_mesh ...
1,488
648
""" The template of the script for playing the game in the ml mode """ class MLPlay: def __init__(self): """ Constructor """ self.direction = 0#上下左右 :1,2,3,4 self.current_x = 0 self.current_y = 0 self.last_x = 0 self.last_y = 0 self.x_dir = 0...
3,120
1,040
#!/usr/bin/env python3 # coding:utf-8 class Solution: def GetNumberOfK(self, data, k): if data == [] or k > data[-1]: return 0 def binSearch(data, num): left = 0 right = len(data) - 1 while left < right: mid = left + (right - left) /...
856
317
# Copyright 2022 Canonical Ltd. # See LICENSE file for licensing details. from typing import Union from ops.model import Application, Relation, Unit class BaseException(Exception): """Base exception for exceptions from this library.""" class InvalidRoleError(BaseException): """The specified role is not one...
2,850
767
import torch import torch.nn as nn from torchvision import models from torch.autograd import Variable from torch.nn.parameter import Parameter from DeepImageDenoiser import LR_THRESHOLD, DIMENSION, LEARNING_RATE from NeuralModels import SpectralNorm ITERATION_LIMIT = int(1e6) SQUEEZENET_CONFIG = {'dnn' : models.squ...
23,356
8,171
from flask import render_template,request,redirect,url_for from .import main from ..request import get_sources,get_articles from ..models import News_article,News_source @main.route('/') def index(): ''' Home page function returns news sources ''' news_sources = get_sources() title = "Welcome" ...
682
197
from models import Mongua class Todo(Mongua): __field__ = Mongua.__fields__ + [ ('title', str, ''), ('completed', bool, False), ] @classmethod def update(cls, id, form): t = cls.find(id) valid_names = [ 'title', 'completed' ] for...
724
246
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: Party.py Author: Scott Yang(Scott) Email: yangyingfa@skybility.com Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved. Description: """ class Party(object): def __init__(self, capacity): self._capacity = capacity def...
371
132
#!/usr/bin/env python import os import shutil import sqlite3 import unittest import init_db '''name of database to use as master''' master_name = 'projects.db' def setUpModule(): '''create and fill the database''' conn = sqlite3.connect(master_name) init_db.execute_file(conn, 'create_db.sql') init...
11,517
3,171
import json from django.http.response import JsonResponse from django.db.models import Q from django.contrib.auth import authenticate from rest_framework import viewsets, mixins from rest_framework.permissions import IsAuthenticated from rest_framework.exceptions import ValidationError, AuthenticationFailed from rest_...
3,668
1,026
def plusdash(plus, dash): for i in range((plus-1)*dash + plus): if i%(dash+1)==0: print('+', end='') else: print('-', end='') print('') def pipe(pipe, space): for i in range((pipe-1)*space + pipe): if i % (space+1) == 0: print('|', end='') ...
1,257
458
import os def get_comm_no(community_id, community_dict): community_id = str(community_id) if community_id in community_dict: return community_dict[community_id] else: return 0 def edgeWeightBipartiteGraphGenerator( layer1, layer2, layer1CommunityFile, layer2CommunityFile, ...
2,624
1,001
from datetime import datetime import logging import json import csv from io import StringIO import pymongo from bson.objectid import ObjectId from . import PUBLICATION_TYPES, PROJECTS, SITES def nowstr(): return datetime.utcnow().isoformat() def date_format(datestring): if 'T' in datestring: if '.' ...
5,171
1,560
#!/usr/bin/env python3 # Copyright (c) 2015-2021 Agalmic Ventures LLC (www.agalmicventures.com) # # 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 limit...
2,534
827
import chainer import pytest def pytest_addoption(parser): parser.addoption( '--value-check-runtime', dest='value-check-runtime', default='onnxruntime', choices=['skip', 'onnxruntime', 'mxnet'], help='select test runtime') @pytest.fixture(scope='function') def disable_experimental_warnin...
545
159
#!/usr/bin/python import BoostBuild t = BoostBuild.Tester() t.write("test.jam",""" actions unbuilt { } unbuilt all ; ECHO "Hi" ; """) t.run_build_system("-ftest.jam", stdout="Hi\n") t.pass_test()
200
88
class MyClass: def __init__(self): pass def func1(self): pass def func2(self): pass def func3(self): pass class MyClass2: def __init__(self): pass a, b = MyClass(), MyClass2() c, (d, e) = a.func1, (a.func2, a.func3) c() d() e()
295
116
from .language import Language from .user_tweet_raw import UserTweetRaw
72
21
import numpy as np from math import ceil,floor class ColorfulData: """ Create custom evenly distributed color palete \n`Get_Colors_Matched`: key,value relationship evenly distributed for given unique values \n`Get_Colors`: Evenly distributed for given length """ @staticmethod def Get_Color...
2,471
776
""" Encodes SPOT MILP as the structure of a CART tree in order to apply CART's pruning method Also supports traverse() which traverses the tree """ import numpy as np from mtp_SPO2CART import MTP_SPO2CART from decision_problem_solver import* from scipy.spatial import distance def truncate_train_x(train_x, train_x_pre...
6,453
2,137
# This package uses tk to create a simple graphical # output representing the iDrive state import tkinter as tk import numpy as np # why not use the numpy native? but whatever def rotate_2D(vector, angle): r = np.array([[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]]) return r.d...
2,954
1,448
class AtomType(): """ Class for each atom type. """ def __init__( self, atom_type_index, label, element_type, mass, charge, core_shell=None ): """ Initialise an instance for each atom type in the structure. Args: atom_type_index (int): Integer index for this ato...
2,054
536
class Solution: def scoreOfParentheses(self, S: str) -> int: stack, score = [], 0 for s in S: if s == '(': stack.append("(") else: last = stack[-1] if last == '(': stack.pop() sta...
641
161
import numpy as np from scipy import stats import utils def fit(xdata, ydata): """Calculate 2D regression. Args: xdata (numpy.ndarray): 1D array of independent data [ntim], where ntim is the number of time points (or other independent points). ydata (numpy.ndarray): 2...
2,116
750
from event import Event class BuffTimeOut(Event): def __init__(self, buff, rotation, engine, char_state, priority): super().__init__('buff_time_out', priority) self.buff = buff self.rotation = rotation self.engine = engine self.char_state = char_state def act(self): ...
796
249
import socket import threading import json PORT = 5000 SERVER = socket.gethostbyname(socket.gethostname()) ADDRESS = ('', PORT) FORMAT = 'utf-8' clients, names = [], [] server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDRESS) def StartChat(): print(f'server is working on: {SERVER}') ...
2,017
584
"""Modules related specifically to the handling of synchronous requests from a supplier system."""
99
21
import gi import time gi.require_version('Gtk', '3.0') from gi.repository import Gtk,GObject,Gdk,Pango,GLib from wta_module import * # Generated By WiredGTK for Python: by Rocky Nuarin, 2018 Phils # #####################www.WireThemAll.com##################### class Handler(usercontrol): #WiredEvent def usercontrolev...
3,636
1,490
from slam_recognition.constant_convolutions.center_surround import rgby_3 from slam_recognition.util.get_dimensions import get_dimensions import tensorflow as tf def rgby_filter(tensor # type: tf.Tensor ): n_dimensions = get_dimensions(tensor) rgby = rgby_3(n_dimensions) conv_rgby = tf.co...
561
199
""" Adapted from https://github.com/huggingface/transformers/blob/master/examples/run_generation.py """ import re import torch import logging from typing import List from collections import defaultdict from transformers import GPT2Tokenizer, XLNetTokenizer, TransfoXLTokenizer, OpenAIGPTTokenizer from transformers impo...
6,293
1,983
from .handlers import router as internal_router __all__ = ["internal_router"]
79
23
import pprint # message message = ''' Books and doors are the same thing books. You open them, and you go through into another world. ''' # split message to words into a list words = message.split() # define dictionary counter count = {} # traverse every word and accumulate for word in words: if not word[-1].isal...
440
145
# Copyright 2021 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 or agreed to in writing, ...
1,959
622
from dataclasses import dataclass from typing import Iterable from minsk.analysis.syntax.expression import ExpressionSyntax from minsk.analysis.syntax.kind import SyntaxKind from minsk.analysis.syntax.node import SyntaxNode from minsk.analysis.syntax.token import SyntaxToken @dataclass(frozen=True) class Parenthesiz...
749
198
#!/usr/bin/python # -*- coding: iso-8859-1 -*- import logging from peachyprinter import config, PrinterAPI import argparse import os import sys import time from Tkinter import * from ui.main_ui import MainUI class PeachyPrinterTools(Tk): def __init__(self, parent, path): Tk.__init__(self, parent) ...
3,113
1,020
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from env_variables import SQL_ALCHEMY_URL _db_url_without_db = '/'.join(SQL_ALCHEMY_URL.split('/')[:-1]) engine = create_engine(f'{_db_url_without_db}', isolation_level='AUTOCOMMIT', echo=True) Session = sessionmaker(engine) def create_dat...
813
262
def threeRailEncrypt(plainText): plainText = plainText.lower() cipherText = "" rail1 = "" rail2 = "" rail3 = "" for i in range(len(plainText)): if i%3 == 0: rail1 += plainText[i] elif i%3 == 1: rail2 += plainText[i] else: rail3 += plainText[i] cipherTe...
404
150
import torch from random import random from torch.nn.utils.rnn import pad_sequence from torch.utils.data import Dataset def collate_fn(batch): ''' Batch-wise preprocessing and padding. :param batch: the current batch. :returns: padded sources, targets, alignments stacks an...
2,382
797
from . import StocklabObject class Crawler(StocklabObject): """The base class for stocklab Crawlers.""" def __init__(self): super().__init__() class CrawlerTrigger(Exception): """ A `Node` will raise this exception when the required data is not locally available (e.g. not in the database)....
649
185
""" A collection of routines for validating, santizing and otherwise messing with content coming in from the web to be :py:class:`tiddlers <tiddlyweb.model.tiddler.Tidder>`, :py:class:`bags <tiddlyweb.model.bag.Bag>` or :py:class:`recipes <tiddlyweb.model.recipe.Recipe>`. The validators can be extended by adding funct...
4,514
1,401
# -*- coding: utf-8 -*- """ Created on Tue May 11 15:31:31 2021 :copyright: Jared Peacock (jpeacock@usgs.gov) :license: MIT """ from pathlib import Path import pandas as pd import numpy as np import logging from mth5.timeseries import ChannelTS, RunTS from mt_metadata.timeseries import Station, Run class LE...
6,548
2,015
import abc import logging import os import pickle from collections import Counter from datetime import datetime from typing import List, Union import numpy as np _logger = logging.getLogger(__name__) class Transformation(abc.ABC): @abc.abstractmethod def analyze(self, raw: object) -> object: pass ...
4,895
1,507
"""Initialize unittest."""
27
9
import pytest from pytest import param as p from anglicize import anglicize, build_mapping @pytest.mark.parametrize( "text, expected", [ p("Abc 123", "Abc 123", id="noop"), p("ĂaÂâÎîȘșȚț", "AaAaIiSsTt", id="romanian"), p("ĄąĆćĘꣳŃńŹźŻż", "AaCcEeLlNnZzZz", id="polish"), p("ÁáÉ...
2,402
1,304
import baopig as bp import images as im # TODO : a city defines the style, a district defines the content
109
33
from datetime import datetime from flask import render_template, flash, redirect, url_for, request from flask_login import login_user, logout_user, current_user, login_required from werkzeug.urls import url_parse from app import app, db from app.forms import LoginForm, RegistrationForm, EditProfileForm, PostForm, ...
11,426
3,584
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait success = True wd = webdriver.Firefox() wait = WebDriverWait(wd, 22) def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False try: wd.ge...
2,147
773
import logging import re from datetime import timezone import pendulum from aioscheduler import TimedScheduler from dateparser import parse from discord.ext import commands from discord.ext.menus import MenuPages import db from cogs import CustomCog, AinitMixin from cogs.Logging import log_usage from const import UNI...
7,035
2,109
import json import base64 import os import boto3 import zlib # Used for decryption of the received payload import aws_encryption_sdk from aws_encryption_sdk import CommitmentPolicy from aws_encryption_sdk.internal.crypto import WrappingKey from aws_encryption_sdk.key_providers.raw import RawMasterKeyProvider from aws_...
4,598
1,466
from django.contrib import admin from .models import Location class LocationAdmin(admin.ModelAdmin): list_display = ["id", "city", "region"] admin.site.register(Location, LocationAdmin)
195
56
# -*- coding: utf-8 -*- # @Date : 2022/4/13 12:07 # @Author : WangYihao # @File : __init__.py.py from SimCam.simcam import SimCam
138
70
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class iSCSI_Data_Out(Base): __slots__ = () _SDM_NAME = 'iSCSI_Data_Out' _SDM_ATT_MAP = { 'Opcode': 'iSCSI_Data_Out.header.Opcode', 'Flags': 'iSCSI_Data_Out.header.Flags', 'TotalAHSLength': 'iSCSI_Data_O...
3,315
1,119
# Generated by Django 4.0.2 on 2022-02-16 14:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rated', '0004_profileapi'), ] operations = [ migrations.DeleteModel( name='ProfileAPI', ), ]
289
104
import cv2 import numpy as np from skimage import exposure as ex from skimage import data from PIL import Image import skfuzzy as fuzz import math import timeit import time ''' Histogram equalization with colour YCR_CB and histogram equalization only on Y @img: the image to modify @return: the image with the histogr...
9,449
3,722
#!/usr/bin/env python """ make_known_good_cice_masks.py Copy known good CICE masks for use in fixing the HadGEM CICE masks. """ import os import numpy as np from netCDF4 import Dataset OUTPUT_DIR = "/gws/nopw/j04/primavera1/masks/HadGEM3Ocean_fixes/cice_masks" def main(): """main entry""" rootgrp = Dataset...
1,812
792
from datetime import timedelta class Statistics: def __init__(self, velocity, dist): # Calculate time self.lap_time = 0 dist_travelled = [] self.time = [] for i in range(len(velocity)): dist_travelled.append(0) self.time.append(0) if i ...
1,071
374
# -*- coding: utf-8 -*- import logging import configparser class Config(object): def __init__(self, filename): logging.config.fileConfig(filename) config = configparser.RawConfigParser() config.read(filename) for option, value in config.items(self.name): try: ...
756
207
import os import subprocess from dotenv import load_dotenv import pymongo from pymongo import MongoClient from pymongo.cursor import Cursor from pymongo.errors import DuplicateKeyError, BulkWriteError from util.args import Args load_dotenv() class Database: def __init__(self, uri=Args.db_host()): self....
2,817
914
from enum import Enum from typing import Union from iqa_common.executor import Command, Execution, ExecutorAnsible, CommandAnsible, ExecutorContainer, \ CommandContainer, Executor from iqa_common.utils.docker_util import DockerUtil from messaging_abstract.component import Service, ServiceStatus import logging cl...
4,066
1,074
import numpy as np from ..mixins import Preprocessor, AlwaysPredictPlotter, AdvantageEstimator from warnings import warn class Bootstrap(Preprocessor, AlwaysPredictPlotter, AdvantageEstimator): def __init__(self, elex_frame, covariate_columns=None, weight_column=None, share_colum...
4,836
1,209
import logging logging.warning('warning message') logging.error('This is an error message') logging.critical('This is a critical error message')
147
39
from textblob import TextBlob a = str(input("enter your word to check spell") _b = TextBlob(a) print (_b.correct()) # from textblob import Textblob #mylst = ["firt","clor"] #correct_list = [] #for word in mylst: # correct_list.append(TextBlob()) # #for word in correct_list: # print (word.correct())
304
112
from __future__ import division import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.special import jn, jn_zeros import subprocess def drumhead_height(n, k, distance, angle, t): nth_zero = jn_zeros(n, k) return np.cos(...
1,657
709
import scrapy from bs4 import BeautifulSoup import requests from QB5.pipelines import dbHandle from QB5.items import Qb5Item class Qb5Spider(scrapy.Spider): name = 'qb5' allowed_domains = ['qb5.tw'] start_urls = ['https://qb5.tw'] def parse(self, response): soup = BeautifulSoup(response.text) ...
704
234
""" :mod: 'BookDatabaseUtility' ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:module:: BookDatabaseUtility :copyright: Copyright BitWorks LLC, All rights reserved. :license: MIT :synopsis: SQLAlchemy ORM engine, metadata, and utility functions for working with dynamic sqlite databases :description: Contains the f...
36,514
9,543
""" Module for math and statistics related functions. """
58
15
import itertools import numpy as np import constants from utils import file class MarkovChain: def __init__(self, n_items: int, pseudo_count: int = 1, use_rejection: bool = True): self.n_items = n_items self.counts = np.empty(n_items) self.first_order_counts = np.empty((n...
3,491
1,124
ACCURACY :::62.86377259982597
31
27
import bsddb.db as bdb import os.path import cPickle from base64 import b64encode, b64decode from struct import pack def toUniqueString(d): if isinstance(d, int) or isinstance(d, float) or isinstance(d, long): s = 'n' + repr(d) elif isinstance(d, str): s = 's' + d elif isinstance(d, list):...
11,611
3,454
# Copyright 2022 AI Singapore # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
1,668
564
# ============================================================================= # Copyright (c) 2021 SeisSpark (https://github.com/kdeyev/SeisSpark). # # 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 Lice...
2,684
879
from unittest import TestCase from unittest import TestSuite from unittest import main from unittest import makeSuite from mwstools.parsers.notifications import Notification class Dummy(object): """ Only used for test_notification_payload since there is not actually a payload to test. """ def __init...
1,116
326
import json from pathlib import Path from typing import Union import jsonschema import yaml class Configuration(object): def load(self, filepath: Union[str, Path]): with Path(filepath).open("r") as file: state = yaml.load(file, Loader=yaml.FullLoader) script_dir = Path(__file__).pare...
1,025
309
from .Event import Event
25
7
import nltk from nltk.chunk.regexp import ChunkString, ChunkRule, ChinkRule from nltk.tree import Tree from nltk.chunk import RegexpParser from nltk.corpus import conll2000 from nltk.tag import NgramTagger #class for Unigram Chunking class UnigramChunker(nltk.ChunkParserI): def __init__(self, train_sents): ...
4,415
1,769
# Imports from os.path import join, isfile from os import remove, rmdir from pysav import Save, does_save_exist, does_app_dir_exist, generate_environment_path from utils.random_data import generate_dict # Test def test_answer(): """Does Save work as expected""" # Test Importing # Create file to be importe...
3,014
880
import doctest import pytest from insights.parsers import ansible_tower_settings, SkipException from insights.tests import context_wrap ANSIBLE_TOWER_CONFIG_CUSTOM = ''' AWX_CLEANUP_PATHS = False LOGGING['handlers']['tower_warnings']['level'] = 'DEBUG' '''.strip() ANSIBLE_TOWER_CONFIG_CUSTOM_INVALID1 = ''' '''.strip...
1,250
467
import os import json from app.config import DATA_PATH """ _id: ID date: 日期 eg "2020-02-06T15:24:59.942Z" msg: 消息内容 eg "这是内容" status: 状态 eg "😫" (a emoji) """ def get_zones(): with open(os.path.join(DATA_PATH, 'zone.json'), 'r') as f: data = json.load(f) return data['data'] de...
1,320
539
import random import pprint import matplotlib.pyplot as plt import numpy as np from cells import * pp = pprint.PrettyPrinter(indent=2) random.seed(5) def get_image_from_state(cells, time, debug=False): """ Generates an image from the cell states """ # print("time: ", time) img = [] for rix,...
2,534
881
#! /usr/bin/python3 import time from events import * def test1(foo, *args): print("foo: %s otherargs: %s time: %06.3f" % (foo, args, time.time() % 100)) q = QueueExecutor() q.addEvent(test1, time.time() + 3, 1, 5, "foo", "bar", "baz") q.addEvent(test1, time.time() + .5, .3, 20, "foo2", "bar") print("Main thread as...
415
181
from typing import Any, Callable, Dict, Iterable, Mapping, Tuple, TypeVar, Union, cast, overload __all__ = ("extract_iterable_from_tuple", "is_iterable", "item_to_tuple", "mapping_merge") KT = TypeVar("KT") VT = TypeVar("VT") T = TypeVar("T") def mapping_merge(*mappings: Mapping[KT, VT], **arguments: VT) -> Dict[K...
1,845
684
import numpy as np from spacetime.potential import Potential class DistortedSchwarzschild(Potential): def __init__(self, theta=np.pi/2, l=3.8, o=1, r_range=(2, 20), num=10000, cont_without_eq=False, verbose=True): super().__init__(r_range=r_range, num=num, cont_wit...
937
360
from typing import Tuple, List from algosdk.v2client.algod import AlgodClient from algosdk.future import transaction from algosdk.logic import get_application_address from algosdk import account, encoding from pyteal import compileTeal, Mode, Keccak256 from tellorflex.methods import report from utils.account import ...
7,672
2,217
#### #### Convert a TSV into a fully parsed JSON list blob that could be #### used by a mustache (or other logicless) template. #### #### Example usage to analyze the usual suspects: #### python3 parse.py --help #### #### Get report of current problems: #### python3 parse-vocab-list.py --tsv ~/Downloads/UCSC中上級教科書_漢字...
11,118
3,128
import builtins, importlib class Importer(object): """An Importer imports either a namespace or a symbol within a namespace. It's like a more general version of importlib.import_module which handles builtins and attributes within a module. An Importer has a symbol_table that's always used to try to ...
2,716
682
from app import app, db from app.models import * import datetime import sys sys.path.append('./sanitize') from sanitize_utils import * from trueskill import setup, Rating, quality_1vs1, rate_1vs1 from trueskill_functions import MU, SIGMA, CONS_MU, BETA, TAU, DRAW_PROBABILITY, populate_trueskills from misc_utils impor...
13,190
4,269
# coding=utf-8 # # Copyright (c) 2015 EMC Corporation # All Rights Reserved # import httplib import cjson import argparse import sys import os import time import json import uuid import base64 import urllib import requests import email from email.Utils import formatdate import cookielib import telnetlib import xml.etr...
406,902
127,980
# -*- coding: utf-8 -*- """ @author: stoberblog @detail: This is a configuration file for the Solar Modbus project. """ # MODBUS DETAILS INVERTER_IP = "192.168.1.29" MODBUS_PORT = 7502 METER_ADDR = 240 MODBUS_TIMEOUT = 30 #seconds to wait before failure # METER INSTALLED METER_INSTALLED =...
851
355
from async_asgi_testclient import TestClient from myapp import main import pytest @pytest.mark.asyncio async def test_willpyre_app(): async with TestClient(main) as client: resp = await client.get("/") assert resp.status_code == 200 assert resp.text == "index page" @pytest.mark.asyncio ...
2,533
808
from .backlight_mode import BacklightMode from .angle_unit import AngleUnit from .measurement_unit import MeasurementUnit
122
34
import random from operations import abstract_operation class Plus(abstract_operation.AbstractOperation): a = 0 b = 0 def __init__(self): super().__init__("+", "Addieren") def get_question(self): return "{} + {}".format(str(self.a), str(self.b)) def solve(self): return ...
577
232