code
stringlengths
1
199k
from __future__ import unicode_literals import re from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _, ungettext_lazy from django.utils.encoding import force_text from django.utils.ipv6 import is_valid_ipv6_address from django.utils import six from django.utils.six...
from __future__ import unicode_literals import logging from django.conf import settings from django.http import HttpRequest, HttpResponse from django.middleware.csrf import ( CSRF_KEY_LENGTH, CsrfViewMiddleware, get_token, ) from django.template import RequestContext, Template from django.template.context_processor...
import unittest from test import support import re rx = re.compile('\((\S+).py, line (\d+)') def get_error_location(msg): mo = rx.search(str(msg)) return mo.group(1, 2) class FutureTest(unittest.TestCase): def test_future1(self): with support.CleanImport('future_test1'): from test import...
import logging import re from webkitpy.common.host import Host from webkitpy.common.webkit_finder import WebKitFinder from webkitpy.thirdparty.BeautifulSoup import BeautifulSoup, Tag _log = logging.getLogger(__name__) class W3CTestConverter(object): def __init__(self): self._host = Host() self._file...
''' $Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $ ''' try: from cStringIO import StringIO except ImportError: from io import StringIO from datetime import datetime, timedelta from struct import unpack, calcsize from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo from pytz.tzinfo import mem...
"""Admin urls.""" from __future__ import unicode_literals from django.conf.urls import url from . import views from .views import ( alias as alias_views, domain as domain_views, export as export_views, identity as identity_views, import_ as import_views ) urlpatterns = [ url(r'^$', domain_views.index, name=...
"""This module manages where downloaded data is stored via a config file. It also has a PathManager to support finding the paths to files of interest.""" import configparser import logging from collections import OrderedDict from pathlib import Path import pandas as pd logger = logging.getLogger(__name__) try: from...
''' BeeSQL core. ''' import beesql def connection(engine='mysql', username=None, password=None, host='localhost', port=3306, db=None, unix_socket=None): ''' Create and return a connection to a Database using specified engine. Arguments: :engine: Database to use; Default to mysql. :username: User...
from django.utils.translation import ugettext_lazy as _ from django.forms.fields import CharField from django.core.exceptions import ValidationError from phonenumber_field.validators import validate_international_phonenumber from phonenumber_field.phonenumber import to_python class PhoneNumberField(CharField): defa...
""" A set of compatibility methods """ import sys from six.moves import configparser def create_configparser(): if sys.version_info > (3, 0): return configparser.RawConfigParser(strict=True) else: return configparser.RawConfigParser() if sys.version_info > (3, 0): def _unicode(s): re...
from __future__ import division from itertools import product, count from random import random, shuffle, randrange, choice from .cross import cross, memoize from math import hypot, sqrt from .mocodo_error import MocodoError def arrange(col_count, row_count, successors, multiplicity, organic, min_objective, max_objectiv...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('imager_images', '0010_auto_20160417_0016'), ] operations = [ migrations.RemoveField( model_name='photo', ...
"""Module tests.""" from click.testing import CliRunner from invenio_accounts.cli import roles_add, roles_create, roles_remove, \ users_activate, users_create, users_deactivate def test_cli_createuser(script_info): """Test create user CLI.""" runner = CliRunner() # Missing params result = runner.inv...
import RPi.GPIO as gpio import time import sys import Tkinter as tk from sensor import distance import random def init(): gpio.setmode(gpio.BOARD) gpio.setup(7, gpio.OUT) gpio.setup(11, gpio.OUT) gpio.setup(13, gpio.OUT) gpio.setup(15, gpio.OUT) def forward(tf): gpio.output(7, False) gpio.ou...
import random class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def createTree(self, h, n): if h > n: return None x1 = random.randint(0, 1000) x2 = random.randint(0, 1000) self.left = TreeNode(x1).cr...
import wx import wx.grid as Grid import images class MegaTable(Grid.GridTableBase): """ A custom wx.Grid Table using user supplied data """ def __init__(self, data, colnames, plugins): """data is a list of the form [(rowname, dictionary), dictionary.get(colname, None) returns the...
import sys from giturlparse import parse print parse(sys.argv[1]).host
try: from urllib2 import Request from urllib2 import urlopen as urlopen2 except ImportError: from urllib.request import Request from urllib.request import urlopen as urlopen2 try: from urllib import urlencode, urlopen except ImportError: from urllib.parse import urlencode from urllib.request...
from django import forms from mptt.forms import TreeNodeMultipleChoiceField from feincms.module.page.models import Page class ModifyFeincmsNavigation(forms.ModelForm): class Meta: model = Page fields = ('feincms_navigation', ) def __init__(self, *args, **kwargs): super(ModifyFeincmsNavig...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import sys import os user = sys.argv[1] passw = sys.argv[2] uid = sys.argv[3] browser = webdriver.Firefox() browser.get("https://wwwsec.serverweb.unb.br/matriculaweb/graduacao/sec/login.aspx") username = browser.find_element_by_n...
def cos(a, b): import math try: return sum([sa*sb if pa == pb else 0 for (pa,sa) in a for (pb,sb) in b])/math.sqrt(sum([sa**2 for (pa,sa) in a])*sum([sb**2 for (pb,sb) in b])) except: return 0
import mock import os import shutil import subprocess import tempfile import unittest from contextlib import contextmanager from datetime import datetime, timedelta from pkg_resources import parse_version from requests.exceptions import RequestException import reqcheck.exceptions as exceptions import reqcheck.packages ...
import urwid import sys from clingo import SymbolType, Number, Function, clingo_main class Board: def __init__(self, plan): self.display = urwid.Text("", align='center') self.plan = plan self.current = plan.first() self.update() def next(self, button): self.current = s...
import time import math import pygame import random def erase(): screen.fill(black) pygame.display.flip() def pixel_draw(position,colour): screen.set_at(position,colour) pygame.display.flip() def pixel_change(position,colour): screen.set_at(position,colour) def cell_draw(position,colour): for y in range(zoom): ...
from . import ions from . import gases from . import liquids
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('coding', '0002_schemes_code_groups'), ] operations = [ migrations.AlterField( model_name='code', name='description', ...
import os import unittest from utils.read_data_file import read_int_array from searching.binary_search import search from sorting.quick_sort import sort BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class BinarySearchTester(unittest.TestCase): def setUp(self): self.collection = read_int_array(os.pat...
import cv import math import numpy from operator import itemgetter import pygame.image import threading import time class CameraThread(threading.Thread): def __init__(self, resolution, scale): threading.Thread.__init__(self) self.resolution = resolution self.circles = list() self.sca...
import zmq import os class Application(object): def __init__(self, zmq_context, gstats_addr, allowed_ips=['127.0.0.1']): self.ctx = zmq_context self.gstats_addr = gstats_addr self.allowed_ips = allowed_ips def dispatch(self, env): """ very simple URL dispatch, a la Cake: /zelink ...
class Login: def __init__(self,senhaDoCartao): self.recebeSenha = senhaDoCartao self.chances = 3 def verificaSenha(self,recebeSenha,senhaDigitada): if(self.chances>0): if(recebeSenha == senhaDigitada): return True else: return Fals...
import cbpos from cbpos.modules import BaseModuleMetadata class ModuleMetadata(BaseModuleMetadata): base_name = 'base' version = '0.1.0' display_name = 'Base Module' dependencies = tuple() config_defaults = ( ('menu', { 'show_tab_bar': False, 'toolbar_styl...
""" ============================================= Feature Union with Heterogeneous Data Sources ============================================= Datasets can often contain components of that require different feature extraction and processing pipelines. This scenario might occur when: 1. Your dataset consists of heteroge...
import os from datetime import timedelta,datetime try: from PIL import Image, ImageOps except ImportError: Image = None ImageOps = None from django.conf import settings from moto.moe.files import ResumableFile from django.core.files.temp import NamedTemporaryFile IMAGE_SIZE = getattr(settings, 'IMAGE_SIZE'...
from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django.utils.six.moves import input from django.core.management import call_command class Command(BaseCommand): def handle(self, *args, **options): User = get_user_model() if not User.objects.filt...
import pytest import responses from flask import url_for from faker import Faker from feedrsub.websub.views import SECRET_TOO_BIG from feedrsub.models.websub_subscription import WebSubSubscription from feedrsub.models.userfeed import UserFeed from tests.websub.websub_handler_test import verify_intent_request_callback f...
import os import sys import subprocess read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: subprocess.call('../run_doxygen.sh') extensions = ['sphinx.ext.mathjax', 'breathe'] breathe_projects = { "rocFFT": "../docBin/xml" } breathe_default_project = "rocFFT" templates_path = ...
import json import datetime import urllib.parse import urllib.request import os import threading repo_name = 'uni-esperimenti-noweb' repo_owner = 'gabibbo97' github_api_url = 'https://api.github.com' secret = os.getenv('GITSECRET', 'nosecret') if secret=='nosecret': secret = input('Insert GitHub secret token: ') ...
import BaseHTTPServer import os import sys import json import re import logging from subprocess import Popen, PIPE from netaddr import IPAddress, IPNetwork PREFIX_REGEX_PATTERN = '^(ft\w+)-.+' prefixToNetwork = {} noPrefixNetwork = None prefixRegex = re.compile(PREFIX_REGEX_PATTERN, re.IGNORECASE) logger = None class U...
from msrest.serialization import Model class Sku(Model): """Billing information related properties of a server. :param name: The name of the sku, typically, tier + family + cores, e.g. B_Gen4_1, GP_Gen5_8. :type name: str :param tier: The tier of the particular SKU, e.g. Basic. Possible values ...
import random from colorama import Back from plugin import plugin @plugin('rockpaperscissors') class rockpaperscissors(): """ rockpaperscissors Dcoumentation. rockpaperscssors is the game Rock - Paper - Scissors that we all know with Jarvis as opponent. First of all you enter how many rounds you will pl...
""" ========================================== IsolationForest example ========================================== An example using IsolationForest for anomaly detection. The IsolationForest 'isolates' observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum ...
from django.contrib import admin from blog.models import Post class PostAdmin(admin.ModelAdmin): list_filter = ('contest', 'author') list_display = ('author', 'contest', 'creation_date', 'title') admin.site.register(Post, PostAdmin)
from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Me...
__revision__ = "test/Java/jar_not_in_PATH.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Ensures that the Tool gets initialized, even when jar is not directly found via the PATH variable (issue #2730). """ import os import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.write...
""" Programmed by: Jared Hall Discription: This is the database models file for the server database. All of the SQL-Alchemy classes are in here. """ from flask_sqlalchemy import SQLAlchemy from sqlalchemy.ext.orderinglist import ordering_list database = SQLAlchemy() class Users(database.Model): username = database.Col...
__all__ = ['mango', 'utils'] from .mango import * from . import utils
from os import mkdir, walk, remove from os.path import exists, join as joinpath from pickle import PicklingError, UnpicklingError from collections import namedtuple from redlib.api.py23 import pickledump, pickleload from . import const AutocompInfo = namedtuple('AutocompInfo', ['command', 'access', 'version']) class Da...
from . import Constant from datetime import date import os.path import time class Clock: def __init__(self): self.cached_today = date.today() self.cached_time = int(time.time() * Constant.Clock.MILLIS_IN_SECOND) def get_timestamped_directory_name(self, dirname): return "{}-{}".format(dirname, self.cache...
import psutil import time from ISStreamer.Streamer import Streamer streamer = Streamer(bucket_name="Example Performance Metrics",bucket_key="compute_metrics", buffer_size=100, ini_file_location="./isstreamer.ini", debug_level=1) sample_rate_in_ms=100 for x in range(1000): streamer.log("sample", x) # Get total CPU usa...
import django from django.contrib import admin if django.VERSION >= (2, 0): from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('private/', include(('privateurl.urls', 'privateurl'), namespace='purl')), ] else: from django.conf.urls import include,...
import pymel.core as pm import logging import traceback import sys from getpass import getuser log = logging.getLogger("ui") class BaseTemplate(pm.ui.AETemplate): def addControl(self, control, label=None, **kwargs): pm.ui.AETemplate.addControl(self, control, label=label, **kwargs) def beginLayout(self, ...
"""UI interface to an activity in the presence service STABLE. """ import logging from functools import partial import dbus from dbus import PROPERTIES_IFACE import gobject from telepathy.client import Channel from telepathy.interfaces import (CHANNEL, CHANNEL_INTERFACE_GROUP, ...
import _plotly_utils.basevalidators class XValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="x", parent_name="barpolar.marker.colorbar", **kwargs ): super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name,...
from django.contrib import admin from django.conf import settings from betterself.users.models import UserPhoneNumberDetails from events.models import SupplementLog, DailyProductivityLog, SupplementReminder, UserMoodLog @admin.register(SupplementLog) class SupplementEventAdmin(admin.ModelAdmin): list_display = ('us...
import unittest from satellite import tree_from_traversals class SatelliteTest(unittest.TestCase): def test_empty_tree(self): preorder = [] inorder = [] expected = {} self.assertEqual(tree_from_traversals(preorder, inorder), expected) def test_tree_with_one_item(self): pr...
"""initialize.""" from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): """Migfrations.""" initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
import sys import pandas as pd import xml.etree.ElementTree as ET from math import radians, cos, sin, asin, sqrt from pykalman import KalmanFilter def output_gpx(points, output_filename): """ Output a GPX file with latitude and longitude from the points DataFrame. """ from xml.dom.minidom import getDOMI...
import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error fr...
""" Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion This module prints the amount of money that Lakshmi has remaining after the stock transactions """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" """ Inputs: none from user....
import _plotly_utils.basevalidators class TicklabelpositionValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="ticklabelposition", parent_name="scattergeo.marker.colorbar", **kwargs ): super(TicklabelpositionValidator, self).__ini...
"""\ Our Standards Jill-Jênn Vie et Christoph Dürr - 2020 """ from sys import stdin def readint(): """ function to read an integer from stdin """ return int(stdin.readline()) def readstr(): """ function to read a string from stdin """ return stdin.readline().strip() def readarray(typ): ...
from django.db import models class PublishModel(models.Model): published_date = models.DateTimeField() published = models.BooleanField(default=False) class Meta: abstract = True
from math import factorial def paths(n): a = factorial(n) a *= a b = factorial(2 * n) return int(b / a) ans = paths(20) print(ans)
from django.shortcuts import render def index(request): return render(request, 'personal/home.html') #must pass render, then the location of the HTML template you want to render. WITH JINJA CAN ALSO PASS A DICTIONARY TO THE HTML FILE FULL OF DATA def contact(request): return render(request, 'personal/basic.html', {'c...
from afanimation import Animation, Patterns
import time import copy import logging from twisted.internet import defer from .exceptions import NoValidTorrent from .torrent import ActiveTorrent from .tracker import TrackerClient from .constants import CLIENT_ID_VER from .btencode import BTEncodeError, BTDecodeError logging.basicConfig(level=logging.DEBUG) class To...
import os from seed_tests import BaseSeedTest class TestReleaseCommand(BaseSeedTest): def setUp(self): super(TestReleaseCommand, self).setUp() def test_dry_run_initial(self): self.create_package() self.write_meta_data() ok = self.run_with_coverage('release --initial --dry-run') ...
import boto.ec2 import argparse from amslib.core.manager import BaseManager from amslib.ssh.sshmanager import SSHManager import time class InstanceManager(BaseManager): def __get_boto_conn(self, region): if region not in self.boto_conns: self.boto_conns[region] = boto.ec2.connect_to_region(regio...
import sys from time import sleep print("请输入账号", end="", flush=True) sleep(5)
from CIM14.CPSM.Equipment.Core.BasicIntervalSchedule import BasicIntervalSchedule class RegularIntervalSchedule(BasicIntervalSchedule): """The schedule has TimePoints where the time between them is constant. """ def __init__(self, timeStep=0.0, endTime='', TimePoints=None, *args, **kw_args): """Init...
from distutils.core import setup setup( name='Tornado-py.test', version='1.0', description='Testing Tornado applications with py.test', author='Piotr Wasilewski', author_email='piotrek@piotrek.io', packages=['tornado_pytest'], scripts=['tornado_pytest/bin/tornado_pytest_app.py'] )
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import logging as log import random import time from euler import Euler from runge_kutta import RK4 from mystring import MyString class String_Simulation(): def __init__(self, parameters): """Assign some initial valu...
from urllib2 import urlopen, URLError import ujson as json import time from httplib import BadStatusLine import sys, os import time import gzip from argparse import ArgumentParser """ This is the info from the bogus app I used """ app_id = '653943651304297' app_secret = '1bc923adced1393d7565dca05a0ea24e' access_tok...
import requests from bs4 import BeautifulSoup import re import __future__ from generate_dicts import load from transform_healthy import t_low_sodium, t_low_fat import pprint import unicodedata import os GLUTEN_FREE = {'bread crumbs':'corn meal', 'bread':'gluten-free bread', 'pasta':'rice', 'noodles':'rice' , ...
""" Read a rvcf file with stability selection scores for taxa. Sort the dataframe by rsq_median. Save box and bar plots for the top N SNPs. Note: R must have packages dplyr and ggplot2 installed. I installed rpy2 with conda, which installs R in the virtual environment directory. In my case that is ~/miniconda3/envs/hve...
from pwn import * def new_note(size): r.sendline("1") r.recvuntil("size: ") r.sendline(str(size)) r.sendline("A" * (size - 2)) r.recvuntil("$ ") def del_note(num): # 2. Delete note r.sendline("2") r.sendline(str(num)) r.recvuntil("$ ") def print_note(num): # 3. Print note r.s...
"""Utility functions and pre-load examples. Author: Yuhuang Hu Email : yuhuang.hu@uzh.ch """ import os from os.path import join import cv2 from moviepy.video.io.ffmpeg_reader import FFMPEG_VideoReader from simretina import package_data_path def check_image_file(file_name): """Check if given file is a image file. ...
"""Auto-generated file, do not edit by hand. ZW metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_ZW = PhoneMetadata(id='ZW', country_code=263, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='2(?:[012457-9]\\d{3,8}|6(?:[14]\\d{7}|\\d...
import _plotly_utils.basevalidators class TickmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="tickmode", parent_name="carpet.aaxis", **kwargs): super(TickmodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
import tensorflow as tf slim = tf.contrib.slim def net_architecture(images, num_classes=10, is_training=False, dropout_keep_prob=0.5, spatial_squeeze=True, scope='Net'): """Creates a variant of the Net model. Args: images: The batch of `Tensor...
from django import template from django.conf import settings from django.template import Template from django.template.loader import render_to_string from django.template.defaultfilters import truncatewords_html from django.template.loader_tags import do_include from django.template import Library from django.utils.saf...
import os import cv2 import numpy as np from PIL import Image, ImageChops, ImageFilter import math from data import PERCENTAGE_TO_CROP_SCAN_IMG, CROPPED_IMG_NAME def crop_by_percentage(origin_im, percentage): width, height = origin_im.size left = int(percentage * width) upper = int(percentage * height) ...
""" An environment class. """ import os import re import sys from contextlib import contextmanager from .memoized import MemoizedObject from .error import TeapotError from .log import LOGGER, Highlight as hl from .signature import SignableObject class Environment(MemoizedObject, SignableObject): """ Represents ...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
from os import path root_path = path.abspath(path.dirname(__file__)) class Table(object): def __init__(self, name): self.name = name def _sql(self, operation): file_path = '{root_path}/tables/{directory}/{operation}.sql'.format( root_path=root_path, directory=self.name, ...
""" Unit tests for gaussian_markov_chain module. """ import numpy as np from ..gaussian_markov_chain import GaussianMarkovChain from ..gaussian_markov_chain import VaryingGaussianMarkovChain from ..gaussian import Gaussian, GaussianMoments from ..gaussian import GaussianARD from ..gaussian import GaussianGamma from ..w...
from setuptools import setup, find_packages from os import path import time if path.exists("VERSION.txt"): # this file can be written by CI tools (e.g. Travis) with open("VERSION.txt") as version_file: version = version_file.read().strip().strip("v") else: version = str(time.time()) setup( name=...
""" Role ==== Defines a basic interface for plugin managers which filter the available list of plugins before loading. One use fo this would be to prevent untrusted plugins from entering the system API === """ from yapsy.IPlugin import IPlugin from yapsy.PluginManagerDecorator import PluginManagerDecorator class Filte...
""" Unittests for the EGO module go here. """ from __future__ import division import unittest from math import sin from copy import deepcopy from scipy import optimize from numpy import * from gaussianprocess import GaussianProcess, PrefGaussianProcess from gaussianprocess.kernel import GaussianKernel_ard, GaussianKern...
import logging import random import time from base64 import b64encode from collections import defaultdict from twisted.internet import task import src.messages.messages_pb2 as pb from src.trustchain.trustchain import TrustChain, TxBlock, CpBlock, Signature, Cons, CompactBlock from src.utils import collate_cp_blocks, my...
import numpy as np import cv2 import math wool_rgb = [ (221,221,221), (219,125,62), (179,80,188), (107,138,201), (177,166,39), (65,174,56), (208,132,153), (64,64,64), (154,161,161), (46,110,137), (126,61,181), (46,56,141), (79,50,31), (53,70,27), (150,52,48), (25,22,22) ] wool_name = ["white", "orange", "magenta", "lig...
""" pycayley is a simple python client for Cayley Database. Homepage http://github.com/canerbasaran/pycayley Copyright (c) 2014, Caner Başaran. License: MIT (see LICENSE for details) """ __author__ = 'Caner Başaran' __version__ = '0.1-dev' __license__ = 'MIT' import requests def request(url, data): return requests....
import subprocess from gitviewfs_objects import CommitParentSymLink, CommitContextNames, Directory,\ DIR_STRUCTURE_CONTEXT_NAME from tests.utils import BaseTestWithRepository, MockDirStructure class CommitParentSymLinkWithRepositoryTest(BaseTestWithRepository): def test_get_target_object(self): self.create_and_comm...
""" @brief test log(time=2s) """ import unittest from pyquickhelper.pycode import ExtTestCase from ensae_teaching_cs.special.student import Student class TestStudent(ExtTestCase): def test_student(self): qna = {'q1': 0.6} st = repr(Student(qna)) self.assertEqual(st, "Student({'q1': 0.6}...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DateTime from itsdangerous import URLSafeTimedSerializer from enum import Enum import AppConfig Base = declarative_base() login_serializer = URLSafeTimedSerializer(AppConfig.APPSECRETKEY) class UserPrivileges(Enum): ...
""" A simplified taxon assignment script. """ import argparse import logging from count_taxa import cleanRanks, formatTaxon from edl import hits as edlhits, util from edl.taxon import TaxNode, ranks def main(): """ The CLI """ description = """ Takes a hit table (reads searched against a database) and assigns e...
import sys import json import socket import board import game_state name = "This is an albatrocity!" def out_handshake(): return {'me' : name} def in_handshake(msg): pass def in_setup(msg): b = board.Board.from_json(msg['map']) gs = game_state.GameState1.from_board(b, players = msg['punters'...
from itertools import takewhile, combinations def pentagonal_generator(): n = 1 while True: yield n*(3*n-1)/2 n = n + 1 seen = set() first_pentagonals = set(takewhile(lambda p: p < 100000000, pentagonal_generator())) for pj, pk in combinations(first_pentagonals, 2): if pk + pj in first_pentagonals and pk ...
import numpy as np import Gridworld THETA = 1e-3 # a small positive number as stopping criterion GAMMA = 0.9 # discount rate P_N = 0.9 # probability of ending up in the chosen action in the windy gridworld if __name__ == '__main__': # create a default gridworld # oo -- traversable state # xx -- untraversable state ...
"""This module contains Language Server Protocol types https://microsoft.github.io/language-server-protocol/specification -- Language Features - References -- Class attributes are named with camel-case notation because client is expecting that. """ from typing import Optional from pygls.lsp.types.basic_structures impor...