text stringlengths 8 6.05M |
|---|
import session_log
import introduction
import image_processing
import keyboard
import flop
import current_stack
import error_log
import pot_odds
import db_query
def check_is_turn(screen_area, deck, stack_collection, db):
element_area = introduction.save_element(screen_area, 'turn_area', db)
if image_processin... |
"""
World
Corporation
DERs
User
Role
"""
import names
import random
import pprint
random.seed(0) # Always generate the same dataset
n_utilities = 5
n_providers = 6
n_sp = 5
admins = 4
sec_auditors = 2
n_der = n_utilities * n_providers * 50
total_accounts = n_utiliti... |
import requests
import sys
import fundamentus
def download_all(stocks, session_id):
s = requests.Session()
for stock in stocks:
referer_url = "{}balancos.php?papel={}&tipo=1".format(
fundamentus.get_base_url(),stock)
s.get(referer_url)
s.headers.update({'Referer': refere... |
# coding=utf-8
from rest_framework import serializers
class PublicServantSerializer(serializers.Serializer):
first_name = serializers.CharField(label='Prenume', max_length=255)
last_name = serializers.CharField(label='Nume', max_length=255)
position = serializers.CharField(label='Funcție', max_length=255)... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from .managers import CustomUserManager
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
klass = models.Positiv... |
import json
import random
import re
from datetime import date
from operator import attrgetter
from typing import List, Optional
from MainSettings import MainSettings
from medalcalc.models.Hero import Hero
from medalcalc.models.HeroHistory import HeroHistory
from common.utils.DateUtils import DateUtils
from medalcalc.m... |
from izigraph.importers import NgvImporter
import izigraph
def test_importer_can_import_graph(tmpdir):
importer = NgvImporter()
content = "0\n0\n"
p = tmpdir.mkdir("sub").join("graph.csv")
p.write(content)
g = importer.import_graph(str(p))
assert isinstance(g, izigraph.Graph)
def test_import... |
# Generated by Django 2.1.7 on 2019-04-30 09:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='catalog',
name='image',
f... |
import requests
import math
import geocoder
def get_mid_of_2pts(coords1,coords2):
x1,y1 = coords1
x2,y2 = coords2
x_mid = (x1 + x2)/2.0
y_mid = (y1 + y2)/2.0
return (x_mid,y_mid)
def address_to_coordinates(user_address):
the_location = geocoder.osm(user_address)
lat = the_location.osm.get('y',None)
lon = t... |
import common
import re
def help():
return {'authors': ['kqr', 'nycz'],
'years': ['2012', '2013'],
'version': '1.2',
'description': 'Interface till Google via något slags ajax json API.',
'argument': '<googlesökning>'}
def run(nick, mess... |
from django.contrib.staticfiles.management.commands.collectstatic import Command as BaseCommand
from js_routing.functions import build_js_file
class Command(BaseCommand):
"""
Command that collects static and generates the routes js from the templates.
"""
help = "Collect static files from apps and oth... |
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
import os
from keras.optimizers import Adam
from keras.callbacks import ModelChe... |
print("Started with GitHub")
|
N = input()
cruzamentos = 0
x = 1 #x é uma variável qualquer temporária
pregos = [int(i) for i in input().split()]
for i in range(len(pregos)-1,0,-1):
for j in range(len(pregos)-1-x,-1,-1):
if pregos[j] > pregos[i]:
cruzamentos +=1
x += 1
print(cruzamentos) |
#import the get_basic_image file as an easier to read name
#no need to import serpapi since it is imported in the get_basic_image file
import get_basic_images as gbi
#An array of all queries that need to be run
#This is a google search query so search syntax can be used link below for examples
#https://support.google... |
from django.shortcuts import render, render_to_response
from django.template.context import RequestContext
# Create your views here.
def home(request):
template = "index.html"
return render_to_response(template, context_instance=RequestContext(request,locals()))
|
from collections import deque
from typing import List
from leetcode import TreeNode, new_tree, test
def level_order_bottom(root: TreeNode) -> List[List[int]]:
if not root:
return []
queue, result = deque([root]), []
while queue:
queue_len = len(queue)
level = []
for _ in ... |
import requests
import Utils
from bs4 import BeautifulSoup
TRULIA_REQUEST_KEY = 'trulia'
HOMEFINDER_REQUEST_KEY = 'homefinder'
REMAX_REQUEST_KEY = 'remax'
ZILLOW_REQUEST_KEY = 'zillow'
def get_next_homefinder_url(raw_html):
soup_file = BeautifulSoup(raw_html, 'lxml')
for link in soup_file.findAll("link", at... |
import os
import git
import yaml
import csv
import re
import time
import gspread
from pydrive.auth import ServiceAccountCredentials
# import pdb; pdb.set_trace()
class Env:
def __init__(self, name):
self.name = name
self.projects = []
self.sum_metrics = None
def get_project(self, nam... |
import math
import sys
if len(sys.argv) == 1:
print('Input filename:')
f=str(sys.stdin.readline()).strip()
else: f = sys.argv[1]
with open(f, 'r') as fp:
l, mreset, string = fp.readline(), [], ''
while l:
string += str(l).strip()
l = fp.readline()
mreset = [int(x) for x in string.split(',')]
... |
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from student.models import Student
class StudentAdmin(admin.ModelAdmin):
list_display = ('name', 'roll_no',)
admin.site.register(Student, StudentAdmin)
|
from time import time
from datetime import datetime
from PIL import Image
from simpleai.search import SearchProblem, astar
from .modules.brute_force_mazeSolver import runSolver #pylint: disable=relative-beyond-top-level
from .modules.a_star_mazeSolver import MazeSolver #pylint: disable=relative-beyond-top-level
from .m... |
import mxnet as mx
import numpy as np
from collections import namedtuple
x = mx.nd.ones((100,100))
y = mx.nd.ones((100,100))
data = mx.sym.var('data')
fc1 = mx.symbol.FullyConnected(data, name='fc1', num_hidden=128)
act1 = mx.symbol.Activation(fc1, name='relu1', act_type='relu')
fc2 = mx.symbol.FullyConnected(act1, n... |
#!/usr/bin/python
## gfal 2.0 ls tool
## @author Adrien Devresse <adevress@cern.ch> CERN
## @license GPLv3
##
import gfal2_utils
import sys
if __name__ == "__main__":
sys.exit(gfal2_utils.gfal_cat_main())
|
from __future__ import print_function
def main():
infile = open('data/adult.data', 'r')
data = []
for line in infile:
data.append(line.split(', '))
#q = Question(9, "Female")
data.pop()
#true_rows, false_rows = partition(data, q)
#gini_data = [data[0],data[1],data[2],data[3],data[4]]
#print(gini(gini_data))
... |
import socket
import select
def parseData(data):
print("Data: ", data)
BUFFER = 2048
clientList=dict({})
host = ''
port = 12345
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientList[server]={'ip':'', 'port':12345}
server.bind((host, port))
server.listen(5)
print("Server is listening for connection... |
"""
astroHOG Statistical tests
"""
import numpy as np
# ------------------------------------------------------------------------------------------------------------------------
def HOG_PRS(phi):
# Calculates the projected Rayleigh statistic of the distributions of angles phi.
#
# INPUTS
# phi - angle... |
from dataloader import tilegenerator
import os
import glob
from multiprocessing import Pool
from functools import partial
def tile_all_process(obj, use_tiss_mask):
if use_tiss_mask:
obj.load_ds_wsi()
obj.stain_entropy_otsu()
obj.morphology()
obj.generate_tiles()
obj.slide_thumbn... |
from analysis import *
fig = plt.figure(figsize =(figWidth,figHeight))
ax = fig.add_axes([0,0,1,1])
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(linW1)
ax.spines[axis].set_color(colK1)
plt.style.use('seaborn-paper')
rc('font',**{'family':'sans-serif','sans-serif':['De... |
import serial
import time
import datetime
import threading
import math
import os
import pytz
import numpy as np
import matplotlib.pyplot as plt
class modemController():
def __init__(self, baud=57600, timeout=0.05):
self.crc = None
self.cmdinf = '01'
self.ser=serial.Serial(
por... |
from typing import List, Tuple
def split_name(prediction: str) -> Tuple[str, int]:
if len(prediction.split("_")) > 1:
return prediction.split("_")[0], int(prediction.split("_")[1])
else:
return prediction, 0
def is_correctly_retrieved(predictions: List[str], ground_truth: List[str]) -> bo... |
#!/usr/bin/env python3.5
print("Hello Poland")
|
from data_structure.linkedlist.Node import Node
# Class Linked List
class LinkedList:
# Initialize
def __init__(self):
self.first = None
self.last = None
self.__size = 0
# Add node on first
def add_first(self, data):
new_node = Node(data)
if self.__is_empty()... |
import mimetypes
from django.conf import settings
from django.db import models as dbmodels
from PyPDF2 import PdfFileReader
from PyPDF2.utils import PdfReadError
from ..utils.auth import get_group_model
from ..utils.rest_api import (
FileField,
IdPrimaryKeyRelatedField,
ModelSerializer,
SerializerMeth... |
import os
from hca.dss import DSSClient
from hca.util.exceptions import SwaggerAPIException
from tests.utils import Progress
class DataStoreAgent:
DSS_SWAGGER_URL_TEMPLATE = "https://dss.{deployment}.data.humancellatlas.org/v1/swagger.json"
DSS_PROD_SWAGGER_URL = "https://dss.data.humancellatlas.org/v1/swag... |
T = int(input())
for _ in range(T):
n = int(input())
a = list(map(int,input().split()))
m = a[-1]
c = [a[-1]]
for i in range(n-2,-1,-1):
if m <= a[i]:
m = a[i]
c.append(a[i])
for i in range(len(c)-1,-1,-1):
print(c[i],end=" ")
print() |
import datetime
import streamlit as st
from threading import Thread
def run(alarmH,alarmM):
while(True):
if(alarmH==datetime.datetime.now().hour and alarmM==datetime.datetime.now().minute):
st.write("Time to wake up")
audio_file=open("song.mp3","rb")
st.audio(audio_file,... |
#A file for testing the python apt module
import apt
import sys
pkg_name = "firefx"
cache = apt.cache.Cache()
#cache.update()
if pkg_name in cache:
pkg = cache[pkg_name]
print(pkg.versions[0].description)
else:
print("Package %s not found" % pkg_name)
|
for abc in ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","u","v","w","x","y","z"]:
salida = open('english-'+abc+'.txt','w')
fichero = open('english.txt', 'r')
for linea in fichero:
#print (len(linea))
if(len(linea) == 9 and linea[0] == abc):
salida.write(linea)
s... |
# -*- coding: utf-8 -*-
import connection
import groups
import users
import logging
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
import sys
name = sys.argv[1]
usrs = sys.argv[2:]
logging.info('creando oficina\nnombre: {}\nusuarios: {}'.format(name, users))
con = con... |
# -*- coding:utf-8 -*-
# class fraction operations
def incor_exit(message):
print(message)
return
class Fraction(object):
def __init__(self, numerator, denominator=1): # a / b
try:
numerator / denominator
except (TypeError, ZeroDivisionError):
incor_exit('Error!'... |
#!/usr/bin/python
#coding: utf8
import numpy as np
class anthill:
def __init__(self):
self.nb_ants = None
self.start = None
self.end = None
self.room = []
self.link = []
self.move = []
self.nb_move = 0
class Ant:
def __init__(self, number, node_path=None,
journey=None, color='g.'):
sel... |
# Generated by Django 2.2.7 on 2019-11-24 20:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0002_auto_20191124_2036'),
]
operations = [
migrations.CreateModel(
... |
x = int(input("Enter x :"))
y = int(input("Enter y :"))
x = x*0+y
y = y*0+x
print(x)
print(y) |
from sympy.ntheory import primefactors
limit = 1000000
for n in xrange(limit):
ok = True
for i in xrange(4):
if len(primefactors(n+i)) != 4:
ok = False
break
if ok:
print n
break
|
# coding=utf-8
import sympy as sp
import numpy as np
from fractions import gcd
import bitwise_operators_strings as bw
def shift_register(iniCond,poly):
"""Generates a maximum length sequence in a shift register from the next arguments:
- iniCond: the initial condition of the shift register
- poly: primiti... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.utils import Sequence as tf_Sequence
from torch.nn import Module
from functools import partial
from graphgallery import functional as gf
class Sequence(tf_Sequence):
def __init__(self, *args, **kwargs):
device = kwargs.pop('device', 'cpu... |
import dash_bootstrap_components as dbc
from dash import Input, Output, html
dropdown = html.Div(
[
dbc.DropdownMenu(
[
dbc.DropdownMenuItem(
"A button", id="dropdown-button", n_clicks=0
),
dbc.DropdownMenuItem(
... |
# based on https://inventwithpython.com/chapter10.html for practice
# tic tac toe game
import random
import time
def get_letter():
while True:
letter = input("Choose your letter ('X' or 'O') >> ")
if letter.upper() == 'X':
return['X', 'O']
elif letter.upper() == 'O':
... |
import torch.utils.data as data
import cv2
import sys
import random
from os import listdir
from os.path import join
import os
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from inference.Compiler import *
# Model Imports
import torch
import torch.nn as nn
imp... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
#from bayes_opt import BayesianOptimization
from bayesian_opt.bayesian_optimization import BayesianOptimization
def target(x):
y = np.exp(-(x-2)**2)+np.exp(-(x-6)**2/5)+1/(x**2+1)+0.1*np.sin(5*x)-0.5
return y
def posterior(... |
#!/usr/bin/python3
'''after party module'''
def append_after(filename="", search_string="", new_string=""):
'''function that inserts a line of text to a file, after
each line containing a specific string'''
input_file = open(filename, mode='r').readlines()
with open(filename, mode="w") as f:
... |
import unittest
from katas.beta.count_vowels_in_a_string import count_vowels
class CountVowelsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(count_vowels('abcdefg'), 2)
def test_equals_2(self):
self.assertEqual(count_vowels('asdfdsafdsafds'), 3)
|
class Player: #수퍼클래스
def __init__(self, name, age):
self.name = name
self.age = age
class SoccerPlayer(Player): #서브클래스
def Goal(self, goal):
self.goal = goal
class Midfielder(SoccerPlayer): #서브클래스의 서브클래스
def assist(self, ass):
self.ass = ass
class GamePlayer(P... |
#! /user/bin/env python3
import imaplib
import email
import os
import sys
import mimetypes
import time
# log in information
# emailAddress = os.environ.get("python_email")
# password = os.environ.get("python_password")
# instagramAddress = os.environ.get('instagram_email')
# instagramPW = os.environ.get('instagram_pas... |
from django.contrib import admin
from .models import User
from django.contrib.auth.admin import UserAdmin
class UserAdmin(admin.ModelAdmin):
filter_horizontal = ['groups']
admin.site.register(User, UserAdmin)
|
from flask import Flask, render_template
from youtube_api import YoutubeDataApi
from youtube import getVideoData
app = Flask(__name__)
@app.route('/')
def sayHello():
return render_template("index.html")
# @app.route('/about')
# def about():
# return render_template("about.html")
@app.route('/suggestions')... |
import socket
import select
HEADER_LENGTH = 3 #Header will be used to specify the length of the message received
IP = socket.gethostname()
PORT = 2000
email_list = ["trinity"]
password_list = ["college"]
coef_authorization = 0
#This function returns a message received in the format: header, message_body-... |
from youtube_api import YoutubeDataApi
from secret import youtube_api
yt = YoutubeDataApi(youtube_api)
def getVideoData(search):
searches = yt.search(q=search, max_results=10)
print(searches[0])
searches = [{'title': search['video_title'], 'date': search['video_publish_date'], 'desc': search['video_desc... |
from flask import Blueprint
from flask import request, jsonify
from flask import render_template
from flask_login import login_required
from .controller import HostMonitor, Performance
bp = Blueprint('performance', __name__)
@bp.route('/performance/host')
@login_required
def host():
all_list = HostMonitor.host_al... |
name = input()
message = "Hello, "
if name == "Johnny":
message += "my love!"
else:
message += f"{name}!"
print(message) |
#!/usr/bin/python
from statistics import median
num=input("Enter number to find median:")
con=[int(x) for x in str(num)]
res=median(con)
print(res)
|
import sys
import numpy as np
from Perceptron import Perceptron
from io_handling import FileOutputter
def main():
p = Perceptron(FileOutputter(sys.argv[2]))
raw_data = np.loadtxt(sys.argv[1], delimiter=',')
data = raw_data[:, [0, 1]]
rows = raw_data.shape[0]
bias_column = np.ones(rows)
bias_... |
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict():
'''
For rend... |
import cv2
import numpy as np
folders = ['Adirondack-perfect', 'Backpack-perfect',
'Couch-perfect', 'Sword2-perfect']
# for different sequences, find depth image
for folder in folders:
# path of images
path = 'D:\\Vision\\HW07_dataset\\Question2\\{}\\{}\\'.format(folder, folder)
# lef... |
"""
# 二叉树
"""
import os
import logging
logger = logging.getLogger(__name__)
class TreeNode(object):
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def pre_order(root):
"""前序遍历二叉树, 借助迭代器+递归实现"""
if root:
yield root.val # 访问根节点
yiel... |
#! /usr/bin/env python
'''
Submission script adapted for Comet and Bridges HPCs, including
multiple options such as accounts, partitions, n of processors,
memory, etc.
Author: Juan V. Alegre Requena, please report any bugs
or suggestions to juanvi89@hotmail.com
'''
import os
from argparse import ArgumentParser
PARTIT... |
from threading import Lock
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO
import redis
async_mode = None
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
redis_store=redis.from_... |
t = int(input())
while t > 0:
s = str(input())
if (min(s.count('0'),s.count('1'))) % 2 == 1:
print("DA")
else:
print("NET")
t = t-1
|
import pytest
"""
配合 -m 标记名 进行筛选执行用例
例如:pytest cases\test_标记.py -m finished
"""
@pytest.mark.smoke
@pytest.mark.finished
def test_func1():
assert 1 == 1
@pytest.mark.unfinished
def test_func2():
assert 1 != 1
@pytest.mark.wait
def test_func3():
assert 1 != 1
|
import unittest
from katas.kyu_6.reversed_words import reverseWords
class ReverseWordsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(reverseWords(
'The greatest victory is that which requires no battle'),
'battle no requires which that is victory greatest The... |
#I pledge my honor that I have abided by the Stevens Honor System
def squareValues(values):
squared_values= int(values)**2
return squared_values
def main():
values= input("Enter a list of values separated by a comma:")
new_values=values.split(',')
for num in new_values:
print(squareValues(nu... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class ExposuresBundleRoadway(Model):
"""NOTE: This class is auto generated by ... |
from flask import current_app
class Holder:
def __str__(self):
return '{}'
def __call__(self, name):
return self
class CacheKey:
HOLDER = Holder()
def __init__(self, *args):
self.holder_count = len(list(filter(
lambda a: isinstance(a, Holder), args)))
se... |
from pandas.core.frame import DataFrame
import pandas as pd
import numpy as np
import re
import calendar
import datetime
import time
SKIP_LINE_SET = {"*** USER INFORMATION MESSAGE", "A ZERO FREQUENCY"}
p_header = re.compile(r"(?P<label>.+(?=SUBCASE))(?P<subcase>SUBCASE\s\d+)")
re_date = re.compile(r'(?P<month>\w+)\... |
import SimpleXML
import base64
import socket
host = "192.168.10.93"
# host="184.183.150.164"
port = 5901
bold_xml = SimpleXML.SimpleXML()
bold_xml.device_id = 909090
bold_xml.event = "*BA"
clip = open("test.mpg", "rb").read()
bold_xml.clip = base64.b64encode(clip).decode("ascii")
bold_xml.bin_size = ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def to_range(images, min_value=0.0, max_value=1.0, dtype=None):
"""Transform images from [-1.0, 1.0] to [min_value, max_value] of dtype."""
assert np.min(images) >= -1.0 - 1e-5 and ... |
class MaxHeap:
def __init__(self):
self.arr = [None]
def push(self, val):
def need_swap(ind):
parent = ind // 2
if self.arr[ind] > self.arr[parent]:
return True
else:
return False
self.arr.append(val)
curr ... |
import numpy as np
'''
Inputs
------
* mu: The mean of the gaussian fit
* sigma: The covariance of the gaussian fit
Outputs
-------
* mu: The center of the ellipse
* a: The semi-major axis length
* b: The semi-minor axis length
* theta: The ellipse orientation
'''
def cov2ell(mu, sigma):
xy = mu
vals, vecs = np.li... |
"""
This is an example of a block comment.
Python supports both block comments and line comments.
Line comments begin with #
"""
# Set a name variable
myName = 'Andy Fischoff'
print(myName) # will print Andy Fischoff |
#!/usr/bin/python
# -*- coding: cp936 -*-
import sqlite3
""" UpdateLeftAccount.py
对于 leftaccount 表格增删查改的操作
"""
class updateLeftAccount:
def update(leftAccounts):
# 插入leftaccount, 存在的就replace
with sqlite3.connect('C:\sqlite\db\hxdata.db') as db:
insert_template = "INSERT OR REPLACE INT... |
'''
This file contains my implementation of a solution to the second problem: Files and Directories.
The functions os.listdir() and os.walk() were not used in this solution due to
the requirement that programs such as ls and similar may not be used.
@author: Naveen Neelakandan
'''
#!/usr/bin/python
import datetime
im... |
import hashlib
from tkinter import *
from array import *
znaki = array("u")
formated = array("u")
indx = 0
cindx = 0
strs = ["" for x in range(11)]
def fastH(string, hash):
if(hash == "sha256"):
h = hashlib.sha256(string.encode()).hexdigest()
return h
if(hash == "md5"):
h = hashlib.md... |
#!/usr/bin/python3
import configparser
import os
import datetime
from git import Repo
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
print(bcolors.OKBLUE + ''... |
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from app.model.accounts import Accounts
from app.model.invite import Invite
from app.model.invites import Invites
from app.forms.invite import InviteF... |
#!/usr/bin/env python3
import sys, os
import hmac, hashlib
sys.path += [ os.path.join(os.path.split(__file__)[0], 'libs') ]
from intelhex import IntelHex16bit
# Plain Unsafe ops (op = bytes = word {little endian})
# ----------------------------------------------------
# ret = 0x08 0x95 = 0x9508
# reti = 0x18 0x95 = 0x... |
from .rng import app |
from colors import *
# app config
FPS = 60
WIDTH = 600
HEIGHT = 600
SIZE = (WIDTH, HEIGHT)
BG_COLOR = BLACK
# consts
INFINITY = 10e10
COEFF = 50 # 3d
# player config
START_POS = (0, 0)
START_ANGLE = 0
ANGLE_SPEED = 1
MOVEMENT_SPEED = 2
# object settings
NLINES = 10
NPOINTS = 0
NCIRCLES = 5
RPOINT = 3
RCIRCLE = 50
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from fpgen import HTML
class NonHTML(HTML): #{
def __init__(self, ifile, ofile, d, letter):
HTML.__init__(self, ifile, ofile, d, letter)
# No page numbers on any non-html
def getPageNumberCSS(self):
return [
"[105] .pageno { display:none; }"
]
... |
#!/usr/bin/python3
import numpy as np
import pandas as pd
import pathlib
from vulkan import *
import PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QLabel
from PyQt5.QtCore import QAbstractTableModel, Qt
# %%
_code_git_version="... |
'''
Original use of functions by Adam Bolton, 2009.
http://www.physics.utah.edu/~bolton/python_lens_demo/
'''
# Given a background source, this lenses it and plots both as output.
# The parameters for the lens can be changed but for it's a point source
def lensed(gamp,gsig,gx,gy,gax,gpa,name,lamp=1.5,lsig=0.05,lx=0.,... |
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
# Homepage
@app.route("/")
def home():
return render_template('index.html')
# Homepage re-route
@app.route("/index.html/")
def home_reroute():
return redirect(url_for("home"))
#Wheelbase page
@app.r... |
from indicator import Indicator
import states
class RSI(Indicator):
def __init__(self, utils, config, logger, timeframe):
Indicator.__init__(self, utils, config, logger)
self.timeframe = timeframe
self.distance = self.cfg.DATA_POINTS
self.period = self.cfg.PERIOD
self.sell = self.cfg.SELL
self.buy = se... |
K=int(input("K= "))
N=int(input("N= "))
if(N>0):
for i in range(0,N):
print(K) |
from mod_base import*
class UserInfo(Command):
"""View info about you or another nick."""
def run(self,win,user,data,caller=None):
args = Args(data)
u = user
if len(args)>0:
result = self.bot.FindUser(args[0])
if result!=False:
u = result
... |
#!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from vr.models.baselines import LstmEncoder
from vr.models.baselines import build_mlp
class HyperVQA(nn.Module):
"""A model that uses a HyperNetwork to produce the weights for a CNN"""
... |
class jumpingTable():
jumpingTable = {}
def set(self, n, i):
self.jumpingTable[n] = i
def going(self, index):
if index in self.jumpingTable:
self.jumpingTable[index]()
elif 'default' in self.jumpingTable:
self.jumpingTable['default']()
else:
... |
import pandas
from sklearn import linear_model, datasets
from sklearn.metrics import accuracy_score
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score
print('reading in data...')
"""Read in dataset"""
set_sizes = [100,500,1000,5000,10... |
import maya.cmds as cmds
import maya.mel
#for selecting all objects
cmds.select(all=True,visible=True)
#for deselecting circle
cmds.select('nurbsCircle1', d=True)
#for deselecting plane and deselecting other objects
cmds.select('nurbsPlane1', d=True)
#for center pivot
cmds.xform(cp=True)
cmds.xform(a=True)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.