text stringlengths 8 6.05M |
|---|
# Generated by Django 2.1.2 on 2018-11-07 22:53
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('misPerrisDJ', '0015_auto_20181107_1932'),
]
operations = [
migrations.AlterField(
mo... |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tf_util.systems import system_from_str
from train_dsn import train_dsn
import sys
from util import fct_integrals as integrals
from util import tf_integrals as tf_integrals
from util import fct_mf as mf
def compute_bistable_mu(Sini, ics_0,... |
from breezypythongui import EasyFrame
def computeDistance(height, index, bounces):
pass
class BouncyGUI(EasyFrame):
def __init__(self):
EasyFrame.__init__(self, title = "Bouncy")
self.addLabel(text = "Initial Height",row = 0, column = 0)
self.heightField = self.addIntegerField... |
# -*- coding: utf-8 -*-
# filename: ZeroAI.py
#from wordcloud import WordCloud, STOPWORDS
import mysql.connector
import mypsw
import time
import datetime
#import matplotlib.pyplot as plt
from basic import Basic
#from poster.streaminghttp import register_openers
import requests
from requests.packages.urlli... |
import random
def roll(number_of_dice=5):
"""
Roll the indicatednumber of 6 sided dice using a random number generator
# Use the seed so our output is always reliable
>>> random.seed(1234)
>>> roll(5)
[1, 1, 1, 4, 5]
"""
return sorted(random.choice((1,2,3,4,5,6))
for i in range... |
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.mixins import UserPassesTestMixin
from django.urls import reverse_lazy
from issues.models import Employee
##### For function-based view #####
LOGIN_URL = 'login_view'
def at_least_... |
import turtle
canvas = turtle.Screen()
canvas.bgcolor("lightgreen")
tess=turtle.Turtle()
tess.color("blue")
tess.pensize(2)
tess.speed(200)
s=1
for i in range(99):
tess.right(90)
tess.forward(s)
s+=2
tess.stamp()
tess.penup()
tess.left(45)
tess.forward(200)
tess.pendown()
l=1
for i in range(99):
... |
import torch as T
from torch.utils.data import Dataset
import pandas as pd
import os
import numpy as np
from . import feature
from . import preprocessing as prep
from . import processing as pro
class MolData(Dataset):
"""Custom PyTorch Dataset that takes a file containing \n separated SMILES"""
def __init__(s... |
import Adafruit_BBIO.UART as UART
import serial
from imu3000 import imu3000
from time import sleep
_TIMEOUT = 1
def openUart():
"""
Opens UART1 (TX = 24, RX = 26). Returns true if successful.
"""
UART.setup("UART1")
ser = serial.Serial(port = "/dev/ttyO1", baudrate=9600, timeo... |
from django.views.generic import TemplateView
class RegistrationIndex(TemplateView):
template_name = "registration/index.html"
|
#!/usr/bin/env python3
"""wcount.py: count words from an Internet file.
__author__ = "Wangkunhao"
__pkuid__ = "1800011715"
__email__ = "1800011715@pku.edu.cn"
"""
import sys
from urllib.request import urlopen
def count(lines):
words = []
word = []
state = 0
nums = dict()
for l... |
import math
import time
def distance(x1,y1,x2,y2):
print("Calculating distance ...")
time.sleep(1)
space = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print("Distance :",space)
distance(4,0,6,6) |
import numpy as np
import pandas as pd
# select the vender has max sell log
raw_data = pd.read_csv('./sales_month_item.csv').as_matrix()
raw_data = np.delete(raw_data, 0, axis = 0) # remove top 1 row
raw_data = np.delete(raw_data, 0, axis = 1) # remove left 1 column
data = raw_data
raw_data = raw_data.tolist();
maxCou... |
"""Строит простой график квадратов чисел от 0 до 10"""
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5]
def squares():
"""Рассчитывает квадраты чисел."""
square = []
for i in input_values:
square.append(i * i)
return square
def plt_settings():
"""Настройки отображения графи... |
import time
x=int(input("Please enter the first number :"))
y=int(input("Please enter the second number :"))
print("Calculating sum :")
time.sleep(1)
sum=x+y
print("Sum :",sum)
time.sleep(1)
if (sum>15) and (sum<20):
print("As the sum of the 2 inputs is between 15 and 20 ...")
time.sleep(1)
print("Sum :",2... |
import os, sys, re
from django.core.files import File
from django.core.files.storage import get_storage_class
from django.conf import settings
from api_docs.models import *
class Importer(object):
def __init__(self, topic, language, version, section=None, options=dict()):
self.topic = topic
self... |
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
vf = np.vectorize(sigmoid)
def predict(input_vector):
assert(input_vector.shape==(4,1))
# taking weighted sum
wsum0_vector = np.dot(w01, input_vector)
# activating
h1_layer = vf(wsum0_vector)
# taking weighted sum
wsum1_vector = np.dot(w10, h1_... |
import math
val = math.factorial(5)
def fact(n):
val = 1
for i in range(2,n + 1):
val *= i
return val
for i in range(1,10):
print('fact({})={}'.format(i,fact(i)))
|
import os
import nltk
from pytest import fixture
from genderbias.document import Document
porter = nltk.PorterStemmer()
wnl = nltk.WordNetLemmatizer()
example_dir = os.path.dirname(__file__) + "/../example_letters/"
examples = {'m': dict(file=example_dir + "letterofRecM", sentences=13, commas=12, words=446),
... |
from NextVersion import nextVersion
#verify that the function output matches the expected output
def verifyFunctionOutput(functionOutput, expectedOutput):
return (functionOutput == expectedOutput)
#verify that the function doesn't match the given output
def verifyFunctionOutputIncorrect(functionOutput, output):
... |
from .api import Api # noqa
from .client import Client # noqa
from .error import * # noqa
from .models import * # noqa
from .utils.constants import TOPICS # noqa
|
#!/usr/local/bin/python
# By: Kyle Finley
# Description: Creates a CSV of all snapshots in an AWS account for auditing
import boto3
from botocore.client import Config
import csv
#- Enables support for multiple Named Profiles -#
profile = None
session = None
while session == None:
profile = raw_input('AWS Named Profile... |
import sys
import threading
from src.tcp import read_request, handle_request, write_response
from src.tcp.tcp_server import create_server_socket, accept_connection
def serve_client(client_socket, cid):
request = read_request(client_socket)
if request is None:
print(f"Client #{cid} disconnected.")
... |
import torchtext
from torchtext import data
from torchtext import datasets
import copy
import torch
import os
from collections import Counter, OrderedDict
import argparse
parser = argparse.ArgumentParser(description='Build a vocabulary for Transformer.')
parser.add_argument('--data_path', type=str, default='./')
pars... |
#------------------------------------------------------------------------------------------------------------------
# train_test_plot_def
#
# MIT License
# Dr Debdarsan Niyogi (debdarsan.niyogi@gmail.com)
#-----------------------------------------------------------------------------------------------------------------... |
import numpy as np
def create_image_cppn_input(output_size, is_distance_to_center=True, is_bias=True, input_borders=((-1, 1), (-1, 1))):
img_height = output_size[0]
img_width = output_size[1]
num_of_input = 2
if is_distance_to_center:
num_of_input = num_of_input + 1
if is_bias:
n... |
from vcenter_connect import add_disk
virtualmachine_name = raw_input("enter virtual machine name:")
disk_size = raw_input("Enter Disc size in GB:")
disk_type = raw_input("Enter Disc type:")
if add_disk(virtualmachine_name,disk_size,disk_type):
print "Disc created"
else:
print "Something went wrong"
|
class Administrator():
def __init__(self,orders):
self.count = 0
self.orders = orders
def enter(self):
print("\nLogin: ")
login = input()
print("\nPassword: ")
password = input()
self.data = login + " " + password
return self
def exit(self):... |
import ast
class SubAttr(object):
def __init__(self):
self._SubAttrName = ""
self._SubAttrLabel = ""
self._IsTypeString = False
self._IsTypeInteger = False
self._IsTypeFloat = False
self._IsTypeDate = Fa... |
hrs = input("Enter Hours:")
h = float(hrs)
rte = input("Enter Rate:")
r = float(rte)
if hrs > 40:
pay = (h - 40) * (r * 1.5) + (40 * r)
else:
pay = (h * r)
print(pay)
|
"""Class to represent the Busy State
"""
import os
import signal
import logging
import subprocess # nosec #pylint-disable type: ignore
import alsaaudio
import requests
from ..hotword_engine.stop_detection import StopDetector
from ..speech import TTS
from .base_state import State
from .lights import lights
logger ... |
# Generated by Django 2.0.7 on 2018-09-15 21:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TraverMsg', '0005_auto_20180915_0057'),
]
operations = [
migrations.AlterField(
model_name='citymsg',
name='img_url'... |
"""
CCT 建模优化代码
A09粒子运动工具类 ParticleRunner 示例
作者:赵润晓
日期:2021年4月29日
"""
from os import error, path
import sys
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
from cctpy import *
# ParticleRunner 类提供了粒子在磁场中运动的函数
# 计算方法包括自己实现的 runge_kutta4 法(GPU加速时也是用这一方法)
# 另外还有 scipy 包提供的 ode 法,这个方法更智能,可以自动调整积分步长
... |
# http://www.codeskulptor.org/#user43_fAwSFN88Y7_0.py
# implementation of card game - Memory
import simplegui
import random
# helper function to initialize globals
def new_game():
global list1,exposed,state,turns,pre_index1,pre_index2
list1 = range(0, 8)
list2 = range(0, 8)
list1.extend(l... |
from .petscmat import *
from .residual import *
from .DREAMEqsys import DREAMEqsys
from .DREAMEqsysUnknown import DREAMEqsysUnknown
|
# Copyright (c) 2018 Amdocs
#
# 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... |
#!/usr/bin/env python
#coding=utf-8
import pymongo
import sys
def get_collection():
mongo = pymongo.Connection("master", 27017)["weibo"]
return mongo["text"]
def run():
reload(sys)
sys.setdefaultencoding('utf-8')
collection = get_collection()
tf = dict()
for blogText in collection.find({... |
#!/usr/bin/env python
#-*- coding:UTF-8 -*-
import os
path='/home/zr/documents/KCFcpp/resource/blanket'
f=open("images.txt",'w')
for pic in os.listdir(path):
f.write(os.path.join(path,pic)+'\n')
f.close()
|
from math import *
from utils import get_primes
import sys
import pickle
sys.setrecursionlimit(10000)
m = 100000
k = 2
primes = get_primes(m)
def rec(prod, n, k):
if n <= 1:
return prod
p = primes[k]
if n % p == 0:
prod *= p
while n % p == 0:
n /= p
return rec(pro... |
import HW7.CalibrationSettings as CalibSets
import HW7.CalibrationClasses as CalibCls
# create a calibration object
calibration = CalibCls.Calibration()
# sample the posterior of the mortality probability
calibration.sample_posterior()
# estimate of annal mortality probability and the 95% credible interval
print('Es... |
import boto3
import uuid
def lambda_handler(event, context):
username = event["username"]
income = event["income"]
rent = event["rent"]
food = event["food"]
transportation = event["transportation"]
recreation = event["recreation"]
print('Generating new DynamoDB record, with ID: ' + username... |
import re
import requests
from bs4 import BeautifulSoup
import os
from random import randrange
import json
#Borramos la ultima coma del archivo nuevos.txt
with open('./nuevos.txt', 'ab') as filehandle:
filehandle.seek(-1, os.SEEK_END)
filehandle.truncate()
filehandle.close()
#Guardamos en array_enlaces_nuev... |
# Generated by Django 3.1.5 on 2021-02-26 06:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JOB', '0004_reqruiteruser'),
]
operations = [
migrations.AddField(
model_name='reqruiteruser',
name='type',
... |
# 感觉挺有意思
# 依次把最大的放到底下,这样翻转上面的就不会影响
# 先把最大的放在最上面,再翻转一次到指定位置
# NP困难问题
class Solution:
def pancakeSort(self, arr: List[int]) -> List[int]:
ans = []
for n in range(len(arr), 1, -1):
index = 0
for i in range(n):
if arr[i] > arr[index]:
index = ... |
PROJECTNAME = "AutocompleteWidget"
SKINS_DIR = 'skins'
GLOBALS = globals() |
from setuptools import setup
setup(
name='dlpdb',
packages=['dlpdb'],
author='Andrew Jewett',
author_email='jewett.aij@gmail.com',
description='collect statistics from the entire PDB library',
long_description='A collection of tiny scripts to help automate the process of downloading and extracting ... |
from lib.experiment import Experiment
from lib import scheduler, utils
experiment = Experiment(N=1000, M=5000, t_max=10000, beta_scheduler=scheduler.ConstantBetaScheduler(0.5),
algorithm="Metropolis", batch_size=None, use_gpu=False)
errors, energies, x = experiment.run()
utils.plot_errors_ener... |
import factory
from archives.models import Archive
from credentials.tests.factories import SshKeyPairFactory
class ArchiveFactory(factory.DjangoModelFactory):
FACTORY_FOR = Archive
name = factory.Sequence(lambda n: "Archive %d" % n)
host = "archive.example.com"
policy = "cdimage"
basedir = "/var... |
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.forms import ModelForm
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
cr... |
from scrapers.asosmen import AsosMenScraper
if __name__ == "__main__":
scraper = AsosMenScraper()
scraper.run()
|
"""Restaurant rating lister."""
# put your code here
import sys
import random
filename = sys.argv[1]
my_file = open(filename)
restaurants_dict = {}
for line in my_file:
words_list = (line.rstrip()).split(':')
restaurants_dict[words_list[0]] = int(words_list[1])
while True:
print("Please select o... |
# file r 只读模式
# 文件不存在会出错
file1 = open("file1", "r")
# 方法一
# data = file1.readlines()
# for i in data:
# print(i.strip())
# 方法二
# for i, j in enumerate(file1.readlines()):
# print(i+1, j.strip())
# 方法三
for i, j in enumerate(file1):
print(i+1, j.strip())
file1.close() |
import numpy as np
from joblib import Parallel, delayed
import timeit
import time
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from .BaseCrossVal import BaseCrossVal
from ..utils import binary_metrics, dict_perc, dict_median
class holdout(BaseCrossVal):
""" Exhaustitive search over p... |
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--validation',
action='store_true',
default=False,
help='To split validation or not.')
parser.add_argument('--train_filename',
default='data/train.csv',
help='... |
import cv2
# Basic functions - resizing image, need to know current image size first
img = cv2.imread("images/profile.jpg")
print(img.shape) # ex output: (1364, 1364, 3) (height, width, # for channel so VGR)
imgResize = cv2.resize(img, (1000, 500))
# Crop image
imgCropped = img[0:200, 200:500] # dont need to use cv ... |
from flask import Flask, render_template, request, url_for, flash, session, redirect
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, IntegerField, validators
from passlib.hash import sha256_crypt
from functools import wraps
from flask_socketio import SocketIO, emit
f... |
# !/usr/bin/env python
# encoding: utf-8
import sys
import os
import json
import datetime
import time
import bisect
import pandas as pd
from functools import total_ordering
class Account(object):
"""Docstring for Account. """
def __init__(self):
"""TODO: to be defined1. """
def order(self, order... |
from report import Report
from server import Server
from travis import Travis
|
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
return all(
any(l <= el <= r for l, r in ranges) for el in range(left, right + 1)
)
if __name__ == "__main__":
solution = Solution()
... |
from django.core.exceptions import ValidationError
from django.test import TestCase
from pycont.apps.accounts.models import Account
from pycont.apps.transactions.models import Transaction
class AccountModelTestCase(TestCase):
fixtures = ['users', 'accounts']
def test_created(self):
emitter = Account... |
import rumps
import os
from subprocess import call
FILE_NAME_STATUS = "gapak"
class Gapa(rumps.App):
def __init__(self, name):
super().__init__(name, icon='images/circle.png', menu=['Toggle Desktop Items', None, 'Quit'], quit_button=None)
try:
with open(FILE_NAME_STATUS, "r") as fil... |
# Full web stack No browser required
# PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast andnative support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG
# http://phantomjs.org/examples/index.html
|
import urllib.request as fetch
import re
from time import sleep
from random import random
from pymongo import MongoClient as mc
ikea = 'http://www.ikea.com'
client = mc()
db = client.IKEA
furniture = db.core_furniture
todo=furniture.find({'done':2})
i=todo.count()
for each in todo:
_id = str(each['id'])
print... |
import tensorflow as tf
from src.main.utils.decorators import lazy_property
class Dataset(object):
def __init__(self, features, target, batch_size):
self.feature_data=features
self.target_data=target
self.batch_size=batch_size
self.features
self.target
self.features... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# sleep 强制等待,缺点是对设置的时间参数不同场景不好把握
# implicitly_wait 隐式等待,缺点是设置对全局生效,若查找元素失败后会一直进行查找,知道超过设置的等待时间
# WebDriverWait 显示等待,通过until和until_not自定义等待条件
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_condition... |
import logging
from tinydb import TinyDB, Query
from collectors.exceptions import DuplicateFound
from storage import Storage
logger = logging.getLogger(__name__)
class StorageTinyDB(Storage):
def __init__(self, db_filename):
super().__init__()
self.db_filename = db_filename
self.db = Ti... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Disallow 'await' in a loop."""
from __future__ import annotations
import ast
from contextlib import contextmanager
from pathlib import PurePath
from typing import Iterator, Sequence
d... |
from synergy import SynergyServer
synergy_server = SynergyServer()
synergy_server.create_room('Global', default_room=True)
synergy_server.start()
"""
From a websocket client:
Sent: {"request": "authenticate", "aid": "c9f93756-2ff6-40aa-8824-2409d7113818"}
Received: {"request": "authenticate", "authenticated": tr... |
# 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... |
import time
start_time = time.time()
fibonacchi = [1, 2]
sum = 2
while fibonacchi[-1] < 4000000:
fibonacchi.append(fibonacchi[-1]+fibonacchi[-2])
if fibonacchi[-1] % 2 == 0 and fibonacchi[-1] < 4000000:
sum += fibonacchi[-1]
print(sum)
print("Elapsed Time: ",(time.time() - start_time)) |
from django.shortcuts import render
# Create your views here.
from django.http import JsonResponse
from src.wrappers import alcohol_limit
from src.singletons import sku_match
import json
from src.expression import Item
from src.Utils.logger import logger
sku_matcher_singleton = sku_match.SkuSingleton()
def check_alc... |
from django.shortcuts import render, HttpResponse
# def index(request):
# response = "Hello, I am your first request!"
# return HttpResponse( response )
def index(request):
print '*' * 100
return render( request, 'first_app/index.html' )
|
import pandas as pd
# get all progress sites
from work.controller import getSiteProgressdf
dfProgressSites = getSiteProgressdf()
# 1: get all hh habs
from consumers.models import Consumer
from django.db.models import Count, F, Q
cs = Consumer.objects.all()
# cshabs = cs.values('site__origin__hab_id','site__hab_id','s... |
import os
import sys
import pickle
import argparse
import logging
from utils import *
from simulate import *
from stem.descriptor import parse_file, DocumentHandler
import stem.descriptor.reader as reader
def find_desc(descs, consensus_paths, desc_writer):
"""
Find descriptors pertaining to a particular cons... |
print(3 + 5)
print(7 - 4)
print(3 * 2)
print(6 / 7)
print(2 ** 2)
# PEMDAS
# Paranthesis
# Exponent
# Multiplication
# Division
# Addition
# Subtraction
|
# Generated by Django 3.0.8 on 2020-08-14 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fhblog', '0005_post_snippet'),
]
operations = [
migrations.AddField(
model_name='post',
name='post_thumbnail_image',... |
import math
from collections import defaultdict
from subprocess import call
import numpy as np
import torch
from squirrel.data.batch import merge_batches, split_batch
from squirrel.decoder import valid_model, valid_model_ppl
from squirrel.optimizer import Adam
from squirrel.utils import Timer, format, gather_dict, it... |
# coding: utf-8
import csv
import pandas as pd
import requests
import time
import json
import datetime
from InstagramAPI import InstagramAPI
from sklearn.externals import joblib
import datetime
import random
import traceback
import os
import sys
from config import user, password
def print_m(message):
""" Функция... |
# 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... |
import requests
from requests.models import Response
import os
import json
from mockito import when, mock, unstub
from form_reader import FormReader
headers = {
'content-type': 'application/json',
'authorization': 'token ' + os.environ["GITHUBTOKEN"]
}
form_url = "https://github.ncsu.edu/test/HW0-51... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return '(name:%s)' % self.name
__repr__ = __str__
print(Student('tangdu')) |
from django.conf.urls import url
from cms import views
urlpatterns = [
# 記事
url(r'^article/$', views.article_list, name='article_list'), # 一覧
url(r'^article/add/$', views.article_edit, name='article_add'), # 登録
url(r'^article/mod/(?P<article_id>\d+)/$',
views.article_edit, name='article_mod'... |
#coding:utf-8
#!/usr/bin/env python
from django.shortcuts import render
from gclib.DBConnection import DBConnection
from django.http import HttpResponse
from gclib.json import json
from gclib.config import config
from excel_import import excel_import
def index(request):
return render(request, 'index.html', {})
def... |
from django.contrib.auth.models import User
from django.utils import timezone
from locations.models import Page
from django.conf import settings
from django.db import models
import datetime
class Question(models.Model):
""" Represents a question. """
objects = models.Manager()
quiz = models.ForeignKey(Page... |
import pandas as pd
import numpy as np
from random import randint
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pylab as pylab
from scipy import stats
# you need at least 2000 games to get a good result
log = pd.read_csv("/home/andras/PycharmProjects/TradingGame/logs/percentChange.csv", se... |
# -*- coding: utf-8 -*-
# This file is part of the pyMor project (http://www.pymor.org).
# Copyright Holders: Felix Albrecht, Rene Milk, Stephan Rave
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
import numpy as np
from ... |
# I pledge my honor that I have abided by the Stevens Honor System - Owen Gresham
def isDateValid(date):
daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
dateVals = date.split("/")
if len(dateVals) != 3:
print("Invalid date")
return
month = int(dateVals[0])
day = int... |
import setuptools
import coin
def get_package_description() -> str:
"""Returns a description of this package from the markdown files."""
with open("README.md", "r") as stream:
readme: str = stream.read()
return readme
setuptools.setup(
name="coin",
version=coin.__version__,
author="... |
#
# Runs two NerTagger's models on given PostgreSQL collection.
# Finds differences between NE annotations produced by two models.
# The collection must have input_layers required by NerTagger.
#
# Outputs summarized statistics about differences, and writes all differences into a
# file. The output will be wr... |
"""System module."""
from webapp import myapp
app = myapp()
client = app.test_client()
def test_root():
"""A dummy docstring."""
url = "http://localhost:5000/"
response = client.get(url)
print(response.data)
assert response.data == b'Hello World!'
def test_health():
"""A dummy docstring."""
... |
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #I pledge my honor that I have abided by the Stevens Honor System -Kyriacos Petrou
>>> #valid date code
>>> def main():
date = input("Enter the dat... |
import cv2
import tensorflow as tf
import sys
DATADIR = "../ruap_data/test/"
IMG_SIZE = 350
IMG_NAME = sys.argv[1] if len(sys.argv) > 1 else "somevalue"
#prilagodba slike za testiranje
def prepare(filepath):
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, I... |
# -*- coding : utf-8 -*-
import path_helper as ph
import file_updater as fu
import log
root_path = ph.get_root_path()
all_java_files = ph.list_all_java_file(root_path)
log.log(len(all_java_files))
for java_file in all_java_files:
log.i("Modifying: ", java_file)
fu.update_file(java_file) |
import matplotlib.pyplot as plt
def set_size(width=17, height=4):
"""Pretty doll function to reshape plot box in notebook"""
plt.rcParams['figure.figsize'] = [width, height]
def set_style(style='seaborn-deep'):
""""Set plot style"""
try:
plt.style.use(style)
except OSError:
raise... |
#input="taco cat"
def palindromePermutation(string):
#Defining a freq table to store the frequency of characters
#removal of all characters which are not letters
freq={}
for i in string:
if(((ord(i)>=65 and ord(i)<=92) or (ord(i)>=97 and ord(i)<=122))):
if(i in freq.keys()):... |
from data.DataGenerator import ImageDataGenerator
from core import resnet_v2
import tensorflow as tf
import math
slim = tf.contrib.slim
result_txt_file = "D:\\pycharm_program\\UrbanFunctionClassification\\result.txt"
DATASET_DIR = "D:\\competition\\data\\test\\test\\"
CHECKPOINT_DIR = 'D:\\pycharm_program\\UrbanFunct... |
from CallBackOperator import CallBackOperator
from ConnectionPackage.ConnectionParameters import ConnectionParameters
class ComboBoxOperator(CallBackOperator):
def __init__(self, window, model=None, value_range=None):
super().__init__(window, model, value_range)
self.ConnectionParameters = Connect... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 2 17:34:38 2017
@author: InfiniteJest
"""
def chunkize_query(chunksize, data):
fmt = '''
'''
for chunk in (data[i:i + chunksize] for i in range(0, len(data), chunksize)):
q = fmt.format(column_data = ', '.join(["'"+str(i)+"'" for i in chunk... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
from sklearn import linear_model
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
# 定义自变量x
x = np.array([[1], [2], [3], [4]], dtype=np.float32)
# 定义因变量y
y = np.array([6, 5, 7, 10], dtype=np.float32)
# 加载scikit-le... |
# see https://blog.alexandruioan.me/2017/01/31/the-2017-university-of-bristol-arm-hackathon for more details
import math
from http.server import BaseHTTPRequestHandler, HTTPServer, urllib
from sys import argv
import sys
import serial
import threading
import queue
import numpy as np
import time
q = queue.Queue()
radiu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.