text stringlengths 8 6.05M |
|---|
from .IPFSServices import IPFSServices |
import numpy as np
import pandas as pd
import seaborn as sns
import folium
import json
from matplotlib import pyplot as plt
from folium import plugin
dados = pd.read_csv("crime.csv", encoding = "latin-1", keep_default_na=False)
locations = dados.groupby('REPORTING_AREA').first()
locations = locations.loc[:, ["lat", "l... |
"""
Bits for creating spline curves.
Class BSplineCurve:
A class that creates, maniuplates, and queries basis-spline curves.
"""
import logging
from typing import Callable, Optional
import numpy as np
from zu.analytic_curve import AnalyticCurve
class BSplineCurve(AnalyticCurve):
"""B-Spline curves are geo... |
from collections import defaultdict
def search_nearby(i, j, grid, paths, n):
"""search_nearby
Returns:
A dictionary which format is like:
{0: No. of Paths, 1: No. of Paths, 2: No. of Paths ...}
Description:
This is a recursive function.
It starts from a coordinate (i, j) which value is n.
... |
from sklearn.externals import joblib
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
import json
if __name__ == '__main__':
with open('log.json') as json_file:
data = json.load(json_file)
data = pd.DataFrame.from_dict(data)
print(data)
# data = pd.DataFrame.from_csv("d... |
__all__ = [
'UpdateGraphsData',
]
from gim.core.tasks.repository import RepositoryJob
class UpdateGraphsData(RepositoryJob):
queue_name = 'update-graphs-data'
def run(self, queue):
super(UpdateGraphsData, self).run(queue)
from .limpyd_models import GraphData
graph, _ = GraphData... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright: Fabien Rosso
# Version 0.1.1 - 19 Avril 2016
# Version 0.1.2 - 29 Avril 2016
from __future__ import unicode_literals
from __future__ import print_function
import os
import psutil
def ListDirectory(path):
''' Fonction listdirector... |
n = int(raw_input().strip())
x = 0
y = 0
for a_i in xrange(n):
a_temp = map(int, raw_input().strip().split())
x += a_temp[a_i]
y += a_temp[n - a_i - 1]
print abs(x - y)
|
# Generated by Django 2.1.3 on 2019-03-28 13:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0006_auto_20190328_0409'),
]
operations = [
migrations.AlterField(
model_name='acciones... |
from collections import OrderedDict
from urllib.parse import urlencode
'''
"params": "query=Materiais de Constru%C3%A7%C3%A3o&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__/ais-highlight__&filters=hide_prices:false AND available:true AND (campus_city:"Aracaju" OR campus_virtual:true) AND (campus_state_a... |
from matrix import Matrix
def main():
A = Matrix([[1,2,3], [2, 4, 4], [4, 4, 4]])
B = Matrix([[1,2,3], [2, 40, 4], [4, 4, 4]])
print(A)
print(B)
print(B.add(A))
if __name__ == '__main__':
main()
|
class Edge:
def __init__(self, startVertex, endVertex):
self.startVertex = startVertex;
self.endVertex = endVertex;
|
from django.db import models
class BlockModel(models.Model):
block_index = models.CharField(max_length=255, unique=True)
block_timestamp = models.CharField(max_length=255)
block_id = models.CharField(max_length=255)
block_hash = models.CharField(max_length=255)
block_previous_hash = models.CharFie... |
import http.client, urllib.request, urllib.parse, urllib.error, base64
from PIL import Image
import numpy as np
from aip import AipImageClassify
from aip import AipOcr
import platform
import ssl
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
def image_caption... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
本示例代码仅作参考。如果您是业务调用,建议对body体也做加密。
注意:本示例用到的鉴权方式不适用于一部分产品(语音识别、人脸识别等)。请查阅您使用产品的API文档,如果鉴权方式基于Access Key(包括Access Key ID(AK)和Secret Access Key(SK)),
且最终认证字符串为bce-auth-v{version}/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}/{signedHeaders}/{signature},则适用本示例。
此外,部... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def number_visible_nodes(self, root):
"""
"""
max_so_far = float('-inf')
count = self.count_visible_nodes(root, max_so_far)
ret... |
#!/usr/bin/env python3
"""
PEA simulateur - Draw cotation
Copyright (c) 2020-2021 Nicolas Beguier
Licensed under the MIT License
Written by Nicolas BEGUIER (nicolas_beguier@hotmail.com)
"""
from pathlib import Path
import sys
import matplotlib.pyplot as plt
# Debug
# from pdb import set_trace as st
COTATION_DIR = s... |
solarsys = ['태양','수성','금성','지구','화성','목성','토성','천왕성','해왕성','지구']
planet = '지구'
pos = solarsys.index(planet)
print('%s은(는) 태양계에서 %d번째에 위치하고 있습니다.'%(planet,pos))
pos = solarsys.index(planet,5)
print('%s은(는) 태양계에서 %d번째에 위치하고 있습니다.'%(planet,pos))
|
from flask import Flask, render_template, request, jsonify
import TestScript
import os
import werkzeug
import cv2
import io
import base64
import time
from PIL import Image
path = "C:/Classnotes/Dress-Virtual-Trialroom/static/"
fn = []
app = Flask(__name__)
def get_response_image(image_path):
with open(image_path... |
class clusterClass:
def __init__(self, res, box, id, car_flag):
self.res = res
self.box = box
self.id = id
self.car_flag = car_flag
self.processed = 0
|
# 区间dp
class Solution:
def strangePrinter(self, s: str) -> int:
n = len(s)
# f[i][j]表示打印i~j字符串需要的最少步数
# 求f[0][n-1]
f = [[math.inf]*n for _ in range(n)]
for i in range(n):
f[i][i] = 1
for d in range(2, n+1):
for l in range(n-d+1):
... |
# -*- coding: utf-8 -*-
# Задача на программирование повышенной сложности: огромное число Фибоначчи по модулю
# Даны целые числа 1≤n≤1018 и 2≤m≤105, необходимо найти остаток от деления n-го числа Фибоначчи на m.
# Sample Input:
# 47905881698199969 76940
# Sample Output:
# 13794
import sys
from functools import lr... |
from ..config import BaseProposalCreatorConfig
import json
from grant.proposal.models import Proposal, ProposalRevision
from grant.utils.enums import ProposalChange
from ..test_data import test_team
test_milestones_a = [
{
"title": "first milestone a",
"content": "content a",
"daysEstimat... |
from app import api
from hello import handlers as hello_handlers
api.add_route('/', hello_handlers.HelloResource())
api.add_route('/test', hello_handlers.HelloResource())
api.add_route('/whatever', hello_handlers.TestVariableResource())
|
"""
z_algo.py
Name: Wirmantono
Contains function for Z algorithm, a linear time pattern matching algorithm
"""
def z_algo(input_str):
"""
Z-algorithm performs prefix matching in linear time
The following implementation of algorithm are based on
Lecture slides provided by the Unit Coordinator for the ... |
from django.utils.encoding import force_text
from wagtail.admin import compare
def page_revision_diff(revision_a, revision_b):
comparison = [
comp(revision_a, revision_b)
for comp in revision_b.get_edit_handler().get_comparison()
]
comparison = [comp for comp in comparison if comp.has_cha... |
import numpy as np
import sys
from Gravity.functions import (mPrismCart, mpoinCart, mHollowSphere,
update_progress)
from Gravity.plotting import plot_gravity, plot_hollow_sphere
"""
v 1.0
Gravity modelling
with point mass and prism models
Author: I. Vasconcelos 2016
Translated t... |
from django.db import models
# Create your models here.
class Led(models.Model):
hub_information = models.CharField(max_length=256)
hub_id = models.IntegerField(default=0)
|
from django.urls import path, re_path
from . import views
urlpatterns = [
path('addhosts/', views.add_hosts, name='add_hosts'),
path('addmodules/', views.add_modules, name='add_modules'),
path('tasks/', views.tasks, name='tasks'),
path('result/', views.result, name='result'),
re_path('^del_arg/(?P<... |
import unittest
from collections import OrderedDict
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../src')
from bio_formators import clean_format_sequence, format_to_string, format_gc_content
class TestBioFormators(unittest.TestCase):
def test_clean_sequence(self)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-23 16:27:40
# @Author : ayyll (upyh@foxmail.com)
# @Link : http://ayyll.com
# @Version : V-1.0.0
import os
import sys
#获取当前目录下的文件
file_arr = os.listdir(os.getcwd())
for i in range(len(file_arr)):
if file_arr[i].endswith('.c') or f... |
import os
import sys
import shutil
import time
import saved_metrics
sys.path.insert(0, 'scripts')
sys.path.insert(0, os.path.join("tools", "families"))
import experiments as exp
import fam
import sequence_model
import ete3
def generate_scheduler_commands_file(datadir, subst_model, cores, output_dir):
results_dir = o... |
import plotly.express as px
import csv
with open("csv files\Student Marks vs Days Present.csv",encoding = "utf-8") as csv_file:
df = csv.DictReader(csv_file)
fig = px.scatter(df,x = "Marks In Percentage",y = "Days Present")
fig.show() |
#!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# # Authors informations
#
# @author: HUC Stéphane
# @email: <devs@stephane-huc.net>
# @url: http://stephane-huc.net
#
# @license : BSD "Simplified" 2 clauses
#
''' Tools needed for Class PixUP '''
import pprint
import... |
#!/usr/bin/env /proj/sot/ska/bin/python
#########################################################################################
# #
# recover_compgradkodak.py: recover compgradkodak_fits from beginning #
# ... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies simple actions when using an explicit build target of 'all'.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('all.g... |
# Find the minimum path sum from top left to bottom right of an N x N matrix by
# only moving to the right and down.
myMatrix = []
def findMinPathSum():
global myMatrix
matrixSize = readMatrix()
for row in range(0, matrixSize):
for col in range(0, matrixSize):
if row != 0 or col ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Hanzhiyun'
def normalize(name):
name = name[0].upper() + name[1:].lower()
return name
# return name.capitalize() #Python 自带的函数使首字母大写,其余小写
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
|
from django.contrib import admin
# import에 include 추가
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# urlpatterns에 추가
path('test1/', include('test1.urls')),
]
|
from django.contrib import admin
from .models import Organization, UserProfile, MailingList
class OrganizationAdmin(admin.ModelAdmin):
pass
class UserProfileAdmin(admin.ModelAdmin):
pass
class MailingListAdmin(admin.ModelAdmin):
pass
admin.site.register(Organization, OrganizationAdmin)
admin.site.regist... |
"""Plot words on sheet."""
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
class PlotObjects(object):
def __init__(self, page_plot, object_in, colour):
self.page_plot = page_plot
self.object_top = object_in[1]
self.object_right = object_in[2]
self.o... |
from tkinter import *
import math, random
import sqlite3
import sys
import django
from time import sleep
django.setup()
# Conductor est un daemon
from threading import Thread
from components.mission import Mission
import signal
polling_interval = 1
def bddCreation():
"""
CREATE TYPE droneStatus AS ENUM('busy'... |
import numpy as np
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import train_test_split
from mypipeline import Mu... |
#!/usr/bin/python
"""
bulkhover.py 1.1
This is a command-line script to import and export DNS records for a single
domain into or out of a hover account.
Usage:
bulkhover.py [options] (import|export) <domain> <dnsfile>
bulkhover.py (-h | --help)
bulkhover.py --version
Options:
-h --help Show this... |
#!/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... |
"""ImageCropper module; imported by ImageOperate aggregate class."""
import statistics
import ImageColumnCropOperators
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
pd.options.mode.chained_assignment = None
class ImageCropper(object):
"""
Cropping function; rem... |
l=list(map(int,input()))
for x in range(0,len(l)):
if(l[x]%2!=0):
print(l[x],end=" ")
|
# Exercício 8.3 - Livro
def areaQuadrado (lado):
area = lado ** 2
return area
a = areaQuadrado(9)
print(a)
|
# ------------------------------------------------------------------------------
# Gnn like cnn Pytorch Implementation
# paper:
# https://arxiv.org/abs/1603.09065
# Written by Haiyang Liu (haiyangliu1997@gmail.com)
# ------------------------------------------------------------------------------
from collections import... |
# -*- coding: utf-8 -*-
'''
Implementa todo el codigo relacionado al modelo y las entidades de los usuarios
'''
import psycopg2
from psycopg2 import pool
from psycopg2.extras import DictCursor
import inject
from model.registry import Registry
import logging
logging.basicConfig(format='%(asctime)s, %(stack_info)s... |
import praw
import time
import datetime
import re
import os
import urllib
import requests
import json
from goog import getQuotes
from collections import OrderedDict
__author__ = '/u/spookyyz'
__version__ = '0.2'
user_agent = 'Stock Quotr 0.2 by /u/spookyyz'
r = praw.Reddit(user_agent=user_agent)
r.login(os.environ['R... |
N=int(input("N="))
sum=int
if(N>0):
sum=0
for i in range(N,2*N+1):
x=i**2
sum=sum+x
print(sum) |
import pandas as pd
import numpy as np
import matplotlib.pyplot as mpl
import copy
import time
# Plot define
mpl.show(block=True)
# Absolute path
path_to_dataset = ''
csv_name = 'NYPD_Motor_Vehicle_Collisions'
def compute_total_weeks(dataframe):
#Print minimum and maximum timestamps available
min_timestamp = min(da... |
from flask import Flask , request
from flask_restful import Resource , Api,reqparse
import json , time
app = Flask (_name_)
api = Api(app)
APP_ROOT =os.path.dirname()
parser = reqparse.RequestParser()
parser.add_argument('info')
class Hello(Resource):
def post(self):
args = parser.parse_args()
name ... |
import sqlite3
from flask import Flask
from flask import render_template, request
from flask import jsonify, flash
app = Flask(__name__)
app.secret_key = "888"
def db_connection():
dbconn = sqlite3.connect('../Data/CTA_Data.db')
cur = dbconn.cursor()
return (cur, dbconn)
@app.... |
import csv
class data_logger():
def twoPressurTransducers(self, data, iteration, fileName='youForgotToNameYourFile',
save_path='C:/Users/bob/Desktop/imu_presure/tests/test_files/'):
fileName = fileName + '.csv'
nameOfFile = save_path + fileName
if iteration =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @Time : 2019-06-20 10:14
# @Author : ryuchen
# @File : ResultManager.py
# @Desc :
# ==================================================
import os
import json
import errno
import socket
import logging
import threading
im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import configparser
import os
import re
import sys
from operator import methodcaller
import pexpect
from funcy import (
autocurry,
compose,
count_by,
filter,
lmap,
lmapcat,
map,
mapcat,
merge,
partial,
rcompose,
re_all,
re... |
#!/usr/local/bin/python3.8
print('Hello, Nabeel')
users_input = input('Enter a message: ')
# First character
print ( 'First character:', users_input[0] )
# Last character
print ( 'Last character:', users_input[-1] )
# Middle character
print ( 'Middle character:', users_input[ int(len(users_input) / 2) ] )
# Ev... |
import torch
from torch import optim
import math
def _check_param_device(param, old_param_device):
if old_param_device is None:
old_param_device = param.get_device() if param.is_cuda else -1
else:
warn = False
if param.is_cuda: # Check if in same GPU
warn = (param.get_devi... |
# coding=utf-8
# matplotlib背景透明示例图
# python 3.5
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl
# import scipy.stats as stats
# 设置中文字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
fig, ax = plt.subplots()
font = {'family': 'Times New Roman',
# 'weight' : 'bold',
'size': 12}
pl... |
from sklearn.model_selection import train_test_split
import pandas as pd
import os
import args
import bert
from bert import run_classifier
from bert import tokenization
def data_processor():
if os.path.exists("sentiment_data/train.csv"):
x_train = pd.read_csv("sentiment_data/train.csv")
x_test ... |
from typing import List, Tuple
from pathlib import Path
from collections import deque
from itertools import repeat
"""
Part 1: find boxes with similar ids
Tasks:
- count the boxes that have exactly 2 repeated letters in their id
- do the same for 3 repeats
Hint: multiple occurences of repeats count only once... |
import os
import re
import wikipedia as wiki
from urllib2 import urlopen
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
from math import log
def tokenize(review, remove_stopwords = True ):
# Function to convert a document to a sequence of words,
# optionally removing stop words. Returns a li... |
#Dictionary python.
# import required libirary
from tkinter import *
from pip import PyDictionary
# Create Object
dictionary = PyDictionary()
root = Tk()
#Set geometry
root.geomentry("400x400")
def dict():
meaning.config(text=dictionary.meaning(word.get())['None'][0])
synonym.config(text=d... |
import json
class MsgConvert():
def __init__(self):
pass
def msg_json(self):
pass
def json_msg(self):
pass
if __name__ == '__main__':
app = MsgConvert()
|
# Generated by Django 3.0.3 on 2020-02-23 02:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import sys
import nltk
import sklearn
print ("Configurations")
print (sys.version) + str("\n")
print str(sys.version_info) + str("\n")
print (sys.path)
print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))
|
# Python dictionary
dictionary = {
"word" : "Meaning",
"python" : "fast programing language",
"C" : "Speed",
"HTML" : "Not programing language"
}
print(dictionary["python"])
# to add elements in python dictionary
dictionary["machine language"] = 10101
print(dictionary)
# To change values in exis... |
from flask import Flask, request
from sqlalchemy.orm import create_session
import sqlite3
import random
from flask import Flask
from flask import request, url_for
from sqlalchemy.orm import sessionmaker
import sqlalchemy
from data import db_session
import db
import sqlite3
app = Flask(__name__)
db_ses... |
#--*-- codign:utf-8 --*--
import sys
from PyQt4 import QtGui,QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example,self).__init__()
self.initUI()
def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif',10))
self.setToolTip('This is a <b>QWidget</b> wid... |
import numpy as np
import h5py
import mcubes
from mayavi import mlab
#from itertools import count
from mayavi.api import OffScreenEngine
import trimesh
input_model_file = 'CA1_ssmall_model.lm'
input_morpho_file = "CA1_ssmall.h5"
# input_morpho_file = "CA1_small.h5"
# input_morpho_file = "CA1.h5"
output_file = 'morph... |
"""
What I will learn
Modules
More built-in Python functions
Module search path
Python Standart Library
#Modules
Python modules are files that have a .py extension.
They can implement a set of attributes (variables), methods(functions), and classes(types).
A module can be included in another Python program by using t... |
from django.shortcuts import render, redirect, reverse
from .models import *
from django.contrib import messages
# Create your views here.
def landing(request):
return render(request, 'login/landing.html')
def process(request):
print 'entered process'
if 'register' in request.POST:
print 'register... |
"""
This code computes the order of two sibling nodes in a dependency subtree,
where the left and the right siblings are defined on the source dependency tree.
Each node is represented by the continuous vector of its dependency link to its
parent node.
"""
__docformat__ = 'restructedtext en'
import os
import sys
imp... |
#!/usr/bin/python
from datetime import datetime
startTime = datetime.now()
import sys
import getopt
import numpy as np
# default parameters
kmer = 15
coverage = 10
file_name = ""
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "hk:f:c:")
except getopt.GetoptError:
print 'knorm.py -k <kmer_size>[15]... |
#
# Sane, easy and straightforward logging for Python
#
# vim:set ts=8:
#
# This Works is placed under the terms of the Copyright Less License,
# see file COPYRIGHT.CLL. USE AT OWN RISK, ABSOLUTELY NO WARRANTY.
#
# Sorry, builtin logging in Python is far too complex.
# There must not be the need for to take care about... |
import time
import threading
from pixels import Pixels, pixels
from alexa_led_pattern import AlexaLedPattern
from google_home_led_pattern import GoogleHomeLedPattern
from flask import Flask
from flask_admin import Admin
app = Flask(__name__)
app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
admin = Admin(app, ... |
# Coffee Machine Class
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
latte = MenuItem('latte', 100, 16, 1, 3.50)
espresso = MenuItem('espresso', 100, 16, 1, 2.50)
cappuccino = MenuItem('cappuccino', 100, 16, 1, 3.25)
coffeeMaker = CoffeeMaker()
payment = ... |
x = 100
print(type(x))
y = 2.0
print(type(y))
z = int(y)
print(type(z))
a = int("123")
print(a) |
#!/usr/bin/env python
import argparse
import numpy
import os
import sys
from pickleExptLogs import readPickledFile
from expsiftUtils import *
from plotCompare import plotClusterBarComparisonDirs
from plotCompare import getRateMbpsFromPropValSet
from plotCompare import getNClassesFromPropValSet
from plotCompare import... |
# RachelPotterP2.py
# A program that takes a list of numbers and returns the sum of numbers in the list
def list_sum(num_list):
total_num = 0
for i in range(len(num_list)):
total_num = total_num + num_list[i]
return total_num
# Let's test it!
# We can create a function to get a list from the user... |
####
# prototyping anomaly detection using python numpy and scipy
####
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from scipy.optimize import curve_fit
import scipy
import datetime
import matplotlib.dates as mdates
#loading data from the arctan csv
data = np.genfromtxt('ArcT... |
""""
A list is a collection of more than one variable
They need not be of the same type
[]--declare a list
"""
x=["John Doe",20,"john@gmail.com","Nairobi", True]
print(x)
dishes=["Ugali","Samaki wa Kupakwa","Boilo","Nyama"]
colors=['Blue','white','grey']
combined=[dishes,colors,["Monday","Tuesday"]]
print(dishes)
pr... |
import requests
import random
import logging
import re
"""
Derpiboooru API accessing for parsing, function parameters are explicitly strings
Changed from urllib2 to requests (3rd party)
Changes are being applied to the derpibooru API
2015-05-31: Minor changes to return non-200 HTTP status codes as if to back off
2015-0... |
from tda import PD, PWGK, PL, PSSK
import tda
import numpy as np
import os
import random
def n_mmd(mat_gram, unbias=True):
n_total = mat_gram.shape[0]
n = int(n_total / 2)
mat_xx = mat_gram[0:n, 0:n]
mat_yy = mat_gram[n:n_total, n:n_total]
mat_xy = mat_gram[0:n, n:n_total]
sum_xx = sum(sum(ma... |
from __future__ import absolute_import
import warnings
from .cuhk01 import CUHK01
from .cuhk03 import CUHK03
from .dukemtmc import DukeMTMC
from .market1501 import Market1501
from .viper import VIPeR
from .veri776 import Veri776
from .vehicleid import VehicleID
__factory = {
'market1501': Market1501,
'cuhk03... |
import torch.nn as nn
from deep_depth_transfer.data.cameras_calibration import CamerasCalibration
from .inverse_depth_smoothness_loss import InverseDepthSmoothnessLoss
from .pose_loss import PoseLoss
from .pose_metric import PoseMetric
from .spatial_photometric_consistency_loss import SpatialPhotometricConsistencyLoss... |
#Write the python program to find the greatest number among the three numbers.
#Solution:
def greatest(num1,num2,num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num3 and num2 >= num1:
return num2
else:
return num3
num1 = int(input("Enter the first num... |
def multiples(s1, s2, s3):
return [a for a in xrange(1, s3) if not(a % s1 or a % s2)]
|
x = [1, 2, 3, 4]
if 5 in x:
print(True)
else:
print(False)
|
import webbrowser
def sad_run():
while True:
print('1. Understand why you are sad')
print('2. A list of great podcasts you might like')
print('3. Here is a list of best hollywood movies of all time to boost your mood')
print('4. Try reading these books might change your opinion ')
... |
import torch
from torch import nn
class LinearAggregator(nn.Module):
def __init__(self, num_labels, n_heads):
super(LinearAggregator, self).__init__()
self.aggregator = nn.Linear(num_labels * n_heads, num_labels)
def forward(self, x):
return self.aggregator(torch.cat(x, len(x[0].sha... |
import urllib.request
import re
# функция принимает три параметра (1 - url, 2 - путь и имя файла, который создастся при скачивании,
# 3 -флаг движка обработки (если True - обрабатываем с помощью lxml, если False - без библиотек))
def GetScriptTag(url, pathName, lib):
# открываем страницу и забираем всё сод... |
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import imutils
import argparse
# In[2]:
img = cv2.imread('./datasets/flower3.jpg')
cv2.imshow("Original_Image", img)
cv2.waitKey(0)
# In[3]:
#Splitting RGB components of an image
#Individual channel investigation hepls in understanding edge detection and t... |
#!/usr/bin/python
import sys, re
import argparse
from dependency_input import Dependency
from operator import itemgetter
import numpy as np
def smart_open(fname, mode = 'r'):
if fname.endswith('.gz'):
import gzip
# Using max compression (9) by default seems to be slow.
# Let's try using the... |
# -*- coding: utf-8 -*-
from django.forms import DateTimeInput
from django.utils.translation import gettext as _
class BootstrapDateTimePickerInput(DateTimeInput):
template_name = 'widgets/bootstrap_datetimepicker.html'
def get_context(self, name, value, attrs):
datetimepicker_id = 'datetimepicker_{n... |
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length=15, default="DefaultUserName")
status = models.IntegerField(default=0)
def __str__(self):
return str(self.name)
|
import os, sys, re
from bs4 import BeautifulSoup
for articleNumber in range(1,60):
filename = './temp/summary'+str(articleNumber)+'XML'
filenumber = 1
print filename+str(filenumber)+'.txt'
while os.path.exists(filename+str(filenumber)+'.txt'):
completeFile = open(filename+str(filenumber)+'.txt', 'r').read()
su... |
import math
import random
def check(n):
if n==1:
return "Nither prime nor composite"
for i in range(2, int(math.sqrt(n))+1):
if n%i==0:
return "Composite"
return "Prime"
x = random.randint(100, 1000)
print("The number " + str(x) + " is " + check(x)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.