text
stringlengths
8
6.05M
# I pledge my honor that I have abided by the Stevens Honor Code # Riley Sikorski #This program will accept a list of numbers #It will return the sum of the numbers in the list def main(): print("This program will accept a list of numbers and squares them all. ") list = [] n = eval(input("Please enter th...
import os, random, socket, urllib from Game import host, Status, Power, Game, Mail, View, Time, TimeZone from Map import Map class Page: # ---------------------------------------------------------------------- def __init__(self, form = {}): # --------------------------------------------------- # Parameters that...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Artist.description' db.delete_column('artists_artist', 'description') # Deletin...
import time from pyspark.sql import SQLContext from pyspark import SparkContext, SparkConf import sys from glob import glob from pyspark.sql.types import * from decimal import * from pyspark.sql import * # Receive as parameter the Scale Factor SF=sys.argv[1] conf = SparkConf().set('spark.memory.fraction', '1.0').se...
from setuptools import setup, find_packages from patchworkdocker.meta import VERSION, DESCRIPTION, PACKAGE_NAME, EXECUTABLE_NAME setup( name=PACKAGE_NAME, version=VERSION, author="Colin Nolan", author_email="cn580@alumni.york.ac.uk", packages=find_packages(exclude=["tests"]), install_requires=...
""" ================ Disease Observer ================ This module contains tools for observing disease incidence and prevalence in the simulation. """ from collections import Counter import pandas as pd from .utilities import (get_age_bins, get_prevalent_cases, get_state_person_time, get_tr...
#!/usr/bin/python -tt # # Copyright (c) 2011 Intel, Inc. # # 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; version 2 of the License # # This program is distributed in the hope that it will be us...
import logging import os from sklearn import tree class DecisionTree(): """This class represents a decision tree classifier for IoT devices. It is used to train a DT using the number of unique ips as a feature between an IoT device and a non-IoT. It parses the .dat files produced in other analysis. ...
from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import json from bs4 import BeautifulSoup # If modifying these scopes, delete the file token.pickle. S...
import urllib.request # urllib.request.urlretrieve('http://www.hellobi.com',filename='1.html') #爬取网页存储 # urllib.request.urlcleanup() #清除缓存 # file=urllib.request.urlopen('http://www.hellobi.com',timeout=1) #实现对目标url的访问 timeout为超时,崩了为超时 # print(file.getcode()) #获取访问的状态码 # print(file.geturl()) #获取获取的URL for i in ran...
from datetime import datetime from constants import IDLE import logging from utils import clamp from rules_manager import RulesManager from history_manager import HistoryManager from application_definition import ApplicationDefinition class AutoScaler(object): """ The source of the scaling decision. """ ...
# -*- coding: utf-8 -*- """ Created on Tue Mar 10 17:31:36 2020 @author: white """ import numpy as np import scipy.stats as sts import matplotlib.pyplot as plt import scipy.constants as sc import scipy.special as scp import timeit start = timeit.default_timer() plt.close('all') fig = plt.figure() ax1 = plt.subplot2...
# Python script that builds timeseries prophet models (72) for each merchant user # and predicts the total number of product sales. Tests results for previous month # and predicts for future month. # Script packages results in a csv file and sends it via email. import warnings from datetime import datetime, timedelta...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: step01_check_valid_country_list # @Date: 2020/3/6 # @Author: Mark Wang # @Email: wangyouan@gamil.com """ python -m SortData.ConstructVariable.step01_check_valid_country_list """ import os import pandas as pd from pandas import DataFrame from Constants impo...
NIinf=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'] PAas=int(input()) if 1<=PAas<=10: print(NIinf[PAas-1])
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn import svm, neural_network, naive_bayes from sklearn.linear_model import Perceptron Attributes = pd.read_csv("hm_hospitales_covid_structured_30d_train.csv", na_values=0, na_filter=True) Outcomes = pd.read_csv("spli...
import socket import time import threading from queue import Queue NUMBER_OF_THREADS = 2 JOB_NUMBER = [1, 2] queue = Queue() all_connections = [] all_addresses = [] # Create Socket (allow to computer communicate) def socket_create(): try: global host global port globa...
person = { "name": "Tung", "age" : 21 } print(person) print(person == {'name'}) if(person == {'name'}): print('key ‘nationality’ does not exist in my dictionary') else: print('key ‘name’ exists in my dictionary')
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='move-my-files', version='0.2.4', description='CLI tools to organize files on your comput...
import math r = {1 : "radius R", 2 : "diametr D", 3 : "length L", 4 : "are circle S"} c = [] i =int(input("i= ")) print(i) N = float(input("")) print(r[i],":",N) if i == 1: R = N c.append(R) c.append(2 * R) c.append(2 * math.pi * R) c.append(math.pi * R**2) elif i == 2: D = N R = D / 2 ...
from model import ENModel, val_transform from data import UnlabeledImagesDataset, ImageCsvDataset import torch import torch.utils.data import torch.nn.functional as F import csv import re from pathlib import Path import os.path from pytorch_lightning.metrics.classification import ConfusionMatrix from argparse import A...
from distutils.core import setup import py2exe setup(console=['test.py'], options = {"py2exe": {'includes':'decimal'}})
import tornado.web import config from views import index class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/', index.IndexHandler), ] super(Application,self).__init__(handlers, **config.settings)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def maxDepth(self, root): """ :type root: TreeNode :rtype: int ...
from itertools import izip_longest def transpose_two_strings(arr): output = '{} {}'.format return '\n'.join(output(*a) for a in izip_longest(*arr, fillvalue=' '))
from flask_admin.contrib.sqla import ModelView from wtforms import TextAreaField from wtforms.widgets import TextArea class CKTextAreaWidget(TextArea): def __call__(self, field, **kwargs): if kwargs.get('class'): kwargs['class'] += " ckeditor" else: kwargs.setdefault('class...
# Copyright 2022 NVIDIA 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 in wr...
from flask import request, session, make_response, jsonify from flask_restx import fields, Resource, Api, Namespace from flask_cors import CORS, cross_origin from werkzeug import FileStorage from werkzeug.datastructures import ImmutableMultiDict from pytezos import Contract, Key from pytezos import pytezos from pytezo...
import random from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np from src.evaluator import ModelBasedEstimator, DoublyRobustEstimator, IPSEvaluator from src.main import simulation from src.policy import RandomPolicy, DeterministicPolicy, CBVowpalWabbit def create_plot(PolicyClass, policy_name):...
# -*- coding: utf-8 -*- """ ytelapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class Body(object): """Implementation of the 'body' model. TODO: type model description here. Attributes: mfrom (string): A valid Ytel Voice enabled ...
from django.shortcuts import render from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.shortcuts import redirect from django.contrib.auth.models import Group from django.contrib.auth.decorators import login_required from all...
""" Carbon Core ########### :Author: Juti Noppornpitak """ from contextlib import contextmanager from imagination.helper.assembler import Assembler from imagination.helper.data import Transformer # from imagination.entity import CallbackProxy from imagination.entity import Entity from imagination.loader impo...
from typing import List from gensim.models import Doc2Vec as GensimDoc2Vec from kts_linguistics.string_transforms.abstract_transform import AbstractTransform from kts_linguistics.string_transforms.transform_pipeline import TransformPipeline from kts_linguistics.misc import Vector1D class Doc2VecTransform(AbstractTr...
import numpy as np from stat_util import get_best_distribution import scipy.stats as st class REPD: def __init__(self,dim_reduction_model,error_func=lambda x: np.linalg.norm(x,ord=2,axis=1)): self.dim_reduction_model = dim_reduction_model self.dnd = None #Distribution non defect ...
#6*6的棋盘求最大路径 import random global count totalprice=0 tmp=0 count=0 a=[[0 for i in range(6)]for i in range(6)] b=[[0 for i in range(6)]for i in range(6)] next=[[1,0],[0,1]] def find(x, y): global totalprice global tmp totalprice+=a[x][y] if x==5 and y==5: if totalprice>tmp: tmp=totalp...
""" This program uses a Monte Carlo simulation to randomly generate the army compositions used in our linear program. Requires the file sim_units.py and the random package """ import random from sim_units import get_Units, get_Terran, get_Protoss, get_Zerg import json def init_army_comps(race, supply_cap=20...
import nltk import math import numpy as np import pandas as pd import tensorflow as tf import os,sys import GPyOpt from sklearn.base import clone from sklearn.metrics import confusion_matrix from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import LabelEncoder,LabelBinarizer from s...
# File: main.py # Auth: David Cerny # Date: 26/07/2021 ################################################## """ Find the nth number in the Fibonacci sequence """ import argparse def calculate_fib_number(n): assert n >= 0, "n must be non-negative!" if n == 0: return 0 elif n == 1: return 1...
# Bài 10: Viết hàm đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n cho trước. # Ví dụ: Hàm trả về 4 nếu n là 19922610 (do n có 4 số lẻ là 1, 9, 9, 1) def dem(n) : if n == 0 : return 0 else : if (n%10)%2 != 0 : return 1 + dem(int(n/10)) else : ...
class Config: FPS = 9 MENU_FPS = 60 WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 CELLSIZE = 20 assert WINDOW_WIDTH % CELLSIZE == 0,"Window width must be a multiple of cellsize" assert WINDOW_HEIGHT % CELLSIZE == 0,"Window height must be a multiple of cellsize" CELLWIDTH = int(WINDOW_WIDTH/CELL...
import time from enum import Enum BLOCK_SIZE = 2**14 class State(Enum): FREE = 0 PENDING = 1 COMPLETE = 2 class Block(): def __init__(self, size=BLOCK_SIZE): self.state = State.FREE self.last_seen = 0 self.size = size self.data = b'' def flush(self): self.d...
#!/usr/bin/python3 # -*- coding:utf-8 -*- import requests import json import queue from locust import HttpUser,TaskSet,task,between class Ncar_Login(TaskSet): @task(1) def work_user_top(self): headers={"content-type":"application/json"} data={"data":{"channel":1,"algorithm":"BASE64","passWd":"YWJjLjEyMw==","user...
# -*- python -*- from flask import Flask, render_template, redirect, request, session app = Flask( __name__ ) app.secret_key = "CounterSecretKey" @app.route( '/' ) def index(): if 'counter' not in session: session['counter'] = 1 else: session['counter'] += 1 return( render_template( "inde...
import unittest from katas.kyu_7.product_of_main_diagonal import main_diagonal_product class MainDiagonalProductTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(main_diagonal_product([[1, 0], [0, 1]]), 1) def test_equals_2(self): self.assertEqual(main_diagonal_product( ...
from os.path import abspath, dirname, join, exists import yaml def find_config(config_filename): """ Return the default config file location. Normally this is the package installation directory, except when install in develop mode or using pytest. If in develop mode, the config file is in the package ...
#The "assert" keyword can be used to check the input data for validity. # If the assert condition is not true, the program quits with the "AssertionError" exception (if you did not catch it). def aun(x,y): assert x!=2 return x*y print(aun(3,2)) #ok print(aun(2,4)) #error x!=2
# Generated by Django 3.0.7 on 2020-07-21 17:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0004_auto_20200623_1522'), ] operations = [ migrations.AddField( model_name='course', name='interested', ...
#!/usr/bin/env python # coding: utf-8 # https://github.com/usnistgov/iprPy import iprPy if __name__ == '__main__': iprPy.command_line()
from __future__ import print_function, absolute_import import logging import re import json import requests import uuid import time import os import argparse import uuid import datetime import socket import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText, textio from...
#!/usr/bin/env python """ plugin_classifier.py v0.1 Given a list of VOSource XML strings, or filepaths, this generates classifications by calling WEKA and other classifier code. Returns information in classification dictionaries. """ import sys, os import copy sys.path.append(os.environ.get("TCP_...
from typing import List import json import math class BaseFixture(object): def __init__(self, x:int, z:int): self.type = "7-pixel-base" self.x = x self.z = z class Protocol(object): def __init__(self, host:str, universe:int, start:int, num:int): self.host = host self.protocol = "artnet" se...
#Saumit Madireddy #I pledge my Honor that I have abided by the Stevens Honor System #I understand that I may access the course textbook and course lecture notes but #I am not to access any other resource. I also pledge that I worked alone on this exam. def main(): menu() def menu(): choice = input(""" Fo...
# Generated by Django 3.2 on 2021-05-28 15:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Case', fields=[ ...
n=input() listn=[int(x) for x in raw_input().split(" ")] m=input() list_label=[int(x) for x in raw_input().split(" ")] list1=[0] for i in listn: list1.append(i+list1[-1]) list1.remove(0) def send(N,list2,ind): a=len(list2) if a==1: if N<=list2[0]: print ind else: print ind+1 elif N<list2[a/2]: send(N,li...
import io from io import UnsupportedOperation class S3StreamObj(io.RawIOBase): # https://alexwlchan.net/2019/02/working-with-large-s3-objects/ def __init__(self, s3file,prefix=""): self.s3_object = s3file self.position = 0 self.size = self.s3_object.content_length self.totalbytes = ...
import _BNode import bisect class _BPlusLeaf(_BNode): __slots__ = ["tree", "contents", "data", "next"] def __init__(self, tree, contents=None, data=None, next=None): self.tree = tree self.contents = contents or [] self.data = data or [] self.next = next assert len(self...
# -*- coding: utf-8 -*- import os from itertools import imap from operator import itemgetter from avl_tree import AVLTree from helpers import (treatment_add_del, find_polygon, l, calc_Y, get_row_dict, update_dict_vals) ALL_XS = [[-181, AVLTree()], ] # runs throughout ALL_XS # stopped = 0 # d...
inp=input("enter list items:") etc=inp.split() for values in etc: for i in range(int(values)): print('*',end="") print("\n") ''' other way inp=input("enter list items:") etc=inp.split() x=len(etc) y=int(x) for values in etc: y=int(values) print("\n") while(y>0): print("*",end="") ...
class NodoPila : def __init__(self,valor ,anterior=None): self.valor = valor self.anterior = anterior def getValor(self): return self.valor def getAnterior(self): return self.anterior class Pila : def __init__(self): self.size = 0 self.nodo = None ...
import utility from flask_jwt_extended import jwt_required from flask import request from flask_restful import Resource from connection import db_session, commit from models.sys_rmodul import SysRmodul class GetRmodul(Resource): @staticmethod @jwt_required def get(): try: with db_sessi...
class Array: def __init__(self, length): self.__items = [0] * length def print(self): for i in self.__items: print(i) array = Array(10) array.print()
import sys, os, logging, __main__, string import json import inspect from ConfigParser import SafeConfigParser from StringIO import StringIO import psycopg2 import psycopg2.pool import psycopg2.extras class AttrDict(dict): """ Extended dict with items accessible as attributes """ def __getattr__(self,...
#!/usr/bin/env python3 if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) maxvalue = runnerup = -100 for value in arr: if value > maxvalue: runnerup = maxvalue maxvalue = value elif value > runnerup and value < maxvalue: runne...
from setuptools import setup, find_packages from os import path from io import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='spotifyscraper', version='1.0.0', description='A sample Python proje...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import zmq import time def main(): context = zmq.Context() xsub_socket = context.socket(zmq.SUB) xsub_socket.connect('tcp://localhost:6001') xsub_socket.setsockopt(zmq.SUBSCRIBE, b'') n = 0 ot = time.time() ln = 0 while True: #pr...
6# -*- coding: utf-8 -*- """ Spyder Editor Dies ist eine temporäre Skriptdatei. """ import matplotlib.pyplot as plt import numpy as np img = plt.imread("test.png") fig, axs = plt.subplots(4,2, figsize=(15,15)) ### a rgb_weights = [1.0, 1.0, 1.0] coloredImage = np.dot(img[...,:3], rgb_weights) axs[0,0].imshow(img,...
nome = input('Digite seu nome: ') print('É um prazer te , {}'.format(nome))
import logging from constants import CONF, Confirmation, FUNCTION, ID, Slot from dialog_action import ActionType, DialogAction class DialogPolicy: """Policy for the dialog agent. Attributes: config (`configs.DialogConfiguration`): Dialog configuration that parametrize dialog policy. ...
from search_tags_service.services.v1.tags import get_tags_from_text def test_same_tags_result(mg_tag_2, same_tag_words, one_word_tag): assert get_tags_from_text(same_tag_words, one_word_tag, mg_tag_2) == {'tags': ['toyota']} def test_combinations_indents(mg_tag_2, tags_combinations_indents, three_words_tag, thr...
def dot_product(vec1,vec2): new=0 for i in range(len(vec1)): new+=vec1[i]*vec2[i] print(new) dot_product([1, 1], [1, 1]) #== 2 dot_product([1, 2], [1, 4]) #== 9 dot_product([1, 2, 1], [1, 4, 3]) #== 12
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # File: osc4py3/oscpeeradapt.py # <pep8 compliant> """Tools to manage high level communications between systems using OSC. The high level packet management encoding/decoding (with support for addrpattern compression/decompression, for checksum, authentication and encryp...
from django.utils.translation import gettext_lazy as _ # Activation types ACTIVATION_TYPE_ACTIVE = 'active' ACTIVATION_TYPE_PASSIVE = 'passive' ACTIVATION_TYPES = ( (ACTIVATION_TYPE_ACTIVE, _("actif")), (ACTIVATION_TYPE_PASSIVE, _("passif")) ) # Character types CHARACTER_TYPE_PC = 'pc' CHARACTER_TYPE_NPC = '...
# encoding.py # Copyright (C) 2011-2014 Andrew Svetlov # andrew.svetlov@gmail.com # # This module is part of BloggerTool and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from __future__ import absolute_import from docutils import core from docutils.writers import html4css1 ...
#! /usr/bin/env python3 from numpy.lib.function_base import append import open3d import numpy as np from ctypes import * # convert float to uint32 import tf import rospy from std_msgs.msg import Header, String import geometry_msgs.msg from sensor_msgs.msg import PointCloud2, PointField from visualization_msgs.msg imp...
import random import time from flask import current_app, render_template from flask_mail import Message, Mail from app import mail, create_app from app.celery import celery @celery.task def send_async_email(to, subject, body, html): app = create_app('development') with app.app_context(): msg = Messa...
import pandas as pd from sklearn import preprocessing from preprocessing import read, split, non_numerical_features, one_hot_encoding data = read('data.csv') label = data['label'] output = read('output.csv') prediction = output['Prediction'] print(prediction) correct = 0 for i in range(0,len(output)): if prediction...
import os, sys, argparse import pandas as pd import backtrader as bt from strategies.GoldenCross import GoldenCross from strategies.BuyHold import BuyHold strategies = { 'golden_cross':GoldenCross, 'buy_hold':BuyHold } parser = argparse.ArgumentParser() parser.add_argument('strategy', help='which strategy to ...
from typing import List from repository.user_repository import User from repository.user_repository import UserRepository class UserService: def __init__(self, user_repo: UserRepository) -> None: self._user_repo = user_repo def get_all(self) -> List[User]: return self._user_repo.get_all()...
from ..FeatureExtractor import InterExtractor from numpy import * class jansky_flux_extractor(InterExtractor): """ Convert the flux from magnitudes to janskies """ active = True extname = 'jansky_flux' #extractor's name # def extract(self): # table1 = { \ # "u": {"central":3650 , "width":680 , "f_lambda(0)...
import imageio import logging import os import shutil import six from smqtk.utils import file_utils, video_utils from smqtk.utils.mimetype import get_mimetypes MIMETYPES = get_mimetypes() class PreviewCache (object): """ Create and cache saved located of preview images for data elements. """ # Pr...
from email.policy import default from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, SubmitField, SelectField, BooleanField, FileField from wtforms.validators import Optional, DataRequired, NumberRange, ValidationError from wtforms.widgets import TextArea class InfiniteRechargeForm(FlaskFor...
n=input("Enter a number : ") for i in range (1,n+1,1): for b in range(1,n+1,-1): print "", for j in range (1,i+1,1): print j, for k in range(i-1,0,-1): print k, print"\n", print range(1,55666666,1000)
import numpy as np import gym from collections import defaultdict from tensorboardX import SummaryWriter class offMCO_Agent(object): def __init__(self, env, maxEpi=100000, gamma = 1, epsilon = 0.1): self.env = env self.maxEpi = maxEpi self.gamma = gamma self.Q = defaultdict(lambda:...
#!/usr/bin/python3 """ Copyright (c) 2015, Joshua Saxe 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 of con...
import unittest from main import insere_dados teste = insere_dados() class MyTestCase(unittest.TestCase): def testa_nome_vazio(self): self.assertFalse(teste.Nome == "", "Nome em branco") def testa_nome_inicia_com_maiuscula(self): self.assertTrue(teste.Nome[0].isupper(), "Nome não inicia com...
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
from deeppavlov import build_model model = build_model("topic_ag_news", download=True) # get predictions for 'input_text1', 'input_text2' predictions = model([ 'Britain Prince Andrew has no recollection of meeting sex accuser Report', 'Maher panics says Nikki Haley has gone full on Team Deplorable This is so scary ...
# The necessary imports for this application import json import requests from time import sleep # The URL of the Extractions Endpoint url = 'https://api.dowjones.com/alpha/extractions/documents' #Our prompts to be inserted into our query. prompt = "> " print("What are you searching for?") search_term =...
def square_it(digits): s = str(digits) s_len = len(s) len_sqrt = s_len ** 0.5 int_sqrt = int(len_sqrt) if len_sqrt == int_sqrt: return '\n'.join(s[a:a + int_sqrt] for a in xrange(0, s_len, int_sqrt)) return 'Not a perfect square!'
s = "If Comrade Napoleon says it, it must be right." a = [100, 200, 300] def foo(arg): print('arg = {arg}') class Foo: pass
# Generated from /Users/labtop/PyCharm/BioScript/grammar/grammar/BSParser.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .BSParser import BSParser else: from BSParser import BSParser # /* parser/listener/visitor header section */ # This class defines a complete listener ...
import urllib2 import re def downURL(url,filename): try: fp=urllib2.urlopen(url) except: print "download exception" return 0 op=open(filename,"wb") while 1: s=fp.read() if not s: break op.write(s) fp.close() op.close() ...
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: res = [] def go(sofar, sumi, i): if sumi > target: return if sumi == target: res.append(sofar) return if i >= len(cand...
from selenium import webdriver import pytest menu = [('Appearence', 'Template'), ('Logotype', 'Logotype'), ('Catalog', 'Catalog'), ('Product Groups', 'Product Groups'), ('Option Groups', 'Option Groups'), ('Manufacturers', 'Manufacturers'), ('Suppliers', 'Suppliers'), ('Delivery Statuses', 'Delivery S...
import subprocess import asyncio import os from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler def runner(path_of_exe): subprocess.call(path_of_exe) def schedule(path_of_exe,dt): scheduler = BackgroundScheduler() print(scheduler.get_jobs()) try: ...
from collections import defaultdict import numpy as np from pyNastran.bdf.bdf import read_bdf, BDF, CTRIA3, GRID from ..logger import msg from .classes import Edge def read_mesh(filepath, silent=True): """Read a Nastran triangular mesh Parameters ---------- filepath : str Path to the Nastra...
# -*- coding: utf-8 -*- import itertools class Solution: def fromBase3(self, digits): return int("".join(str(digit) for digit in reversed(digits)), 3) def sumBase3(self, digits): return sum(digit for digit in digits if digit) % 3 def toBase3(self, num): digits = [] while...
""" Flingo TV Queue/Player for XBMC Announce, then display the Flingo queue """ import sys import os import xbmc import xbmcplugin import xbmcaddon import xbmcgui import socket import uuid import httplib, urllib import re settings = xbmcaddon.Addon(id='plugin.video.flingo') # dbg = settings.getSetting("debug") == "t...
from flask import Flask, session from flask_socketio import SocketIO from .chatlog import * from .mem import * from .mongo import * try: monogo.Init() chatlog.Init(monogo.AddChatLog, monogo.Getlast20) print('mongo') except Exception as e: chatlog.Init(mem.AddChatLog, mem.Getlast20) print('mem') ch...
import os from glob import glob import numpy as np import matplotlib.pyplot as plt def train_history(acc_dir, set_sizes=(1, 2, 4, 8), save_as=None): """plots training history; specifically, accuracy on entire training set for each epoch, with separate lines on plot for each "set size" of visual search s...