text stringlengths 8 6.05M |
|---|
import csv
import matplotlib.pyplot as plt
my_file = csv.DictReader(open('train.csv'))
def clean_data(datapoint, average):
age = datapoint[0]
pclass = datapoint[1]
cleaned_data = []
if (age == ""):
age = average
else:
age = float(age)
pclass = int(pclass)
cleaned_data.appe... |
import re
def pertty(text):
"""替换Markdown中的部分特殊符号,支持代码块,便于wox复制"""
return text.replace("```", "").replace("\n", "")
if __name__ == "__main__":
print(pertty("""`1111`
1234"""))
|
import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
from builtins import str
import csv
import sys, getopt
import xml.etree.ElementTree as ET
from xml.dom.minidom import parse, Node
import xml.dom.minidom
from num... |
class Ticket(object):
'''
This class is the parking ticket
'''
__slotId = 0
__registratonNumber = None
__age=None
def __init__(self, slotId, registratonNumber,age):
'''
Constructor
'''
self.__slotId = slotId
self.__registratonNumber = registratonNumber... |
# The code below almost works
name = raw_input("Enter your name")
print('Hello '+str(name)) |
class Subject:
"""
important to note that objects that inherit from this class
will have state, that will then be passed to the 'notify_observers'
method in the event that this state mutates.
"""
def __init__(self):
self.observers = set()
def register_observer(self, observer):
... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.jvm.resolve.jvm_tool import JvmToolBase
class AvroSubsystem(JvmToolBase):
options_scope = "java-avro"
help = "Avro IDL compiler (https://avro.apache.org/)."
defaul... |
import numpy as np
class NeuralNetwork(object):
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
# Set number of nodes in input, hidden and output layers.
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
... |
n=input()
list1=[int(x) for x in raw_input().split(" ")]
count=0
def f(l,r,x):
sum=0
for k in range(l,r+1):
if list1[k-1]==x:
sum+=1
return sum
for j in range(1,n+1):
for i in range(1,j):
if f(1,i,list1[i-1])>f(j,n,list1[j-1]):
count+=1
print count |
'''
252. Meeting Rooms
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
For example,
Given [[0, 30],[5, 10],[15, 20]],
return false.
'''
# Solution is to sort the array first using start time
# since intervals ... |
# coding:utf-8
from __future__ import absolute_import, unicode_literals
from jspider.manager import Manager
__author__ = "golden"
__date__ = '2018/6/4'
if __name__ == '__main__':
manager = Manager()
spider = manager.setup_spider('qb')
spider.run_forever = False
spider.run()
# manager.add_spider(spi... |
import numpy as np
a_pressure = 101325
a_temperature = 279
e_temperature = 294
k = 1.4
C_v = 718
eta_t = 0.40
V = (1.5*0.001)/5
V_ans = (1-eta_t)**((k-1)**-1)*V
T_1 = a_temperature
T_4 = e_temperature
T_2 = ((1-eta_t)**-1)*T_1
T_3 = (T_4*T_2)/T_1
q_in = C_v*(T_3-T_2)
q_out = C_v*(T_4-T_1)
T_1 = np.array([17+273.15, 23... |
__author__ = "Narwhala"
import time
def consumer(name):
print('%s来了,准备吃包子!!'%name)
while True:
baozi = yield
print('%s的包子来了,被%s吃掉了'%(baozi,name))
# c = consumer('Narwhala')
# c.__next__()
# c.send('猪肉馅')
def producer(name):
c1 = consumer('A') #只是把consumer()变成生成器
c2 = consumer('B'... |
import cv2
import numpy as np
from PIL import ImageDraw
import copy
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import imutils
import sys
def plot_img(img):
if len(img.shape) == 3:
plt.imshow(img)
else:
plt.imshow(img, cmap='gray', vmin=0, vmax=255) ... |
import os
import sys
import subprocess
import shutil
import fam
sys.path.insert(0, 'scripts')
sys.path.insert(0, 'tools/raxml/')
import experiments as exp
import time
import saved_metrics
import run_raxml_supportvalues as raxml
import sequence_model
def run_pargenes(datadir, pargenes_dir, subst_model, starting_trees... |
# You are given the array paths, where paths[i] = [cityAi, cityBi]
# means there exists a direct path going from cityAi to cityBi.
# Return the destination city, that is, the city without any path
# outgoing to another city.
#
# It is guaranteed that the graph of paths forms a line without
# any loop,... |
import cx_Freeze
executables = [cx_Freeze.Executable("slither.py")]
cx_Freeze.setup(
name = "Slither",
options = {"build_exe":{"packages":["pygame"], "include_files":["apple30px.png", "snakehead20px.png"]}},
description = "Slither Game",
executables = executables
) |
from bs4 import BeautifulSoup
import requests
import os
import warnings
warnings.filterwarnings('ignore')
from tqdm import tqdm
def log_in():
return s.post(url, data=values, verify=False).content
def routine():
source = log_in()
tree = BeautifulSoup(source, 'html.parser')
# Iterate through all curr... |
#I pledge my honor that I have abided by the Stevens Honor System.
#Zachary Jones
# HW 5 Problem 1
def recursive_square(list):
if not list:
return []
return [list[0] ** 2] + recursive_square(list[1:])
numbers_list = [2, 4, 6, 8, 10, 11]
print('Squared entries: ' + str(recursive_square(numbers_list))... |
"""A place to make 'leftover' plots for the thesis."""
import numpy as np
import seaborn as sns
import astropy.units as u
import matplotlib.pyplot as plt
sns.set_style('white')
from astropy.constants import c, h, k_B
c, h, k_B = c.value, h.value, k_B.value
def plot_SED():
# These l's are just the exponent fo... |
import chainer
import chainer.functions as F
from chainer import testing
import numpy as np
from onnx_chainer.testing import input_generator
from tests.helper import ONNXModelTest
@testing.parameterize(
{'op_name': 'average_pooling_2d',
'in_shape': (1, 3, 6, 6), 'args': [2, 1, 0], 'cover_all': None},
{'... |
import psycopg2
import yaml
import os
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
CONFIG_PATH = os.path.join(DIR_PATH, '..', 'config.yaml')
with open(CONFIG_PATH) as conf:
try:
config = yaml.load(conf)
except yaml.YAMLError as exc:
print('Error in config file: {0}'.f... |
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=128)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
publish = models.DateTimeField(
auto_now_add=False,
auto_now=False,
null=True,
blank=True
... |
"""
Submodule for basic MPI environment discovery
"""
from __future__ import annotations
__all__ = [
"rank",
"size"
]
def rank() -> int:
"""
Returns the MPI rank of the process
"""
def size() -> int:
"""
Returns the MPI size (no. of processes) of the run
"""
|
from .db import db
from .loan import Loan |
from flask import Flask, render_template, request, url_for, redirect
from passlib.handlers.sha2_crypt import sha256_crypt
import psycopg2, time
hostname = 'localhost'
username = 'postgres'
password = 'admin'
database = 'PongGame'
myConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
import numpy as np
import matplotlib.pyplot as plt
#import gif
"""
surface plot
INPUTS:
- ax : axis to draw figure on
- x : numpy array corresponding to ROWS of Z (displayed on x-axis)
x[0] corresponds to Z[0,:] and x[end] corresponds to Z[end,:]
- y : numpy array corresponding to COLUMNS of Z (... |
from flexp.flexp.core import (
setup,
describe,
name,
static,
backup_files,
backup_sources,
get_static_file,
get_file_path,
get_file,
set_metadata,
disable,
close,
)
|
from flask import Flask, request, render_template
from flask_cors import cross_origin
import sklearn
import pickle
import pandas as pd
import nltk
nltk.download('stopwords')
import re
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
import... |
import sys
from collections import defaultdict
from lib.intcode import Machine
if len(sys.argv) == 1 or sys.argv[1] == '-v':
print('Input filename:')
f=str(sys.stdin.readline()).strip()
else: f = sys.argv[1]
verbose = sys.argv[-1] == '-v'
for l in open(f):
mreset = [int(x) for x in l.strip().split(',')]
cla... |
from flask_restful import fields
class Fields:
def timestampedmodel_fields(self):
return {
}
def timestampedmodel_fields_min(self):
return {
}
def product_fields(self):
return {
"id": fields.Integer,
"name": fields.String,
"brand": fields.String,
"description": fields.String,
"barcod... |
# Generated by Django 3.0.6 on 2020-06-15 19:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LaF', '0022_auto_20200615_2105'),
]
operations = [
migrations.AlterField(
model_name='find',
name='PIN_code',
... |
# -*- coding: utf-8 -*-
from app.models import PasswordToken, User
from app.tests import dbfixture, UserTokenData, PasswordTokenData, UserData
from app.tests.models import ModelTestCase
from web import config
class TestPasswordToken(ModelTestCase):
def setUp(self):
super(TestPasswordToken, ... |
import re
from functools import reduce
def read_morse_to_plaintext_dictionary():
with open('morse.txt', 'r') as lines:
return dict([ tuple(reversed(line.strip().split(' '))) for line in lines ])
def read_plaintext_to_morse_dictionary():
with open('morse.txt', 'r') as lines:
return dict([ tupl... |
from django.db import models
from django.utils import timezone
from accounts.models.client import Client
from accounts.models.supplier import Supplier
class Project(models.Model): ## TODO: change on_delete
class Meta:
verbose_name = 'project'
verbose_name_plural = 'projects'
client ... |
from typing import List, Union
from .property import Property
from graph_db.engine.types import INVALID_ID
from .label import Label
class Node:
""" Node in a Graph. """
def __init__(self,
label: Label,
id: int = INVALID_ID,
properties: List[Property] = list... |
import logging
import fmcapi
def test__application_productivity(fmc):
logging.info("Testing ApplicationProductivity class.")
obj1 = fmcapi.ApplicationProductivities(fmc=fmc)
logging.info("All ApplicationProductivities -- >")
result = obj1.get()
logging.info(result)
logging.info(f"Total items:... |
import urllib.request
import json
import dml
import prov.model
import datetime
import uuid
import csv
import numpy
import statistics as stats
# from alyu_sharontj_yuxiao_yzhang11.Util.Util import *
class Constraint_Solver(dml.Algorithm):
contributor = 'alyu_sharontj_yuxiao_yzhang11'
reads = ['alyu_sharontj_... |
import logging
from textwrap import dedent
import numpy as np
from PIL import Image
logger = logging.getLogger("osmo_camera.rgb.convert")
# Constant used to convert from 0-1 RGB values to 0-255
MAX_COLOR_VALUE = 255
def to_bgr(rgb_image):
""" Converts an `RGB image` to a `BGR image`
Args:
rgb_imag... |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from credentials.models import SshKeyPair
from archives.policies import CdimageArchivePolicy
from archives.archivers import SshArchiver
POLICIES = {"cdimage": CdimageArchivePolicy}
ARCHIVERS = {"ssh": SshArchiver}
@python_2_... |
# -*- coding: utf-8 -*-
# Create your models here.
from __future__ import unicode_literals
from django.utils import timezone
from django.contrib.gis.geos import Point
from django.contrib.gis.db import models
from django.contrib.gis import geos
from django.contrib.auth.models import User
from django.conf import setti... |
from django.contrib import admin
from .models import Profile, Neighborhood , Post, Business
#
# Register your models here.
admin.site.register(Neighborhood)
admin.site.register(Post)
admin.site.register(Business)
admin.site.register(Profile)
|
import os
import sys
sys.path.insert(0, 'scripts')
import experiments as exp
def get_model(subst_model):
return subst_model.split("+")[0]
def get_gamma_rates(subst_model):
if ("G" in subst_model.split("+")):
return 4
else:
return 1
def is_invariant_sites(subst_model):
return "+I" in subst_model
def... |
import json
class BufferedWriter:
def __init__(self, out_folder, out_name, table_name_key=None, ext='.json' ,count_limit=25):
# out_folder is /a/b
# out_name is with extention 'somefile.json'
# ext='.json'
# count_limit=25
self.folder = out_folder # no slash at end
... |
import socket # importing the socket module.
HOST = "127.0.0.1" # specifying the host's address.
PORT = 65432 # specifying the port to be used in the communication between the server and the client.
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creating an object that calls on the socket method ... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="flare",
version="0.1.5",
author="Jacob Pettit",
author_email="jfpettit@gmail.com",
short_description="Simple implementations of reinforcement learning algorithms.",
long_description=lo... |
import re
from collections import Counter
# VOWELS = list('aeiou')
VOWELS = 'aeiou'
def get_word_max_vowels(text):
"""Get the case insensitive word in text that has most vowels.
Return a tuple of the matching word and the vowel count, e.g.
('object-oriented', 6)"""
vowel_count = {}
for ... |
import pytreebank
import nltk
import itertools
from numpy import array
import numpy as np
SENTENCE_START_TOKEN = 'eos'
UNKNOWN_TOKEN = 'unk'
def word2index(sentences, vocabulary_size):
tokenized_sentences = [nltk.word_tokenize(sent) for sent in sentences]
# Count the word frequencies
word_freq = nltk.Freq... |
# coding:utf-8
number = 0
while number <= 10:
number += 1
if number * 3 >= 10:
break
print(number)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Vladimir Shurygin. All rights reserved.
import uvicorn
from app.server import get_app
app = get_app()
if __name__ == "__main__":
uvicorn.run("run:app", host="127.0.0.1", port=8080, log_level="info", reload=True)
|
if __name__ == '__main__':
n = int(input())
ans = []
for _ in range(n):
op, *line = input().split()
val = list(map(int, line))
if(op =="remove"):
ans.remove(val[0])
elif(op=="pop"):
del ans[len(ans)-1]
elif(op=="reverse"):
... |
'''
Created on Dec 8, 2015
@author: jj1745
'''
class Restaurant(object):
'''
The restaurant object, where each restaurant is determined by its unique camis_id
'''
def __init__(self, camis_id):
'''
Constructor
'''
self.id = camis_id
def test_grades(self, grade... |
"""
Insertion sort implementation
Useful for when the list is known to be
nearly/mostly sorted
"""
numbers = [3,53,65,1,321,54,76,43,2,4,66]
# O(n) best case, O(n^2) generally
def insertionSort(array):
length = len(array)
for x in range(length):
value = array[x]
j = x-1
while j ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('basketball', '0032_auto_20160124_1912'),
]
operations = [
migrations.AddField(
model_name='statline',
... |
import sys
import copy
from requests.exceptions import HTTPError
from biigle import Api
# Enter your user email address here.
email = ''
# Enter your API token here.
token = ''
# ID of the volume to process.
volume_id = 0
# ID of the label to attach to new annotations.
label_id = 0
# Number of grid rows for each image... |
# 编译proto文件
# protoc object_detection/protos/*.proto --python_out=.
# 将Slim加入PYTHONPATH
# export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
# 完成安装测试
# python3 object_detection/builders/model_builder_test.py |
import sys,os
from catalog.models import Category, Item, Brand, Specification, UserReview
from django.core.exceptions import ObjectDoesNotExist
from memcached_utils import cache_categories as cache_categories
from django.core.cache import cache
from django.template import RequestContext
from django.shortcuts import r... |
"""Console script for fundamentals_of_data_science."""
import os
import sys
import click
from rich import traceback
WD = os.path.dirname(__file__)
@click.command()
def main(args=None):
"""Console script for fundamentals_of_data_science."""
read_included_file('test.txt')
click.echo("Replace this message... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
## Version 0.2
desc={
"geral" : "-RISD",
"pri" : "-P",
"back" : "-B",
"con" : "-C",
"as" : "2860:",
"palha":"0000"
}
vrfs={
"1":"VPN_RIS",
"2":"VPN_RIS_WIFI_UTENTES",
"3":"VPN_SICAD",
"4":"VPN_CH_CHLO",
"5":"VPN_CH_CHTV",
"6":"VPN_CH_CHBV"
}
vrfs_rds={
"VPN_R... |
def banner_text(text: str = " ", width: int = 80) -> None:
"""
Center the entered text and border with asterisks
:param text: the string to be printed
:param width: the width around the entered text
:return: nothing is returned
"""
screen_width = width
if len(text) > screen_width - 4:
... |
# !/usr/bin/env python
# Object : project for Optimisation 2016 AIC
# Author : Herilalaina, Xiyu ZHANG
# Date : Wed Oct 12 23:36:30 CEST 2016
# Email : zacharie.france@gmail.com
# ==============================================================================
import numpy as np
def paretoRank(objectives):
"""Thi... |
from router_solver import *
import compilador.objects.semantic_table
from compilador.objects.semantic_table import *
# CLASE QUADRUPLE
# Objeto que guarda operando, operadores y resultado de una expresión o instrucción
class Quadruple(object):
def __init__(self, operator, operand_1, operand_2, result_id):
... |
import logging
import os.path
from poap.controller import BasicWorkerThread, ThreadController
from pySOT.experimental_design import SymmetricLatinHypercube
from pySOT.strategy import SRBFStrategy
from pySOT.surrogate import CubicKernel, LinearTail, RBFInterpolant
from pySOT.optimization_problems.optimization_problem im... |
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path='C:\\Users\\Ольга\\Downloads\\питон\\geckodriver.exe')
driver.get("https://www.avito.ru")
element = driver.find_element_by_id("search")
element.send_keys('модем роутер') #вписать в поисковик
elemen = driver.find_element_by_class_nam... |
ok_bags = ["shiny gold"]
# Repeat this process until no new ok bags are found
while True:
new_bags = []
for bag_color, contents in data.items():
#print(bag_color.upper(), end=": ")
for each in contents:
# Find the position of the number at the start so you can get rid of it
... |
import tkinter, os
import tkinter.messagebox
from tkinter.filedialog import askopenfilename
import pyperclip, re
import hashlib
import subprocess
import threading
import time, sys
from tkinter.messagebox import showinfo
import os
import signal
import subprocess
import multiprocessing
import time
window = tkinter.T... |
"""
kumquat application
"""
import typing
import logging
import inspect
import uvicorn
from kumquat.context import env_var
from kumquat.response import (
TextResponse,
JsonResponse,
SimpleResponse,
TemplateResponse,
HTMLResponse,
)
from kumquat.route import Route, Router
from kumquat.request impor... |
def beach(sentence):
word = []
for character in sentence:
character = character.lower()
word.append(character)
word = "".join(word)
counter = 0
while word:
if word[:3] == 'sun':
counter += 1
if word[:4] == 'fish':
counter += 1
if word[:... |
def knapsack_dp(wt,val,W,n):
t=[[-1 for j in range(W+1)] for i in range(n+1)]
#Base Condition Initialization
for i in range(n+1):
for j in range(W+1):
if i==0 or j==0:
t[i][j] = 0
#Recursive Case
for i in range(1,n+1):
for j in range(1,W+1):
... |
# Generated by Django 2.1.7 on 2019-03-15 15:33
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('contest', '0007_submission_time'),
]
operations = [
migrations.AlterField(
... |
from max_number_occurence import generated_list
from decorators import run_time_decorator
def unique_elements_in_list(array):
unique_elements = [i for i in set(array)]
return unique_elements
list1 = generated_list(10000)
list2 = generated_list(10000)
def common_elments_in_lists(first_list, second_list):
... |
from tuneup.horserace import latex_horse_race
from tuneup.trivariatesingleobjectivesolvers.trivariateboxsolvers import GOOD_SOLVERS, sigopt_cube
from tuneup.trivariateobjectives.trivariateboxobjectives import OBJECTIVES
from pprint import pprint
import random
def race_specification(debug:bool):
solvers = GOOD_SOL... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or i... |
class Decision(object):
def __init__(self, exits={}):
self.exits = exits
self.template = 'decision' |
"""
1.Logical Operators
//- Floor operator- division that results into a whole number
%- modlus
**- exponent
2.Comparision operators
>,<,==,!=,
"""
# x=34
# y=65
# print(x+y)
# print(x/y)
# print(x%y)
# print(x**y)
# print(y//x)
# print(y/x)
# x=int(input("Enter a number:"))
# y=int(input("Enter a number:"))
# z= x... |
from spack import *
import re
import os, sys
from glob import glob
import fnmatch
class FwliteToolConf(Package):
url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml'
version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017615', expand=False)
depends_on('scram')
depends_on('gmake-toolfi... |
import writeBack
import alu
import cache
import issue
import fetch
import simulator
import memory
from helpers import SetUp
gobal_cycle = 0
class simClass:
#instruction
# R = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
# 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#
# postMemBuf... |
from django import forms
from django.forms import modelformset_factory
from . import models
class NewTicketForm(forms.ModelForm):
class Meta:
model = models.Ticket
fields = ['title', 'category', 'text']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
fo... |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
... |
# Generated by Django 3.2.3 on 2021-06-10 05:47
from django.db import migrations, models
import django.db.models.deletion
import pizza_app.models
class Migration(migrations.Migration):
dependencies = [
('pizza_app', '0004_auto_20210610_0105'),
]
operations = [
migrations.CreateModel(
... |
import math
import matplotlib.pyplot as pp
import sys
if (len(sys.argv) < 2):
print('no data file\n')
exit()
fp = open(sys.argv[1],'r')
line = fp.readline()
gdiff = []
values = fp.readline().strip().split(',')
xp = float(values[0])
yp = float(values[1])
zp = float(values[2])
line = fp.readline().strip()
while line:
... |
"""
Copyright 2019 Sangkug Lym
Copyright 2019 The University of Texas at Austin
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 require... |
import numpy as np
#1. 훈련 데이터
x_train = np.array([1,2,3,4,5,6,7,8,9,10])
y_train = np.array([1,2,3,4,5,6,7,8,9,10])
x_test = np.array([11,12,13,14,15,16,17,18,19,20])
y_test = np.array([11,12,13,14,15,16,17,18,19,20])
x3= np.array([101, 102, 103, 104, 105, 106])
x4= np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,... |
### Summary
# This module grabs an image from the screen and funnels
# it to the processing module
# -------------------------------------------------
from mss import mss # python3 -m pip install -U --user mss
import cv2 # pip install opencv-python
from PIL import Image # python3 -m pip install Pillow
import numpy a... |
#
# Solver settings object
#################################
import numpy as np
from .. DREAMException import DREAMException
from . ToleranceSettings import ToleranceSettings
from . Preconditioner import Preconditioner
LINEAR_IMPLICIT = 1
NONLINEAR = 2
LINEAR_SOLVER_LU = 1
LINEAR_SOLVER_MUMPS = 2
LINEA... |
import typing
from starlette.responses import HTMLResponse
from cbv import WebSocketBase
from temp_router import TempRouter
router = TempRouter()
class WebSocketTest(
WebSocketBase,
path="/ws",
router=router
):
async def on_receive(self, data: typing.Any) -> None:
await self.websocket.send_te... |
"""Console script to launch Colorgorical.
Colorgorical can be launched through the console as either a terminal
application or as a web application built on top of a Tornado server.
"""
import argparse
from src.makeSamples import MakeSamples
import src.server as server
desc = "Colorgorical is a color palette design ... |
from django.core.exceptions import ImproperlyConfigured
def dependency_ordered(test_databases, dependencies):
"""Reorder test_databases into an order that honors the dependencies
described in TEST_DEPENDENCIES.
"""
ordered_test_databases = []
resolved_databases = set()
while test_databases:
... |
import os
import tempfile
from settings import settings
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.files.file import File
root_site_url = settings.get('url')
client_credentials = ClientCredential(settings.get('client_credentials').get('client_id'),
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
from scipy import cluster
import numpy as np
import sys
# importlib.reload(sys)
import pandas as pd
from scipy.cluster import hierarchy
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from pandas.core.frame import DataFrame
# filename =... |
from zope.interface import Interface
class IEscoAuction(Interface):
""" Esco Auction """ |
__author__ = 'Justin'
# DESCRIPTION:
# This function returns a max speed based on Open Street Map (OSM) naming conventions
# Each OSM edgetype has a given max speed in mph by convention
#
def getdefaultspeed(string):
unknownspeed = 30
restrictedspeed = 0.01
defaultspeeds = {
'motorway':70,
... |
from openpyxl import Workbook
import openpyxl as pyxl
def grade_point_from_letter(1):
l_s_map = {"S":9}
wb = pyxl.load_workbook("student.xlsx")
sheet = wb.active
for row in sheet.iter_rows(min_row = 3, min_col = 2, max_row = 4, max_col = 3):
if row:
data = [c.value for c in row]
|
# for adafruit circuit playground express
# flash w or w/o buzz morse for "lame" or "SOS"
"""
The dot duration is the basic unit of time measurement in code transmission.
The duration of a dash is three times the duration of a dot.
Each dot or dash is followed by a short silence, equal to the dot duration.
The lette... |
class Solution(object):
def remove_element_v1(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if not nums:
return nums
for i in range(len(nums)-1, 0, -1):
if nums[i] == val:
print(nums)
... |
import requests
from celery import chain, shared_task
from .models import Currency
@shared_task
def parse_private():
url = 'https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5'
response = requests.get(url)
currency = response.json()
return currency
@shared_task
def save_currency_to_mode... |
import unittest
from katas.kyu_5.airport_arrivals_departures_1 import flap_display
class FlapDisplayTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(flap_display(['CAT'], [[1, 13, 27]]), ['DOG'])
def test_equal_2(self):
self.assertEqual(
flap_display(['HELLO ... |
from fastapi_scaffolding.main import get_app
app = get_app()
def test_heartbeat(test_client) -> None:
response = test_client.get('/api/health/heartbeat')
assert response.status_code == 200
assert response.json() == {"is_alive": True}
def test_default_route(test_client) -> None:
response = test_clie... |
# albus.exceptions
class AlbusError(Exception):
def __init__(self, message, inner=None, detail=None):
self.message = message
self.inner = inner
self.detail = detail
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.