text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
from atlas.extensions import db
from atlas.database import SurrogatePK, TimestampedModel
class SlackToken(SurrogatePK, TimestampedModel):
token = db.Column(db.String, unique=True, nullable=False)
channel = db.Column(db.String, nullable=False)
description = db.Column(db.String)
... |
import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
rds = redis.Redis(connection_pool=pool)
def set(key, val):
rds.set(key, val)
def get(key):
return rds.get(key)
def remove(key):
return rds.delete(key)
|
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run multicolored-lamp
# https://py.checkio.org/mission/multicolored-lamp/
# The New Year is coming and you've decided to decorate your home. But simple lights and Christmas decorations are so boring, so you have figured that you can use... |
__author__ = 'Hk4Fun'
__date__ = '2018/3/28 15:53'
'''题目描述:
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12],
after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do... |
import numpy as np
import pandas as pd
raw = pd.read_csv("Group2-311DataPreCOVID-Cold Season.csv")
cols2Drop = ["ADDRESS", "Sum SOURCE ", "Sum DAYTOCLOSE",
"CREATTIME", "CREATEMO", "CREATEYR", "CLOSEMO", "ADDGEOC", "CASEURL"]
s1 = raw.drop(cols2Drop, axis=1)
|
from django.db import models
class Customer(models.Model):
customer_name = models.CharField(max_length=50)
city = models.CharField(max_length=50)
state = models.CharField(max_length=5)
address = models.CharField(max_length=150)
class Circuit(models.Model):
customer = models.ForeignKey('Customer',... |
from django.shortcuts import render
from .models import *
from django.http import JsonResponse
import json
def store(request):
items = Item.objects.all()
context = {'items': items}
return render(request, 'store.html', context)
def cart(request):
if request.user.is_authenticated:
customer = ... |
#!/usr/bin/env python
# coding: utf-8
'''
Turtle starter code
ATLS 1300
Author: Dr. Z
Author: YOUR NAME
May 29, 2020
'''
from turtle import * #import the library of commands that you'd like to use
#Create a panel to draw on.
panel = Screen()
w = 600 # width of panel
h = 600 # height of panel
panel.setup(width=w, he... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Send SMS via PanaceaMobile API"""
#
# @author: Jacek Smit<info@jaceksmit.nl>
#
from contextlib import suppress
import random
import string
import requests
from PanaceaMobile.const import VERSION, \
CONFIG_FILE_CONTENT
_API_URL = "http://api.panacea... |
from django.contrib.auth.forms import UserChangeForm,UserCreationForm ,AuthenticationForm
from .models import CustomUser
from django.db import models
class CustomUserCreationForm(UserCreationForm):
class Meta:
model =CustomUser
fields=('username','email','full_name')
class CustomUserChangeForm(UserChangeFor... |
#to guess a number
guessnum=78
innum=0
user_input=0
while innum!=guessnum:
innum=int(input("Enter the number"))
user_input+=1
if innum<guessnum:
print("number is less")
else :
print("number is right")
if user_input>3:
print("that must have been complicated")
print("you guessed... |
#!/usr/bin/env python
import sys
def parseInput():
with open ("input.txt", "r") as myfile:
myInput = myfile.read()
myInput = myInput.split('\n')
return myInput
def part1():
my_input = parseInput()
steps_set = set()
for l in my_input:
steps_set.add(l[5])
steps_set.add(l... |
# // The colors to blend
# source = {'r': 255, 'g': 213, 'b': 0, 'a': 0.6}
# backdrop = {'r': 141, 'g': 214, 'b': 214, 'a': 0.6}
def colorme(colors):
# // This example shows the result of blending 'source' and 'backdrop' with the 'hue' blending mode, according to the W3C or Adobe spec
# // However the composite could ... |
# Generated by Django 2.1.7 on 2019-04-30 17:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0021_assignment_restrict_date'),
('courses', '0023_auto_20190430_1310'),
]
operations = [
]
|
import logging
from typing import Optional
import torch
import torch.nn as nn
from os.path import exists
from os import makedirs
class TrainLogger(object):
def __init__(self, experiment_type, experiment_no):
"""
Custom logger to log hyperparameters, results and save model checkpoints
:par... |
#! usr/bin/env python
import string, time
print("This program adds numbers. Type in numbers in the form: a,b. Thanks.")
while True:
try:
numstr = input("Input: ")
except Exception as inst:
numstr=None
print("It seems you didn't type in the correct form.")
continue
if type(numstr) is not tuple:
print("It ... |
from django.test import TestCase
from ..models import ContactForm
from django.utils import timezone
from django.core.urlresolvers import reverse
# Model test
class ContactFormTest(TestCase):
"""Docstring for ContactFormTest. Building test for contact/models.py """
def create_contactform(self, first_name="test... |
from django.db.models import Sum
from rest_framework import serializers
from restaff.api.employee.models import Employee
from restaff.api.hr.models import Vacancy
from restaff.core.base.models import Skill, Position
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fie... |
"""
mkinit netharn.schedulers
"""
__DYNAMIC__ = False
if __DYNAMIC__:
import mkinit
exec(mkinit.dynamic_init(__name__))
else:
# <AUTOGEN_INIT>
from netharn.schedulers import core
from netharn.schedulers import iteration_lr
from netharn.schedulers import listed
from netharn.schedulers.core ... |
from google.appengine.ext import ndb
class Guestbook(ndb.Model):
name = ndb.StringProperty()
email = ndb.StringProperty()
message = ndb.StringProperty()
time = ndb.DateTimeProperty(auto_now_add=True)
deleted = ndb.BooleanProperty(default=False) |
import re, Assignments, fileinput, Averages
gradeConverter = re.compile(r'''
(.*)
\-
\s(\d+)\s
\/
\s(.*)''', re.VERBOSE)
def customRegex(word, position, path):
print('\n')
wordS = re.compile(word)
with open(Assignments.all_paths[position], 'r') as f:
for line in f:
c... |
# imports
import torch
from torch import nn
import twobitreader
from twobitreader import TwoBitFile
from torch.utils.serialization import load_lua
print("got pytorch version of {}".format(torch.__version__))
# set the code and data directories
# dir_code = "/Users/mduby/Code/WorkspacePython/"
# dir_data = "/Users/mdu... |
import sys
from PyQt import QtCore, QtGui, uic
import random
def callWords():
#get words puts them in lbls
def pushButton(local):
#push button to get words
|
#!/usr/bin/env python
from git import Repo
from sys import exit
from pync import Notifier
from time import sleep
import requests
import argparse
import getpass
import json
class WatchGitHubOrgPRs:
def __init__(self, api_url, org, creds):
self.api_url = api_url
self.org = org
self.creds = creds
self... |
import hashlib, binascii, os
from flask import Flask, session, request, render_template, flash, redirect, url_for, jsonify
from flask_session import Session
from sqlalchemy.orm import scoped_session, sessionmaker
from models import *
from create import app
from datetime import timedelta
from sqlalchemy import or_, and... |
import numpy as np
from bokeh.plotting import figure, show, output_file, ColumnDataSource
import matplotlib.pyplot as plt
def vectorize(Y):
vector = np.zeros(10, dtype=int)
vector[Y] = 1
return vector
with open('./train_x.txt') as x:
train_x = np.array([element.split(' ') for element in x.readlines()[... |
#!/usr/bin/python
#suppose the all DNs have been extracted
import ldap
import sys, ldif
def onelevel_dn_search(baseDN,ldap_conn):
#ldap_result_id = ldap_conn.search(baseDN, ldap.SCOPE_ONELEVEL, "accountNumber=*1")
ldap_result_id = ldap_conn.search(baseDN, ldap.SCOPE_ONELEVEL)
result_set = []
#ldif_writer=ldif.... |
from gpiozero import LED
from signal import pause
green = LED(19)
green.blink(on_time=0.5, off_time=0.5)
try:
pause()
except:
pass
print("end") |
def equilateral(sides):
equilateral = False
if sides[0] > 0 and sides[1] > 0 and sides[2] > 0:
if sides[0] == sides[1] and sides[0] == sides[2]:
if max(sides) < (sum(sides)-max(sides)):
equilateral = True
return equilateral
def isosceles(sides):
isosceles = False
... |
import pickle
from collections import Counter
import matplotlib.pyplot as plt
if __name__ == '__main__':
with open('../../../data/neko.vocab', 'rb') as f:
w_cnt = pickle.load(f)
counts = [cnt for w, cnt in w_cnt.most_common()]
plt.scatter(range(1, len(counts) + 1),counts)
plt.xscale('log')
... |
import numpy as np
import scipy.sparse as sp
from .distortion import filter_adj
def grid_adj(shape, connectivity=4, dtype=np.float32):
"""Return adjacency matrix of a regular grid."""
assert connectivity == 4 or connectivity == 8
h, w = shape
if connectivity == 4:
filt = [-w - 2, -1, 1, w ... |
"""
day: 2020-09-08
url: https://leetcode-cn.com/problems/find-positive-integer-solution-for-a-given-equation/
题目名: 找出给定方程的正整数解
给出一个函数 f(x, y) 和一个目标结果 z,请你计算方程 f(x,y) == z 所有可能的正整数 数对 x 和 y。
给定函数是严格单调的,也就是说:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
思路:
"""
from typing import List
"""
This is the custom functio... |
# -*- coding: utf-8 -*-
from ..vendor import Qt
from ..vendor.Qt import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(524, 722)
Form.setMinimumSize(QtCore.QSize(0, 0))
self.gridLayout = QtWidgets.QGridLayout(Form)
... |
#!/usr/bin/env python
# coding=utf-8
from setuptools import setup
package_name = 'calculadora'
filename = package_name + '.py'
setup(
name=package_name,
version=1.0,
author='gui',
author_email='gui.ironweasel',
description='curl statistics made simple',
url='https://github.com/reorx/httpsta... |
import json
import random
from string import ascii_letters
studentsData = json.load(open("sample_students.json"))
names = [
"Brunilda Brownlee",
"Dionne Tart",
"Roseanne Locker",
"Berry Branscum",
"Eulalia Frates",
"Lessie Mcnear",
"Karisa Ingham",
"Zona Avitia",
"Love Levingston",... |
class PID(object) :
def __init__(self, dt=0.01, Kp=8.0, Ki=0.0, Kd=0.09 ):
self.dt = dt
self.previous_error = 0.0
self.integral = 0.0
self.derivative = 0.0
self.setpoint = 0.0
self.output = 0.0
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
... |
import string
import os
from ROOT import *
import ROOT
import math
from array import array
gROOT.LoadMacro("AtlasStyle.C")
from ROOT import SetAtlasStyle
SetAtlasStyle()
gROOT.SetBatch(True)
def calQ(s,b):
Q = 2*((s+b)*math.log(1+s/b)-s)
return Q
def plotQ():
h2 = TH2F('h2', '', 100,0,1,100,0,1)
fo... |
from pyomo.environ import *
from pyomo.opt import SolverFactory, SolverManagerFactory
from DiseaseEstimation import model
# create the instance
instance = model.create('DiseaseEstimation.dat')
# define the solver and its options
solver = 'ipopt'
opt = SolverFactory( solver )
if opt is None:
raise Val... |
import tensorflow as tf
import skimage.transform
import numpy as np
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
# Wrap... |
import modifyrandomsingle as mdet
import os
import re
import subprocess
import modifylib as lib
def main():
modifyFilePath = "/home/jan/coreutils/src/touch.c"
testFilePath = ["/home/jan/coreutils/tests/touch", "/home/jan/coreutils/tests/misc/help-version.sh", "/home/jan/coreutils/tests/misc/invalid-opt.pl"]
... |
### File: MKP.py
### Purpose: to solve the MDMKP using Traditional Jaya or Modified Jaya
### Author: Zachary Kern
###
import random
# just a random seed that i created so that the random numbers are repeatable
random.seed(123456789)
from collections import Counter
### Class: Solution
### Pur... |
from peewee import *
from peewee import DoubleField, FloatField, ProgrammingError
import numpy as np
import inspect
import sys
from playhouse.postgres_ext import PostgresqlExtDatabase, ArrayField
from IPython import embed
import scipy as sc
from scipy import io
import csv
import os
sys.path.append(os.path.dirname(os.pa... |
#!/usr/bin/env python
import pandas as pd
import sys
unclean = sys.argv[1].strip()
ranking = sys.argv[3].strip() # ranking algorithm
scorings = sys.argv[4:]
clean_filename = unclean[:-4] + '_clean.tsv'
print clean_filename
table = pd.read_csv(unclean)
cols = set(table) # Create set from table headers
cols.remove('SU... |
__author__ = "Calvin Huang"
from wpilib import DriverStation
from grt.core import Sensor
# button/pin pair list
BUTTON_TABLE = [('button1', 1), ('button2', 3), ('button3', 5),
('button4', 7), ('button5', 9), ('button6', 11),
('button7', 13), ('button8', 15),
('l_toggle'... |
# code adapted from here:
# https://github.com/maksim2042/SNABook
# We often want to be able to traverse the structure of a graph or network
# to find the shortest path from node A to node B, or to understand the
# structure of the graph.
print()
import matplotlib.pyplot
import networkx
from net... |
"""Defines two operations on dbus type strings:
* `typehint(str)` generates a list of python type hints in string form,
for adding to generated code templates.
* `instantiate(str)` returns a list of the default values of every type
in the input string.
Both functions take an optional argument `dbus: bool` argumen... |
import datetime
import collections
pod_name_job = {}
job_id_job = {}
batch_id_batch = {}
def _log_path(id):
return f'logs/job-{id}.log'
def _read_file(fname):
with open(fname, 'r') as f:
return f.read()
_counter = 0
def max_id():
return _counter
def next_id():
global _counter
_co... |
# -*- coding: utf:8 -*-
import sys
import numpy as np
import subprocess
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QSize, QBasicTimer
from PyQt5.QtGui import *
class Rgb(QWidget):
def __init__(self):
super().__init__()
self.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
tarea_1.py
------------
Tarea de desarrollo de entornos y agentes
==========================================
En esta tarea realiza las siguiente acciones:
1.- Desarrolla un entorno similar al de los dos cuartos (el cual se encuentra
en el módulo doscuartos_o.py),... |
# script to generate report
from email.utils import COMMASPACE, formatdate
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename
import smtplib
import patientdata
from monitoringmonths import MonitoringMonthLis... |
#!/bin/env python
from server import app
from config import SERVER_HOST, SERVER_PORT
if __name__ == '__main__':
# start running server
app.run(host=SERVER_HOST, port=SERVER_PORT, threaded=True) |
from .models import *
from .serializers import *
from rest_framework import generics
class LeadListCreate(generics.ListCreateAPIView):
queryset = Lead.objects.all()
serializer_class = LeadSerializer
class LeadDetails(generics.RetrieveUpdateDestroyAPIView):
queryset = Lead.objects.all()
serializer_cl... |
import pygame, sys, random
from pygame import *
from random import *
init()
size = width,height = 800,600
screen = display.set_mode(size) # makes the screen
best_time = [0, 4, 8, 12, 18, 20]
best_update = ""
frame_count = 0
frame_rate = 20
clock=pygame.time.Clock()
cards = []
card_types = []
sb = 0
length = 0
brea... |
from autograd import value_and_grad
from autograd import grad as compute_grad
import autograd.numpy as np
from autograd.misc.flatten import flatten
from autograd.misc.flatten import flatten_func
# gradient descent function
def gradient_descent(g,w_unflat,alpha_choice,max_its,version,**kwargs):
verbose = False
... |
a=int(input())
r=0
s=0
s1=0
s2=0
t=0
while(a!=0):
t=a%10
s=t
a=a//10
s1=s*s*s
s2+=s1
print(s2)
if(a!=s2):
print("yes")
else:
print("no")
|
def part1(expenses: [int]) -> int:
for e1 in expenses:
for e2 in expenses:
if e1 + e2 == 2020:
return e1 * e2
def part2(expenses: [int]) -> int:
for e1 in expenses:
for e2 in expenses:
for e3 in expenses:
if e1 + e2 + e3 == 2020:
... |
# https://leetcode.com/problems/search-suggestions-system/
"""
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If ... |
"""
Created on Thu Dec 7 21:59:58 2017
@author: Raphael
"""
import json
import numpy as np
data = json.load(open('../dataset/train.json'))
#Preprosessing: cusine norminalization
cuisine_cnt_vector = {'greek': 0, 'southern_us': 0, 'indian': 0,
'italian': 0, 'mexican': 0, 'chinese': ... |
import sqlite3
"""
sql_statement - string
args - tuple. If only one item, must append with empty comma.
example: sql_statement = 'SELECT * FROM Stock WHERE TickerSymbol=?
args = ('APPL',)
"""
def db_query(sql_statement, args=(), onerow=False):
conn = sqlite3.connect('db.sqlite3')
conn.row_factory = sqlite3.Row
... |
import sys
import re
from anonymizeSkype import anonymizeSkype
from anonymizePhone import anonymizePhone
from anonymizeEmail import anonymizeEmail
if (len(sys.argv) < 4):
print("Pass command, input and output file names to script as command line arguments!")
print("For example: python3 ep i.txt o.txt")
sys.exit(1)... |
import hug
import falcon
import hug.development_runner
from multipart.hug_multipart import multipart
api = hug.API(__name__)
api.http.set_input_format("multipart/form-data", multipart)
route = hug.http(api=api)
@route.post("/upload")
def upload(**kwargs):
file = kwargs.get("upload_file")
if file:
pri... |
# -*- coding: utf-8 -*-
"""
Created on Thu July 20 2017
This is the main execution script dynamic network type contact networks for RT structures.
Files formed- all_contacts.txt, framesXXXX_contacts.txt, comntact_matrix.txt
@author: ashutosh
"""
import os
import sys
import command_args
import create_network
import nu... |
# Database Manager for the server side. Handles all queries to the MongoDB
# database.
# Author: Alvin Lin (alvin.lin.dev@gmail.com)
from bson.objectid import ObjectId
from pymongo import MongoClient
import os
import time
from util import Util
DATABASE_NAME = 'api-project'
DATABASE_URL = os.environ.get('MONGOLAB_UR... |
import views
from flask import render_template, Flask, g, redirect, url_for, request
from werkzeug.contrib.cache import SimpleCache
from werkzeug.contrib.fixers import ProxyFix
# 14 days
CACHE_TIMEOUT = 60*60*24*14
cache = SimpleCache()
app = Flask(__name__)
app.register_blueprint(views.mod)
app.wsgi_app = ProxyFix(... |
# pip install Augmentor
import Augmentor
p = Augmentor.Pipeline("/Users/AdaTaylor/Desktop/ml_pics/data/caltech-101/101_ObjectCategories")
# We will only do replacements of the images we have
# so it's easy to keep the ground truth array the same
# and just copy if for multiple sets of images
# Set the probabilitie... |
class StatsComputeOptions(object):
def __init__(self):
pass
def get_apply_seasonal_cycle_filter(self, default="false"):
raise Exception("Please implement")
def get_max_lat(self, default=90.0):
raise Exception("Please implement")
def get_min_lat(self, default=-90.0):
ra... |
import os, sys
import pickle
import torch
import torchvision
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as pl
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.gridspec as gsp
import matplotlib.colors as mpc
from mpl_toolkits.mplot3d impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
from faker import Faker
@pytest.fixture(scope="module")
def faker():
return Faker()
|
import unittest
import parity
class ParityTests(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self.maxDiff = None
self.grid_1 = [
["X","O","X","X","X"],
["X","X","O","O","O"],
["X","O","X","O"... |
import socket
import sys
from time import sleep
from random import randrange
if len(sys.argv) < 2 or not sys.argv[1].isdigit():
sys.exit("Port number required")
# set GET message
data1 = "JOIN_CHATROOM: room\nCLIENT_IP: 0\nPORT: 0\nCLIENT_NAME: client\n"
data2 = "CHAT: room\nJOIN_ID: 0\nCLIENT_NAME: client\nMESSA... |
import unittest
import numpy as np
import pandas as pd
from geeksw.utils.pd_utils import format_errors_in_df
np.random.seed = 123
class Test(unittest.TestCase):
def test_pd_utils(self):
# check if format_errors_in_df works
a = np.random.uniform(size=10)
a_err = np.random.uniform(size=1... |
"""
Runs LKH one by one
"""
import subprocess
import os
gridsize=8
os.chdir("../LKH")
for i in range(gridsize):
for j in range(gridsize):
print i,j
ass=subprocess.Popen(["./LKH","cut"+str(i)+"_"+str(j)+".par"])
ass.wait() |
from flask import Flask, request, render_template
import praw
import json
import pandas as pd
import numpy as np
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA
import seaborn as sns
from IPython import display
from pprint import pprint
import praw
import matplotlib.pyplot as plt
app =... |
import csv
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn.model_selection import train_test_split
# cutomize the Decision tree, make the maximum numbe... |
from tkinter import *
import random
import time
import datetime
width = 1350
height = 650
root = Tk()
root.geometry(str(width) + "x" + str(height) + "+0+0")
root.title("Billing Systems")
Tops = Frame(root, width=width, height=100, bd=8, relief='raise')
Tops.pack(side=TOP)
# main-frame
f1 = Frame(root, width=900, he... |
from __future__ import division
import os
import numpy as np
import pandas as pd
from inferelator.distributed.inferelator_mp import MPControl
from inferelator import utils
from inferelator.utils import Validator as check
# Number of discrete bins for mutual information calculation
DEFAULT_NUM_BINS = 10
# DDOF for C... |
from erlyx.agents.base import PolicyAgent
from erlyx.policies import Policy
from erlyx import types
import numpy as np
from collections import deque
class EpsilonGreedyAgent(PolicyAgent):
def __init__(self, policy: Policy, epsilon):
super(EpsilonGreedyAgent, self).__init__(policy=policy)
self.ep... |
from urllib.parse import urlparse, urljoin
from flask import Flask, render_template, request, session, redirect
from flask_login import LoginManager, UserMixin, login_user, login_required, \
current_user, logout_user
from flask_sqlalchemy import SQLAlchemy
APP = Flask(__name__)
APP.config['SECRET_KEY'] = 'ThisIsAS... |
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
from io import BytesIO
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
"""
handle the githup webhook notifications. this method does not care the concrete
event. just pull and update simply.
... |
class NoSuchRoomError(Exception):
pass # TODO Add logging to all Exceptions
# TODO Add exceptions to Exceptions file
class NotEnoughPlayersError(Exception):
pass
class GameAlreadyStartedError(Exception):
pass
class CanNotEnterRoomError(Exception):
pass
|
import time
A = [34, 8, 64, 51, 32, 21]
def choice_sort(A):
start = time.time()
for i in range(0,len(A)):
t = i
for j in range(i,len(A)):
if A[i] > A[j] & A[t] > A[j]:
t = j
j += 1
A[t],A[i] = A[i],A[t]
end = time.time()
print(A)
pr... |
import os
from telethon import TelegramClient, events, sync, types
from flask import (Flask,session, g, json, Blueprint,flash, jsonify, redirect, render_template, request,
url_for, send_from_directory)
from werkzeug.utils import secure_filename
from asgiref.sync import async_to_sync, sync_to_async
im... |
import os
from xml.etree import ElementTree
import pandas as pd
class Patient:
def __init__(self):
self.text = None
self.id = 0
self.Asthma = None
self.CAD = None
self.CHF = None
self.Depression = None
self.Diabetes = None
self.Galls... |
"""
Author:Nguyễn Mạnh Trung
Date: 11/10/2021
Problem:
A group of statisticians at a local college has asked you to create a set of functions
that compute the median and mode of a set of numbers, as defined in Section
5.4. Define these functions in a module named stats.py. Also include a function
n... |
"""
Lexicographic Permutations
Project Euler Problem #24
by Muaz Siddiqui
A permutation is an ordered arrangement of objects. For example, 3124 is one
possible permutation of the digits 1, 2, 3 and 4. If all of the permutations
are listed numerically or alphabetically, we call it lexicographic order. The
lexicograph... |
def isValidChessBoard(board: dict) -> bool:
if "bking" not in board.values() or "wking" not in board.values():
return False
# count players pawns
black_amount= 0
white_amount = 0
white_pawns_count = 0
black_pawns_count = 0
for count in board.values():
if count[0] == 'b':
... |
import turtle
def main_game():
pen3.clear()
def game_over():
win1 = turtle.Screen()
win1.bgcolor("black")
win1.setup(width=800, height=600)
win1.tracer(0)
pen.clear()
pen2 = turtle.Turtle()
pen2.speed(0)
pen2.color("white")
pen2... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 09:49:54 2021
@author: i0853
"""
from flask import Flask, request, abort
import json
import logging
from kiteconnect import KiteConnect
logging.basicConfig(level=logging.DEBUG)
kite = KiteConnect(api_key="your_api_key")
# Redirect the user to the ... |
# -*- coding: utf-8 -*-
'''
WhatsApp Xtract v2.0
- WhatsApp Backup Messages Extractor for Android and iPhone
Released on April 26, 2012
Last Update on May 2nd, 2012 (v2.0-bugsfixed-8)
Tested with Whatsapp (Android) 2.7.5613
Tested with Whatsapp (iPhone) 2.5.1
Changelog:
V2.0 (updated by Fabio Sangiac... |
### Anthony Soroka HW 4 CS 207
from pytest import raises
from binsearch import binary_search
import numpy as np
import random
# baseline test that binary search can find value in sorted list
def test_BS():
myInput = list(range(10))
assert binary_search(myInput,5) == 5
# Index returned is less than length of the i... |
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import pyttsx3
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
... |
#!/usr/bin/python
formatter = "%r %r %r %r"
print formatter % (1,2,3,4)
print formatter % ("one","two","three","four")
print formatter % (True,False,False,True)
print formatter % (formatter,formatter,formatter,formatter)
print formatter % ("String one",
"String two",
"String three"... |
# roep deze functie aan om het spel opnieuw klaar te zetten
def resetBoard(self, white, black):
# dit zet de array op volgorde zodat erdoor heen kan worden gegaan op volgorde van de for loop
whiteConverted = {
"R1" : [white["R1"][0], "K1"],
"N1" : [white["N1"][0], "Q1"],
... |
import argparse
import subprocess
import shlex
import shutil
#from pathlib import Path
import yaml
import os
import sys
# Options
def get_args():
parser = argparse.ArgumentParser("Somatic Variant Calling Pipeline\n")
parser.add_argument("-a", "--analysis",
help="Options: preprocess, c... |
import sys
import pylab
import numpy
import time
import math
import imp
import moose
import os
import datetime
print "moose path", moose.__path__
dataDir = '_data'
stamp = datetime.datetime.now().isoformat()
dataDir = os.path.join( dataDir, stamp )
if not os.path.exists( dataDir ):
os.makedirs( dataDir )
loadpa... |
import Model
from datetime import datetime
def iniciarScript():
Model.carregarUsuariosDoArquivo()
def cadastrarUsuario():
Model.cadastrarUsuario()
def listarUsuarios():
Model.listarUsuarios()
input("\n\nPressione qualquer tecla para sair.")
def excluirUsuario():
login = input(" Informe o logi... |
class InvalidString(Exception):
def __init__(self,msg):
self.msg = msg
def print_exception(self):
print("Invalid String Exception:",self.msg)
def asteriskChecker(mymessage):
try:
flag = 0
for k in mymessage :
if k == '*':
flag = 1
else... |
#Компьютер выбирает случайное слово и переставляет буквы
#Задача - угадать слово
import random
#создаем последовательность слов
WORDS = ("угадай", "слово", "буквы", "перепутаны", "рандомно")
#выбираем случайное слово из созданной последовательности
word = random.choice(WORDS)
count = 0
correct = word
#соз... |
# coding: utf-8
# ## Eager evaluation
#
# Let's consider a function that generates a fibonacci series of length `n`. This is an *eager* implementation, because the full series is created and held in memory at once.
# In[1]:
def eager_fibonacci(n):
l = [1, 1]
for i in range(n-2):
l.append(sum(... |
import unittest
import mock
ROVER_ID = 1
class TestMapper(unittest.TestCase):
def setUp(self):
from surfacemapper.mapper import Mapper
self.mapper = Mapper()
def testDown(self):
self.mapper = None
def test_mapper_init(self):
self.assertIsNotNone(self.mapper)
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.