text stringlengths 8 6.05M |
|---|
from cv2 import cv2
import numpy as np
from PIL import Image
import math
import glob
import os
import time
import csv
def rotate_image_and_crop(mat, angle, bound_w,bound_h):
height, width = mat.shape[:2] # image shape has 3 dimensions
image_center = (width / 2, height / 2) # getRotationMatrix2D needs coordin... |
# Default TimeServer and ClientServer buffer length.
buffer = 1024
# TimeServer default port port number.
port = 8981
# Maximum waiting time for clients' response, in seconds.
timeout = 10
# Inclusive range for server response's delay (min, max).
server_response_delay_range = [1, 2]
|
from bitstring import BitArray, BitStream
import Image
import sys
import hashlib
def getKey(pw):
sha = hashlib.sha1()
sha.update(pw)
key = BitArray(bytes=sha.digest())
return key
def getImageData(image):
img = Image.open(image)
data = img.getdata()
#print len(data)
return data
|
# coding=utf-8
"""Реализовать скрипт, в котором должна быть предусмотрена
функция расчета заработной платы сотрудника.
В расчете необходимо использовать формулу:
(выработка в часах * ставка в час) + премия.
Для выполнения расчета для конкретных значений
необходимо запускать скрипт с параметрами. """
from sys import... |
""" function to load pulse shape of atmoNC, IBD and fast neutron events from file and add dark counts to the
pulse shape.
These pulse shapes with dark counts are then also saved and can be analyzed with analyze_PSD_cut_v2.py.
"""
import datetime
import os
import re
import numpy as np
def get_numbers_from_fil... |
# 绝对值 abs()
print('-400的绝对值', abs(-400))
# 求幂 pow() ,也可以用math.pow()
print('2的10次方:', pow(2, 10))
# 序列求和 sum()
l1 = [1, 2, 3, 4, 5]
print('l1序列的和为:', sum(l1))
print('l1序列的和再加2:', sum(l1, 2))
# 最大值 max() ,最小值 min()
print('l1序列中的最大值和最小值分别为:%d \t %d' % (max(l1), min(l1)))
|
import csv
from io import StringIO
import uuid
from guests.models import Event, Guest
def import_guests(path):
with open(path, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
first_row = True
for row in reader:
if first_row:
first_row = False
... |
import json
import requests
import telepot
import re
def search_taobao(msg):
item_name = msg['text']
response = requests.get('https://s.taobao.com/search?q='+item_name)
html = response.text
regex = r'g_page_config =(.+)'
items = re.findall(regex, html)
items = items.pop().strip()
... |
import pdb
import sys
import simpleaudio as sa
import wave
import time
class infinite_array():
def __init__(self,inp):
self.standard_input = inp
def pop(self,*args):
return self.standard_input
def append(self,*args):
return None
class myPdb(pdb.Pdb):
play_obj = None
def... |
#!/usr/bin/env python3
from functools import partial
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import netCDF4 as nc4
from e3sm_case_output import E3SMCaseOutput, day_str
START_DAY = 1
END_DAY = 15
END_ZM10S_DAY = 19
START_AVG_DAY = 3
END_AVG_DAY = 15
DAILY_FILE_LOC... |
import time, math
start_time = time.time()
def prime_factor(number):
if number == 1:
return False
elif number < 4:
return True
elif number % 2 == 0:
return False
elif number < 9:
return True
elif number % 3 == 0:
return False
else:
r = math.floor(n... |
import RPi.GPIO as gpio
from time import sleep,time
#from Tkinter import *
from distance import distance_front, distance_rear
import random
def init():
gpio.setmode(gpio.BOARD)
gpio.setup(13, gpio.OUT) # Yellow wire
gpio.setup(15, gpio.OUT) # Green wire
gpio.setup(16, gpio.OUT) # Red wire
... |
import random
class Agent:
def __init__(self):
self.n = 5
def nextAction(self, percept):
return random.randint(0, self.n)
|
from json import *
from io import StringIO
class Edit(object):
def __init__(self):
self.value = 0
self.byte = 3
def changeValue(self, new):
self.value = new
def readValue(self):
return self.value
def __str__(self):
return str(self.__dict__)
class Editeur(obje... |
# Python functions for NucDynamics
import sys
import numpy as np
import multiprocessing
import traceback
PROG_NAME = 'nuc_dynamics'
DESCRIPTION = 'Single-cell Hi-C genome and chromosome structure calculation module for Nuc3D and NucTools'
N3D = 'n3d'
PDB = 'pdb'
FORMATS = [N3D, PDB]
MAX_CORES = multiprocessing.cpu_co... |
#!/usr/bin/env python
__author__ = "Master Computer Vision. Team 02"
__license__ = "M6 Video Analysis. Task 1"
# Import libraries
import os
import math
import cv2
import numpy as np
from evaluate import evaluate_sample
# Path to save images and videos
images_path = "std-mean-images/"
video_path = "background-subtrac... |
"""Calculates total volume of all selected elements."""
import clr
clr.AddReference('RevitAPI')
import Autodesk
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI import TaskDialog
clr.AddReference('RevitServices')
myDialog = TaskDialog("Volume Result:")
myDialog.MainInstruction = "Hello1"
myDialog.ExpandedContent... |
from django.core.management.base import BaseCommand
from django.conf import settings
from architect.manager.models import Manager
class Command(BaseCommand):
help = 'Synchronise Manager objects'
def handle(self, *args, **options):
for engine_name, engine in settings.MANAGER_ENGINES.items():
... |
#
# Copyright © 2021 Uncharted Software Inc.
#
# 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 l... |
from django.conf.urls import include, url
import views
urlpatterns = [
url(r'^handleRequest$',views.handleRequest),
]
|
# Generated by Django 2.0.2 on 2018-09-07 21:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inquiry', '0002_auto_20180719_1338'),
]
operations = [
migrations.AddField(
model_name='inquiry',
name='when_interes... |
from django.conf.urls import include, url
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.urls import reverse_lazy
from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView, RedirectView
from decorator_include import decora... |
class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(data=nodes.pop(0))
self.head = node
for elem in nodes:
node.next = Node(data=elem)
node = node.next
def __repr__(self):
... |
"""DeviceGroupRecords class."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from fmcapi.api_objects.device_services.devicerecords import DeviceRecords
from fmcapi.api_objects.device_ha_pair_services.ftddevicehapairs import FTDDeviceHAPairs
import logging
import warnings
class DeviceGroupRecords(... |
# Copyright 2020 Pulser Development Team
#
# 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 i... |
class Node:
def __init__(self,data = None, leftlink = None, rightlink = None):
self.__data = data
self.__left = leftlink
self.__right = rightlink
def getData(self):
return self.__data
def getLeft(self):
return self.__left
def getRight(self)... |
import numpy as np
from braindecode.analysis.create_amplitude_perturbation_corrs import load_exp_pred_fn
from braindecode.analysis.create_amplitude_perturbation_corrs import (
create_batch_inputs_targets_amplitude_phase,
perturb_and_compute_covariances)
from braindecode.paper.amp_corrs import transform_to_corr... |
#!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
import os
import json
from getpass import getuser
from collections import namedtuple
from subprocess import Popen
from tempfile import Named... |
# Copyright 2010-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = ['digraph']
from collections import deque
import sys
from portage import _unicode_decode
from portage.util import writemsg
class digraph(object):
"""
A directed graph object.
"""
def __init__(se... |
#!/usr/bin/env python3
#
# This is my code that will check if in my schedule that there is a "Monday" in it without a function, and prints the schedule's length.
#
def main():
mycalendar1 = """Day Time Subject
Monday 9:10 AM - 10:15 AM LA
... |
"""
Author: Ben Knisley [benknisley@gmail.com]
Date: 26 March, 2021
"""
import numpy as np
from scipy.signal import filtfilt, butter
def smooth_samples(samples):
"""
Smooths out any major waves crossing the 0-axis.
Normalizes values back around 0-axis, by using a Butterworth filter to
create a ... |
import numpy as np
x = np.zeros((3,5))
print(x)
print(x.nbytes) |
from django.apps import AppConfig
class RevenueExpendituresConfig(AppConfig):
name = 'revenue_expenditures'
|
def swap(st):
output = ''
for x in st:
if x in 'aeiou':
output+=x.upper()
else:
output+=x
return output
'''
When provided with a String, capitalize all vowels
For example:
Input : "Hello World!"
Output : "HEllO WOrld!"
'''
|
# THIS FILE HOUSES MAIN APPLICATION AND ENDPOINTS
# COMPLEX CALCULATION AND DB QUERIES SHOULD BE MADE ELSEWHERE
from flask import Flask, Response
from flask_cors import cross_origin, CORS
import json
import service.model_service as s
application = Flask(__name__)
cors = CORS(application)
@application.route("/anomal... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__),)
SECRET_KEY = '1+z60-pf0mz6_7ofaahfa*u_g7a95f(68r&1s-3#_+%0cymr_g'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.se... |
sv=int(input())
print(sv*2)
|
import requests
from urllib.parse import quote
import json
# first try
def example_parse_some_data():
url = "https://openlibrary.org/search.json?q=clean%20code"
return requests.get(url)
def example_get_some_json():
url = "https://openlibrary.org/search.json?q=clean%20code"
response = requests.get(url)
retur... |
from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=45)
author = models.CharField(max_length=45)
description = models.CharField(max_length=225)
class Meta:
... |
from flask_wtf import FlaskForm
from wtforms import PasswordField, SubmitField, StringField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired
class SignInForm(FlaskForm):
email = EmailField("Email", validators=[DataRequired()])
password = PasswordField("Пароль", validator... |
from utils import *
class Solver():
def __init__(self):
self.memory = {}
def solve(self,game):
hashed = hash(game.position)
if hashed in self.memory:
return self.memory[hashed]
else:
if game.PrimitiveValue() != Value.UNDECIDED:
self.... |
#!/usr/bin/env python
# ----------------------------------------------------------
# event MODULE for GlassCockpit procject RJGlass
# ----------------------------------------------------------
# This module will take the keys that are pressed on the keyboard and take appropriate action.
#
# Copyright 2009 Michael LaBri... |
import torch
import torch.nn
import cv2
import numpy as np
import pickle
import socket
import sys
import os
import time
from joblib import load
from PIL import Image
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import plot_confusion_matrix
from sklearn import prepr... |
#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc.
#
# 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 o... |
import serial
from drawnow import *
import matplotlib.pyplot as plt
import numpy as np
from datetime import date
import csv
arduino = serial.Serial('COM3', 9600)
beer_temps = []
fridge_temps = []
hours = []
plt.ion()
def makeFig():
plt.ylim(0, 35)
plt.title('Fermentation temperatures live')
plt.grid(True, which=... |
__author__ = 'Sebastian Bernasek'
import os
import matplotlib.pyplot as plt
class Base:
"""
Base class for figures providing some common methods.
Attributes:
data (pd.DataFrame) - data
fig (matplotlib.figure.Figure)
"""
# set default directory as class attribute
directory = 'graphic... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-07-05 17:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('manage_member', '0015_auto_20180705_1141'),
]
operations = [
migrations.Add... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Created By Liang Jun Copyright owned
import sys,os,math
import cv2 as cv
import numpy as np
VESSEL = [1,1,1];
ERYTHROCYTE = [0,255,0];
NEGATIVE = [0,0,255];
RangeType = 3; #5,7,9,11,13,15,21
# ["Nine-Box",
# "Sixteen-Box",
# "Five-Sixteen-Box",
# "Five-Sixteen-Box",... |
from unittest import TestSuite
from zope.testing import doctest
from Testing import ZopeTestCase as ztc
from z3c.table.testing import setUp
from z3c.table.testing import tearDown
optionflags = (
doctest.REPORT_ONLY_FIRST_FAILURE |
doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
def te... |
"""
Find the Largest Even Number
Write a function that finds the largest even
number in a list. Return -1 if not found.
The use of built-in function max() is prohibited.
Examples:
largest_even([3, 7, 2, 1, 7, 9, 10, 13]) ➞ 10
largest_even([1, 3, 5, 7]) ➞ -1
largest_even([0, 19, 18973623]) ➞ 0
Notes:
Consider using t... |
# -*- coding: utf-8 -*-
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
#Main of window
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 440)
MainWindow.setMinimumSize(QtCore.QSize(800, 550))
MainWindow.setMaximumSize(Q... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'numfields.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):... |
#!/usr/bin/env python
import os
import platform
from setuptools import setup, find_packages
from torch.utils.cpp_extension import BuildExtension, CppExtension
def check_env_flag(name, default=''):
return os.getenv(name, default).upper() in set(['ON', '1', 'YES', 'TRUE', 'Y'])
DEBUG = check_env_flag('DEBUG')
eca... |
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
import numpy as np
import pandas as pd
from polyglot.detect import Detector
from langdetect import detect
from polyglot.detect.base import logger as polyglot_logger
from tqdm import tqdm
tqdm.pandas()
polyglot_logger.setLevel("ERROR")
n... |
#!/usr/bin/python
import numpy as np
import pylab as py
from COMMON import nanosec,yr,week,grav,msun,light,mpc,hub0,h0,omm,omv
from scipy import integrate
import pyPdf,os
from matplotlib import colors
print 'THERE IS SOMETHING WRONG WITH THE AXES!!!!!!!!!!!'
#Input parameters:
maxreds=100 #Maximum redshift considered... |
from tkinter import *
from sudoku import Sudoku |
# coding=utf-8
#noinspection PyUnresolvedReferences
from paypal.interface import PayPalInterface
#noinspection PyUnresolvedReferences
from paypal.settings import PayPalConfig
#noinspection PyUnresolvedReferences
from paypal.exceptions import PayPalError, PayPalConfigError, PayPalAPIResponseError
#noinspection PyUnresol... |
# -*- coding: utf-8 -*-
import os
import sys
import tempfile
from contextlib import contextmanager
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
if sys.version_info < (3,):
import codecs
def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
def u(x):
return x
@contex... |
# -*- coding: utf-8 -*-
import urllib2
import requests
import lxml.html
import types
import codecs
import csv
class get_data:
def __init(self,url):
self.url = url
html = urllib2.urlopen(url)
self.source = lxml.html.fromstring(html.read())
def __get_url(self):
return raw_input(... |
import requests
from bs4 import BeautifulSoup
import json
import random
import os
import sqlite3
# import reqiests
# from lxml import etree ---xpath
def find():
urls = 'https://www.1905.com/api/content/index.php'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
... |
#지역변수 => 파이썬은 예외가 많아요
print("\n===함수 내부 변수1===")
#함수 호출시 인자를 전달할때 변수의 데이터만 전달
#함수 안과 밖은 이름은 같지만 다른변수가 존재할 수 있다.
a = 1 #100
def test(a): #200
a += 1
print("함수 호출 전 a : %d"%a)
test(a)
print("함수 호출 후 a : %d"%a)
del a
print("\n===함수 내부 변수2===")
def test():
#함수 내부에서 선언된 변수 => 함수가 끝나면 없어지는 변수
a ... |
# A class for communicating in Go Text Protocol
#
# An already-connected socket should be passed in, then this class
# can be used to handle some aspects of GTP simply
# Commands that any user of this class *must* support...
# quit
# boardsize
# clear_board
# komi
# play
# genmove
class GTPSocket:
# By default t... |
from django.apps import AppConfig
class CalculationConfig(AppConfig):
name = 'calculation'
verbose_name = 'Калькуляция'
|
class Class1():
var1 = 100
var2 = 0.1
var3 = 'asdf'
def fun1(self):
print('我是fun1')
print('var1=',self.var1)
def fun2(self):
print('我是fun2')
print('var2=',self.var2)
def fun3(self):
print('我是fun3')
print('var3=',self.var3)
A = Class1()#实例化
A.fun1()
A.fun2()
A.fun3() |
import optuna
from tuneup.util import dilate
from optuna.logging import CRITICAL
def optuna_cube(objective,scale, n_trials):
def cube_objective(trial):
u1 = trial.suggest_float('u',1e-6,1-1e-6)
u2 = trial.suggest_float('u',1e-6,1-1e-6)
u3 = trial.suggest_float('u',1e-6,1-1e-6)
ret... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import collections
import pathlib
import time
import typing as t
from .. import TE
from ..dataset import Dataset
from ..indicator import ThreatIndicator
from ..content_type import meta
from . import command_base
class Experi... |
# from data_process.train_dataset import RegularDataset
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Dataset
import os.path as osp
from PIL import Image
import numpy as np
from torchvision import transforms
from torchvision import utils
from u... |
# coding: utf-8
# In[2]:
import os
import numpy as np
import json
import pandas as pd
import sklearn
import xgboost as xgb
from sklearn import cross_validation
get_ipython().magic('matplotlib inline')
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accurac... |
developer A : line1
developer B: line 1
|
from tkinter import *
import os
def register_user():
username_info = username.get()
password_info = password.get()
file=open(username_info, "w")
file.write("Username:\n")
file.write(username_info +"\n")
file.write("Password:\n")
file.write(password_info)
file.close()
... |
from django.shortcuts import render, reverse
from django.http import HttpResponse, HttpResponseRedirect
from batchthis.models import Batch, Fermenter, BatchTestType, BatchNoteType
from django.shortcuts import get_object_or_404
from .forms import BatchTestForm, BatchNoteForm, BatchAdditionForm, RefractometerCorrectionFo... |
#打印九九乘法表
'''
for i in range(1,10):
for j in range(1,i+1):
print('{0}*{1}={2}'.format(i,j,i*j),end='\t')
print()
#使用列表和字典存储表格和数据
r1=dict(name='vgh',age=17,salary=30000,city='beijing')
r2=dict(name='ghj',age=17,salary=20000,city='beijing')
r3=dict(name='mnn',age=17,salary=15000,city='beijing')
r=[r1,r2,r... |
from bsp.leveleditor.DocObject import DocObject
# Base class for serializable map data
class MapWritable(DocObject):
ObjectName = "writable"
def __init__(self, doc):
DocObject.__init__(self, doc)
def writeKeyValues(self, keyvalues):
raise NotImplementedError
def readKeyValues(self, ... |
#!/usr/bin/env python3
__appname__ = '[models.py]'
__author__ = 'Pablo Lechon (plechon@uchicago.edu)'
__version__ = '0.0.1'
## IMPORTS ##
import numpy as np
## FUNCTIONS ##
def lotka_volterra(t, N, params):
'''
Differential equations of a GLV
Parameters:
s (int): number of species... |
# -*- coding: utf-8 -*-
def cambiar(cantidad):
tipo_cambio=18.81
return cantidad/tipo_cambio
def main():
print('Calculadora de Dolares')
print('')
cantidad=float(input('Ingresa la cantidad de pesos que quieres convertir:'))
result=cambiar(cantidad)
print('${} p... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT... |
from typing import Any
from typing import List
from typing import Optional
from fastapi import HTTPException
from pydantic_aioredis import Model
class FastAPIModel(Model):
"""
Useful with fastapi, offers extra class methods specific to using pydantic_aioredis with Fastapi
"""
@classmethod
async... |
import random
import math
import matplotlib.pyplot as plt
from collections import Counter
l2c = 16.65
f4c = 0
f8e = 0
l4e = 0
three = 0
stat = []
for i in range(100):
result = 0
f4c = random.uniform(104.64,180)
for j in range(math.floor(f4c)):
f8e = random.uniform(150,183.2)
for k in range(math.floor(f8e)):
... |
import json
import os
import requests
API_VERSION = "2019-11-01"
def get_secrets():
with open("keys.json") as file:
secrets = json.load(file)
return secrets
def authenticate_to_azure(secrets) -> str:
"""
Function to authenticate to Azure as a service principal via OAUTH2
"""
tenant... |
##Linear Regression##
#----------Preparing the data ----------#
#%%
import numpy as np
import matplotlib.pyplot as plt
X = 2 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.randn(100, 1)
X_new = np.array([[0], [2]])
#---------- Linear Regression ----------#
#%%
from sklearn.linear_model import LinearRegression
lin_... |
from selenium import webdriver
class SeleniumDriver:
def __init__(self, selenium_driver):
self.driver = selenium_driver
def browser():
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
return driver
|
# -*- coding: utf-8 -*-
"""Tests using the intermediate test class."""
import unittest_templates
from tests import constants
from tests.constants import A, B, BaseLetter
class TestA(constants.TestLetter):
"""Tests for A."""
cls = A
class TestB(constants.TestLetter):
"""Tests for a B."""
cls = B
... |
#_calculate_basin_statsgo_summary.py
#Cody Moser
#cody.moser@amec.com
#AMEC
#Description: calculates basin % soil class from .csv files
#import script modules
import glob
import os
import re
import numpy
import csv
####################################################################
#USER INPUT SECTIO... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-08-14 21:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20190813_0813'),
]
operations = [
migrations.AlterField... |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure the link order of object files is the same between msvs and ninja.
"""
import TestGyp
import sys
if sys.platform == 'win32'... |
#coding=UTF-8
x = 10
if x >= 0:
y = 1
else:
y = -1
print(y)
y = 1 if x >= 0 else -1
print(y)
def f(x):
return 1 if x >= 0 else -1
print(f(x))
|
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
from cloudinary.models import CloudinaryField
from django.db.models.fields import DateTimeField
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils imp... |
from typing import Optional
import torch
from torch.nn import CrossEntropyLoss
from transformers import (
BertForSequenceClassification,
ElectraForSequenceClassification,
)
class CachedInferenceMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.use_cache ... |
import cv2 as cv
import numpy as np
import os, argparse, yaml
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--filename', type=str, default='[VCB-Studio]Hyouka[05][BDRip][720p][x264_aac].mp4', help='Filename of input video')
parser.add_argument('--input_dir', type=str, default='... |
'''
class for prepping shapefiles and selecting the shapes we will use in the predictor class
'''
import pandas as pd
from .utils import *
class PrepShapes():
def __init__(self, dataOrFileName, shapeNameColDict:Optional[dict]=None, boundaryBuffer:int=12000):
'''
Class for prepping shapefiles. Used... |
import unittest
import monoalphabetic
class TestMonoalphabeticCipher(unittest.TestCase):
def test_string_without_space(self):
plaintext = 'defendtheeastwallofthecastle'
key = 'qmrhsnxbwpgjauoecklfzyvtdi'
ciphertext = 'hsnsuhfbssqlfvqjjonfbsrqlfjs'
self.assertEqual(ciphertext, monoa... |
import json
from flask import request, jsonify, g
from web.controllers.api import route_api
from common.models.food.Food import Food
from common.models.member.MemberCart import MemberCart
from common.libs.member.CartSerivce import CartService
from common.libs.Helper import selectFilterObj,getDictFilterField
from comm... |
import pytest
import os
from pydodo import episode_log
from pydodo.bluebird_connect import ping_bluebird
bb_resp = ping_bluebird()
@pytest.mark.skipif(not bb_resp, reason="Can't connect to bluebird")
def test_eplog():
pytest.xfail("BlueBird currently does not return a log.")
filepath = episode_log()
a... |
import numpy as np
import pandas as pd
import os
import datetime
def realizedVolatility(series): # 计算波动率
series = series.set_index('date')
resampled = series.resample('W').last().ffill()
resampled['log_ret'] = np.log(resampled['adjust_net_value']/resampled['adjust_net_value'].shift(1))
vola = resampled... |
import json
none = "d3043820717d74d9a17694c176d39733"
# region ASG
class ASG:
def __init__(
self,
product=none,
spot_instance_types=none,
name=none):
"""
:type product: str
:type spot_instance_types: List[str]
:type name: str
"""
self.product = product
self.spot_instance_types = spot_instance... |
import numpy as np
import cv2
from imutils import imutils
# translations
image = cv2.imread("/home/mmc/code/python_opencv/Books/Practical Python and OpenCV, 3rd Edition/code/images/trex.png")
M = np.float32([[1, 0, 25], [0, 1, 50]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape
[0]))
cv2.imshow("Shif... |
# Copyright 2010 Alon Zakai ('kripken'). All rights reserved.
# This file is part of Syntensity/the Intensity Engine, an open source project. See COPYING.txt for licensing.
"""
Some extremely basic things for our system. Among the first modules loaded, useful in
loading the others in fact.
"""
import os, sys, __main... |
import unittest
from katas.kyu_7.exes_and_ohs import xo
class XOTestCase(unittest.TestCase):
def test_true(self):
self.assertTrue(xo('xo'))
def test_true_2(self):
self.assertTrue(xo('xo0'))
def test_false(self):
self.assertFalse(xo('xxxoo'))
|
# This module automates pixels
#
# Use this like:
# pixels1 = neopixel.NeoPixel(board.A1, 20, brightness=0.2, auto_write=False)
# p = EPixels(pixels1)
# p.setAll(0xff0000) # red
# p.setDisableMask(10, 0) # stops a bad pixel
import time
class EPixels:
def __init__(self, pixels):
self.pixels = pixel... |
#Models creates the database
from django.db import models
from django.utils import timezone
#table
class Billboard(models.Model):
created_date = models.DateTimeField(default=timezone.now)
title = models.CharField(max_length=200)
text = models.TextField(max_length=2000)
author=models.CharField(max_le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.