content
stringlengths
0
894k
type
stringclasses
2 values
#coding:utf-8 # # id: bugs.core_1056 # title: A query could produce different results, depending on the presence of an index # decription: # tracker_id: CORE-1056 # min_versions: [] # versions: 2.0 # qmid: bugs.core_1056 import pytest from firebird.qa import db_factory, isql_act, Acti...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-02-22 19:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mimicon2016', '0001_initial'), ] operations = [ migrations.AlterField( model_name='signupextra', ...
python
from django.contrib import admin from models import * # Register your models here. class CategoryAdmin(admin.ModelAdmin): list_display = ['id', 'title'] class GoodsInfoAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'price', 'unit', 'click', 'inventory', 'detail', 'desc', 'image'] admin.site.regis...
python
from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from app import db, login_manager @login_manager.user_loader def load_user(id): return User.query.get(int(id)) dictionary_table = db.Table('dictionary', db.Column('user_id', d...
python
from typing import List, Tuple import torch from torch.utils.data import Dataset from .feature import InputFeature class FeaturesDataset(Dataset): def __init__(self, features: List[InputFeature]): self.features = features def __len__(self,): return len(self.features) def __getitem__(s...
python
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 req...
python
#!/usr/bin/env python3 """Emulate a client by calling directly EC2 instance.""" import os import sys import json import logging # AWS Lambda does not ship requests out of the box # import requests import urllib3 # Global configuration logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.IN...
python
# -*- coding: utf-8 -*- """ Implement S3 Backed Binary and Unicode Attribute. Since the content of big Binary or Unicode are not stored in DynamoDB, we cannot use custom attriubte ``pynamodb.attributes.Attribute`` to implement it. """ import os import zlib from base64 import b64encode, b64decode from pynamodb.model...
python
# Copyright 2016 Isotoma Limited # # 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...
python
from __future__ import print_function, division import sys sys._running_pytest = True import pytest from sympy.core.cache import clear_cache def pytest_report_header(config): from sympy.utilities.misc import ARCH s = "architecture: %s\n" % ARCH from sympy.core.cache import USE_CACHE s += "cache: ...
python
# -*- coding: utf-8 -*- from .munsell import * # noqa from . import munsell __all__ = [] __all__ += munsell.__all__
python
import argparse import importlib from verify import mnist, cifar, imagenet import time def verify(args): try: net_class_module = importlib.import_module(args.netclassfile) net_class = getattr(net_class_module, args.netclassname) except Exception as err: print('Error: Import ...
python
""" Produces template's named argument to article categories mapping """ from __future__ import print_function import logging import json import re from collections import defaultdict from mwclient.client import Site import requests logging.basicConfig(level=logging.INFO) def get_articles_from_top_categories(site...
python
""" BaMi_optimal.py - compares BaMiC with BaMiF and includes the (according to us) optimal integration strategies. """ import sys import matplotlib.pyplot as plt from pywmi.engines.xsdd.literals import LiteralInfo from _pywmi.vtree.bottomup_elimination import bottomup_balanced_minfill as bamif from _pywmi.vtree.topdow...
python
# Lint as: python3 # Copyright 2018 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 ...
python
#!/usr/bin/env python3 # Copyright 2021 Cloudera, 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...
python
# by amounra 0216 : http://www.aumhaa.com # written against Live 9.6 release on 021516 from __future__ import absolute_import, print_function import Live import math from ableton.v2.base import inject, listens from ableton.v2.control_surface import ControlSurface, ControlElement, Layer, Skin, PrioritizedResource, Co...
python
# <Copyright 2019, Argo AI, LLC. Released under the MIT license.> """Collection of utility functions for Matplotlib.""" from typing import Any, Dict, List, Optional, Tuple, Union import matplotlib.pyplot as plt import numpy as np from descartes.patch import PolygonPatch from matplotlib.animation import FuncAnimation ...
python
from fastapi.testclient import TestClient from app.main import app client = TestClient(app) def test_valid_input(): """Return 200 Success when input is valid.""" response = client.post( '/predict', json={ 'title': 'Water bike', 'blurb': 'A bike that floats', ...
python
encode,decode=lambda s:''.join(c//200*"🫂"+c%200//50*"💖"+c%50//10*"✨"+c%10//5*"🥺"+c%5*","+(c==0)*"❤️"+"👉👈"for c in s.encode()),lambda s:bytes([200*(c:=b.count)("🫂")+50*c("💖")+10*c("✨")+5*c("🥺")+c(",")for b in s.split("👉👈")[:-1]]).decode()
python
# -*- coding: utf-8 -*- """Sweep config interface.""" from .cfg import SweepConfig, schema_violations_from_proposed_config from .schema import fill_validate_schema, fill_parameter, fill_validate_early_terminate __all__ = [ "SweepConfig", "schema_violations_from_proposed_config", "fill_validate_schema", ...
python
from typing import Callable from fastapi import FastAPI from app.db.init_db import init_db, create_engine def create_startup_handler(app: FastAPI, db_url: str) -> Callable: async def startup() -> None: engine = create_engine(db_url) await init_db(engine) app.state.alchemy_engine = engine...
python
__author__ = 'socialmoneydev' from jsonBase import JsonBase from programlimit import ProgramLimit from programinterestrate import ProgramInterestRate class ProgramChecking(JsonBase): def isHashedPayload(self): return True def __init__(self): self.category = None self.type = None ...
python
#!/usr/local/bin/python3.5 -u answer = 1 + 7 * 7 - 8 print(answer)
python
__version__ = '0.1.5' name = "drf_scaffold"
python
def count_prime_fuctors(n, c): # count the number of primes in particular number # argument `c` should be Counter class if n<2: return m=n i=2 while i<=m: while m%i==0: m//=i c[i]+=1 i+=1 from collections import Counter n=int(input()) d=Counter() ...
python
#from time import sleep class SessionHelper(): def __init__(self, app): self.app = app def login(self, user_email, password): driver = self.app.driver self.app.open_page() #driver.find_element_by_id("email").click() driver.find_element_by_id("email").send_keys(user_ema...
python
#!/bin/env python # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
python
# vim: set tabstop=4 shiftwidth=4 expandtab ############################################################################## # Written by: Brian G. Merrell <bgmerrell@novell.com> # Date: 12/03/2008 # Description: helpprovider.py wrapper script # Used by the helpprovider-*.py tests ###################...
python
import warnings import numpy as np from scipy._lib.six import callable, string_types from scipy._lib.six import xrange from scipy.spatial import _distance_wrap from scipy.linalg import norm import MyTimer _SIMPLE_CDIST = {} def _copy_array_if_base_present(a): """ Copies the array if its base points to a par...
python
class Color(object): RESET = '\x1b[0m' BLACK = 0 RED = 1 GREEN = 2 YELLOW = 3 BLUE = 4 MAGENTA = 5 CYAN = 6 WHITE = 7 NORMAL = 0 BOLD = 1 @staticmethod def to_color_string(string, foreground = 7, ...
python
import os import unittest import pytest from github import GithubException from ogr import GithubService from ogr.abstract import PRStatus, IssueStatus from ogr.persistent_storage import PersistentObjectStorage from ogr.exceptions import GithubAPIException DATA_DIR = "test_data" PERSISTENT_DATA_PREFIX = os.path.join...
python
# django from django import forms # local django from exam.models import CustomExam from exam.validators import CustomExamValidator class CreateCustomExams(forms.ModelForm): """ Form to create a custom exam. """ description = forms.CharField(widget=forms.Textarea) class Meta: # Define m...
python
# Generated by Django 2.2 on 2020-08-09 06:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coupons', '0003_coupon_max_discount'), ] operations = [ migrations.AlterField( model_name='coupon', name='max_discount...
python
import threading from Queue import Empty, Full from multiprocessing import Process, Queue, Value import datetime import os import zmq import logging from logging import handlers from platformData import * from BEMOSSThread import BThread, BProcess from commandProcessor import processCommand import cgitb cgitb.enable...
python
from tabulate import tabulate table = [['one','two','three'],['four','five','six'],['seven','eight','nine']] print(tabulate(table, tablefmt='html')) """Generate Report Function""" with open('example.log') as f: lines = f.readlines() print lines print(lines[2]) HTML_file= open("Report.html","w+") HTML_...
python
''' Environment simulators. ''' from models.simulator import POMDPSimulator from models.simulator_momdp import MOMDPSimulator from models.tiger import TigerPOMDP from models.rock_sample import RockSamplePOMDP from models.tools.belief import DiscreteBelief
python
""" Uma matriz de confusão. Não confundir com uma tabela de confusão. A matrix de confusão possui mais do que uma duas linhas e duas colunas, por isso difere da tabela de confusão, que possui duas linhas e duas colunas Para criar a matriz de confusão escolhi o formato de dictionary da seguinte maneira...
python
## process_rootroopnft.py # first let's just check how many tweets it grabbed. with open("rootroopnft.txt", "r") as fid: line = fid.read() # end with open line = line.split("Tweet(url=") print("line[0]: ", line[0]) print("line[-1]: ", line[-1]) last_date = line[-1].split("date=datetime.datetime(")[1].split(", tzin...
python
import cv2 import numpy as np class ColorTrack(): def __init__(self): pass def detect_green(self,frame): return self.detect_color(frame,np.array([33,80,40]),np.array([102, 255, 255])) def detect_red(self,frame): return self.detect_color(frame,np.array([78, 43, 46]), np.array([99,...
python
from __future__ import print_function, absolute_import import sys import subprocess from distutils.errors import DistutilsPlatformError import semantic_version class Binding: """ Binding Options """ # https://github.com/PyO3/PyO3 PyO3 = 0 # https://github.com/dgrunwald/rust-cpython RustCP...
python
# imports from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from bs4 import BeautifulSoup import time import re import csv # easy function for viewing list def printlist(list): length=len(list) for i in range(length): ...
python
"""The SquonkServer class handles get, post and delete requests against the squonk base_url using the SquonkAuth class to refresh the authentication token when required. """ import requests import json import logging from email.policy import default from collections import namedtuple try: from .Squo...
python
# -*- coding: utf-8 -*- import logging from mathutils import Vector class BlockDef(object): class _BlockItem(object): def __init__(self, name="", color=(0, 0, 0), block_def=(35, None)): self._name = name self._color = color self._block_def = block_def @property...
python
from flask_wtf import FlaskForm from wtforms import StringField, DateField, SubmitField from wtforms.validators import DataRequired class QuestionsForm(FlaskForm): class Meta: csrf = False # Example of defining a field. A in depth description can be found. # field_name = FieldType(label, descriptio...
python
import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from scipy.special import factorial2 class Hermite: def __init__(self, num_pol = 5): self.h = [] def h0(x): return torch.ones_like(x) self.h.append(h0) def h1(x): return x sel...
python
import numpy as np import math import cv2 class PSNR(): def __init__(self, range=1): self.range = range def __call__(self, img1, img2): mse = np.mean((img1 - img2) ** 2) return 20 * math.log10(self.range / math.sqrt(mse)) class SSIM(): def __init__(self, range=1): self.r...
python
from excursion.sampler import * from excursion.models import ExcursionModel, SKLearnGP from excursion.acquisition import * from excursion.excursion import ExcursionProblem, ExcursionResult # # move this into the excursion result, unless we add scikit learn implementation # # def build_result(details: ExcursionProble...
python
def settings (): # Input manually all extensions and copy settings extensions = [] key = "Y" while (key != "N"): extension = str(input("Enter a extension to search and organize: ")).strip().replace(".", "").lower() extensions.append(extension) key = str(input("Continue? Y/N: ")...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'resources/treeDialog.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TreeDialog(object): def setupUi(self, TreeDialog): ...
python
# Crie um programa que leia algo e mostre seu tipo pimitivo e todas as informações possíveis sobre ele. print('=-'*7, 'DESAFIO 4', '=-'*7) n = input('Digite algo: ') print('O tipo primitivo desse valor é {}.'.format(type(n))) # Ponto de melhoria! print('Só tem espaços? {}'.format(n.isspace())) print('É um número? {}'....
python
import sys import math import json class Point: def __init__(self, x, y, z, index): self.x = x self.y = y self.z = z self.index = index def getDist(a, b): return math.sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y) + (a.z - b.z)*(a.z - b.z)) for arg in sys.argv: fi...
python
from scipy import interp import numpy as np from itertools import cycle from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from itertools import cycle import matplotlib.pyplot as plt def plot_roc_pr( y_pred : np.ndar...
python
class withdelta(object): """ Wraps any object into the `value` property, and adds a `delta` floating point property that can be used to store extra information, such as percentage of improvement over a over a different values. All the attributes are forwarded to `value`, except for `value` and `del...
python
class Dummy(object): def purge(self, path): pass
python
""" cluster_graph.py ClusterGraph are a class for tracking all possible smirks decorators in a group (or cluster) of molecular fragments. Moving forward these will be used to find the minimum number of smirks decorators that are required to have a set of smirks patterns that maintain a given clustering of fragments. "...
python
from abc import ABC from typing import Any class IWord(ABC): command: Any class Word(IWord): def __init__(self, command=None): self.command = command self.address = 0 def dump(self): return self.command.dump() @property def original(self): return self.command.original def ...
python
#!/usr/bin/env python3 import argparse import os def main(dir): with open(os.path.join(dir, 'text'), 'w', encoding='utf-8') as out_f: for line in open(os.path.join(dir, 'text.ort2'), encoding='utf-8'): key, sent = line.strip().split(None, 1) if len(sent) > 0 and sent[0] == "*": ...
python
import json import unittest import urllib.request from multiprocessing.dummy import Pool from tests.gunicorn_utils import run_gunicorn def run_code_in_snekbox(code: str) -> tuple[str, int]: body = {"input": code} json_data = json.dumps(body).encode("utf-8") req = urllib.request.Request("http://localhost...
python
import numpy as np import tensorflow as tf import random as rn from keras.layers import multiply,concatenate,Embedding from keras.layers.merge import dot from keras import backend as K from keras.models import Sequential # The below is necessary in Python 3.2.3 onwards to # have reproducible behavior for certain hash...
python
from __future__ import print_function import os import sys from burlap import ServiceSatchel from burlap.constants import * from burlap.decorators import task class ApacheSatchel(ServiceSatchel): name = 'apache' post_deploy_command = 'reload' templates = [ '{site_template}', ] @proper...
python
import requests import nels_master_api def get_nels_ids(): try: ids = [] response = requests.get(nels_master_api.get_full_url("users/ids" ),auth=(nels_master_api.CLIENT_KEY, nels_master_api.CLIENT_SECRET)) if(response.status_code == requests.codes.ok): json_response = response....
python
import pandas as pd import math data = pd.read_csv('data/DATALOG2.CSV', delimiter=",", names=['date', 'time', 'lat', 'lon', 'vgps', 'velocity', 'course', 'heading', 'pitch', 'roll']) # data['vhead'] = data['velocity']*math.cos(math.pi/180*(data['course']-data['heading'])) data['drift'] = data.apply(...
python
import logging import multiprocessing import multiprocessing_logging import os log_level_from_env = os.environ.get('LOGLEVEL', '').upper() log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s %(message)s' log_level = logging.DEBUG if log_level_from_env == 'DEBUG' else logging.INFO logging.basi...
python
## Data and Visual Analytics - Homework 4 ## Georgia Institute of Technology ## Applying ML algorithms to detect seizure import numpy as np import pandas as pd import time from sklearn.model_selection import cross_val_score, GridSearchCV, cross_validate, train_test_split from sklearn.metrics import accuracy_score, cl...
python
#!/usr/bin/env python from __future__ import absolute_import import os import shutil import time import datetime from flask.ext.script import Manager from modelconvert import create_app from modelconvert.utils import fs app = create_app() manager = Manager(app) @manager.command def run(): app.run(threaded=Tr...
python
"""Configuration classes for ``varfish-cli case *`` commands.""" import attr import uuid import typing from ..common import CommonConfig @attr.s(frozen=True, auto_attribs=True) class CaseConfig: """Configuration for the ``varfish-cli case`` command.""" #: Global configuration. global_config: CommonCon...
python
import subprocess import sys import os import time import cProfile def prepare_io(list_of_files, exe_file, input_path, output_path, job_number): # read file names with open(list_of_files, "r") as files_to_read: list_files = files_to_read.read().split("\n") job_number = int(job_number) - 1 inpu...
python
import numpy as np # Collection of activation functions # Reference: https://en.wikipedia.org/wiki/Activation_function class Sigmoid(): def __call__(self, x): return 1 / (1 + np.exp(-x)) def gradient(self, x): return self.__call__(x) * (1 - self.__call__(x)) class Softmax(): def __call__...
python
#!/usr/bin/env python3.7 import sys from blist import blist from collections import defaultdict # Solution to the day 9 puzzle from Advent of Code 2018. # https://adventofcode.com/2018/day/9 def parse_data(filename): """ Load the data from FILENAME. """ data = list() with open(filename) as f: el...
python
import time import hashlib import requests import urllib3 from lxml import etree urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def xdl_proxy(orderno, secret, host, port): host_port = host + ":" + port # get sign timestamp = str(int(time.time())) string = "" str...
python
# -*- coding: utf8 -*- """ ====================================== Project Name: NLP File Name: utils Author: czh Create Date: 2021/8/6 -------------------------------------- Change Activity: ====================================== """ import torch import torch.nn as nn import torch.nn.functional as ...
python
''' Author: Mario Liu Description: Module to detect faces with R200 camera. Adapted from https://docs.opencv.org/3.4.3/d7/d8b/tutorial_py_face_detection.html ''' import logging logging.basicConfig(level=logging.INFO) import time import numpy as np import cv2 import pyrealsense as pyrs face_cascade = cv2.CascadeClass...
python
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('sud2.jpeg',0) img = cv2.medianBlur(img,5) ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY,11,2) th3 = cv2.adaptiveThreshold(img,255...
python
# # Imported module functions # #https://camo.githubusercontent.com/582226b9ba41bcbc13eaa81d2764092abb443bd416578c175bc2c1c5742d0647/68747470733a2f2f692e696d6775722e636f6d2f6b7a6978316a492e706e67 # Use our SimpleRequests module for this experimental version. from SimpleRequests import SimpleRequest from SimpleRequests....
python
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
python
import json from itertools import groupby from operator import itemgetter import django from django import forms from django.conf import settings from django.contrib.admin.views.decorators import staff_member_required from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectD...
python
# Sum Compare # Get 3 numbers from the user. Find the # biggest number and add them all together. # If the sum is bigger than 2 times the # biggest of the 3 numbers, then print the sum. # If it's smaller, multiply the sum by 3 and print the product. # write code here
python
import tensorflow as tf import math class BatchNormalization(tf.keras.layers.BatchNormalization): """Make trainable=False freeze BN for real (the og version is sad). ref: https://github.com/zzh8829/yolov3-tf2 """ def call(self, x, training=False): if training is None: training =...
python
""" Some simple code to make particle flux spectrograms with matplotlib @author: Liam M. Kilcommons (minor modifications R. Redmon, A.G. Burrell) """ import numpy as np import matplotlib.pyplot as pp import datetime as dt def dmsp_spectrogram(times, flux, channel_energies=None, lat=None, lt=None, ...
python
from django.apps import apps from django.forms.models import ModelChoiceField, ModelMultipleChoiceField from django.forms import ChoiceField from smart_selects.widgets import ChainedSelect, ChainedSelectMultiple try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding imp...
python
class Person(object): def demo(self): print('888')
python
import datetime import json import argparse from typing import Any, Dict import pytz from astral import LocationInfo, Observer, sun options = argparse.ArgumentParser() options.add_argument( "-n", "--name", dest="name", default="Somewhere", help="Location name (free-form text)", ) options.add_argu...
python
n, m = map(int, input().split()) if n == 1: if m == 0: print(1, 2) else: print(-1) exit() if m < 0 or m + 2 > n: print(-1) else: print(1, 2 * (m + 2)) for i in range(1, m + 2): print(2 * i, 2 * i + 1) for j in range(m + 2, n): print(2 * j + 1, 2 * j + 2)
python
from sklearn import preprocessing from tqdm import tqdm import time import pandas as pd import numpy as np import torch import torch.nn as nn from sklearn.metrics import accuracy_score, recall_score from sklearn.metrics import precision_score, f1_score from sklearn.metrics import classification_report from core.utils...
python
#Actualizado Lunes,28 de mayo dos mil diez y ocho #Autor: Rosnel Alejandro Leyva-Cortes# import os import re import sys import struct import socket import urllib import time from subprocess import Popen, PIPE import json as m_json try: from urllib.parse import urlparse except ImportError: from urlparse import u...
python
import pymysql from sshtunnel import SSHTunnelForwarder class Database: def initialize(self, server_name): self.server = SSHTunnelForwarder( '51.75.163.1', ssh_username='karthik', ssh_password='btm56Vy.3', remote_bind_address=('127.0.0.1', 3306) ...
python
class Station: def __init__(self, station_id, direction, stop_name, station_name, accessible, red, blue, green, brown, purple, purple_exp, yellow, pink, orange, latitude, longitude): self.station_id = station_id self.direction = direction self.stop_name = stop_name self.station_name ...
python
meses = {'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12} #entrada mes = int(input()) #processamento & saída for k, v in meses.items(): if v == mes: print(k) break
python
from gruffy import AccumulatorBar g = AccumulatorBar() g.title = "Gruffy's Graph" g.data("add", [10, 50, 150, 20]) g.hide_legend = True g.labels = {0: '2003', 1: '2004', 2: '2005', 3: '2006'} g.transparent = 0.7 g.y_axis_increment = 50 g.maximum_value = 300 g.write('gruffy-accumulatorbar.png')
python
from sym_lis3 import GlobalEnv import pytest def test_dyn(): g = GlobalEnv() g.eval_str('(define "foo" (lambda (x y) (if (in? dyn_env x) y 0)))') assert not g.eval_str('(in? root_env "x")') assert g.eval_str('(foo "x" 1)') == 1 assert g.eval_str('(foo "+" 1)') == 0 assert g.eval_str('(foo ...
python
class BaseEngine: def __init__(self, world): self.world = world self._cull_method = self.default_cull_method def check_collision(self, entity, collider): raise NotImplementedError('Nope.') def resolve_collision(self, entity, collider): raise NotImplementedError('No...
python
from ..typecheck import * from . layout import Layout from . image import Image from . css import css, div_inline_css, icon_css, none_css class element: def __init__(self, is_inline: bool, width: Optional[float], height: Optional[float], css: Optional[css]) -> None: super().__init__() self.layout = None #type: O...
python
from django.core.mail import send_mail, EmailMessage from django.forms import modelformset_factory from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from .models import Question, Choice, FilePathFieldForm ...
python
from ...utils.IndexedRect import IndexedRect class IndexedRectBuilder(object): def __init__(self): self.last_rect = None self.initial_point = None self.reset() def set_initial_point(self, x, y): self.initial_point = (x,y) def get_initial_point(self): return self.i...
python
# -*- coding: utf-8 -*- import binarybrain as bb import binarybrain.core as core import numpy as np from typing import List class Optimizer(bb.Object): """Optimizer の基本クラス """ def __init__(self, core_optimizer=None): super(Optimizer, self).__init__(core_object=core_optimizer) ...
python
#coding:utf8 # Author : tuxpy # Email : q8886888@qq.com # Last modified : 2015-03-26 13:14:11 # Filename : gale/utils.py # Description : from __future__ import unicode_literals try: # py2 from urlparse import urlsplit from urllib import unquote_plus from urllib import quote...
python
import cv2 import numpy as np from matplotlib import pyplot as plt # calculer difference entre les deux flow optique adjacents def diffimage(lastframe, nextframe, size): diff_frame = nextframe - lastframe ABS = abs(diff_frame) diff_value = (ABS.sum(axis = 0)).sum(axis = 0)/size return diff_frame, dif...
python
import pytest from mcanitexgen.animation.parser import Duration, ParserError, Time, Timeframe, Weight class Test_Timeframe_init: @pytest.mark.parametrize( "start, end, duration, expected_timeframe", [ # Deduce end and duration (0, None, None, Timeframe(0, 1, 1)), ...
python
#!/usr/bin/env python3 from yaml import load class ComposePlantuml: def __init__(self): pass def parse(self, data): return load(data) def link_graph(self, compose, notes=False): result = 'skinparam componentStyle uml2\n' for component in sorted(self.components(compose))...
python