text stringlengths 8 6.05M |
|---|
import numpy as np
import pytest
import math
from sklearn.base import clone
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
import doubleml as dml
from ._utils import draw_smpls
from ._utils_irm_manual import fit_irm, boot_irm
@pytest.fixture(scope='module',
params=[[Ran... |
from django.db import models
from django.contrib.auth.models import User
class Tweet(models.Model):
user = models.ForeignKey(User, related_name='tweets', on_delete=models.CASCADE)
body = models.CharField(max_length=140)
timecreated = models.DateTimeField(auto_now_add=True)
|
import os.path
import sys
import glob
import os
from kapteyn import wcs
import pyfits
def get_img_WCS_map(fits_filename):
hdulist = pyfits.open(fits_filename)
header = hdulist[0].header
proj = wcs.Projection(header)
return proj.sub(nsub=2)
pass
def get_img_WCS_posn(fits_filename, pixel_tuple):
wc... |
f = open("yesterday","r",encoding="utf-8")
f2 = open("yesterday2","w",encoding="utf-8")
for line in f:
if "肆意的快乐等我享受" in line:
line = line.replace("肆意的快乐等我享受","肆意的快乐等---黄世杰----享受")
f2.write(line)
f.close()
f2.close() |
from django.shortcuts import render_to_response
from django.http import HttpResponse
from .models import User
# Create your views here.
def index(request):
user = User.objects.all()
return render_to_response('jan/personal.html', locals()) |
import cmath
a=int(input('a:'))
b=int(input('b:'))
c=int(input('c:'))
disc=cmath.sqrt(b**2 - 4*a*c)
sol1=(-b+disc)/(2*a)
sol2=(-b-disc)/(2*a)
print(round(sol1.real,3)+round(sol1.imag,3)*1j)
print(round(sol2.real,3)+round(sol2.imag,3)*1j) |
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from appointments.models import Appointment
import datetime
class HomePage(LoginRequiredMixin, ListView):
login_url = 'login'
redirect_field_name = 'redirect_to'
... |
"""
cis and trans eigenvector decomposition on Hi-C numpy arrays
refactored from mirnylib and hiclib
"""
def _filter_heatmap(A, transmask, perc_top, perc_bottom):
# Truncate trans blowouts
lim = np.percentile(A[transmask], perc_top)
tdata = A[transmask]
tdata[tdata > lim] = lim
A[transmask] = tda... |
import paramiko, time
from termcolor import colored
import requests
from functions import SSH
import scp
def statusWebsite():
url = "https://media.scheijvens.com"
status = requests.get(url)
if status.status_code == 200:
status_active = colored("Active", "green")
else:
status_active = c... |
# -*- coding:utf-8 -*-
__author__ = 'lish'
import urllib2,re,urllib,json,time,bs4
import MySQLdb,random,os,StringIO,gzip
from multiprocessing.dummy import Pool as ThreadPool
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
base_path=os.path.split( os.path.realpath( sys.argv[0] ) )[0]
# isExists=os.path.exists(ba... |
D = {
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five"
}
with open('./7.txt', 'w') as f:
for key in D:
f.write(str(key) + ", "+ D[key] + "\n")
f.close() |
#!usr/bin/env python3
#coding=utf8
source = [1,5,2,8,10,3,7,6,9,4]
class Solution:
def sortArray(self, arry:list)->list:
length = len(arry)
if length == 1 or length == 0:
return arry
mid = int(length/2)
midNum = arry[mid]
#print("mid:%d,midNu... |
'''
猩球崛起
'''
class Person:
def __init__(self, name, atk, left):
self.name = name
self.atk = atk
self.left = left
def attack(self, starstar):
starstar.left = starstar.left - self.atk
def __str__(self):
msg = '{}的攻击力是{},剩余生命力{}'.format(self.name, self... |
"""
Calculates the mean and variance over h5 audio trainings files.
"""
__author__ = 'David Flury'
__email__ = "david@flury.email"
import os
import glob
import json
import h5py
import time
import argparse
import numpy as np
import progressbar
def calculate_sum(file):
data = h5py.File(file,'r')
stereo = ... |
from typing import List, Optional, Tuple, Union
class User:
def __init__(self, name: str, discord_id: Optional[int], telegram_id: Optional[int], vk_id: Optional[int]):
self.name = name
self.discord_id = discord_id
self.telegram_id = telegram_id
self.vk_id = vk_id
class Image:
d... |
from django.contrib import admin
from .models import UserFavouriteProducts
# Register your models here.
class FavouriteProductsAdmin(admin.ModelAdmin):
list_display = ['__str__', 'owner']
class Meta:
Model = UserFavouriteProducts
admin.site.register(UserFavouriteProducts,FavouriteProductsAdmin)
|
import os
from dotenv import load_dotenv
load_dotenv()
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
BASE_API_URL = os.getenv("BASE_API_URL")
PASSWORD = os.getenv("PASSWORD")
HOST_DB = os.getenv("HOST_DB")
USER_DB = os.getenv("USER_DB")
PASSWORD_DB = os.getenv("PASSWORD_DB")
DB = os.getenv("DB") |
from leetcode import test
def is_valid(s: str) -> bool:
stack = []
for ch in s:
if ch in ("(", "[", "{"):
stack.append(ch)
elif not stack:
return False
elif (stack[-1], ch) in (("(", ")"), ("[", "]"), ("{", "}")):
stack.pop()
else:
... |
import math
class Vector(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, v):
return Vector(self.x + v.x, self.y + v.y)
def __sub__(self, v):
return Vector(self.x - v.x, self.y - v.y)
def __mul__(self, coef):
return Vector(self.x*coef, self.y... |
# coding=utf-8
# @Time : 2021/9/25 15:48
# @Author : 黄鸿林
# @File : index.py
# @Software : PyCharm
import yaml
from todaySchool.utils.Utils import Utils
from todaySchool.login.NjitLogin import NjitLogin
from todaySchool.actions.AutoClock import AutoClock
def getConfig(yaml_file='config/userConfig.yml'):
file=open(... |
def pl(items):
if type(items) == type(list()):
for i in items:
print i
else:
print "## pl: expected <type 'list'>, got %s" % type(items)
return items
def pd(items):
if type(items) == type(dict()):
for i in items.keys():
print i, "|", items[i]
else:
print "## pl: expected <type 'di... |
from django.db import models
import jsonfield
from django.contrib.postgres.fields import JSONField
class Estimates(models.Model):
QUOTE_STATUS = (
('IQ', 'Initial Quote'),
('QS', 'Quote Send'),
('WP', 'Waiting for Payment'),
('QC', 'Completed'),
)
quote_id = models.AutoField(primary_key=True)
quote_numbe... |
"""Constants for the Toggl integration."""
DOMAIN = "toggl"
CONF_SENSOR = "sensor"
|
import pyautogui
from pyautogui import *
import ppadb
from ppadb.client import Client
from PIL import Image
import numpy
import time
from mss import mss
adb = Client(host='127.0.0.1', port=5037)
devices = adb.devices()
if len(devices) == 0:
print("No device found")
quit()
device = devices[0]
#device.shell... |
def sortAsc(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
temp1 = alist[i]
temp1 = temp1.split("/")
temp1 = temp1[::-1]
temp1 = int("".join(temp1))
temp2 = alist[i + 1]
temp2 = temp2.split("/")
... |
#!/usr/bin/python
from __future__ import print_function
from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
def structure_corpus(path_to_files, new_corpus_name='structured_corpus'):
"""
Structure a corpus in some kind of sequence
"""
import corpkit
import os
import shutil
b... |
# Every email consists of a local name and a domain name,
# separated by the @ sign.
#
# For example, in alice@leetcode.com, alice is the local name,
# and leetcode.com is the domain name.
#
# Besides lowercase letters, these emails may contain '.'s or '+'s.
#
# If you add periods ('.') between some c... |
import os
from glob import glob
import numpy as np
from tqdm import tqdm
from PIL import Image
# skimage
from skimage import io, color
import skimage.transform as sktrsfm
from sklearn.metrics import precision_score, recall_score
# Pytorch
import torch
import torch.nn.functional as F
from torch.utils import data
impo... |
import sys
import io
from pathlib import Path
import requests
import numpy as np
from astropy.table import Table
from astropy.io import fits
import astropy.units as u
import astropy.coordinates as coord
SIA_URL = 'https://irsa.ipac.caltech.edu/SIA'
sia_params = {
'COLLECTION': 'wise_allwise',
'RESPONSEFORMAT'... |
class Mapper():
def __init__(self, dynamo_client):
self.dynamo_client = dynamo_client
def map(self, data):
raise NotImplementedError("Should have implemented this")
class Reducer():
def __init__(self, dynamo_client):
self.dynamo_client = dynamo_client
def reduce(self, data):... |
# 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
#
# 说明:
#
# 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
#
# 示例 1:
#
# 输入: [2,2,1]
# 输出: 1
#
#
# 示例 2:
#
# 输入: [4,1,2,1,2]
# 输出: 4
# Related Topics 位运算 哈希表
# 👍 1584 👎 0
from typing import List
from functools import reduce
# 这个数字与0异或运算以后还是自己, 然后数字与自己运算以后就变成0, 想要
# ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# type: ignore
import codecs
import os.path
import subprocess
from pathlib import Path
import setuptools
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), "r") as fp:
... |
while True:
lista = input().split(' ')
n = int(lista[0])
b = int(lista[1])
aux = 1
count = 0
def fib(n):
global count
count += 1
if n < 2:
return n
else:
return (fib(n-1)+fib(n-2))%b
if n != 0 and b != 0:
fib(n)
print(f'Case {aux}: {n} {b} {count}')
aux += 1
else:
break
|
from .models import address
def handle_uploaded_file(file){
for row in file:
newItem = address(email=row[0], name=row[1])
newItem.save()
#created = address.objects.bulk_create(email=row[0],name=row[1])
} |
import module
print("Adding the name variable from naming.py") # This should be run when the script is imported
# as __name__ = "__name__" ins't done
name = input("What's your name? ") |
# Bài 06: Viết chương trình lấy ra các phần tử key-value xuất hiện trong cả 2 dict
dict1 = {
1: 1,
2 : 2,
3 : 'Name',
4:4
}
dict2 = {
2: 1,
1 : 2,
3 : 'Name',
4 :4
}
dict1 = list(dict1.items())
dict2 = list(dict2.items())
for i in dict1 :
if i in dict2 :
print(i)
|
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from direct.directnotify import DirectNotifyGlobal
from pirates.piratesbase import TODDefs
from pirates.piratesbase import TODGlobals
from direct.distributed.ClockDelta import *
class DistributedTimeOfDayManagerAI(DistributedObjectAI):
notify =... |
"""
My implementation of the Conway's game of life in python
Ref: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
Rules
Any live cell with fewer than two live neighbours dies, as if by underpopulation.
Any live cell with two or three live neighbours lives on to the next generation.
Any live cell with mo... |
"""
2010.8.3 (onetail) : modify EPL_USB constructor and add variable self.isConnect
"""
import os
import usb1
import sys
import binascii
class DeviceDescriptor(object) :
def __init__(self, vendor_id, product_id, interface_id) :
self.vendor_id = vendor_id
self.product_id = product_id
self.in... |
import numpy as np
import pandas as pd
import time
import numba as nb
import scipy.sparse as sparse
from inference_model import MeanField, DynamicMessagePassing
from sir_model import frequency, indicator
from scipy.sparse import csr_matrix
import sib
@nb.njit()
def count_valid_c1(alli, allj, allt, maxS, minR):
"... |
import pygame
from pygame.surface import Surface
from GameLogic.Unit import *
from Helpers.EventHelpers import EventExist
from Vector2 import Vector2
class BuyUnitItem:
def __init__(self, offset: Vector2, id, image: Surface = None, rect=None):
self.Offset = offset
self.Image = image if image is n... |
import numpy as np
from operator import itemgetter
from collections import defaultdict
from collections import Counter as ct
file = "Day6/ruben.txt"
coordinates=[]
def manhatton_distance(x1,y1,x2,y2):
return abs(x1-x2)+abs(y1-y2)
#read the file
with open(file,'r') as f:
for i, line in enumerate(f):
p... |
from django.db import models
# Create your models here.
class Notes(models.Model):
title = models.CharField('Note title', max_length=50)
text = models.CharField('Text', max_length=200)
date = models.DateTimeField('Date', auto_now_add=True)
|
import sys
import os
import socket
from main import *
from Choice import *
from DoS import *
from Pass import *
from SQL import *
from datetime import datetime
from PyQt5.QtWidgets import QMainWindow, QApplication
import pymysql.cursors
conexao = pymysql.connect(
host='127.0.0.1',
user='root',
... |
import json
from flask import Flask, request, jsonify
from demo import Wikipedia
from datetime import datetime
import logging
logging.basicConfig(filename='app.log',
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
app = Flask(__name__)
@... |
# Generated by Django 3.2.5 on 2021-08-02 14:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0002_alter_project_title'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'ve... |
# coding: utf-8
# packages
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import Stra... |
################################################################# GLOBAL CLASSES ###################################################################################
## Stats for the citizen's city
class City():
var_list = [
'houses','tax','population','tax_income','barracks','troops','troop_percent',... |
from django.apps import AppConfig
class ImportExportsConfig(AppConfig):
name = 'imports'
|
from ._title import Title
from plotly.graph_objs.layout.ternary.baxis import title
from ._tickformatstop import Tickformatstop
from ._tickfont import Tickfont
|
from spotibot.core.objects import (
Activity,
Context,
General,
Music,
Podcasts,
Time,
User,
Device,
)
# Request, \
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-11 23:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resres', '0003_auto_20170511_2246'),
]
operations = [
migrations.AlterField... |
from braindecode.datasets.set_loaders import BCICompetition4Set2A
from braindecode.datasets.signal_processor import SignalProcessor
from glob import glob
import h5py
import numpy as np
import logging
log = logging.getLogger(__name__)
# Test A: check if loaded sets signal is correct for train test
# and labels correct... |
from collections import OrderedDict
from functools import reduce
from glob import glob
from operator import add
import matplotlib.pyplot as plt
import numpy as np
from PyCAR.PyCIT.FT import PowDens
from aer_construction import AerModel
from citvappru.SourceCAREM2_1_1 import Geometry
def main():
alf = AerModel()
... |
# -*- coding: utf-8 -*-
import heapq
class Solution:
def kClosest(self, points, K):
return heapq.nsmallest(K, points, key=lambda xy: xy[0] * xy[0] + xy[1] * xy[1])
if __name__ == "__main__":
solution = Solution()
assert [[-2, 2]] == solution.kClosest([[1, 3], [-2, 2]], 1)
assert [[3, 3], [... |
def compare(arg_a, arg_b) :
print(arg_a, arg_b)
if arg_a > arg_b :
print("the first argument is larger than the second one")
else:
print("the second argument is larger than the first one")
compare(3, 7)
compare(5, 3)
compare(100, 102) |
n2=('1','2','3','4','5')
#元组的数据是不能改的
#连接数据库
print(n2[1])
#n2[1]=3会出错哦
|
import torch
_TORCHFUNCTION_SUBCLASS = False
class _ReturnTypeCM:
def __init__(self, to_restore):
self.to_restore = to_restore
def __enter__(self):
return self
def __exit__(self, *args):
global _TORCHFUNCTION_SUBCLASS
_TORCHFUNCTION_SUBCLASS = self.to_restore
def set_r... |
import pandas as pd
x = pd.Series(['Jonh','Ton','Carot','Lisa','Jackie'])
a = pd.Series([1100,2000,1000,1000,1000])
b = 50
y = a+b
data= pd.DataFrame({'Name': x, 'Income': y})
print(data)
|
import optproblems.cec2005
import numpy as np
import time
from IA import *
import os
def IAalgorithm(n_parties, politicians, R, function, function_index, max_evaluations, desertion_threshold):
IA = IdeologyAlgorithm(n_parties=n_parties, politicians=politicians, R=R, function=function,
function_inde... |
from flask import request, jsonify, url_for, redirect, g, send_file
from models import Drawings
from sqlalchemy.exc import IntegrityError
from index import app, db
from modelHandler import addNewModel, getModel, getAllModels
import csv
import ast
@app.route('/api/model', methods=['POST'])
def addModel():
data = re... |
import pyaudio
import librosa
import numpy as np
import tensorflow as tf
from datetime import datetime
########## Variables ##########
RECORD_SECONDS =60
CHUNK = 8192
CHANNELS = 1
FORMAT = pyaudio.paInt16
RATE = 44100
# Socket Variables
ADDRESS = '192.168.123.6'
PORT = 21536
###############################
##########... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 14:11:49 2019
code to investigate stars going into PSFs
@author: ppxee
"""
### Import required libraries ###
import matplotlib.pyplot as plt #for plotting
from astropy.io import fits #for handling fits
from astropy.table import Table #for handl... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-07 09:57
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("organisations", "0038_copy_org_data")]
operations = [
migrations.AlterModelOptions(
... |
# Changed 9/7/2019
import sqlite3
import os
#class Sql3Conn(dbConnection):
class SQLite:
#yug = dbConnection()
#yug.foo()
# import sqlite3
path = 'init'
def __init__(self, in_Name: str):
self.name = in_Name
# groink = dbConnection("Tommy")
# groink.foo... |
#-*-coding:utf-8-*-
#selenium端测试
import re
from selenium import webdriver
import threading
import time
import unittest
from naruto import create_app,db
from naruto.models import Role,User,Post
class SeleniumTestCase(unittest.TestCase):
client=None
@classmethod
def setUpClass(cls):
#启动浏览器
... |
import tensorflow as tf
import numpy as np
import os
from scipy.stats import linregress
from util import *
from time import time
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def build_network(n_io, savename, n_hidden, n_clusters, learn_type, nonlin, learn_vars, lr_vars, train_state, norm_type):
# Construct ne... |
import unittest
import pygame
import main
class TestKeyboard(unittest.TestCase):
def setUp(self):
self.game = main.Game()
self.game.start()
def test_catching_of_pressed_buttons(self):
pygame.event.post(pygame.event.Event(pygame.KEYDOWN,
... |
#!/usr/bin/env python
import subprocess
print "Content-type: text/html"
print "<title>Picture taking CGI</title>"
print "<p>I'm going to upload the picture!</p>"
subprocess.call(['/home/pi/smile.sh'])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from student_downloader import StudentDownloader
from student_analyzer import StudentAnalyzer
from constants import Constants
import datetime
def main():
"""Run an example for a studentIDGetter class."""
#downloader = StudentDownloader()
#
# Us... |
hiddenimports = ['musclex.modules.QF_utilities'] |
import scrapy
from douban250.items import Douban250Item
class Douban250Spider(scrapy.Spider):
"""豆瓣电影Top250爬虫Spider"""
name = 'douban250'
allowed_domains=['movie.douban.com',]
base_url='https://movie.douban.com/top250?start=0'
offset=0
start_urls=[base_url+str(offset),]
def parse(self, ... |
import random
from functools import reduce
from discord.ext import commands
def roll_dice(number_of_pipes: int, throws: int) -> [str]:
return [random.randint(1, number_of_pipes) for _ in range(throws)]
def get_dices_result(number_of_pipes: int, throws: int) -> str:
dice_throw_result = roll_dice(number_of_p... |
from typing import Dict, Any
def get_stack_data():
"""Get all the stack data
This is a testing utility to oganize data required by the troposhpere stack generation.
RUNTIME (execution modes, credentials, verbosity, etc)
GLOBAL (extra-environment data like connection mapping, default enviroment da... |
#!/usr/bin/python3
import pdb
import kivy
kivy.require('1.9.0')
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
class MapTile(Widget):
""" MapTile object
"""
tile = ObjectProperty(... |
from app.utils.constant import GCN_MODEL, SUPPORTS
from app.model import base_model
from app.layer.GC import SparseGC
import tensorflow as tf
class Model(base_model.Base_Model):
'''Class for GCN Model'''
def __init__(self, model_params, sparse_model_params, placeholder_dict):
super(Model, self).__in... |
#!/usr/bin/env python
"""
This removes lines from pdb files which define
where HELIX, SHEET, or TURNs are located.
"""
import sys
def main():
for line in sys.stdin:
if ((line[0:6] != "HELIX ") and
(line[0:6] != "SHEET ") and
(line[0:5] != "TURN ")):
sys.stdout.write(... |
import datetime
from decimal import Decimal
import xlrd
from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = """
Import a XLS file containing a list of Orders.
Supports the format used by the Teaching Lab as of December 2018,
... |
'''
包其实就是一个目录,是为了解决模块名冲突的情况,只要最顶级的目录名不同,
就算模块名相同也不会有问题
包下面一定有一个__init__的文件,文件内容可以什么都不写
'''
|
import utils
import pandas as pd
import numpy as np
from datetime import timedelta
# PLEASE USE THE GIVEN FUNCTION NAME, DO NOT CHANGE IT
def read_csv(filepath):
'''
TODO: This function needs to be completed.
Read the events.csv, mortality_events.csv and event_feature_map.csv files into events, morta... |
from __future__ import division, print_function
import time
import matplotlib.pyplot as plt
import numpy as np
from numpy import asarray
from numpy import expand_dims
from numpy import log
from numpy import mean, cov
from numpy import exp
from numpy import std
from math import floor
import os
from keras.models import M... |
import argparse
from glob import glob
from operator import itemgetter
from os.path import basename, join
from pyrosetta import *
from pyrosetta.rosetta.core.scoring import ScoreType as st
from pyrosetta.rosetta.core.select.residue_selector import \
ChainSelector, NeighborhoodResidueSelector, ResidueIndexSelecto... |
import re
import requests
import time
import os
import logging
from lxml import etree
from logging.handlers import RotatingFileHandler
import pymysql
class LookComUa:
def __init__(self):
self.material_url = 'http://www.look.com.ua'
self.headers = {
'referer': self.material_url,
... |
import sys
from math import ceil
from itertools import accumulate
if len(sys.argv) == 1 or sys.argv[1] == '-v':
print('Input filename:')
f=str(sys.stdin.readline()).strip()
else: f = sys.argv[1]
verbose = sys.argv[-1] == '-v'
for l in open(f):
data = [int(x) for x in l.strip()]
def num(l):
return sum([ x... |
from lettuce import *
from nose.tools import assert_equal, assert_in
from webtest import TestApp
from app.code.bank.app import app, BANK
from app.code.bank.account import Account
@step(u'Given I create following account:')
def given_i_create_following_account(step):
for row in step.hashes:
a = Account(ro... |
__author__ = 'thomas'
import unittest
from MathFunctions import *
class TestHelperFunctions(unittest.TestCase):
def test_modexp(self):
"""
check modexp of a number
:return:
"""
self.assertEqual(MathFunctions.modexp(2, 5, 7), 4)
self.assertEqual(MathFunctions.modex... |
import os, fnmatch
oldName = input("Insert old app name (stackedql): ") or "stackedql"
newName = input("Insert new app name: ")
if not newName: exit(0)
apppath = "src/"+oldName+"_app"
ferrypath = "src/"+oldName+"_ferry"
newapppath = "src/"+newName+"_app"
newferrypath = "src/"+newName+"_ferry"
def checkdirs():
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 10:23:54 2020
@author: Alex
"""
import numpy as np
import matplotlib.pyplot as plt
#Defin a routine which in 1D interpolates a lagrange polynomial through 3 samples, and/
#then calculated the minima of the interpolated parabola
def par_min(x0, x1, x2, f):
y0, y1,... |
from django.contrib import admin
# Register your models here.
from backend.models import *
class SubcategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'get_category_name')
def get_category_name(self, obj):
return obj.category.name
class FilledSubcategoryAdmin(admin.ModelAdmin):
list_displ... |
# vim: set fileencoding=utf-8 :
"""
~~~~~~~
Classes
~~~~~~~
Contains :class:`DictableModel` that can be used as a base class for
:meth:`sqlalchemy.ext.declarative_base`.
"""
from __future__ import absolute_import, division
from zeelalchemy import utils
class DictableModel(object):
"""Can be used as a base cla... |
n = int(input())
for x in range(n):
a = int(input())
if a % 2 == 0:
print("é par")
else:
print("é impar") |
import gevent
# gevent中的主要模式是Greenlet
# 以C扩展的模块形式接入到Python的轻量级协程
# 全部运行在操作系统进程的内部 但他们被协作式的调度
def Foo():
print('running in foo')
gevent.sleep(1)
# 模仿IO操作
print('Explicit context switch back to foo ')
def Bar():
print('Explicit context to bar')
# Explicit精确的
gevent.sleep(2)
print("Impli... |
from .roleplaying import Roleplaying
def setup(bot):
bot.add_cog(Roleplaying(bot))
|
#!/usr/bin/python
import sys
sys.path.insert(0,"/var/www/flaskapp/")
from hello import app as application |
import unittest
from katas.kyu_6.length_of_missing_array import get_length_of_missing_array
class LengthOfMissingArrayTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(get_length_of_missing_array(
[[1, 2], [4, 5, 1, 1], [1], [5, 6, 7, 8, 9]]
), 3)
def test_equ... |
#!/usr/bin/env python3
import socket
myServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
myIP = ('172.20.1.1')
myPort = 5000
myServerInfo = (myIP, myPort)
print('Server Port:', myPort)
myServerSocket.bind(myServerInfo)
myServerSocket.listen(1)
while True:
print(f'Waiting for a connection on {myIP... |
import pyglet
from pyglet.gl import *
import pymunk
from pymunk import Vec2d
import math
import levelassembler
import camera
from math import sin,cos
import particles2D
import loaders
import PiTweener
class Hint:
def __init__(self, position, padding, image):
self.position = position
self.padding = ... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the queensAttack function below.
# def move_queen(n, updated_row, updated_col, r, c, obstacles):
# p = 0
# while True:
# r = updated_row(r)
# c = updated_col(c)
# key = (r - 1) * n + c
# if (c < ... |
import numpy as np
import matplotlib.pyplot as plt
import time
start_time = time.time() # start time of execution of code
seed = 0.1; # seed value or starting value
rnum = 5000 # number of values 'r' takes.
rlist = np.linspace(0.1,4,rnum) # array storin... |
print('%2d-%2d' % (3, 1))
print('%.2f' % 3.1415926)
s1 = 72
s2 = 85
r = s2-s1
print('%.1f%%' % r)
print('Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.