text
stringlengths
38
1.54M
from django.shortcuts import render from django.http import HttpResponse import json import telepot from telepot.loop import MessageLoop from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton from django.http import HttpResponseForbidden, HttpResponseBadRequest, JsonResponse from django.views.generic...
import os import pickle import argparse from itertools import product, cycle from collections import defaultdict import numpy as np import tikzplotlib import graphviz as gv import matplotlib.pyplot as plt import polytope def policy_evaluation(P, R, gamma, policy): """ Policy Evaluation Solver We denote by ...
from django.contrib import admin from .models import java admin.site.register(java) # Register your models here.
#!/usr/bin/env python from utils_new import * def genDivs(): datesuffixes = [ ('2016-01-01','1'), ('2016-01-02','1'), ('2016-01-03','1'), ('2016-01-04','0'), ('2016-01-05','0'), ('2016-01-06','0'), ('2016-01-07','0'), ('2016-01-08','0'), ('20...
#!/usr/bin/python import json import socket import sys import time import os import array import math import sqlite3 import xdriplib import mongo # Datenhaendling zur Mongodatenbank. BG Values openapsDBName='openaps.sqlite' DBVersion=1 tableNameDBVersion='DBVersion' tableNameWixeldata='WixelData' tableNameSensordata...
class Solution: def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None max_ = 0 for i in range(len(nums)): if nums[max_] < nums[i]: max_ = i ...
import argparse from sudoku.grid import Grid def display_grid(): args = parse_args() grid = Grid(args.filepath) grid.print() def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('filepath', help='Path to file containing sudoku grid') return parser.parse_args() if __name__...
import msvcrt, os from MasterOfSudoku.visual import visual # Kleine module om relevante key-presses te lezen keys = {75: "left", 77: "right", 72: "up", 80: "down", 8: "del", 48: 0, 49: 1, 50: 2, 51: 3, 52: 4, 53: 5, 54: 6, 55: 7, 56: 8, 57: 9, 27: "escape", 13: "enter"} diffs = ["easy", "medium", "har...
import ROOT import sys from limittools import addPseudoData infname=sys.argv[1] #samplesWOttH=['ttbarOther','ttbarPlusCCbar','ttbarPlusBBbar','ttbarPlusB','ttbarPlus2B','singlet','wjets','zjets','ttbarZ','ttbarW','diboson'] samplesWOttH=['ttbarOther','ttbarPlusCCbar','ttbarPlusBBbar','ttbarPlusB','ttbarPlus2B'] ca...
# two 1 or 0 -> true if they are same a, b = input().split() bool = int(a) == int(b) print("%d" %bool)
# Generated by Django 3.1 on 2020-09-06 09:23 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Attendance', fields=[ ...
import datetime import pytest from src import todo, core @pytest.mark.parametrize( "weekday,today,expected,description", [ ( todo.Weekday.Monday, datetime.date(2020, 11, 16), datetime.date(2020, 11, 16), "On Monday a Monday todo should return today.", ...
class Solution: def isBalanced(self, root: TreeNode) -> bool: def helper(root: TreeNode) -> int: if not root: return 0 left = helper(root.left) if left == -1: return -1 right = helper(root.right) if right == -1: ...
from django.conf.urls import url from django.contrib.auth import views as auth_views from accounts.views import SignUp,CreateProfile,DetailProfile,VerifyProfile app_name= 'accounts' urlpatterns = [ url(r'^login/$',auth_views.LoginView.as_view(template_name= 'accounts/login.html'),name= 'login'), url(r'^logout/...
#!/usr/bin/python #FIRST remome all <row> s import xml.etree.ElementTree as et from functools import reduce def pc(s): #PascalCase s=s.text.strip() return ' '.join(list(map(lambda w:w[0].upper()+w[1:],s.split(' ')))).strip() #return reduce(lambda s,x:(s+' '+x).strip(),list(map(lambda w:w[0].upper()+w[1:],s.split(...
#!/usr/bin/python3 # pybuster # A dir buster clone that doesn't derp out when a connection fails. # # Laurance Yeomans 2018 # # Why: # dirb has a sad when it fails and stops. # This adds a 5 sec time out before trying again. # # No license. Do whatever with it. import requests import sys import time import signal #...
""" Write a program that contains a function called drawRegularPolygon where you give it a Turtle, the number of sides of the polygon, and the side length and it draws the polygon for you """ import turtle def draw_regular_polygon(t, n_sides, side_length): i = 0 while i < n_sides: t.forward(side_lengt...
n = int(raw_input()) for _ in xrange(n): name, started, dob, courses = raw_input().split() if int(started[:4]) >= 2010: print "%s eligible" % name elif int(dob[:4]) >= 1991: print "%s eligible" % name elif int(courses) > 40: print "%s ineligible" % name else: print "%...
import numpy as np import pandas as pd def l2_normalization(vectors): return vectors / np.linalg.norm(vectors, ord=2, axis=1).reshape(vectors.shape[0], 1) def combine_content2vec_and_skill2vec_one_taxonomy(content2vec_path, skill2vec_path, output_path): content2vec = pd.read_csv(content2vec_path, index_col=...
import threading from ftplib import FTP import sys def save_ftp( filename , my_ftp_url ,my_ftp_username ,my_ftp_password , my_ftp_remote_path , my_local_path): ftp = FTP(my_ftp_url ) ftp.login(my_ftp_username, my_ftp_password) ftp.cwd(my_ftp_remote_path) file = open(my_local_path+filename,'rb'...
lst = ["Vienna", "London", "Paris", "Berlin", "Zurich", "Hamburg"] fruitList = {"Apple","manago"} for f in fruitList: print(f)
""" Defines how the style of the input text is to be parsed into a complete book. This depends upon the formatting of the input, and needs to be customized based on the style that it was originally written. """ class StyleSheet(object): def __init__(self): object.__init__(self) def update_section(se...
from django.contrib import admin from .models import FishDist, FishAsso, PrvType, Prvs # Register your models here. admin.site.register(FishDist) admin.site.register(FishAsso) admin.site.register(PrvType) admin.site.register(Prvs)
from __future__ import absolute_import import uuid from datetime import datetime from enum import Enum from sqlalchemy import Column, DateTime, ForeignKey, String, Text, Integer from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.orm import relationship from sqlalchemy.schema import Index, UniqueConstrai...
#Penn State Abington #IST 440W #Fall 2016 #Team Pump Your Brakes #Members: Abu Sakif, David Austin, Qili Jian, Abu Chowdhury, Gary Martorana, Chakman Fung import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(11,GPIO.OUT) p = GPIO.PWM(11,50)#PWM'Pulse-width Modulation' puts pin...
#!/usr/bin/env python # encoding: utf-8 # author: AlisaAlbert # 2019/5/19 12:26 import pandas as pd import numpy as np import pickle import time,os from multiprocessing import Pool import pymysql import warnings warnings.filterwarnings('ignore') pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns...
#!/usr/bin/env python import sys, math def changeBaseFromTen(num,base): digits = [] while num > 0: digits.insert(0, str(num % base)) num /= base return "".join(digits) def isHappy(num,base): thisNum = changeBaseFromTen(num,base) numsPassed = [thisNum] while (thisNum != "1"): ...
import urllib.request,re import random def ip(): thisurl = "https://seofangfa.com/proxy/" date = urllib.request.urlopen(thisurl).read().decode("utf-8", "ignore") pat = '((\\d+\\.\\d+\\.\\d+\\.\\d+).*?(\\d+))' res1 = re.compile(pat, re.S).findall(date) thisip =[] for i in res1: res = re...
import turtle from turtle import * import random #make a screen win = turtle.Screen() win.bgcolor("black") win.setup(800,600) #make a turtle ruba = turtle.Turtle() ruba.color("yellow") ruba.shapesize(2,2) ruba.speed(0) #color list for the square: color_list = ["yellow", "gold", "orange", "red", "maroon", "violet",...
# # This is a primitive script to parse the output of cdfIntegrate, and # to generate a set of files (one for each track) that contains some of # the integration results. # # It is intended as an example from which more useful scripts can be # generated. # import sys, re, regex, regsub, math from math import sqrt, atan...
# Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
from skimage import io,color import matplotlib.pyplot as plt def negative_image(img): return 255 - img img = io.imread('./images/negative_image.jpg') img_gray = color.rgb2gray(img) negative_img = negative_image(img_gray) plt.figure(1) plt.subplot(1,2,1) plt.imshow(img) plt.title('Original Imag...
# encoding: UTF-8 import datetime def get_modified_date(): ''' 获取当前时间的字符串形式 :return: ''' modified_date = datetime.datetime.now() modified_date = modified_date.strftime("%Y-%m-%d %H:%M:%S") return modified_date def split_dt_list(start_dt, end_dt): ''' 根据输入的日期,输出分割的日期,按照月分割 :pa...
import pygame from pygame import * class Player(): def __init__(self,x,y,w,h,vel,sprite,s_w,s_h): self.x=x self.y=y self.w=w self.h=h self.vel=vel self.sprite=sprite self.s_w=s_w self.s_h=s_h self.walkcount=0 self.hitbox=pygame.Rect...
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # harmonictook.py - Main game file import math import random import utility import argparse import unittest import statistics class Player(object): def __init__(self, name = "Player"): self.name = name self.order = 0 self.isrollingdice = False ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 29 13:21:41 2020 @author: rahul """ #--------------------------------------------------Importing Libraries---------------------------------------------------- import numpy as np import pandas as pd from sklearn.model_selection import train_test_spli...
#plotting a graph using data of a CSV file import matplotlib.pyplot as plt import csv #file location of the csv file filename = "D:\Sheet1.csv" x = [] y = [] #opening csv file to read with open(filename, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #iterating over the objects in csv file ...
# matplotlib # 1. 그래프그리기. 1. X는 0~99, Y는 0~99로 변수정하고 이를 plot해라 2. X_1은 100까지, Y_1은 y=cos(x), X_2도 100까지, Y_2는 y=sin(x),그리고 추가로 y=x도 plot을 한번에하셈. 3. 10*10 inch의 figure set을 만들고 각각 1,2,1/1,2,2의 2개의 판을 넣는다. 첫번재판엔 위의 cos, 두째판엔 sin 그래프넣어라. #color 4. x= 0~100, y=x, y=x+100을 plot해라.단 wjswksms 색깔 '#000000', 후자는 'c'...
import numpy as np import cv2 #Reading the images logo= cv2.imread('python_logo.jpg',cv2.IMREAD_COLOR) img1= cv2.imread('test_image_1.jpg',cv2.IMREAD_COLOR) img2 = cv2.imread('test_image_2.jpg',cv2.IMREAD_COLOR) sized_logo = cv2.resize(logo, (128, 128)) sized_img1 = cv2.resize(img1, (512, 512)) sized_img2...
a, b = 1, 2 sum = 0 while b < 4000000: print "a:" + str(a) + " b:" + str(b), if b % 2 == 0: sum += b print " sum:" + str(sum) a, b = b, a+b
import pytorch_lightning as pl import segmentation_models_pytorch as smp import torch from torch.optim.lr_scheduler import CosineAnnealingLR from torch.utils.data import DataLoader from data.dataset_seg import IntracranialDataset from models.commons.get_base_model import load_base_weights from models.commons.radam imp...
from datetime import datetime import uuid from django.db import models from stdimage.models import StdImageField # Create your models here. class Blog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) category = models.ForeignKey('Category',on_delete=models.SET_DEF...
#import time HELP = """ help - выводить список команд add - добавить задачу show - показать задачи done - убрать выполненную задачу exit - закрыть приложение """ todo = {} def checkDate(date): try: time.strptime(date, "%d.%m.%Y") return True except ValueError: print("Error. Не правильный формат да...
# Generated by Django 2.0.3 on 2018-03-25 00:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0005_playercharacter_knocked_down'), ] operations = [ migrations.AddField( model_name='monstercharacter', na...
import math import random random.seed(101) m = int(input('M: ')) n = int(input('N: ')) initial_sequence = input('Starting action_sequence (West: w, East: e, North: n, South: s): ').split() # move_cost: North, South, West, East # move_cost = [2, 2, 2, 2] move_cost = [random.randint(2, 5), random.randint(...
# Generated by Django 3.0.5 on 2020-05-01 22:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('base', '0012_access_user'), ] operations = [ migrations.RemoveField( model_name='access', name='user', ), ]
import os import subprocess import sys from contextlib import contextmanager from tempfile import NamedTemporaryFile import pytest import requests import ray import ray.actor import ray._private.state from ray.util.state import list_actors from ray import serve from ray._private.test_utils import wait_for_condition ...
import logging from typing import Dict, Iterable import pymorphy2 from .utils import Singleton logger = logging.getLogger(__name__) class Inflector(metaclass=Singleton): def __init__(self) -> None: self._morph = pymorphy2.MorphAnalyzer() def inflect_to_case(self, string_to_inflect: str, case: str...
# frame_grabber.py - Frame grabber for full resolution stills from video # Mainained by Anthony Spears aspears@gatech.edu # Internal note: Using virtualenvwrapper - $ workon frame_grabber # The output png files are named based on KITTI dataset formats import ffmpeg import cv2 import sys ###########################...
import pickletools as pt import pikara.analysis as pa from .test_parse import ops def test_NONE(): po = pa.PickledObject.for_parsed_op(ops.NONE, None) assert po.pickletools_type is pt.pynone assert po.value is None def test_NEWFALSE(): po = pa.PickledObject.for_parsed_op(ops.NEWFALSE, None) as...
# -*- coding: utf-8 -*- """ Created on Sun Jul 1 16:38:37 2018 @author: Inki Kim's lab """ import pandas as pd import numpy as np import os os.chdir('G:\\Resource for Xiang\\Lian Cui experiment\\eyetracking data\\2.New Experiment\\4.analysis\\eyetracking\\2.Sycronized data') outputpath = 'G:\\Resource for...
from verce.processing import * import socket import traceback import json class specfemMakeMovieSurface(SeismoPreprocessingActivity): def compute(self): try: userconf = json.load(open(self.parameters["solver_conf_file"])) ...
import copy def get_max_nodes_rooted_at(node, parent, graph): children = copy.deepcopy(graph[node]) if parent != None: children.remove(parent) if len(children) == 0 or len(children) == 1: return 1 results = [] for child in children: results.append(get_max_nodes_r...
import onmt def split_line_by_char(line, word_list=["<unk>"]): chars = list() words = line.strip().split() for i, word in enumerate(words): if word in word_list: chars.append(word) else: for c in word: chars.append(c) if i < (len(words) - ...
import json import random import re import time import uuid from enum import Enum from typing import List, Set, Optional from room.participant import Participant from utils import remove_chinese_punctuation, sum_dict from .word_bank import Word, WordBank class WordGuessingGameRole(str, Enum): GUESSER = "guesser...
import pygame w,h = 800,600 window = pygame.display.set_mode((w,h)) bg = pygame.transform.scale(pygame.image.load("bg.jpg"), (w,h)) game = True while game: for e in pygame.event.get(): if e.type == pygame.QUIT: game = False window.blit(bg, (0,0)) pygame....
from sklearn.feature_extraction import DictVectorizer from pandas import DataFrame import numpy as np from functools import * from sklearn.ensemble import RandomForestClassifier import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set(color_codes=True) tuned_parameters = {'n_estimators': [20...
import tassle import time import multiprocessing import numpy as np from scipy.signal import welch from dask.distributed import as_completed from dask.distributed import Client from dask_jobqueue import SLURMCluster def main(n=100, processes=64, days=1): # Set up cluster cluster = SLURMCluster(queue='regular'...
from rest_framework import serializers from rest_framework.exceptions import ValidationError from .models import Event, InvitationsSent class CreateEventSerializer(serializers.Serializer): title = serializers.CharField() venue = serializers.CharField() start_time = serializers.DateTimeField() end_tim...
from numpy import* from numpy.linalg import* mat = array(eval(input("digite: "))) vet = zeros(shape(mat)[0],dtype=int) for i in range(size(vet)): for j in range(7): vet[i] += mat[i,j] print(vet)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('nopims', '0008_auto_20140910_0558'), ] operations = [ migrations.AlterField( model_name='master', na...
from mini.Lexer import * from mini.Parser import * from mini.Interpreter import * ################################################################################ ## RUN ################################################################################ def run(a_file_name, a_command): lexer = Lexer(a_file_name, a_c...
#!/usr/bin/python # # Copyright (C) 2010 Google Inc. """ Builds SQL strings. Builds SQL strings to pass to FTClient query method. """ import re __author__ = 'kbrisbin@google.com (Kathryn Hurley)' class SQL: """ Helper class for building SQL queries """ def showTables(self): """ Build a SHOW TABLES sql st...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier ds = pd.read_csv('train.csv') #print(ds.head(10)) #print(ds.shape) #prin...
import os try: os.makedirs('/data/test/01/02', mode=0o770) except FileExistsError as e: print(e)
from multiprocessing import Process, Queue import time def producer(q_production): num = 1 while True: print("q_production") try: q_production.put_nowait(num) except: pass num = num + 1 def consumer(q_consume): while True: try: n...
import paho.mqtt.client as paho import socket import ssl import json import base64 from imutils import paths from pyimagesearch import config from time import sleep connflag = False def on_connect(client, userdata, flags, rc): # func for making connection global connflag print("Connected to A...
from django.db import models from django.template.loader import render_to_string class Room(models.Model): def __unicode__(self): return "%s" % (self.name,) name = models.CharField(max_length=80) description = models.TextField() def send(self, msg): for char in self.char_set.all(): ...
#!/usr/bin/env python3 import hashlib import os import logging import json import uuid import redis import requests import subprocess SOS_URL = 'http://sos:8280' SOS_PORT = '8280' STATUS_OK = requests.codes['ok'] STATUS_BAD_REQUEST = requests.codes['bad_request'] STATUS_NOT_FOUND = requests.codes['not_found'] LOG = l...
budget = float(input()) count_product = 0 total_price = 0 product = input() while product != "Stop": count_product += 1 price = float(input()) if count_product % 3 == 0: price /= 2 total_price += price if total_price > budget: break product = input() if total_price <= bud...
import pymongo from pymongo import Connection #new authenticate in progress below: def floop(x,u,p): res=x for r in res: if r['user']==(u): if r['pw']==(p): return True return False def mfloop(x,u): res=x for r in res: if r['user']==(u): retu...
import numpy as np from scipy.io import loadmat import scipy.optimize as opt import matplotlib.pyplot as plt from PIL import Image #loading DATA data=loadmat('D:\Desktop\MACHINE LEARNING\Models\machine-learning-ex3\ex3\ex3data1.mat') X=data['X'] y = data['y'] #loading Weights weights=loadmat('D:\Deskt...
import docker import os import shutil import uuid import time from docker.errors import * # Start up docker client. client = docker.DockerClient() # Image uploaded to Docker; contains environment to run code for Java, Python, and C++. IMAGE_NAME = 'dannyhp/coderpad_env' # Code file created in temporary build director...
import torch from torch import nn, tensor, bool import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.utils.data import DataLoader from torchvision.transforms import ToTensor from torch.nn.utils import prune from torch.nn import Conv2d, Conv1d class VariationalDropout(object): def __...
class A(): def __init__(self): self.__private() self.public() def __private(self): print('__private() method of A') def public(self): print('public() method of A') class B(A): def __private(self): print('__private() method of B') def public(self): prin...
__author__ = 'haywire' from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity from yowsup....
from django.urls import path from api import views urlpatterns = [ path('login/', views.MyTokenObtainPairView.as_view(), name='login'), path('signup/', views.SignUp.as_view(), name='signup'), path('<str:store_uuid>/products/<str:barcode>/', views.ProductView.as_view(), name='product-detail'), ...
# Example 1: asynchronous requests with larger thread pool import asyncio import concurrent.futures import requests import random import time import sys import datetime from numpy import random counter = 0 generatedRequests = [] random.seed(0) maxWorkers = int(sys.argv[1]) lambdaValue = int(sys.argv[2]) runningDurat...
from django.core.management.base import BaseCommand from django.db.models import Count, Avg, F from annotation.models import Eficaz_prediction import sys ###! Create pseudo-ROC curve? class Command(BaseCommand): help = 'COMMAND BRIEF' def handle(self, *args, **options): """...
import pandas as pd import os os.chdir("C:\\Users\\arman\\OneDrive\\Desktop\\2020\DataCamp\\15 Merging_Data_Frames_Pandas\\01_Preparing_Data\\Summer Olympic medals") os.getcwd() os.listdir("C:\\Users\\arman\\OneDrive\\Desktop\\2020\DataCamp\\15 Merging_Data_Frames_Pandas\\01_Preparing_Data\\Summer Olympic medals"...
import csv import pandas as pd import numpy as np import sys sys.__stdout__ = sys.stdout df = pd.read_csv('review.csv', delimiter=",", encoding='utf-8') print(df.head()) header_rows = [] ##group = x.groupby('business_id')['text'].unique() ##framed = group[group.apply(lambda x: len(x)>1)] ##print(framed....
#! /usr/bin/env python3 ''' Python Script to understand the Python topics Scopes, Closures and Decorators ''' # Decorator Application - Decorator Class # - This is because we can an object can be made callable def dec_fac(a, b): def dec(fn): def inner(*args, **kwargs): print('Decorated funct...
''' LF2: Lambda proxy for API gateway to search photos based on user query ''' import boto3 from requests_aws4auth import AWS4Auth import json import logging import requests import os logger = logging.getLogger() logger.setLevel(logging.DEBUG) lex_bot_name = os.environ.get('LEX_BOT_NAME') elastic_search_host = o...
# intialize the batch size and number of epochs for training batch_size = 32 epochs = 40 # test-train split ratio split = 0.25 # path to save the features path_feature_train = 'output/features_train.npy' path_feature_test = 'output/features_test.npy' # class weights, this is because there is class # imbalance betwee...
from __future__ import annotations from prettyqt import constants, core, eventfilters, widgets CC = widgets.QStyle.ComplexControl SC = widgets.QStyle.SubControl class SliderMoveToMouseClickEventFilter(eventfilters.BaseEventFilter): ID = "slider_move_to_mouse_click" def _move_to_mouse_position(self, scroll...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 提供矩阵支持,以及矩阵相关的数值计算模块(包含最优化、线性代数、积分、插值、拟合、特殊函数、快速傅里叶变换、信号处理和图像处理、常微分方程求解等功能) """
import numpy as np import cv2 import ccv import cropper import filefinder import lbp import tester import classify # define a main function def main(): training = np.loadtxt("out.txt") #training = filefinder.getTrainingData() trainingdata = training[:,range(0,128)].astype(np.float32) size ...
from django.contrib.auth.models import AbstractUser from django.db import models class Tag(models.Model): description = models.CharField(max_length=200, blank=True, null=True, default=None, auto_created=True) def __str__(self): return self.description if self.description is not None else '????????' ...
from __future__ import unicode_literals import socket, threading, os import tornado.web, tornado.websocket, tornado.ioloop, tornado.iostream import json class NADClient(object): def __init__(self, host, receive_callback): self.host = host self.port = 23 self.receive_callback = receive_call...
from rest_framework import generics from ..serializers import ToastingSerializer from ..models import Toasting class ToastingListCreateView(generics.ListCreateAPIView): queryset = Toasting.objects.all() serializer_class = ToastingSerializer
# Leetcode problem 13. # Convert roman numerals to integers def rom_to_int(num): conv = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1} res = 0 for i in range(len(num)): value = conv[num[i]] if i+1 < len(num) and conv[num[i+1]] > value: res -= value else: res += value return res nu...
#-*- coding: utf-8 -*- from __future__ import print_function import iterL1 as itr import numpy as np x = np.arange(1000)/1000.0 Gorig = np.column_stack((x,np.sin(2*np.pi*x*1000.0/200.0))) G = np.column_stack((x,np.ones(x.size))) tval = np.array([5,0.5]) y = np.dot(Gorig,tval) m,S = itr.L1error_BS(G,y, ngroup=25, ...
from Artist import * from User import * from KNN import * import random import time import numpy as np import matplotlib.pyplot as plt def readFile(filepath, filelist): """ read the data file from the filepath/filename """ data = [] for filename in filelist: f = open(filepath+filename,"r") filedata = [] # rea...
import RPi.GPIO as GPIO import time from urllib.request import urlopen from bs4 import BeautifulSoup import re from RpiMotorLib import rpiservolib import schedule import functools #Protect against exceptions def catch_exceptions(cancel_on_failure=False): def catch_exceptions_decorator(job_func): @functools.wra...
import cv2 import numpy as np import imutils class ImageFeatures: def __init__(self, bins): self.bins = bins def getFeatures(self, image): image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) features = [] (h, w) = image.shape[:2] (cw, ch) = (int(w * 0.5), int(...
class KMP: def __init__(self, needle): """ https://ja.wikipedia.org/wiki/クヌース–モリス–プラット法 :param typing.Sequence needle: 何を検索するか """ self._needle = needle kmp = [0] * (len(needle) + 2) kmp[0] = -1 kmp[1] = 0 i = 2 j = 0 while i < ...
# Copyright (c) 2014-2019 Cloudify Platform Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
""" .. module:: gene_cross_reference_file_generators :platform: any :synopsis: Module that generates the Gene Cross Reference files .. moduleauthor:: AGR consrotium """ import os import logging import csv import json from upload import upload from headers import create_header from validators import json_vali...
# CS121 Linear regression # General purpose model representation and selection code #NAME: ALEISTER MONTFORT #CNETID: 12174240 import numpy as np import matplotlib.pylab as plt import math from asserts import assert_Xy, assert_Xbeta #from dataset import DataSet ############################# # ...
# coding=utf-8 # Copyright 2022 Google LLC. # # 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 ...