index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
7,700 | ce3c1a7210632d0a8475fe886d514eb91d3c75ac | ''' Model package should containt all data types for the database engine,
which means that projects like PyCIM can be included within ''' |
7,701 | dffd575b9d5b763abdbce6f88586c183b71086c4 | def formula(a,b):
if(b == 0):
print "You can not divide by zero"
else:
return (a+b)/b
print formula(4,4)
print formula(2,0)
|
7,702 | 6199a2ac12e80395f4a7a54877c5b639315e64aa | import numpy as np
import sys
class NeuralNetworkClassifier():
def __init__(self, hidden_units, learning_rate, batch_size, epochs, l_1_beta_1, l_1_beta_2, l_2_alpha_1, l_2_alpha_2):
self._hidden_units = hidden_units
self._learning_rate = learning_rate
self._batch_size = batch_size
... |
7,703 | f398b724fc28bc25ddb8baf492f34075db0c1f61 | COPY_GOOGLE_DOC_KEY = '1CdafeVmmtNa_PMV99TapPHvLUVzYz0xkvHcpINQtQ6c'
DEPLOY_SLUG = 'al-qassemi'
NUM_SLIDES_AFTER_CONTENT = 2
# Configuration
AUDIO = True
VIDEO = False
FILMSTRIP = False
PROGRESS_BAR = False |
7,704 | cd9f25a2810b02f5588e4e9e8445e7aaec056bf8 | import scrapy
from yijing64.items import Yijing64Item
# import pymysql
class ZhouyiSpider(scrapy.Spider):
name = 'zhouyi'
allowed_domains = ['m.zhouyi.cc']
start_urls = ['https://m.zhouyi.cc/zhouyi/yijing64/']
def parse(self, response):
li_list = response.xpath("//div[@class='gualist1 tip_tex... |
7,705 | 4a223cdd3c957af2f54e33c910ce70d2b5e6c963 | # 斐波那契数列(后一位=前两位之和)
# 又叫黄金分割数列,前/后 越来越接近0.618
# list1 = []
# for i in range(20):
# if i <= 1:
# list1.append(1)
# else:
# list1.append(list1[-2]+list1[-1])
# print(list1)
import random
dict1 = {'A': [], 'B': [], 'C': [], 'D': []}
for i in range(20):
re = random.randint(1, 100)
if re >=... |
7,706 | 8be6031caad26ec6b6b99b8d8b8f80d16ad243d4 | from django.db.models import Count
from django.utils.text import slugify
from rest_framework.serializers import ModelSerializer, SerializerMethodField, Serializer
from rest_framework import serializers
from category.models import Category
from product.models import Product, GalleryProduct, Stone, Color, Size
... |
7,707 | 8aeb7786984f27fabdcaffa54f52eb868c277fdb | # Global version information
__version__ = "0.6.1"
|
7,708 | 834469f9c6e065fb29dfe1fd3e421fbb752f5094 | from datetime import datetime
from app import db
class Vocabulary(db.Model):
_id = db.Column(db.Integer, primary_key=True)
language = db.Column(db.String(64), index=True)
word = db.Column(db.String(64), index=True, unique=True)
date = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
7,709 | b670655e3a8e88b97eed35e187b01d6524a16af3 | #!/usr/bin/python
# -*- coding: utf-8 -*-
plugins_list = []
class PluginType(type):
def __init__(cls, name, bases, attrs):
super(PluginType, cls).__init__(name, bases, attrs)
# registrar el plugin en la lista
if not cls in plugins_list:
plugins_list.append(cls)
class PluginB... |
7,710 | 2783fc24806c323ab4ac44fbac55eef73142ab80 | from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
class Project(models.Model):
project_id = models.IntegerField(primary_key=True)
project_name = models.CharField(max_length=50)
project_description = models.CharField(max_length=200, blank=True, ... |
7,711 | c00db6d6fd903236de37ccc029ed30fd46dccdef | import numpy as np
import pandas as pd
import matplotlib as plt
import scipy.linalg
from distance_metrics import *
import time
import random
RANDOM_SEED = 42
np.random.seed(RANDOM_SEED)
random.seed(RANDOM_SEED)
################################################################
# PCA #
##############################... |
7,712 | 1f45bdbfdd29a0b832ebac7e4ff91df1203ae158 | #容器序列
#list tuple collections.deque dict
#扁平序列
#str
#可变序列
#list collections.deque dict
#不变序列
# tuple str |
7,713 | 69d48bc9ecd0f003d7b22c6fbaa532d28137b38e | """
Escreva um programa que leia as coordenadas x e y de um ponto R² e calcule
sua distância da origem(0,0).
"""
import math
print("Origem = 0")
x = int(input("X: "))
y = int(input("Y: "))
aux = (x*x)+(y*y)
dist = math.sqrt(aux)
print("Distância da origem {:.2f}".format(dist)) |
7,714 | 00f8a56b160cab22bf73c0d2397eb2c411e8c966 | import sys, getopt
sys.path.append('.')
import RTIMU
import os.path
import time
import math
import encoders
import motors
#right is master, left is slave
master_power = .6
slave_power = -.6
right_num_revs = 0
left_num_revs = 0
kp = .5
encoders.init()
motors.init()
en_left, en_right = encoders.read()
SETTINGS_FILE ... |
7,715 | 655e6531dc21dcdf8fa827184444cee483492b81 | __author__ = "Sarah Hazell Pickering (sarah.pickering@anu.edu.au)"
__date__ = "2018-11-15"
""" QC and Trimming with fastp
Trimming and QC with fastp.
Then subsampling of reads via seqtk.
Now starts with a sample/sample.file structure.
Number of reads to sample is can be supplied via pairs_to_sample
... |
7,716 | 2b7415d86f9157ae55228efdd61c9a9e9920bc5c | __author__ = 'fshaw'
import gzip
import hashlib
import os
import uuid
import json
import jsonpickle
from chunked_upload.models import ChunkedUpload
from chunked_upload.views import ChunkedUploadView, ChunkedUploadCompleteView
from django.conf import settings
from django.core import serializers
from django.core.files.ba... |
7,717 | 95845aeb47e0d2c579739767ece35f4134564d98 | import json
import math
import rospy
import sys
import RPi.GPIO as GPIO
from std_msgs.msg import Float32
from geometry_msgs.msg import Point32
from time import sleep
#pulse width of difference rotations
d_45 = 1.0
d_90 = 1.5
d_180 = 2.5
frequency = 50.0
t_per_cycle = (1.0 / frequency) * 1000.0
#convert to duty cycle... |
7,718 | cb6ed6422a5591f1de0a947f75ad080f250e8443 |
# read in file of customs declaration responses
declarations_file = open('day6_declarations.txt', 'r')
lines = declarations_file.readlines()
# initialise variables
group_responses = [] # temporary container for all responses of each group member
count_any_member_has_response = 0 # count for part... |
7,719 | 25f3c9f48b779d2aec260d529529156ff3c508ca | '''
文件读写的步骤
1.打开文件
2.处理数据
3.关闭文件
1.open函数:
fileobj = open(filename, mode)
fileobj是open()函数返回的文件对象
mode第一个字母指明文件类型和操作的字符串,第二个字母是文件类型:
t(可省略)文本类型,b二进制类型。
文件打开模式:r只读(默认),w覆盖写(不存在则新创建)
a追加模式(不存在则创建)
2.read(size):从文件读取长度为size的字符串,若未给定或为负则读取所有内容
3.readline():读取整行返回字符串
4.readline... |
7,720 | 29cae66fdca65020a82212e5eabbc61eb900e543 | # test_LeapYear.py
# By Alex Graalum
import unittest
import LeapYear
class test_leapyear(unittest.TestCase):
def test_four(self):
self.assertEqual(LeapYear.leapyear(2012), True)
def test_hundred(self):
self.assertEqual(LeapYear.leapyear(2100), False)
def test_fourhundred(self):
self... |
7,721 | d1077107a5cd3a9f489f74b030a698b0521841f3 | # 파이썬 딕셔너리
# 범용적으로 가장 많이 사용되는 타입
# key와 value의 대용관계 type
# 순서 X, key 중복 X, 수정 O, 삭제 O
# {}
# class란 실세계(오브젝트)의 명사,동사적인 특징들을 추상화시키는 것, 즉 프로그램 내 인스턴트(객체)를 추출하는 템플릿이다
# class는 틀이고 인스턴스는 틀에의해 만들어지는 결과물.하여 instance.class()로 표현
#temp = {}
#print(type(temp))
dic01 = {'name' : 'seop',
'age' : 48,
... |
7,722 | 138abb40fda0f19b4a74a294d5cd0dd326dc59ce | from getMerriamWebster import searchMerriamWebster
from searchWikipedia import searchWikipedia
from synonyms import searchSynonyms
class Scraping:
def __init__(self, clues, answers, gridIndex):
self.clues = clues
self.domains = {"across": {}, "down":{}}
self.answers = answers
self.g... |
7,723 | 3375bc94d214b0b1c67986d35b0587714dd63bcd | # -*- coding: utf-8 -*-
import os
import sys, getopt
import paho.mqtt.client as mqtt
import random
import _thread
import time
import json
HOST = '0.0.0.0'
PORT = 9090
# gb_freq = 0
CONFIG_PATH = 'config/config.cfg'
ITEMS_PATH = 'config/items.cfg'
MILISECOND = 0.001
class Item(object):
def __init__(self, string):
... |
7,724 | 1eab2ddda6fdd71db372e978caa6e7d24c7fe78e | """
Написать программу, которая принимает строку
и выводит строку без пробелов и ее длину.
Для удаления пробелов реализовать доп функцию.
""" |
7,725 | 564c613491b0d1797b216a0bd425690e9fae12bc | import json
from asgiref.sync import async_to_sync
from daphne_API.diversifier import activate_diversifier
from daphne_API.models import Design
def send_archs_back(channel_layer, channel_name, archs):
async_to_sync(channel_layer.send)(channel_name,
{
... |
7,726 | caa92eb5582135f60a6034cb83d364501361d00e | #!/usr/bin/python
# -*- coding: utf-8 -*-
# you can use print for debugging purposes, e.g.
# print "this is a debug message"
def solution(A):
N = len (A)
#min_avg = min( (A[0] + A[1]) / 2, (A[0] + A[1] + A[2]) / 3)
min_avg = (A[0] + A[1]) / 2.0
min_idx = 0
now_avg = 0.0
for i in xra... |
7,727 | 16106250548ef60b475b009116cfeb7a25101637 | import torch.nn as nn
class RNN_instruction_encoder(nn.Module):
def __init__(self, vocab_size, word_vec_dim, hidden_size,
n_layers, input_dropout_p=0, dropout_p=0, bidirectional=True,
variable_lengths=True, word2vec=None, fix_embeddings=False,
rnn_cell='lstm'):
... |
7,728 | 98ddf0be2c38cd9b10dfa9cc09f53907b34c1287 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
config = {
'name': 'beziers',
'author': 'Simon Cozens',
'author_email': 'simon@simon-cozens.org',
'url': 'https://github.com/simoncozens/beziers.py',
'description': 'Bezier curve manipulation library',
'lo... |
7,729 | 1bb953b665f48638691986e2fcae73b10a1c2ce0 | #!/usr/bin/env python
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import unittest
# Allow interactive execution from CLI, cd tests; ./test_cli.py
if __package__ is None:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ksconf.con... |
7,730 | 40744a8530df28f0bd8648900beb8a66e2d44cd0 | # Background: The Fibonacci numbers are defined by F(n) = F(n-1) + F(n-2).
# There are different conventions on whether 0 is a Fibonacci number,
# and whether counting starts at n=0 or at n=1. Here, we will assume that
# 0 is not a Fibonacci number, and that counting starts at n=0,
# so F(0)=F(1)=1, and F(2)=2. Wit... |
7,731 | 9c98ecde2e8aac00a33da7db6e5e6023519e4b84 | from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.db.models.signals import pre_save
from NetFlix.db.models import PublishStateOptions
from NetFlix.db.receivers import publicado_stado_pre_save, slugify_pre_save
class VideoQuerySet(models.QuerySet):
def... |
7,732 | 415a6cf1c3f633a863851a4a407d416355398b39 | import torch
import numpy as np
import torch.utils.data as data
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
class CNN(nn.Module):
def __init__(self,
fragment_length,
conv_layers_num,
conv_kernel_size,
pool_kernel_size,
fc_siz... |
7,733 | 57564c2e94a65187bf5e033ee06926fb593e11a7 | from yapsy.IPlugin import IPlugin
import wolframalpha
import yaml
keys_file = open("friday/plugins/KEYS")
keys = yaml.load(keys_file)
keys_file.close()
class Wolfram(IPlugin):
def can_perform(self, friday, request):
return 'result' in request and 'resolvedQuery' in request['result']\
and ... |
7,734 | 34c8541e640596f51a5232cba06172df5814db14 | #!/usr/bin/python
from PyMca5.PyMcaGui import PyMcaQt as qt
from RixsTool import mainWindow
app = qt.QApplication([])
win = mainWindow.RIXSMainWindow()
win.show()
app.exec_()
|
7,735 | c6a4d566460a06504abf7e2c54be4f2ea36e01fb | # VGGNet
import numpy as np
np.random.seed(317)
from glob import glob
from itertools import cycle
from keras.applications.vgg19 import VGG19
from keras.optimizers import Adam
from keras.models import Model
from keras.layers import Input, BatchNormalization, Flatten, Dropout, Dense
from keras.utils import plot_model
fr... |
7,736 | 2728c3ab26fbdbaac9c47054eafe1c114341f6f2 |
from sand_game.Environment import Environment
from sand_game.behaviours.Behaviour import Behaviour
class EphemeralBehaviour(Behaviour):
"""Removes the particle after one frame
"""
def behave(env: Environment, loc: tuple[int, int]) -> tuple[int, int]:
env.set(loc[0], loc[1], None)
|
7,737 | a5918679b6e3a9bde54808264d9526c6a191578f | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 10:34:15 2021
@author: Ivan
課程教材:行銷人轉職爬蟲王實戰|5大社群平台+2大電商
版權屬於「楊超霆」所有,若有疑問,可聯絡ivanyang0606@gmail.com
第一章 爬蟲基本訓練
Html爬蟲Post教學-台灣股市資訊網
"""
import requests
from bs4 import BeautifulSoup
# 要抓取的網址
url = 'https://goodinfo.tw/StockInfo/StockDividendPolicy.asp?S... |
7,738 | 31275ca9e20da9d2709ea396e55c113b3ff4f571 | from django.apps import AppConfig
class ModuloConfig(AppConfig):
name = 'modulo'
verbose_name = 'TUM:JungeAkademie - Modulo'
def ready(self):
#start-up / initialization code here!!!
from .recommender import Recommender
Recommender.initialize() |
7,739 | 1fbe269c9c09fe58b0df1ebd4354cf9dc31a2f90 | def is_palindrome_v2(word):
'''(string)->boolean
returns if word is palindrome (ignores white space)'''
if len(word) < 2:
return True
if(not word[0].isalpha() or not word[1].isalpha()):
if(word[0].isalpha()):
return is_palindrome_v2(word[:-1])
if(word[-1].isal... |
7,740 | bf1221bc9768cff2edb67e0e5f5cea0ee2dd64e5 | """social_website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
7,741 | c475e095571b211693e66583637442edbf72c260 | from twitter.MyStreamListener import MyStreamListener
import tweepy
from threading import Thread
class TwitterWorker(Thread):
def __init__(self):
Thread.__init__(self)
CONSUMER_KEY = 'IwZZeJHjLXq55ewwQwD0SogHU'
CONSUMER_SECRET = '80kELQhDGNvLNFfNZ7qliIbzAoA3tsgQ... |
7,742 | b419e26cbf5bbb746f897367ddaa829773a6860c | from django.db import models
from django.utils import timezone
from accounts.models import AllUser
from profiles.models import Profile
### MODEL HOLDING MEMBER TO CLIENT RELATIONSHIPS. ###
class MemberClient(models.Model):
created = models.DateTimeField(auto_now_add=timezone.now())
client = models.ForeignKey(... |
7,743 | 6f05d1915cd2e123dd72233b59d4de43fd724035 | from . import find_resault
from . import sql |
7,744 | 9f42a9d0ca622d6c4e2cf20bc2e494262c16055b | import cv2
import numpy as np
from matplotlib import pyplot as plt
#cargar la imagen a analizar
imagen= cv2.imread("tomate22.jpg")
#cv2.imshow("Original", imagen)
#cv2.waitKey(0)
# Convertimos en escala de grise
gris = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY)
#cv2.imshow("En gris", gris)
#cv2.waitKey(0)
# Aplicar s... |
7,745 | f81e4c9a502855dca31c6c991a08a12af1c2e2a6 | import scipy.constants as const
import scipy.optimize as opt
import numpy as np
import pum.algorithms as alg
from pum.lines import *
from pum.net import *
mu = 1
eps = 2.56
b = 2.8 * const.milli
C = 13.0
Z0 = 50
f0 = 1.34 * const.giga
k = 10 ** ( - np.abs(C) / 20)
print 'k = {}' .format( k)
Z0e = ... |
7,746 | e54eea2261517a2b15fde23c46b3fe75c0efec64 | # генераторы списков и словарей
# lists
my_list = [1, 2, 3, 4, 5]
new_list = []
for i in my_list:
new_list.append(i**2)
new_list_comp = [el**2 for el in my_list]
lines = [line.strip() for line in open("text.txt")]
new_list_1 = [el for el in my_list if el % 2 == 0]
str_1 = 'abc'
str_2 = 'def'
str_3 = 'gh'
new_... |
7,747 | cc66dcd34115e72479953ca24f4b2eaeb52cf313 | import socket
import json
import numpy as np
"""TCP client used to communicate with the Unity Application"""
class TCP:
def __init__(self, sock = None):
# Create a TCP socket
if sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
self.s... |
7,748 | 891a490410fd8c7b8879f1e71f24df2db62ff85d | import httplib
def get_status_code(host, path="/"):
try:
connect = httplib.HTTPConnection(host)
connect.request("HEAD", path)
return connect.getresponse().status
except StandardError:
return None
if __name__ == '__main__':
print get_status_code("google.com")
|
7,749 | 056235f8f65a3d6a310ee8a8742c1369b5398f28 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
One cycle policy based on Leslie Smith's paper(https://arxiv.org/pdf/1803.09820.pdf)
Created on Wed Mar 31 13:53:39 2021
"""
import logging
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
logging.getLogger('tensorflow').setLevel(logging.ERR... |
7,750 | 32bb6d5ad0a1398c9ab89190c087fe3916631878 | import ordenador
import pytest
import contatempo
class TestaOrdenador:
@pytest.fixture
def ordenad(self):
return ordenador.Ordenador()
@pytest.fixture
def list_quase_ord(self):
c = contatempo.ContaTempos()
return c.lista_quase_ordenada(100)
@pytest.fixture
def list_al... |
7,751 | fb4a95197882cc6fe72a5f3c2420a474d9cd97aa | # -*- coding: utf-8 -*-
import scrapy
import re
class LeedsAcUkSpider(scrapy.Spider):
name = 'leeds_ac_uk'
allowed_domains = ['webprod3.leeds.ac.uk']
start_urls = ['http://webprod3.leeds.ac.uk/catalogue/dynmodules.asp?Y=201920&M=ANAT-3105']
def parse(self, response):
item = {}
item['Su... |
7,752 | 98f36b216e718fc4fe42d1717ff9ba82cc24c2ff | def to_bitmask(n, bits):
# [2:] to chop off the "0b" part
mask = [int(digit) for digit in bin(n)[2:]]
# pad to fixed length
return [0] * (bits - len(mask)) + mask
def invert_mask(mask):
return [int(not bit) for bit in mask] |
7,753 | 923a433a3a04a8538b43d162d17d379daab4698a | #!/usr/bin/env python3
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ... |
7,754 | 55a061a1c0cd20e5ab7413c671bc03573de1bbdf | #!/usr/bin/python3
"""
list = list(range(97, 123)
for (i in list):
if (i % 2 == 0):
i = (i - 32)
"""
for letter in "zYxWvUtSrQpOnMlKjIhGfEdCbA":
print('{:s}'.format(letter), end = "")
|
7,755 | 4ddff57790ad191fc29fc092bcc714f0b6273100 | # _*_ coding: utf-8 _*_
# 按层打印二叉树
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class PrintTree(object):
def printTree(self, root):
if not root:
return
'''
定义next_last为下一层的最后一个,cur_last为当前层最后一个
... |
7,756 | d8e0198244c3df77fa0258cc97a55042e36d056f | """
默认查询所有
> db.test1000.find()
{ "_id" : ObjectId("5c3559ab648171cce9135dd6"), "name" : "zhangdapeng" }
{ "_id" : ObjectId("5c3559af648171cce9135dd7"), "name" : "zhangdapeng1" }
{ "_id" : ObjectId("5c3559b2648171cce9135dd8"), "name" : "zhangdapeng2" }
{ "_id" : ObjectId("5c3559b4648171cce9135dd9"),... |
7,757 | d1af148bc6b27d38052f2e57f1c610c86eccebef | #!/usr/bin/python3
import sys
import math
class parameter :
opt = 0
xp = 0
yp = 0
zp = 0
xv = 0
yv = 0
zv = 0
p = 0
def check_args() :
try :
int(sys.argv[1])
int(sys.argv[2])
int(sys.argv[3])
int(sys.argv[4])
int(sys.argv[5])
int(sys... |
7,758 | 0f6512bb734336a67eab2f13949dd960f5ffc1d5 | from arma_scipy.fit import fit, predict
|
7,759 | ee47b60274ed2eb53a05203e0086d7815bcaaa6e | # -*- coding: utf-8 -*-
from sklearn.feature_extraction.text import TfidfVectorizer
import sentimentAnalysis as sA
import sys
import os
import numpy as np
from sklearn import decomposition
from gensim import corpora, models
if len(sys.argv) > 1:
keyword = sys.argv[1]
else:
keyword = 'data'
... |
7,760 | f507fbe7c92134c0a7149aafe7de88debebd42f5 | #파이썬 심화
#클래스 메소드, 인스턴스 메소드, 스테이틱 메소드
# 기본 인스턴스 메소드
class Student(object):
"""
Student Class
Author : Kim
Date : 2020.11.07
Description : Class, Static, Instance Method
"""
#Class Variable
tuition_per = 1.0
def __init__(self, id, first_name, last_name, email, grade... |
7,761 | 9dde8e5fd0e83860ee86cf5402ab6eeb5b07ab2c | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qtGSD_DESIGN.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(... |
7,762 | cd175c236dd1d1c7387a21a491e80d6723f161dc | import json
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
total=list()
url= input ('Enter Location: ') #user input url
print('Retrieving: ', url)
uh = urllib.request.urlope... |
7,763 | 33c0efb47e3253442b6a808c7ebffac275c19321 | from pylab import *
import pandas as pd
from matplotlib import pyplot
import pylab
from mpl_toolkits.mplot3d import Axes3D
from threading import Thread
from threading import Semaphore
from threading import Lock
from Queue import Queue
sam = Semaphore(1)
lck = Lock()
q=Queue(10)
def myFunc(z):
#if z%2==0 and z>1:
... |
7,764 | 512a13084a860e2784020664a3d5824d9dace6db | from django.db import models
import django.utils.timezone as timezone
# Create your models here.
# Create your models here.
class Categories(models.Model):
# 文章分类
name = models.CharField(max_length=200, verbose_name = "分类名称")
parent = models.ForeignKey('self', default=0, on_delete=models.DO_NOTHING, null = True... |
7,765 | 91f3aae4e74f371cadaf10385510bc1c80063f55 | import sys
import time
def initialize(x: object) -> object:
# Create initialization data and take a lot of time
data = []
starttimeinmillis = int(round(time.time()))
c =0
file1 = sys.argv[x]
with open(file1) as datafile:
for line in datafile:
c+=1
if(c%100==0):
... |
7,766 | dc5630e17bb6ed85157b06108250427be41416d1 |
def ddm_dd_convert(coord, direction):
"""Converts GPS reading from DDM to DD
str coord - the ddm coordinate from $GPGGA
str direction - the direction of the coord (N,S,W,E)
returns - string representation of dd coordinate
"""
value = ''
if (direction == 'S' or direction =... |
7,767 | 6c0a1d4ffd64e0566be53937d9b48975f2530852 | import matplotlib.pyplot as plotOp
import numpy as np
from random import randint
import re as regexOp |
7,768 | d2af2b25a1ba2db93c977a13fe0273919bc2e6e0 | from DataStructures.BST.util import *
def storeInorder(root, inorder):
if root is None:
return
storeInorder(root.left, inorder)
inorder.append(root.data)
storeInorder(root.right, inorder)
def arrayToBST(arr, root):
# Base Case
if root is None:
return
# First update the ... |
7,769 | 0d862715524bd35347626e7708c7c8f8b370bb3a | import sklearn
import pandas as pd
import numpy as np
from sklearn import datasets, ensemble
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
import statistics as st
import itertools
from sklearn.model_selection import cross_val_score
from sklearn.experimen... |
7,770 | 38504dae7b010c2df8c16b752c2179b6b3561c0e | # day one question 1 solution
# find product of two numbers in input.txt list that sum to 2020
# pull everything out of input file
nums = []
with open('input.txt', 'r') as file:
for line in file:
nums.append(int(line))
target = 0
product = 0
# for each number in the input, figure out what it's complement... |
7,771 | f8972067fa88e7e74e05cdcc7bdec184116dec4a | import os
import random
import argparse
from vapory import *
from data import colors, object_types
class Torus(POVRayElement):
""""""
def render_scene(filename, object_type, color, location, rotation):
assert (object_type in object_types)
assert (color in colors)
color = colors[color]
size = ... |
7,772 | 305133d4840741bd5c318a99a96660d8988dd61a | # Copyright (C) 2020 Claudio Marques - All Rights Reserved
dataset_path = "data/output/dataset{toReplace}.csv"
dataset_path_final = "data/output/final/datasetFinal.csv"
log_path = "data/logs/output_append.log"
numberOfThreads = 45
inputFileMalign = "data/input/malign/all.log"
outputFileMalign = "data/output/fil... |
7,773 | 1c9345923fe83aa0ee7165ce181ce05ac55e2b2f | class Action(dict):
def __init__(self, action, player=None, target=None):
self['action'] = action
self['player'] = player
if target != None:
self['target'] = target
|
7,774 | 8475792cc2d55f030f0bd9e7d0240e3b59ed996b | import os
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plotObject(obj):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x,y,z = numpy.nonzero(obj>0)
ax.scatter(x,y,z,c='r',s=10)
xb,yb,zb = numpy.nonzero(obj<0)
ax.scatter(xb,yb,zb,c='b',s=1)
plt.show()
c... |
7,775 | dcb12e282962c63f8e7de5d29c4c81ad177a387e | import heapq
class Solution: #priority queue
# def sortElemsByFrequency(self, arr):
# if arr:
# mydict = {}
# for k,v in enumerate(arr):
# mydict[v] = mydict.get(v, 0) + 1
# sorted_dict = sorted(mydict.items(), key = lambda x:x[1])
# return sorted_dict
def sortElemsByFrequen... |
7,776 | 7451b09c54734fb02167d43b96df972420d86853 | import sys
from domain import *
from fuzzy_set import *
from parser import *
class FuzzyControler(object):
def __init__(self, angle_rules, acc_rules, domains_angle, domains_acc):
self.angle_rules = angle_rules
self.acc_rules = acc_rules
self.domains_angle = domains_angle
self.domains_acc = domains_acc
s... |
7,777 | a9eb2b3f26396918c792de3f126e51bde334b709 | #!/usr/bin/env python3
# given a set A and n other sets.
# find whether set A is a strict superset of each of the n sets
# print True if yes, otherwise False
A = set(map(int, input().split()))
b = []
for _ in range(int(input())):
b.append(A > set(map(int, input().split())))
print(all(b))
|
7,778 | 084c9ad83091f6f96d19c0f0c28520ccda93bbaf | import base64
import bleach
import errno
import fcntl
import gzip
import hashlib
import importlib
import inspect
import magic
import mimetypes
import morepath
import operator
import os.path
import re
import shutil
import sqlalchemy
import urllib.request
from markupsafe import Markup
from collections.abc import Iterabl... |
7,779 | b9386cf8c17b28fd1fea6e587ca4401de247cbea | #!/usr1/local/bin/python
import os, sys, re, shutil, random
from tempfile import *
# program location
prog_dir = '/home/jpei/test_promals3d_package/bar/promals_package/bin/'
# program names
promals_web = prog_dir + "progress_for_web.py"
csv_cutoff_g = 5
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV... |
7,780 | 4c5416582afb3cfeb56259954cda2701ea26f8cd | # -*- coding: utf-8 -*-
"""
helpers
~~~~~~~
Implements various helper functions.
:copyright: (c) 2016 by Patrick Spencer.
:license: Apache 2.0, see LICENSE for more details.
"""
from datetime import datetime, timedelta
import calendar
def month_bounds(year, month):
"""
Returns a tuple of ... |
7,781 | 730aaa0404a0c776ce4d3a351f292f90768b6867 | import re
def parse_rule(rule):
elem_regex = re.compile("(\d+) (.*) bags?.*")
rule = rule[:-1]
color, inside = tuple(rule.split(" bags contain"))
result = []
for element in inside.split(","):
match = elem_regex.search(element)
if match:
result.append((match.gro... |
7,782 | c99878dbd5610c8a58f00912e111b1eef9d3893e | from os import path
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.pipeline import Pipeline
from sta211.datasets import load_train_dataset, load_test_dataset, find_best_train_dataset
from sklearn.model_selection import GridSearchCV
from sta211.selection import get_naive_bayes, get_mlp, get_svm,... |
7,783 | 187c2a56ba9360b89c8ded09861091e2deedf32e | import os, sys, shutil
import fnmatch, logging, zipfile
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d,%H:%M:%S', level=logging.DEBUG)
def scan_files(dir, pattern):
fileList = []
for root, subFolders, files in os.walk(dir):
for file in files:
... |
7,784 | a63e5186c0eb8b5ae8510b473168db3461166513 | from django.views.generic import (ListView, DetailView, CreateView,
DeleteView, UpdateView, TemplateView)
from django.views.generic.edit import ModelFormMixin
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators i... |
7,785 | 7f63097265b1058785e90441f85b7f0088946717 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('guac_auth', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='guacamoleconnectiongroup',
... |
7,786 | 053fa80c80d40cd28acb7d6a8bf1b2c30be9b36e | from PIL import Image, ImageDraw, ImageFont
import sys
### Create 1024,1024 pixel image with a white background.
img = Image.new("RGB", (1024, 1024), color = (255,255,255))
### Take text to be drawn on the image from the command terminal.
text = sys.argv[1]
### Chose favourite font and set size of the font.
fnt = Im... |
7,787 | 4f9729e396e01cb3d6c9011f79a1ebe618a8e762 | import os
import subprocess
import discord
import asyncio
import traceback
import sys
import ast
from discord.ext import commands
# Import Cogs
from cogs.misc import Miscellaneous
from cogs.serversettings import ServerSettings
from cogs.mod import Moderator
from cogs.automod import AutoMod
from cogs.google import Goo... |
7,788 | 2440f5bc774f2e2f746a246cbb2e305965c9e576 | from __future__ import absolute_import
from django.conf.urls import patterns, url
from sentry_plugins.jira_ac.views import JiraConfigView, \
JiraDescriptorView, JiraInstalledCallback, JiraUIWidgetView
urlpatterns = patterns(
'',
url(r'^plugin$', JiraUIWidgetView.as_view()),
url(r'^config$', JiraConfi... |
7,789 | 937a101cf5c7e943fc62d18b77357eea151fdfaf | cardlist = []
card = []
for j in range(1,5):
for k in range(1,14):
if j == 1:
cardlist.append(["S", "{}".format(k)])
elif j == 2:
cardlist.append(["H", "{}".format(k)])
elif j == 3:
cardlist.append(["C", "{}".format(k)])
elif j == 4:
c... |
7,790 | 856a27e953a6b4e1f81d02e00717a8f95a7dea5f | import cv2
# open webcam (웹캠 열기)
webcam = cv2.VideoCapture(0)
if not webcam.isOpened():
print("Could not open webcam")
exit()
sample_num = 0
captured_num = 0
# loop through frames
while webcam.isOpened():
# read frame from webcam
status, frame = webcam.read()
sample_num = s... |
7,791 | 2060f0af351c1487f8aa45943dbaa050f4291c58 | from typing import Any, Callable, Generator, List, Optional
import pytest
from _pytest import nodes
from _pytest.config import hookimpl
from _pytest.python import Function, PyCollector # type: ignore
from hypothesis.errors import InvalidArgument # pylint: disable=ungrouped-imports
from .._hypothesis import create_t... |
7,792 | 0110d26e17a5402c22f519d0aeb2aacca3279d00 | import datetime
now = datetime.datetime.now()
# Printing value of now.
print ("Time now : ", now)
|
7,793 | 3583ce664bc9f42ef8f751de8642997819e08e31 | # -*- coding: utf-8 -*-
import scrapy
import re
import time
import random
import hashlib
from quotetutorial.items import ScrapyItem
import requests
import os
import io
import sys
# 科学技术部
class MostSpider(scrapy.Spider):
index = 12
name = 'most'
allowed_domains = ['www.most.gov.cn']
start_urls = [
... |
7,794 | 5711613df0bda10512466f147febcffacfe1607b | # [BEGIN IMPORTS]
from mainhandler import MainHandler
from sec.data import *
# [END IMPORTS]
class UpVoteHandler (MainHandler):
def get(self):
user = self.get_user()
if user:
post_id = self.request.get('post_id')
post = PostData.get_by_id(int(post_id))
voter_l... |
7,795 | c58bfa620df9f1b1f31c83a76d0d8a4576cbd535 | #!/usr/bin/env python
from scapy.all import *
from optparse import OptionParser
import socket
import struct
class MagicARP:
def __init__(self, iface):
self.iface = iface
self.macrecs = {}
def magic_arp(self, pkt):
# only look for queries
if ARP in pkt and pkt[ARP].op == 1:
# Get a rand... |
7,796 | e31f1e24c319f338d728661dfd50e758526112d6 | import pygame
from settings import *
import random
class Cell:
def __init__(self, game, x, y, bombs):
self.game = game
self.x = x
self.y = y
self.i = x // TILESIZE
self.j = y // TILESIZE
self.revelada = False
self.bomba = False
self.bombas_total = bo... |
7,797 | 679d4b224733dbe264caeeda4e228edd090ea9de | # coding=UTF-8
'''
Created on Jul 21, 2013
@author: jin
'''
from django import template
register = template.Library()
@register.filter
def get_list_number(value,num):
result=value[num]
return result
# register.filter('get_list_num', get_list_num)
'''
test
'''
if __name__=='__main__':
print get_list_numb... |
7,798 | 3035ac8044b5629d0b5de7934e46890ad36ed551 | from nltk.tokenize import RegexpTokenizer
from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
from gensim import corpora, models
import gensim
tokenizer = RegexpTokenizer(r'\w+')
# create English stop words list
en_stop = get_stop_words('en')
# Create p_stemmer of class PorterStemmer
p_s... |
7,799 | 4745c00ca0f3ca4316117228a9d44bdb5df02877 |
def lucas():
yield 2
a = 2
b = 1
while True:
yield b
a, b = b, a + b
l = lucas()
for i in range(10):
print('{}: {}'.format(i,next(l))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.