text stringlengths 38 1.54M |
|---|
# Generated by Django 3.0 on 2020-11-07 18:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(au... |
# Union Find: Union and find techniques are not just for graph.
# They aim to build an array indicating the parent of each element.
# When find, do path compression. When union, do union by rank
# Python Program for union-find algorithm to detect cycle in a undirected graph
# we have one egde for any two vertex i.e ... |
# Generated by Django 3.1.7 on 2021-07-08 01:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0007_auto_20210703_1138'),
]
operations = [
migrations.RemoveField(
model_name='file',
... |
class Solution(object):
def canPartition(self, nums):
def canReachSum(nums,S):
sums = set([S])
for i in range(len(nums)):
tmp=set()
#print sums
for s in sums:
nv = s-nums[i]
if nv < 0: continue
... |
import turtle as t
def ract(hor,ver,col):
t.pendown()
t.pensize()
t.color(col)
t.begin_fill()
for i in range(1,3):
t.forward(hor)
t.right(90)
t.forward(ver)
t.right(90)
t.end_fill()
t.penup()
t.penup()
t.speed(1000)
t.bgcolor("blue")
t.go... |
## Without filtering results with VIF, calculate the importance for all the features.
## Works for "first" and "structcoef"
from util_relaimpo import *
from util import loadNpy, loadCsv
def main(x_name, y_name, method, feature_names = []):
# INFO
print("Dataset", x_name.split('_')[0])
print("Method", str(m... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn im... |
from Buildings.material import DIRT, BRICKS, WATER, AIR, FENCE, TORCH
fountain = {
"height": -1,
"building": [
[
[DIRT, DIRT, DIRT, DIRT, DIRT, DIRT],
[DIRT, BRICKS["STONE"], BRICKS["STONE"], BRICKS["STONE"], BRICKS["STONE"], DIRT],
[DIRT, BRICKS["STONE"], WATER, WAT... |
'''
column_types()
Returns pandas dataframe column names, column object pandas dtypes and column python data types
The `dtype` results from `pandas.Dataframe.info()` are outputs from `pandas.DataFrame.dtypes()` method.
The `dtypes()` method does not differentiate between st... |
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
""" Tạo c... |
import pytest
from datetime import timedelta, datetime
from tensorhive.models.Reservation import Reservation
def test_reservation_creation(tables, new_reservation):
new_reservation.save()
def test_interfering_reservation_cannot_be_saved(tables, new_reservation, new_reservation_2):
# Create initial record
... |
"""
This code is intended to start up and safely shut down an RPI with a single-throw switch.
The ST switch is wired to a GPIO of ESP8266 which is pulled up (high).
When switching on, the GPIO goes low, which triggers 'on_press' function - activate the SSR and turn on the LED.
When switching off, the GPIO goes back to ... |
from wtforms import StringField, IntegerField, FloatField, Field, SelectField,ValidationError, FieldList, FormField
from wtforms.validators import DataRequired, length, Email, Regexp, EqualTo
from app.libs.enums import ClientTypeEnum
from app.models.user import User
from app.validators.base import BaseForm as Form
... |
#!/usr/bin/env python3
"""__init__ pycircuit file"""
__all__ = ["bit", "bitvector", "pin", "ic"]
|
from src.API.blueprints.functions import byRecentDay, byRecentWeek, byTimeperiod, byDate, byRecentYear, byRecentMonth
from flask import Blueprint
airtemp = Blueprint('airtemp', __name__)
value = "temperature_float"
type = "airtemp"
@airtemp.route('/solapi/airtemp/recent/day')
def airTempDay():
return byRecentD... |
from django.conf.urls import re_path
from .views import *
urlpatterns = [
re_path('contact/', ContactView.as_view(), name='contact'),
re_path('success/', Success.as_view(), name='success'),
# News Letter
#re_path('', newsletter_signup, name='newsletter_signup'),
#re_path(r'^unsubscription/', newsle... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from niveristand._decorators import nivs_rt_sequence, NivsParam
from niveristand.realtimesequencetools import run_py_as_rtseq, save_py_as_rtseq
__all__ = ["NivsParam",
... |
class ChannelsDb():
def __init__(self, collection):
self.collection = collection
def add(self, object):
if self.collection.find_one({"_id": object._id}) is None:
self.collection.insert_one(object.__dict__)
print(f"Канал '{object.title}' добавлен в БД")
else:
... |
species(
label = 'C7H9(408)(407)',
structure = SMILES('[CH]1CC=CC=CC1'),
E0 = (267.309,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,2900,2950,3000,3050,3100,3150,900,925,950,975,1000,1025,1050,1075,1100,300,800,800,800,800,800,800,800,800,800,800,800,1600,1600,1600,1600,1... |
# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.header import Header
import time
start_time = time.time()
import re
import requests
import pandas as pd
##############打印昨天####################
import d... |
import pygame
import random
import math
#initializing pygame
pygame.init()
#initializing values
player = 1
level = 1
x = 0
boat_index = 0
lost = None
winners = []
count = 0
player1 = 0
player2 = 0
draw = 0
timer_started = False
timer_started1 = False
clock = pygame.time.Clock()
#initializing fonts
font = pygame.f... |
# _*_ coding:utf-8 _*_
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from twi.com.utility import plot_decision_regions
from sklearn.metrics import accuracy_score
from twi.anns.ann_bp_multi im... |
import math
import os
from collections import Counter
from nltk.tokenize import RegexpTokenizer
from nltk import StanfordNERTagger
import ethnicolr
import pandas as pd
import gender_guesser.detector as gender
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
data_path = os.path.join(BASE_PATH, 'data')
class Use... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 16:54:18 2019
@author: jbhud
"""
#load list of states from before midterm
import pickle
home="C:/Users/jbhud/Documents/Thesis/Thesis Code/"
#
naturalStates = []
with open(home+"1. Simulation/listNatStates.txt", "r") as f:
for row in f:
naturalStates = natu... |
palabra = input("Ingrese una palabra: ")
while(palabra != "FIN"):
if(palabra[0] == palabra[-1]):
print("Empieza y termina con la misma letra")
palabra = input("Ingrese una palabra: ")
|
#람다 함수
"""
def plus_one(x):
return x+1
print(plus_one(1))
#람다 함수 사용 이유
plus_two=lambda x: x+2
print(plus_two(1))
"""
#map 함수 -> map(함수명,자료형)
def plus_one(x):
return x+1
a=[1,2,3]
print(list(map(plus_one,a)))
print(list(map(lambda x : x+1 ,a)))
#모든 변수가 해당 함수의 영향을 받을 수 있다. !
|
from primitives import ListNode
__author__ = 'V Manikantan'
documentation = '''
DETAILS OF THE METHODS:
1) Push adds new value to queue at rear
2) Pop removes a value from queue at front if it exists, otherwise returns empty queue.
3) Front returns the front value of queue and Rear returns the rear value of quqeu... |
import sys
import os
sys.path.insert(0, "./lib")
from pypodio2 import api
import boto3
def handler(event, context):
client_id = os.environ['client_id']
client_secret = os.environ['client_secret']
s_app_id = int(os.environ['s_app_id']) # Staffing app
s_app_token = os.environ['s_app_token'] ... |
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import qgis.utils
import psycopg2
from PyQt4.QtCore import QSettings
import os
import re
import sys
import csv
import resources
import interface_menu
from interface_menu import *
from interface_f... |
#! /usr/bin/python
import argparse
from datetime import datetime
import time
import os
import json
from live_update_server.utils import NonRepeatingLogger
from live_update_server.googlesheet import GoogleSheetReader
# TODO decide better file naming for the following three
from live_update_server.roomdataparser import... |
import matplotlib.pyplot as plt
import statistics as stat
import time
import operator
import copy
import sys
def file_to_x_y(filename):
x_y = []
x_cord = []
y_cord = []
try:
file = open(filename, 'r')
no_of_points = int(file.readline())
for i in file:
i = i.split()
i[1] = int(i[1])
i[2] = int(i[2])
... |
from django.db import models
class Usermodel(models.Model):
username = models.CharField(max_length=32, unique=True) #名称
password = models.CharField(max_length=256)#密码
email = models.CharField(max_length=64, unique=True)#邮箱
sex = models.BooleanField(default=False) #性别
icon = models.ImageField(upload... |
#Quick n' dirty day 1
file = open('sortedInput.txt', 'r')
content = file.read().split()
lower, upper = list(map(int, content[:9])), list(map(int, content[9:])) # 2020 cant be the sum of two integers where x>1010 OR x<1010 is true for BOTH
li = ui = 0 # so for efficencys sake only compare integers where it's pos... |
# Copyright (c) 2016 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
#!/usr/bin/python2
import commands as c
import os
while True:
try:
os.system("Xdialog --title 'FTP server Configuration' --cancel-label 'back' --menubox '' 15 50 5 1 configure 2 activate 3 deactivate 4 Status 5 Uninstall 2>.temp")
ch=int(c.getoutput("cat .temp|head -1"))
except:
os.system("rm -f .temp")
... |
"""
Class Potential
This class performs calculations on arbitrary potentials.
Public Functions:
minimize : Minimize a generic potential
TODO: Complete this
"""
# Required Modules
import numpy
import sympy as sy
from sympy.matrices import hessian
from sympy.solvers import solve
# Currently Unused
from scipy.o... |
import random
import torch
import numpy as np
global RANDOM_SEED
RANDOM_SEED = None
def set_random_seed(seed=None):
global RANDOM_SEED
changed = False
if RANDOM_SEED is None:
RANDOM_SEED = random.randint(1, 10000)
changed = True
if seed is not None:
RANDOM_SEED = seed
... |
for t in range(int(input())):
l=list(input().split());s=[];c=1
for i in range(len(l)-1):
if l[i].isdigit():s.append(l[i])
else:
try:
a,b=int(s.pop()),int(s.pop())
if l[i]=='+':r=b+a
elif l[i]=='-':r=b-a
elif l[i]=='/':... |
"""
Pabuito Auto Script
3DF History Deleted
This script contains a auto script for the Pabuito Grade Tool. This tool searches for history on a single expected mesh.
!!!
All scripts need to create a progress bar and print status to stdout
!!!
All auto scripts need to return the grade information in the form of a dic... |
#===========================================================================
# iterate through a list using indexing
#===========================================================================
Titans = ['Apple', 'Alphabet', 'Microsoft']
# Iterate through the list using the index
for i in range(len(Titans)):
print... |
import collections
def slidingWindow(s: str, t: str):
need = collections.defaultdict(int)
window = collections.defaultdict(int)
for ch in s:
need[ch] += 1
left, right = 0, 0
valid = 0
while(right < len(s)):
# c是将移入窗口的字符
c = s[right]
# 右移窗口
... |
#!/usr/bin/python
# coding=utf-8
import numpy as np
class BaseLoss(object):
def __init__(self, lamb=0.0):
self.lamb = lamb
def grad(self, preds, labels):
raise NotImplementedError()
def hess(self, preds, labels):
raise NotImplementedError()
class SquareLoss(BaseLoss):
... |
import unittest
from mirror.visualisations.core import Visualisation
from mirror.visualisations.web import WebInterface
from functools import partial
class ModuleTracerTest(unittest.TestCase):
def test(self):
class TestVisualisation(Visualisation):
def __call__(self, inputs, layer, something=... |
class Employee:
raise_amount=1.04
def apply_raise(self):
self.pay=self.pay*self.raise_amount
def __init__(self,name,pay):
self.name=name
self.pay=pay
emp_1=Employee('Corey',50000)
emp_2=Employee('John',40000)
emp_1.raise_amount=1.03
Employee.raise_amount=1.02
print(emp_1.raise_amo... |
import random
guess=str(random.randint(100,1001))
while True:
inp = input('Enter any three digits: ')
if len(inp) != 3:
print('Number entered is not three digits, Please try again!')
continue
if guess[0] == inp[0] or guess[1] == inp[1] or guess[2] == inp[2]:
print('Match')
else:
... |
import FWCore.ParameterSet.Config as cms
# Center-of-mass energy 10 TeV
herwigppEnergySettingsBlock = cms.PSet(
hwpp_cm_10TeV = cms.vstring(
'set /Herwig/Generators/LHCGenerator:EventHandler:LuminosityFunction:Energy 10000.0',
'set /Herwig/Shower/Evolver:IntrinsicPtGaussian 2.1*GeV',
),
)
|
import sys
def input():
return sys.stdin.readline()[:-1]
n=int(input())
li=[[0]*10 for i in range(10)]
for i in range(n):
tmp=str(i+1)
li[int(tmp[0])][int(tmp[-1])]+=1
# print(li)
ans=0
for i in range(10):
for j in range(10):
ans+=li[i][j]*li[j][i]
print(ans) |
import random
from Classes.enemy import Enemy
enemy1 = Enemy(200, 60)
print(enemy1.getHp())
'''
playerhp = 400
enemyatkL = 60
enemyatkH = 100
while playerhp > 0:
dmg = random.randrange(enemyatkL,enemyatkH)
playerhp -= dmg
if playerhp <= 30:
playerhp = 30
print('Player is attacked for', d... |
import cv2
import numpy as np
img = cv2.imread("images/shapes oki.jpg", 0)
img = cv2.resize(img, (800, 600))
# cv2.imshow("org", img)
ret, thr = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('thresh', thr)
cv2.imwrite("thr.jpg", thr)
kernel = np.ones((7, 7), np.uint8)
opening = cv2.morphologyEx(thr, c... |
from ray.dag.dag_node import DAGNode
from ray.dag.function_node import FunctionNode
from ray.dag.class_node import ClassNode, ClassMethodNode
from ray.dag.input_node import (
InputNode,
InputAttributeNode,
DAGInputData,
)
from ray.dag.constants import (
PARENT_CLASS_NODE_KEY,
PREV_CLASS_METHOD_CALL_... |
from quark_runtime import *
import quark.reflect
class pkg_C_event1_Method(quark.reflect.Method):
def _init(self):
quark.reflect.Method._init(self)
def __init__(self):
super(pkg_C_event1_Method, self).__init__(u"quark.void", u"event1", _List([]));
def invoke(self, object, args):
... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
-------------------
begin : 06.07.2021
git sha : :%H$
copyright : (C) 2021 by Dave Signer
email : d... |
# Generated by Django 3.0.6 on 2020-05-24 13:55
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrati... |
##############################################
# Project: Microwave Filter Tuner
# File: OpenCV.py
# Date: January 18, 2020
# Programmer(s): Braden Massé and Matthew Rostad
# Sub-Systems: Visual Identification Sub-System
# Version: 1.2
##############################################
# Import Libraries #
import numpy as... |
from board import Board
from snake import Snake
from snakes.codesnake import CodeSnake
from multiprocessing import Pool
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import time
import pymongo
from pprint import pprint
app = Flask(__name__)
app.config['SECRET_KEY'] = '... |
from stem import Signal
from stem import CircStatus
from stem.control import Controller
import threading
import os
import urllib2
headers ={'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0', 'Accept-Encoding' : 'gzip, deflate', 'Accept' :'text/html,application/xhtml+xml,a... |
# coding=utf-8
import grpc
import os
from fastapi import FastAPI
from pydantic import BaseModel
import _pickle as pickle
import tensorflow as tf
from spacy.tokens import Span
from spacy.lang.fr import French
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
... |
#!/usr/bin/env python3
import struct
from glob import glob
from functools import partial
from multiprocessing import cpu_count, Pool
import sys
import os
from os.path import dirname, basename, join as p_join
import scipy
import numpy as np
import librosa
def getDtype(inputformat):
if inputformat == 0:
re... |
import get_db_connection
connection = get_db_connection.getConnection()
print("Connect successful!")
sql_select = "SELECT * FROM test"
sql_insert = "INSERT INTO test (text)" \
+ " VALUES (%s)"
try:
# объект для работы с БД
cursor = connection.cursor()
cursor.execute(sql_select)
print("... |
from datetime import datetime
from django.conf import settings
from django.urls import reverse
from telegram import Update
from bot.common import send_telegram_message, ADMIN_CHAT, remove_action_buttons
from notifications.email.users import send_welcome_drink, send_rejected_email
from notifications.telegram.posts imp... |
from elasticsearch import Elasticsearch
import os
import json
from wikidata.config_path import WIKIDATA5M_DOCTITLE_ENTITY_DIR
"""
Build elastic search index of the wikipedia titles corresponding to the titles in WIKIPEDIA_CHUNKS_FILE (psgs_100w.tsv) to the wikidata entities.
Some of these wikidata entities may not... |
import matplotlib as mpl
import numpy as np
import pandas as pd
import scipy.cluster.hierarchy as hac
from matplotlib import pyplot as plt
import vishelper as vh
mpl_update = {'font.size': 14, 'figure.figsize': [12.0, 8.0],
'axes.labelsize': 20, 'axes.labelcolor': '#677385',
'axes.titlesiz... |
def top_words(textsample,lang='english'):
from sklearn.feature_extraction.text import CountVectorizer
if lang == 'english':
vectorizer = CountVectorizer(stop_words=lang,lowercase=True)
if lang == 'spanish':
from nltk.corpus import stopwords
spanish_stopwords = stopwords.words('spani... |
import android
import time
import math
global dist
dist=0
droid=android.Android()
def main():
r = droid.dialogGetInput("ATENCAO","Indique o raio de seguranca (m):","50")
raio_seguro = float(r.result)
print raio_seguro
coord = getLocation()
lat1=coord[0]
lon1=coord[1]
#coordenada fatec
#la... |
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker, relationship
from sqlalchemy import create_engine
Base = declarative_base()
engine = create_engine('sqlite:///catalog.db')
# Limited session for c... |
"""
Adapters for compatibility between persistables and executors. Adapters are the
pluggable wrappers for persistables that ensure interoperability between
steps in processing.
Adapters must not contain any logic central to the processing. They can only be
interfaces to align formats, signatures, etc for consistent b... |
from numpy import*
falt = array(eval(input("Faltas registradas: ")))
vet = zeros(6)
for i in range(0, size(falt)):
if falt[i] == 2:
vet[0] = vet[0] + 1
elif falt[i] == 3:
vet[1] = vet[1] + 1
elif falt[i] == 4:
vet[2] = vet[2] + 1
elif falt[i] == 5:
vet[3] = vet[3] + 1
elif falt[i] == 6:
vet[4] = vet[... |
import math
import logging
from cache import Cache
FETCH_INSTRUCTION = 0
READ_MEMORY = 2
WRITE_MEMORY = 3
MES = ('M', 'E', 'S')
class Processor(object):
INTERESTED = 1
NOT_INTERESTED = 0
NOT_STALLED = 0
STALLED = 1
NO_BUS = 0
BUS_READ = 1
BUS_READ_EXCLUSIVE = 2
def __init__(... |
import pymel.core as pm
import maya.mel as mel
import tempfile
def ar_playblast(fileName, width, height, startTime=None, endTime=None):
"""
pcg_playblast using custom setting.
:param fileName: string (file path)
:param width: int
:param height: int
:param startTime: float
:param endTime: f... |
from src.race_manager import RaceManager
from src.race_inferer import RaceInferer
from src.race_inferer_wrapper import RaceInfererWrapper
from src.race import Race
from multiprocessing import cpu_count, Pool
import gmplot
import numpy as np
if __name__ == '__main__':
# Process & Inference flags
process_all_ra... |
"""
Ragdoll initialisation.
"""
from .db import *
from .composite import *
from .nutrient import *
from .flyweight import *
from .dictionary import *
from .human import *
from .req import *
from .plots import *
__version__=0.1 |
# -*- coding: utf-8 -*-
"""
This example demonstrates the use of GLSurfacePlotItem.
"""
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.opengl as gl
import numpy as np
import pyqtgraph_visualizer as pqvis
class Solid:
def __init__(self, timeres=100, cols=90, rows=100):
self... |
from django.db import models
class Group(models.Model):
group_text= models.CharField(max_length=150)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.group_text
class Question(models.Model):
group = models.ForeignKey(Group)
questio... |
#!/usr/bin/env python
# Copyright (c) 2015, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of condition... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('accounts.views',
url(r'^(?P<user_id>\d+)/queues/', include('queues.urls')),
url(r'^(?P<user_id>\d+)/music/', include('music.urls')),
url(r'^register/$', 'register'),
url(r'^(?P<user_id>\d+)/$', 'view')
)
|
import socket
import sys
port = 10000
size = 1024
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.connect(('127.0.0.1', port))
except socket.error as message:
if s:
s.close()
print ("Could not open socket: " + message)
sys.exit(1)
while... |
n = int(input())
list1 = list(map(int, input().split()))
a = 0
b = 0
for i in list1:
if i % 5 == 0:
a += i
else:
b += i
print(a)
|
# -*- coding: utf8 -*-
"""`veetou.model.entities_`
Provides the Set class
"""
from . import functions_
import collections.abc
import abc
__all__ = ('Set',)
class Set(collections.abc.MutableSet):
"""A set of unique items stored as references (but key-compared by value).
This set also counts how many times gi... |
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
from quantization.adaround.adaround import apply_adaround_to_layer
from quantization.adaround.utils import (
AdaRoundInitMode,
AdaRoundMode,
AdaRoundActQuantMode,
AdaRoundLossType,
AdaRoundTempDecayType,
)
|
# -*- coding: utf-8 -*-
#
# Blocksmurfer - Blockchain Explorer
#
# © 2020-2021 March - 1200 Web Development
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
Allowed = [ 'a', 'b', 'c' ] #список допустимых припереборе элементов
def select( n ) :
'''
generator passwords выдает элементы по одному
'''
if n == 0 :
yield ''
else :
for prev in select(n-1) :
for s in Allowed :
... |
from lxml import html
from colorama import Fore, Back, Style
from crawler_api.crawler import Crawler
from crawler_api.forum_item import ForumItem
from crawler_api.booter_url import BooterURL
class Crawler_Hackforums(Crawler):
'Crawler for web services of www.hackforums.net'
def __init__(self, sleep_level=1):
doma... |
import numpy as np
import cv2
import os
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers i... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 04 19:11:07 2017
@author: Alexander
"""
import random
import math
import matplotlib.pyplot
from matplotlib.pyplot import *
def f(x):
# A function to generate example y values
r = random.random()
y = x-10*r-x**r
return y
random.seed(35... |
from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime
from sqlalchemy import Float, Text, Boolean, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
from passlib.apps import custom_app_cont... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/6/12 12:25
# @Author : cui
# @File : runner.py
#定义一个test组件
from jiaoben.ATM.flow.test_liow import Flow
Flow().main_test()
|
from django.conf.urls import url,include
from django.contrib import admin
from appointmentscheduler.views.Options.Invoice import Invoice
from .Options import Options,Payments,CheckoutForm,terms
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^CountryTemplate/', include('shoppingcart.options.countri... |
import sys
sys.stdin = open("Line_test2_input.txt", "r")
def permute(arr):
global mat
ans = [arr[:]]
c = [0] * len(arr)
i = 0
while i < len(arr):
if c[i] < i:
if i % 2 == 0:
arr[0], arr[i] = arr[i], arr[0]
else:
arr[c[i]], arr[i] = arr... |
"""
Logging facilities
These are thin wrappers on logging facilities; logs
are all directed either to stdout or to $GAME_DIR/server/logs.
"""
import sys
from traceback import format_exc
import os
import threading
import logging
from logging.handlers import TimedRotatingFileHandler
class Logger(object):
"""
... |
from unittest import TestCase
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
from artificial.utils import PriorityQueue
class PriorityQueueTest(TestCase):
def setUp(self):
self.sample_sequence = (('first', 1), ('second', 10),
... |
# -*- coding:utf-8 -*-
from numpy.core import overrides
from models import User
import pymssql
import pyodbc
import engine_conf
from flask import Flask, render_template, flash, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_sess... |
#!/usr/bin/env python2
#-*-encoding:utf-8-*-
### <-----------------------------------------------------------------------------------> ###
# welcome to use this script
# This script is used to generate and execute CBA Netconf xml, and then check result #
# ./generate_NetconfXml_CBA.py snmpSet [-u|-d... |
'''
Exercício 2 - Substring
Dada uma string , ache o tamanho da maior substring , que não tenha caracteres
repetidos. Complexidade de tempo limite aceitável: O(n^2) .
'''
def most_substring(string):
letter_not_repeat = set()
most_value = 0
for letter in string:
if letter not in letter_not_repeat:
... |
class Scene(object):
def __init__(self):
self.backgroundColor = [0.0, 0.0, 0.0]
self.cameraPos = [0.0, 0.0, 0.0]
self.lookAt = [0.0, 0.0, 1.0]
self.lightPos = [0.0, 0.0, 0.0]
self.objs = [] # objects in the scene, class Obj
self.spheres = [] # legacy
clas... |
import wx
class LoginDialog(wx.Frame):
def __init__(self, parent=None, title='Enter username password', size=(300, 300)):
#super(LoginDialog, self).__init__(parent, title=title, size=(250, 150))
#wx.Dialog.__init__(self, None, title='abcd', size=(300,300))
wx.Frame.__init__(self, None, -1,... |
import ExternalCreditRatings
p1 = ExternalCreditRatings.probability_default(4, 'AAA')
p2 = ExternalCreditRatings.probability_default(3, 'B', 'during')
p3 = ExternalCreditRatings.probability_default(5, 'B', 'during')
p4 = ExternalCreditRatings.probability_default(3, 'BBB', 'during', 'no')
p5 = ExternalCreditRatings.pr... |
# import the necessary packages
"""
For P3 cameras:
python3 real_time_object_detection.py -n 1 \
-w 3840 -t 1080 -r "1200x300" \
-p P3_mobilenetSSD_deploy.prototxt \
-m P3_mobilenetSSD_deploy.caffemodel -c 0.3
"""
import numpy as np
import argparse
import imutils
impo... |
#!/usr/bin/env python3
import os
import shutil
import ntpath
from basic.clean import *
for p in os.walk('..'):
if '__pycache__'==ntpath.basename(p[0]):
shutil.rmtree(p[0],ignore_errors=True)
|
import unittest
from mesa.space import ContinuousSpace
from test_grid import MockAgent
TEST_AGENTS = [(-20, -20), (-20, -20.05), (65, 18)]
class TestSpaceToroidal(unittest.TestCase):
'''
Testing a toroidal continuous space.
'''
def setUp(self):
'''
Create a test space and populate w... |
import arcade
import pathlib as p
import numpy as np
from numpy.random import choice, uniform
import pyglet.clock as clock
from enemy_spawns import *
from modifier import *
class level(metaclass=ABCMeta):
enemy_spawns=[]
number_of_enemies=-1
name=""
modifier_field=[]
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.