text
stringlengths
8
6.05M
#!/usr/bin/env python3 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. ''' This script finds all HTML pages in a folder and downloads all images, replacing...
#str 타입 csv으로 변경 csv_values = """ 이름, 연락처, 나이, 이메일 철수, "010-1234-4567", 23, "chulsu@gmail.com" 영희, "010-1234-2345", 30, "234@naver.com" """ #첫과 마지막 줄을 지워죠. csv_values = csv_values.strip('\n') #스티링 csv_list = csv_values.split('\n') print(csv_list) # key 값 리스트 만들기 keys = [] for el in csv_list[0].split(','): key...
import api.helpers.endpoint_checks as endpoint_checks from seat.models.token import Token from django.http import HttpResponseServerError, JsonResponse def validate_token_success_json_model(exam_id): return JsonResponse({ 'success' : True, 'error' : False, 'exam_id': exam_id }) def va...
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db.models.signals impo...
from rdflib.namespace import RDF from source.utils import id2uri, g_add_with_valid import json import csv import glob def create_ttl(g, u, row): """ name: AP-1 transcription factor network pwacc: Pathway Interaction Database:ap1_pathway pwtype: organism_specific category: pathway url: http://pi...
""" John Eslick, Carnegie Mellon University, 2013 See LICENSE.md for license and copyright details. """ import os from PyQt5 import uic mypath = os.path.dirname(__file__) _optMessageWindowUI, _optMessageWindow = \ uic.loadUiType(os.path.join(mypath, "optMessageWindow_UI.ui")) class optMessageWindow(_optMessag...
from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, PickleType from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Member(Base): __tablename__ = 'member' id = Column(Integer, primary_key=True, nullable=False) name = Column(String(100), nullab...
#!/usr/bin/python3 # Copyright (C) 2019 Aleksa Sarai <cyphar@cyphar.com> # Licensed under MIT. import requests STORE_URL = lambda key: "https://store.ncss.cloud/%s" % (key,) def fetch(key): resp = requests.get(STORE_URL(key)) if not resp.ok: raise KeyError("key not present in store") return resp.json() def sto...
print(""" Short Tutorial on Dictionaries ------------------------------ Dictionaries are a poor man's object, akin to structs in other languages. Think of them like arrays (or lists), except instead of each element having an index that defines its position in the array, each element is defined and accessed by a k...
# -*- coding: utf-8 -*- from typing import List class Solution: def countGoodRectangles(self, rectangles: List[List[int]]) -> int: max_square_side_length, result = float("-inf"), 0 for length, width in rectangles: square_side_length = min(length, width) if square_side_leng...
def test(n): for i in range(1, n, 2): if n == i*(i + 2): return True return False for j in range(0, 1000): a = (4*(j**3)) - (3*j) if test(a) == True: print(j) ''' j = 0 while(1): a = (4*(j**3)) - (3*j) if test(a) == True: print(j) j = j + 1 '''
# # Print out list of students. students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def classroom(dict): for item in range(0, len(dict)):...
#!/usr/bin/env python # Copyright (C) 2015 Dmitry Rodionov # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from ..dtrace.apicalls import apicalls import inspect from sets import Set from os import sys, path def choose_package_class(file_type, fi...
from testutil import * import numpy as np import smat # want module name too from smat import * import timeit import os,os.path import matplotlib matplotlib.use('Agg') # off-screen rendering import matplotlib.pyplot as plt ####################################################################### def _apply_unary...
import math import matplotlib.pyplot as plt import numpy as np from scipy import integrate def EulerIntegrator(h, y0, f): """ Делает один шаг методом Эйлера. y0 - начальное значение решения в момент времени t=0, h - шаг по времения, f(y) - правая часть дифференциального уравнения. Возвращает ...
from flask import flask app= Flask() @app.route('/') def index(): return "Home Page" @app.route('/page2') def hello(): return "Welcome to page 2" @app.route('/user/<username>') def show_user_profile(username): return 'Hey there %s' % username @app.route('/post/<int:post_id>') def show_post(post_id): r...
class ConfigParser(): content = '' config_dict = {} def _parse(self): self.content = self.content.replace('\r', '') content = self.content lines = content.split('\n') for line in lines: if line.startswith('#'): continue if line.starts...
import os print(__file__) abspath=os.path.abspath(__file__) print(abspath) dir_path=os.path.dirname(abspath) print(dir_path) file_path=dir_path+"\sample.html" print(file_path) print(os.path.join(dir_path,"sample.html"))
import sqlite3 conn = sqlite3.connect('RRTS_DB.db') class __ResidentsSchema: def __init__(self): self.curs = conn.cursor() conn.execute(''' CREATE TABLE IF NOT EXISTS "Complaints" ( "complaintId" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "roadLocation" TEXT NOT NULL...
# -*- coding: utf-8 -*- # filename: Console.py import profile import sys def run(coroutine): try: coroutine.send(None) except StopIteration as e: return e.value while True: print ('input :') value = sys.stdin.readline() print(value)
from Tkinter import * import time #import dbi, odbc from socket import * bits = 0 # 0 = 8 bits, 1 = 12 bits # xxx [] = [ {8bits}, {12 bits}] one_g = [40,624] num_loop = 5000 max_value = one_g[bits]*2 min_value = one_g[bits]*2*(-1) shift = [170,2800] def show2(self): print "2" def TestConn(self): #import m...
"""django_informixdb: Django Informix database driver""" from .version import VERSION
from __future__ import absolute_import import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from models.basic_conv import BasicGraphConv from models.graph_atrous_conv import GraphConv from models.enc_dec import Enc_Dec from models.graph.h36m_graph import AdjMatrixGraph from models.g...
class BankAccount: NEXT_ACC_NUMBER = 1 def __init__(self): self.cash = 0.0 BankAccount.NEXT_ACC_NUMBER += 1 def deposit_cash(self, amount): if not isinstance(amount, float) and amount <= 0.0: raise ValueError("Deposit can't be negative!") self.cash += amount ...
import pandas as pd import numpy as np import talib as ta import tushare as ts import matplotlib.pyplot as plt def BBANDS(ts_code,timeperiod=14,k=0.5): dw = ts.get_k_data(ts_code) dw = dw[10:] dw.index = range(len(dw)) dw['upper'], dw['middle'], dw['lower'] = ta.BBANDS( dw....
from ..actions.session import init_session, get_session_analysis, get_session_analysis_deprecated from ..actions.elo import get_player_info FUNCTION_PER_COMMAND = { 'faceit_elo': get_player_info, # TODO: Replace this with get_session_analysis when FACEIT API gets FIXED 'faceit_session': get_session_anal...
""" Testing brain segmentation module """ import numpy as np from numpy.testing import (assert_almost_equal, assert_array_equal) from nose.tools import (assert_true, assert_false, assert_raises, assert_equal, assert_not_equal) from ..brain_segmentation import brain...
from flask import Flask, request from flask_cors import CORS, cross_origin from flask_restful import Resource, Api from json import dumps from flask_jsonpify import jsonify import psycopg2 import jinja2 app = Flask(__name__) api = Api(app) CORS(app) def initDB(): conn_string = "host='ec2-54-83-50-145.compute-1.am...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 13 17:01:32 2019 @author: thomas """ #In this script, we will be using the expansion and compression displacement # data created by PRQuantitative.py #We will attempt to find a fit for the data SSL and LSL #The fit will be based on 3 parameters: Re...
#!/usr/bin/python def displayPathtoPrincess(n,grid): if grid[0][0] == 'p' or grid[0][0] == 'P' : dir1 = "LEFT" dir2 = "UP" elif grid[n-1][n-1] == 'p' or grid[n-1][n-1] == 'P' : dir1 = "RIGHT" dir2 = "DOWN" elif grid[n-1][0] == 'p' or grid[n-1][0] == 'P' : dir...
from __future__ import (absolute_import, division, print_function, unicode_literals) import copy import numpy as np class CommunityDetector(object): def __init__(self, adj_dict): """ adj_dict is an adjacency list of node: neighbors. make sure adj_dict has no duplicates. num_stubs =...
import requests import re import time from multiprocessing import Pool headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } def re_scraper(url): res = requests.get(url,headers=headers) ids =re.findall('<h2>(....
from plotter import plotter import sys from Jsonreader import Jsonreader from Csvreader import Csvreader def plotWithGroups(plotting,apartmentdict, xaxis, yaxis, group, IsGroupBuildingdict, selectbypair ): listx=[] listy=[] listz=[] for a in apartmentdict: ap = apartmentdict[a] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from common.desired_caps import appium_desired from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from common.common_fun import Commom class Log...
import glob, os, pexpect, pytest, sys, time from forge.tests.common import mktree, defuzz, match from forge.tasks import sh DIR = os.path.dirname(__file__) SPECS = [os.path.relpath(n, DIR) for n in glob.glob(os.path.join(DIR, "*/*.spec"))] + \ [os.path.relpath(n, DIR) for n in glob.glob(os.path.join(DIR, "*.s...
#--encoding: utf-8 -- import scipy as sp class Lattice(object): """Grid of dipoles with nearest-neighbour interactions 2D grid of dipoles which can either point up or down. Every pair of anti-parallel neighbours adds one unit of energy. On every simulation step, the lattice evolves by always minimizin...
import requests import os from twilio.rest import Client STOCK_NAME = "TSLA" COMPANY_NAME = "Tesla Inc" STOCK_ENDPOINT = "https://www.alphavantage.co/query" NEWS_ENDPOINT = "https://newsapi.org/v2/everything" STOCK_API_KEY = os.environ.get("STOCK_API_KEY") NEWS_API_KEY = os.environ.get("NEWS_API_KEY") SMS_API_KEY ...
from govr.test_runner import TestRunner def coverage_report(weights): report = [ "============================================================", " GOVRAGE REPORT ", "============================================================" ] report.extend(["[ %s ] -> [ %s%% ]"...
""" ゼロから学ぶスパイキングニューラルネットワーク - Spiking Neural Networks from Scratch Copyright (c) 2020 HiroshiARAKI. All Rights Reserved. """ import numpy as np import matplotlib.pyplot as plt def stdp_ltp(dt, a=1.0, tc=20): """ Long-term Potentiation """ return a * np.exp(-dt / tc) def stdp_ltd(dt, a=-1.0, tc=20): ""...
import dash_bootstrap_components as dbc list_group = dbc.ListGroup( [ dbc.ListGroupItem("Item 1"), dbc.ListGroupItem("Item 2"), dbc.ListGroupItem("Item 3"), ] )
def number_of_occurrences(element, sample): return sample.count(element) ''' Write a functionthat returns the number of occurrences of an element in an array. Examples sample = [0, 1, 2, 2, 3] number_of_occurrences(0, sample) == 1 number_of_occurrences(4, sample) == 0 number_of_occurrences(2, sample) == 2 number_...
import os def clear(archiveDir): print("CLEARING ARCHIVE") for filename in os.listdir(archiveDir): os.remove(archiveDir + "/" + filename) print(" -- Deleted " + filename)
# -*- coding: utf-8 -*- { 'name': "EHCS Login Captcha", 'summary': """ Add reCAPTCHA in your login page.""", 'description': """ CAPTCHA stands for Completely Automated Public Turing Test to Tell Computers and Humans Apart. It's goal is to check if a user is a real person or a bot. ...
# '##::::'##::::'###::::'##::: ##:'####:'########:'##:::'##:'##::::'##:'##::: ##:'########:'##::::'##: # ##:::: ##:::'## ##::: ###:: ##:. ##::... ##..::. ##:'##:: ###::'###: ###:: ##: ##.....:: ###::'###: # ##:::: ##::'##:. ##:: ####: ##:: ##::::: ##:::::. ####::: ####'####: ####: ##: ##::::::: ####'####: # ##:::: #...
from pyramid.config import Configurator from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.exceptions import NotFound from frontend_manager.py.utils.security import groupfinder, RootFactory from shared.BaseConfig import BaseConfig from s...
# -*- coding: utf-8 -*- from app.models.meta import metadata, Base from app.models.users import User from app.utils import Enum from sqlalchemy import Table, Column, Integer, String, ForeignKey, DateTime from sqlalchemy.orm import mapper, relationship import datetime import web results_table = Table( "...
from django.db import models from django.urls import reverse # from django.utils.text import slugify # Create your models here. class Posts(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=50) content = models.TextField() def publish(s...
import sys import os import glob from distutils.core import setup setup( name="experiments", version='0.1', description='Python numerical experiments engine', author='Tigran Saluev', author_email='tigran.saluev(at)gmail.com', url='http://github.com/Saluev/python-experiments', packages = ['e...
import PagePost import RandomMeme import time import syslog actual_meme = 1 folder = "/home/marisa/Programas/AutismBot/" meme = RandomMeme.Conscious_Meme(folder) minutes = 30 ver = "AutismBot v1.3" seconds = minutes * 60 syslog.openlog('AutismBot') syslog.syslog("Bot iniciado") while True: try: meme ...
import json from unittest import TestCase from unittest.mock import patch from app.adapter import PokemonsRequest from tests.fixtures.mocks import API_MOCK_RESPONSE from app import app class ServiceTestCase(TestCase): def setUp(self): self.app = app self.app_context = self.app.app_context() ...
import youtube_dl import variables as var def get_playlist_info(url, start_index=0, user=""): items = [] ydl_opts = { 'extract_flat': 'in_playlist' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: attempts = var.config.getint('bot', 'download_attempts', fallback=2) for i in range(...
from utility import generate_data, average from linear import linear_sort, linear_inline_sort from time import time times = [] num_tests = 1000000 for i in range(num_tests): set = generate_data(5) end_index = len(set) - 1 start = time() # linear_inline_sort(set, 0, end_index) linear_sort(set) ...
## Pre-processing and library importing. import csv import cv2 import matplotlib.image as mpimg import numpy as np import os import tensorflow as tf current_dir = os.getcwd() lines = [] from keras.preprocessing import image from keras.models import Model from keras.layers import Dense, GlobalAveragePooling2D, Dropout...
from django.urls import path, re_path from .views import ( Dashboard, DashboardPrint, # InputUndss, InputUndssView, InputMasterIncidentView, # ImportDataView, UndssDetailView, MasterIncidentDetailView, get_district, get_area_city, get_incident_subtype, load_district, ...
# Generated by Django 3.2.8 on 2021-10-28 06:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chatbot', '0001_initial'), ] operations = [ migrations.AlterField( model_name='intentsamples', name='product_ref', ...
import unittest import os import json import time from six.moves import urllib from click.testing import CliRunner import unfurl.configurators # python2.7 workaround import unfurl.configurators.shell # python2.7 workaround import unfurl.configurators.supervisor # python2.7 workaround from unfurl.yamlmanifest import...
import asyncio import os import unittest from urllib.error import URLError from aiohttp import ClientConnectorError from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN from integration_tests.helpers import async_test from slack import WebClient class TestWebClient(unittest.TestCase): def ...
#1 import math a = int(input("enter a ")) b = int(input("enter b ")) c = int(input("enter c ")) D = b**2 - 4 * a * c print(D) if D < 0: print("The result is a complex value") elif D == 0: x = -b / 2 * a else: x1 = ((-b + math.sqrt(D)) / (2 * a)) x2 = ((-b - math.sqrt(D)) / (2 * a)) ...
'''Common dataclasses''' from datetime import datetime class NewsArticle: headline: str publish_on: datetime content: str
import sys from lib.intcode import Machine if len(sys.argv) == 1 or sys.argv[1] == '-v': print('Input filename:') f=str(sys.stdin.readline()).strip() else: f = sys.argv[1] verbose = sys.argv[-1] == '-v' for l in open(f): mreset = [int(x) for x in l.strip().split(',')] class SpringDroid: def __init__(self...
"""" Tarea # 1: Tarea1 ##COMENTARIO integrantes: Almaraz Garcia Iori Alejandro(AGIA) Carrillo Medina Alexis Adrian(CMAA) Nombre del programa: Tarea1 """ # ----- seccion de bibliotecas . import numpy as np import matplotlib.pylab as plt # ----- #-------------------------------------------------------------------...
import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import fetch_mldata from chainer import cuda, Variable, FunctionSet, optimizers import chainer.functions as F from xlwings import xrange plt.style.use('ggplot') batchsize = 100 n_epoch = 20 n_units = 1000 # MNISTの手書き数字データのダウンロード # #HOME/scikit...
from django.db import models # Create your models here. class Eleicao (models.Model): local = models.CharField(max_length=20) dataInicio = models.DateTimeField(blank=False, null=False) dataFim = models.DateTimeField(blank=False, null=False) class Token (models.Model): codigo = models.CharField(m...
import tensorflow as tf import tensorflow_compression as tfc import functions def one_step_rnn(tensor, state_c, state_h, Height, Width, num_filters, scale, kernal, act): tensor = tf.expand_dims(tensor, axis=1) cell = functions.ConvLSTMCell(shape=[Height // scale, Width // scale], activation=act, ...
from office365.sharepoint.base_entity import BaseEntity class EventReceiverDefinition(BaseEntity): pass
import socket def recv_msg(udp_socket_recv): """接收消息""" recv_data = udp_socket.recvfrom(1024) print("%s:%s" % (str(recv_data[1]),recv_data[0].decode("utf-8"))) def main(): """client_recv用于实现用户端对服务端的全时监听""" udp_socket_recv = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #绑定信息 udp_socket_recv.bind(("",7788)...
print('hello world') #import pandas as pd a=1223567
# Questão 2 - Lista Telefônica Econômica n = int(input()) lista_tel = [] #n = 3 #lista_tel = [[5,3,5,4,5,6],[5,3,5,4,8,8],[8,3,5,4,5,6]] #n = 2 #lista_tel = [[1,2,3,4,5],[1,2,3,5,4]] max = 0 # leitura da lista for i in range(n): num = list(input()) lista_tel.append(num) # procurar a linha com maior numero econ...
from tkinter import * from PIL import Image,ImageTk class Window(Frame): def __init__(self,master=None): Frame.__init__(self,master) self.master = master self.init_window() def init_window(self): self.master.title("Hello Tkinter") self.pack(fill=BOTH,expand=1) ...
#insertion, deletion or substitution global words def edit_distance(s1,s2): m=len(s1)+1 n=len(s2)+1 tbl = {} for i in range(m): tbl[i,0]=i for j in range(n): tbl[0,j]=j for i in range(1, m): for j in range(1, n): cost = 0 if s1[i-1] == s2[j-1] else 1 tbl[i,j] =...
#!/usr/bin/env python from __future__ import print_function import fastjet as fj import fjcontrib import fjext import tqdm import argparse import os import numpy as np import array import copy import random import uproot import pandas as pd from pyjetty.mputils import logbins from pyjetty.mputils import MPBase from...
#coding=utf-8 __author__ = 'shifx' from django.views.decorators.csrf import csrf_exempt #用于处理post请求出现的错误 from research_report.models import ReportUser from django.shortcuts import render_to_response from research_report.thread import ThreadControl #主页面 def report_main(request): # ProbTotals.objects.all().delet...
class Solution(object): def cloneGraph(self, node): def dfs(node): if node in map: return map[node] clone = Node(node.val, []) map[node] = clone for nei in node.neighbors: clone.neighbors.append(dfs(nei)) return clone ...
# # (C) Copyright 2012 Enthought, Inc., Austin, TX # All right reserved. # # This file is open source software distributed according to the terms in # LICENSE.txt # import threading from traits.api import HasTraits, Bool, Int, Str, Enum, Tuple, Set, Instance, Property from .animated_context import AbstractAnimatedCo...
from PyQt5 import QtCore, QtGui, QtWidgets#, QtWidgets.QFileDialog #from PyQt5 import *#.QtWidgets import QFileDialog #from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog #from PyQt5 import QtCore, QtGui, QtWidgets import pyodbc import sys, os import copy import datetime...
Battle = int(input("대결 횟수 : ")) count = 0 round = 1 while count < Battle: Ulist = [] #["Busan","Seoul","Ewha"] Dlist = [] #[100,400,300] => max(Dlist) => Dlist.index(400) uni_input = int(input("%s회차 비교 학교 수 : "%round)) while uni_input > 0: name = input("대학이름 : ") drink = int(inp...
from script.base_api.service_identity.versionInfo import *
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from utils.AverageMeter import AverageMeter from utils.criterion import * import warnings warnings.filterwarnings('ignore') #######################################################################...
import pygame import sys import random from pygame.locals import * clock = pygame.time.Clock() pygame.init() pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 14) WINDOW_SIZE = (896, 560) pygame.display.set_caption('Platformer') screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32) display = pygame.Surfa...
class Vehicle: def __init__(self,name,color): self.__name=name self.__color=color def getColor(self): return self.__color def setColor(self,color): self.__color=color def getName(self): return self.__name class Car(Vehicle): def __init__(sel...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ##################################################################################### # # # print_html_page.py update/create html page related acis does plots ...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from dataclasses import dataclass from typing import Iterable from pants.backend.python.goals import lockfile from pants.backend.python....
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
"""Script that extracts,crops and stores images in black and white in a new folder using OpenCVs Deep Neural Network (Pre-trained for face Detection). Script is adapted from several sources, with parts taken from each of the following: 1. van Gent, P. (2016). Emotion Recognition With Python, OpenCV and a Face Dataset. ...
import numpy as np from scipy.stats import norm def simple_co_model(hi, fir, w_co, offset_centre=0., offset_scale=0.5, x_co_centre=2., x_co_scale=0.5): def lnlike(p): theta, offset, x_co, stddev = p # N = len(hi) # diff = (fir - np.tan(theta) * (hi...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from ast import literal_eval from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.metrics.pairwise import linear_kernel, cosine_similarity from nltk.stem.snowball imp...
#!/usr/bin/env python3 from sys import argv """ Version 3: as fast as version 2 (it now uses list comprehensions to store all palindromes in a tuple and count occurrences). Finds palindromes greater than X characters. It also prints: - the size of the longest palindrome - the size of the s...
import os import optparse import time from threading import Timer import requests import chardet from BeautifulSoup import BeautifulSoup class Crawler(object): def __init__(self, url, outfile): """ :param url: url to Crawling :param outfile: Place output """ self.url = url...
from .pages.product_page import ProductPage from .pages.login_page import LoginPage import pytest from .pages.basket_page import BasketPage import time @pytest.mark.user_add_to_basket class TestUserAddToBasketFromProductPage: @pytest.fixture(scope="function", autouse=True) def setup(self, browser): lo...
from __future__ import print_function import torch.utils.data as data import os import glob from PIL import Image from utils import preprocess class OurDataset(data.Dataset): CLASSES = [ "background", "road", "side-walk", "people", "car", "building", "bridg...
# -*- coding: utf-8 -*- """ Created on Fri Mar 18 23:34:37 2016 A 0MQ Client to dispatch messages to other services to get required information @author: alex """ import zmq import json class ServiceConnector(object): def __init__(self, discovery_conn, inbound_connection_info, logging): #Es...
# -*- coding: utf-8 -*- from typing import List class Solution: def destCity(self, paths: List[List[str]]) -> str: starts, ends = set(), set() for (start, end) in paths: starts.add(start) ends.add(end) return ends.difference(starts).pop() if __name__ == "__main__...
import csv d={'1':'__label__NEUTRAL','0':'__label__NEGATIVE','2':'__label__POSITIVE'} l=[] with open('train.csv','rt')as f: data = csv.reader(f) for row in data: l.append(row) with open('actual_train.txt','a') as f: for i in range(len(l)): s=l[i][0]+' '+l[i][1]+'\n' f.write...
# -*- coding: utf-8 -*- from at import interfaces from zope.schema.vocabulary import SimpleVocabulary from zope.app.component.hooks import getSite from zope.app.pagetemplate import ViewPageTemplateFile vendorImages={"Alfa Romeo":"/media/237459/1.jpg", "Audi":"/media/237462/2.jpg", "BMW":"/m...
'''Write a function bestSum(targetSum, numbers) that takes in a targetSum and an array of numbers as arguments The function should return an array containing the shortest combination of numbers that add up to exactly the targetSum If there is any tie for the shortest combination, you may return any one of the shortes...
""" Django settings for pympm project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # ...
from flask import Flask, json, jsonify ,render_template from flask import request import requests from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow order_counter=1 catalog_counter=1 #front end tier will send requests to order server and catalog server cache_size = 5 id_count = {} #in...
# coding: UTF-8 __author__ = 'Steeve' __version__ = '1.0.0' import os import re import argparse from beautifultable import BeautifulTable as btft class GenericAplication(): def __init__(self, arquivo, namearq, display ,binaryfile ,textfile): self.arquivo = arquivo self.namearq = namearq se...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import shutil DOC_DIR = "." AMAO_DIR = "../AMAO" def generate_rst_for_app(app,excludes=None): "Cria os arquivos .rst para a app em questao usando o sphinx-apidoc" command_template = "sphinx-apidoc -f -o %(APP_DOC_DIR)s %(APP)s %(EXCLUDES)s" ...
# Generated by Django 2.2.2 on 2019-07-06 09:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('task', '0003_auto_20190619_1247'), ] operations = [ migrations.AlterField( model_name='task', name='contribution', ...