text stringlengths 38 1.54M |
|---|
# Create your views here.
from django.shortcuts import render_to_response
from petra.rsdownloads.models import *
from django.http import HttpResponse
from django.core import serializers
from django.utils import simplejson
def view_download(request, download_id):
"""
Prepare data for view of download
download_i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 10:26:19 2019
@author: rakshit
"""
from pprint import pprint
import argparse
import os
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--PrTest', type=int, default=1)
parser.add_argument('--lr', type=float,... |
# -*- coding: utf-8 -*-
#
# League of Code server implementation
# https://github.com/guluc3m/loc-server
#
# The MIT License (MIT)
#
# Copyright (c) 2017 Grupo de Usuarios de Linux UC3M <http://gul.es>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated doc... |
from setuptools import setup, find_packages
setup(
name="skepticoin",
description="The Coin for Non-Believers",
long_description=open("README.md", 'r').read(),
long_description_content_type='text/markdown',
author="Sashimi Houdini",
url="https://github.com/skepticoin/skepticoin/",
install... |
# Generated by Django 3.2.4 on 2021-07-02 02:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cn', '0006_auto_20210630_2100'),
]
operations = [
migrations.AlterField(
model_name='colab',
name='rut',
... |
import os
import numpy as np
import xml.etree.ElementTree as ET
from PIL import Image
from xml.etree.ElementTree import *
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
class API_auto_annotation... |
"""""""""""""""""""""
Lab2 - find median
2/22/2019 - Ken M. Amamori
CS2302 MW 10:30 - 11:50
"""""""""""""""""""""
from random import random
import copy
import time
""""""""""""""""""""""""""""""""""""
#List Functions
class List(object):
# Constructor
def __init__(self):
self.head = None
... |
#!/usr/bin/python3
# coding: utf-8
from unittest import TestCase
import requests
base_url = 'http://localhost:8080/user/'
class TestAppUser(TestCase):
def test_login(self):
url = base_url+"login/"
data = {
'name': '13629189683',
'pwd': '189683'
}
resp = re... |
import ROOT
import os
#rootfile_dir = '/afs/cern.ch/user/x/xgao/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/Run2016E/HLTPhysics_2016E/HLTPhysics/HLTPhysics0/160726_112922/0000'
#if '.root' in rootfile_dir:
# tmp_file = ROOT.TFile.Open(rootfile_dir)
# print 'open file : %s'%rootfile_dir... |
import random
import unittest
import torch
HAS_INDEX_MUL_2D_RELU = None
try:
from apex.contrib.index_mul_2d import index_mul_2d
except ImportError as e:
HAS_INDEX_MUL_2D_RELU = False
else:
HAS_INDEX_MUL_2D_RELU = True
@unittest.skipIf(not HAS_INDEX_MUL_2D_RELU, "`apex.contrib.index_mul_2d` is not found.... |
#########################################################################
# Date: 2018/10/02
# file name: 3rd_assignment_main.py
# Purpose: this code has been generated for the 4 wheel drive body
# moving object to perform the project with line detector
# this code is used for the student only
#########################... |
# -*- coding: UTF-8 -*- #
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('integer', type=int, help='display an integer')
parser.add_argument('-string', type=str, dest='haha', default='abc', help='display an string')
args = parser.parse_args()
print args.integer
#if args.string:
# print ar... |
from serial import Serial
from m_rfid.db import *
import logging
import time
import re
timePause = 0;
logging.basicConfig(level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)-15s - [%(levelname)s] %(module)s: %(message)s', )
def Rfid_loop():
ser = Serial()
try:
ser... |
from dojo.connectdatabase import ConnectDatabase
from peewee import *
class Entries(Model):
get_counter = IntegerField()
post_counter = IntegerField()
class Meta:
database = ConnectDatabase.db
|
import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QWidget,QPushButton,QHBoxLayout,QFileDialog
def openSaveDialog():
option=QFileDialog.Options()
#first param is qwidget
#second param is Window Title
#third title is Default File Name
#fourth param is FileType
#fifth is options
... |
'''Sutton Dole's P5
String manipulation
'''
def plural(oldString):
newString = ""
listOfExceptions = ["o", "ch", "s", "sh", "x", "z"]
listOfVowels = ["a", "e", "i", "o", "u"]
indexOfSpaces = []
listOfOldStrings = []
currentIndex = 0
for x in oldString:
if x == ' ':
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import re
from operator import attrgetter
import psycopg2
import yaml
# Matches a view or function definition
SQL_VIEW_STATEMENT_RE = re.compile(
r'(?P<declaration>'
'create\s+(or replace\s+)?' # Matches 'create [or replace]'
'(?P<... |
def list_vms(nova_client):
'''
query nova, list all virtual machines
'''
vms = nova_client.servers.list(True)
return vms
def list_routers(neutron_client):
'''
query neutron, list all routers
'''
routers = neutron_client.list_routers()
return routers
def list_ports(neutron_client):
'''
query neutron,... |
# -*- coding: utf-8 -*-
""" Models for the articles application. """
# standard library
# django
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.formats impo... |
# -*- coding: utf-8 -*-
import sqlite3
import sys
args={};
args[1]="PATH"
for i in range(len(sys.argv)):
args[i]=sys.argv[i]
curType=args[1]
# SQLite DB 연결
conn = sqlite3.connect("/home/pi/app/BaroScript/data/config.db")
# Connection 으로부터 Cursor 생성
cur = conn.cursor()
# SQL 쿼리 실행
cur.execute("select type,def,v... |
#!/usr/bin/env python3
# -*-coding:utf-8 -*-
# __author__:Jonathan
# email:nining1314@gmail.com
from django.conf.urls import url
from asset import views
urlpatterns = [
url(r'report/asset_with_no_asset_id/$', views.asset_with_no_asset_id),
url(r'dashboard/$', views.dashboard),
url(r'events_list/$', views.... |
"""
A `Memoizer` can be used as a factory for creating objects of a certain class.
It exposes a constructor and 2 methods
* `memoizer = Memoizer(SomeClass)`
* `memoizer.get(*args, **kwargs)`
* If `memoizer` has never seen the given arguments, it creates `SomeClass(*args, **kwargs)` and returns it.
* If `memoiz... |
from Products.Five import zcml
from Products.Five import fiveconfigure
from Testing import ZopeTestCase as ztc
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import onsetup
@onsetup
def setup_pakki_policy():
"""Set up additional products required for the Pakki site policy... |
# coding: utf-8
# ## Теория вероятностей и математическая статистика
#
# ## Задание №1
# #### Основные понятия математической статистики. Вариационный ряд. Эмпирическая функция распределения.
#
# In[167]:
import matplotlib.pyplot as plt
import numpy as np
import math
import random
import pandas as pd
def gen(n... |
#!/usr/bin/env python
#integer
i1 = 100
i2 = 0x100
i3 = 0b100
i4 = 0o100
#floats
f1= 1234312.12
f2= .34
f3= 1.23e18
#integers can be as big as necessary
x=22
y=5
print(x + y)
print(x * y)
print(x - y)
print(x / y)
print(x // y)
print(x ** y)
print(x % y)
a=5
b=0
try:
result = a/b
except ZeroDivisionError as ... |
from data import get_data
from common import get_path
class GetParams:
def getparams(self,api_id):
path = get_path.get_api()
casedate1 = get_data.ExcelData().openexl(path, 'Sheet2')
casedate = []
for index, value in enumerate(casedate1):
# print(index,value)
... |
###############################################################################
##
## Copyright (C) 2011-2014 Tavendo GmbH
##
## 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
##
#... |
#!/usr/bin/python
import sys
for line in sys.stdin:
line = line.strip().split('\t')
val1 = line[6].split(' ')
Word1 = val1[0]
Word2 = val1[1]
Word3 = val1[2]
val2 = '~'.join([Word3,Word2,Word1])
line[6] = val2
print '\t'.join([line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7],line[8]])... |
import numpy as np
import matplotlib.pyplot as plt
ang2bohr = (1.e-10)/(5.291772106712e-11)
coords_initial_min = np.array([[0.000000000000000, 0.000000000000000, 0.000000000000000],
[0.1318851447521099, 2.088940054609643, 0.000000000000000],
[1.786540362044548, -1.386051328559878, ... |
import os
import glob
import re
# Simple script to rename files. This was used to fix file names before a convention was decided upon.
# base_path = r"C:\Users\setup\Documents\VR_files"
base_path = r"J:\Drago Guggiana Nilo\Prey_capture\VRExperiment"
all_files = [f for f in os.listdir(base_path) if os.path.isfile(os.... |
'''
Write a script prints the number of times a vowel is used in a user inputted string.
'''
string_input = input("Please enter a string: ")
vowels = ["a", "e", "i", "o", "u"]
count = 0
for letter in string_input:
if letter in vowels:
count += 1
print(count) |
from gpiozero import MotionSensor as motion
import time
import sys
import os
pir = motion(10)
while True:
if pir.motion_detected:
print("Motion")
os.system("fswebcam 720x650 USERS/access0/today.jpg")
time.sleep(5)
sys.exit(0)
else:
print("... |
from flask import Flask, request, render_template, url_for, redirect
import os
import sqlite3
dir = os.path.dirname(__file__)
filename = os.path.join(dir, "flask_dojo.db")
app = Flask(__name__)
@app.route("/")
def main():
return "Check this out!"
@app.route("/counter", methods=["GET", "POST"])
def counter():
... |
# Importing libraries and files being refered here
import media
import fresh_tomatoes
# Initialising instances of movie class
Lion_King = media.Movie(
"The Lion King",
"Naive cub and lion prince Simba is made to believe that he killed his"
" father, which is why he flees into exile. After several years, Si... |
#Python内建的filter()函数用于过滤序列。
#和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
#例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
#把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return ... |
import numpy as np
import matplotlib.pyplot as plt
import xarray as xr
import scipy as sp
import pandas as pd
import Denmark_Strait.src.ssa_core as ssa
import Denmark_Strait.src.spectra_and_wavelet_functions as sw
import pycwt as wavelet
from pyspec import helmholtz as helm
from pyspec import spectrum as spec
impor... |
from __future__ import unicode_literals
from django.db import models
class Station(models.Model):
name = models.CharField(max_length=255)
location_lat = models.FloatField(default=0)
location_lng = models.FloatField(default=0)
address = models.TextField(max_length=255)
|
# Author:Winnie Hu
"""面向对象介绍
世间万物,皆可分类:人类、动物、植物、食品、电子设备、文具等等都属于一类。
世间万物,皆为对象:人类在某一人,你家的猫,冰箱的可乐,你的手机就是具体的对象
只要是对象,就肯定属于某种品类
只要是对象,就肯定有属性"""
"""面向对象编程
OOP编程是利用“类”和“对象”来创建各种模型来实现对真实世界的描述,
使用面向对象编程的原因一方面是因为它可以使程序的维护和扩展变得更简单,
并且可以大大提高程序开发效率 ,另外,基于面向对象的程序可以使它人更加容易理解你的代码逻辑,
从而使团队开发变得更从容。
/////面向对象的几个核心特性如下//////
1、class类... |
# Generated by Django 2.0.9 on 2019-09-27 15:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('census', '0029_auto_20190926_2034'),
]
operations = [
migrations.RenameField(
model_name='basecopy',
old_name='rasmussen_wes... |
def print_var_type(var1: str, var2: str, var3: str) -> None:
print('Типы переменных. {}:{}, {}:{}, {}:{}'.format(var1, type(var1), var2, type(var2), var3, type(var3)))
str_dev = 'разработка'
str_socket = 'сокет'
str_decorator = 'декоратор'
print_var_type(str_dev, str_socket, str_decorator)
str_dev = 'р... |
quar = int(input("How many quarters do you have?"))
dime = int(input("How many dimes?"))
nick = int(input("Nickels?"))
penn = int(input("And finally pennies?"))
total = (quar*0.25)+(dime*0.1)+(nick*0.05)+(penn*0.01)
doll = int(total*100)//100
cent = int(total*100)%100
print("This is the total money you have:", doll,... |
# -*- coding: utf-8 -*-
import mne
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator)
subjects = ['erica_peterson']
raw_files = ['%s_emojis_raw.fif']
data_dir = '/media/erica/Rocstor/genz'
ecg_ch = 'ECG001'
for subject in subjects:
for file in ... |
import pandas as pd
import nltk
from nltk.corpus import stopwords
import string
import re
from string import digits
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
data = pd.read_csv('clean_data.csv')
texts = data['text'].astype(str)
y = data['is_offensive']
cleaned_text=[]
# table... |
import os
import xml.etree.ElementTree as ET
import numpy as np
import cv2
import pickle
import copy
import settings
"""
#for kitti class
import pykitti
import tracklet
from tracklet import Tracklet
"""
class VOC:
def __init__(self, phase):
if settings.dataType == 0 :
self.data_path = '/hom... |
from PyQt4 import QtCore, QtGui
from Ui.listOfEmployee import Ui_Dialog
from Ui.empList import Ui_EmpList
from allInfo import EmployeeAllInformation
#from payAdvancePayment import PayAdvanceAmount
class EmployeeList(QtGui.QDialog):
def __init__(self,query,parent = None):
QtGui.QDialog.__init__(self,parent)... |
import gevent
_UNSET = object()
class BufferedSocket(object):
def __init__(self, sock, timeout=10, maxbytes=32 * 1024):
self.sock = sock
self.sock.settimeout(None)
self.rbuf = ""
self.sbuf = []
self.timeout = timeout
self.maxbytes = maxbytes
def settimeout(se... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen as req
import re
import time
from itertools import *
import unicodecsv as csv
from datetime import date
... |
from flask import Flask, render_template
import startgame, random
create_cards = list()
def create_app():
app = Flask(__name__)
@app.route('/')
def start_game():
global create_cards
create_cards = startgame.card_info()
game = startgame.hide_cards(create_cards)
return rende... |
import dilap.core.tools as dpr
import dilap.core.vector as dpv
import dilap.structures.structure as dst
import dilap.mesh.tools as dtl
import matplotlib.pyplot as plt
class house(dst.structure):
def __init__(self,*args,**kwargs):
dst.structure.__init__(self,*args,**kwargs)
self._def('l',20,**kwar... |
# Generated by Django 2.2 on 2020-08-24 16:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Categoria',
fields=[
... |
class Tableau(object):
def __init__(self):
self.isEmpty = True
self.tableau_stack = []
def add_card(self, the_card):
self.tableau_stack.insert(0, the_card)
def get_length(self):
return len(self.tableau_stack)
def isnt_empty(self):
if len(self.tableau_stack) ... |
from pyvex.const import get_type_size
from .... import sim_options as o
from .. import ccall
from ....errors import SimCCallError, UnsupportedCCallError
import logging
l = logging.getLogger(name=__name__)
def SimIRExpr_CCall(engine, state, expr):
if o.DO_CCALLS not in state.options:
return state.solver.U... |
a = int(input())
b = int(input())
try:
print(a / b)
except ZeroDivisionError:
print('The Error!')
|
import optparse
import boto3
import botocore
import rds_handler
from app import config
conf = config.configuration
suffix = config.suffix
def __get_comma_separated_args(option, opt, value, parser):
setattr(parser.values, option.dest, value.split(','))
def get_options():
parser = optparse.OptionParser()
... |
def right(least, middle, max):
if least**2 + middle**2 == max**2:
return "right"
else:
return "wrong"
while 1:
num_list = list(map(int, input().split()))
num_list.sort()
if num_list.count(0)==3:
break
print(right(*num_list))
|
import sys
# configure and settings
from .config_utils import Configurable
# dynamic loader
from .dynamic_utils import *
# io utils
from .io_utils import *
# pytorch helper
try:
from .torchhelper import *
except:
print('no PyTorch installed, ignore torchhelper')
# keras helper
try:
from .keras_runner i... |
#!/usr/bin/env python3
#coding=utf-8
import aioredis
async def msghandler(msg):
pass
# This serves further purpose on redis cache for individual customization |
#
# Spherical shell bins are not as smooth as I'd like.
# Horse around.
#
plt.close('all')
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(1,1,1)
ax.set_aspect('equal')
left=nar([0.,0.,0.])
right=nar([1.,1.,1.])
N = nar([32,32,32])
dx = (right-left)/N
for ix in range(N[0]+1):
ax.plot( [ix*dx[0], ix*dx[0]], ... |
from getpaid.core.options import PersistentOptions
import interfaces
LuottokuntaOptions = PersistentOptions.wire("Luottokunta",
"getpaid.luottokunta",
interfaces.ILuottokuntaOptions )
|
#_*_ coding: utf-8_*_
import numpy
import matplotlib
import operator
from math import log
#给定一个集合,计算该集合的信息熵(信息的杂乱程度)
def calShannonEntropy(dataSet):
numberOfEntry = len(dataSet)
labelCount = {}
for item in dataSet:
currentLabel = item[-1]
if currentLabel not in labelCount.keys():
... |
"""Class for BRATS 2017 patch extraction."""
import os
import numpy as np
import cv2
import time
from scipy.ndimage import interpolation
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import sys
class PatchExtractorISLES(object):
"""Class for ISLES 2017 patch extraction."""
"""
Attribute... |
#!/usr/bin/env python3
import sys
def main():
if len(sys.argv) < 3:
print("HIBA! Nem adott meg megfelelő számú argumentumot!")
print("Kérem adjon meg két számot argumentumként.")
final = int(sys.argv[1]) + int(sys.argv[2])
print("A két szám összege:", final)
if __name__ == "__main__":
... |
#!/usr/bin/python
import nltk.corpus.reader.wordnet, sys
if len(sys.argv) != 3:
sys.exit("usage: leastcommonhypen WORD1.POS.SENSENUM WORD2.POS.SENSENUM")
print 'loading wordnet'
wn = nltk.corpus.reader.wordnet.WordNetCorpusReader(nltk.data.find('corpora/wordnet'))
print 'done loading'
S = wn.synset
L = wn.lemma
#... |
# 3. Receba a base e a altura de um triângulo. Calcule e mostre a sua área.
def calculaAreaT():
try:
b = int(input("Digite a base do triângulo: "))
h = int(input("Digite a altura do triângulo: "))
result = (b*h)/2
print("Resultado: ", result)
except ValueError:
print("D... |
import imutils
import dlib
import cv2
import os
import numpy as np
import lib.utils.models.models as models
import lib.utils.encodings.encodings as codes
import lib.utils.faces as face
import lib.utils.objects as obj
from imutils.video import VideoStream
import time
from PIL import Image
import tensorflow as tf
defau... |
from django.conf.urls import url
from .views import HomeView
from tastypie.api import Api
# Normal Url
urlpatterns = [
url(r'^$', HomeView.as_view(), name='common-home'),
# url(r'attorney/$', AttorneyListView.as_view(), name='attorney-list'),
# url(r'^attorney/(?P<slug>[-_\w]+)/$', AttorneyDetailView.as_v... |
from django.test import TestCase
from django.contrib.webdesign import lorem_ipsum
import random
from datetime import timedelta, datetime
from pactpatient.models import PactPatient
from patient.models import Patient, DuplicateIdentifierException
import settings
class basicPatientTest(TestCase):
def setUp(self):
... |
'''
This script creates a table of positive face expression from the videos
'''
import os
import numpy as np
import pandas as pd
import Python.Data_Preprocessing.config.config as cfg
def compute_posiface(video_name_1, video_name_2, parallel_run_settings):
'''
Compute for posiface status of the talkturn
... |
'''''''''
Project: Digit recognition using sigmoid neural network using MNIST data from SCRATCH!
AMIT KUMAR
IIT(ISM) Dhanbad
CSE(B.tech)
'''''''''
import NeuralNetwork
import LoadData
training_data, validation_data, test_data = LoadData.ProcessData()
neuron = NeuralNetwork.SigmoidNeuralNetwork([784, 30, 10])
neuron.M... |
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
urlpatterns = [
path("profile", views.profile, name="user-profile"),
path("register", views.register, name="register-user"),
path(
"login",
auth_views.LoginView.as_view(template_name="accou... |
def solve(i, d):
C, I, prices = d
C = int(C)
prices = list(map(int, prices.split()))
for p1, P1 in enumerate(prices[:-1]):
remains = C-P1
left = prices[p1+1:]
if remains in left:
result = [p1+1, p1+left.index(remains)+2]
return i, ' '.join(map(str... |
#!/usr/bin/env python
#coding:utf-8
from socket import gethostbyname
DOMAIN= "yuming.txt"
with open(DOMAIN,'r') as f:
for line in f.readlines():
try:
host = gethostbyname(line.strip('\n')) #域名反解析得到的IP
except Exception as e:
with open('error.txt','a+') as ERR: #error.tx... |
import sys
import os.path
import string
import struct
import getopt
import tempfile
from subprocess import *
import os
from PIL import Image
import binascii
import numpy as np
## Helper Function
def print_help():
print("Usage: "+os.path.basename(filedir)+" filein.bnt [fileout.abs]")
sys.exit()... |
import os
import json
from elasticsearch import Elasticsearch
import logging
logger = logging.getLogger('management.commands')
from django.conf import settings
from ebisc.celllines.models import Cellline
'''ORM to ElasticSearch importer.'''
BASEDIR = os.path.join(os.path.dirname(__file__), '../elastic/')
MAPPING... |
from django.shortcuts import render
from layout.forms import StartForm
def index(request):
default_name = request.session.get('last_layout', 'DEFAULT')
form = StartForm(initial={'layout': default_name})
return render(request, 'view/index.html', {'form': form})
|
# enumerate all possible combinations of four 4
from itertools import permutations
def evaluate(equation):
#print(equation)
stack = []
postfix = []
for i in range(len(equation)):
if equation[i] == 4:
postfix.append(equation[i])
elif equation[i] == '+' or equation[i] == '-':
... |
firstNumber = input("Give a number: ")
firstNumber = int(firstNumber)
secondNumber = input("Give another number: ")
secondNumber = int(secondNumber)
firstEven = firstNumber % 2
firstEven = int(firstEven)
secondEven = secondNumber % 2
secondEven = int(secondEven)
if (firstEven == 0) and (secondEven == 0):
print("... |
:qage=input(int("Please enter your age"))
f1=0
f2=1
sum=1
while (f2<=age)
sum=sum+f2
temp=f1+f2
f1=f2
f2=temp
print (temp)
print (sum)
|
import logging
from typing import Optional
from asyncio import ensure_future
from discord.ext.commands import Cog, command
from ... import exceptions
from ...rich_guild import get_guild
from ... import messagemanager
from ...playback import PlayerState
log = logging.getLogger(__name__)
class Playback(Cog):
@co... |
"""empty message
Revision ID: 54a2d38c2077
Revises: 2a6adb4515be
Create Date: 2015-01-22 13:11:40.423243
"""
# revision identifiers, used by Alembic.
revision = '54a2d38c2077'
down_revision = '2a6adb4515be'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.Index),
path('login',views.PageLogin),
path('login/',views.Login),
path('logout/',views.Logout),
path('upload',views.Upload)
] |
import RE_Crowdfunding
import Utilities
import CrowdStreet
import CrowdStreet_TestPage
import RealtyShares
import browse
import time
import Input_Output
import airtable
import pprint
if __name__ == "__main__":
print('================================')
print('Starting Analayis')
print('===========================... |
import json
import logging
from typing import Optional, Tuple
from urllib.parse import urlparse
import boto3
import requests
import time
from flask import Blueprint, Request, Response, render_template, render_template_string, request, url_for
from itertools import islice
from overtrack_models.dataclasses.apex.apex_gam... |
# For GMail or Google Apps
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'mianamirlahore@gmail.com'
EMAIL_HOST_PASSWORD = 'choosebesttobethebest2019'
EMAIL_POST = 587
|
from .names import names_page
from .tags import tags_page
from .users import users_page
from .models import models_page
from .components import components_page
from .sims import sims_page
|
#!/usr/bin/env python
# coding: utf-8
# In[289]:
# Run first time only
import re
import ast
import csv
import nltk
import warnings
import numpy as np
import pandas as pd
from ast import literal_eval
from textblob import TextBlob
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from nltk.corpus import... |
import unittest
from mlc_tools.base.model import Model
from mlc_tools.core.class_ import Class
class TestModel(unittest.TestCase):
def setUp(self):
self.model = Model()
def test_empty_copy(self):
new_model = self.model.empty_copy()
self.assertNotEqual(id(new_model), id(self.model))
... |
from django.contrib import admin
from .models import cust_details
admin.site.register(cust_details)
# Register your models here.
|
import argparse
from unittest import TestCase
from soltrannet import _run
import io
class TestCommandLine(TestCase):
def test_command_line(self):
with io.StringIO() as buf:
correct='c1ccccc1,-1.053,\nc1ccccc1 .ignore,-1.053,\nCn1cnc2n(C)c(=O)n(C)c(=O)c12,-1.132,\n[Zn+2],-6.882,Other-typed Atom(... |
import logging
from multiprocessing_logging import install_mp_handler
mp_logging_enabled = False
def get_logger(name="django_elastic_migrations"):
real_logger = logging.getLogger(name)
for level in ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']:
setattr(real_logger, level, getattr(logging, level)... |
import yaml
from google.appengine.ext import ndb
from webapp2_extras import security
from webapp2_extras.appengine.auth.models import User as WebApp2User
class User(WebApp2User):
"""
Subclass of the WebApp2 User class to add functionality.
The WebApp2User class is an expando model, so the User
class i... |
#######################################################
# Bucky_33_Classes and Self
#######################################################
# We can create functions inside of the class
# Those functions are METHODS
# Every parameter in the class should take 'self' and # any other parameters
#------------------------... |
from Core.Globals import *
class event(object):
def __getattr__(self, attr):
if not attr.endswith('Event'):
return object.__getattribute__(self, attr)
def f(*args):
return getattr(game().event, attr), args
return f
E = event()
class Mapping(object):
def __getattribute__... |
import requests
from bs4 import BeautifulSoup
def get_html(url):
html = requests.get(url)
html.raise_for_status
html.encoding = 'gbk'
return html.text
def get_content(url):
content = get_html(url)
soup = BeautifulSoup(content,'lxml')
movies_list = soup.find('ul', class_='picL... |
import re
from collections import namedtuple
from lxml import etree
from twisted.internet import defer
import structlog
logger = structlog.get_logger()
ARPEntry = namedtuple('ARPEntry',
['ip', 'type', 'flags', 'mac', 'mask', 'device'])
def load_arp_table():
with open('/proc/net/arp', 'r'... |
# stdlib
from typing import Any
from typing import Dict
# syft absolute
import syft as sy
from syft import serialize
from syft.core.io.address import Address
from syft.grid.messages.group_messages import CreateGroupMessage
from syft.grid.messages.group_messages import CreateGroupResponse
from syft.grid.messages.group_... |
# cf. https://gist.github.com/ageitgey/82d0ea0fdb56dc93cb9b716e7ceb364b
# https://github.com/kairess/face_detector/blob/master/main.py
import dlib
import cv2
import sys
import numpy as np
import openface
predictor_model = "shape_predictor_68_face_landmarks.dat"
face_detector = dlib.get_frontal_face_detector()
face_p... |
def fib():
a, b = 1, 2
while True:
yield a
a, b = b, a + b
def even(seq):
for number in seq:
if not number % 2:
yield number
def under_million(seq):
for number in seq:
if number > 4000000:
break
yield number
print(sum(under_million(even(... |
# /* encoding: utf-8 */
# Copyright Altaire bot © Assassin, 2011 - 2012
# This program published under Apache 2.0 license
# See LICENSE for more details
# My EMail: assassin@sonikelf.ru
# sh package for Altaire XMPP bot
def command_sh(source, parameters):
if parameters.strip():
<<<<<<< HEAD
result = popen(parameter... |
import json
import threading
import urllib.parse as urlparse
from datetime import datetime, timedelta
from random import randint, randrange
from urllib.parse import urlencode
import names
import pandas as pd
import requests
import shortuuid
def random_date():
"""
This function will return a random datetime b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.