text stringlengths 38 1.54M |
|---|
from accounts.models import CustomUser
from .models import Todo
import time
from django.shortcuts import render,HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model
from django.db.models.fields.files i... |
import os
import random
from Clustering.K_Means.HTML_CLUSTERING.main import run
from Clustering.K_Means.HTML_CLUSTERING.utils import HtmlPage
def get_test_data():
for root, _, files in os.walk("./download", topdown=False):
for f in files:
yield os.path.join(root, f)
def load_page(file_path)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from ClientMachineRest import ClientMachineRest
from Rectangle import Rectangle
from Logger import Logger
class ClientScreenParserRest(object):
"""ScreenParser Client to Call Restful Service
binding Rest base url when create
"""
... |
import names
import pandas as pd
import numpy as np
import random as rand
# SECTION 1
# Creating a list to store random student names
from pandas import DataFrame
num = 100 # Determining the number of students
name_list = [] # Preallocating the list to store names
for i in range(num):
name_list.append(names.get... |
from frw_tester import *
from logger import *
import os
import shutil
from supervisor import supervisor
import timeout_decorator
class ScenarioMaker:
# ------------------------------------------------ constructor ----------------------------------------------------------
def __init__(self):
# -----... |
# --> smtp lib, ssl
import smtplib, ssl
def sendmail(message):
s_server = "smtp.gmail.com"
port = 587
send_mail = "seceminiproject@gmail.com"
mail_password = "sriram@raghu"
recv_mail = "r4ghunandhan@gmail.com"
con = ssl.create_default_context()
try:
server = smtplib.SMTP(s_server... |
#coding=utf-8
import io
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.key... |
from model.contact import Contact
import random
def test_delete_contact_by_id(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname="qqqqqqqq", middlename="wwwwwww", nickname="eeefdeeee", title="vvvvvvvvvv",
lastname="eeeeeeeee", com... |
#!/usr/bin/env python
# coding: utf-8
# # Q1.Given an array of integers and a number, perform left rotations on the array.
# In[1]:
def rotate(arr,n):
x=arr[n-1]
for i in range(n-1,0,-1):
arr[i] = arr[i-1];
arr[0] = x
arr=[1,2,3,4,5]
n = len(arr)
print("Given array is")
for i in range(0,n):
... |
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# At... |
#!/usr/bin/python
import time, os, subprocess
import RPi.GPIO as GPIO
# set up GPIO on pin 17 for button press
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(22, GPIO.OUT)
def say_something(something):
subprocess.call(["c... |
import asynctest
from asynctest.mock import patch
from asynctest.mock import call
from charlesbot.slack.slack_message import SlackMessage
class TestPagerdutyEscalations(asynctest.TestCase):
def setUp(self):
patcher1 = patch('charlesbot_pagerduty_escalations.pagerdutyescalations.PagerdutyEscalations.load_... |
# -*- coding:utf-8 -*-
# @Desc :
# @Author : Administrator
# @Date : 2019-07-31 15:54
from django.core.mail import send_mail
from django.conf import settings
import string
import random
from users.models import EmailVerifyCode
# 生成验证码(随机字符串)
def get_random_code(slen):
return ''.join(random.sample(string.ascii_l... |
"""
Exercicios com strings
"""
print("*"*40)
print("")
print("BRINCANDO COM STRING USANDO PALINDROMO")
print("")
print("*"*40)
enter = input("Digite uma palavra ou frase: ")
def palindromo(enter):
if enter[::-1] == enter:
return f"A palavra {enter} é um palindromo"
else:
return f"A palavra {e... |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
RainbowList = [0, 1, 2, 3, 4, 5]
pos = mc.player.getTilePos()
x = pos.x
y = pos.y
z = pos.z
""" the L in RainbowList is not capitalized """
for color in Rainbowlist:
""" missing the argument for the color, and wool is not defined """
mc.setBlock(x,... |
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "pacmang2",
version = "0.0.1",
author = "Gaetan Gourdin",
author_email = "bouleetbil@frogdev.info",
description = ("Python binding for pacman-g2"),
licen... |
#MenuTitle: Wet Paint
# -*- coding: utf-8 -*-
__doc__="""
Wet Paint
"""
import GlyphsApp
from NaNGFGraphikshared import *
from NaNGFAngularizzle import *
from NaNGFNoise import *
from NaNFilter import NaNFilter
from NaNGlyphsEnvironment import glyphsEnvironment as G
from math import atan2, degrees
import math
import r... |
# -*- coding: utf-8 -*-
# Tools.py
from scipy import *
from scipy import signal
from scipy import fftpack
import pandas as pd
def FFT(TD,T=None):
"""
Single time domain array (TD) to FFT series and powerspectrum
"""
TD = array(TD).flatten()
Tfull = TD.shape[0]
if T==None:
nn = arg... |
a = int(input(""))
b = int(input(""))
c = int(input(""))
resultado = (a + b + c)/3
print(resultado)
|
import json
import os
import requests
from utils.config import Config
from utils.singleton import Singleton
GITHUB_HOST = 'https://api.github.com'
class Github(Singleton):
def __init__(self):
if hasattr(self, '_init'):
return
self._init = True
c = Config()
token = c... |
import torch
import torchvision.transforms as transforms
from newevaluate import evaluate
from itertools import chain
import numpy as np
def post_process(image):
image = image.view(-1, 3, 32, 32)
image = image.mul(0.5).add(0.5)
return image
def generate_image(image, frame, name):
image = image.cpu()
image = pos... |
import datetime
from openpyxl import load_workbook, Workbook
import sqlite3
from telebot import types
from misc import DB_DIR, REPORTS_DIR, CHATS_ID, OO_DIR
now = datetime.datetime.now()
current_day = now.day
current_hour = now.hour
# -----------------------ФУНКЦИИ ДЛЯ ДЕЛИШЕК----------------------------------
de... |
import datetime
import smtplib
from django.contrib.auth.forms import PasswordChangeForm
import pytz
from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib import mess... |
import sys
import copy
import traceback
from collections import defaultdict
from mysql_merge.utils import MiniLogger, create_connection, handle_exception
from mysql_merge.mysql_mapper import Mapper
from mysql_merge.mysql_merger import Merger
import mysql_merge.config as config
# VALIDATE CONFIG:
if len(config.merged_d... |
"""
A simple way for objects to subscribe to other objects for a "feed-like"
functionality in a Django project
"""
__version__ = '0.1.5'
__author__ = 'Rick Vause'
__email__ = 'rvause@gmail.com'
|
# Copyright Mark Jenkins, 2013
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
# http://www.gnu.org/prep/maintain/html_node/License-No... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 17:04:29 2019
@author: domin
"""
import matplotlib.pyplot as plt
from numpy import linalg as LA
import numpy as np
from scipy import fftpack
#f=8,4,2,1 for each additional qubit
f = 2 # Frequency, in cycles per second, or Hertz
f_s = 40 # Sampling rat... |
import logging
from contextlib import contextmanager
from datetime import datetime
from typing import List, Dict
from records import Database
logger = logging.getLogger(__name__)
@contextmanager
def db_connection(db_config: dict):
connection = Database(db_config['public-transport-stops'])
yield connection
... |
from src.bayes.utils import load_data
def test_load_data(file_path):
symptoms, diseases = load_data(file_path)
assert symptoms[0][1] == 0.96
assert diseases[0][1] == 0.99
|
read = open('in.in', 'r')
write = open('out.out', 'w')
cases = int(read.readline())
for case in range(cases):
line = read.readline()[:-1]
fields = line.split(" ")
n = int(fields[0])
r = int(fields[1])
p = int(fields[2])
s = int(fields[3])
# counts = []
# counts += [(r, p, s)]
imposs = False
for i in ran... |
import torch
learning_rate = 0.8
batch_size = 128
epochs = 10
classes = 10
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
def fact(n):
"Calcula el factorial de n"
if n==1:
return 1
else:
return fact(n-1)*n
print("2!:",fact(2))
print("5!:",fact(5))
print("13!:",fact(13))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MeterOpenModel import MeterOpenModel
class ExerciseItemOpenModelThird(object):
def __init__(self):
self._desc = None
self._external_item_id = None
sel... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
import cv2 as cv
"""
形态学操作 - 开操作
开操作 = 腐蚀 + 膨胀
opencv关于形态学操作进行了封装,所有的形态学操作可使用一个api进行,即
cv.morphologyEx(src, option, kernel, anchor, iterations)
- src: 任意输入图像,可以为灰度、彩色或二值
- option: 形态学操作的枚举
- kerne... |
from roger.components.data_conversion_utils import TypeConversionUtil
def test_type_comparision():
datatype_1 = list.__name__
datatype_2 = str.__name__
datatype_3 = bool.__name__
datatype_4 = float.__name__
datatype_5 = int.__name__
# list should always come first
assert datatype_1 == Type... |
#coding=utf-8
import re,urllib,sys,MySQLdb as mdb
import chardet
reload(sys)
#sys.setdefaultencoding('utf-8')
#s='#NAME?' #或者用raw_input()输入也行
def geturl():
#db =mdb.connect(host='127.0.0.1',user='root',passwd='hehe',db='public_opinion',charset='utf8')
#cur=db.cursor()
s=raw_input("请输入关键词:")
s=s.decode(sys.stdin.en... |
__author__ = 'Evenvi'
import tesseract
import cv
#image = cv.LoadImage("./img/plateBinary.jpg",cv.CV_LOAD_IMAGE_GRAYSCALE)
image = cv.LoadImage("./img/plateBinary.jpg",cv.CV_LOAD_IMAGE_GRAYSCALE)
#chiImage = cv.LoadImage("./img/chiPlate.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)
def recognize(image):
api = tesseract.TessB... |
from pymongo import MongoClient
client = MongoClient() # The call to mongoclient is outside the connecCollection function,
# to only make the call once, and save time and resources.
def connectCollection(database, collection):
# Get a database and a collection from mongoDB
db = client... |
# _*_ coding: utf-8 _*_
import os
ifile = open('test.txt','r')
ofile = open('result.txt','w')
num = 1
for line in ifile.readlines():
print line
print num
num = num + 1
if ((line.startswith('#') != 1) and (line != '\n')):
ofile.write(line)
# if (line != '\n')
# for line in ifile.readline():
# ... |
"""MyGame URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
from django.shortcuts import render
from .models import StudentsInfo,GuardianInfo
# , GuardianInfo
# Create your views here.
def GuardianInfoListVW(request):
all_guardian = GuardianInfo.objects.all()
context = {"Guardian_list":all_guardian}
return render(request, 'students/guardian_info_list.html', context... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 10:47:04 2019
@author: 19233292
"""
def cumulative_sum(l):
count = 0
new_list = []
for i in l:
count += i
new_list.append(count)
return new_list
print(cumulative_sum([1,2,3])) |
# https://towardsdatascience.com/lstm-for-time-series-prediction-de8aeb26f2ca
# https://romanorac.github.io/machine/learning/2019/09/27/time-series-prediction-with-lstm.html
import sys
import torch
import torch.nn as nn
import os
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as ... |
import fasttext
import sys
import os
import argparse
'''
No hay mucha magia (o al revés: hay demasiada).
Usamos la librería de fasttext para entrenar nuestro modelo, y luego appendeamos las predicciones con el valor __label__ pues esa es la salida esperada
'''
def train_and_test():
model = train(args.train_data)
... |
#!/usr/bin/python
#
# Given v7 and v8 objects at 6m, create versions at different heights
#
refheight=6
cut=3
for obj in ['Safedock2S-%sm.obj',
'Safedock2S-%sm-pole.obj',
'Safegate-%sm.obj',
'Safegate-%sm-pole.obj']:
for height in [3, 3.5, 4, 4.5, 5, 5.5, 6.5, 7, 7.5, 8]:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 18 13:54:26 2019
@author: gdussert
"""
import keras
# import keras_retinanet
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
from keras_retinanet.utils.visualiz... |
import logging
import torch
import torch.nn as nn
from kma.modules.attention import Attention
LOG_FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
logging.basicConfig(format=LOG_FORMAT, level=getattr(logging, 'INFO'))
logger = logging.getLogger(__name__)
class RNNDecoder(nn.Module):
KEY_ATTN_SCOR... |
'''
WSGI接口:只要求web开发者实现一个函数,就可以响应http请求
'''
def HelloWorld(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'<h1 style background:red>HelloWorld, I am python server</h1>']
# 2.7---str 3.6---byte
# 为什么return的内容必须是list?????????????????????
# environ:一个包含所有HTTP请求信息... |
'''
@author: xilh
@since: 20200127
'''
class Father:
def f1(self):
print("Father.f1 ...")
class Son(Father):
def f2(self):
print("Son.f2 ...")
print("== 单继承 ==")
son = Son()
print(son.f2())
print(son.f1()) |
'''
Created on Aug 29, 2014
'''
import os,sys,subprocess,time,shutil
from comMethods import *
from numpy import ceil
class Fitter:
""" This class performs the UNCLE fits to the VASP data that has been gathered so far. It also
keeps track of the fitting errors, prediction errors, and summaries of cluster... |
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
# Create your models here.
class StudentField(models.Model):
title = models.CharField(max_length=255)
def __str__(self):
return self.title
def handle_avatar_upload_path(... |
def get_final_line(fname):
with open(fname) as f:
for line in f:
pass
return line
if __name__ == "__main__":
print(get_final_line("/etc/passwd"))
|
#import the os module
import os
#import the csv module
import csv
budget_data_csv = os.path.join("Resource", "budget_data.csv")
#variable to hold total profits and losses
total = 0
#list to hold all csv data
BudgetInfo = []
#list to hold months column from csv data
Months = []
#list to hold profits and losses column ... |
import re
class server_cvar:
# server_cvar: "mp_friendlyfire" "1"
pattern = re.compile("server_cvar: \"(?P<cvar>.*)\" \"(?P<value>.*)\"")
@staticmethod
def isMatch(instr):
return (server_cvar.pattern.match(instr) != None)
def __init__(self,instr):
obj = server_cvar.pattern.match(instr)
self.cvar = obj.gro... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
from __future__ import division
import pandas as pd
import numpy as np
from scipy import stats
from scipy.stats import ttest_ind, levene, f_oneway, f
from math import sqrt
from itertools import combinations
from qsturng import psturng
# ===== STATISTICAL TESTS USED BY CEP =====
def get_cohens(sample_a, sample_b):
... |
from recommendations import recommendation
import MySQLdb
import numpy as np
import math
from scipy import spatial
conn1 = MySQLdb.connect(host = "localhost", user = "root", passwd = "40OZlike", db = "plalyst")
cur= conn1.cursor()
class Song():
def __init__(self, name):
self.name = name
cur.exec... |
import pygeo.geocelery_conf
def url_to_download_filepath(user_url, url):
user_filepath = user_url_to_filepath(user_url)
filepath = '%s/%s' %(download_dir(), user_filepath)
filepath += url[6:]
return filepath
def download_dir():
return "%s/esgf" % pygeo.geocelery_conf.DOWNLOAD_DIR
def user_url_to... |
"""
Problem 120 - Triangle
Given a triangle, find the minimum path sum from top to bottom. Each
step you may move to adjacent numbers on the row below.
"""
from typing import List
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
for i in range(len(triangle) - 2, -1, -1):
... |
#!/usr/bin/env python
# coding: utf-8
import binascii
def MD2(input_string):
""" Calculates the MD2 hash of any string input.
Arguments:
input_string
Returns:
Hexadecimal MD2 hash of the input string.
"""
#---------------------------------------------------------------------------... |
import random
l = [0] * 4
m = [list(l) for x in range(4)]
for i in range(4):
for j in range(4):
m[i][j] = random.randint(0, 16)
print(m)
diag1 = [m[i][i] for i in range(4)]
diag2 = [m[i][4 - i - 1] for i in range(4)]
border = [m[0][i] for i in range(4)] + [m[3][i] for i in range(4)] + [m[i][0] for i in ... |
from __future__ import division
import argparse
# from . import main, utils
import pkg_resources
import pandas as pd
import ast
import subprocess
import numpy as np
def run():
parser = argparse.ArgumentParser(
description='run diffacto for scavager results',
epilog='''
Example usage
------... |
import pytest
from denorm.models import DirtyInstance
from django.core.exceptions import ValidationError
from django.db.models import ProtectedError
from model_bakery import baker
from bpp.models import Wydawca
from bpp.models.wydawca import Poziom_Wydawcy
@pytest.mark.django_db
def test_wydawnictwo_zwarte_wydawca_d... |
x=int(input())
l=[64,32,32,16,16,8,8,4,4,2,2,1]
num=0
for i in range(len(l)):
if l[i]<=x:
if x-l[i]>=0:
x-=l[i]
num+=1
print(num)
|
# -*- coding: utf-8 -*-
from deptreevis import *
from deptree import *
from eval import *
from macrodef import *
def make_foo():
sl = StatementList()
arg = sl.make_var()
ret = sl.call(access_macro('b'), arg)
arg.make_arg()
ret.make_ret()
return user_macro(lambda:sl)
def make_bar(foo):
sl = StatementLi... |
def is_nan(string):
return string != string
# Usado pra pegar a primeira linha das tabelas normais
def get_begin_row(data, begin_string):
begin_row = 0
for row in data:
begin_row += 1
if(row[0] == begin_string):
break
while is_nan(data[begin_row][0]):
begin_row += ... |
from flask import g
from werkzeug.local import LocalProxy
from flask_dance.consumer import OAuth2ConsumerBlueprint
__maintainer__ = "Oleg Lavrovsky <oleg@datalets.ch>"
def make_hitobito_blueprint(
client_id=None,
secret=None,
domain=None,
*,
scope=None,
redirect_url=None,
redirect_to=Non... |
import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
kPluginNodeName = "MitsubaHKShader"
kPluginNodeClassify = "/shader/surface"
kPluginNodeId = OpenMaya.MTypeId(0x87015)
class hk(OpenMayaMPx.MPxNode):
def __init__(self):
OpenMayaMPx.MPxNode.__init__(... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy_splash import SplashRequest
import pdb
import time
import json
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
from scrapy.http import FormReques... |
import numpy as np
import math
from function import khoang_cach, mid_point
def head_pose_ratio(nose, left_eye, right_eye):
g_t = mid_point(left_eye[0][0], left_eye[0][3])
g_p = mid_point(right_eye[0][0], right_eye[0][3])
x2 = (g_t[0], nose[1])
x1 = (g_p[0], nose[1])
y2 = (nose[0], g_t[1])
y1 =... |
# -*- coding: utf-8 -*-
"""Admin models and registration for trivia app."""
# Part of Trebek (https://github.com/whutch/trebek)
# :copyright: (c) 2018 Will Hutcheson
# :license: MIT (https://github.com/whutch/trebek/blob/master/LICENSE.txt)
from django.contrib import admin
from . import models
admin.site.register(m... |
import string
s = 'The quick brown for jumped over the lazy doc.'
print(s)
# 首字母大写.
print(string.capwords(s))
|
import gym
from environment import TSCEnv
from world import World
from generator import LaneVehicleGenerator
from agent import MaxPressureAgent, IntersectionAgent
from metric import TravelTimeMetric
import argparse
from plan import *
import os.path as osp
# parse args
parser = argparse.ArgumentParser(description='Run ... |
# This coding is to make a local backup of following mathematics competition problems and solutions
# provided on AOPS website, in case they do not provide contents in the future, and also for convenience
# to practice the problems on local.
#
# AMC 8
# AMC 10
# AMC 12
# AIME
# USAJMO
# USAMO
#
import urllib.request
i... |
import tensorflow as tf
from tensorflow.python.keras import backend as K
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
print(x_train[0:2])
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28))... |
"""
__init__.py adding folders to the __path__ object
"""
from sys import path
path.insert(0, "src/controllers")
|
import os
import csv
import time
import datetime
import subprocess
from multiprocessing.pool import ThreadPool
from config import *
multi_result = []
def pull_price(resource_name, size, now_time):
vm_name = resource_prefix + 'vm-' + '111'
command = " az vm create \
--resource-group {} \
--na... |
## Given a list of points as a tuple (x, y) and an integer k,
## find the k closest points to the origin (0,0).
# Calculates a point's distance from the origin by
# adding up how many "steps" it would take to reach (0,0).
def distance(point):
return abs(point[0]) + abs(point[1])
def closest_points(points, k):
... |
import numpy as np
import matplotlib.pyplot as plt
import argparse
import warnings
warnings.filterwarnings("ignore")
from Map import makeMap
from Dijkstra import runDijkstra
from AStar import runAStar
def booleanParser(val):
if val.lower() == 't':
return True
else:
return False
def checkRes(sPts,gPts,res):
... |
#!/usr/bin/env python
import os
import pytest
import pexpect
TIMEOUT_SECONDS = 2
child = None
def check_result(pattern):
index = child.expect(
[pattern, pexpect.EOF, pexpect.TIMEOUT], timeout=TIMEOUT_SECONDS
)
try:
assert index == 0
except AssertionError:
""" print(
... |
import re
import json
from typing import Union
from grandpybot.helpers import base_path
class Parser:
"""The parser used for user questions input.
Attributes:
_stopwords (set): A list of words considered as non keywords.
_punctuation (set): A list which contains punctuation chara... |
from django.db import models
# Create your models here.
class Code(models.Model):
objects = models.Manager()
id = models.CharField(max_length = 10, primary_key=True)
name = models.CharField(max_length=512)
parent = models.ForeignKey('self', models.SET_NULL, blank=True, null=True)
|
n = int(input())
from collections import deque
stack = deque()
l = []
l.append(0)
l1 = []
l2 = []
l2.append(0)
l3 = []
l3.append(0)
l4 = []
l4.append(0)
s = input().split()
j = 0
m2 = 0
m1 = 0
k = 0
for i in s:
j = j+1
if i == "1":
stack.append("Y")
if len(stack)>m2:
m2 = len(sta... |
"""
Copyright 2014 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... |
import torch
from torch import nn
class ClampLoss(nn.Module):
""" Wrapper Module for `(clamp(input, 0, 1) - clamp(target, 0, 1))`
"""
def __init__(self, module, min_value=0, max_value=1, eta=0.001):
super().__init__()
self.module = module
self.min_value = min_value
self.max... |
"""create results schema
Revision ID: 2e7dac655911
Revises:
Create Date: 2020-09-15 21:06:39.157407
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2e7dac655911'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.execute("CREAT... |
import time
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from numpy import random, mean, median
import GiniCoef
import candidates
import citizens
import financers
import parameters
import os
# Generate agents
def generate_citizens(num_cit, inc_list):
my_citizens = []
for i in range(... |
import numpy as np
import pandas as pd
class Sudoku:
def __init__(self,matrix):
try:
self.sudoku_matrix = np.zeros([9,9]) + np.array(matrix)
except:
raise "Matriz de tamanho errado."
aux_possibility_matrix_dict = {}
for i in range(0,9):
aux_possi... |
import numpy as np
def get_k_means_plus_plus_center_indices(n, n_cluster, x, generator=np.random):
'''
:param n: number of samples in the data
:param n_cluster: the number of cluster centers required
:param x: data- numpy array of points
:param generator: random number generator from 0 to n for ... |
import csv
import plotly.express as px
import plotly.figure_factory as ff
import pandas as pd
dataFile=pd.read_csv("csv/normal.csv")
fig=ff.create_distplot([dataFile["Weight"].tolist()],["Weight"],show_hist=False)
fig.show() |
# 226. Invert Binary Tree
# Given the root of a binary tree, invert the tree, and return its root.
# Example 1:
# Input: root = [4,2,7,1,3,6,9]
# Output: [4,7,2,9,6,3,1]
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left... |
#-*- coding:utf-8 -*-
import os
class CodeReplace(object):
def __init__(self,rootPath):
self.old = '"code", java.getCode()'
self.new = '"id", java.getId()'
self.rootPath = rootPath
self.repFileList = []
def run(self):
self.recursionReplace(self.rootPath)
self.lo... |
class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
if self.items:
return self.items.pop()
print('Stack is empty')
# show the next value that is ready to be popped
def p... |
import chess
from chessboard import display
def evaluateScore():
if board.is_checkmate():
if board.turn: #If White turn return -9999 meaning Black won. Else return 9999 meaning White won
return -9999
else:
return 9999
#Score pieces based on position. Piece square t... |
import pytest
import os
from polyglotdb.io import inspect_mfa, inspect_textgrid
from polyglotdb import CorpusContext
def test_load_discourse(graph_db, mfa_test_dir, textgrid_test_dir):
test_file_path = os.path.join(mfa_test_dir, "mfa_test.TextGrid")
acoustic_path = os.path.join(textgrid_test_dir, 'acoustic_... |
'''
Driver for KMTRonic RS485 Relay
the board has 8 relays and a status command
note: KMT status seems quite buggy
(oscilloscope measures noisy response)
'''
from . import rs485
size = 8 # no. relays
ID = 4 # id-select-switches currently toggled for ID4
stat_byte = 0xA0
byte1 = 0xFF
def status():
'''
... |
"""
Спросить имя пользователя и сохранить его.
Прочитать файл questions.txt и последовательно задать вопросы пользователю.
Проверить ответы из файла answers.txt
Записать результаты в файл и назвать его именем пользователя.
В результатх указать количество правильных и не правильных ответов.
"""
score_right = 0
scor... |
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
def get_variable_type(variable_type):
initial_type = variable_type
var_type = variable_type.upper()
if(var_type == 'BYTE'):var_type = 'INT1'
if(var_type == 'WORD'):var_type = 'INT2'
if(var_type == 'INT'):var_type = 'INT4'
if(var_type == 'LONG'):var_type = 'INT8'
if(var_type in ['DOU... |
from bellman_ford import BellmanFord
from dijkstra import Dijkstra
class Johnson:
@staticmethod
def johnson(network):
"""
Calculates the shortest path using Johnson's algorithm
Parameters
----------
src : str, int
An arbitrary node that does not exist in th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.