index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
1,200
c4f437e6f5aaeccb6dd0948c3ed1f1d465bb29ce
import speech_recognition as sr import pyttsx3 import pywhatkit import datetime listner = sr.Recognizer() engine = pyttsx3.init() #change voices voices = engine.getProperty('voices') engine.setProperty('voice',voices[10].id) rate = engine.getProperty('rate') engine.setProperty('rate', 150) #for machine to say def t...
1,201
4ed730369cf065936569a8515de44042829c2143
import os from test.test_unicode_file_functions import filenames def writeUniquerecords(dirpath,filenames): sourcepath=os.path.join(dirpath,filenames) with open(sourcepath,'r') as fp: lines= fp.readlines() destination_lines=[] for line in lines: if line not in destination_l...
1,202
b65d25198d55ab4a859b9718b7b225fa92c13a2b
from whylogs.core.annotation_profiling import Rectangle def test_rect(): rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{"name": "test"}]) test = Rectangle([[0, 0], [5, 5]]) assert rect.area == 100 assert rect.intersection(test) == 25 assert rect.iou(test) == 25 / 100.0 def test_r...
1,203
e78c4f65d84d5b33debb415005e22f926e14d7d4
"""Get pandas dataframes for a given data and month. *get_dataframes(csvfile, spec=SPEC)* is a function to get dataframes from *csvfile* connection under *spec* parsing instruction. *Vintage* class addresses dataset by year and month: Vintage(year, month).save() Vintage(year, month).validate() *Collecti...
1,204
5ab877ef15cdcd52463b1567c28327dc2eeea2de
from selenium import webdriver from selenium.common.exceptions import WebDriverException from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By SELENIUM_TIMEOUT = 12 def get_browser_driver(): """获取浏览器服务...
1,205
a21942a835f7b2ea70e9dd7b26285ea2dd411750
class person(object): population=50 def __init__(self,name,age): self.name=name self.age=age @classmethod def getpopulation(cls): return cls.population @staticmethod def isadult(age=17): return age>=18 def display(self): print(self...
1,206
50ae47c88bbc0f281ef75784377fb65192e257b0
import numpy as np import cv2 import glob from scipy.spatial.transform import Rotation import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import mpl_toolkits.mplot3d.art3d as art3d from matplotlib.patches import Rectangle import celluloid from celluloid import Camera # couldn't save animation ...
1,207
480e6ae9eee70b2da58ca5624a43d8f5dcae1d33
#!/usr/bin/env python import unittest from pyspark import SparkConf, SparkContext from mmtfPyspark.io.mmtfReader import download_mmtf_files from mmtfPyspark.datasets import secondaryStructureExtractor from mmtfPyspark.filters import ContainsLProteinChain from mmtfPyspark.mappers import StructureToPolymerChains class...
1,208
3b959481f7c818ec35b8af174b1982954b4c72eb
""" Forms and validation code for user registration. Note that all of these forms assume your user model is similar in structure to Django's default User class. If your user model is significantly different, you may need to write your own form class; see the documentation for notes on custom user models with django-re...
1,209
cfa7dc295c635bbdf707f1e899c4fbf8ea91df9a
#!/usr/bin/python3 import sys import csv infile = sys.stdin for line in infile: line = line.strip() my_list = line.split(',') if my_list[0] != "ball": continue batsman = my_list[4] bowler = my_list[6] if my_list[9] == 'run out' or my_list[9] == '""' or my_list[9] == "retired hurt": ...
1,210
7a01bffa5d7f0d5ecff57c97478f2cf5e9a27538
import torch, torchvision import torch.nn.functional as F import transformers from transformers import BertTokenizer, BertModel from transformers.models.bert.modeling_bert import BertPreTrainingHeads from utils import construct_bert_input, EvaluationDataset, save_json from fashionbert_evaluator_parser import Evaluation...
1,211
7c60ae58b26ae63ba7c78a28b72192373cc05a86
import smtplib import requests import datetime import json import time from datetime import date from urllib.request import Request,urlopen today = date.today().strftime("%d-%m-%y") count = 0 pincodes = ["784164","781017","784161","787001"] date = 0 temp = str(14) + "-05-21" while True: for...
1,212
45a57fac564f23253f9d9cd5d0fd820e559c15b9
import requests from requests import Response from auditlogging.Trail import Trail from utils.Utils import is_empty from auditlogging.agents.AuditAgent import AuditAgent class APIAuditAgent(AuditAgent): """ Captures the audit trail using a REST endpoint URL (POST) Add this agent to Auditor in order to cap...
1,213
1e84b28580b97e77394be0490f3d8db3d62a2ccb
from django.contrib.auth.models import User from rt.models import Movie_Suggestion, MovieDB, ActorDB, TVDB def user_present(username): if User.objects.filter(username=username).count(): return True return False #Takes in a list of MovieDB/TVDB objects #Outputs a list of sorted titles def sort_title(movies): ti...
1,214
f2e2ebd5b848cf3a01b7304e5e194beb3eec1c10
# -*- coding: utf-8 -*- """ /*************************************************************************** TileMapScalePlugin A QGIS plugin Let you add tiled datasets (GDAL WMS) and shows them in the correct scale. ------------------- begin ...
1,215
0deec9058c6f7b77ba4fa3bfc0269c8596ce9612
''' quarter = 0.25 dime = 0.10 nickel = 0.05 penny = 0.01 ''' #def poschg(dollar_amount,number):
1,216
eb9135c6bcf89a62534cfc8480e5d44a089fe5a8
# -*- coding: utf-8 -*- """ Created on Wed Feb 7 17:42:18 2018 @author: Tim """ import music21 as m21 import music21.features.jSymbolic as jsym import scipy.stats from collections import Counter import numpy as np import matplotlib.pyplot as plt from timeit import default_timer as timer # round all duration values t...
1,217
918653cdeea8d91921f8b96779fcd3ebce491948
#!/usr/bin/env python class Problem1(object): def sum_below(self, threshold): current_number = 1 total = 0 while current_number < threshold: if (current_number % 3 == 0) or (current_number % 5 == 0): total += current_number current_number += 1 ...
1,218
2acfd0bbad68bb9d55aeb39b180f4326a225f6d5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 31 14:35:49 2019 @author: devinpowers """ # Lab 1 in CSE 231 #Quadratic Formula # Find the roots in the Quadratic Formula import math a = float(input("Enter the coeddicient a: ")) b = float(input("Enter the coeddicient b: ")) c = float(input(...
1,219
0276181055f2c70562c1f557a16d00ba7107d003
import pyximport pyximport.install(build_in_temp=False,inplace=True) import Cython.Compiler.Options Cython.Compiler.Options.annotate = True import numpy as np from test1 import c_test,c_test_result_workaround a = np.ascontiguousarray(np.array([ [1,2,3],[1,2,3],[1,2,3] ], dtype=np.long), dtype=np.long) print '\nStar...
1,220
472a79767f5dc7dc3cd03d89999d322b3885dcbf
from django.contrib.auth import get_user_model from rest_framework import generics from rest_framework.response import Response from rest_framework_jwt.settings import api_settings from status.api.serializers import StatusInlineUserSerializer from status.api.views import StatusAPIView from status.models import Status ...
1,221
6109efeb3462ac2c5a94a68fbfa4f2f0617dd927
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 19 09:31:20 2021 @author: dclabby """ import os import cv2 import pickle from utils import locateLetterRegions # # Constants # sourceFolder = '/home/dclabby/Documents/Springboard/HDAIML_SEP/Semester03/MachineLearning/Project/solving_captchas_code_e...
1,222
2a92c47231b75a441660fed80a9bce9a35695af5
from selenium import webdriver import time import math def calc(x): return str(math.log(abs(12*math.sin(int(x))))) try: br = webdriver.Chrome(); lk = 'http://suninjuly.github.io/get_attribute.html' br.get(lk) #собираю treasure=br.find_element_by_id('treasure') valuex = treasure.get_attribute('valuex') radio_...
1,223
92eaceb46974ba3a5944300139d5929d44673181
from tqdm import trange import numpy as np class GPTD_fixedGrid: def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]): self.env = env self.gamma = gamma self.sigma0 = sigma0 self.kernel = kernel.kernel if (not V_mu): V_mu = lambda s: np.zeros((s.sh...
1,224
c926e16ef2daa5978b6c71e7794721d320bb9b1e
def tetrahedron_filled(tetrahedrons, water): var=0 br=0 tetrahedrons.sort() for numbers in tetrahedrons: v=(tetrahedrons[var]**3*(2**0.5))/12000 if v<water: br=br+1 water=water-v var=var+1 print (br) print (tetrahedron_filled([1000,10],10))
1,225
c349fa484476e3195e0932e425cbe93d7a7e5394
#!/usr/bin/env python import rospy from nav_msgs.msg import Odometry from geometry_msgs.msg import Twist from std_srvs.srv import Empty, EmptyResponse import tf from math import radians, degrees, fabs class MovementNullifier: def __init__(self): rospy.Subscriber("odom", Odometry, self.OdomCallback) ...
1,226
3ffe16494eb45896563a2952f3bcf80fc19b2750
def solution(record): answer = [] db = {} chatting = [] for log in record: log_list = log.split() if log_list[0] == 'Enter': db[log_list[1]] = log_list[2] chatting.append([True, log_list[1]]) elif log_list[0] == 'Leave': chatting.append([Fals...
1,227
8c166dd4cb091dcd2d80b5ae3085b5dee77564e0
from django.db import models #from publicservants import models from django.utils.encoding import smart_unicode # Create your models here. class Score(models.Model): #score ID - publicservant ID plus score #sID = models.ManyToOneRel(field=PublicServant.psID) #PS Score at time t pst = models.Inte...
1,228
9d3db4ca5bf964c68e9778a3625c842e74bf9dbd
import os import z5py from shutil import copytree, copyfile ROOT = '/g/kreshuk/pape/Work/data/mito_em/data' SCRATCH = '/scratch/pape/mito_em/data' def create_file(out_path, ref_path): os.makedirs(out_path, exist_ok=True) copyfile( os.path.join(ref_path, 'attributes.json'), os.path.join(out_pa...
1,229
4e7cfbf51ec9bad691d8dd9f103f22728cf5e952
# Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy.special import erfc import time from ..core.errors import InvalidConfigError def compute_integrated_acquisition(acquisition,x): ''' Used to compute the acquisition function when s...
1,230
cb32aa6a1c42e7bb417999f3f6f74ec22209c5a0
from django.core.cache import cache from rest_framework import serializers from thenewboston.constants.crawl import ( CRAWL_COMMAND_START, CRAWL_COMMAND_STOP, CRAWL_STATUS_CRAWLING, CRAWL_STATUS_NOT_CRAWLING, CRAWL_STATUS_STOP_REQUESTED ) from v1.cache_tools.cache_keys import CRAWL_CACHE_LOCK_KEY, ...
1,231
7ef62e5545930ab13312f8ae1ea70a74386d8bfa
def ip_address(address): new_address = "" split_address = address.split(".") seprator = "[.]" new_address = seprator.join(split_address) return new_address if __name__ == "__main__": ipaddress = ip_address("192.168.1.1") print(ipaddress)
1,232
8f558593e516aa4a769b7c5e1c95c8bc23a36420
import torch import util import numpy as np import argparse import losses args = argparse.Namespace() args.device = torch.device('cpu') args.num_mixtures = 20 args.init_mixture_logits = np.ones(args.num_mixtures) args.softmax_multiplier = 0.5 args.relaxed_one_hot = False args.temperature = None temp = np.arange(args....
1,233
c5bbfa1a86dbbd431566205ff7d7b941bdceff58
#!/usr/bin/env python # encoding: utf-8 """ plot: regularization on x axis, number of k_best features on y Created by on 2012-01-27. Copyright (c) 2012. All rights reserved. """ import sys import os import json import numpy as np import pylab as plt import itertools as it from master.libs import plot_lib as plib ...
1,234
2c4fa92b28fa46a26f21ada8826474baac204e00
def mysum(*c): print(sum([x for x in c])) mysum(1,2,3,4,0xB)
1,235
af2aa236f6bfc582093faf868a374be1ebdfabf2
""" """ import os import json import csv cutoff = float(input("Tolerance (decimal)? ")) docpath = "C:/Users/RackS/Documents/" out = open("isosegmenter_scoring_error"+str(cutoff*100)+".csv", 'w', encoding='UTF-8') summary = open("isosegmenter_score_summary_error"+str(cutoff*100)+".txt", 'w', encoding='UTF-8') out.write...
1,236
2396f7acab95260253c367c62002392760157705
import random import numpy as np import torch from utils import print_result, set_random_seed, get_dataset, get_extra_args from cogdl.tasks import build_task from cogdl.datasets import build_dataset from cogdl.utils import build_args_from_dict DATASET_REGISTRY = {} def build_default_args_for_node_classification(da...
1,237
dace25428f48da633ee571b51565d15650782649
#!/usr/bin/python import os import sys import csv import json from time import sleep from datetime import datetime ShowProgress = False ConvertTime = False def print_welcome(): print(""" [*******************************************************************************************************] ...
1,238
347627df4b08eca6e2137161472b4d31534cf81b
import pytz import datetime def apply_timezone_datetime(_local_tz: str, _time: datetime.time): """ set time zone + merge now().date() with time() :param _local_tz: :param _time: :return: """ return pytz.timezone(_local_tz).localize( datetime.datetime.combine(datetime.datetime.now()...
1,239
a36a553342cfe605a97ddc0f636bbb73b683f6a6
import re def match_regex(filename, regex): with open(filename) as file: lines = file.readlines() for line in reversed(lines): match = re.match(regex, line) if match: regex = yield match.groups()[0] def get_serials(filename): ERROR_RE = 'XFS ERROR (\[sd[a-z]\])' #...
1,240
1ed7fb0dd5f0fa5e60c855eceaaf3259092918ef
x, y = [float(x) for x in raw_input().split(" ")] print(x*y)
1,241
b1a1287c2c3b624eb02f2955760f6e9eca8cdcf9
cars=100 drivers=30 passengers=70 print "There are",cars,"cars available." print "There are only",drivers,"drivers available." print "Each driver needs to drive",passengers/drivers-1,"passengers."
1,242
e68d872232b3eab4c33cbbe4376be7dd788888e2
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-20 08:05 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depe...
1,243
df39a97db25f03aca8ebd501283fd6a7c486db8c
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.utils import timezone from timesheets.models import TimeSheet from channels import Group class ProjectTS(models.Model): class Meta: ...
1,244
f80de2b069cf1dee2e665556262c6e84ce04b208
""" Compiled: 2020-09-18 10:38:52 """ #__src_file__ = "extensions/AppWorkspaceTools/etc/FAppWorkspaceDesignerNodes.py" """ Compiled: 2018-06-07 17:06:19 """ #__src_file__ = "extensions/AppWorkspaceTools/etc/FAppWorkspaceDesignerNodes.py" import acm import FUxCore import Contracts_AppConfig_Messages_AppWorkspace as Ap...
1,245
b6df9414f99294c7986d3eb5332d40288f059cd1
class default_locations: mc_2016_data_directory = "/afs/hephy.at/data/cms06/nanoTuples/" mc_2016_postProcessing_directory = "stops_2016_nano_v0p23/dilep/" data_2016_data_directory = "/afs/hephy.at/data/cms07/nanoTuples/" data_2016_postProcessing_directory = "stops_2016_nan...
1,246
122c4f3a2949ee675b7dd64b9f9828e80cbe5610
import cv2 import os import re class TestData: def __init__(self, image_path= '../../data/test_images/'): test_names = os.listdir(image_path) self.images = [] self.numbers = [] self.treshold = .25 for name in test_names: self.images.append(cv2.imread(...
1,247
23236cd8262eb414666db88215c01d973abf1d97
decoded = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"...
1,248
7aa6bba8483082354a94ed5c465e59a0fc97fe23
#https://codeforces.com/problemset/problem/1321/A n=int(input()) r=list(map(int,input().split())) b=list(map(int,input().split())) l=[0]*n x=0 y=0 for i in range(n): if r[i]-b[i]==1: x+=1 elif r[i]-b[i]==-1: y+=1 if x==0: print(-1) else: print(y//x+min(y%x+1,1))
1,249
4c9f2b6fd119daa58b7f1dd7153c90df747e62cb
# Moving Averages Code # Load the necessary packages and modules import pandas as pd import matplotlib.pyplot as plt import data.stock as st # Simple Moving Average def SMA(data, ndays): SMA = pd.Series(data['close'].rolling(ndays).mean(), name='SMA') # SMA = pd.Series(pd.rolling_mean(data['close'], ndays),...
1,250
db55a603615c7d896569ada84f3110dd6c0ce45f
import shell def executeUpgrade(): shell.executeCommand('pkg upgrade') def executeInstall(pkg_name): shell.executeCommand('pkg install ' + pkg_name) def executeRemove(pkg_name): shell.executeCommand('pkg remove ' + pkg_name) shell.executeCommand('pkg autoremove') def executeFindByName(name): ...
1,251
3078a0c7e2c711da88846ca3401c7924b1790dbc
#!/usr/bin/env python # # ConVirt - Copyright (c) 2008 Convirture Corp. # ====== # # ConVirt is a Virtualization management tool with a graphical user # interface that allows for performing the standard set of VM operations # (start, stop, pause, kill, shutdown, reboot, snapshot, etc...). It # also attempts to s...
1,252
64fd597918fe8133d53d1df741512cd2e49a111d
# -*- coding: utf8 -*- from django.db import models import custom_fields import datetime #import mptt # Create your models here. class Message(models.Model): user = models.ForeignKey('User') time = models.DateTimeField(auto_now=True,auto_now_add=True) text = models.TextField() #true если это ответ подд...
1,253
05aec07b94f3363e07d8740b102262d817e08e71
# coding: utf-8 """ Knetik Platform API Documentation latest This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com. OpenAPI spec version: latest Contact: support@knetik.com Generated by: https://github.com/swagger-api/swagger-codeg...
1,254
dbb007af79b2da2b5474281759c2bcce2a836fb5
from requests import get from bs4 import BeautifulSoup, SoupStrainer import httplib2 import re from win32printing import Printer def getLinks(url): links = [] document = BeautifulSoup(response, "html.parser") for element in document.findAll('a', href=re.compile(".pdf$")): links.append(element.get(...
1,255
12f0eeeb81fe611d88e33fd2e8df407e289fb582
# Error using ncdump - NetCDF4 Python ncdump -h filename
1,256
bbb3d27ce8f4c1943ecc7ab542346c9f41cbd30e
# Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """This module implements helpers for GN SDK e2e tests. """ # Note, this is run on bots, which only support python2.7. # Be sure to only use python2.7 feature...
1,257
ba483c7eaf2f2ced7f70a14b53c781f190585024
from AStar import astar def main(): grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0,...
1,258
b0fad3847519bb18365a8cd4226d06e9d96a8308
from django.contrib import admin from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('admin/', admin.site.urls), path(r'', views.index, name='index'), ]
1,259
68a776d7fccc8d8496a944baff51d2a862fc7d31
# flush in poker def IsContinuous(numbers): if not numbers or len(numbers) < 1 : return False numbers.sort() number_of_zero = 0 number_of_gap = 0 for i in range(len(numbers)): if numbers[i] == 0: number_of_zero += 1 small = number_of_zero big = small + 1 whi...
1,260
d73491d6673abdabad85176c5f75a191995c806d
from . import views from django.urls import path, re_path app_name = "blogs" urlpatterns = [ path('', views.index, name='index'), re_path(r'^blogs/(?P<blog_id>\d+)/$', views.blog, name='blog'), path('new_blog/', views.new_blog, name='new_blog'), re_path(r'^edit_blog/(?P<blog_id>\d+)/$', views.edit_blog, name='edit_bl...
1,261
618b6c74133e181ce5cbaf4e969d9fc3aa44ce98
# -*- mode: python; coding: utf-8 -*- # Copyright 2019-2021 the AAS WorldWide Telescope project # Licensed under the MIT License. from __future__ import absolute_import, division, print_function import numpy as np import numpy.testing as nt import os.path import pytest import sys from xml.etree import ElementTree as ...
1,262
f5f9a1c7dcb7345e24f50db54649a1970fc37185
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon # are the lat/lon values of the lower left and upper right corners # of the map. # resolution = 'c' means use crude resolution coastlines. m = Basemap(projection='cea',llcrnrlat=-90,urcr...
1,263
76dd4d2b5f68683c77f9502a2298e65c97db7c8d
class ConfigError(ValueError): pass
1,264
f16d43d9dfb3e9b9589fa92eb82aaa4c73fe48cd
from django.contrib.auth.decorators import login_required from django.shortcuts import render from orders.models import Setting def search(request): return render(request, 'ui/search.html') def search_printed(request): print_url = '' setting = Setting.objects.filter(name='printer').first() if setting ...
1,265
dc81ab808720c3a2c76174264c9be9bcdd99c292
A = [] ans = 0 def merge(left, mid, right): global A global ans n1 = mid - left n2 = right - mid l = [] r = [] for i in range(n1): l += [A[left + i]] for i in range(n2): r += [A[mid + i]] l += [10**18] r += [10**18] i = 0 j = 0 ans += right - left for k in range(left, right): if l[i] <= r[j]: A[...
1,266
a6192e39d86005882d0bde040a99f364bf701c3b
# -*- coding: utf-8 -*- def merge_sort(mlist): if len(mlist) <= 1: return mlist mid = int(len(mlist) / 2) # 使用递归将数组二分分解 left = merge_sort(mlist[:mid]) right = merge_sort(mlist[mid:]) return merge(left, right) # 将每次分解出来的数组各自排序,合并成一个大数组 def merge(left, right): """ ...
1,267
7cbf2082d530c315fdcfdb94f5c6ac4755ea2081
#!/usr/bin/python3 """ program of the command interpreter """ import cmd import models import re from models.base_model import BaseModel from models import storage from models.user import User from models.state import State from models.city import City from models.amenity import Amenity from models.place import Place ...
1,268
4db8b4403dd9064b7d5f935d4b9d111508c965fb
from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.db.models import Q from cvmo import settings from cvmo.context.models import ContextDefinition, Machines, ClusterDefinition, MarketplaceContextEntry from cvmo.context.plugins im...
1,269
816c11717c4f26b9013f7a83e1dfb2c0578cbcf8
from yama.record import Record class MongoStorage(object): _collection = None _connection = None _root_id = None _roots = None def __init__(self, connection): self._connection = connection self._collection = connection.objects self._roots = connection.roots root_...
1,270
ca5057a5fdfef0edf4cf0c3ff3e2a371907ca4ee
import tkinter as tk import tkinter.ttk as ttk import GUIForm import sys def main(): global window global _form print("You are using Python {}.{}.{}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)) window=tk.Tk() GUIForm.BuildInterface(window) window.mainloop()...
1,271
11a7ebac3dad1f91a6d46b62f557b51ded8e3d7a
#!/usr/bin/env python # -*- coding: utf-8 -*- # ユークリッド距離 # http://en.wikipedia.org/wiki/Euclidean_space # 多次元空間中での 2 点間の距離を探索する def euclidean(p,q): sumSq=0.0 # 差の平方を加算 for i in range(len(p)): sumSq+=(p[i]-q[i])**2 # 平方根 return (sumSq**0.5) #print euclidean([3,4,5],[4,5,6])
1,272
ea8676a4c55bbe0ae2ff8abf924accfc0bd8f661
from lib.utility import start_time, end_time from lib.prime import read_primes from bisect import bisect_left start_time() primes = read_primes(100) # limit = 10 ** 16 import random # limit = random.randint(1000, 10 ** 5) limit = 43268 # limit = 10 ** 16 print('limit=', limit) v1 = set() v2 = set() def version_100_i...
1,273
fa081ccd8081f5c3319f482b7d8abd7415d8e757
''' Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val...
1,274
af442d4a78930a0ebcd85a1cdfe4aa86461be5c1
import re from django import forms from django.contrib.auth import password_validation from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.password_validation import validate_password from .models import Account class EditProfileModelForm(forms.ModelForm): class Meta: model...
1,275
07a546928df1acfedf7a7735dc813de9da8373e0
##This script looks at a path for a dated file, then parses it by row into two different files/folders based on fields being blank within each row. import os.path from datetime import date ##sets date variables/format today = date.today() todayFormatted = today.strftime("%m%d%Y") print(todayFormatted) ##Se...
1,276
bd00644b9cf019fe8c86d52494389b7f0f03d3c3
# !usr/bin/env python # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2018-08-16 11:43:42 # @Last modified by: Brian Cherinka # @Last Modified time: 2018-08-16 11:58:06 from __future__ import print_function, division, absolute_import import pytest import os f...
1,277
34dd6966a971e3d32e82a17cd08c3b66bb88163b
def login(): usernameInput = input("Username : ") passwordInput = input("Password : ") if usernameInput == "admin" and passwordInput == "1234": return (showMenu()) else: print("User or Password Wrong.") return login() def showMenu(): print("---Please Choose Menu---") prin...
1,278
5461d50d3c06bc4276044cc77bd804f6e7c16b3b
#!/usr/bin/python3 ''' FileStorage module ''' import json from models.base_model import BaseModel import models from models.user import User from models.place import Place from models.state import State from models.city import City from models.amenity import Amenity from models.review import Review class FileStorage:...
1,279
8b671404228642f7ef96844c33ac3cee402bdb19
import os, subprocess, time from os.path import isfile, join import shutil # to move files from af folder to another import math def GetListFile(PathFile, FileExtension): return [os.path.splitext(f)[0] for f in os.listdir(PathFile) if isfile(join(PathFile, f)) and os.path.splitext(f)[1] == '.' + FileExtension] d...
1,280
33aa5c5ab75a26705875b55baf61f7f996cb69cd
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='VitaminSHE-home'), path('signup/', views.signup, name='VitaminSHE-signup'), path('login/', views.login, name='VitaminSHE-login'), path('healthcheck/', views.healthcheck, name='VitaminSHE-healthcheck'), path('...
1,281
6b616f5ee0a301b76ad3f7284b47f225a694d33c
from plprofiler_tool import main from plprofiler import plprofiler
1,282
26ae44b5be1d78ed3fe9c858413ae47e163c5460
from typing import List """ 1. Generate an array containing the products of all elements to the left of current element 2. Similarly, start from the last element and generate an array containing the products to the right of each element 3. Multiply both arrays element-wise """ class Solution: def productExceptS...
1,283
284955a555ce1a727ba5041008cd0bac3c3bed49
from django.db import models # Create your models here. class Covid(models.Model): states= models.CharField(max_length=100, null=True, blank=True) affected = models.IntegerField(null=True) cured = models.IntegerField(null=True) death = models.IntegerField(null=True)
1,284
3aff6bdfd7c2ffd57af7bb5d0079a8a428e02331
import tensorflow as tf import numpy as np from datetime import datetime import os from CNN import CNN from LSTM import LSTM from BiLSTM import BiLSTM from SLAN import Attention from HAN2 import HierarchicalAttention import sklearn.metrics as metrics import DataProcessor as dp import matplotlib.pyplot as plt import num...
1,285
6b2f10449909d978ee294a502a376c8091af06e0
import tkinter as tk from pickplace import PickPlace import sys import math from tkinter import messagebox import os DEBUG = False class GerberCanvas: file_gto = False file_gtp = False units = 0 units_string = ('i', 'm') """ my canvas """ def __init__(self, frame): self.x_fo...
1,286
d56aa0f0b7c420e4021736cf8f80923121856d1c
import json import requests import time class TRY(): rates = list() def __init__(self, r): # if(TRY.rates[-1] != r): TRY.rates.append(r) def ls(self): # print("TRY: "+TRY.rates[e] for e in range(1, len(TRY.rates))) print(f"TRY: {TRY.rates}") class USD(): rates = lis...
1,287
f3789d70f784345881f705fc809c49ad4e3526bc
# -*- coding: utf-8 -*- """ ====================== @author : Zhang Xu @time : 2021/9/8:16:29 @email : zxreaper@foxmail.com @content : tensorflow subclassing 复现 NPA ====================== """ import tensorflow as tf from tensorflow.keras import * from tensorflow.keras.layers import * from keras import ...
1,288
4a17db6b65e1615b0d519581b3e63bc34ad16093
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 15 15:36:38 2021 @author: mav24 """ import pandas as pd import numpy as np from sklearn.preprocessing import QuantileTransformer, StandardScaler, PowerTransformer, MaxAbsScaler from sklearn.cross_decomposition import PLSRegression from sklearn.en...
1,289
563e534e4794aa872dcdc5319b9a1943d19f940f
import random import time class Cells: UNDEFINED = 0 DEAD = 1 ALIVE = 2 def __init__(self, nx, ny, density = 5): self.nx = nx self.ny = ny self._cells = [[Cells.UNDEFINED for y in range(ny)] for x in range(nx)] self._nextCells = [[Cells.UNDEFINED for y in range(ny)] for...
1,290
85dfb30a380dc73f5a465c8f4be84decccfbcb59
/Users/sterlingbutters/anaconda3/lib/python3.6/encodings/cp037.py
1,291
6192099bdecffd9ce3576f4034567478145115a0
import queue import copy import heapq import sys sys.setrecursionlimit(100000) dx =[1,0,0,-1] dy=[0,1,-1,0] class PriorityQueue: pq=[] elements={} task=0 def insert(self , priority,x_val,y_val): entry = [priority, self.task,x_val,y_val] self.elements[self.task]=entry heapq.hea...
1,292
94d296b5a13bfa59dba5812da31707f9db9080af
""" Implements a Neural Network """ from vectorflux import VectorFlux from mnist import read, show, normalize from vectorflux.layers import Dense from vectorflux.layers.Dropout import Dropout train = list(read('train')) test = list(read('test')) print("Train size: {}".format(len(train))) print("Test size: {}".forma...
1,293
0e337ce21450e0fdb7688183d0542ebf902a9614
import messages import os import requests from bs4 import BeautifulSoup URL = "https://mailman.kcl.ac.uk/mailman/" ADMIN = "admin/" ROSTER = "roster/" OUTPUT_FOLDER = "../output/" def makeoutput(path): if os.path.exists(path): pass else: os.mkdir(path) def mailinglist_cookies(mailinglist, password): # this o...
1,294
e6320bc1c344c87818a4063616db0c63b7b8be49
from tkinter import * global math root = Tk() root.title("Calculator") e = Entry(root,width=60,borderwidth=5) e.grid(columnspan=3) def button_click(number): #e.delete(0, END) current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_clear(): e.delete(0, END) ...
1,295
13fa650557a4a8827c9fb2e514bed178df19a32c
""" Image Check / Compress Image""" import re import os from PIL import Image from common.constant import PATH def check_image(file_type): match = re.match("image/*", file_type) return match def compress_image(data): with open(PATH.format(data['name']), 'wb+') as file: file.write(data['binary'...
1,296
927b42326ad62f5e484fd7016c42a44b93609f83
#!/usr/bin/python # coding: utf-8 from os.path import dirname, abspath PICKITEMSP = True RAREP = True REPAIRP = False ITEMS = { "legendary": ["#02CE01", # set "#BF642F"], # legndary "rare": ["#BBBB00"] } current_abpath = abspath(dirname(__file__)) + "/" # Wi...
1,297
65aa761110877bd93c2d2cb3d097fa3e126f72b1
from application.processing_data.twitter import TwitterAPIv2 from azure.ai.textanalytics import TextAnalyticsClient from azure.core.credentials import AzureKeyCredential from .twitter import TwitterAPIv2 categories={ 'Noise Complaints': { 'loud', 'party', 'noisy', 'noise', '...
1,298
0ee902d59d3d01b6ec8bb4cc8d5e8aa583644397
from __future__ import print_function import ot import torch import numpy as np from sklearn.neighbors import KernelDensity from torch.utils.data import Dataset import jacinle.io as io import optimal_transport_modules.pytorch_utils as PTU import optimal_transport_modules.generate_data as g_data from optimal_transport_m...
1,299
de0d0588106ab651a8d6141a44cd9e286b0ad3a5
""" 采集端任务状态统计 直接在数据库查找数据 create by judy 2018/10/22 update by judy 2019/03/05 更改统一输出为output """ from datetime import datetime import time import traceback import pytz from datacontract import ETaskStatus from datacontract.clientstatus.statustask import StatusTask from idownclient.clientdbmanager import DbManager from...