text stringlengths 38 1.54M |
|---|
import numpy as np
import pickle
from flask import Flask, request, render_template
# Create app
app = Flask(__name__, template_folder='Templates')
# Use pickle to load in the pre-trained model.
with open(f'rf.sav', 'rb')as f:
model = pickle.load(f)
@app.route("/")
def home():
return render_template("inde... |
# Generated by Django 3.0.4 on 2020-04-18 13:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('argus', '0005_auto_20200409_2116'),
]
operations = [
migrations.AddField(
model_name='scan',
name='port_range',
... |
co = float(input('Digite o cateto oposto'))
ca = float(input('digite o cateto adjacente'))
hi = (co**2+ca**2)**(1/2)
print ('A hipotenusa vai medir {:.2f}'.format(hi))
|
'''
------------------------------------------------------------------------------
Copyright (c) 2015 Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction,... |
import sys
sys.path.append('../app')
class Bar:
def __init__(self, name):
self.name = name
def foo(self):
return f"{self.name}_foo"
def bar(self):
return f"{self.name}_bar"
if __name__ == "__main__":
app = Bar('quux')
|
# package for command line tools
# see: setup.py:entry_points
# implement cli access here to separate the core- and lib-packages from
# the commandline argument parsing.
|
"""Server settings loader and handling"""
import os
import sys
import configparser
# ordered from low prio to high prio
SETTINGS_PATHS = [
"./server.conf",
os.path.expanduser("~") + "/.sepia-stt-server.conf"
]
class SettingsFile:
"""File handler for server settings (e.g. server.conf)"""
def __init__(... |
#!/usr/bin/env python
"""
Script to update the svn snapshot of the current filelist.
Usage: update_svn.py <options> [target_dir]
Arguments:
target_dir Location of svn checkout, defaults to current dir
Options:
-h, --help Print command help
-t, --time Output timing infomation
--nocopy ... |
from pytest import *
from pythonapi import config as cfg
from pythonapi.core.api_test import *
@fixture(scope="class")
def api():
psapi = ApiTest(cfg.API_BASE_URL)
yield psapi
del psapi
|
# -----------------------------------------------------------------------------
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens & Font Bureau
# www.pagebot.io
#
# P A G E B O T
#
# Licensed under MIT conditions
# Made for usage in DrawBot, www.drawbot.com
# ------------------------------... |
#!/usr/bin/env python3
from unittest import TestCase, main
from car import Car
class TestCar(TestCase):
def testDefaultCar(self):
car = Car()
self.assertEqual(car.id,Car.DEFAULT_ID)
self.assertEqual(car.name,Car.DEFAULT_NAME)
self.assertEqual(car.running,Car.DEFAULT_RUNNING)
... |
# encoding: utf8
from __future__ import unicode_literals
from django.db import models, migrations
import fancypages.mixins
import shortuuidfield.fields
class Migration(migrations.Migration):
dependencies = [
('fancypages', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
class AnswerType(type):
def __init__(self, name, bases, namespace):
self.answer=42
class Book(metaclass=AnswerType): pass
assert Book.answer==42
|
# convert sequences and ids to fasta format
import pandas as pd
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_protein
from Bio import SeqIO
# load the data
data = pd.read_csv("/home/dillon/data/dssp/cpdb2_dssp_14726.csv")
data["seq"] = data["seq"].str.replace("!", "*", re... |
# ∗ CSCI3180 Principles of Programming Languages ∗
# ∗ --- Declaration --- ∗
# ∗ I declare that the assignment here submitted is original except for source
# ∗ material explicitly acknowledged. I also acknowledge that I am aware of
# ∗ University policy and regulations on honesty in academic work, and of the
# ∗ discip... |
# python dps_api.py -f ~/Downloads/cv-3.pdf -ft application/pdf -it recibida -d 2021-07-01 --debug
import argparse
import pathlib
import sys
from datetime import datetime
from secrets import DPS_API_INVOICE_UPLOAD_ENDPOINT, DPS_API_SERVER, DPS_API_TOKEN
import requests
BANK_LIST = [
'BANCO CAMINOS',
'BANKIA',... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('list/', views.Booklists.as_view(), name='booklist'),
path('view/', views.Bookview.as_view(), name='bookadd'),
path('delete/<int:pk>', views.BookDelete.as_view(), name='bookdelete'),
path('up... |
from sqlalchemy.orm import Session
from . import models, schemas
from sqlalchemy.sql.expression import func, update
#5.1
def get_suppliers(db: Session):
return db.query(models.Supplier).order_by(models.Supplier.SupplierID).all()
def get_supplier(db: Session, id: int):
return (
db.query(models.Suppl... |
from google.cloud import vision
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "credentials.json"
def lambda_handler(event, context):
client = vision.ImageAnnotatorClient()
print(client)
|
import base64
import json
class HttpServer:
METHOD_PUT = "PUT"
METHOD_POST = "POST"
METHOD_GET = "GET"
METHOD_DELETE = "DELETE"
METHOD_OPTIONS = "OPTIONS"
METHOD_HEAD = "HEAD"
AUTHTYPE_BASIC = "Basic"
event = None
def __init__(self, event):
self.event = event
def g... |
#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
# Original idea from :
# Maxime Biais <maxime@biais.org>
# but has been nearly all rewritten since...
# Marc Poulhičs <marc.poulhies@epfl.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GN... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# movescheduler.py
#
# Copyright 2019 Marcus D. Leech <mleech@localhost.localdomain>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; ei... |
#coding:utf-8
import requests
import HTMLParser
import os.path
import re
def get_pic(path,num,proxies):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
url='http://www.budejie.com/pic/{}'
for i in range(1,num):
... |
import torch
def get_gradient_penalty(x, y, model):
alpha = torch.rand((x.size(0), 1), device=x.device)
interpolates = alpha * x + (1 - alpha) * y
f_int = model(interpolates).sum()
grads = torch.autograd.grad(f_int, interpolates, create_graph=True)[0]
slopes = grads.pow(2).sum(1).sqrt()
gp = t... |
# Импортирование математической библиотеки
import math
# Сторона равностороннего треугольника
side = 0
# Получение данных
while side == 0:
side = math.fabs(float(input("Введите размер стороны равностороннего треугольника: ")))
# Вычисление периметра равностороннего треугольника
perimeter = side * 3
# Вычисление... |
"""
This job processes guru dataset and exports the processed data object
"""
import logging
import pandas as pd
from data.data_provider import DataProvider
from data.data_exporter import DataExporter
from sklearn.preprocessing import MultiLabelBinarizer
from freelancer.freelancer_dataset import FreelancerData
class... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.model_selection import train_test_split
class Calculate(object):
def __init__(self, ddofnumber, csvstring, columnname='price', correlationname='overall_satisfaction'):
self.dd... |
import os
import shutil
import tempfile
import pytest
import pyproj
@pytest.fixture(scope="session")
def aoi_data_directory():
"""
This is to ensure that the ntv2_0.gsb file is actually
missing for the AOI tests.
"""
data_dir = pyproj.datadir.get_data_dir()
with tempfile.TemporaryDirectory()... |
def add_stop_words(new_word):
'''
INPUT: STR, new word to list to the added stop list
OUTPUT: SET of updated stop words
'''
added_stop_words = {'rt', 'via', 'new', 'time', 'today', 'one', 'say', 'get', 'go',
'im', 'know', 'need', 'made', 'https', 'http', 'that', 'would',
... |
import threading
import sys
import json
class waitingRoom():
def __init__(self,d):
self.d = d
self.lobbyLock=list()
self.logged=0
def logging(self,clientsock):
username=""
password=""
loggIn=self.log_in_data(username,password)
#while (True,1) or... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import time
import xlwt #创建workbook和sheet对象
workbook = xlwt.Workbook() #注意Workbook的开头W要大写
sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)
sheet1.write(0,0,'序号')
sheet1.write(0,1,'通用名' )
sheet1.write(0,2,'剂型')
sheet1.write(0,3,'规格')
she... |
import sys
import click
import requests
import json
import re
from PIL import Image
try:
from StringIO import StringIO
except: # when using python3.x
from io import BytesIO, StringIO
from bs4 import BeautifulSoup
#IMDBSEARCHURL = 'http://www.imdb.com/search/title?title=The%20Godfather&page=1&ref_=adv_nxt'
I... |
import webbrowser # imports web browser controller
class Movie ():
"""Class containing the attributes common to all movie objects.
Args:
movie_title (str): movie title.
movie_storyline (str): storyline summary.
poster_image (str): url to the movie's poster image.
trailer_youtube (str): url to th... |
import torch
import torch.nn.functional as F
device = torch.device("cuda:0")
latent_size = 24
label_size = 10
class MaxOneHot(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
idx = torch.argmax(input, dim=0)
ctx._input_shape = input.shape
ctx._input_dtype = input.dty... |
import numpy as np
import sys
class SOM(object):
def __init__(self, dims, grid_side):
self.neurons = np.random.random((grid_side * grid_side, dims))
grid = []
# for x in range(grid_side):
# for y in range(grid_side):
# grid.append([x, y])
# self.grid = np.... |
import datetime
import time
game = "FFX_"
ext = ".txt"
fileName = "none"
fileStats = "none"
def writeLog(message):
global logFile
global fileName
logFile = open(fileName, "a")
logFile.write(message)
logFile.write("\n")
logFile.close()
def nextFile():
global fileName... |
#coding=utf-8
#作者:cq
#创建时间:2019/3/21 15:55
#IDE: PyCharm
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['name', 'email', 'url', 'text'] |
from typing import List, Optional, Union
from pydantic import BaseModel, Field, constr, root_validator, validator
from virtool_core.models.history import HistorySearchResult
from virtool_core.models.index import IndexMinimal
from virtool_core.models.reference import (
Reference,
ReferenceGroup,
ReferenceIn... |
import os
import random
import shutil
import sys
def sample_files():
in_dir = sys.argv[1]
source_dir = os.path.join(in_dir, "tabel")
target_dir = os.path.join(in_dir, "tabel-sample")
source_files = []
for file_name in os.listdir(source_dir):
if file_name.endswith('.csv'):
sour... |
from typing import List
# 可以分为两部分,第一部分是最长递增子序列,第二部分是最长递减子序列
class Solution:
def longestMountain(self, A: List[int]) -> int:
if not A:
return 0
n = len(A)
left = [0] * n
for i in range(1, n):
left[i] = (left[i - 1] + 1 if A[i - 1] < A[i] else 0... |
import argparse
import json
from helpers import *
def get_assocs_info(associations_file,rare_diseases_list,EFO_names):
# Parses the Open Targets associations file and the list of rare diseases (output from `rare_diseases.py`) to collect the following
# for diseases which are highly associated with each target
# (... |
#!/usr/bin/env python
import socket
import serial
import time
import math
#UDP settings:
UDP_IP = "89.103.47.53" #89.102.98.39"
UDP_PORT = 8089
#serialport settings:
#ser = serial.Serial('/dev/ttyACM3', 9600, timeout=61, xonxoff=False, rtscts=False, dsrdtr=False)
#serial flushing
time.sleep(0.5)
#ser.flushInput()... |
from __future__ import print_function
import numpy as np
import sys
import os
import time
import subprocess
import argparse
import signal
def eprint(*args, **kwargs): #prints errors/warnings to stderr
print(*args, file=sys.stderr, **kwargs)
def signal_handler(signal, frame):
global interru... |
#import
import os
import sys
import numpy as np
#------------------------------------------------------------------
def bayes(pA,pB,pBA):
pAB = (pBA * pA) / pB
return pAB
#------------------------------------------------------------------
if __name__ == '__main__':
#What is the probability of a facecar... |
import argparse
import keras
from keras import backend
from keras.layers import Dense, Flatten
from keras.applications import resnet50
from keras.preprocessing.image import ImageDataGenerator
import os
from keras.models import Sequential
defaults = {
'num_classes': 10,
'epochs': 100,
'batch_size': 128,
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 09:02:24 2019
@author: Administrator
"""
import numpy as np
import pandas as pd
import numba
import matplotlib.pyplot as plt
import seaborn as sns
import os
from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix
from CCAM im... |
import pandas as pd
def get_data(tr_file_name,ts_file_name):
x_train,y_train,w_train = None,None,None
x_test,y_test,w_test = None,None,None
cols = None
if tr_file_name:
print "Loading training dataset..."
print "..\n."
tr_data = pd.read_csv(tr_file_name,index_col=0)
cols = tr_data.columns
x_train = ... |
from Acquisition import aq_inner
from Acquisition import aq_parent
from plone.app.layout.nextprevious.interfaces import INextPreviousProvider
from plone.app.layout.viewlets import ViewletBase
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile
from zo... |
import os
import glob
dts = ['train','tune', 'test']
dts_out = [ 'train', 'dev', 'test']
domains = ['Family_Relationships', 'Entertainment_Music']
for dt,dt_out in zip(dts,dts_out):
fout = open(os.path.join('slue_data','GYAFC','{}.tsv'.format(dt_out)),'w')
for domain in domains:
for label in ['forma... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Process Success and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.model.naming import make_autoname
from process_success.ps_core.api import get_cre... |
# for tc in range(int(input())) :
# n = int(input())
# ma = []
# for i in range(n) :
# ma.append(list(map(int,input().split())))
# c = [-1] * n
# for i in range(n-2,-1,-1) :
# res = []
# while len(res) < n :
# t = 0
# a = -1
# b = -1
# for i in range(n) :
# for j in range(n) :
# if ma[i][j] > t... |
from django.test import TestCase, Client, RequestFactory
from django.core import mail
from django.urls import reverse
from django.http import HttpRequest
from django.contrib import messages
from django.contrib.auth import get_user_model
from accounts.views import validate_email
User = get_user_model()
c... |
"""Files tests simple file read related operations"""
from __future__ import division
from io import open
class SimpleFile(object):
"""SimpleFile tests using file read api to do some simple math"""
def __init__(self, file_path):
self.numbers = []
"""
TODO: reads the file by path and pa... |
import numpy as np
from w2v_utils import *
words, word_to_vec_map = read_glove_vecs('glove.6B.50d.txt')
print(word_to_vec_map.keys())
def cosine_similarity(u, v):
distance = 0.0
dot = np.dot(u, v)
norm_u = np.linalg.norm(u)
norm_v = np.linalg.norm(v)
cosine_similarity = dot / (norm_u ... |
from django.contrib.auth import authenticate
from django.contrib.auth.models import update_last_login
from rest_framework.authtoken.models import Token
from bankapp.models import LoanDetail, User, LoanUserAddress, Document, Review, AddressType
from django.core import exceptions
import django.contrib.auth.password_valid... |
'''
Constants and Configuration data for simulation
{"TC": {"TC0": [78.9337934710637, "F"]}, "AI": {"AI0": [5.102922332635204, "V"]}, "DI": {"DI0": 1}}
'''
################ Constants #########################
#Units
DEGREES_F = 'F'
DEGREES_C = 'C'
VOLTS = 'V'
AMPS = 'A'
############ Sensor Configuration Data ######... |
import codecs
import re
# 找到所有的app名称
from collections import Counter
def findApps(apps, data):
# 将NOR关键字分行处理,便于后续操作
data = data.replace('[NOR]', '\n[NOR]')
rcode = r'\b' + start + r'.*?' + end + r'\b'
a = re.findall(rcode, data, flags=0)
for i in a:
# 裁剪字符串
s = i.find(']') + 1
... |
#!/usr/bin/env python
import crypto
INPUT = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
KEY = "ICE"
def repeat_to_length(string_to_expand, length):
return (string_to_expand * ((length/len(string_to_expand))+1))[:length]
def xor_with_key(string, key):
char_string = repeat_... |
# coding:utf-8
from rest_framework import serializers
from menu.serializers import MenuSerializer
from .models import Role
class RoleSerializer(serializers.ModelSerializer):
menu = MenuSerializer(many=True)
class Meta:
model = Role
fields = "__all__"
|
import calendar
# print(calendar.calendar(2020))
# calendar.prcal(2020)
# print(calendar.month(2020, 6))
# calendar.prcal(2020, 6)
# year = int(input("년도를 입력하세요:")) #년도를 입력하세요:2021
# print(year, "년은", "윤년입니다." if calendar.isleap(year) else "평년입니다.") #2021 년은 평년입니다.
weekdays = ["월", "화", "수", "목", "금", "토", "일"]
pri... |
# -*- coding: utf-8 -*-
"""
Temperature Conversion
Created on Wed Nov 20 05:20:50 2019
@author: Ashley
"""
temperature = ""
while temperature.upper() != "Q":
# Get a temperature, specified in Kelvin, Centigrade, or Fahrenheit.
temperature = input("Enter a temperature number and scale letter" +
... |
class Validator(object):
@staticmethod
def validate(element, selector):
selector_tag_name = selector.get('tag_name')
element_tag_name = element.tag_name.lower()
if selector_tag_name and selector_tag_name != element_tag_name:
return None
return element
|
from invoke import run, task
@task
def test():
run("nosetests .")
# We'll want these eventually.
'''
@task
def doc():
run('cd docs && make html')
@task
def docserve():
print 'Serving docs on localhost:8000...'
run('cd docs/_build/html && python -m SimpleHTTPServer')
@task
def publish():
run('./setup.... |
# dict.popitem()
# dictionary에 가장 최근에 삽입된 item(key, value)를 반환하고, 해당 dictionary에서 삭제한다.
a = dict()
a[1] = "a"
a[3] = "c"
a[2] = "b"
print(a.popitem())
# (2, 'b')
print(a)
# {1: 'a', 3: 'c'} |
from django.contrib import admin
from apps.docs.models import DocsTitle, Docs
class DocsInline(admin.TabularInline):
model = Docs
class DocsTitleAdmin(admin.ModelAdmin):
inlines = [
DocsInline,
]
admin.site.register(DocsTitle, DocsTitleAdmin) |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
x=np.linspace(0,5,20)
plt.subplot(111)
y2=2*np.sin(0.5*np.pi*x+2)
plt.title('正弦信号')
plt.grid(True)
plt.stem(x,y2)
plt.show() |
# 9-2 Three Restaurants
from tiy_9_1 import Restaurant as rest
r1 = rest('red lobster', 'seafood')
r2 = rest("maggiano's", "italian")
r3 = rest("chen's", "chinese")
r1.describe_restaurant()
r2.describe_restaurant()
r3.describe_restaurant()
|
import time
from sentian_miami import get_solver
def main():
t0 = time.time()
solver = get_solver("mono")
a = solver.NumVar(lb=0)
b = solver.NumVar(lb=0)
c = solver.NumVar(lb=0)
solver.Add(a == 1)
solver.Add(2*a - 2*b == 0)
solver.Add(-1*a + 1*c == 0)
#solver.SetObjective(a + b,... |
# pytest文档33-Hooks函数获取用例执行结果(pytest_runtest_makereport)
# pytest_runtest_makereport
"""
这里item是测试用例,call是测试步骤,具体执行过程如下:
-- 先执行when=’setup’ 返回setup 的执行结果
-- 然后执行when=’call’ 返回call 的执行结果
-- 最后执行when=’teardown’返回teardown 的执行结果
"""
# 运行案例
"""
conftest.py
test_hooks_1.py
运行用例的过程会经历三个阶段:setup-call-teardown,每个阶段都会返回的 Res... |
import unittest
from Calculator.Calculator import Calculator
class MyTestCase(unittest.TestCase):
def setUp(self):
self.calculator = Calculator()
def test_setUp(self):
self.assertIsInstance(self.calculator, Calculator)
def test_calc_return_add(self):
result = self.calculator.add... |
#!/usr/bin/env python3
from sys import argv
import json
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib.figure import Figure
assert len(argv) == 3
data = json.loads(open(argv[1], "r").read())
rc("figure", figsize=(11.69, 8.27))
fig = plt.gcf()
fig = plt.figure()
ax = fig.add_subplot(111)
... |
import joblib
import numpy as np
import torch
from torch import nn, optim
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
y_train = torch.from_numpy(y_train.astype(np.int64)).clone()
X = X_train[0:4]
y = y_train[... |
import heapq
ggraph = []
trap = []
graphFake = []
ge = 0
mn = 1e9
def dfs(curr, distance_cost):
global graphFake, mn
fake = 0
if curr == ge:
mn = min(distance_cost, mn)
return
if curr in trap:
if not graphFake[curr]:
graphFake[curr] = True
fake = 1
... |
# This file is part of OpenVideoChat.
#
# OpenVideoChat is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenVideo... |
from activities.models import Message
from categories.models import Category, Keyword
from constance import config
from employees.models import Employee, Location, Position, Role
from events.models import Event, EventActivity
from stars.models import Badge
from django.conf import settings
from django.contrib.sites.mode... |
# encoding: utf-8
# module System.Runtime.InteropServices.ComTypes calls itself ComTypes
# from mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. ... |
# A partir du code du slide "Animation", faites bouger le cercle
# en x et en y et faites le rebondir sur les bords de la fenêtre
# Ce défi ne compte pas pour la note
import pygame
# initialisation de pygame
pygame.init()
# demande une fenêtre de 800x600 pixels
screen = pygame.display.set_mode([800, 600])
xCircle =... |
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
if not l1:
... |
from flask import Flask, render_template, url_for
app = Flask(__name__)
#Hola Mundo
@app.route('/')
def index():
return "<h2> Hola mundo </h2>"
@app.route('/nodeschool')
def node():
return "NodeSchool San Miguel"
#Pasando variables mediante la ruta
@app.route('/saludo/<nombre>',methods=['GET','POST'])
def ... |
import rdflib
from rdflib.Graph import Graph
# TODO : improve namespace usage
rdf_type = rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')
lv2_ControlPort = rdflib.URIRef('http://lv2plug.in/ns/lv2core#ControlPort')
lv2_index = rdflib.URIRef('http://lv2plug.in/ns/lv2core#index')
lv2_symbol = rdflib.URIRe... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import newton
import os
os.environ['QT_PLUGIN_PATH'] = '/opt/anaconda3/lib'
def r1():
def func(x):
return (x**x) - 100
def derivada(x):
return (x**x) * (np.log(x)+1)
root= newton(func, x0=3, fprime=derivada)
print(... |
a = {"맥북13인치2015":80, "ps4slim":20, "desktopPC":40}
b = a.values()
print(b)
print(type(b))
|
'''
Created on Sep 6, 2016
@author: sheldonshen
'''
class Animal(object):
def run(self):
print("Animal is running")
class Dog(Animal):
def run(self):
print("Dog is running")
def eat(self):
print("Eating meat....")
class Cat(Animal):
def run(self):
pr... |
import pandas as pd
import json
exchanges_filter_all = ["NYMEX", "CME", "NASDAQ", "EEXP", "DTN", "ENID", "NYSE", "EEXE", "EEXN", "FTSE", "SGX", "CME-FL", "CBOT", "MGE", "NFX", "ICEFU", "ICEFC", "KCBOT", "ICEEF", "ICEEC", "KBCB", "MGKB", "MGCB", "COMEX", "CFE", "PK_SHEETS", "DJ", "OPRA", "NYSE_MKT", "ASXCM", "BMF", "B... |
"""Given a list of numbers 1...max_num, find which one is missing in a list."""
#define function that takes in list of nums, and max_num
def missing_number(nums, max_num):
"""Given a list of numbers 1...max_num, find which one is missing.
*nums*: list of numbers 1..[max_num]; exactly one digit will be missing... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 6 18:16:01 2019
@author: amazinger
"""
import sys, pygame
import random
import numpy as np
import matplotlib.pyplot as plt
class Maze:
def __init__(self, width, height):
if width < 3:
print("error: width should not less t... |
import discord
import utilities as utils
import objects as obj
import database as database
POLLS = database.PollDatabase()
MEMES = database.MemeDatabase()
COMMANDS = database.CommandDatabase()
class CommandDataHolder():
# Holds data for commands
def __init__(self, name, args_array, args_text, channel, author):
... |
#!/usr/bin/env python
from sunlight import openstates
import json
import sys
obj = json.load(open(sys.argv[1], 'r'))
ret = []
for state in obj:
inf = obj[state]
total = len(inf['upper']) + len(inf['lower'])
ret.append({
"name": state,
"count": total
})
print json.dumps(ret)
|
# In previous code, we are decreasing the resolution one by one
# But we have one method called as gaussian pyramid
import cv2
img = cv2.imread('./data/lena.jpg')
layer = img.copy()
gaussian_pyramid = [layer]
for i in range(6):
layer = cv2.pyrDown(layer)
gaussian_pyramid.append(layer)
cv2.imshow(str(i), ... |
#!/usr/bin/python
"""
Parsing of incomming messages from Parrot Bebop
usage:
./navdata.py <logged file>
"""
import sys
import struct
ARNETWORKAL_FRAME_TYPE_ACK = 0x1
ARNETWORKAL_FRAME_TYPE_DATA = 0x2
ARNETWORKAL_FRAME_TYPE_DATA_LOW_LATENCY = 0x3
ARNETWORKAL_FRAME_TYPE_DATA_WITH_ACK = 0x4
ARNETWORK_MANAGER... |
import numpy as np
import cv2
import math
block_size = (8, 8)
PI = math.pi
Q = np.array([[16, 11, 10, 16, 24, 40, 51, 61],
[12, 12, 14, 19, 26, 58, 60, 55],
[14, 13, 16, 24, 40, 57, 69, 56],
[14, 17, 22, 29, 51, 87, 80, 62],
[18, 22, 37, 56, 68, 109, ... |
# WAP to create a guessing game where the user inputs the secret number and guessing limit for his friend to play.
from random import randint
start=input("Press enter to start the game, 'quit' to exit: ")
if start=='':
try:
ans = int(input("Enter the number you want someone to guess: "))
no_of_gues... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Fan
from datetime import datetime
def index(request):
return HttpResponse(loader.get_template('quiz/index.html').render())
def new(request):
if request.method == "GET":
name ... |
# Generated by Django 3.1.3 on 2020-11-09 10:43
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
import django.utils.timezone
class Migration(migrations.Mi... |
import unittest
import numpy as np
from shapely.geometry import LineString, Point, Polygon
from threedigrid.orm.base.fields import ArrayField
from threedigrid.orm.base.filters import (
BaseCompareFilter,
BaseFilter,
EqualsFilter,
get_filter,
InFilter,
)
from threedigrid.orm.fields import (
Bbo... |
class Basic:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child == None:
self.left_child = Basic(value)
else:
new_node = Basic(value)
new_node.l... |
class Solution(object):
def reverse(self, x):
y=x
x=int(str(abs(x))[::-1])
if (abs(x) > (2 ** 31 - 1)):
x=0
return -x if(y<0) else x
print(2 ** 31 - 1)
val=Solution().reverse(1534236469)
print(val)
|
# Generated by Django 2.2.16 on 2020-09-21 15:07
import core.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("aids", "0108_auto_20200615_1055"),
]
operations = [
migrations.RenameField(
model_name="aid",
ol... |
# vindo da pagina:
# http://computsimu.blogspot.com/2015/07/interior-point-method-primal-affine.html
import numpy as np
import scipy.io
from scipy.sparse import csr_matrix
import scipy
import pandas as pd
import time
import math
import numba
class PrimalAffine(object):
def __init__(self, c, a, b, opt_gap=1.0e-6,... |
from __future__ import print_function, unicode_literals
from pynxos.device import Device
from getpass import getpass
from pprint import pprint
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
device = Device(host... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.