text stringlengths 8 6.05M |
|---|
import os
import glob
import h5py
import keras
import numpy as np
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
from keras.models import load_model
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.imagenet_utils import preprocess_input
from keras.models ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
class Plotter(object):
def __init__(self, glw, hist_brush=(0,255,0,150), zoom_pen=(0,128,0,150), show_title=True):
super(Plotter, self).__init__()
self.glw = g... |
"""Docker Sproc
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import socket
import sys
import time
import click
import docker
import six
from treadmill import cli
from treadmill import... |
import logging
import sys
import inject
import datetime
sys.path.insert(0,'../../../python')
from model.config import Config
logging.getLogger().setLevel(logging.DEBUG)
from autobahn.asyncio.wamp import ApplicationSession
from asyncio import coroutine
'''
python3 persist.py dni name lastname city country address gen... |
# Generated by Django 3.2.4 on 2021-06-30 22:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='About',
fields=[
... |
import sys, sqlite3, os.path
from zipfile import ZipFile
if __name__ == '__main__':
args = sys.argv
def result(query):
with open('files-part1.txt', 'a') as output:
res = cur.execute(query)
for row in res:
output.write(str(row) + '\n')
#print (res.description)
direct... |
# import nbformat
import os
import os.path
from jupyter_core.paths import jupyter_path
from lxml import html
from nbconvert.exporters.html import HTMLExporter
from nbconvert.filters.markdown_mistune import markdown2html_mistune as markdown2html
from traitlets.config import Config
class NBSGHTMLExporter(HTMLExporter)... |
# -*- coding: utf-8 -*-
class Solution:
def partitionLabels(self, S):
last_occurrences = {c: i for i, c in enumerate(S)}
result = []
current_first, current_last = 0, 0
for i, c in enumerate(S):
current_last = max(current_last, last_occurrences[c])
if i == ... |
#!/bin/python3
import sys
if len(sys.argv) != 3:
print("Usage: ", sys.argv[0], "dump-file", "dest-dir")
exit(0)
f = open(sys.argv[1], "rb")
heap = f.read()
f.close()
keys = 0
key_path = sys.argv[2] + "/key_"
for off in range((len(heap)//16) - 1):
display = True
for i in range(31):
display &... |
__winc_id__ = 'ae539110d03e49ea8738fd413ac44ba8'
__human_name__ = 'files'
def main():
#----------------------------------------------------------------------
#Question 1
def clean_cache():
import os.path, os, shutil
current_directory = str(os.getcwd())
cache_folder_in_directory = current_directory + ... |
# -*-coding=utf-8-*-
__author__ = 'rocchen'
from lxml import html
from lxml import etree
import urllib2, requests
def lxml_test():
url = "http://www.caixunzz.com"
req = urllib2.Request(url=url)
resp = urllib2.urlopen(req)
#print(resp.read())
'''
parse_body=html.fromstring(resp.read())
href... |
# coding=utf-8
import os
import argparse
import numpy as np
from PIL import Image, ImageDraw, ImageOps
import cv2
import json
import pickle
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from torchvision.utils import save_image
class VtonDataset(data.Dataset):
"""
仮想試... |
from pydub import AudioSegment
import os
import librosa
import matplotlib.pyplot as plt
from scipy.io import wavfile
import numpy as np
def gen_spectrumgram(folder, filename):
spec_filename = filename[:len(filename) - 4] + ".png"
samplingFrequency, signalData = wavfile.read(folder + filename)
# Plot th... |
#!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# 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 la... |
from bs4 import BeautifulSoup
import requests
import re
class Scrape:
def __init__(self):
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.13 Safari/537.36",
"Referer": "http://tools.iedb.org/bcell/"
... |
def tail_swap(arr):
fmt = '{}:{}'.format
(head, tail), (head_2, tail_2) = (a.split(':') for a in arr)
return [fmt(head, tail_2), fmt(head_2, tail)]
|
# Generated by Django 2.1.4 on 2018-12-28 18:26
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... |
######### CLASS TREE #########
import Node
import json
class Tree:
def __init__(self, root):
self.root = root
def parse(self,node):
result = {}
if node.children:
for child in node.children:
if node.handled_data in result:
result[node.handled_data].append(self.parse(child))
else:
result[... |
#!env/bin/python
from dotenv import load_dotenv
from connection import Mercari, ROOT_PATH
import os
import json
from datetime import datetime
import argparse
from linebot import LineBotApi
from linebot.models import TextSendMessage
from linebot.exceptions import LineBotApiError
load_dotenv()
mercari_api = Mercari()... |
import requests
import json
import xlrd
import pymysql
def header():
header = {'Content-Type': 'application/json'}
def token_header():
header = {'Content-Type': 'application/json'}
con_url = 'http://172.18.1.143:8888/admin/login/verify'
con_body = {"captcha": "999999", # 验证码999999
"pho... |
import sys
import os
import re
import time
matchCpp = re.compile(r".*\.cpp")
matchExe = re.compile(r".*\.exe")
matchTxt = re.compile(r".*\.txt")
def toCompileCommand(file):
return "g++ -std=c++17 -O2 " + file + " -o " + file[:-3]+"exe"
def main():
command = ""
if len(sys.argv) == 2:
command = sys.... |
from msgs import fatal
# class to save user options
class userOptions(object):
def __init__(self):
self.opt = {}
def setGenType(self, fmt):
self.gentype = fmt
def getGenType(self):
return self.gentype
def addopt(self,k,v):
# print("adding {}:{}".format(k, v))
self.opt[k] = v
def getop... |
"""
В области информационных технологий, очередь это структура данных с принципом
доступа к элементам «первый пришёл — первый вышел» (FIFO, First In — First Out).
Добавление элемента (принято обозначать словом "enqueue" — поставить в очередь
или "push") возможно лишь в конец очереди, выборка — только из начала очере... |
# more like quteutils
import os
def send_to_qute(msg):
with open(os.environ["QUTE_FIFO"], "w") as f:
f.write("{}\n".format(msg))
def qute_print_cmd(msg, cmd):
send_to_qute("{} '{}'".format(cmd, msg.translate("".maketrans("", "", "\"'"))))
def qute_print(msg):
qute_print_cmd(msg, "message-info... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
class Animal(object):
def reply(self):
self.speak()
class Mammal(Animal):
def speak(self):
print('Mammal!')
class Cat(Mammal):
def speak(self):
print('meow')
class Dog(Mammal):
def speak(self):
print('wong')
class Pri... |
# Import necessary libraries
import serial
import time
# Create a variable that will create
# a communication between the Raspberry Pi
# and the Arduino
# Serial(arg1, arg2)
# The first argument, arg1 to the Serial variable
# is the port name.
# The second argument arg2 to the Serial variable
# is the baud rate.
# I... |
import time
from Pages.base_page import BasePage
from Utils.locators import *
class ModalsPage(BasePage):
def __init__(self, driver):
self.locator = ModalsLocators
super().__init__(driver)
def launch_single_modal(self):
button = self.driver.find_element(*self.locator.launch_modal_bu... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Flatten3d(nn.Module):
def forward(self, x):
N, C, D, H, W = x.size()
return x.view(N, -1)
class OctNet(nn.Module):
def __init__(self):
super(OctNet, self).__init__()
def forward(self, cubes):
ret... |
num_int = int(input("Enter a number "))
num_int += 2
num_int *= 3
num_int -= 6
num_int /= 3
print("Number is: ", num_int)
|
def can_permute_palindrome(s):
"""
:type s: str
:rtype: bool
"""
letters = {}
for letter in s:
if letters.has_key(letter):
letters[letter] += 1
else:
letters.setdefault(letter, 1)
odd_allowed = True
for key in letters:
if letters[key] & 1 == 1:
if len(s) & 1 == 0:
return False
elif odd... |
import numpy as np
from collections import defaultdict
def string_to_index_list(s, char_to_index, end_token):
"""Converts a sentence into a list of indexes (for each character).
"""
return [char_to_index[char] for char in s] # Adds the end token to each index list
def getIndexList(data,char_to_index):
... |
#Li Xin
#Student number: 014696390
#xin.li@helsinki.fi
import socket
import traceback
def listy(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, int(port)))
s.listen(5)
loop = True
except Exception:
print(traceback.print_exc())
loop = False
#create cmsg file or cle... |
from django.db import models
from datetime import datetime
# Create your models here.
class Post(models.Model):
user_id = models.IntegerField()
owner = models.CharField(max_length=20, default="???")
title = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
body = ... |
"""Models related to domain aliases management."""
from reversion import revisions as reversion
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core imp... |
# 문제 1
def solution(a, b, n):
answer = 0
while n >= a:
answer += n // a * b
n = n // a * b + n % a
return answer
# 문제 2
def solution(s):
answer = []
queue = []
for i in range(len(s)):
if s[i] not in queue:
answer.append(-1)
queue += s[i]
... |
import urllib
import time
import os
import numpy as np
import pandas as pd
import csv
import h5py
import pyodbc
from netCDF4 import Dataset
from ftplib import FTP
from datetime import time, timedelta, date
import datetime
import schedule
global geoid
geoid = 0
def declaring_variables():
# declaring all used date ... |
from flip_a_coin import *
def two_sided_p_value(x: float, mu: float = 0, sigma: float = 1) -> float:
if x >= mu:
return 2 * normal_probability_above(x, mu, sigma)
else:
return 2 * normal_probability_below(x, mu, sigma)
two_sided_p_value(529.5, mu_0, sigma_0) |
import matplotlib.pyplot as plt
import numpy as np
from . EquationException import EquationException
from . PrescribedParameter import PrescribedParameter
from . PrescribedInitialParameter import PrescribedInitialParameter
from . UnknownQuantity import UnknownQuantity
from .. TransportSettings import TransportSettings... |
"""
Create dense matrix from 10x MTX output
Michael Heskett
"""
import os
import csv
import scipy
import pandas as pd
import scipy.io
from sys import argv
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert 10x files to a dense table")
parser.add_ar... |
import numpy as np
#use GLoVe
#imput string arr size [N, sentence_length_not_same]
#imput numpy arr size [N, max_size, glove_embedded_size]
def embedder(sentence_batch,max_size,glove_embedded_size,glove_dict,UNK_vec,EOS_vec):
N = len(sentence_batch)
embedded_sentences = np.zeros((N,max_size,glove_embedded_size... |
from django.contrib import admin
from models import UserData, Profile, Post, Comment, Follow, Agree
# Register your models here.
admin.site.register(UserData)
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Agree)
admin.site.register(Follow)
admin.site.register(Profile) |
# Copyright (c) 2015 OpenStack Foundation. 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 ... |
from django.shortcuts import render
from rest_framework import routers, serializers, viewsets
from django.http import HttpResponse
from eleicao.models import *
from eleicao.serializers import *
# Create your views here.
class EleicaoViewSet(viewsets.ModelViewSet):
queryset = Eleicao.objects.all()
serializer_... |
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots['AttendanceTestCase::test_nonexisting_user_cannot_subscribe_to_event 1'] = {
'data': {
'attendEvent': None
},
'errors': [
... |
# -*- coding: utf-8 -*-
# @Time : 2019-12-24
# @Author : mizxc
# @Email : xiangxianjiao@163.com
from mongoengine import *
class Plan(EmbeddedDocument):
title = StringField(max_length=1000, required=True)
level = StringField(max_length=100, required=True)
isDone = BooleanField(default=False)
class Y... |
def traverse_list(self):
if self.start_node is None:
print("List has no element")
return
else:
n = self.start_node
while n is not None:
print(n.item, " ")
n = n.nref |
# Generated by Django 3.0.6 on 2020-06-07 16:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('musicRun', '0008_auto_20200607_1729'),
]
operations = [
migrations.AlterField(
model_name='song',
name='duration',
... |
import sys
from io import StringIO
class CaptureOutErr(object):
"""Context manager to capture the content of stdout and stderr.
Example:
>>> with CaptureOutErr() as cm:
>>> ...run_code()
>>> print(cm)
"""
def __enter__(self):
self.stdout = []
self.stderr = []
... |
from rest_framework import routers
from sneakers_colors_sizes_rel.api import SneakersColorsSizesRelViewSet, SneakersColorsSizesRelSearch
router = routers.DefaultRouter()
router.register('api/v0/sneak_col_siz_rel', SneakersColorsSizesRelViewSet, 'sneak_col_siz_rel')
urlpatterns = router.urls
|
import pymongo
import time
import datetime
from pymongo import MongoClient
from datetime import datetime
from bson.json_util import dumps
class UploadDB:
client = ""
db = ""
def __init__(self):
self.client = MongoClient()
self.db = self.client.AppInsight_DB
... |
# api.py
from flask import Flask, request, render_template
from preprocessing import preprocessing
from werkzeug.utils import secure_filename
from openpyxl import load_workbook
import pickle
import mysql.connector
import os
import json
import simplejson
db = mysql.connector.connect(
host="localhost",
user="root"... |
from gevent.pool import Pool
from gevent.queue import JoinableQueue as Queue
import logging as log
import time
class GeventPool(object):
"""
Caller should ensure that gevent monkey patch is run, if necessary.
"""
def __init__(self, size):
self._running = True
self._queue = Queue()
self._pool = Pool(size)
... |
import rips
import time
import grpc
import math
import os
from operator import itemgetter
from ecl.eclfile import EclFile
from ecl.grid import EclGrid
from ecl.summary import EclSum
import matplotlib.pyplot as plt
# Define the function to calculate energy changes in well bottomholes
def energywell():
# Connect to ... |
from pkg_resources import resource_filename
import tensorflow as tf
from keras.models import load_model
import numpy as np
import ctd_model
graph = tf.get_default_graph()
inference_model = None
labels = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
def dask_setup(service=None):
... |
from flask import Flask,flash,render_template,request,redirect,url_for
from flask_mail import Mail,Message
from decouple import config
from flask_mysqldb import MySQL
from itsdangerous import URLSafeTimedSerializer, SignatureExpired
import MySQLdb.cursors
import re
import os
from dotenv import load_dotenv
load... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
import os
import ujson
import uuid
import aiofiles
from sanic import Blueprint
from sanic import response
from sanic.log import logger
from sanic.request import Request
from sanic_jwt import inject_user, scoped, protected
from web_backend.nvlserv... |
import binascii
from enum import Enum
import time
import struct
import os, shutil
"""
FPFF file type enum
"""
class FileType(Enum):
ASCII = 1
UTF8 = 2
WORDS = 3
DWORDS = 4
DOUBLES = 5
COORD = 6
REF = 7
PNG = 8
GIF87 = 9
GIF89 = 10
"""
Contains FPFF functions
"""
class FPFF():
... |
# Determine if a quadratic equation has no, equal or distinct roots
import math
# Get coefficients of x^2, x and constant
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if (b*b - 4*a*c < 0):
print("No real roots")
elif (b*b - 4*a*c == 0): # equal roots
print(-b/(2*a))
else: # (b*b - 4*a*c > 0)... |
import os
import torch
import torch.utils.data as data
import torchvision
from torchvision import transforms
def get_dataset(dataset_name, if_download, batch_size, num_workers):
# getting data for training; just CIFAR10(?)
transform_train = transforms.Compose([
transforms.RandomHorizontalFlip(),
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
user_data_by_id_query = '''
SELECT usr.id AS user_id,
usr.email AS email,
usr.password AS pass... |
# -*- coding: utf-8 -*-
import urllib.parse
import scrapy
class PubMedSpider(scrapy.Spider):
name = 'pubmed'
def __init__(self, term='', *args, **kwargs):
super(PubMedSpider, self).__init__(*args, **kwargs)
self.term = term
def start_requests(self):
url = 'https://pubmed.ncbi.nl... |
from router_solver import *
import game_engine.constants
from game_engine.constants import *
from game_engine.spritesheet import *
class Character(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, speed):
super().__init__()
self.x = x
self.y = y
self.width = width
... |
#list
squares = [1, 4, 9, 16, 25]
print (squares)
print (squares[0])
print (squares[-1])
print (squares[-3:])
print ('______________________________________')
print (squares + [36,49,64,81, 100])
print ('______________________________________')
cubes = [1,8,27,65,125]
print (cubes)
cubes [3] = 64
print (cubes)
cub... |
#!/usr/bin/python
import os
import pygame
from glm import ivec2, vec2
from game.base.inputs import Inputs
from game.base.signal import Signal
from game.constants import SPRITES_DIR, DEBUG
from game.base.stats import Stats
from game.states.game import Game
from game.states.intro import Intro
from game.states.menu imp... |
#Chris Hasty 17.2 Exercise ( Books Database )
import sqlite3
import pandas as pd
connection = sqlite3.connect('books.db')
pd.options.display.max_columns =10
pd.read_sql('SELECT * FROM authors', connection, index_col=['id'])
pd.read_sql('SELECT * From titles', connection)
df = pd.read_sql('SELECT * FROM author_... |
# coding=utf-8
from myspider.items import NewsItem
from scrapy.http import Request
import scrapy
import re
class jandan_article(scrapy.Spider):
name = 'jandan_article'
allowed_domains = ['jandan.net']
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8... |
import requests
r = requests.get("https://lpu.in")
|
Import('*')
try:
env_gskiplist # env value to override for settings
except:
env_gskiplist = Environment()
env_gskiplist.Append(LIBS='glib2-0')
env_gskiplist.Append(CFLAGS=['-pthread','--std=c99'])
static_gskiplist = env_gskiplist.StaticLibrary("libgsimplecache", [Glob("*.c")])
OS_gskiplist = env_gskiplist.Sha... |
# Copyright 2021 Pulser Development Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import urllib.request, math, os
def results(query, kwparse, fromYear, fromMonth, toYear, toMonth, numberofentries):
query = str(numberofentries) + "_" + query
if not os.path.exists(query):
os.makedirs(query) # making a seprate directory for storing webpages
else:
print("Folder with similar ... |
import csv
import numpy as np
import Config
def load_data(filename):
lines = open(filename, 'r').readlines()
lines = lines[1:] #removing the header
tokens = []
data = []
labels = []
for line in lines:
data.append(line.split("\t")[1])
tempLabel = line.split("\t")[2]
if fl... |
# Generated by Django 2.2.2 on 2019-06-20 11:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('info', '0003_auto_20190620_0822'),
]
operations = [
migrations.AlterField(
model_name='news',
name='published_at',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#The MIT License (MIT)
#
#Copyright (c) <2013> <Colin Duquesnoy and others, see AUTHORS.txt>
#
#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 wit... |
from django.shortcuts import render, redirect ,HttpResponse
import random
def index(request):
if "numbers" not in request.session:
request.session ["numbers"]=random.randint(1, 100)
print( request.session ["numbers"])
return render(request,"index.html")
def guess(request):
if reque... |
import tensorflow as tf
import numpy as np
import os
import sys
from PIL import Image, ImageOps
from utils import get_shape, batch_norm, lkrelu
class Discriminator(object):
def __init__(self, inputs, is_training, stddev=0.02, center=True, scale=True, reuse=None):
self._is_training = is_training
sel... |
import unittest
from katas.kyu_6.evil_autocorrect_prank import autocorrect
class AutocorrectPrankTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(autocorrect('u'), 'your sister')
def test_equals_2(self):
self.assertEqual(autocorrect('you'), 'your sister')
def test_eq... |
import numpy as np
import scipy as sp
import matplotlib.pyplot as py
import random as rd
import math as m
global ylim
global xlim
global nb_cust
global kNN
global clim
global Capacity
ylim = 200
xlim = 200
clim = 20
nb_cust = 10
kNN = 5
Capacity = 75
# Creation of a test instance
inst_test2 = [(0, 0), (11, 120), (-1... |
import rsa
keys_list = {}
publicKey, privateKey = rsa.newkeys(512)
keys_list[publicKey] = privateKey
message = "ankit"
enc = rsa.encrypt(message.encode(), publicKey)
print("origibal String: ", message)
print("encrypted String: ", enc)
decMessage = rsa.decrypt(enc, privateKey).decode()
print("decrypted message: "... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = pd.read_csv("all_data_100000_patches.csv")
#data at 100,000 updates in non-ecology mode
dataNoEco = data[data.loc[:,"ecology"]== "N" ]
#data at 100,000 updates in ecology mode
dataEco = data[data.loc[:, "ecology"]== "Y" ]
#Patches x S... |
import sys, os
print("~/read_column.py [txtfile] [delimiter]")
with open(sys.argv[1]) as f:
fline = f.readline().split(sys.argv[2])
linenum=0
for line in fline:
linenum+=1
if '"' in line:print(linenum, ":", line.replace('"',''))
else:print(linenum, ":", line)
|
import threading
from socket import *
import sys
import os
import pyaudio
import wave
import glob
import tensorflow as tf
import numpy as np
from datetime import datetime
from header import *
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
if len(sys.argv) < 2:
print("compile error: please input total node number")
e... |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/4/8 19:07
# @Author :'liuyu'
# @Version:V 0.1
# @File :
# @desc :
import tensorflow as tf
import json
import os,re
import logging
logging.basicConfig(level= logging.INFO)
def calc_num_batches(total_num,batch_size):
return total_num // batch_size + in... |
import math
def f(x):
return pow(2,x+2)-4 |
from django_tables2 import tables, Column
from .models import ChangeLog
class ChangeLogListTable(tables.Table):
""" Describes ChangeLog list table (django-tables2 package) """
changed = Column(orderable=True,)
model = Column(orderable=False)
record_id = Column(orderable=False)
user = Column(orde... |
"""
PRACTICE Test 3, problem 6.
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and Muqing Zheng. October 2015.
""" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE.
import time
def main():
""" Calls the TEST functions in this module. """
# test_good_input()
... |
import plotly.express as px
import pandas as pd
line1 = pd.read_csv("line_chart.csv")
# print(line1.tail())
graph = px.line(line1,x="Year", y = "Per capita income", color="Country", title="Yearly Per Capita Income(Country)")
print("Bouncing you there...")
graph.show() |
import os
import numpy as np
from math import floor
from datetime import datetime
from datetime import timedelta
import asyncio
from time import sleep
from shared.LogParser import LogParser
from shared.RedisManager import RedisManager
from shared.BaseConfig import BaseConfig
from shared.ServiceManager import ServiceM... |
import random
from faker import Faker
class FakeData:
"""Class for generating an fake data"""
def __init__(self):
self.faker = Faker()
# default data type values
_default_types = (
'string', 'integer', 'boolean',
'float', 'array_int', 'array_str',
'datetime'
)
... |
import turtle
turtle.speed(100)
turtle.pensize(10)
angle = 20
for i in range(18):
turtle.left(angle)
for i in range(4):
turtle.forward(120)
turtle.left(90)
turtle.mainloop()
|
import json
import random
import time
import numpy as np
import yaml
def fread(path):
"""
将文件读出来
:param path: file path
:return: list
"""
with open(path, "r") as f:
s = f.read()
v = [float(i) for i in s.split()]
return v
# 将数据写入文件
def fwrite(path, v):
"""
写入数... |
import socket
import cv2
import sys
cascPath = 'C:\\Users\\BIPUL\\Documents\\socket programming\\haarcascade_frontalface_alt.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = c... |
# coding=utf-8
from lxml import etree
import requests
import random
class SpiderTB_Xpath():
ua_list = [
"Mozilla/5.0 (Windows NT 6.1; ) Apple.... ",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0)... ",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X.... ",
"Mozilla/5.0 (Macintosh; Intel Mac OS... |
import pika
import time
import pandas as pd
import json
credentials = pika.PlainCredentials('thinhle', 'meomeo')
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='171.244.51.228', port=5672, virtual_host='/',
credentials=credentials))
channel = connection.chann... |
#!/usr/bin/env python
import time
from time import sleep
f = open("/usr/local/tcollector/collectors/0/05_B_100_vibX", "r")
print 'input TSDB Start'
while True:
line = f.readline()
if not line: break
print str(line)
time.sleep(0.001)
print 'input Done'
f.close()
|
from django.db import models
# Create your models here.
class ShopModel(models.Model):
name = models.CharField(max_length=10)
address = models.CharField(max_length=20)
# item_name=models.CharField(max_length=20)
class Meta:
db_table = 'shop'
class ItemModel(models.Model):
name = models.... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('src_imgs/pic2.jpg',0)
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0... |
#!/usr/bin/env python
"""
@author: Jean-Lou Dupont
"""
import httplib
def doHead(site, url):
conn=httplib.HTTPConnection(site)
conn.request("HEAD", url)
resp=conn.getresponse()
return resp
def doGet(site, url):
"""
Performs an HTTP GET request
"""
conn=httplib.HTTPConnection(site)... |
from typing import List, Dict
class Database:
COLUMNS_HUMAN = [
'human_id', 'gender', 'age', 'preliminary_diagnosis',
'admission_to_the_hospital', 'arrival_date', 'approximate_growth', 'hair_type',
'room_number', 'full_name'
]
COLUMNS_ROOM = ['room_number', 'room_id', 'room_type', ... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def find_height(root: TreeNode):
if root is None:
return 0
return max(find_height(root.left), find_height(root.right)) + 1
root_node = TreeNode(10)
root_node.left = TreeNode(5)
... |
"""
Liquid time constant snn
"""
import os
import shutil
import torch
from torch import nn
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn import init
from torch.autograd import Variable
import math
def create_exp_dir(path, scripts_to_save=None):
if not os.path.exists(path):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.