text stringlengths 38 1.54M |
|---|
class TestMigrations:
def test_alembic(self, tmp_path):
from sqlalchemy import create_engine
from spellbot import get_db_url
from spellbot.data import create_all, reverse_all
db_file = tmp_path / "spellbot.db"
connection_string = f"sqlite:///{db_file}"
db_url = get_... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import logout as logout_user
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from .models import Travel, TravelPlaceKeeper , TravelType
# Create your views here.
d... |
import sqlite3
from Updater import run_updater
print("\t \t \t \t Update your spendings here _|_ \t \t \t \t")
dict = {}
date = str(input("Enter the date in YY-mm-dd format : "))
dict["DATE"] = date
db_loc = r'C:\Users\chand\Documents\P\Projects\Locally_personalised_ads\db\payment_db.db'
table_name_1 = "tab1"
# Ge... |
from nltk.corpus import gutenberg, nps_chat
import nltk
moby = nltk.Text(gutenberg.words('melville-moby_dick.txt'))
print(moby.findall(r"<a><.*><man>"))
print(moby.findall(r"<a>(<.*>)<man>"))
chat = nltk.Text(nps_chat.words())
print(chat.findall(r"<l.*>{3,}")) |
# coin_key = "35ad627a-d583-4961-828e-36eead5e8e3b"
coin_key = "9188e46a-558a-4d2c-8496-21c9719ec1d2"
secret_key = "235 h sdblfgghf__aghg9843ty fmsa"
DATABASE = "data/movimientos.db" |
"""
Извлекаем из файла images.json вытащенные из гугл-таблицы
со статистикой урлы-ссылки на эскизы и сохраняем их в базе.
"""
import json
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'edu_test.settings'
django.setup()
from .models import Student, Task, Image
with open('images.json', 'r') as f:
... |
from flask import Flask, render_template,request
#import flask_mysqldb
#from flask_mysqldb import MySQL
from similar import similar, similar_papers
import pandas as pd
app = Flask(__name__)
data = pd.read_csv("cite_updated.csv")
@app.route("/")
def home():
return render_template("home.html")
@app.route('/resul... |
str = "a b\t c \nd"
print(str)
list = str.split()
print(list)
result = "\n".join(list)
print(result)
|
import torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
import os
def batch_transform(batch, transform):
"""把一个batch的样本应用于transform
Args:
batch (): a batch的样本
transform (callable):用来转换batch samples的 function/transform
"""
# 以tensor形式将单通道标签转换为RGB
# 1. torc... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
RESTAURANT_URL = reverse("user:restaurant")
CREATE_RESTAURANT_URL = reverse("user:createrestaurant")
def create_user(**params):... |
import requests
import argparse
import threading
def logo():
print("""
\x1b[32m
____ _ _ ____ _
| __ )| | __ _ ___| | _| _ \(_)_ __
| _ \| |/ _` |/ __| |/ / | | | | '__|
| |_) | | (_| | (__| <| |_| | | |
|____/|_|\__,_|\___|_|\_\____/|_|_| version:0.2
================================... |
from bref_feature_engineering.rollingavg_seasonlog_teamrecord import teamrecord
from bref_feature_engineering.proportion_ip_available import get_games_played, append_proportion_ip_avail
celtics_17 = teamrecord("Boston Celtics", 2017)
append_proportion_ip_avail(celtics_17, "Boston Celtics")
print(celtics_17) |
import os
import sys
import struct
import collections
import argparse
from os.path import exists, join, relpath, isdir
from contextlib import contextmanager
from typing import Tuple, List
from . import mod
from . import uassetz
MOD_APPID = "346110"
DEFAULT_MOD_STORAGE_DIR = "steamapps/workshop/content/" + MOD_APP... |
from GeneralPythonCopy.General import General
'''
Process for User uploading data:
1. User: uploads files to Website and chooses the y_variable for the regression (discrete occurance) [views.py]
2. Backend: uploaded files go to uploaded_files along with a txt file with the specified y_variable which is acce... |
import numpy # we import the array library
from matplotlib import pyplot # import plotting library
myarray = numpy.linspace(4, 5, 2)
print(myarray)
a = 5 #a is an integer 5
b = 'five' #b is a string of the word 'five'
c = 5.0 #c is a floating point 5
print(type(a))
print... |
from app_instance import app
from umongo import Document
from umongo.fields import StringField, IntegerField, ListField
@app.lazy_umongo.register
class Movies(Document):
name = StringField(required=True, allow_none=False)
popularity = IntegerField()
director = StringField(required=True, allow_none=False)
... |
#!/usr/bin/env python
#--------Include modules---------------
from copy import copy
import rospy
from visualization_msgs.msg import Marker
from std_msgs.msg import String
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyGrid
from os import system
from random import random
from numpy import arr... |
import random
from ac_flask.hipchat import Addon, room_client, addon_client, sender, context
from ac_flask.hipchat.glance import Glance
from flask import Flask
addon = Addon(app=Flask(__name__),
key="test-addon",
name="Test AddOn",
allow_room=True,
scopes=['send_... |
# Copyright 2022 The HuggingFace Authors.
#
# 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... |
#jam
import sys,os,platform
import time
import subprocess
import multiprocessing
import threading
import pandas as pd
#subprocess.call(["python3","test.py"])
#abc=subprocess.check_output(["python3","test.py"])
# print("abc")
# lists=subprocess.Popen(["python3","test.py"],stdout=subprocess.PIPE)
# try:
# abc=lists.c... |
from sys import argv, exit
from Tkinter import Tk
try:
tkObj = Tk()
except Exception as e:
print "Failed to create the Tkinter object: " + str(e)
cssPath = tkObj.clipboard_get()
print "The CSS path retrieved from your clipboard is:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + str(cssPath)
... |
#
# @lc app=leetcode.cn id=77 lang=python3
#
# [77] 组合
#
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res = []
self.dfs(n,k,1,[],res)
return res
def dfs(self,n,k,start,path,res):
if k == 0 and path not in res:
res.append(path)
ret... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def listprint(self):
head = self.head
while head is not None:
print(head.value)
head = head.next
... |
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from apps.lib.template import render_to
from .item import generate_thumbnail_of_item
from .models import Item
@render_to('recent.html')
def recent(request):
items = Item.objects.order_by('-created_at')[:30]
return dict(items=i... |
#!/usrabin/env pyhton
import sys
sys.path.append('/usr/local/lib/python3.6/site-packages')
# 链家租房
import requests
from tools.UserAgent import USERAGENT_LIST
from lxml import etree
import random
import time
import re
import pymysql
import gevent
from tools.spider_58 import five_eight
from tools.ziru import ZiruSpider
c... |
## Group members : Myungjin Lee, Krishna Akhil Maddali, Yash Shahapurkar
import copy
import numpy
import random
from matplotlib import pyplot as plt
inp_file='clusters.txt'
f_inp_obj=open(inp_file, 'r')
x=[]
y=[]
for line in f_inp_obj:
tmp=line.split(',')
if len(tmp)==2:
x.append(float(... |
name = 'zed a shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
height_cm = height * 2.54
weight_kg = weight * 0.453592
eyes = 'blue'
teeth = 'white'
hair = 'brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall")
print(f"(that's {height_cm} in cm)")# convert to cm
print(f"He's {... |
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/topics/items.html
from scrapy.item import Item, Field
class Etymology(Item):
# define the fields for your item here like:
entry_word = Field()
entry_link = Field()
description_word = Field()
descripti... |
def roundup(k):
if k != int(k): k = k // 1 + 1
return int(k)
n = int(input())
pakls = [float(inp) for inp in input().split()[:n]]
bound = [float(inp) for inp in input().split()]
cost = int(input())
unf = len(pakls)
loss = 0
for pak in pakls:
if not (bound[0] <= pak <= bound[1]):
unf -= 1
... |
import random
def getElements():
lst = []
for i in range(1,11):
lst.append(random.randint(1,20))
return lst
lst = getElements()
ele1 = int(input("Guess a number in range (1-20) :"))
ele2 = int(input("Guess a number in range (1-20) :"))
ele3 = int(input("Guess a number in range (1-20) :"))
if ele1... |
n = int(input().strip())
A = [int(A_temp) for A_temp in input().strip().split(' ')]
b=set(A)
ans=max(A)
c=0
for i in b:
if A.count(i)>=2:
ans=min(ans,abs((A.index(i))-(len(A)-A[::-1].index(i)-1)))
else:
c+=1
if(c==len(A)):
print(-1)
else:
print(ans) |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 16:02:55 2019
@author: leona
"""
#Now from the clean intro and plots we start building the dictionary that will have "index":word, so we have a unique associatioin between a word in the dataset we care about and a number. Obviously we will save it as json file,... |
"""
grpc test client
"""
from fastapi import FastAPI
from api.services.books import router
app = FastAPI(docs_url='/api', openapi_url='/api/openapi.json')
app.include_router(router, prefix='/api/book', tags=['book'])
|
import turtle
import winsound
import os # For screen clear command
wn = turtle.Screen()
wn.title("Mini project")
wn.bgcolor("black")
wn.setup(width = 800, height = 600)
wn.tracer(0)
#Score
score_a = 0
score_b = 0
#Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.col... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import matplotlib
matplotlib.use('Agg') # don't try to use $DISPLAY
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.gridspec as gridspec
import numpy as np
import math
import operator
def setC... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class obere(object):
a = 15
def __init__(self):
self.zahl = 42
self.a = 4
def fun(self):
return 17
def show(self):
print(self.a)
def delete(self):
del self.a
def arit(self):
self.a = self.a +4
class unt... |
from __future__ import with_statement
from builderror import BuildError
from shermanfeature import ShermanFeature
import codecs
import os
import re
import subprocess
class Feature(ShermanFeature):
@ShermanFeature.priority(90)
def sourcesConcatenated(self, locale, moduleName, modulePath):
print " ... |
from run import db, User
username = "Admin"
password = "admin123"
level = "Admin"
db.session.add(User(username,password,level))
db.session.commit() |
class ExceptionSignalsBinder:
def __init__(self,exception_handler,choose_posts,post_to_group,edit_post,liable_about_view,warning_message,vk_operator):
self.__warning_message = warning_message
self.__exception_handler = exception_handler
self.__liable_about_view = liable_about_view
... |
import salem
from salem.utils import get_demo_file
import xarray as xr
import matplotlib.pyplot as plt
import pdb
import numpy as np
from functools import partial
from salem import get_demo_file, open_xr_dataset, GeoTiff, wgs84
dat = xr.open_dataarray('/users/global/cornkle/data/pythonWorkspace/proj_CEH/topo/gtopo_1... |
print("Welcome to the Shipping Accounts Program\n")
ls = ["john","mike","jasmine","george","kelvin"]
name = input("Hello, what is your username: ").lower()
if name in ls:
print("Hello {}. Welcome back to your account.".format(name))
print("Current shipping prices are as follows:")
print("Shipping orde... |
# Bradley Aiken
# roster_fields.py
# used with cs176roster.webadvisor.txt
# reformat student information from read file
old_roster = open("cs176roster.webadvisor.txt", "r")
new_roster = open("roster.txt", "w")
# 0: name, 1: id, 2: email, 3: major, 4: year, 5: adviser, 6: credits
count = 0
for line in old_roster.readl... |
from mininet_test.test_monitor import TestMonitor
from mininet_test.test_monitor_host import TestMonitorHost
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of te... |
import boto3
def lambda_handler(event, context):
db = boto3.resource('dynamodb')
table = db.Table('Users')
with table.batch_writer() as batch:
batch.put_item(
Item={
'id': 1,
'name': 'parwiz',
'age': '20'
}
)
... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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 a... |
from torch import nn
import torch
import numpy as np
class TextLSTM(nn.Module):
"""
lstm model of text classify.
"""
def __init__(self, opt):
self.name = "TextLstm"
super(TextLSTM, self).__init__()
self.opt = opt
self.embedding = nn.Embedding(opt.vocab_size, opt.embed_... |
from django.http import HttpResponse
from django.shortcuts import render
import datetime
# Create your views here.
def date_time_view(request, retun=None):
date=datetime.datetime.now()
s='<h1> The current Data And Time at server is :' +str(date)+'</h1>'
return HttpResponse(s) |
import pygame
from math import sin, cos
from random import randint
SCREEN_WIDTH, SCREEN_HEIGHT = 650, 650
FPS = 850
BACKGROUND = [ 0 ] * 3
# --- Core ---------------------------------------------------------
class FuncDrawer:
def __init__(self, x_func, y_func, t_begin, t_end, t_step=0.1, tail=100):
self._x_func =... |
#!/usr/bin/python
# ADB.py
#
# Functions to manage an AWARE database dictionary
#
# This file is used to merge a heirarchy of json files used to track AWARE
# Imaging System.
#
# Developed by: Steve Feller on 11/8/2012
# Release Date:
# versions: 0.1
#
# Functions:
# generate(path) - function to generate a dictiona... |
from __future__ import absolute_import
from agms.agms import Agms
from agms.request.invoicing_request import InvoicingRequest
from agms.response.invoicing_response import InvoicingResponse
from agms.exception.invalid_request_exception import InvalidRequestException
class Invoicing(Agms):
"""
A class represent... |
import socket
serversocket = socket.socket(socket.AF_NET, socket.SOCK_STREAM)
host = socket.gethostbyname()
port = 444
serversocket.bind(("192.168.1.104", port))
serversocket.listen(3)
while True:
clientsocket, address = serversocket.accept()
print("received connection from %s " % str(addres... |
import warnings
warnings.filterwarnings('ignore')
from datasetup.utils import *
from datasetup.data_preprocessing import filterPAR, getPoints
from datasetup.data_segmentation import *
data_file = 'exported/Cleaned_Dataset.csv'
""" User Input Declaration:
1. filter_mode = 0 (Don't filter); 1 (Filter TC that pas... |
#!/bin/env
"""
Script that generates body_synapse file using specified annotation datatype with synapes.
lau, 01/16 first version of script
example:
python generate_body_synapses_dvid.py emdata1:8500 44d42 bodies3_annotations mb6_synapses annotations body_synapses_test
"""
# ------------------------- imports ----... |
import os
import json
from datetime import datetime
from random import shuffle
from flask import Flask, session, redirect, url_for, request, render_template, jsonify
# Custom .py
import helper.helper as helper
import riddles.riddle as riddle
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY... |
from general.utils import MyTask
import numpy as np
class Classifier(MyTask):
def createmodel(self, inputsize, outputsize, update_model=False):
tmpsample=np.array([np.zeros(inputsize)])
newshape=self._reshape(tmpsample).shape[1:]
return self._createmodel(newshape, outputsize,update_model=up... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 11:11:23 2020
@author: Administrator
"""
import os
path = r'C:\Users\Administrator\Desktop'
os.chdir(path)
name = 'rsrp_grid50'
with open('rsrp_grid_09.sql',encoding ='utf-8') as f:
content = f.readlines()
for i,line in enumerate(content):
if 'SET F... |
from django.contrib import admin
from .models import Winery, Wine, Grape, County, Comment
# Register your models here.
admin.site.register(Winery)
admin.site.register(Wine)
admin.site.register(Grape)
admin.site.register(Comment) |
from opentrons import protocol_api
metadata = {'apiLevel': '2.2',
'protocolName': 'Clip Template v2',
'author': 'Gabrielle Johnston',
'description': 'DNABot updated clip template'}
def run(protocol: protocol_api.ProtocolContext):
def clip(
prefixes_wells,
... |
# Copyright 2021 Google
#
# 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, softw... |
def reduce(polymer):
changed = True
#print(''.join(polymer))
while changed:
changed = False
i = 0
while i < len(polymer) - 1:
if abs(ord(polymer[i]) - ord(polymer[i+1])) == 32:
del polymer[i:i+2]
changed = True
else:
... |
fi = open("somecode.txt", 'r')
print('hi')
for line in fi.readlines():
for symbol in line:
if symbol == '(':
print('[', end = '')
elif symbol == ')':
print(']', end='')
else:
print(symbol, end='') |
#!/usr/bin/env python -W ignore::DeprecationWarning
"""
Grasp Metrics for EE106B grasp planning lab
Author: Chris Correa
"""
# may need more imports
import numpy as np
from lab2.utils import vec, adj, look_at_general, hat
import cvxpy as cvx
import math
import scipy
def compute_force_closure(vertices, normals, num_fac... |
# Generated by Django 2.1.5 on 2019-04-02 01:40
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('ticketingApps', '0011_auto_20190401_1845'),
]
operations = [
... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from ..models import *
from datetime import datetime
# Create your views here.
def index(request, text):
user = request.user
testString = 'auth.patient' in user.get_all_permissions()
if not testString:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#vim: set enc=utf8:
# More elaborate GUI-operations
# Supporting the AutoIT syntax would be nice
from .interact import Emulate, Screen
import os
class ScriptFiles:
"""A class for managing the directory with scripts.
The name of the script is the same as the filename.... |
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image as Img
from PIL import ImageTk as imgtk
import os
class DataProcessing(object):
def __init__(self, data):
self.data = data
def get_datetime_from_twelve(self):
data = pd.DataFrame(self.data)
... |
lotteryPlayer ={
'name' : 'jeffy',
'numbers':(5,9,7,8,6)
}
class LotteryPlayer:
def __init__(self, name):
self.name = name
self.numbers = (5,9,8,9,7)
def total(self):
return sum(self.numbers)
# Instance or creating an object of LotteryPlayer
# Object oriented programming
play... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later ... |
""" Given a list of words, list of single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used ... |
import glooper_python_swig_wrap as glooper
import rng_python_swig_wrap as rng
M = glooper.Market()
U = rng.UniformGenerator()
P = rng.ParetoGenerator(10000,1.3)
N = rng.NormalGenerator()
G = glooper.ClassicAgentGenerator(U,N,P,U,U,M,10)
AP = glooper.AgentPopulation(U,G)
|
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))
import matplotlib.pyplot as plt
import numpy as np
from sklearn import preprocessing
from sklearn.manifold import TSNE
from neural_network.Dataset import FullDataset
from neural_network.SNN import initialise_snn
from configu... |
#!/usr/bin/env python
from multiprocessing.dummy import Pool
import socket, hashlib, argparse, re, textwrap, sys, select
'''
TODO
- generate random AUTHENTICATOR
- fuzzing?
'''
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
sub_str = 'th'
n1 = len(word)
n2 = 2... |
from projects.golem_api.pages import auth
def test_get_token(data):
response = auth.get_token_request(data.env.users.admin.username, data.env.users.admin.password)
assert response.status_code == 200
assert type(response.json()) is str
def test_get_token_with_incorrect_password(data):
response = auth... |
"""
libspecinfra-python
----
Python bindings for libspecinfra
"""
__version__ = '0.0.1'
import sys
import ctypes
import os
import libspecinfra.resource
from libspecinfra.structures import SpecinfraS, BackendWrapperS
library = None
def load():
global library
if library is None:
libdir = os.path.dir... |
import numpy as np
from tkinter import *
from tkinter.filedialog import askopenfilename
import cv2
import consts
from keras.models import load_model
from data import Data
from PIL import Image, ImageTk
model = load_model('trashnet.h5')
root = Tk()
PATH = StringVar()
CATIGORY = StringVar()
def browsefunc():
... |
class ParsingError(Exception):
def __init__(self, token):
self.errorToken = token
def __str__(self):
return "Parsing error at line {}".format(self.errorToken.lineNumber)
@classmethod
def raises(cls, tok):
raise cls(tok)
|
# -*- coding: utf8 -*
from django.db import models
class FileDescriptor(models.Model):
name = models.CharField(max_length=255)
path = models.FileField(upload_to='%Y/%m/%d')
description = models.CharField(max_length=255, blank=True, null=True)
tag = models.CharField(max_length=255, blank=True, null=True)
type = m... |
import os, sys, math
import ply.lex as lex
import ply.yacc as yacc
tokens = [ # List of token names
'INT',
'FLOAT',
'NAME',
'PLUS',
'MINUS',
'DIVIDE',
'MULTIPLY',
'EQUALS',
'R_PARENTHESIS',
'L_PARENTHESIS',
'DELIMITER'
]
literals = [ '{', '}' ]
|
import numpy as np
import cv2
import cv
from Gen import Gen
class Osc(Gen):
def __init__(self, name):
Gen.__init__(self, name)
self.attrs['freq'] = 220.0
self.attrs['phase'] = 0.0
self.attrs['sync'] = 2.0
def update_attrs(self, updates = {}):
for attr_type in updat... |
"""
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1].
The next permutation of an array of integers is the next lexicographically greater permutatio... |
from testflows.core import *
from testflows.asserts import error
from rbac.requirements import *
from rbac.helper.common import *
import rbac.helper.errors as errors
@TestSuite
def describe_with_privilege_granted_directly(self, node=None):
"""Check that user is able to execute DESCRIBE on a table if and only if
... |
#!/usr/bin/python
# coding: utf-8
try:
import cPickle as pickle
except ImportError:
import pickle
import threading
import os
import sys
import ConfigParser
import base64
import logging
import json
import time
from subprocess import Popen
from subprocess import PIPE
from cement.core import foundation
from dc.Event... |
from django.db import models
class Pokemon(models.Model):
name = models.CharField(max_length=200, unique=True, blank=False)
pokemon_id = models.IntegerField(unique=True, blank=False, primary_key=True)
weight = models.IntegerField(default=0)
height = models.IntegerField(default=0)
hp = models.Intege... |
from flask import request, render_template
from flask_socketio import emit
from datetime import datetime
from . import data_holder
from .app import app, socket
def _broadcast(payload : dict):
emit('emit', payload, broadcast=True, namespace='/')
def _emit(payload : dict):
emit('emit', payload, broadcast=False... |
from flask import Flask, render_template, request
import json
import os
import psycopg2
application = Flask(__name__)
STATIC_PATH = os.path.dirname(os.path.abspath(__file__)) + "/static"
conn = psycopg2.connect(
user=os.environ.get("PGUSER"),
host=os.environ.get("PGHOST"),
port=os.environ.get(... |
from enum import Enum
from sqlalchemy import Column, Integer, String
from sqlalchemy_utils.types import URLType
from upload.db.base_class import Base
class FileStatusEnum(str, Enum):
""" Перечисление доступных статусов для файла """
new: str = "new"
in_queue: str = "in queue"
finished: str = "finis... |
# Generated by Django 2.1.5 on 2019-02-13 03:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='bio',
field... |
"""
Recommendations Engine
===============
Business Objective:
To recommend applications to users that they might find useful in their everyday objectives
Website Link: https://github.com/aml-development/ozp-documentation/wiki/Recommender-%282017%29
Data that could be used for recommendations
- Listing Bookmarked
- K... |
import base64
import logging
import re
import shlex
import subprocess
from email.headerregistry import Address
from typing import Optional
import orjson
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.utils.translation import gettext as _
from zerver.decorator import aut... |
# @Time : 2021/2/1 11:42 下午
# @Author : Xingyou Chen
# @File : linklist_postorder.py
# @Software: PyCharm
class linknode():
def __init__(self, value):
self.data = value
self.next = None
def create_link(li):
head = linknode(li[0])
now = head
for i in li[1:]:
now.next = linknode... |
# Generated by Django 2.2.6 on 2019-10-17 14:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('picker', '0005_auto_20190331_1043'),
]
operations = [
migrations.AddField(
model_name='credential',
name='extractor_u... |
from web3 import Web3
from web3.utils.encoding import to_hex
import time
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
filter = w3.eth.filter('latest')
while True:
for blk_hash in filter.get_new_entries():
block = w3.eth.getBlock(blk_hash,True)
for tx in block.transactions:
print(... |
"""
Reads mail templates into memory and provides functions to format them.
"""
with open('mail_templates/verification_html.txt', 'r') as f:
_verification_mail_html = f.read()
with open('mail_templates/verification_plain.txt', 'r') as f:
_verification_mail_plain = f.read()
def format_verification_mail_html(... |
from django.shortcuts import render
from django.http import HttpResponse
from todo.models import Todo
# Create your views here.
def home(request):
if request.method == 'POST':
todo = request.POST['todo'].strip()
priority = request.POST['priority'].strip()
Todo.objects.create(todo=todo, priority=priority)
els... |
#!/usr/bin/env python
from optparse import OptionParser
from tracker_module import *
from predict import *
from tracker_gui import *
import sys
if __name__ == '__main__':
#--------START Command Line option parser------------------------------------------------
usage = "usage: %prog -a <Server Address> -p <Se... |
from architecture.service_structure import ServiceStructure
from interaction.chatbots.minuteur_chatbot import MinuteurChatBot
from interaction.recognition import RecognitionStates
import base64
import time
import threading
class ConversationStates:
ANSWER_FOUND = "Answer found"
ANSWER_NOT_FOUND = "Answer not... |
import requests
from base64 import b64encode
from color import Color
import string
import random
images = 10
size = 64
types = ['jpeg', 'png', 'gif']
file_path = "../js/photos.js"
chars = string.ascii_letters + string.digits
def gen_id(length = 2, chars = chars):
return ''.join(random.choice(chars) for x in range... |
from win32api import GetKeyState, mouse_event
from win32con import MOUSEEVENTF_WHEEL
def key_down(key):
keystate = GetKeyState(key)
if (keystate==0) or (keystate==1):
return 0
else:
return 1
def scroll_wheel_forward(x,y):
if mouse_event(MOUSEEVENTF_WHEEL,x,y) > 0:
return 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.