text
stringlengths
38
1.54M
class Solution(object): def tree2str(self, t): res = [] self.tree2strRec(t, res) return ''.join(res) def tree2strRec(self, t, res): if t is None: return res.append(str(t.val)) if t.left is None and t.right is None: return if...
# ********************************************** # # Training Pipeline proceducte in pytorch # 1 ) Design model (input, output size, fowrd pass) # 2 ) construct loss optimizer # 3 ) Training loop # - forward pass: copute prediction # - backward pass: gradients # - update weights # *********************...
import sys from random import randint def is_prime(x): return x % 2 != 0 and x % 3 != 0 and x % 5 != 0 and x % 7 != 0 def get_factor(x): if x % 2 == 0: return 2 if x % 3 == 0: return 3 if x % 5 == 0: return 5 if x % 7 == 0: return 7 return 0 def to_base(s, b): r, p = 0, 1 for c in rev...
class Employee: no_of_emps = 0 increment = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@email.com' Employee.no_of_emps += 1 def full_name(self): return '{} {}'.format...
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Opti...
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import DrowsyDriverUserCreationForm, DrowsyDriverUserChangeForm from .models import DrowsyDriverUser class DrowsyDriverUserAdmin(UserAdmin): """Create a custom admin for cus...
# ___________________________________________________________________________ # # Prescient # Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # This software is ...
################################################################################# # WaterTAP Copyright (c) 2020-2023, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National Laboratory, # National Renewable Energy Laboratory, and National Energy Technology # Labo...
# -*- coding: utf-8 -*- import json import re import scrapy import logging # 解析赛事 from parsel import Selector from okooo.items import MatchInfo class okoooSpider(scrapy.Spider): name = "sp_match" allowed_domains = ["www.okooo.com"] headers = { "Accept": "text/html, */*", "Accept-Encodi...
""" Test reading and changing the active set of available packages""" import shutil import pytest from pkgpanda import Install, Repository from pkgpanda.util import expect_fs, is_windows, resources_test_dir @pytest.fixture def repository(): return Repository(str(resources_test_dir("packages"))) @pytest.fixtu...
import xlrd class ProcessExcel: def __init__(self, filepath): self.filepath = filepath def get_data(self): wb = xlrd.open_workbook(self.filepath) sheet = wb.sheet_by_index(0) for i in range(1, sheet.nrows): temp_dict = {} for j in range(0, she...
from parameterized import parameterized import unittest # 实现加法的方法 def add(x, y): return x+y test_data = [(1, 1, 2), (1, 0, 1), (-1, 2, 1), (0, 0, 0)] class TestAdd(unittest.TestCase): # def test_add_01(self): # res1 = add(1, 1) # self.assertEqual(2, res1) # # # def test_add...
from django.contrib import admin from django.forms import TextInput, Textarea # Register your models here. from .models import Course, User, Formation, Inspiration, CourseReview, CourseInstance from django.db import models class YourModelAdmin(admin.ModelAdmin): formfield_overrides = { models.CharField: {'w...
import os import types import binascii from Crypto.Cipher import AES from Crypto import Random from Crypto.Random import random from clients import ClientManager from string import ascii_letters, digits class KeystoneManager(object): """ Class for ensuring role assignments in keystone. Give it a role ass...
def isISBN(x): if type(x) != str: #prevent the outcome is string return False if len(x) != 10: #prevent the exeption of outcome return False a = int(x[0]) b = int(x[1]) c = int(x[2]) d = int(x[3]) e = int(x[4]) f = int(x[5]) g = int(x[6]) h = int(x[7])...
#!/bin/usr/env python from spaceinv.enemy import Enemy from spaceinv.explosion import ExplosionManager from sys import exit import pygame #gestore nemici class EnemyManager(object): def __init__(self, surf): self._enemies = [] #lista di nemici vuota self._surf = surf #surface per il disegno dei ne...
import numpy as np if __name__ == '__main__': # 矩阵的创建 A = np.array([[1,2], [3, 4]]) print(A) # 矩阵的属性 # 获取矩阵的元素 # : 切片表达式, 表示从头到尾 print(A[:,0]) # 单位矩阵 I = np.identity(2) print(A.dot(I)) print("I.dot(A) = {}".format(I.dot(A))) # 逆矩阵 invA = np.linalg.inv(A) pr...
import pandas as pd df = pd.read_csv('imdb_data.csv', delimiter = ';') # Import data into a pandas dataframe stored in the variable pd
# -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- from docplex.mp.solut...
import sys import os import pdb if len(sys.argv) == 1 : print ("Provide argumanet") print ("-a for append with string") print ("-v for display") sys.exit(1) if len(sys.argv) >= 1: first = sys.argv[1] if (first == "-a"): if not sys.argv[2]: print ("Give String") else: string = sys.argv[2] ...
import cProfile import sf_abm_mp_igraph ### with python-igraph # import sf_abm_mp_qdijkstra ### with our sp implementation cProfile.run('sf_abm_mp_igraph.main()', 'sf_abm_mp_profile.txt') # cProfile.run('sf_abm_mp_qdijkstra.main()', 'sf_abm_mp_profile.txt')
import json import random import math import numpy as np import requests from model.decision_makers.deep_behaviour_state import DeepBehaviourState from model.tools.binary_printer import BinaryPrinter from model.utils.choiceUtils import weighted_random import urllib class DeepBehaviour: distribution = np.random....
from collections import deque # f = open("in.txt") # 제자리 상 우 하 좌 dx = [0,-1,0,1,0] dy = [0,0,1,0,-1] # y,x,dist,power # test_num = int(f.readline()) test_num = int(input()) result = 0 def pri(arr): for i in range(len(arr)): print(arr[i]) # bfs def mark(r,c, idx, dist): que = deque() que.append((r...
#Time Complexity:O(2^N) #Space Complexity:O(2^n) #Ran sucessfully on Leetcode: Yes #Algorithm: # 1. Create a array for returning result # 2. Create a helper function, with the given list , current list being returned as result, index of the element in nums we are dealing with. # 3. In the helper function we append the...
from django.conf.urls import url from django.contrib import admin from .views import index, group, user urlpatterns = [ url(r'^menu_all$', index.menu_all, name='menu_all'), url(r'^menu_per$', index.menu_per, name='menu_per'), url(r'^group$', group.group, name='group'), url(r'^group/add$', gro...
from django.contrib.auth import get_user_model from django.db import models class Message(models.Model): author = models.ForeignKey(get_user_model(), related_name='author_message', on_delete=models.CASCADE, verbose_name='Автор') recipient = models.ForeignKey(get...
from django.urls import path from .views import ( ManageUsersView, ManageUserView, ManageUserCreateView, ManageUserEditView, ManageUserDeleteView ) web_page_urls = [ path('', ManageUsersView.as_view()), path('<int:id>/', ManageUserView.as_view()), path('create/', ManageUserCreateView.as...
# -*- coding: utf-8 -*- """ python-annict ~~~~~~~~~~~~~~~~~~~~~ Annict API for Python. """ __title__ = "python-annict" __version__ = "0.7.0" __author__ = "Hiro Ashiya" __license__ = "MIT" from .api import API # noqa
class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ m=len(citations) start=0 end=m-1 while start<=end: mid=(start+end)/2 if citations[mid]==m-mid: return m-mid ...
nterms=int(input("Number of terms to be displayed from the serirs? ")) a=0 b=1 count=0 while count<nterms: print(a) c=a+b a=b b=c count+=1
import requests url='https://icanhazdadjoke.com' #res=requests.get(url,headers={'Accept':'text/plain'})#Will get plain text only from this.Not all websotes supports it #print(res.text) res=requests.get(url,headers={'Accept':'application/json'})#Json converts plain text to a dictionary which we can use it in our p...
import sys sys.path.append("..") from players.PlayerInterface import PlayerInterface import random class RandomPlayer(PlayerInterface): def __init__(self, show=True): self.show = show def chooseMove(self, moves): """Choosen a move randomly """ chosen = random.randint(0, len(m...
# coding: utf-8 # author: wie@ppi.co.jp import sys from PySide import QtGui, QtCore from numbers import Number class SpreadsheetCompare(): _keyCount = 3 _keys = [] _ascending = [] def _operator(self): pass class Cell(QtGui.QTableWidgetItem): _cell = None _cachedValue = None _cach...
# # Copyright (c) 2015 Intel Corporation # # 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 law or agreed to i...
import mxnet as mx from ..config import config from ..PY_OP import rpn_fpn_ohem3, cascade_refine t = rpn_fpn_ohem3 c = cascade_refine PREFIX = 'RF' F1 = 0 F2 = 0 _bwm = 1.0 def conv_only(from_layer, name, num_filter, kernel=(1, 1), pad=(0, 0), stride=(1, 1), bias_wd_mult=0.0, shared_weight=None, share...
# -*- coding: utf-8 -*- """ Created on Thu Nov 23 08:50:22 2017 Módulo que permite hacer loggeo de información en una ruta específica @author: rlarios """ import time import os import io from datetime import datetime from pytz import timezone class logger(): def __init__(self , pathlog = './log/log' , logName ...
import os import time import unittest from jina.flow import Flow from jina.proto import jina_pb2 from tests import JinaTestCase, random_docs cur_dir = os.path.dirname(os.path.abspath(__file__)) def random_queries(num_docs, chunks_per_doc=5): for j in range(num_docs): d = jina_pb2.Document() for ...
from django.contrib import admin from .models import User # Register your models here. # class CustomUserAdmin(admin.ModelAdmin): # model = User admin.site.register(User)
from boto import ec2 from boto.exception import EC2ResponseError, BotoClientError from boto.ec2.securitygroup import SecurityGroup import sys ###Patch the Source code Include VPC and Outbound rules######### def copy_to_region_vpc(self, region=None, vpc=None, name=None, dry_run=False): if region.name == self.region:...
import pandas as pd import matplotlib.pyplot as plt income = pd.read_csv('us_income.csv') # This is the mean median income in any US county. mean_median_income = income["median_income"].mean() print(mean_median_income) def get_sample_mean(start, end): return income["median_income"][start:end].mean() ...
from flask import Flask, render_template, redirect import pymongo import scrape_mars app = Flask(__name__) # setup mongo connection conn = "mongodb://localhost:27017" mongo = pymongo.MongoClient(conn) # connect to mongo db and collection db = mongo.mars_project collection = db.mars_data @app.route("/") def index(...
import torch from torch.utils.data import DataLoader, Dataset import torch.nn as nn from torch import optim import torch.nn.functional as F import torchvision.datasets as dset import torchvision.transforms as transforms from torch.autograd import Variable import numpy as np import random from PIL import Image import PI...
t = input() for i in range(t): n = input() v = map(int, raw_input().split(' ')) sorted_v = list(v) sorted_v.sort(reverse=True) s = "" if len(v) >= 2: while sorted_v[0] != sorted_v[1]: ind = v.index(sorted_v[0]) v[ind] -= 1 sorted_v[0] -= 1 s += chr(ord('A') + ind) + ' ' sorted_v.sort(revers...
import numpy as np import argparse import os import math_lib import plot_lib import Finite_horizon_controller import Infinite_horizon_controller if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--stage_number", default=300, type=int) # Number of stages parser.add_argument...
import math import random class FinishedFlag: def __init__(self): self.finished = False self.counter = 0 def is_finished(self): return self.finished def mark_finished(self): self.finished = True def tick(self): self.counter = self.counter + 1 def __str_...
import matplotlib.pyplot as plt import matplotlib.animation as animation import csv plt.style.use('ggplot') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) def animate(i): with open('output.csv', 'r') as csvFile: csvReader = csv.DictReader(csvFile) line_count = 0 xar = [] yar = [] ...
#!/usr/bin/python import sqlite3 import random import sys import signal from datetime import datetime def update_metrics(conn, question, answer, questioned_at, is_answer_correct): conn.execute( "insert into metrics (question_id, answer, questioned_at, answered_at, is_answer_correct) values (?,?,?,?,?)", ...
import requests import json #Created by Raul Jimenez, UTA CS Senior """ Since some teachers do not allow us to mass email other students on canvas because they have the options disabled I decided to create a script that would allow me approximatly get the list of all emails for the students in the course numb...
# -*- coding: utf-8 -*- import numpy as np import time from CSRec.DataView.filetrust_data import build_rating_data from CSRec.DataView.filetrust_data import build_rating_matix def matix_factorization(R, K): N = len(R) # 用户数 M = len(R[0]) # 项目数 P = np.random.rand(N, K) Q = np.random.rand(M, K) ...
import sys import unittest import unittest.mock as mock from imagemounter._util import check_output_ from imagemounter.parser import ImageParser from imagemounter.disk import Disk class PartedTest(unittest.TestCase): @unittest.skipIf(sys.version_info < (3, 6), "This test uses assert_called() which is not present...
# -*- coding: utf-8 -*- __author__ = 'manman' """ 根据用户输入打印正三角,比如用户输入3打印如下: * * * * * * * * * * 打印菱形 """ # 1. 三角形 # def show_triangle(num): # """ # print triangle # :param num: # :return: # """ # for i in range(num): # # print('i%s' % i) # print(' ' * (num - i - 1), e...
from aiohttp import web from payu_fake import create_app if __name__ == '__main__': app = create_app() web.run_app(app, host='localhost', port=5959)
import cv2 import os def work(time): print(time) os.system('./run.sh') os.system('./main<main.in') vc = cv2.VideoCapture('data/main.mp4') os.system('g++ -o main main.cpp') c = 0 print("Begin") if vc.isOpened(): rval, frame = vc.read() else: rval = False print("Can't open file") f=open("../dark...
#-*- coding: utf-8 -*- """ Spectral fire model =================== Model for spectral response following a fire """ import numpy as np def spectral_temporal_response(num_days=20): """ Return of healthy vegetation length Computes the mixture of ash and recovered vegetation --> --> NOT...
from datetime import datetime from FlaskApplication import db, loginManager from flask_login import UserMixin #Manage Multiple User Login @loginManager.user_loader def load_user(user_id): return User.query.get(int(user_id)) #Model of a User Account To Be Stored In Database class User(db.Model, UserMixin): id ...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-06 15:28 from __future__ import unicode_literals import annoying.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True ...
# Copyright (c) 2015 # # All rights reserved. # # This file is distributed under the Clear BSD license. # The full text can be found in LICENSE in the root directory. from boardfarm.devices import prompt from boardfarm.tests import rootfs_boot class LanDevPing6Router(rootfs_boot.RootFSBootTest): '''Device on LAN...
import numpy as np from sklearn import svm from scipy.io import loadmat import copy import torch from utils import * if __name__ == '__main__': # parameter setting train_size = 10000 test_size = 1000 linear_svm_flag = 1 # 1 for use linear svm, 0 for use kernel kernel_type = "rbf" # "linear" "sigmo...
#!/usr/bin/env python import socket import sys HOST = '' PORT = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Soc...
import json from django.test import TestCase, Client from ..models import User, Book from rest_framework import status from ..serializer import UserSerializer, BookSerializer from django.urls import resolve, reverse client = Client() class UserSampleTestCase(TestCase): def setUp(self): User.objects.crea...
from datetime import timedelta from constance import config from django.utils import timezone from .generics import GenericSession class ConstanceSession(GenericSession): constance_key = None def headers(self): return {} def params(self): return {'access_token': getattr(config, self.co...
#!/usr/bin/python3 def uniq_add(my_list=[]): unique = my_list[:] result = 0 for i in set(unique): result = result + i return (result)
# Base de datos, los datos from flask_restful import Resource names = { "balbino": {"name": "balbino", "age": 23, "salary": 1000.0}, "paulina": {"name": "paulina", "age": 27, "salary": 1500.0}, } class HelloWorld(Resource): def get(self, name): return names[name] def put(self, name, age, sal...
from scipy.stats import percentileofscore as pctrank from pandas.io.formats.style import Styler from bs4 import BeautifulSoup from datetime import datetime import pandas as pd import numpy as np import sys, os ################################################################################################### DIR = os...
# import orjson from django.conf import settings from django.contrib import messages # from django.contrib.gis.forms import PointField from django.db.models.deletion import ProtectedError from django.shortcuts import render # from django.template.response import TemplateResponse # from django.utils.decorators import m...
num=int(input("enter the num:")) num1=int(input("enter the num1:")) # a=[] i=1 while i<=(num): j=1 b=[] while j<=(num1): b.append(j) print(b,end=" ") print() j=j+1 print() i=i+4
# -*- coding: utf-8 -*- """ Created on Mon Dec 14 10:02:23 2020 @author: tonyz """ #HomeWork Budget_Data #@Author: BCSUWA_Tony_Zhao 18/12/2020 import os import csv file_name = "resources/budget_data.csv" with open(file_name, newline = '', encoding="utf8") as f: lines = csv.reader(f, delimiter = ",") budge...
import os def get_size_file(file): return os.path.getsize(file) def is_a_folder(a): if os.path.isdir(a): return True else: return False def get_size(a): size=0 if is_a_folder(a): for element in os.listdir(a): size += get_size(f"{a}/{element}") else: ...
import torch import matplotlib.pyplot as plt import gym import random import time def train(Q, env, episodes, visualization=False): epilision=0.7 gamma=0.6 alpha=0.1 total_rewards=[] for e in range(episodes): episode_done=False state=env.reset() env.render() if visualization is True else None while not...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import datetime from google.appengine.ext import ndb from google.protobuf import text_format from components import auth from components import p...
# This is where I'll configure rule-consolidation and route-checkup import pandas as pd import typer def main(config_file: str): ## Reading Excel Configuration file = pd.ExcelFile(config_file) # Read Address Groups from Excel policies_file = pd.read_excel(file,'ACLs') new_policies_file = ...
import uuid from django.db import models from django.conf import settings from django.core.exceptions import ImproperlyConfigured try: from django.contrib.gis.geos import * from django.contrib.gis.db import models as geomodels except ImproperlyConfigured: pass # environment without geo libs from djang...
# -- encoding:utf-8 -- from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.datasets import make_blobs import matplotlib.pyplot as plt import numpy as np import argparse def sigomid_activation(x): return 1.0/(1+np.exp(-x)) def predict(X,W): preds=...
# # Example file for formatting time and date output # from datetime import datetime def main(): # Times and dates can be formatted using a set of predefined string # control codes now = datetime.now() #### Date Formatting #### # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month ...
# Copyright (C) 2014 Biomathematics and Statistics Scotland # # Author: David Nutter (david.nutter@bioss.ac.uk) # # 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 mus...
from django.db import models class Piece(models.Model): name = models.CharField(max_length=200) author = models.CharField(max_length=200, blank=True) source_url = models.URLField(blank=True) source_title = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True) tex...
import pandas as pd import glob import os import numpy as np from pathlib import Path def merge_customer_files(): ''' Merge customer files after combining from two folders. Each folder/file data includes essential pieces to the conversion project ''' folder_exportcustomers = Path(".\DataFiles\ExportC...
# Whether to send SMTP 'Date' header in the local time zone or in UTC. EMAIL_USE_LOCALTIME = True # for test EMAIL_BACKEND = 'djangomail.backends.console.EmailBackend' # for prod # EMAIL_BACKEND = 'djangomail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 465 EMAIL_HOST_U...
# This document is to summarize a series of web services exercises from UM Python Cousera # # Chapter 11 - Regular Expressions # Need to start by importing the re library # Typical commands are re.search() and re.findall() import re myText = "Hello there: this is fun is it not?" a = re.search("hello", myText) # retur...
from fabric.api import settings from burlap.constants import * from burlap import Satchel from burlap.decorators import task INDIGO = 'indigo' KINETIC = 'kinetic' class ROSSatchel(Satchel): name = 'ros' def set_defaults(self): # http://wiki.ros.org/Distributions #self.env.version_name = I...
def verify_sudoku_solution(solution): valid = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) found = [False] * 9 for row in solution: for number in row: if found[number - 1] or number not in valid: return False else: found[number - 1] = True found[:]...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 28 17:03:14 2019 @author: ismael Bonneau Ce fichier sert à récupérer des informations sur l'API the TV db lien : https://api.thetvdb.com/swagger Il cherche parmi toutes les séries du dataset celles qui se trouvent sur le site et construit un fich...
import argparse import time import mmcv import os import torch from mmcv import Config from mmcv.parallel import MMDataParallel from mmcv.runner import load_checkpoint from mmdet3d.apis import seg_test_with_loss from mmdet3d.datasets import build_dataloader, build_dataset from mmdet3d.models import build_detector from...
# 14. Поміняти місцями вміст змінних A і B і вивести нові значення A і B. a = 5 b = 9 a,b = b,a print (a, b) c = b b = a a = c print (a, b)
# -*- coding: utf-8 -*- """ Created on Mon May 11 15:25:55 2020 @author: Lenovo """ # import re module import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print ("matchObj.group() : ", matchObj.group()) print ("matchObj.group...
import argparse import imutils import cv2 import os import numpy as np import operator # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") ap.add_argument("-d", "--detector", required=True, help="path to Op...
# -*- coding: utf-8 -*- """ Created on Wed Sep 30 15:44:26 2020 @author: Connor """ import logging import os import pprint import threading import time import timeit os.environ["OMP_NUM_THREADS"] = "1" # Necessary for multithreading. import torch from torch import multiprocessing as mp from u...
import os a = os.environ.get('FP_Django_SecretKey') b = os.getenv('FP_Django_SecretKey') print(a) print(b)
class Solution: def search(self, nums: List[int], target: int) -> bool: left, right = 0, len(nums)-1 while left<=right: mid = left+(right-left)//2 if nums[mid]==target: return True while left < mid and nu...
from aiogram.types import Message, CallbackQuery, InlineQuery from aiogram.dispatcher import FSMContext from aiogram.utils.exceptions import MessageToEditNotFound from loader import dp, bot, upload_client from keyboards.inline.callback_datas import stories_callback from keyboards.inline.generate import user_keyboard fr...
from django.db import models from datetime import datetime class Tea(models.Model): english_name = models.CharField(max_length=200) pinyin_name = models.CharField(max_length=200, blank=True, null=True) chinese_name = models.CharField(max_length=200, blank=True, null=True) description = models.TextFiel...
#! /usr/bin/python2.7 import argparse import logging import logging.handlers import os import os.path as op import Queue import re import socket import threading MIME_TYPES = { 'aac': 'audio/aac', 'abw': 'application/x-abiword', 'arc': 'application/octet-stream', 'avi': 'video/x-msvideo', 'azw': '...
# (0,0) is bottom_left # Because I'm too lazy to precompute lmao from helpers import memoize @memoize def get_pow_2(n): return pow(2, n) def is_top_left(N, bottom_right): x,y = bottom_right return x < get_pow_2(N - 1) and y >= get_pow_2(N - 1) def is_bottom_left(N, top_right): x,y = top_right return x < get_po...
""" Zaimplementuj klasę Basket umożliwiającą dodawanie produktów w określonej liczbie do koszyka. Zaimplementuj metodę obliczającą całkowitą wartość koszyka oraz wypisującą informację o zawartości koszyka. Dodanie dwa razy tego samego produktu do koszyka powinno stworzyć tylko jedną pozycję. Przykład użycia: basket = B...
# Generated by Django 2.2 on 2019-04-07 03:10 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('org', '0001_initial'), ] operations = [ migrations.CreateMod...
# Python3 code to print all possible subarrays # for given array using recursion # Recursive function to print all possible subarrays # for given array def printSubArrays(arr, start, end): # Stop if we have reached the end of the array if end == len(arr): return # Incre...
# Copyright 2020 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff # This software is distributed under the 3-clause BSD License. ''' An extension to initialize PH weights and/or PH xbar values from csv files. To use, specify either or both of the following keys to the PHoptions dict: "...
# data_manipulation.py # 11th Nov. 2018 # Arnav Ghosh import csv import numpy as np import os import pickle # CONSTANTS POSITIVE = "+" NEGATIVE = "-" REV_CLASS_MAP = [NEGATIVE, POSITIVE] BASES = ["A", "C", "G", "T"] NUM_CLASSES = 10 #O-IDX : -, 1-IDX: + DIM = 10 #FILENAMES DATA_DIR = os.path.join("data") PROCESSED_...
from django.core.exceptions import ObjectDoesNotExist from .models import Wishlist from stores.models import Store from stores.services import get_nearby_stores_within def get_wishlists(latitude: float, longitude: float, options: dict): return Wishlist.objects.filter( **options, store__in=get_near...
from selenium.webdriver.common.by import By class Locator: """Locator objects for finding Selenium WebElements""" def __init__(self, l_type, selector): self.l_type = l_type self.selector = selector def parameterize(self, *args): self.selector = self.selector.format(*args) class ...