index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
12,800
c09448ff9548db2752d574887efc08514d4c69ce
import cloudpassage import sys import os import yaml import datetime sys.path.append(os.path.join(os.path.dirname(__file__), '../../', 'lib')) from event import Event config_file_name = "portal.yml" tests_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")) config_file = os.path.join(tests_dir, "co...
12,801
436278f16f3fcd08993f4995842dcf546473af50
import pandas as pd import numpy as np import tensorflow as tf from typing import List import twins # TODO - remove dep on the service in this repo; create a package that gets # imported into both things (parent). But for sake of time just use the # svc client here import svc def _join(x) -> str: cols = ["inte...
12,802
44ecdd1e564fd398959adb2529f307d1183507a2
#!/usr/bin/env python # -*- coding: utf-8 -*- from bili import cols from bili.bili_video_name import * if __name__ == "__main__": for _col in cols[1: -1]: init_ignore_id() video_aids = get_video_aid(_col) _names = get_video_name(video_aids) update_db_video_name(_names) print(_col, "DONE!!!") # conn.close(...
12,803
38897d9694a15e0a6f5d64c021eea56982120910
# -*- encoding: utf-8 -*- from django import template from reqApp.models import * from reqApp.choices import * from reqApp.util import * from random import randrange register = template.Library() @register.filter(name="proyecto") def proyecto(request): return getProject(request) @register.filter(name="invertOrd"...
12,804
374aa1504c4270171ebf7014449aab9e85e10716
import ast from collections import OrderedDict from PythonVoiceCodingPlugin.library import sorted_by_source_region,get_source_region,make_flat from PythonVoiceCodingPlugin.library.info import * from PythonVoiceCodingPlugin.library.traverse import search_upwards,search_upwards_log, find_matching,match_node, find_all_no...
12,805
aac2bf245619832434bc896b0e73e40378a322ac
from __future__ import absolute_import from __future__ import division from __future__ import print_function from setuptools import setup, find_packages import setuptools.command.install as _install import subprocess class install(_install.install): def run(self): subprocess.check_call(["make"]) ...
12,806
2c4a5307efa9d3887183a67f06cf4fc2a262bbe5
from urllib.request import urlopen html=urlopen("http://www.pythonscraping.com/pages/page1.html") print (html.read())
12,807
efae03c673cdfd3529f4182946f7b33635e665b1
__all__ = ["csv_col_save"] import csv def csv_col_save(fileName, cols, colHeader): __save_to_csv_col(cols, fileName, colHeader) def __save_to_csv_row(rows, fileName): """ :param rows: list of Dictionaries where each item is a dictionary mapping the fidld name to the value. :param fil...
12,808
45e0f562b49fdcbf14b79a3bfacf65841195d7df
import csv #input number you want to search cardName = input('Enter part of name to find\n') #read csv, and split on "," the line csv_file = csv.reader(open('MunchkinTreasureCards.csv', "r"), delimiter=",") #loop through the csv list for row in csv_file: if len(row) > 1: #checking for empty rows #if input is...
12,809
dced9cf7d4feef7ead9fba935c0a888a3d40aca9
from flow.core.params import VehicleParams,InFlows,SumoCarFollowingParams,SumoParams, EnvParams, InitialConfig, NetParams, SumoLaneChangeParams from flow.controllers import IDMController, RLController from controller import SpecificMergeRouter,NearestMergeRouter # from flow.core.params import from network import Highw...
12,810
a227de636abf8cf28525011ecaae489d895353b9
# -*- coding: utf-8 -*- """ Utility functions (:mod:`refmanage.fs_utils`) ============================================= .. currentmodule:: fs_utils """ import os import glob import pathlib2 as pathlib from pybtex.database.input import bibtex from pybtex.exceptions import PybtexError from pybtex.scanner import TokenRe...
12,811
1981ad50b63b60e005211e35baf9512ab89e95bc
# from jsonschema import Draft4Validator from jsonschema import validate, RefResolver import json import os with open('schema/config-schema.json') as f: schema = json.load(f) # Bugfix in jsonschema # https://github.com/Julian/jsonschema/issues/313 schema_dir = os.path.dirname(os.path.abspath('schema/config-schema...
12,812
5a9b0726d37a76f73f4478a6c81d8416b460b9ce
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from functools import reduce from datetime import datetime as dt class CasesCategory(scrapy.Item): positive = scrapy.Field(serialier = int) pres...
12,813
41ff88dbeff121c8834d8863359e071927ac0d5c
from yolo import YOLO from PIL import Image import cv2 yolo = YOLO() cap = cv2.VideoCapture("nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720,format=(string)I420, framerate=(fraction)30/1 ! nvvidconv flip-method=0 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)B...
12,814
07ac997bdb549666376009055e4c8f72fb81f00d
import json import os import zipfile from unittest import mock import pytest from cloudify_system_workflows.snapshots.snapshot_create import EMPTY_B64_ZIP from cloudify_system_workflows.tests.snapshots.utils import ( AuditLogResponse, load_snapshot_to_dict, prepare_snapshot_create_with_mocks, FAKE_EXE...
12,815
8229a54455948ae88bdfdc854b5a062551077410
# -*- coding: utf-8 -*- # Copyright 2015 Yelp and Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
12,816
6c0bcb5bebb0e7167591a48683f55befad4f8bdf
#!/usr/bin/python # -*- coding: utf-8 -*- # Print all solutions encoded in one file clingo output (with one answerset per line) import sys filename = sys.argv[1] gridsize = int(sys.argv[2]) #print("This is the name of the script: ", sys.argv[0]) #print("Number of arguments: ", len(sys.argv)) #print("The arguments ar...
12,817
ce907d89ce436c9ded3d18e38cc8f215a8e4fcca
# -*- coding: utf-8 -*- from scrapy import Spider, Request from Amazonspider.items import AmazonspiderItem import re class AmazonmacSpider(Spider): name = 'AmazonMacSpider' allowed_domains = ['www.amazon.com'] start_urls = ['https://www.amazon.com/s/ref=sr_pg_1?fst=p90x%3A1&rh=n%3A172282%2Ck%3Amacbook&key...
12,818
ebeeafb91d72d8b3c4ecb2120c6bbc860060a189
nota1 = float(input('digite uma nota: ')) nota2 = float(input('digite outra nota: ')) print('a media das notas desse aluno será: \033[34m{:.1f}\033[m'.format((nota1+nota2)/2))
12,819
fa715c6a2f91a5778127ba41ef2e5eb835be58bb
from __future__ import annotations import json import operator as op import typing import warnings from collections import defaultdict from dataclasses import dataclass from datetime import datetime from functools import cached_property from typing import ( TYPE_CHECKING, Any, Callable, Collection, ...
12,820
ad9deb761e8f37a1865aa8170373be7de8efe490
#!/usr/bin/python3 from http.server import BaseHTTPRequestHandler as BaseHandler,HTTPServer import threading import time import json from .MInfo import * class MServer: def __init__(self, handle_chat, handle_dm): pass def chat(self): pass def dm(self): pass class TestMServer(MServer): def __...
12,821
8c4f7b49f612d63f939fa96665a3c8ab18c9b38a
from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from .models import User, Address from django.contrib.auth import authenticate, login, logout from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.template.loa...
12,822
8853305ab7bbd9294d46f383dec781d742fb905f
import time import io import cv2 from threading import Thread, Lock from thread import start_new_thread camera = None current_photo = None current_photo_lock = Lock() def init(res,shutter_speed): global camera exposure_time = 1e9/shutter_speed camera = cv2.VideoCapture(0) camera.set(cv2.cv.CV_CAP_PR...
12,823
f827400ba12990e0a319480cdddf6014cdbe1312
from enum import Enum from typing import Any, Dict, Optional, overload from .conditions import RuleConditionKey from .user_restriction import DurationUnit, UserRestriction from .util._codegen import BaseParameters class RuleType(Enum): ... class RuleAction(BaseParameters): def __repr__(self): ... def ...
12,824
663da754865dc0a49ca4fa4dfc3869d094a6aaa7
# 2017 Qualification Round - A. Oversized Pancake Flipper # https://code.google.com/codejam/contest/3264486/dashboard#s=p0 def solve(pancakes, k): pancakes = list(map(lambda p: p == '+', pancakes)) res = 0 for i in range(len(pancakes)-k+1): # print(pancakes, i, pancakes[i]) if not panc...
12,825
e10cb90299dfe03ca46cb14330561400ea6f46b2
import importlib import sys __all__ = ( 'client' )
12,826
12d88b47e948efb6a4094f07bc58c35c6886f634
# Generated by Django 2.0.1 on 2018-01-16 00:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talks', '0024_auto_20180114_0111'), ] operations = [ ]
12,827
a4b2cf93d4d83e32f837f2e7e60eda731aa74af0
#!/usr/bin/python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
12,828
5306ba5840d1e3965481932185e099939ffdc17c
import numpy as np import DataProcessingTools as DPT from .rpllfp import RPLLFP from .rplhighpass import RPLHighPass from .rplraw import RPLRaw from .helperfunctions import computeFFT import matplotlib.pyplot as plt import os from .misc import getChannelInArray class FreqSpectrum(DPT.DPObject): filename = "freqs...
12,829
370aafa4477562bdf91947a72f703c833360f1cd
# In your team's parameter file where you have values such as 1.96E-6. The E-6 refers to (10 ** -6) # So you will need to change the -6 to reflect a difference in your paramters # ---------------------------------------------------- # ENTER GROUP PARAMETERS HERE from pip._vendor.distlib.compat import raw_input Input...
12,830
e8bea8d2ea58fb54048d633c974c3c64c339803a
from point2D import Point2D class Point3D(Point2D): _z:int def __init__(self,x,y,z): super().__init__(x,y) self._z = z def __getZ__(self) -> int: return(self._z) def __setZ__(self,z): self._z=z
12,831
f9102d02ac438551c107216f873ca165c2886482
import django.forms from django.shortcuts import render from django.db import models from django.forms import HiddenInput from django.http import HttpResponseRedirect from django.urls import reverse from .models import Message, Agent, Quiz, Comment from .forms import AgentForm, MessageForm, QuizForm, CommentForm # Crea...
12,832
942fef326fed51cdc7635076c45f07af02b8b7f2
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import re import nltk from sklearn.datasets import load_files # nltk.download('stopwords') import pickle from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.feature_extraction.text import CountVectorizer ...
12,833
ac3f9f6cd21790993da3193abad9cd8d67644392
def re2sqrt(s): j = s.find("^(1/2)") while j != -1: j -= 1 while '0'<=s[j]<='9': j=j-1 if (j+1) < 0: s = 'sqrt('+s else: s = s[:j+1]+'sqrt('+s[j+1:] s = s.replace("^(1/2)",")",1) j = s.find("^(1/2)") return s
12,834
09529f2290d3434bea5e41beac7d74d42a5b41c4
#coding:UTF8 #字典排序 #统计目录下占用空间最大的前10个文件 import os import sys import operator def get_dic(topdir): dic = {} a = os.walk(topdir) for p,d,f in a : for i in f: fn = os.path.join(p,i) f_size = os.path.getsize(fn) dic[fn]=f_size return dic if __name__ =='__main_...
12,835
7957fbe702b87873d0bb00dc4637f1c881f3c081
""" 146. LRU Cache Medium Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void pu...
12,836
8a2cdff66b39835b752ac1f32623bebb9893449e
# # Python GUI - Colors - Gtk # from gtk import gdk from GUI import export from GUI.GColors import Color as GColor class Color(GColor): _alpha = 1.0 def _from_gdk_color(cls, _gdk_color): c = cls.__new__(cls) c._gdk_color = _gdk_color return c _from_gdk_color = classmethod(_from_gdk_color) def __init_...
12,837
0a1c816109520270ad0c0f9588c5927c64f68ee8
#!/usr/bin/env python2 # # git-deps - automatically detect dependencies between git commits # Copyright (C) 2013 Adam Spiers <git@adamspiers.org> # # The software in this repository is free software: you can redistribute # it and/or modify it under the terms of the GNU General Public License # as published by the Free ...
12,838
48196432260c0e3c6ab9f578417de03671c20932
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from dipy.io.streamline import load_tractogram from dipy.align.streamlinear import set_number_of_points from dipy.viz import window, actor, colormap as cmap import numpy as np import time import os from models.tf_tools.transformer.transformer im...
12,839
2f8f4eb9c22fa400d89eed9fb3a700f3624d789f
from datetime import timedelta, datetime import pytest from tests.conftest import assert_equal_objects, obj_id from saana_lib.recommendation import MinimizeRecommendation, \ AvoidRecommendation, PrioritizeRecommendation, RecipeRecommendation patient_id = obj_id recipe_id = obj_id @pytest.fixture def tags_find_...
12,840
8774c7dc21ae8a9aa6f1ce413ececdd90b632c9a
import numpy as np import matplotlib.pyplot as plt t0=2.0 xprime=9.0*(np.exp(-t0))/(1.0+9.0*(np.exp(-t0)))/(1.0+9.0*(np.exp(-t0))) q1file=open('q1py.txt','w') def x(t): return 1.0/(1.0+9.0*(np.exp(-t))) def xprimeest(x0,x,deltat): return ((x-x0)/deltat) def derivdiff(prime,estprime): return np.abs...
12,841
6e49c2b0e7f2772f61c1dc17b9d6962b352f0694
from random import randint def start_game(): print('Welcome to the number guessing game!') attempts = 0 random_number = randint(1,10) while True: attempts += 1 try: guess = int(input("Guess a number 1-10 ")) except ValueError: print("Oops, thats not a ...
12,842
3e444e78871a0b200fbfec93ad3e3a7ece3ecffa
from geopy.distance import geodesic from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse from sklearn import metrics from applications.user.models import AdminInfo from applications.work.models import CarWorkDay, Route from applications.work.models import ...
12,843
f9f5c976ad01450d91ab7f9b959d7b4f9d10b76c
''' Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. a being 1, b being 2, etc. As an example: alphabet_position("The sunset sets at twelve o' clock.") Should return "20 8 5 19 ...
12,844
576b5618f1cde5101559a242e4643f947e34ab9d
dict = {'name': 'John', 'age': 49} str = '****'.join(dict) print(str)
12,845
03e888a7b2b6e31b85ec53ee77aa679ff0b2a79f
class Addition: @staticmethod def sum(augend,addend=None): if isinstance(augend,list): return Addition.sumList(augend) return augend + addend @staticmethod def sumList (valueList): result = 0 for element in valueList: result = Addition.sum(result...
12,846
34fe60eec9e6f6f9f08e09a7498cf3062eb9b855
# Generated by Django 2.2.4 on 2019-08-07 07:32 from django.db import migrations, models import main.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id'...
12,847
e8f7926e9a3e9c1a6413b049a601c393075c810f
import random def lottery(names): return random.choice(list(set(names)))
12,848
70c495c2bd975235fab0f993553776df1ea626a8
# I have created this file - Akanshu from django.http import HttpResponse from django.shortcuts import render from .methods import * def index(request): return render(request, 'index.html') def analyse(request): #getting the text djtext = request.POST.get("text", "default") #applied operation dj...
12,849
4352ee21338f1b09b20ec2f4a513225696ec1869
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 02:49:31 2020 @author: User """ #Candies and two sisters ''' import math t = int(input()) ans = [] for i in range(t): n = int(input()) if n%2 == 0: ans.append(int(n/2-1)) else: mid = math.ceil(n/2) ans.append(n-mid) ...
12,850
2e7ca75adfcd5f8d017689aca34b70ae8bf4f3ac
#this script handles the operations to be performed on user accounts #for example adding user or deleting user class Userr(object): def __init__(self, username, email, f_name, l_name, password): self.username = username self.email = email self.f_name = f_name self.l_name = l_name ...
12,851
3ce5e4c703da51461914620cc1f2cb7f9fe69fe9
import sqlite3 from app.api.classes import Flashcard from flask import current_app import json def create_flashcard(title: str, description='', source='', image_url='', tags=[]): with sqlite3.connect(current_app.config['DB']) as db: c = db.cursor() c.execute( """ INSERT INTO...
12,852
284c0c7705406f30a4d245e5a41597b1ef9b53dd
# main_train.py import os import torch import argparse import numpy as np from torch import nn from sklearn.model_selection import train_test_split import utils as u import model as m from preprocess import Preprocess from data import TwitterDataset from train import training path_prefix = './data/' # 要不要固定embedding...
12,853
d4c22e7ff93cd8b5b2c19da34d16c4e7299c88dd
from django import forms from django.contrib.auth.models import User from django.forms.extras.widgets import SelectDateWidget class RegistrationForm(forms.Form): username = forms.CharField(max_length = 50, widget = forms.TextInput(attrs={'class':'form-control', ...
12,854
28021f8a73db4f3d33e21216396a2705e6c023f0
N,M=map(int,input().split()) even=0 odd=0 for i in range(0,N): even+=i for j in range(0,M): odd+=j print(odd+even)
12,855
d78bc7c085ad64c3628c03c0717dcbae323b68c9
from django.shortcuts import render from django.contrib.auth.decorators import login_required def index(request): context ={} return render(request, 'index.html', context) @login_required def test_admin(request): context = {} return render(request, 'test.html', context)
12,856
7b01dfd98b2bdf532a63860514ec57f1d8eb306d
# this function is what calculates the account that has the most similar rating # to the account logged in from file_manip import * import constants as c def get_similar(account_name): # declare variables filename = 0 sorted_distances = [] distance = 0 distances = [] variant = 0 i = 0 j = 0 # get songs from...
12,857
f95bba57463087af0ec777e0affa9031c52ac32b
from LExprVisitor import LExprVisitor from LExprParser import LExprParser class CalcVisitor(LExprVisitor): def visitAdd(self, ctx: LExprParser.AddContext): return self.visit(ctx.e(0)) + self.visit(ctx.e(1)) def visitMult(self, ctx: LExprParser.MultContext): return self.visit(ctx.e(0)) * self...
12,858
8a333a216fcc6c4c32cafd942586e9306fb4ea25
# calculating gcd of two numbers in python def gcd(a,b): if(b==0): return a else: return gcd(b, a%b) a,b=map(int,input().split()) print(gcd(a,b))
12,859
bf58db0be13530e9c42c3a6ac4f80939365b356b
import os import groot import numpy as np import PIL import torch import torchvision class GroceryDataset(torch.utils.data.Dataset): def __init__( self, root, split="train", string_labels=True, transforms=None, adjust_freq=True, eps=1e-5, use_all_la...
12,860
a13b60dbb71aad02cb565ca86f9cca2406395502
from distutils.core import setup import py2exe # Dependencies are automatically detected, but it might need fine tuning. #buildOptions = {"packages": [], "excludes": [""]} # GUI applications require a different base on Windows (the default is for a # console application). # #expectstub = Target( # ...
12,861
725f87903c3319614fbe9e54e49129b78cd194f7
import torch import torch.utils.data from .. import utils import numpy as np import math from typing import Dict, Any, List, Optional class InfiniteSampler(torch.utils.data.Sampler): def __init__(self, data_source: torch.utils.data.Dataset, replacement=True, seed=None): super().__init__(data_source) ...
12,862
2dd84cc7c225967a15a898297939e879521d5b79
"""from difference_of_squares import difference, square_of_sum, sum_of_squares """ def difference(i): """ calculate the difference """ return square_of_sum(i) - sum_of_squares(i) def sum_of_squares(i): """ sum of squares """ return sum([j**2 for j in range(1, i+1)]) def square_of_sum(i): """ ...
12,863
435eb0706395e7aa736f6480f71cccebc7bb6bed
import sys, os, time os.environ['TF_CPP_MIN_LOG_LEVEL']='2' sys.path.insert(1, os.path.join(sys.path[0], '..')) import tensorflow as tf # Import model builder from model import build_neurosat # Import tools from cnf import ensure_datasets import instance_loader import itertools from util import timestamp, memory_usage ...
12,864
a6e329e74c5b0145d753d3ca3ff8c2a600fdf1d3
from django.conf.urls import url from . import views app_name = 'annotations' urlpatterns = [ url(r'^export/(\d+)/create/$', views.create_exportformat, name='create_exportformat'), url(r'^export/(\d+)/auth/$', views.export_auth, name='export_auth'), url(r'^export/(\d+)/download/$', views.download_export, ...
12,865
e5c85ac93e1c87fe37cc08346fd0d79095560b16
import sqlite3 import logging import time __version__ = "0.1.0" initial_sql = """CREATE TABLE IF NOT EXISTS log( Id INTEGER PRIMARY KEY AUTOINCREMENT, TimeStamp TEXT, Source TEXT, LogLevel INT, LogLevelName TEXT, ...
12,866
a09025429e0d60a6ea00153469cb498e913feb29
# from flask import render_template # from myapp import application, db # # # @application.errorhandler(404) # def not_found_error(error): # return render_template('errors/404.html'), 404 # # # @application.errorhandler(500) # def internal_error(error): # db.session.rollback() # return render_template('erro...
12,867
e04116e697f9aaaef9d2d101f0492d67f02347c4
import parsing parsing.parser.add_option("--timed-repeat", metavar="SECONDS", type="float", help="Repeat each test, for a limited time") def process_options(options): if options.timed_repeat is not None: from testoob.running import fixture_decorators parsing.kwargs["fixture_decorators"].append( ...
12,868
1e7ced31fcb03df750e30ddb7aa03f135f2075b7
from django.conf.urls import patterns, include, url from rest_framework import routers from api import views from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'evemonline.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url('^ap...
12,869
21510265a27134984ca4dd70be2cc51b15bf4264
import numpy as np from basemodel import BaseModel from sklearn import svm, cross_validation from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.neighbors impo...
12,870
a95dd29ec685fc5b7146c38593e46fb9b4a4dd17
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ @Author: Fabian Fey """ import os from logzero import logger COLORPATH = '/etc/regolith/styles/costum-theme/color' def ChangeColors(colorsList): colors = [ "#define color_base03 " + colorsList[0], "#define color_base02 " + colorsList[1], ...
12,871
9de009b51146daed062c267950754576eb557833
import torch import torch.autograd as autograd import torch.optim as optim import numpy as np import matplotlib as mpl from datetime import datetime mpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os from torch.autograd import Variable import torch.nn as nn import torch.n...
12,872
247e7ec49f8cda539d2189ca06573638098b3f4f
from LAFitness import LAFitness from Member import Member from datetime import datetime if __name__ == "__main__": # load from config file... # parameters monthlyFee = 25 initFee = 25 # main laFitness = LAFitness(monthlyFee, initFee) LDai= Member("Dai Lian", datetime(2016,12,15)) ...
12,873
a1b37349c0daa801a705e632a97e5fb1f12dce4e
# Cats with hats theCats = {} loops = 0 #create 100 hatless cats in theCats dictionary for i in range(1, 1001): theCats["Cat " + str(i)] = False for i in range(1, 1001): loops += 1 count = 0 for cat, hats in theCats.items(): count += 1 if count % loops == 0: if theCats[cat]...
12,874
a9538fa94cd31f9c574dcc7e79ba7138bd806014
def dodawanie(a, b): return(a+b) def get_info(): print("Program kalkulator. Autor: Kasia") get_info() try: l1 = int(input()) l2 = int(input()) print(dodawanie(l1, l2)) except: print("Program zakończył się nieoczekiwanym błędem") print("Możesz go zgłosic pod adresem autor.pl")
12,875
9bad1a06a5cc083d12cd42d9b67d35a279e7e5e5
# -*- encoding=utf8 -*- __author__ = "xsl" import pytest from tools.tool import * from tools.config import * from airtest.core.api import * from poco.drivers.android.uiautomation import AndroidUiautomationPoco poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False) auto_setup(__file__, l...
12,876
3fd0383b6aef00ca2c300da292c545dc3b1d64c1
import matplotlib.pyplot as plt import numpy as np import h5py import caesar import os import sys from plotting_methods import * plt.rc('text', usetex=True) plt.rc('font', family='serif', size=18) palette_name = 'tol' min_mass = 9. max_mass = 12. dm = 0.25 # dex snap = '151' model = sys.argv[1] wind = sys.argv[2] if...
12,877
03b411831dd18ff1939b7a7470514edf2f43ec66
def get1(nums): m=len(nums) for i in range(m): if i not in nums: return i l1=[3,0,1] print(get1(l1))
12,878
0991db10ec09ff1006dd959adb3911c943d913f7
""" Gif.py David Merrell 2018-06-28 This module defines the Gif class. Gif objects correspond to whole GIF files; i.e., for each GIF you want to make, a Gif object must be constructed and acted upon. """ import matplotlib.pyplot as plt import subprocess as sp import math import os class Gif: """ Each instan...
12,879
60d404dc38ecef65f8df6994ba9c27866463de92
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod, abstractproperty class AbstractClient(object): __metaclass__ = ABCMeta @abstractmethod def findOrgStructureByAddress(self): pass @abstractmethod def getScheduleInfo(self): pass @abstractmethod def getPatien...
12,880
cbc14dc91b7b4cb71110d0c9a65fa645cd874113
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re import csv from bs4 import BeautifulSoup if len(sys.argv) <= 1: sys.exit() cols = ["id_row","return","name","city","prov","postalcode"] cw = csv.DictWriter(sys.stdout, cols) f = open(sys.argv[1], "r") intext = f.read() intext = re.sub(r"&nbsp;", ...
12,881
a7aaee3dd664cbdb877d1b9b3e4a74891c1f9ba4
from app import db from sqlalchemy.orm import relationship from sqlalchemy_utils.types import PasswordType from sqlalchemy_searchable import Searchable, SearchQueryMixin from sqlalchemy_utils.types import TSVectorType from flask.ext.sqlalchemy import SQLAlchemy, BaseQuery from wtforms_alchemy import ModelForm ROLE_US...
12,882
be42717a8bd736378c5ac3921ce701fdc92ff683
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[deeplens_inference_lambda.py demonstrates how to create an inference Lambda function on an AWS DeepLens model.] # snippet-service:[deeplens] # snippet-keyword:[AWS DeepLens] # snippet-keyword:[Python] #...
12,883
6be0fee7e208872b03b152bb1953bf1dde74ce88
import sys,os import data_processing as dp import ecc_tools as tools import timeit # import pydca-ER module import matplotlib #matplotlib.use('agg') import matplotlib.pyplot as plt from pydca.erdca import erdca from pydca.sequence_backmapper import sequence_backmapper from pydca.msa_trimmer import msa_trimmer from pyd...
12,884
30ff09278265f131b92ef8d937bf8034942c657b
#! /usr/bin/env python3 import io import sys import json from itertools import tee, chain, groupby from difflib import ndiff from pprint import pprint from colorama import Fore, Style def windows(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b, c = tee([None]+list(iterable)+[None, None], 3) next(...
12,885
7cdbf060bcfb6306b1d4b1661180177deba22f9f
d = [1, 2, 3, 4, 5] # list of int declaration list_iterator_obj = iter(d) print(list_iterator_obj.__next__()) print(list_iterator_obj.__next__()) print(list_iterator_obj.__next__()) print(list_iterator_obj.__next__()) print(list_iterator_obj.__next__()) print(list_iterator_obj.__next__())
12,886
27d14d2518e1fced23952ca7e8224b48816d9657
# # classifiers.py # define classifiers as basis for Neighborhood Graph Analysis # # Copyright (c) 2018 Wesley Reinhart. # This file is part of the crayon project, released under the Modified BSD License. from __future__ import print_function import _crayon import numpy as np class Classifier: R""" abstract cla...
12,887
4c1a751d59046189ee999b2d7b6d20dcd28b12c3
from evdev import InputDevice from select import select dev = InputDevice('/dev/input/event0') # This can be any other event number. On my Raspi it turned out to be event0 while True: r,w,x = select([dev], [], []) for event in dev.read(): # The event.code for a scroll wheel event is 8, so I do the...
12,888
2a53702620c887bbeaa459346af6fcd42dbd48ac
# Create your views here. from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from feed.models import JsonFeeds from rest_api.serializer import FeedSerializer from datetime import datetime from rest_framework import permissions @api_view(['...
12,889
d0d18f5395040fba9f1294814dd8a67936d4a455
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import InputRequired, Length, Email class LoginForm(FlaskForm): name = StringField('name', validators=[InputRequired(message='Please enter a name'),Length(min=5)]) password = PasswordField('pass', validators...
12,890
74a2101351c155f40b6a0018a45d63df7ec32987
# -*- coding: utf-8 -*- # Conventions are according to NumPy Docstring. """ n! means n * (n − 1) * ... * 3 * 2 * 1 For example, 10! = 10 * 9 * ... * 3 * 2 * 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ import time impor...
12,891
adaefd6068a1d558f79d0badc920d14fed4b745b
from selenium import webdriver from selenium.webdriver.common.by import By # 选择器 from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import time browser = webdriver.Chrome() wait_obj = WebDriverWait(browser, timeout=5) # 产生一个等待对象,固定最大等待时间 try: ...
12,892
90f96a17a8c1b8dca11176d33468c8d6425aa361
__author__ = 'student' import cv2 import numpy as np from detector_node import getHistParams import pickle def draw_mask(event,x,y,flags,param): global frame,drawing,img,mask samplesize = 100 if (event == cv2.EVENT_LBUTTONDOWN): img = np.copy(frame) w,h,c=img.shape mask = np.zeros((...
12,893
c087f63b6e922734f80d0ab1345e610dd810539e
import sqlite3 conn=sqlite3.connect('shopDb.db', timeout=10); chooseDb=conn.cursor(); if(conn): print('Baglanti Başarılı!') else: print('Bağlantı Başarısız!') def registerPage(): print('--REGISTER PAGE---\n'); print('Name: '); userName=input(); print('Surname: '); userSurname=input(); ...
12,894
c6a456476b8c18af989eba0b72acc8e014bd4dec
class PID: error = 0 cumErr = 0 derErr = 0 def __init__(self, Kp, Ki, Kd): self.Kp = Kp self.Ki = Ki self.Kd = Kd def control(self,desired,mesured,controlTarget): olderr = self.error self.error = desired - mesured self.derErr = self.error - olde...
12,895
86e522dbe54bdd414f9537062925c6a1906c15e6
import sys import os from dotenv import load_dotenv from pathlib import Path basedir = os.path.dirname(os.path.abspath(__file__)) env_path = Path(os.path.join(basedir, ".")) / '../.env' load_dotenv(dotenv_path=env_path) prevdir = basedir[:basedir.rfind('/')] sys.path.append(basedir) sys.path.append(prevdir) def is_l...
12,896
718f88433e67abfa8379fbc539ee7199d81dbb67
#! /usr/bin/env python3 -b # extract markdown documentation from cpp # complete hack class Item: def __init__(self): self.name = '' self.decl = '' self.comment = '' self.type = '' self.children = [] def make_doc(cpp, first_only=False): # comment blocks items = [] ...
12,897
eb1c147a0e08e674936080bc59b8ed0569804b1e
import cv2 # after installing opencv # now time for loading image # if u want to connect camera -- cap=cv2.VideoCapture(0) # define camera # start / on while True: status_camera,img=cap.read() # start camera to take picture print(type(img)) cv2.rectangle(img,(0,200),(100,400),(255,0,...
12,898
68261306975633e2528cfd37e7a206929c84a099
#!/usr/bin/env python # coding=utf-8 familiar_person = {'first_name':'Kobe','last_name':'Bryant','age':31,'city':'Los Angeles'} print(familiar_person['first_name']) print(familiar_person['last_name']) print(familiar_person['age']) print(familiar_person['city'])
12,899
c263c95f105601ea9bcf0c554b08ade02dcc4b4f
import re def parse_ranges(string): """takes a string ,eg: '1-5, 20, 30->exit'""" p = re.compile(r'(?P<start>\d+)-?(?P<end>\d+)?') match = re.finditer(p, string) ls = list() for m in match: begin = int(m.group('start')) end = int(m.group('end'))+1 if m.group('end') is not None els...