text stringlengths 38 1.54M |
|---|
import logging
from twisted.python import log
class LevelFileLogObserver( log.FileLogObserver ):
def __init__( self, file, level = logging.INFO ):
log.FileLogObserver.__init__( self, file )
self.log_level = level
def emit( self, event_dict ):
if event_dict['isError']:
le... |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import datetime,pytz,types,calendar,time,locale,sys,json
import xml.etree.cElementTree as ET
from argparse import ArgumentParser
def conv_xml(r,ra,num,fecha,entrada):
elemento=ET.SubElement(r, u"instant")
elemento.attrib={u"date":str(fecha), u"ordinal":str(num)}
def... |
units_digit = ['','one','two','three','four','five','six','seven','eight','nine']
tens_digit = ['','ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']
def reading(number):
unit= (int((str(number))[1]))
tens = (int((str(number))[0]))
return tens_digit[tens] , units_digit[u... |
from pymd5 import md5, padding
import httplib, urlparse, sys
import urllib
url = sys.argv[1]
parsedUrl = urlparse.urlparse(url)
params = {}
for x in parsedUrl.query.split('&'):
y = x.split('=')
params.update({ y[0] : y[1] })
originalMessageHash = params['token']
m = parsedUrl.query.replace('token=' + params[... |
#!/usr/bin/env python
#
# Copyright (C) 2019 FIBO/KMUTT
# Written by Nasrun (NeverHoliday) Hayeeyama
#
VERSIONNUMBER = 'v1.0'
PROGRAM_DESCRIPTION = "Test detect multiscale"
########################################################
#
# STANDARD IMPORTS
#
import sys
import os
import optparse
######################... |
from filter import ImageHolder
import multiprocessing
import os
IMAGE_DIR = "images"
if __name__ == "__main__":
print("Virtual cores:", multiprocessing.cpu_count())
ImH = ImageHolder()
processes = []
for i, filename in enumerate(os.listdir(IMAGE_DIR)):
processes += [multiprocessing.Process(ta... |
# "venkatesh"
# "vhesnekta"
s="venkat"
s1=""
l=len(s)-1
if len(s1)<len(s):
for i in range(len(s)):
s1=s1+s[i]
for j in range(l,l-1,-1):
p=l-j
s1=s1+s[p]
l=l-1
print(s1)
|
from .file_utilities import *
from .math_utilities import *
from .plot_utilities import *
from .data_utilities import *
|
# Generated by Django 2.0.5 on 2018-07-07 18:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('server_alpha_app', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='usermodel',
name='name',
... |
# find the last element of a list
# use python's built in list indexing with a special case for an empty list
# note: I believe cpython keeps track of a list's length for quick lookup so
# len() does not require a traversal, only field lookup, but I should
# find where that's spelled out or write a test to... |
######################
### Custom Imports ###
######################
from . import commands
from . import settings
######################
def start(): # The Start up of game
print("""
*--------------------------------*
Welcome to Space Exploration Game
coded in Py3.7
By: DrProfMaui
*-------... |
"""Tile."""
class Tile:
"""Tile."""
def __init__(self, sprite, solid=False, high=False, mask=None, slow=False):
"""Constructor."""
self.sprite = sprite
self.mask = mask
self.solid = solid
self.high = high
self.slow = slow
self.type = type
self... |
'''
Write a python program that it should consist of special char, numbers and chars .
if there are even numbers of special chars
Then 1) the series should start with even followed by odd
Input: t9@a42&516
Output: 492561
If there are odd numbers of special chars then the output will be starting with odd followed by ... |
from django.test import TestCase
from api.models import (
Company,
DeviceModel,
Device,
)
from rest_framework.test import APIClient
from rest_framework import status
from django.urls import reverse
class CompanyViewTestCase(TestCase):
"""Test suite for ... |
#!/usr/bin/env python3
from __future__ import print_function
import errno
import sys
import logging
from pyocd.core.helpers import ConnectHelper
from pyocd.flash.file_programmer import FileProgrammer
from pyocd.flash.eraser import FlashEraser
from binho.utils import log_silent, log_verbose
from binho.errors import D... |
import sys
#sys.path.append(
# '/home/jbs/develop.old/articles/201509_python_exercises_generator')
#sys.path.append('/home/jbs/develop/201902_questions_transformer')
sys.path.append('../qom_questions_transformer')
import string
from random import sample
from random import choice
from random import randint
from r... |
import os, struct, sys
def make_file_index(fname, idx_fname) :
# open the original file normally, and the index file as a
# binary file
with open(fname,'r') as f_in, open(idx_fname,'wb') as f_out :
# doing a normal iteration over the file lines
# as in 'for line in f_in' will not work... |
from argparse import ArgumentParser
from pymad import loadTrack, synthesize
from pymad.piano import loadDrum
if __name__ == "__main__":
parser = ArgumentParser("drum", description="synthesis drum track")
parser.add_argument("track", help="track path")
parser.add_argument("output", help="output wav path")
... |
#methods of list
a=['hello','I','am','ritu','soni','I','am','happy']
#append
a.append(3)
print(a)
a.append(34)
a.append(4.45)
a.append(len(a))
a.append(True)
print(a)
x=a.append(56) #extend and append do not return anything x is none
print(x)
#extend(iterable)
b=[1,2]
x=a.extend(b)
print(x)
a.extend(b)
print(a)
#... |
from PowCapTools import ParseData
from PowCapTools import FindFile
def main():
fileName = '/home/henry/NeslStore/vikram/powcapData/Jason-Drive/mains_130313_030126-chan_1.dat'
start_at_second = 1
end_at_second = 20
window_second = 200e-3
sampRate = 1e6
analysis = "plot"
... |
from django.db import models
from django.contrib.auth.models import User
from shop.models import Product,Category
class Profile(models.Model):
user = models.OneToOneField(User , on_delete=models.CASCADE)
auth_token = models.CharField(max_length=100 )
phone=models.IntegerField(default=+917447650728)
is... |
# Original Code here:
# https://github.com/pytorch/examples/blob/master/mnist/main.py
import os
import argparse
from filelock import FileLock
import tempfile
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import ray
from ray i... |
if __name__== "__main__":
filepointer = open('stateMachine_1.txt', 'r')
for line in filepointer:
print(line)
print("next")
filepointer.close()
|
'''
thin wrapper around sklearn classifiers, provide easy access and some additional model evaluation metrics
'''
import logging
import numpy as np
import scipy.stats
import scipy.sparse
from sklearn.linear_model import LogisticRegressionCV
class ModelTrainer(object):
def __init__(self):
sel... |
#https://www.hackerrank.com/challenges/game-of-thrones/problem
#!/bin/python3
import math
import os
import random
import re
import sys
def gameOfThrones(s):
s = ''.join(sorted(s))
palindrome = True if len(s) % 2 == 0 else False
i = 0
for j in range(0, len(s)):
if(s[i] != s[j]):
i... |
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from typing import Tuple
from pants.engine.fs import PathGlobs, Snapshot
from pants.source.filespec import matches_filespec
from pants.testutil.test_base import TestBase
class FilespecT... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
class TwitterBot:
def __init__(self,username,password):
self.username=username
self.password=password
self.bot= webdriver.Firefox()
def login(self):
bot=self.bot
bot.get("https://... |
l = []
matrix = []
g = int(input("enter puzzleno:"))
print("enter puzzle")
for i in range(0,5):
l = list(raw_input())
matrix.append(l)
x = []
p = []
m = ' '
print("enter operations")
for y in range(0,1):
p = list(raw_input())
for j in range(0,5):
for t in range(0,5):
if matrix[j][t] == m:
... |
fac = [1]
n = 1
for x in range(1, 101):
n *= x
fac.append(n)
for _ in range(int(raw_input())):
print fac[int(raw_input())]
|
'''
Created on 2020. 2. 10.
@author: gd7
learnex1.py : 머신러닝 예제. 사이킷런 툴 사용하기
'''
from sklearn import svm #pip install sklearn
xor_data = [[0,0,0],[0,1,1],[1,0,1],[1,1,0]]
data = [] #샘플데이터
label = [] #결과값
#샘플데이터 생성
for row in xor_data :
p = row[0]
q = row[1]
r = row[2]
data.append([p,q])
label.append... |
from django.shortcuts import render, redirect, get_object_or_404,HttpResponse
from .form import DreamrealForm
from .models import book
def index(request):
return render(request, 'index.html')
def save_book1(request):
b_name = request.GET['name']
b_price = request.GET['price']
n_pages = request.GET['... |
import os
import os.path
import random
import string
import cherrypy
import base64
from pyparsing import unicode
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
LETTERS = string.ascii_uppercase
seed_number = ""
class StringGenerator(object):
@cherrypy.expos... |
import dask.bag as db
import networkx as nx
import pandas as pd
import time
import json
import community
import collections
import matplotlib.pyplot as plt
from dask.distributed import Client, LocalCluster
from karateclub import EgoNetSplitter
def not_none(edge):
return edge is not None
def pars... |
from django.shortcuts import render
from .models import MyForm, MyImage
from django.views.generic import FormView
from PIL import Image
class MyImages(FormView):
form_class = MyForm
template_name = 'ex00/my_images.html'
initial = {'key': 'value'}
success_url = 'my_images'
def get(self, request):
... |
import random
def busqueda_binaria(valor):
inicio = 0
final = len(lista)-1
while inicio <= final:
puntero = (inicio+final)//2
if valor == lista[puntero]:
return puntero #ver que pasa si lo cambio por valor
elif valor > lista[puntero]:
in... |
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
from PyQt5.QtSvg import QSvgGenerator
from PyQt5.QtWidgets import QMainWindow, QAction, QFileDialog, QSizePolicy, QSplitter, QTableWidget, QTableWidgetItem
from PyQt5.QtGui import QPen, QColor, QBrush
from PyQt5.QtCore import QSize
from PyQt5.QtChart import QCha... |
from get_fish_info import get_fish_info
import pandas as pd
from pathlib import Path
import pylab as pl
import pickle
import numpy as np
root_path = Path("/n/home10/abahl/engert_storage_armin/ariel_paper/free_swimming_behavior_data/dot_motion_coherence")
for experiment in ["chrna2a",
"disc1_hetinx"... |
# Generated by Django 2.2.10 on 2020-08-03 07:17
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('school', '0035_auto_20200803_1232'),
]
operations = [
migrations.AlterField(model_nam... |
# Generated by Django 3.0.5 on 2020-05-09 10:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('med_result', '0005_auto_20200509_1038'),
('visit', '0009_auto_20200509_1242'),
]
operations = [
migrations.RemoveField(
... |
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from two_factor.urls import urlpatterns as tf_urls
from django.conf.urls import url
from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_urls
#Custom admin p... |
from django.shortcuts import render , redirect
from .models import Profile
from .forms import ProfileForm
from django.http import Http404
from django.contrib.auth import get_user_model
# Create your views here.
User = get_user_model()
def update_profile_view(request, *args, **kwargs):
if not request.user.is_aut... |
import typer
import pyodk
import logging
from pyodk.rest import ApiException
import configparser
import sys
import click
import time
import progressbar
import subprocess
from oktawave_cli.lib.oci import OciHelper
from oktawave_cli.lib.subregion import SubregionHelper
from oktawave_cli.lib.tickets import TicketHelper
fr... |
import json
import os
import yaml
def load_data(file_name):
#获取上一级目录
# print(os.path.abspath(os.path.join(os.getcwd(), "..")))
file_path = os.getcwd() + os.sep + "configure" + os.sep + file_name + ".yml"
file = open(file_path, 'r', encoding='utf-8')
data = yaml.load(file)
return data
if __... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
okay 56ms 80%
:type root: TreeNode
:rtype: List[Li... |
import requests
import feedparser
from bs4 import BeautifulSoup
from alfheimproject.settings import CONFIG
def get_medium_posts():
page = requests.get("https://medium.com/feed/@{user}".format(user=CONFIG['api']['medium']['username']))
rss = feedparser.parse(page.content)
posts = []
for i, post in en... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class QiushibaikePipeline (object):
fp =... |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
k, n = list(map(int, input().split()))
a = list(map(int, input().split()))
diff = [0] * n
for i in range(len(a) - 1):
diff[i] = abs(a[i] - a[i+1])
diff[-1] = abs(a[-1] - k) + a[0]
print(k - max(diff))
|
def ais(a):
g = []
for i, j in zip(a, a[1:]):
if i > j:
g.append('>')
elif i < j:
g.append('<')
elif i == j:
g.append('=')
print(g)
print(len(a))
print(len(g))
s = [40, 50, 60, 10, 20, 30]
ais(s)
|
import skimage
from lr_utils import load_dataset
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
"""
w.shape = (dim, 1)
X.shape = (px * px * 3, num_of_pic)
Y.shape = (1, ...)
"""
# sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 初始化
def initialize_with_zeros(dim):
w = n... |
import sys
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifie... |
#!/usr/bin/env python
"""Project Euler - project 1 - Hadoop version (reducer)
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."""
import sys
def read_mapper_output(file):
for ... |
# Generated by Django 2.2.5 on 2019-12-10 14:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0004_auto_20191013_2242'),
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
... |
# Testing classes
class AnonymousSurvey():
'''Collects anonymous answers to a survery question'''
def __init__(self, question):
self.question = question
self.responses = []
def show_questions(self):
'''Show survey questions'''
print (self.question)
... |
from django.conf import settings
def IS_PRODUCTION(request):
return {'IS_PRODUCTION': settings.IS_PRODUCTION} |
from django.db import models
from django.contrib.auth.models import User
class StudySkillsResult(models.Model):
"""
Stores students reponses to study skills assessment.
"""
student = models.ForeignKey(User)
answers = models.TextField()
date_taken = models.DateTimeField(auto_now_add=True)
|
from django.shortcuts import render, redirect
from .models import Song, Songs_list, Artist, Album, Reviews, Album_Reviews, Artist_Reviews, Song_Reviews
from django.db import IntegrityError
from django.contrib import messages
from enum import Enum
from datetime import date
from django.core.mail import send_mail
from dja... |
#!/usr/bin/env python
# coding: utf-8
class lazyproperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
... |
from math import *
n = int(raw_input())
pos = list(map(float, raw_input().split()))
sp = list(map(float, raw_input().split()))
mx = max(pos)
mn = min(pos)
def f(p):
ans = 0.0
for x in xrange(n):
ans = max(ans, abs(pos[x] - p)/sp[x])
return ans
def bin():
hi = mx
lo = mn
best = 10000000000.0
for x in xrange... |
# to find files in the html string
import re
import requests
url = 'https://www.sina.com.cn'
url = 'https://www.hlgnet.com'
text = requests.get(url).text
# print(text)
re_str = r'src = "(.*?\.jpg)"'
re_str = r'https:.+\.jpg'
re_str = r'[jpg|gif]'
file_name_list = re.findall(re_str, text)
print(file_name_list)
|
class Spam:
num_instances = 0
def __init__(self):
Spam.num_instances = Spam.num_instances + 1
def print_num_instances(self):
print('Number of instances created: %s' % Spam.num_instances)
a = Spam()
b = Spam()
c = Spam()
Spam.print_num_instances(a)
|
Total = int(input('Please enter the amount of cents:'))
print(Total // 200 , "toonies")
Toonies = Total % 200
print(Toonies // 100 , "loonies")
Loonies = Toonies % 100
print(Loonies // 25 , "quarters")
Quarters = Loonies % 25
print(Quarters // 10 , "dimes")
Dimes = Quarters % 10
print(Dimes // 5 , "nickles")
Nickles =... |
from datetime import datetime
import json
class MyLogging:
t = datetime.now()
def __init__(self, path):
self.f = open(str(path) + '/' + self.t.strftime('%d_%m_%y_%H_%M_%S')+'.txt', 'w+')
self.boof = ''
self.path = str(path)
def write_data(self, data):
if self.f.closed:
... |
import os
from Strava.StravaData import StravaData
# Audrey - 18301580
# Ethan - 22985222
# Amy - 23312763
athletes = [23312763, 18301580, 22985222]
for athlete in athletes:
strava = StravaData(athlete_id=athlete)
print("###################################################")
print(f"Athlete {athlete}")
... |
def Substring(str1, str2, n, m):
dp = [[0 for k in range(m+1)] for l in range(n+1)]
maxN = 0
for i in range(1, n+1):
for j in range(1, m+1):
if str1[i-1] == str2[j-1]:
dp[i][j] = 1+dp[i-1][j-1]
if maxN < dp[i][j]:
maxN... |
import unittest
import sys
import os
from pymongo import MongoClient
from bson.objectid import ObjectId
from linguine.transaction import Transaction
class TransactionTest(unittest.TestCase):
def setUp(self):
self.trans = Transaction('test')
self.test_data = {}
def test_parse_json(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 16:29:06 2019
@author: aalipour
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 20:00:30 2019
@author: aalipour
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 21:42:02 2019
@author: aalipour
"""
import torch
import torch.nn as nn... |
class Job:
def __init__(self,available,cost,work):
self.available=available
self.cost=cost
self.work=work
def minimum(job,D):
job_a = sorted(job,key=lambda l:l.available)
for i in range(len(job)):
print(job_a[i].available,job_a[i].cost,job_a[i].work)
job_c = sort... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tues Jul 21
@author: Sebastian Gonzalez
"""
####################################
### Neccessary Import Statements ###
####################################
# Data Manipulation
import numpy as np
# Model Classes
from sklearn.ensemble import RandomForestClas... |
import dask.bag as db
from dask.bag import random
def test_choices_size():
"""
Number of randomly sampled elements are exactly k.
"""
seq = range(20)
sut = db.from_sequence(seq, npartitions=3)
li = list(random.choices(sut, k=2).compute())
assert len(li) == 2
assert all(i in seq for i i... |
# -*- coding: utf-8 -*-
"""Electrical billing for small consumers in Spain using PVPC. Base dataclass."""
import json
from datetime import datetime
from enum import Enum
import attr
import cattr
# Serialization hooks for datetimes and Enums
cattr.register_unstructure_hook(Enum, lambda e: e.value)
cattr.register_struc... |
"""Get the distribution of correlation z scores for pairs a-x or x-b where x
is an intermediate between gene pair a-b.
"""
import sys
import ast
import pickle
import random
import logging
from os import path
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
import matplotlib.pyplot ... |
from math import sqrt
num = int(input('digite um numero: '))
if num > 0:
print(f'A raiz quadrada do numero digitado é {(sqrt(num))}, é seu quadrado é {(num ** 2)}')
|
# Written at the 2013 DC Lady Hackathon for Karen
import email, getpass, imaplib, os
import smtplib
from email.mime.text import MIMEText
user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(... |
#import the minecraft modules
import mcpi.minecraft as minecraft
import mcpi.block as block
#import random so you can create lights in random locations
import random
#import time so we can put delays into our program
import time
#create the connection
mc = minecraft.Minecraft.create()
mc.postToChat("Minecraft Whac-a-... |
#!/usr/bin/env python
import sys
import factor
from math import sqrt
def is_perfsq(n):
if n < 0:
return False
rn = sqrt(n)
if rn == int(rn):
return True
return False
def check(a, b, c):
if not is_perfsq(c - b) or \
not is_perfsq(c + b) or \
... |
from django.shortcuts import render
from django.views import View
from .models import HashTag
class HashTagView(View):
def get(self, request, hashtag, *args, **kwargs):
hashtag = HashTag.objects.get(tag=hashtag)
posts = hashtag.get_posts()
return render(request, "hashtags/tag_page.html", {... |
from flask import flash
from mongoengine.errors import DoesNotExist, NotUniqueError
from weltcharity import bcrypt
from ..models import User, ContactInfo, Address
class UserFactory():
"""UserFactory handles multiple methods of creating a user or
logging a user in.
"""
@staticmethod
def get_user_i... |
# looping through a sequence of numbers using range() method
# range(5) will generate [0,1,2,3,4]
for i in range(8):
print(i)
|
from django.urls import path, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.BranoListView.as_view(), name='sanremo-brani'),
path('brani/<int:pk>', views.BranoDetailView.as_view(), name='sanremo-brano'),
]
if settings.DEBU... |
import pandas as pd
from docx import Document
import datetime
import os
import math
# remember to relabel the CITY/STATE columns in the excel sheet - they are backwards
# ADDRESS LINE 2 has a SPACE in front of it
currYear = datetime.date.today().strftime("%Y")
currMonth = datetime.date.today().strftime("%m")
def is_... |
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision import datasets
from torchvision.models import vgg16
import Pt_nn
from skimage.transform import resize
# Define the neural network that is used to classify images from the CIFAR10
# dataset.
class VGG16_CNN(nn.Module):
... |
import heapq
class PriorityQueue:
def __init__(self, data=None, key=lambda x:x):
self.empty = True
self.key = key
if data:
self._data = [(key(item), item) for item in data]
heapq.heapify(self._data)
self.empty = False
else:
self._data ... |
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .models import BusinessUnit, Location, Role, User, Manager, Calendar, Event, CalendarSharing, Invitation
#BusinessUnit retrieve API view
class BusinessUnitRetrieveAPIView(generi... |
import torch
from torch import nn,optim
from torch.nn import functional
from torchvision import datasets,transforms
class trainer:
def __init__(self):
self.train_loader,self.test_loader = dataloaders(batch_size=32)
self.model = basicConv()
self.loss_func = nn.CrossEntropyLoss()
... |
import csv
import requests
from lxml import html
page = requests.get('http://www.mah.gov.on.ca/page1591.aspx')
tree = html.fromstring(page.content)
muni_names = tree.xpath(
'//*[@id="content"]/div/table/tbody[2]/tr/td[1]/p/a[contains(@href, "h")]/text()'
)
muni_urls = tree.xpath(
'//*[@id="content"]/div/table/... |
import logging
from glob import glob
from jinjafy import Jinjafier
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
template = "project.md"
default_meta = glob("data/meta/*.ymd") + glob("./data/meta/*.yaml")
meta = "data/projects/merck.uldir.ymd"
j = Jinjafier(template, default... |
import io
import avroc.codegen.read
import avroc.codegen.write
import fastavro.write
import fastavro.read
import fastavro._read
import pytest
import decimal
import datetime
import uuid
class testcase:
def __init__(self, label, schema, message=None, message_list=None):
self.label = label
self.schem... |
import sys
from time import sleep
import pygame
from random import randint
from bullet import Bullet
from Rectangle import Rectangle
def fire_bullet(ai_settings, screen, ship, bullets):
"""如果还没有达到限制,就发射一颗子弹"""
# 创建新子弹,并将其加入到编组bullets中
if len(bullets) < ai_settings.bullets_allowed:
new_bullet = Bul... |
# 파이썬은 느리기 때문에 순차적으로 풀면 시간초과
# 부분합(DP)을 이용해야 한다고 함
import sys
n, m = map(int, sys.stdin.readline().split())
array = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
dp = [[0]*m for _ in range(n)]
for i in range(n):
for j in range(m):
dp[n][m] = dp[0][0]+
k = int(sys.stdin.re... |
#!/usr/bin/env python
"""Day 16 of advent of code"""
def swap(array, index_a, index_b):
"""Swaps two elements"""
tmp = array[index_a]
array[index_a] = array[index_b]
array[index_b] = tmp
def dance(array, commands):
"""Do the dance"""
for command in commands:
if command[0] == 's':
... |
import numpy as np
from scipy.ndimage.filters import sobel, gaussian_filter
from skimage import filter, transform, feature
from skimage import img_as_float
from coins._hough import hough_circles
def compute_center_pdf(image, radius,
low_threshold, high_threshold,
gradi... |
import e3cnn.nn as enn
from e3cnn import gspaces
import torch.nn as nn
import numpy as np
from .base import BaseEquiv, GatedFieldType
from .ft_nonlinearity import FTNonLinearity
class SteerableCNN(BaseEquiv):
def __init__(self, in_channels=1, out_channels=1, type='spherical', max_freq=2, kernel_size=3, padding=0,... |
# -*- coding: utf-8 -*-
'''
Installation of Ruby modules packaged as gems
=============================================
A state module to manage rubygems. Gems can be set up to be installed
or removed. This module will use RVM if it is installed. In that case,
you can specify what ruby version and gemset to target.
.... |
from dataloader import *
import tensorflow as tf
import numpy as np
import argparse
import math
VAL_RATIO = 0.2
TEST_RATIO = 0.2
LOAD_FACTOR = 0.5
def train(args):
data_set = load_synthetic_data(args.data_dir, args.norm_label)
data_sets = create_train_validate_test_data_sets(data_set, VAL_RATIO, TEST_RATIO, s... |
#importation
import Bigeleisen_KIE as kie
import pandas as pd
#path of Excel you have fill with your data
df = pd.read_excel('../OneDrive/Bureau/KIE_Vibration.xlsx')
#Data
lini=df['frequencies of the molecule containing the light isotope at the initial state'].to_list()
hini=df['frequencies of the molecule containing... |
import getpass
adict = {}
def new_user():
user = input('用户名: ').strip()
if user:
if user not in adict:
# passwd = input('密码: ').strip()
getpass.getpass
if passwd:
adict[user] = passwd
print('注册成功')
else:
pr... |
"""
A representation of one field.
Created on Aug 2013
@author: zul110
"""
class TvField(object):
def __init__(self, name, termVector):
self._name = name # a string
self._termVector = termVector # a dictionary.
def to_dict(self):
return {'name': self._... |
import torch
import pytorch_lightning as pl
# A LightningModule ORGANIZES the PyTorch code into the following modules:
# 1. Computations (init)
# 2. Training loop (training_step)
# 3. Validation loop (validation_step)
# 4. Test loop (test_step)
# 5. Optimizers (configure_optimizers)
##################################... |
from PyQt5.QtWidgets import QDialog, QApplication, QVBoxLayout, QCalendarWidget, QLabel
import sys
from PyQt5 import QtGui
class Window(QDialog):
def __init__(self):
super().__init__()
self.title = "This is first thing"
self.height = 700
self.width = 1100
sel... |
from torch.autograd import Variable
import torch
import torch.utils.data
import torch.tensor
import torch.nn as nn
import torch.nn.functional as nn_func
import torch.optim as optim
import numpy as np
import math
class ConvNet (nn.Module):
output_vector_size = 60
def __init__(self,wordvector_size_input):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.