text
stringlengths
8
6.05M
# -*- coding: utf-8 -*- import os from extractor import * extractor = CLAbstractExtractor() parent_folder = "../articles" output_folder = "../output" with open(output_folder + "/" + "log.txt", "w") as log: for (_, _, filenames) in os.walk(parent_folder): for filename in filenames: try: ...
from tkinter import * import tkinter.messagebox from random import randint from users import * from Vehicles import * from rental_info import * import tkinter from tkcalendar import * import pymongo from pymongo import MongoClient cluster = MongoClient("mongodb+srv://amogh:amogh@shivi-usyoc.mongodb.n...
# -*- coding: utf-8 -*-""" """ This module encapsulates the logic of the model view controller. Classes Provided: GroupPoints(list) a list of ('Coord', ['x', 'y']). ClusterPoints(GroupPoints) extends GroupPoints with 'medoid(self)' and 'overlaps(self, other)' methods. """ # Python Standard Libarary from ...
# Mountaineer from Globals import * from Utilities import * def setup(): fullScreen() # Keeps images from going blurry noSmooth() # Where I store everything accessed by draw() global globals globals = Globals(width, height) # Part of the init for the player globals.player...
# -*- coding: utf-8 -*- import serial from django.shortcuts import render from django.http import HttpResponse, HttpRequest from django.contrib.auth import login, logout from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.contrib import messages from django.template import ...
import unittest from tree_data import FileSystemTree from tree_data_helper_test import print_directory DIR_PATH = "Testing\\" WIDTH = 1000 HEIGHT = 600 class Test_File_System_Get_Leaf(unittest.TestCase): # Testing the corners of Testing\\Depth 2 def test_rectangle_corners(self): filesys =...
from itertools import product functions = dict(triangle=lambda n: n * (n+1) / 2, square=lambda n: n**2, pentagonal=lambda n: n * (3*n - 1) / 2, hexagonal=lambda n: n * (2*n - 1), heptagonal=lambda n: n * (5*n - 3) / 2, octagonal=lambd...
import hmac import time import urlparse from hashlib import sha1 from time import time from .account import get_temp_url_key, set_temp_url_key from .credentials import swift class Object(object): """ A swift object. Can be initialized by specifying a full name (includes container), or container and nam...
def permuta(a,b,c): temp = a a = b b = temp print("A = " + str(a) + ", B = " + str(b) + ",C = " + str(c)) x = input() y = input() z = input() permuta(x,y,z) permuta(y,z,x) permuta(x,y,z) permuta(x,z,y)
import tensorflow as tf import os from gmc.conf import settings from gmc.core.cache import store class NN: def __init__(self, dataset, n_input=None): self.data = dataset self.layers = [] self.weights = [] self.bias = [] self.results_dir = os.path.join(settings.BRAIN_DIR, "nn...
from djl_ui import * from djl_templater import * class PostResponder(object): def __init__(self, posts, template, graph): self.posts = posts self.template = template self.templater = Templater() self.graph = graph def respond(self): for post in self.posts: s...
import os from path import Path def delete_file(DIRECTORY,filename): d = Path(DIRECTORY) #replace directory with your desired directory for i in d.walk(): if i.isfile(): if i.name == filename: i.remove() def delete_file_by_extension(DIRECTORY, extension= "*.pyc...
import os import struct from transitions.extensions import GraphMachine from Game.utils import send_push_message, send_reply_message class GameMachine(GraphMachine): def __init__(self, user_id, **machine_configs): self.machine = GraphMachine(model = self, **machine_configs) self.user_id = user_id ...
# coding: utf-8 import sys import argparse import lglass.generators.roa import lglass.database.file def build_argparser(): argparser = argparse.ArgumentParser(description="Generator for ROA tables") argparser.add_argument("--database", "-D", default=".", type=str, help="Path to database") argparser.add_argumen...
import re finename = "sequencias.fasta" match = int (1) mismatch = int(-1) gaps = int (-2) #lendo o arquivo .fasta with open(finename) as f: arquivo = f.readlines() #transformando o arquivo em string sequencia = ''.join(arquivo) #dividindo cada fita fitaCodificadora = re.split('\n', sequencia) s = re.split('...
#!/usr/bin/env python import os import subprocess p = subprocess.Popen("/home/dstarr/src/TCP/Software/ingest_tools/lcs_classif.py http://127.0.0.1:5123/get_lc_data/?filename=dotastro_215153.dat&sep=,", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) sts = os.waitpid(p...
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from .managers import CustomUserManager class User(AbstractUser): username = None first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=2...
import numpy as np import pandas as pd tmass= pd.read_csv("/users/alex/Data/tmassF.min.db") print("imported 2mass") vvv = pd.read_csv("/users/alex/Data/vvvEQUF.min.db") print("imported vvv") print(tmass) print(vvv)
"""Top-level package for fundamentals_of_data_science.""" __author__ = """Andrew Stewart""" __email__ = 'andrew.c.stewart@gmail.com' __version__ = '2.0.0'
#!/usr/bin/env python # -*- coding: utf-8 -*- # # geraTabFreq.py # # Copyright 2015 Cristian <csanterio@gmail.com> """ 6. Construa a tabela de frequencias de palavras das bíblias católica e protestante, novo e velho testamento. Salve as tabelas em arquivos separados. Em seguida, use a planilha eletrônica para cria...
import os import sys import argparse import math import shutil import time import logging from io import open import numpy as np import torch from torch import nn from torch.nn import init from torch.nn.parameter import Parameter import torch.nn.functional as F import torch.optim as optim #python train_cifar_dvs_snn...
from bs4 import BeautifulSoup as BS from urllib.request import urlopen import csv html = urlopen("https://en.wikipedia.org/wiki/List_of_international_cricket_centuries_by_Sachin_Tendulkar") bsObj = BS(html, "html.parser") table_of_interest = bsObj.findAll("table", {"class":"wikitable"})[1] # 1 for Test Centuries rows ...
import turtle canvas = turtle.Screen() leo = turtle.Turtle() for i in range(5): leo.forward(50) leo.right(145) canvas.exitonclick()
"""Miscellaneous functions for Canto, Raga, Wilkin (1996) bow shocks """ import numpy as np def th1_approx(th, beta): """Equation (26) of CRW""" fac = 0.8*beta*(1.0 - th/np.tan(th)) return np.sqrt(7.5*(np.sqrt(1.0 + fac) - 1.0)) def radius(th, th1): """Radius in terms of D from Eq (23) of CRW ...
# import env Import('env') env.Append(LIBS=['purple']) env.Append(LIBPATH='.') env.Append(CPPPATH = ['/usr/include/glib-2.0/','/usr/lib/glib-2.0/include/','/usr/include/libpurple/']) #env.ParseConfig( 'pkg-config --cflags --libs glib-2.0') env.Object([Glob('*.cpp')])
from drivers.driverchrome import DriverChrome from drivers.driverfirefox import DriverFirefox from drivers.driverIE import DriverIE class DriverFactory(): @staticmethod def get_driver(browser): if browser== "chrome": return DriverChrome() if browser== "firefox": return ...
from tkinter import * from tkinter import messagebox import requests from bs4 import BeautifulSoup import re import webbrowser def Spider(): url = var1.get() pattern = re.compile(r'av[0-9]*') matchResult = pattern.search(url) if not matchResult: messagebox.showinfo("警告", "输入非法!!!") html = r...
""" ゼロから学ぶスパイキングニューラルネットワーク - Spiking Neural Networks from Scratch Copyright (c) 2020 HiroshiARAKI. All Rights Reserved. """ import numpy as np import matplotlib.pyplot as plt def lif(currents, time: int, dt: float = 1.0, rest=-65, th=-40, ref=3, tc_decay=100): """ simple LIF neuron """ time = int(time / dt...
""" Simple python script that launches a worker (for rq). """ from misc.env_vars import * from rq import Worker, Queue, Connection if __name__ == '__main__': with Connection(REDIS_CONN): worker = Worker(Queue('default')) worker.work(logging_level="INFO")
####### ####### Ensure that opencv-contrib is installed ####### import cv2 import argparse import sys import math import numpy as np import time as t import os from yolo import yolo_on_one_frame from stereo_to_3d import stereo_to_3d_wls master_path_to_dataset = "C://Users//joebo//Documents//00uni//year3//vision//TT...
"""Application config""" import os PWD = os.path.abspath(os.curdir) SECRET_KEY = "8dd09dcb561d308eca351346b8f5a37c6ff33dc39d41154e82b9c4ccc6fde33b691be96ef24692be" DB_NAME = "truthiness.db" NETWORK = b'\x6f' SQLALCHEMY_DATABASE_URI = 'sqlite:///{}/{}'.format(PWD, DB_NAME)
import sys import os import django from twilio.rest import Client from twilio.twiml.messaging_response import MessagingResponse sys.path.append(os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "emblazEX.settings" django.setup() TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") TWILIO_AUTH_TOKEN = os.envi...
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv(r'C:\Users\HP\Desktop\Matter\python\machinelearning\House_Price.csv', header=0) pd.set_option('display.expand_frame_repr', False) print(df.head()) print(df.shape) print(df.describe()) """ print(sns.jo...
#!/bin/python3 import sys def quickSort(arr): left = [] equal = [] right = [] pivot = arr[0] for x in arr: if x == pivot: equal.append(x) elif x > pivot: right.append(x) else: left.append(x) arr[:] =[] arr += left arr += equa...
import re import time import tornado from tornado import gen from tornado import web from tornado.ioloop import IOLoop from providers.google_rss import GoogleRSS from utils import config class FeedHandler(tornado.web.RequestHandler): def data_received(self, chunk): pass def __init__(self, applicati...
import subprocess from datetime import datetime import time import random def jtalk_normal(t): open_jtalk=['open_jtalk'] mech=['-x','/var/lib/mecab/dic/open-jtalk/naist-jdic'] htsvoice=['-m','/usr/share/hts-voice/mei/mei_normal.htsvoice'] speed=['-r','1.0'] outwav=['-ow','open_jtalk.wav'] cmd=...
r=input() if r.isnumeric(): h=int(r) if h%2==0: print("Even") else: print("Odd") else: print("invalid")
#encoding=UTF8 ''' 导入redis接口 使用时,直接使用r.get,r.set等方法即可 ''' import redis r=redis.Redis(host='192.168.184.128',port=6379,db=0)
# preprocessing for ml model ''' 1. clean the data (optional) 2. use tfiffvectorizer ''' # preprocessing for dl model ''' 1. clean the data (optional) 2. use the tokenizer to convert to sequences 3. pad the sequences ''' # Trying out preprocessing using the same pipeline as our project #helper functions for lemm...
import unittest from src.insertion_sort import insertion_sort class InsertionSortTest(unittest.TestCase): def test_correct_worc(self): unsorted_list = [5, 4, 3, 2, 1] sorted_list = [1, 2, 3, 4, 5] self.assertListEqual(insertion_sort(unsorted_list), sorted_list) def test_second_corre...
def disl_relax_script(pair_info, units, atom_style, masses, read_data, temp = 0): mass = '' group_move = '' for i in xrange(len(masses)): mass += 'mass %i %f\n'%(i+1,masses[i]) if i < len(masses)/2: group_move += ' '+str(i+1) newline = '\n' script = newline.join(['bound...
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
#!/usr/bin/env python # Copyright (C) 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list ...
# coding: utf-8 """ Context manager """ fh = open('test_file_path.txt', 'a') # fh.write('test string') # fh.writelines(['test string']) print fh.readlines() # -> ['', ''] fh.close() with open('test_file_path.txt', 'r') as fh: lines = fh.readlines() print lines class Hypervisor(object): """ Hy...
# -*- coding: utf-8 -*- """ Created on Thu Apr 23 16:15:06 2020 @author: 100293 """ import cx_Oracle import pandas as pd conn=cx_Oracle.connect("xxxxxxx","xxxxxxx","xxxxxxx") querry="SELECT * FROM pharma_sales_master WHERE ROWNUM <= 1000" df1=pd.read_sql_query(querry,conn) df1.shape df1.describe() ...
from django.core.management.base import BaseCommand from django.conf import settings from architect.monitor.models import Monitor class Command(BaseCommand): help = 'Synchronise Monitor objects' def handle(self, *args, **options): for engine_name, engine in settings.MONITOR_ENGINES.items(): ...
from django.apps import AppConfig class PhDAmissionPortalConfig(AppConfig): name = 'phDAdmissionPortal'
import os import boto3 from .formatter import FormatReport from .sender import SendReport, sender_sns, sender_stdout def parse_args(): return {'region': 'us-west-2'} def list_to_dict(obj, key='Key', value='Value'): return {o[key]: o[value] for o in obj} class AutoScaling: def __init__(self, region):...
# -*- coding: utf-8 -*- from app.models.meta import metadata, Base from sqlalchemy import Table, Column, Integer, Date, Text from sqlalchemy.orm import mapper from sqlalchemy.sql.expression import desc import web news_table = Table("NEWS", metadata, Column("id", Integer, primary_key=True...
# with open('weather_data.csv') as data_file: # data = data_file.readlines() # print(data) # import csv # # # with open('weather_data.csv') as data_file: # data = csv.reader(data_file) # flag = False # temperatures = [] # for row in data: # if flag: # temperatures.append(int(...
import random inputs = {"hallo" : "hello", "katze" : "cat"} def recover(): with open("words", "r") as f: for line in f: (key, value) = line.split() inputs[key] = value print(inputs) def safe(): file = open("words", "w") for keys in inputs: file.write(keys + " " + inputs[keys]) file.write("\n") def n...
import numpy as np import torchvision.transforms as transforms import torch import cv2 from . import cifar from . import cub200_2011 LOADER_LUT = { 'cifar' : cifar.CIFARData, 'cub200_2011': cub200_2011.CUBData, } def get_loader(dataset_type, data_path, loader_type, label_path=None, cfg=None, logg...
from sympy import pprint from sympy import Symbol from sympy import Eq from sympy import simplify from sympy.solvers import solve ex_new = Symbol("E_x|t+dt; i,j,k") ex_old = Symbol("E_x|t; i,j,k") dt = Symbol("dt") dx = Symbol("dx") dy = Symbol("dy") dz = Symbol("dz") sigma_x = Symbol("o`x") sigma_y = Symbol("o`y") si...
from uc.itm import UCWrappedFunctionality from uc.utils import wait_for import logging log = logging.getLogger(__name__) class Contract_Pay(UCWrappedFunctionality): def __init__(self, k, bits, sid, pid, channels, pump, poly, importargs): self.ssid = sid[0] self.P_s = sid[1] self.P_r = s...
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer import numpy as np import pandas as pd from scipy.sparse import csr_matrix from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score train_20news = fetch_20newsgroups(subset='train'...
import torch import torch.nn as nn from torch.distributions import MultivariateNormal import numpy as np device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Memory: def __init__(self): self.actions = [] self.ee_pos = [] self.logprobs = [] self.rewards = []...
from betterapis.app import api, db if __name__ == '__main__': db.create_all() api.run(port=8080, debug=True)
"""Top-level project Main function.""" from ColumnCropper import ColumnCropper import ImageReader import RunTimeData import ColumnWindowFinder import sys sys.path.append('../../runtime_data/') import RunTimeData def main(): """Read file directory images and the run the Image Operator aggregate function.""" ...
#!/usr/bin/env python3 # LSST Data Management System # Copyright 2014 LSST Corporation. # # This product includes software developed by the # LSST Project (http://www.lsst.org/). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publishe...
#定义列表 class Node: def __init__(self,v): self.val=v self.next=None #列表转链表 def ls_node(ls): head=Node(None) p=head #p为链表指针 for i in ls: p.next=Node(i) p=p.next return head.next #链表转列表 def node_ls(head): ls=[] while True: ls.append(head.val) he...
UPLOAD_FOLDER = 'images/' MAX_FILE_SIZE_MB = 5
#!/usr/bin/env python """Test suite for aospy.timedate module.""" import datetime import cftime import numpy as np import pandas as pd import pytest import xarray as xr from itertools import product from aospy.data_loader import set_grid_attrs_as_coords from aospy.internal_names import ( BOUNDS_STR, RAW_STAR...
# Generated by Django 3.0.4 on 2020-03-17 06:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('titanic', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='titanic', name='Fare', ), ]
# Calculator of angle between hour and minute needle print("This program indicates the angle between hour and minute needle!. " "This program works with 12 hour clock !") # Error handling code block. H = 0 M = 0 while 1 >= H <= 12 and 1 >= M <= 60: try: H = int(input("Please introduce the hour betw...
from django import forms import datetime from django.contrib.admin import widgets from django.contrib.admin.widgets import AdminTimeWidget,AdminDateWidget #import html5.forms.widgets as html5_widgets #from suit.widgets import SuitDateWidget, SuitTimeWidget, SuitSplitDateTimeWidget from functools import partial DateInpu...
import datetime from io import StringIO import sys import signal import time import os import configparser from configobj import ConfigObj from subprocess import call import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler from watchdog.events import FileSystemEventHandle...
import cv2 import os import time import click @click.command() @click.option('--model-name', default='haarcascade_frontalface_default.xml', help='The name of the pre-trained model to load. Download more from https://github.com/opencv/opencv/tree/master/data/haarcascades') @click.option('--camera-id', def...
#=============================================================================== # The application will not be able to exit out of the Task phase # unless the criteria are met. # Gating criteria are only evaluated during process. # Expects GatingChannel's signal to be scaled so +1.0 is the top of the screen # -e.g., i...
raio = int(input()) PI = 3.14159 volume = (4 * PI * (raio**3)) / 3 print(f"VOLUME = {volume:.3f}")
# -*- coding: utf-8 -*- from lxml import html from dataPreprocess import dataPreprocess from public_functions import * __author__ = 'benywon' class QASentdataPreprocess(dataPreprocess): def __init__(self, use_clean=False, **kwargs): dataPreprocess.__init__(self, **kwar...
from django.contrib import admin from riot.models import Places, Profile, RiotPronePlaces, NowRioting # Register your models here. admin.site.register(RiotPronePlaces) admin.site.register(NowRioting) admin.site.register(Profile) admin.site.register(Places)
from opencv.cv import * from opencv.highgui import * import time import sys counter = 0 size = None def initCamera(): global size camera = cvCreateCameraCapture(1) if not camera: print "Could not open webcam!" sys.ext(1) cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320) cvSetCaptureProperty(camera, C...
#coding:utf-8 #!/usr/bin/env python from gclib.object import object from game.utility.config import config class almanac(object): def __init__(self): """ 构造函数 """ object.__init__(self) self.card = set() self.equipment = set() self.skill = set() self.combine = [] self.user = None return ...
from keras.datasets import cifar10 from keras.utils import np_utils from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.optimizers import SGD, Adam, RMSprop import matplotlib.pyplot as plt #CIFAR10은...
from django.urls import path, include from . import views urlpatterns = [ path('mapa', views.mapa, name='mapa'), path('lugarocupado', views.lugarocupado, name='lugarocupado'), path('propina', views.propina, name='propina'), path('calificar', views.calificar, name='calificar'), ]
import time import numpy as np from util import get_data, np_loader if __name__ == "__main__": root = "data" num = 1000000 path_list, label_list, num_to_cat = get_data(root) print("Total images :", len(path_list)) mean = 0.0 var = 0.0 n = min(len(path_list), num) # Go through the wh...
def nume_persoane(x): return str(x) def nume_persoana(y): return str(y) bucla = 1 bucla2 = 1 print("Buna ziua") salut = input() print("Bine ati venit in agenda telefonica calculatorului") agenda_telefonica = {"Sebi" : 770421464, "Balau" : 748113188, "Bianca" : 768152514, "Crisan" : 7242481...
import unittest import os import sys from scholarly import scholarly, ProxyGenerator from scholarly.publication_parser import PublicationParser import random import json from contextlib import contextmanager class TestLuminati(unittest.TestCase): skipUnless = os.getenv("USERNAME") and os.getenv("PASSWORD") and os...
from django.contrib import admin from orders.models import Order from django.contrib.auth.admin import User from .models import * class SystemoptionsAdmin (admin.ModelAdmin): list_display = ["id", "email_send", "get_email_pool", "phone_send", "get_phone_pool", "email_from"] list_editable = ["email_send", "ph...
print("hello tests")
import sys import compilador.helpers.file_parser from compilador.helpers.file_parser import * import compilador.vm.virtual_machine from compilador.vm.virtual_machine import * import game_engine.engine from game_engine.engine import * # CLASE EXECUTER # Comunicación entre parser, vm y juego class Executer(object): ...
import os #from google.appengine.api import memcache from google.appengine.api import users #from google.appengine.ext import db from google.appengine.ext.webapp import template #import src.accounts as accounts #from app.model.account import Account from app.model.accounts import Accounts # Tools # ----- class Cont...
from flask import * app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/aaaa', methods=["POST"]) def res_json(): return jsonify( { "XXXXXXXX": "YYYYYYYYYYYYYYYYYYY" } ) if __name__ == '__main__': app.run(debug=True, hos...
import sys from datetime import datetime from bs4 import BeautifulSoup import numpy import pandas as pd import requests import backtrader as bt import pprint from dateutil import relativedelta # https://stackoverflow.com/questions/21806496/pandas-seems-to-ignore-first-column-name-when-reading-tab-delimited-data-giv...
from django.contrib import admin from .models import Parliament1 # Register your models here. admin.site.register(Parliament1)
# -*- coding: utf-8 -*- import random from dataPreprocess import dataPreprocess from public_functions import * __author__ = 'benywon' class insuranceQAPreprocess(dataPreprocess): def __init__(self, neg_low=15, neg_high=30, Max_length=50, **kwar...
# This program 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 Software # Foundation; either version 2 of the License, or (at your option) any later # version. # This program is distributed in the hope that it will be useful, but W...
# Imports import numpy as np import cv2 import dlib from scipy.spatial import distance as dist from scipy.spatial import ConvexHull def eye_size(eye): eyeWidth = dist.euclidean(eye[0], eye[3]) hull = ConvexHull(eye) eyeCenter = np.mean(eye[hull.vertices, :], axis=0) eyeCenter = eyeCenter.astype(int) ...
# # Assignment 6 # # Student Name : Aausuman Deep # Student Number : 119220605 # # Assignment Creation Date : March 7, 2020 from nltk.corpus import gutenberg as g from nltk.stem.porter import * def analyze(book_name): # This function analyzes the 'book_name' file and prints out its characteristics using nltk pack...
i=1 s=0 even_s=0 odd_s=0 sevn_s=0 while i<=100: s+=i if(i%2==0): even_s+=i else: odd_s+=i if(i%7==0): sevn_s+=i; i+=1 print("1부터 100까지의 합 = ",s) print("1부터 100까지의 짝수의 합 = ",even_s) print("1부터 100까지의 홀수의 합 = ",odd_s) print("1부터 100까지의 7의 배수의 합 = ",sevn_s) ...
from django import forms class StarterForm(forms.Form): METHOD_OPTIONS = (("", "Please select one"), ("0", "Harris Corner Detection")) image = forms.ImageField(required=True) method = forms.ChoiceField(choices=METHOD_OPTIONS, required=True) custom_name = forms.CharField(max_length=50, required=False, ...
#!/usr/bin/env python import sys from graph import Graph, Vertex """ Implementation of the Word Ladder Algorithm using Breadth First Search on a Graph. """ def buildGraph(g): d = {} with open("words.txt") as file: for word in file: word = word.replace("\n", "") for i in rang...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.scala.dependency_inference.symbol_mapper import AllScalaTargets from pants.backend.scala.subsystems.scala import ScalaSubsystem from pants.backend.scala.util_rules.versio...
''' Created on 2016.6.14 @author: huke ''' def combine(num2,max2,max): i = num2 j = max-1 for x in range(max2,i): if max2 >1: combine(i-1,max2-1,max); else: for y in range(0,max-1): print(max) print('\n') if __name__ == '__main__': ...
import json import re import requests from bs4 import BeautifulSoup as bs from bs4.element import Comment import os import asyncio import logging # Write to a json file def write_to_file(filename, data): with open(os.getcwd() +f"/service_workers/data/{filename}.json", 'w') as fp: json.dump(data, fp) # C...
def decompose_single_strand(single_strand): output = '' for frame in range(3): output+='Frame {}: {} '.format(frame+1, single_strand[:frame]).strip() for i in range(frame,len(single_strand),3): output+=' {}'.format(single_strand[i:i+3]) output+='\n' return output[:-1] ...
import sys import time import subprocess import Jetson.GPIO as GPIO from .controll_sys import LedBlink class PowerListener(object): """docstring for PowerListener""" def __init__(self, handler, pin_type, input_pin): super(PowerListener, self).__init__() self.__handler = handler self.__input_pin = input_pin...
operand1 = 95 operand2 = 64.5 #operations print operand1 + operand2 print operand1 - operand2 print operand1 * operand2 print operand1 / operand2 print operand1 % operand2 #This method is useful because you dont need to rewrite the numbers, #you just change the variables and the result will automaticly appear.
#!/usr/bin/env python import random import string import os import os.path def gen_random(str_len): return ''.join(random.choice(string.hexdigits) for x in range(str_len)) def main(): # Don't need to create config folder if env vars are already set if os.getenv('API_SECRET_KEY', None) and os.getenv('DATABASE...
from main.activity.desktop_v3.activity_login import * from main.activity.desktop_v3.activity_logout import * from main.activity.desktop_v3.activity_myshop_editor import * from utils.lib.user_data import * from utils.function.setup import * import unittest class TestEditMyshopInfo(unittest.TestCase): _site = "live...