code
stringlengths
1
199k
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL)...
from ..map_resource.utility import Utility from .. import tools import pandas as pd settings = { 'app_id': 'F8aPRXcW3MmyUvQ8Z3J9', 'app_code' : 'IVp1_zoGHdLdz0GvD_Eqsw', 'map_tile_base_url': 'https://1.traffic.maps.cit.api.here.com/maptile/2.1/traffictile/newest/normal.day/', 'json_tile_base_url': 'http...
'''Compare performance between PIL and OpenCV''' from __future__ import print_function import os import sys import cv2 from PIL import Image from time import time from pilib import ExtendedImage as pilImage from cvlib import ExtendedImage as cvImage class Benchmark(object): def __init__(self, bmClass): self...
n=int(input('digite um valor: ')) x=0 for x in range (n): print(x)
import os DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_ROOT = os.path.normpath( os.path.join(os.path.dirname(__file__), os.pardir)) ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql...
from __future__ import absolute_import, division import argparse import os import platform import re import shutil import subprocess import sys import warnings import setuptools from distutils.core import Command from Cython.Distutils import build_ext as _build_ext __package__ = 'pydriver' SKIP_PCL_HELPER = False if pl...
from __future__ import absolute_import, print_function from glob import glob from os.path import basename, splitext from setuptools import find_packages, setup setup( name="builder", version="0.1.0", license="MIT", description="Builder Component.", long_description="Builder Component.", author="...
from __future__ import absolute_import, print_function import logging from tornado import gen import re import requests import kazoo.client import kazoo.exceptions import requests import requests.exceptions from . import exceptions from . import zookeeper from .. import log, util from modules.util import flat_list from...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
import unicodecsv from openelex.base.load import BaseLoader from openelex.models import RawResult from openelex.lib.insertbuffer import BulkInsertBuffer from openelex.lib.text import ocd_type_id from .datasource import Datasource """ Pennsylvania elections have pre-processed CSV results files for elections beginning in...
from modeltranslation.translator import translator, TranslationOptions from .models import NotificationTemplate class NotificationTemplateTranslationOptions(TranslationOptions): fields = ('subject', 'body', 'html_body') translator.register(NotificationTemplate, NotificationTemplateTranslationOptions)
from django.core.management.base import BaseCommand from bongo.apps.bongo.models import Issue class Command(BaseCommand): def handle(self, *args, **options): for issue in Issue.objects.all(): issue.save()
from time import sleep, time def f(): sleep(.3) def g(): sleep(.5) t = time() f() print('f took: ', time() - t) # f took: 0.3003859519958496 t = time() g() print('g took:', time() - t) # g took: 0.5005719661712646
request = { "method": "POST", "uri": uri("/post_chunked_all_your_base"), "version": (1, 1), "headers": [ ("TRANSFER-ENCODING", "chunked"), ], "body": "all your base are belong to us" }
""" main_no_background.py: Start visualization, no background. This script runs a visualization of the electricity prices over Europe for the period of April 2014, with controls to increase the installed wind and solar capacity, and change scenarios for the rest of the system. Wind and solar penetra...
"""All the builtin operations (operators) are defined here Also, for the moment, some builtin functions will also be defined here """ from __future__ import unicode_literals, print_function import six import sys import operator import itertools from whispy_lispy import keywords, types, exceptions if six.PY3: unicod...
from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors o...
from components.propertyeditor.QPropertyModel import QPropertyModel from components.propertyeditor.Property import Property from components.ConnectorsInfoWnd import ConnectorsInfoWnd class BlockPropTreeModel(QPropertyModel): def __init__(self, mainWnd, rb, parent=None): super(BlockPropTreeModel, self).__in...
import sys t = int(raw_input()) for i in range(t): n = int(raw_input()) digits = [int(j) for j in list(str(n))] count = 0 for d in digits: if (d != 0) and (n%d == 0): count += 1 print count
import os import shutil import sys from os.path import expanduser TESTING = 'nosetests' in sys.argv[0] if TESTING: DATA_DIR = '/tmp/tsgtest123aeiae31ea/' shutil.rmtree(DATA_DIR, ignore_errors=True) else: # DATA_DIR = os.path.dirname(os.path.abspath(__file__))+'/../data/' DATA_DIR = expanduser("~") + '/t...
# -*- coding: utf-8 -*- import projecteuler as pe def main(): pass if __name__ == "__main__": main()
from __future__ import absolute_import import os from .base import * SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "CHANGEME!!!")
import os from datetime import datetime from collections import defaultdict from subprocess import Popen, PIPE sout,serr = Popen(["which", "cql2"], stdout=PIPE, stderr=PIPE).communicate() if len(serr) > 0: raise Exception(serr) if len(sout) == 0: raise Exception("Could not find 'cql2' in path. Library requires this...
import os import yaml from mtm.util.Assert import * def loadYamlFilesThatExist(*paths): configs = [] for path in paths: if os.path.isfile(path): config = loadYamlFile(path) if config != None: configs.append(config) return configs def loadYamlFile(path): re...
from __future__ import print_function import xml.etree.ElementTree as ET from glob import glob from pprint import PrettyPrinter as PP LONG_TESTS_DEBUG_VALGRIND = [ ('calib3d', 'Calib3d_InitUndistortRectifyMap.accuracy', 2017.22), ('dnn', 'Reproducibility*', 1000), # large DNN models ('features2d', 'Features...
__author__ = 'riko' import calculations as calc import numpy as np A = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) A = calc.smooth_time_series(A, 0.5) print A
import cv2 import numpy as np from PIL import Image import zbarlight cap = cv2.VideoCapture(1) def QRCODE(): while(cap.read()): # 讀進來之做高斯模糊 然後Canny再抓輪廓 _,frame = cap.read() img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) img_gray = cv2.equalizeHist(img_gray) th, bi_img =...
from flask import Flask, render_template, redirect import rethinkdb as r app = Flask(__name__) @app.route('/') def main(): return render_template('main.html') @app.route('/<user>') def bio(user): rconn = r.connect('localhost') useri = r.db('bittybio').table('users').get(user).run(rconn) rconn.close() i...
str1 = "Hello World" print(str1.isalpha()) str2 = "MyFavoriteSite" print(str2.isalpha())
from __future__ import division, unicode_literals, print_function import json import glob import itertools import logging import math import os import re import warnings import xml.etree.cElementTree as ET from collections import defaultdict from io import StringIO import numpy as np from monty.io import zopen, reverse...
import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc from dolfin import * import numpy as np import PETScIO as IO import common import scipy import scipy.io import time import scipy.sparse as sp import BiLinear as forms import IterOperations as Iter import MatrixOperations as MO import CheckPet...
import difflib import os import multiprocessing import utils import jdecode import cardlib libdir = os.path.dirname(os.path.realpath(__file__)) datadir = os.path.realpath(os.path.join(libdir, '../data')) cores = multiprocessing.cpu_count() def list_split(l, n): if n <= 0: return l split_size = len(l) / ...
import os import errno def list_directory(path): list_dire=[] list_dire=os.listdir(path) return list_dire def list_dir(path): list_file=[] list_file=os.listdir(path) return list_file def change_dir(path): os.chdir(path) change_dir("/home/mancube/Downloads/data/") #p1 ... list_directory= list(list_dir("/home/man...
import os import datetime import time class Utilities(): ''' Encapsulates the utility methods used by other parts of the tool ''' ONE_DAY = 24 * 60 * 60 def __init__(self): pass def execute(self, call_string): handle = os.popen(call_string) return handle.read() def create_directory(self, directory): if not...
from ansiblelint import AnsibleLintRule class LineTooLong(AnsibleLintRule): id = 'E602' shortdesc = 'Line too long' description = 'Line too long' tags = ['formatting'] def match(self, file, line): if len(line) > 80: self.shortdesc += " ({} characters)".format(len(line)) ...
""" Compute Gradients of a Field ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Estimate the gradient of a scalar or vector field in a data set. The ordering for the output gradient tuple will be {du/dx, du/dy, du/dz, dv/dx, dv/dy, dv/dz, dw/dx, dw/dy, dw/dz} for an input array {u, v, w}. Showing the :func:`pyvista.DataSetFilters.comput...
from PIL import Image, ImageTk, ImageDraw from collections import namedtuple import tkinter as tk Point = namedtuple('Point', ['x', 'y']) class Application(tk.Frame): def __init__(self, master): super().__init__(master, width=640, height=480, bg='white') self.width = 640 self.height = 480 ...
""" Module with standard logging hook. """ import logging from typing import Iterable import numpy as np from . import AbstractHook from ..types import EpochData class LogVariables(AbstractHook): """ Log the training results to stderr via standard :py:mod:`logging` module. .. code-block:: yaml :capt...
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="color", parent_name="layout.scene.xaxis.tickfont", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_nam...
import codecs import json from bottle import request from conans import DEFAULT_REVISION_V1 from conans.errors import NotFoundException, RecipeNotFoundException, PackageNotFoundException from conans.model.ref import ConanFileReference, PackageReference from conans.paths import CONAN_MANIFEST from conans.server.rest.bot...
#!flask/bin/python """ Author: StackFocus File: app.py Purpose: runs the app! """ from swagip import app app.config.from_object('config') if __name__ == "__main__": app.run()
from logger import logger from cache import Cache import db class Costume: """ Costume class """ def __init__(self, costume_id, job, level): self._info = Cache.costume(job, costume_id) self._info['costume_id'] = costume_id self._info['job'] = job self._info['level'] = level def costume_id(self): r...
''' Created on Jul 29, 2012 @author: rafaelolaechea ''' import subprocess from AppendPartialInstanceAndGoals import generate_and_append_partial_instances_and_goals from spl_claferanalyzer import SPL_ClaferAnalyzer def execute_main(): spl_names = ["apacheicse212", "berkeleydbqualityjournal", "berkeleydbsplc2011", ...
""" :Program: WAFNinja :ModuleName: db :Version: 1.0 :Revision: 1.0.0 :Author: Khalil Bijjou :Description: The db module is responsible for the interaction with the database. """ import sqlite3 def getPayload(type, waf): """ :Description: This function retrieves Payloads from the dat...
import re import io import csv def CSVDEFILTER(inputfilename, outputfilename): "Change CSVDE output CSV file to simple user based CSV file for import" inputfile = open(inputfilename, "r") outputfile = open(outputfilename, "w") scsv = '' for line in inputfile: if re.search(",user,", line): s...
from contextlib import closing from django.db import connection import csv import re def dump_table(table_name, pk_column, batch_size, dest_file): with closing(connection.cursor()) as cursor: cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name)) count, = cursor.fetchone() for offset in ra...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('imager_images', '0001_initial'), ] operations = [ migrations.AlterField( model_name='imageralbum', name='published', ...
from __future__ import unicode_literals from .base import * DEBUG = True TEMPLATES[0]['OPTIONS']['debug'] = True ADMINS = (('John', 'john@example.com'), ) # Log email to console when DEBUG = False SECRET_KEY = "DEV" ALLOWED_HOSTS = ['127.0.0.1', '.quantzen.cn', ] DATABASES = { 'default': { 'ENGINE': 'djang...
""" Backend for test environment. """ from django.core import mail from django.core.mail.backends.locmem import EmailBackend class SMSBackend(EmailBackend): """A SMS backend for use during test sessions. The test connection stores SMS messages in a dummy outbox, rather than sending them out on the wire. The dummy o...
from __future__ import absolute_import, division, print_function, unicode_literals import io import numpy as np from numpy.testing import assert_array_equal from .. import converters from .. import exceptions from .. import tree from ....tests.helper import raises, catch_warnings @raises(exceptions.E13) def test_invali...
from abc import abstractmethod import logging import zmq from zmq.eventloop import zmqstream logger = logging.getLogger(__name__) ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) class Connector: def _...
""" get data from a Geras time-series database. There are two main options: --list lists all time series in the Geras database --get gets a specified time series In all cases a Geras key must be given using the --key option. If no key if given on the command line, the user will be prompted for it, in which case it will...
""" RenderPipeline Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
''' ''' from .base import ( ToolBase, # execute_in_main_thread ) class RotateTool(ToolBase): # default settings override # polling = 0.066 # in seconds # threshold = 0.2 tool_context = "RotateSuperContext" class MoveTool(ToolBase): # default settings override # polling = 0.066 # in sec...
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Solution comments: Answer is the product of all primes in all the divisors, with each prime beeing included onl...
import blueback.config from blueback.job import Job def run(): configs = blueback.config.get_config() for config in configs: job = Job(config) job.run() if __name__ == "__main__": run()
from msrest.serialization import Model class GenerateUpgradedDefinitionParameters(Model): """GenerateUpgradedDefinitionParameters. :param target_schema_version: The target schema version. :type target_schema_version: str """ _attribute_map = { 'target_schema_version': {'key': 'targetSchemaVe...
from pybrain.utilities import drawGibbs import random from wolfmodbot import Role, Claim from fakeirc import Event class SimpleWolfPlayer(): def __init__(self, name, modbot): self.name = name self.modbot = modbot self.e = Event("privmsg", self.name, None, None) def getOtherPlayers(self): return [p f...
from django.test import TestCase from apps.courses.models import Course from django.contrib.auth.models import User from apps.documents.models import Document #def test_dokument(self):
class Draft4(object): PersonQuery = { "properties": { "from": {"type": "string"}, "till": {"type": "string"}, "start": { "type": "integer", "minimum": 0 }, "limit": { "type": "integer", ...
import os import sys import math from itertools import product import rexi_benchmarks from mule_local.JobGeneration import * from mule.JobParallelization import * from mule.JobParallelizationDimOptions import * jg = JobGeneration() verbose = False jg.compile.mode = 'release' if '_gnu' in os.getenv('MULE_PLATFORM_ID'): ...
from hubbot.response import IRCResponse, ResponseType from hubbot.moduleinterface import ModuleInterface class Triggers(ModuleInterface): triggers = ["triggers"] help = "triggers [module] -- returns a list of all commands, if no module is specified, " \ "returns all commands currently loaded." de...
import unittest from config import settings as config from probSyllabifier import Utils ''' testing exists for parseCelexTrainingSet() but not for makeNistPhonemeLst() ''' class TestSyllabParser(unittest.TestCase): def setUp(self): self.utils = Utils() self.training_set = ["@-b2d", "dI-litIN", "pVI-...
from setuptools import setup setup( entry_points={ 'console_scripts': [ 'kappa_catalytic_potential = KaSaAn.scripts.kappa_catalytic_potential:main', 'kappa_observable_plotter = KaSaAn.scripts.kappa_observable_plotter:main', 'kappa_observable_coplotter = KaSaAn.scripts.kap...
import random def read_input(): return (input().rstrip(), input().rstrip()) def print_occurrences(output): print(' '.join(map(str, output))) def PolyHash(S, p, x): hash = 0 for c in reversed(S): hash = (hash * x + ord(c)) % p return hash def PrecomputeHashes(T, lenP, p, x): lenT = len(T)...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
from __future__ import unicode_literals from contrail_api_cli.context import Context from contrail_api_cli.resource import Resource from contrail_api_cli.utils import printo, continue_prompt from ..utils import CheckCommand class CleanSubnet(CheckCommand): """Command to fix subnets KV store. This command works ...
"""empty message. Revision ID: 0563ce5ca262 Revises: ('21a2938dd9f5', '40f652bd98a8') Create Date: 2018-02-26 12:26:55.304692 """ from alembic import op import sqlalchemy as sa revision = '0563ce5ca262' down_revision = ('21a2938dd9f5', '40f652bd98a8') def upgrade(): pass def downgrade(): pass
__GPL__ = """ SIPVicious report engine manages sessions from previous scans with SIPVicious tools and allows you to export these scans. Copyright (C) 2007 Sandro Gauci <sandrogauc@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public...
__version__ = '1.1' __author__ = 'alfred richardsn' __description__ = 'чат-бот для вк, который может быть использован для добавления пользователей в беседы в случае их исключения оттуда'
from contentbase.auditor import ( audit_checker, AuditFailure, ) def includeme(config): config.scan('.testing_views') config.scan(__name__) def has_condition1(value, system): return value.get('condition1') @audit_checker('testing_link_source', condition=has_condition1) def checker1(value, system): ...
from maze_builder.random2 import weighted_choice, Choice class LineIllustratorBase(object): def __init__(self): self.image = None def __call__(self, cubic): return self.draw(cubic) def prepare(self, width, height): pass def draw_wall(self, p0, p1): pass def draw_featu...
"""Settings that need to be set in order to run the tests.""" import os def get_env_setting(setting, default): """ Get the environment setting or return exception """ try: return os.environ[setting] except KeyError: return default TMDB_API_KEY=get_env_setting('TMDB_API_KEY', '626b3a716f24694...
'''"Executable documentation" for the pickle module. Extensive comments about the pickle protocols and pickle-machine opcodes can be found here. Some functions meant for external use: genops(pickle) Generate all the opcodes in a pickle, as (opcode, arg, position) triples. dis(pickle, out=None, memo=None, indentleve...
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ...
from KBParallel.utils.job import Job class Task: """ An object representing a task to be run either locally or remotely. Contains module_name, method_name, and parameters for a task. Also contains a list of jobs that were run, a count of run failures, error messages, and responses. If a task is ...
import unittest from livefyre import Livefyre from livefyre.tests import LfTest from livefyre.src.cursor.factory import CursorFactory from livefyre.src.cursor import TimelineCursor from livefyre.src.cursor.model import CursorData import datetime from livefyre.src.utils import pyver class TimelineCursorTestCase(LfTest, ...
import sys from os.path import abspath, dirname import django from django.conf import settings from django.core.management.utils import get_random_secret_key sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( SECRET_KEY=get_random_secret_key(), INSTALLED_A...
from __future__ import absolute_import, division, print_function from itertools import product from math import ceil from numbers import Number from operator import getitem, add, itemgetter import numpy as np from toolz import merge, accumulate, pluck, memoize from ..base import tokenize from ..compatibility import lon...
import os.path import posixpath import pinax PINAX_ROOT = os.path.abspath(os.path.dirname(pinax.__file__)) PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) PINAX_THEME = 'default' DEBUG = True TEMPLATE_DEBUG = DEBUG SERVE_MEDIA = DEBUG INTERNAL_IPS = ( '127.0.0.1', ) ADMINS = ( # ('Your Name', 'your_em...
from flask import Flask from flask_webapi import WebAPI, authenticate, authorize, route from flask_webapi.authenticators import Authenticator, AuthenticateResult from flask_webapi.permissions import Permission, IsAuthenticated from unittest import TestCase class TestView(TestCase): def setUp(self): self.app...
"""Figure generating functions to accompany behavior_analysis, used by automatic scripts All functions should return either a figure or list of figures. """ import matplotlib import matplotlib.pyplot as plt import numpy as np import itertools as it from scipy.misc import comb try: from bottleneck import nanmean, na...
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ island_num = neighbor_num = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: island_n...
import time import cv2 import numpy as np from matplotlib import pyplot as plt def empty_callback(value): pass def ex_1(): def load_image_and_filer(image_filename): img = cv2.imread(image_filename, cv2.IMREAD_COLOR) cv2.namedWindow('img') cv2.createTrackbar('kernel_size', 'img', 0, 50, e...
from surveymonkey.calls.base import Call class User(Call): def __get_user_details(self, **kwargs): return self.make_call(self.__get_user_details, {}, kwargs) __get_user_details.allowed_params = [] get_user_details = __get_user_details
try: import json except ImportError: from django.utils import simplejson as json from respite.serializers.jsonserializer import JSONSerializer class JSONPSerializer(JSONSerializer): def serialize(self, request): data = super(JSONPSerializer, self).serialize(request) if 'callback' in request....
import sys import logging from pyqtgraph.Qt import QtGui, QtCore from PyQt4.Qt import QMutex import pyqtgraph as pg import template import datetime import qdarkstyle import krakenex logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s:%(me...
import six from .dsl import BaseQuery, MetaQuery from .exceptions import NoQueryError QUERIES = { 'match_all': { 'kwargs': ('boost',), }, # Full text queries # 'match': { 'field': True, 'args': ('query',), 'kwargs': ( 'operator', 'zero_terms_query', 'cutof...
import json from twisted.web.server import Site from twisted.web.resource import Resource from twisted.internet.threads import deferToThread from twisted.web.server import NOT_DONE_YET from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol from autobahn.twisted.resource import WebSocketR...
class EvolucionDiaria(models.Model): paciente = models.ForeignKey(Paciente, on_delete = models.CASCADE) fecha_hora = models.DateTimeField() Descricion = models.TextField() class EncabezadoHistoriaIngreso(models.Model): paciente = models.ForeignKey(Paciente, on_delete = models.CASCADE) diagnostico = models.TextFiel...
from test_framework.test_framework import mitcoinTestFramework from test_framework.util import * import os.path class ReindexTest(mitcoinTestFramework): def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain_clean(self.options.tmpdir, 1) def setup_netwo...
import subprocess class ProxyTools(object): '''Main class with methods to list/modify mac SOCKS proxy status''' def __init__(self, interface): self.interface_name = interface def is_proxy_on(self): '''Determines the current state of the SOCKS proxy. Returns True if the proxy is enabled, and ...
"""Retriever script for direct download of vertnet data""" from builtins import str from retriever.lib.models import Table from retriever.lib.templates import Script import os from pkg_resources import parse_version try: from retriever.lib.defaults import VERSION except ImportError: from retriever import VERSIO...
""" Atheloph: an IRC bot that writes a log. TODOs: DONE) implement proactive ping so bot knows if it's disconnected DONE) implement auto-reconnect 3) HTML logs with one anchor per line (or write a separate script to convert text to html) 4) NICK and TOPIC functions 0) regularly tidy up code! """ import so...
from .base import * DEBUG = True FIXTURE_DIRS = ( os.path.join(BASE_DIR, 'fixtures'), )
import sys def prime(n): yield 2 primes = {} for m in range(3,n,2): if all(m%p for p in primes): primes.get(m) yield m def printPrimeNumber(a): while True: yield next(a) def main(argv): a = prime(int(argv)) print(list(printPrimeNumber(a))) if __name__ == "__main__": main(sys.argv[1])
import unittest from nose.tools import * from ni.core.stack import Stack def test_new_stack(): s = Stack() assert repr(s) == repr([]) assert str(s) == str([]) assert unicode(s) == unicode([]) assert len(s) == len([]) def test_new_stack_sized(): s = Stack(10) assert s.size == 10 def test_stac...
""" Created on Tue Nov 6 19:34:21 2018 @author: alek """ import sys sys.path.append('.') import pyDist.endpointSetup print('starting a ClusterExecutorNode...') node = pyDist.endpointSetup.setup_cluster_node(num_cores=4) node.boot('0.0.0.0', 9000)
class Solution(object): def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ def findWordFromPos(board, m, w, i, j): print board print m print w print i ...
import os, csv if "scrapeMORB_output.csv" in os.listdir(os.getcwd()): os.remove("scrapeMORB_output.csv") outfile = open("scapeMORB_output.csv", 'a') for i in os.listdir(os.getcwd()): if "MORB_OUTPUT.csv" in i and enumerate(i, 1) >= 100: with open(i, 'r') as infile: reader = csv.reader(infile...