text
stringlengths
8
6.05M
from pystachio import * from pystachio.matcher import Any, Matcher def test_matcher(): matcher = Matcher('hello') assert list(matcher.match(String(''))) == [] assert list(matcher.match(String('hello'))) == [] assert list(matcher.match(String('{{hello}}'))) == [('hello',)] matcher = Matcher('packer')[Any][A...
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options import t...
from django.conf.urls.defaults import patterns, include, url from shopback.base.authentication import UserLoggedInAuthentication from shopback.base.permissions import IsAuthenticated __author__ = 'meixqhi' urlpatterns = patterns('shopback.logistics.views', url('company/$','update_logistics_company',name='update_...
from code import ColoredGraph, nptsp_path, random_graph # Tests for nptsp_path.py ------------------------------------------------------ def test_is_valid_path(): # Test 1: invalid path adj_matrix = random_graph.generate_adj_matrix(12) graph = ColoredGraph.ColoredGraph(adj_matrix) for v in range(1, 13): graph....
import pygame import sys import random """© reyan mehmood All right reserved""" # general setup pygame.init() clock = pygame.time.Clock() # Setting up the main window ScreenWidth = 1200 ScreenHeight = 700 screen = pygame.display.set_mode((ScreenWidth, ScreenHeight)) pygame.display.set_caption('Pong') # shapes ball =...
import pickle ''' Function for getting parts of a text which are separeted with a space. @Parameters: String: path of the file. @Return: Tuple: fragments of the text. ''' def getTextFragments(path): text = [] with open(path) as handle: for line in handle: line = line.strip() ...
# -*- encoding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 5 _modified_time = 1281450322.0771639 _template_filename=u'/Users/korol1bp/python/envs/pcp/lib/python2.6/site-packages/pcpbridge/templates/base.mako' _templ...
# -*- coding: utf-8 -*- from odoo import models, fields, api class SaleOrderInherit1(models.Model): _inherit = 'sale.order.line' size = fields.Selection([ ('large', 'Large'), ('small', 'Small'), ('medium', 'Medium')], default='large', required=True, store=True) class InheritStockLin...
# Generated by Django 3.2.2 on 2021-05-24 19:16 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('serviceapp', '0001_initial'), ('m...
import tensorflow as tf from tensorflow import keras from tensorflow.examples.tutorials.mnist import input_data def build_model(units_l1=128, units_l2=10): # Build a model model = keras.Sequential([ keras.layers.Dense(units_l1, activation=tf.nn.relu), keras.layers.Dense(units_l2, activation=tf...
import numpy as np import scipy.ndimage as nd from nibabel import save, Nifti1Image def _cone3d(shape, ij, pos, ampli, width): """Define a cone of the proposed grid """ temp = np.zeros(shape) pos = np.reshape(pos, (1, 3)) dist = np.sqrt(np.sum((ij - pos) ** 2, axis=1)) codi = (width - dist) * (...
#_*_coding:utf-8_*_ from django.conf.urls import patterns, include, url from django.views.generic import TemplateView urlpatterns = patterns('', url(r'^my_issue/?$','apps.accounts.views.my_issue',name='my_issue'), url(r'^change_dep/?$','apps.accounts.views.change_dep',name='change_dep'), )
import numpy as np import matplotlib.pyplot as plt size = 1000 biases = np.linspace(0,1,size) priors = np.ones(size)/len(biases) # generate random p p = np.random.rand() print("Coin bias, p(X=1) = {}".format(p)) # define number of iterations num_iterations = 1000 # iterate through for curr_iter in range(num_iter...
#!/usr/bin/env python #-*-coding:utf-8-*- ''' Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, ...
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/inicio') def inicio(): return render_template('index.html') @app.route('/estudios') def estudios(): skills = [ { "curso":"PYT...
# a file to process data from 3 tabs in 2 excel documents into 1 # summary table, then exported to excel # original 05.15, updated 05.16 # masked some things & removed some comments since i originally made this # for work and all import pandas as pd c_markets = ['AZ', 'AR', 'CA', 'FG', 'K', 'LV', 'LO', 'NC',...
# Generated by Django 2.1.5 on 2019-03-31 13:08 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0003_auto_20190331_1157'), ] operations = [ migrations.AddField( model_name='weeklytask', n...
import pandas as pd import time from twitter import * #from collections import Counter config = {} execfile("config.py", config) filename = "ModestoBeeFollowers.csv" twitter = Twitter(auth = OAuth(config["access_key"], config["access_secret"], config["consumer_key"], config["consumer_secret"])) ######### Used to...
import sys import os import re from p5Dict import * inputFile = open(sys.argv[1], 'r') lines = inputFile.readlines( ); def parseLine(lines): varTypeD = { } varValueD = { } labelD = { } count = 1 for line in lines: print("%3d. %s" %(count, line.strip('\n'))) if re.search('[a-z0-9A-...
""" LeetCode - Hard """ """ Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to se...
x=input("adj meg egy szamot") xI=int(x) tomb=[] tomb.append(xI) atlag=0 while (x!="ennyi"): x=input("Adj meg egy ujabb szamot") if x=="ennyi": print("Max ertek a tombben: ") print(max(tomb)) print("Minimum ertek a tombben: ") print(min(tomb)) for i in range(0,len(tomb...
import io, os, argparse, random def replicate(file, k, upsample, add = None): src = [] tgt = [] augmented_src = [] augmented_tgt = [] with io.open(file, encoding = 'utf-8') as f: for line in f: toks = line.strip().split() seg = ''.join(c for c in toks) tgt.append(seg) src.append(seg.replace('!...
#Sock Merchant problem in hackerrank def sockMerchant(n, ar): count = 0 sets = set(ar) for i in sets: count += int(ar.count(i)/2) return count
N = int( input()) A = [ int( input()) for _ in range(N)] now = 0 ans = 0 for i in range(N): a = A[i] if now == 1: if a >= 1: ans += 1 a -= 1 now = 0 ans += a//2 a = a - a//2*2 if a == 1: now = 1 print( ans)
import shutil import pytest from gitrack import helpers, exceptions class TestInit: def test_init(self, repo_dir, cmd, mocker): mocker.patch.object(shutil, 'which') shutil.which.return_value = 'gitrack' assert helpers.is_repo_initialized(repo_dir) is False assert (repo_dir / '.g...
# set 집합 {} # list-index/dic-key로 첨자가 있었는데 set은 첨자가 없음 - 중복불가 # 저장속도는 빠르나 검색은 반복하여 찾아야됨 / 자료 수집에 몰빵 # 집합은 여러 값들의 모임, 저장순서 보장안되고 중복값을 허용하지않음 # 딕셔너리처럼 {}로 쓰나 key,value값이 지정되어있지 않음 #print할때마다 순서가 바뀜 # names = {'허준', '신사임당', '권율', '홍길동', '허준 ', 212, 'ㅅㅅㅅ'} # print(type(names)) #class 'set' # print(len(name...
import openke, torch from openke.config import Trainer, Tester from openke.module.model import TransE from openke.module.loss import MarginLoss, SigmoidLoss from openke.module.strategy import NegativeSampling from openke.data import TrainDataLoader, TestDataLoader from pathlib import Path # dataloader for training tra...
import pandas as pd from pandas import DataFrame import csv data1=pd.read_csv('data.csv') data=DataFrame(data1) # a=data.loc[1,'star'] # print(a) # print(data.info()) del data['number'] def traindata(): with open('trainmodle.txt','a',encoding='utf-8') as f: for row in data['comments']: ...
""" Type definition for model parameters """ from typing import List, Optional from pydantic import BaseModel, Extra, validator from pydantic.dataclasses import dataclass # Forbid additional arguments to prevent extraneous parameter specification BaseModel.Config.extra = Extra.forbid class Time(BaseModel): sta...
from .pixelcnn import PixelCNN from .pixelcnn_drop import DropPixelCNN from .pixelcnn_pp import PixelCNNpp
#!/usr/bin/env python3 langs = ["Perl", "Python", "Java", "Go", "Perl", "Rust", "C++", "Python", "Perl", "Go"] bad_langs = {"Perl", "C++"} def count_set(list, set): count = 0 for elem in list: if elem in set: count += 1 return count result = count_set(langs, bad_langs) print("Level ...
# -*- coding: utf-8 -*- """ <ENTER DESCRIPTION HERE> """ __author__ = "Jakrin Juangbhanich" __email__ = "juangbhanich.k@gmail.com" def add(f1: float, f2: float) -> float: return f1 + f2
# -*- coding: utf-8 -*- # # * Copyright (c) 2009-2017. Authors: see NOTICE file. # * # * 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...
from flask import Flask, render_template, request, redirect, session, flash from flask_bcrypt import Bcrypt from mysqlconnection import connectToMySQL import re EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') name_regex = re.compile(r'^[a-zA-Z]+$') mysql = connectToMySQL('registerdb') app ...
def calculate_revenue(melon_tallies, melon_prices): total_revenue = 0 txt_descriptions = [] for melon_type in melon_tallies: price = melon_prices[melon_type] revenue = price * melon_tallies[melon_type] total_revenue += revenue msg = "We sold %d %s melons at %0.2f each for a ...
from scrapy.spiders import Spider from scrapy.selector import Selector from ..items import JianshuItem class JianshuSpider(Spider): name = "jianshu_spider" allowed_domains = [] start_urls = ['http://www.jianshu.com/'] def parse(self, response): sel = Selector(response) title = sel...
from evennia import DefaultCharacter from evennia.commands.cmdset import CmdSet class AI(DefaultCharacter): pass
# This file contains functions mainly called by movingclass but possibly also by kitesimulate for # conversion of stuff - fairly std functions I think and generally should now work with both # 2 and 3D objects #note these functions were originally written to work with pygame coordinates with origin at # bottom left - ...
# Generated by Django 2.0.6 on 2018-06-17 13:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('rooms', '0001_initial'), ] operations = [ migrations.CreateModel( name='Answer', fi...
from django.views.generic.base import View from django.template.response import HttpResponse from share.oaipmh.fmr_repository import OaiPmhRepository class OAIPMHView(View): CONTENT_TYPE = 'text/xml' def get(self, request): return self.oai_response(**request.GET) def post(self, request): ...
transportation = ['motorcycle', 'car', 'bicycle'] print("I would like to own a " + transportation[0]) print("I would like to own a " + transportation[1])
# PyBank # -------------------------------INSTRUCTIONS ------------------------------------------------------------------------- # In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company. # You will give a set of financial data called [budget_data.csv](PyBan...
import os import openpyxl from openpyxl.styles import Font, Alignment, Border, Fill, Protection from copy import copy def copyCell(src_cell, dst_cell, style=True): '''复制一个单元格,不能是合并的单元格,style=False时只复制单元格值,忽略样式''' if type(src_cell) != openpyxl.cell.cell.Cell or type(dst_cell) != openpyxl.cell.cell.Cell: ...
# -*- coding: utf-8 -*- """ Created on Sun Apr 7 18:35:07 2019 @author: BaX Cruiser """ def breakingRecords(scores): maxScore=minScore=scores[0] pointsMax=pointsMin=0 for e in scores: if e>maxScore : maxScore=e pointsMax+=1 if e<minScore: m...
import numpy as np from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation from tensorflow.keras.optimizers import SGD from tensorflow.keras.datasets import mnist from tensorflow.keras.utils import to_categorical from tensorflow.keras.me...
class Consts(object): MAX_SERVER_LISTEN = 100 MAX_MSG_LENGTH = 1024 TIMEOUT_SELECT_DATA = 5 AUTHENTICATED_STATUS_MSG_LENGTH = 1
from flask import request from app import app, db import app.auth.service as s @app.route('/api/auth/check', methods=['POST']) def check_login_status(): return s.check_login_status() @app.route('/api/auth/refresh', methods=['POST']) def refresh_access_token(): refresh_token = request.cookies.get('refreshTo...
file1 = open("testfile1.txt", "r") x = file1.readlines() file1.close() file2 = open("testfile2.txt", "w") file2.writelines(x) file2.close()
from webtest import TestApp as Client def test_view_home(swissvotes_app): client = Client(swissvotes_app) home = client.get('/').maybe_follow() assert "<h2>home</h2>" in home assert home.request.url.endswith('page/home')
# # # from django.shortcuts import render from django.http import ( HttpResponse, HttpResponseRedirect, ) from django.views.generic import TemplateView, View from django.contrib.auth.decorators import login_required from django.contrib import messages from django.utils.decorators import method_decorator from ...
#作者:王皓平、仲银炜 创建时间:2019.8.22 最后修改时间:2019.9.10 """test3 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: pat...
import os #plotnamelist=['gf12fmhdcv'] plotnamelist=['gf12fmhdcv','gf12fcr_700','gpm12fmhdcv','gpm12fcr_700',\ 'gf12mmhdcv','gf12mcr_700','gpm12mmhdcv','gpm12mcr_700'] for plotname in plotnamelist: os.system('qsub -v PLOTNAME={'+plotname+'} job.pbs')
from .segments import vcsh_repo # noqa
#torch tensor and autograd import torch import torchvision import torch.nn as nn import torch.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt """ 总体上来说 torch.function 等价于 tensor.function 存储上 .function() 返回新的tensor .function_() 就地inplace操作,修改本tensor """ """ ============...
MODELS = ["VGG-Face", "Facenet", "OpenFace", "DeepFace"] METRICS = ['cosine', 'euclidean', 'euclidean_l2'] PLACES = ["Arucas","Teror", "PresaDeHornos", "Ayagaures", "ParqueSur" ] # sorted by run's control point FACES_MODELS = ["retinaface","retinafaceliif50", "retinafaceliif100", "retinafaceliif300", ...
from rif_cpp.test import *
from Tkinter import * from mapUtil import * from raft import * import maps import random grid_length = 40 grid_columns = 8 grid_rows = 8 canvas_width = grid_length * grid_columns canvas_height = grid_length * grid_rows class GameGUI: ''' The GameGUI creates the canvas and all its items. The canvas is updated ...
''' Program: GAS : Internet Speed Tester Author: Shashi Kumar GitHub: sbkshashi Read Me Before running 1. All module should come with Python basic installation except speedtest. 2. To install speedtest run a. pip install speedtest_cli 3. I have used Python3.9.2 64-bit ''' ##Required Imports fro...
from flask import Flask, render_template import csv import json app = Flask(__name__) @app.route('/') def hello(): data = [] with open('../data/processed/beginner_1.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: data.append(row) return render_template('test.html', phrases_json=data) ...
from decimal import Decimal from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple from hummingbot.strategy.amm_arb.amm_arb import AmmArbStrategy from hummingbot.strategy.amm_arb.amm_arb_config_map import amm_arb_config_map def start(self): connector_1 = amm_arb_config_map.get("connector...
num_lines = int(input('Enter number of lines: ')) num_stars = int(input('Enter number of stars: ')) for line in range(num_lines): for star in range(num_stars): print('*', end=' ') print()
import cv2 #/*! 模糊用于去除图像中的噪声,也称为平滑。它是对图像应用低通滤波器的过程。在 OpenCV 中对图像进行模糊,我们常用 GaussianBlur。 */ img = cv2.imread("image.jpg") print(img.shape) #imgBlur = cv2.GaussianBlur(img,(sigmaX,sigmaY),kernalSize) #kernalsize-表示内核大小的Size对象。 #sigmaX-代表X方向上高斯核标准偏差的变量。 #sigmaY-与sigmaX相同 imgBlur = cv2.GaussianBlur(img, (15,15), 0) #低通滤波...
import os import cv2 import numpy as np import random source = 'enhanced/' dest = 'enhancedRandomData2/' files = os.listdir(source) files.sort() padding = 15 for file in files: image = cv2.imread(source + file, cv2.IMREAD_GRAYSCALE) croppedName = file[:-4] for i in range(150): row = random.ran...
# -*- coding: utf-8 -*- """ Navigation toolbar for matplotlib widgets """ import numpy as np from PyQt5.QtCore import QObject from PyQt5.QtCore import QPoint from PyQt5.QtCore import QSize from PyQt5.QtCore import QVariant from PyQt5.QtCore import Qt from PyQt5.QtCore import pyqtSignal from PyQt5.QtCore import pyqtSl...
# -*- coding: utf-8 -*- """ Created on Wed Aug 21 14:35:44 2019 @author: gustavo.fonseca """ import matplotlib.pyplot as plt import pandas as pd import funcs as f1 #Tarefa 18 #Exercício 1: print('Exercício 1') t=pd.read_csv('file:///C:/Users/gustavo.fonseca/Downloads/BDSinfo.csv', delimiter='\t') f=t['F...
import os from sot import * funcList = [ "Robot Hardware Setup", checkEncoders, calibSensors, ["Start SoT", startSot], ["Walk test", execTestPattern2], " ", "OnOff", servoOn, servoOff, " ", "ChangePose", goInitial, goHalfSitting, " ", "etc:", saveLog, reboot, shutdown, ] expert_mod...
import math class BinaryHeap(object): def __init__(self): self.heap = [] def heap_size(self): return len(self.heap) def _heap_size(self): return len(self.heap) - 1 def add(self, elem): self.heap.append(elem) hs = self._heap_size() parent = math.ceil(h...
server = 'rally1.rallydev.com' apikey = '_LhzUHJ1GQJQWkEYepqIJV9NO96FkErDpQvmHG4WQ' workspace = 'Sabre Production Workspace' project = 'LGS' #rally = Rally(server, apikey=apikey, workspace=workspace, project=project)
import re import markdown import sys # taken from latex2wp def process_latex(content): def separatemath(m) : mathre = re.compile(r"\$.*?\$" r"|\\begin\{equation}.*?\\end\{equation}" r"|\\\[.*?\\\]") math = mathre.findall(m) text = mathre.split(m) return (math,text) def processmath(M) : R = []...
import random from deap import base from deap import creator from deap import tools
from django.db import models """ Модель артикуля. photo добавлять не обязательно. """ class Article(models.Model): manufacturer = models.CharField(max_length=150, default='default') name = models.CharField(max_length=100, default='default') barcode = models.BigIntegerField(default=0) photo =...
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.utils.crypto import get_random_string from django.db.models.signals import post_save from django.dispatch import receiver import pycount...
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height > 120: print("You can ride the roller coaster") age = int(input("What is your age?\n")) if age<12: print("You have to pay $5") elif age>12 and age<18: print("You have to pay $7 ") else: print("You h...
import numpy as np from .matcher import Matcher from scipy import optimize class HungarianMatcher(Matcher): def __init__(self, metric, sigma): super().__init__(metric) self.sigma=sigma def __call__(self, tracklets, detection_features): similarity_matrix = self.metric(tracklets, detecti...
import socket # HOST = 'localhost' # The remote host HOST = '10.20.96.141' PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data)
# Function to find best way to cut a rod of length n # where rod of length i has a cost price[i-1] def rodCut(price, n): # T[i] stores maximum profit achieved from rod of length i T = [0] * (n + 1) # consider rod of length i for i in range(1, n + 1): # divide the rod of length i into two rods...
from django.shortcuts import render from products.models import Product, SizeChart from .models import IndexCarousel def index(request): """ Render index page with carousel imgs, new in and bestseller products """ carousels = IndexCarousel.objects.all() all_products = Product.objects.all().filte...
import cookielib def rainbow(self,form): """fd03058401369729668d1dc2cdcc7525 curl --get --include 'http://apis.baidu.com/chazhao/md5decod/md5decod?md5=b035b895aae7ea345897cac146a9eee3369c9ef1' -H 'apikey:您自己的apikey' """ import urllib2,urllib cookie = cookielib.CookieJar() opener = urllib2.build_opener...
print("will it?") print("not sure")
from __future__ import annotations from functools import partial from pathlib import Path from typing import Callable, List, Optional, Union, overload from .base import PathableConcept from .exceptions import PackageNotFound from .graph import PackageGraph from .info import Info from .label import Label, ResolvedLabe...
# -*- coding: utf-8 -*- import sys # 自定義常用工具 # 用於NTL的代碼簡化和適配 __all__ = [ 'jsrange', 'jsstring', 'jsint', 'jsmaxint', 'jsfloor', 'jsceil', 'jsround', 'jskeys', 'jsvalues', 'jsitems', 'jssquare', 'jssign', 'jsappend', 'jsupdate' ] ##################################################################...
#!/usr/bin/env python # # # Third party dependencies: # # pyaudio: for audio input/output - http://pyalsaaudio.sourceforge.net/ # numpy: for FFT calcuation - http://www.numpy.org/ import argparse import numpy import struct import pyaudio import threading import struct from collections import deque import time from bi...
# prepare jsons that store doc info # 1. [(speaker_id, gender, dr, test_train)] # 2. all phones # dumped to "docjsons/" import __init__ from __init__ import * import json import utils import utils.sentence_access as access import itertools def do_speaker_info(): print("collecting speaker info") speaker_info...
from setuptools import setup setup(name='mongoimx', version='0.1', description='Criate a API to help document insertion in a mongo db in IMX line.', url='https://github.com/gustavu92/MO410-projeto_final', author='Caio Dadauto and Gustavo Vasconcelos', author_email='caiodadauto@gmail.com a...
import pygame from pygame.locals import * import util import colors class Display: def __init__(self): pygame.font.init() self.myfont = pygame.font.SysFont('helvetica', 30) self.background_blits = [] self.foreground_blits = ['ball'] self.scaled_blits = util.load_scaled_blits() self.blit_locations ...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys last1,last2,result,cntr=1,1,2,4 x = int(sys.argv[1]) if x <= 2: print("1") elif x==3: print("2") else: while(cntr<=x): last2 = last1 last1 = result result = last1+last2 cntr+=1 print(result)
import unittest from unittest.mock import MagicMock from models.questions import Questions from daos.questions_dao import QuestionsDAO from daos.daos_impl.questions_dao_impl import QuestionDaoImpl from service.questions_services import QuestionsServices from models.quizzes import Quizzes from daos.quizzes_dao import ...
#!/usr/bin/python3 def main(msg): print(msg) print("Hello World")
from django.db import models try: import simplejson as json except ImportError: import json class Grade(models.Model): """ The grade assigned to a particular ``approved.QActual`` question. """ # How much did the person score (can sometimes be negative, or in some # cases exceed the maximum...
def common_elements_in_sorted_arrays(arr1, arr2): sol = [] i, j, = 0, 0 while (i < len(arr1)) and (j < len(arr2)): if arr1[i] == arr2[j]: sol.append(arr1[i]) i += 1 j += 1 elif arr1[i] < arr2[j]: i += 1 else: j += 1 retu...
import numpy as np import cv2 import random img = cv2.imread('Houghcircles.jpg',0) blur = cv2.GaussianBlur(img,(3,3),1) v = np.median(blur) # apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0 - 0.43) * v)) upper = int(min(255, (1.0 + 0.43) * v)) edged = cv2.Canny(blur, lower, upp...
import math from hitable import Hitable from hit_record import HitRecord from vector import Vector class Sphere(Hitable): def __init__(self, center, radius): """ type center: Vector type radius: float """ self.center = center self.radius = radius def hit(self,...
#!/usr/bin/env python2 # social_client.py --- # # Filename: social_client.py # Description: # Author: Niels Zeilemaker # Maintainer: # Created: Mon Oct 28 14:10:00 2013 (+0200) # Commentary: # # # # # Change Log: # # # # # This program is free software; you can redistribute it and/or # modify it under the terms of th...
import pygame class Entity: def __init__(self, position, size, image_file, convert_image=False): self.position = position self.size = size self.width, self.height = self.size self.image = pygame.image.load(image_file).convert() if convert_image else pygame.image.load(image_file) ...
from django.contrib import admin from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns #import appuno.views from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = p...
HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36', }
N = int( input()) for _ in range(N): a, b = map( int, input().split()) if a == b: print(-1) else: print( abs(a-b))
from functions import create_batch import numpy as np import torch import torch.optim as optim from sklearn.preprocessing import PolynomialFeatures import re import torch.nn.functional as F from torch.autograd import Variable import logging import tqdm from config import logging_config use_cuda = torch.cuda.is_availab...
class WordCounter: def __init__(self): self class WordCounterImpl(WordCounter): def process(self, file_content_list): thisdict = {} for word in file_content_list: if word in thisdict: thisdict[word] = thisdict.get(word) + 1 else: ...
# -*- coding: utf-8 -*- # flake8: noqa # Generated by Django 1.10.7 on 2017-05-31 20:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('support', '0002_supportcategory'), ] operations = [ migratio...