content
stringlengths
5
1.05M
# coding: utf-8 from sqlalchemy import CHAR, Column, Date, Float, ForeignKey, Integer, LargeBinary, SmallInteger, String, Table, Text, text from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Category(Base): __ta...
from art import logo, vs from data import data import random print(logo) my_score = 0 missed = True while missed: random_data1 = random.choice(data) score_1 = random_data1["follower_count"] random_data2 = random.choice(data) score_2 = random_data2["follower_count"] print(f"Compare A: {rando...
from typing import List, Optional from aws_cdk.aws_lambda import Runtime from aws_cdk.core import Stack from b_cfn_lambda_layer.lambda_layer import LambdaLayer class OpensearchIndexLayer(LambdaLayer): def __init__( self, scope: Stack, name: str ) -> None: super().__init__( ...
import no_pda_exceptions as e class NOPDA(object): def __init__(self, rules, input_alphabet, states, initial_states, terminate_states): self.rules = rules self.input_alphabet = input_alphabet self.states = states self.current_state = initial_states self.ter...
# Generated by Django 3.1.13 on 2022-05-28 00:03 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', model...
# -*- coding: utf-8 -*- """ Created on Tue Apr 21 16:29:21 2020 @author: willi """ import re try: from snapgene_reader import snapgene_file_to_dict, snapgene_file_to_seqrecord except: pass try: from Bio import SeqIO from Bio import Entrez except: pass import os class FileParser(): ''' Cl...
#!/usr/bin/python3.8 import time from flask import render_template, flash, redirect, url_for, request from flask_login import login_user, current_user, logout_user, login_required from werkzeug.utils import secure_filename from webapp import app, config, db, db_manager, bcrypt from webapp.models import User from webap...
import numpy as np from config import Config def compute_challenge_metric_custom(res,lbls,normalize=True): normal_class = '426783006' normal_index=Config.HASH_TABLE[0][normal_class] lbls=lbls>0 res=res>0 weights = Config.loaded_weigths observed_score=np.sum(weights*get_...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt import copy import frappe import frappe.share from frappe import _, msgprint from frappe.utils import cint rights = ("select", "read", "write", "create", "delete", "submit", "cancel", "amend", "print", "email", "repor...
#!/usr/bin/python import os,sys import lcm import time home_dir =os.getenv("HOME") #print home_dir sys.path.append(home_dir + "/drc/software/build/lib/python2.7/site-packages") sys.path.append(home_dir + "/drc/software/build/lib/python2.7/dist-packages") from ipab.pause_command_message_t import pause_command_message_...
from exporters.logger.base_logger import TransformLogger from exporters.pipeline.base_pipeline_item import BasePipelineItem class BaseTransform(BasePipelineItem): """ This module receives a batch and writes it where needed. It can implement the following methods: """ def __init__(self, options, metad...
from Acccount import Account class Drive(Account): type = int activo = int def __init__(self, name, document, type, activo): super().__init__(name, document) self.type = type self.activo = activo
import unittest from app.models import Source class SourceTest(unittest.TestCase): ''' Test Class to test the behaviour of the Source class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_source = Source(1,"Washington Post", "Leading ...
""" opstate.py "Specification of the OpState class." @author: Johan Monster (https://github.com/Hans-Bananendans/) """ class OpState: """This class represents a separate operational state, and can be used to calculate used power values and separate these by channel.""" def __init__(self, device_powe...
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# -*- coding: utf-8 -*- from ..setup.constants import NETWORK_DEVICE, SERIAL_DEVICE from ..user import User, UserDetail from ..settings import Setting from ..certificate import Certificate from ..notifications import Notification, NotificationSetting from ..zones import Zone from ..keypad import KeypadButton HOSTS_FI...
################################################################################ # # Copyright (C) 2013-2015, Michele Cappellari # E-mail: michele.cappellari_at_physics.ox.ac.uk # # Updated versions of the software are available from my web page # http://purl.org/cappellari/software # # This software is provide...
from typing import Optional from asserts import ( assert_equal, assert_false, assert_raises, assert_succeeds, assert_true, ) from dectest import TestCase, test from dbupgrade.args import Arguments from dbupgrade.files import FileInfo from dbupgrade.filter import ( MAX_API_LEVEL, MAX_VERSIO...
# -*- coding: utf-8 -*- from django.core.management import CommandError, call_command from django.test import TestCase from django.test.utils import override_settings from six import StringIO try: from unittest import mock except ImportError: import mock class ResetSchemaExceptionsTests(TestCase): """Tes...
from django.db.models.manager import BaseManager from .querysets import LocationQuerySet class LocationManager(BaseManager.from_queryset(LocationQuerySet)): """ Manager class for location models constructed from LocationQuerySet. Uses miles as distance unit. """
from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager from panel.models import Discount from product.models import Product,ProductDetail # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self,email,first_name,last_name,password): ...
#!/pxrpythonsubst # # Copyright 2020 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # ...
#! /usr/bin/env python3 # Copyright 2019 Samsung Research America # # 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 app...
import discord import youtube_dl import os #import ffprobe from discord.ext import commands from discord.utils import get from discord import FFmpegPCMAudio from os import system from packages.CRITICAL.CLIENT import client from packages.CRITICAL.VERSION import EJ_DJ_VERSION import asyncio import subprocess import urlli...
from applications_superstaq._init_vars import API_URL, API_VERSION from applications_superstaq.superstaq_exceptions import ( SuperstaQException, SuperstaQModuleNotFoundException, SuperstaQNotFoundException, SuperstaQUnsuccessfulJobException, ) from . import converters from . import finance from . import...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # pycreviewer: source_file_parser.py # Dromar [https://github.com/dromar-soft] # License: MIT #------------------------------------------------------------------------------ from pycparser import parse_file, c_genera...
import random import sc2 from sc2 import Race, Difficulty from sc2.constants import * from sc2.player import Bot, Computer from sc2.position import Point2, Point3 class RampWallBot(sc2.BotAI): async def on_step(self, iteration): cc = self.units(COMMANDCENTER) if not cc.exists: return ...
from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from .managers import MetaTagManag...
import torch import torch.nn as nn def weights_init(m): if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight.data) nn.init.constant_(m.bias, 0.1) class PNet(nn.Module): ''' PNet ''' def __init__(self, ): super(PNet, self).__init__() # ...
from bayesnet.tensor.constant import Constant from bayesnet.tensor.tensor import Tensor from bayesnet.function import Function class Negative(Function): """ element-wise negative y = -x """ def forward(self, x): x = self._convert2tensor(x) self.x = x if isinstance(self.x, ...
""" This script takes the LIRICAL output TSV and converts it to a format that can be uploaded to seqr (pending implementation of https://github.com/broadinstitute/seqr/issues/2742). """ import argparse import pandas as pd import re from utils.gene_ids import get_entrez_to_ensembl_id_map def main(): p = argparse...
import discord from discord.ext import commands from discord.ext.commands import cooldown from discord.ext.commands.cooldowns import BucketType import time import asyncio import asyncpg from datetime import datetime, timedelta from random import randint from random import choice import psutil import os import sys colo...
from numbers import Number class TresholdEqual: """ Implementation of numeric objects considered equal when within a specified tolerance. The optional 'tolerance' parameter defaults to 1. Only comparison operators are implemented. Attempt to compare with objects of different types raises Ty...
# -*- coding: utf-8 -*- """ Created on Tue Dec 24 20:43:09 2019 @author: elif.ayvali """ import sys import gym import pandas as pd import numpy as np import matplotlib.collections as mc import matplotlib.pyplot as plt from helpers import create_uniform_grid,discretize,visualize_samples class QLearningAgent: """Q...
import numpy as np from dgl.frame import Frame, FrameRef from dgl.utils import Index, toindex import backend as F import dgl import unittest N = 10 D = 5 def check_fail(fn): try: fn() return False except: return True def create_test_data(grad=False): c1 = F.randn((N, D)) c2 = ...
# Open The Text File & 'Read' It # Insert The File Path Between The Brackets & Quotation Marks with open(" ", "r") as file: # Read The File & Write The First Replace Method remove_1 = file.read().replace(" .", ".") # Remaining Replace Methods remove_2 = remove_1.replace(" , ", ", ") remove_3 = remove_...
import os,re,sys # initializing bad_chars_list bad_chars = [',', ';', ':', '!', '.', '(', ')', '"', "*"] #filename="mat2vec-1a5b3240-abstracts-head.csv" filename=sys.argv[1] #"mat2vec-1a5b3240-abstracts.csv" print(filename) filename_w="cleaned_"+filename with open( filename_w, 'a+') as corpus_w: with open(filena...
### INTERACTIVE NAPLPS DEMO ### ### Interact with NAPLPS Client (PP3) over a serial connection ### ### John Durno, January 2017 ### ### Added auto-advance April 2017 ### ### Added chunks April 2017 ### ### Added quit (q) April 2017 ### ### Added timeout (auto=M) May 2017 ### ## Imports ### import collections import se...
from flask import Flask, abort, jsonify, request from flask_restful import Resource, reqparse from flask_cors import CORS app = Flask(__name__) CORS(app) ## DUMMY DATA ## currencies = [ { "name": "btc", "balance": "0.65448", "address": "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2", "seeds":...
import os import copy import random import functools from datetime import datetime import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.utils.data as data import torch.utils.tensorboard as tensorboard from core.model import NAC from core.metric import AverageMe...
from crowd_sim.envs.utils.agent import Agent from crowd_sim.envs.utils.state import JointState class Human(Agent): # see Agent class in agent.py for details!!! def __init__(self, config, section): super().__init__(config, section) self.isObstacle = False # whether the human is a static obstac...
# _*_ coding: utf-8 _*_ import multiprocessing from gensim.test.utils import datapath from gensim.models.word2vec import LineSentence from gensim.models.word2vec import PathLineSentences from gensim.models import word2vec from gensim.models import Word2Vec from gensim.models import KeyedVectors from gensim.utils.util...
""" This package contains utilities that are only used when developing drms in a copy of the source repository. These files are not installed, and should not be assumed to exist at runtime. """
#!/usr/bin/env python ## # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ...
/home/runner/.cache/pip/pool/9d/74/0a/c53d742787105b6eebdef5c502cadfb8aaf2c96273099593c4c552f563
from .tictactoe import * from .connectfour import *
from django.urls import path from . import views urlpatterns = [ path('users/', views.usersView.get, name='usersUrl'), path('users/search', views.usersView.search, name='usersSearchUrl'), path('users/<str:username>/', views.usersView.selected, name="selectedUserUrl"), path('repos/', views.reposView...
import argparse from core import compat, app, utils, colors from core.ctrl import api compat.check_version() app.mode = 'cli' parser = argparse.ArgumentParser( description="CTRL command line tool", epilog="All accessible arguments listed above" ) parser.add_argument('method', help="Specify API method") parse...
from k5test import * plugin = os.path.join(buildtop, "plugins", "hostrealm", "test", "hostrealm_test.so") # Disable the "dns" module (we can't easily test TXT lookups) and # arrange the remaining modules in an order which makes sense for most # tests. conf = {'plugins': {'hostrealm': {'module': ...
""" @brief: fill queue with new tasks read from tasks file. """ import pika import sys from .ip_provider import get_valid_ip def create_new_tasks(fn,broker): tasks=[] with open(fn,"r") as f: for line in f: tasks.append(line) connection = pika.BlockingConnection(pika.ConnectionParamet...
''' @file: MPNCOV.py @author: Jiangtao Xie @author: Peihua Li Copyright (C) 2018 Peihua Li and Jiangtao Xie All rights reserved. ''' import torch import numpy as np from torch.autograd import Function class Covpool(Function): @staticmethod def forward(ctx, input): x = input batchSize = x....
# Copyright 2013 Nebula Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
import pytest from constants.pipelines import OperationStatuses, PipelineStatuses from factories.factory_pipelines import OperationRunFactory from pipelines.celery_task import ClassBasedTask, OperationTask from polyaxon.celery_api import app as celery_app from tests.utils import BaseTest @pytest.mark.pipelines_mark ...
import os import pygame from game_defines import DIRECTIONS ASSET_BASE = os.path.join(os.path.dirname(__file__), "assets") class Actor(object): @staticmethod def asset(name): return os.path.join(ASSET_BASE, name) def __init__(self, name, image_path, actor_type, startx, starty): self...
""" File: 240.py Title: Search a 2D Matrix II Difficulty: Medium URL: https://leetcode.com/problems/search-a-2d-matrix-ii/ """ import unittest from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: m = len(matrix) n = len(mat...
# -*- coding: utf-8 -*- """ safedun-server Created on Sun Oct 13 00:00:00 2019 Author: Adil Rahman GitHub: https://github.com/adildsw/safedun-server """ import argparse import socket from backend import safedun from flask import Flask, render_template, request, send_file app = Flask(__name__) @app.route('/') def ...
"""The Policy can use these classes to communicate with Vizier.""" import abc import collections import dataclasses import datetime from typing import Dict, Iterable, List, Optional from vizier import pyvizier as vz @dataclasses.dataclass(frozen=True) class MetadataDelta: """Carries cumulative delta for a batch m...
from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^sponsor/$', views.sponsor, name='sponsor'), url(r'^hospitality/$', views.hospitality, name='hospitality'), url(r'^transport/$', views.tran...
import numpy as np import math import pandas as pd ####################################################################### """ These functions are applied to hierarchically classify the images. level_n(x): determines the prediction at level n. If there is no prediction to be made at level n, the function returns nan....
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.utils import timezone from django.views import generic from .models import Choice, Question # Create your views here. class IndexView(generic.ListView): template_name =...
#!/usr/bin/env python import sys from os import listdir def proc_files(files): fs = [] for f in files: try: fs.append(open(f, "r")) except Exception as exct: print("Failed to read file {:s}".format(f)) sys.exit(1) done = False result = [] whil...
"""Define language independent properties at the module level""" from adam.language.lexicon import LexiconEntry, LexiconProperty from adam.language.dependency import MorphosyntacticProperty # Define universal morphosyntactic properties FIRST_PERSON = MorphosyntacticProperty("1p") SECOND_PERSON = MorphosyntacticPropert...
# -*- coding: utf-8 -*- """ Created on Wed Jan 6 16:31:59 2021 @author: msantamaria """ # Redes Neuronales Artificiales # Parte 1 - Pre procesado de datos # Importar las librerías import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importar el data set dataset = pd.read_csv("Churn_Modelling....
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-01-29 08:44 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('codenerix_products', '0008_auto_20180126_1711'), ('...
# %% from sklearn.metrics import r2_score import pandas as pd import numpy as np import matplotlib.pyplot as pl from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression # %% # Other type of file could be used which contains tabular data advertising = pd.read_csv("a...
# -*- coding: utf-8 -*- from collections import OrderedDict import os import re from lxml import etree from django.db.models import Count, Prefetch from selections.models import PreProcessFragment from stats.utils import get_label_properties_from_cache, prepare_label_cache from .models import Corpus, Tense, Alignm...
from math import exp import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models # from kornia.color import rgb_to_yuv from torch.nn.modules.loss import _Loss import numpy as np def gaussian(window_size, sigma): gauss = torch.Tensor([exp(-(x - window_size//2)*...
from rvsml.align import dtw2, OPW_w from rvsml.EvaluateRVSML import EvaluateRVSML_dtw from rvsml.NNClassifier import NNClassifier_dtw from rvsml.RVSML_OT_Learning import RVSML_OT_Learning_dtw
import sys class Foobar: def __init__(self, foobar="foobar"): self.foobar = foobar def __repr__(self): return(self.foobar)
import os import json import requests import telegram def custom_alert_slack(message): text = "" text = "%s" % message requests.post(os.getenv('SLACK_WEBHOOK'), data=json.dumps({"text": text}), headers={'Content-type': 'application/json'}) def publish_on_telegram_channel(chat_id, message, token=None, image=None): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author Eric Bullen <ebullen@linkedin.com> @application jtune.py @version 4.0.1 @abstract This tool will give detailed information about the running JVM in real-time. It produces useful information that can further assist the user ...
import os base_dir = os.getcwd() project_name = '{{cookiecutter.project_name}}' project_path = f'{project_name}' # https://github.com/cookiecutter/cookiecutter/issues/955 for root, dirs, files in os.walk(base_dir): for filename in files: # read file content with open(os.path.join(root, filename)) ...
import unittest from parameterized import parameterized as p from solns.combinationSum3.combinationSum3 import * class UnitTest_CombinationSum3(unittest.TestCase): @p.expand([ [] ]) def test_naive(self): pass
import pymongo class Database(object): # Database class inherits all attributes from object class URI = "mongodb://127.0.0.1:27017" # class attributes which defines a value for every class instance DATABASE = None @staticmethod def initialize(): # method that creates path to desired mongodb database...
from talon import Context, actions ctx = Context() ctx.matches = r""" app: mintty """ ctx.tags = ['terminal', 'user.file_manager', 'user.generic_terminal', 'user.git', 'user.kubectl'] @ctx.action_class('user') class UserActions: def file_manager_open_parent(): actions.insert('cd ..') actions.key('e...
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from django.conf.urls import url from . import views # The API URLs are now determined automatically by the router urlpatterns = [ url(r"^$", views.index, name="index_page"), url(r"^projects/create$", views.project_creat...
from flask import Flask, render_template from flask_cors import CORS from prometheus_client import Summary, MetricsHandler, Counter from agaveflask.utils import AgaveApi, handle_error from controllers import MetricsResource, CronResource from errors import errors app = Flask(__name__) CORS(app) api = AgaveApi(app, ...
#!/usr/local/bin/python import SimpleHTTPServer, SocketServer, logging, subprocess, sys, glob, re, mimetypes import argparse as argparse # Stop traceback on ctrl-c sys.tracebacklimit = 0 parser = argparse.ArgumentParser() parser.add_argument("-p", nargs='?', default=8000) parser.add_argument("-d", nargs='?', defaul...
import os import time import numpy as np import paddle.fluid as fluid import config as cfg from nets.attention_model import attention_train_net from nets.crnn_ctc_model import ctc_train_net from utils import data_reader from utils.utility import get_ctc_feeder_data, get_attention_feeder_data def main(): """OCR tr...
#Importing Libraries import os import cv2 import time import struct import socket import pyaudio import freenect import wikipedia import playsound import numpy as np from gtts import gTTS from scripts.rhino.rhino import * from scripts.porcupine.porcupine import * #Fucntion to get images def get_image(type, client): ...
from .publish_measurement_handler import PublishMeasurementTransactionHandler from .issue_ggo_transaction_handler import IssueGGOTransactionHandler from .transfer_ggo_handler import TransferGGOTransactionHandler from .split_ggo_handler import SplitGGOTransactionHandler from .retire_ggo_handler import RetireGGOTrans...
__author__ = 'guorongxu' import sys import re import math import logging def parse_correlation(correlation_file): correlation_list = {} with open(correlation_file) as fp: lines = fp.readlines() for line in lines: fields = re.split(r'\t+', line) correlation_list.update({...
"""Create grid-based spatial indexes. Basic Usage =========== Calculate the grid index or indices for a geometry provided in well-known binary format at a given resolution: Example: >>> from shapely.geometry import Point >>> pnt = Point(555000, 185000) >>> bng_pnt = calculate_bng_index( wkb = pn...
from enum import IntEnum class Finger(IntEnum): Thumb = 0 Index = 1 Middle = 2 Ring = 3 Little = 4 @staticmethod def get_array_of_points(finger): finger_array = None if finger == Finger.Thumb: finger_array = [(0, 4), (4, 3), (3, 2), (2, 1)] elif fing...
import torch import os import sys import re import logging from os.path import isfile import copy import threading import time import enum from torch.multiprocessing import Pool, Process, set_start_method, Manager, Value, Lock try: set_start_method('spawn') except RuntimeError: pass class CFMode(enum.Enum): MANU...
""" Expose PV data """ # # import logging # from datetime import datetime, timedelta # from typing import List # # from fastapi import APIRouter, Depends # from nowcasting_datamodel.models import PVYield # from nowcasting_datamodel.read.read_pv import get_latest_pv_yield, get_pv_systems # from sqlalchemy.orm.session im...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class HostManagementConfig(AppConfig): name = 'host_management'
import numpy as np from scipy.io import readsav class fts: ll = None ii = None cc = None nu = None datafile = './fts_disk_center.idlsave' def __init__(self): # watt / (cm2 ster AA) as emitted at solar surface t = readsav(self.datafile) # convert to ...
# Copyright (c) 2019 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
import discord from itertools import cycle from discord.ext import commands, tasks status = cycle(['Add ur text here','ur text here','ur text here','ur text here']) # you can add as much as you want EX: 'Stiizzy cat is hot','Name' bot = commands.Bot(command_prefix="!") # prefix will not be used for changng status @...
import logging from datetime import datetime from pprint import pprint from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import text from opennem.db import db_connect from opennem.db.load_fixtures import update_existing_geos from opennem.db.models.opennem import Fac...
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 # from http://stackoverflow.com/questions/15896217/django-loading-a-page-that- # has-external-authentication-changes-the-session-key class PersistentSessionMiddleware(object): """ Injects the username into REMOTE_USER so that ...
# -*- coding: UTF-8 -*- from mpi4py import MPI from sympy import pi, cos, sin from sympy.abc import x, y from sympy.utilities.lambdify import implemented_function import pytest from sympde.calculus import grad, dot from sympde.calculus import laplace from sympde.topology import ScalarFunctionSpace from sympde.topolog...
# Solution of; # Project Euler Problem 226: A Scoop of Blancmange # https://projecteuler.net/problem=226 # # The blancmange curve is the set of points $(x, y)$ such that $0 \le x \le 1$ # and $y = \sum \limits_{n = 0}^{\infty} {\dfrac{s(2^n x)}{2^n}}$, where # $s(x)$ is the distance from $x$ to the nearest integer. ...
from aiohttp import ClientSession from asyncio import get_event_loop class ManagedHTTP: def __init__(self): self.session = ClientSession() async def ensure_session(self): if self.session.closed: self.session = ClientSession() async def request(self, method: str, url: str, *ar...
"""Test the functions exposed at the top level of the module. This isn't a full test of each method's capabilities, just checking that the method is exposed at the top level namespace. """ import warnings import pytest import uk_politics import uk_politics.exceptions def test_color(): """Check that...
# Copyright 2018 Google Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Generated by Django 3.1.2 on 2020-10-25 14:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
name = 'membercount' aliases = ['members'] async def run(message): 'Lists the number of people that are in this server' true_member_count = message.guild.member_count await message.channel.send( f'There are **{true_member_count:,}** people in this server.' )
import subprocess as sp import os import shutil import tempfile import logging logger = logging.getLogger(__name__) class AutoLoader(object): """Base class for automatic loaders (e.g. Git)""" pass class Git(AutoLoader): def __init__(self, url, import_as=None, branch=None): "Creates a temporary di...