code
stringlengths
1
199k
r"""A class supporting chat-style (command/response) protocols. This class adds support for 'chat' style protocols - where one side sends a 'command', and the other sends a response (examples would be the common internet protocols - smtp, nntp, ftp, etc..). The handle_read() method looks at the input stream for the cur...
class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = """ options: mode: required: false default: null description: - Mode the file or directory should be. For those used to I(/usr/bin/chmod) remember that modes are actually octal numbers (like 0644). ...
""" Tests for field subclassing. """ from django.db import models from django.utils.encoding import force_unicode from fields import Small, SmallField, SmallerField, JSONField class MyModel(models.Model): name = models.CharField(max_length=10) data = SmallField('small field') def __unicode__(self): ...
""" Window instrumentation. @group Instrumentation: Window """ __revision__ = "$Id$" __all__ = ['Window'] from winappdbg import win32 Process = None Thread = None class Window (object): """ Interface to an open window in the current desktop. @group Properties: get_handle, get_pid, get_tid, ...
from django import template from django.template.loader import render_to_string from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib import comments from django.utils import six from django.utils.deprecation import RenameMethodsBase from django.utils.encoding i...
from django.db import models class Foo(models.Model): name = models.CharField(max_length=255) class Meta: app_label = 'another_app_waiting_migration'
from __future__ import unicode_literals from django.db import models, migrations import oscar.models.fields.autoslugfield import oscar.models.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('catalogue', '0001_initial'), ('address', '0001_initial'), ...
"""Android system-wide tracing utility. This is a tool for capturing a trace that includes data from both userland and the kernel. It creates an HTML file for visualizing the trace. """ import errno, optparse, os, re, select, subprocess, sys, time, zlib flattened_css_file = 'style.css' flattened_js_file = 'script.js' ...
import WebIDL def WebIDLTest(parser, harness): parser.parse(""" [NoInterfaceObject] interface TestExtendedAttr { [Unforgeable] readonly attribute byte b; }; """) results = parser.finish() parser = parser.reset() parser.parse(""" [Pref="foo.bar",Pref=flop] ...
from .ast import * from .invoke import S from itertools import count tagger = lambda x=count(): next(x) def fixtags(t): return tuple(fixtags_(t)) def fixtags_(t): reg = {} i = 0 for x in t: if x[0] == 'label': reg[x[1]] = i else: i += 1 for x in t: fx ...
import sys, os, pgq, skytools DEST_TABLE = "_DEST_TABLE" SCHEMA_TABLE = "_SCHEMA_TABLE" class TableDispatcher(pgq.SerialConsumer): def __init__(self, args): pgq.SerialConsumer.__init__(self, "table_dispatcher", "src_db", "dst_db", args) self.part_template = self.cf.get("part_template", '') s...
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DeliveryMethod', fields=[ ('id', models.AutoField(auto_created=T...
""" Python 3 removed the 'cmp' function and raises a Type error when you try to compare different types. This module recreates Python 2 style 'cmp' function which produces a "total ordering" for mixed type lists. """ import functools import itertools def cmp(a, b): """ >>> cmp(1, 1) 0 >>> cmp('A', 'A') ...
""" This module provides the main entry to the program. Provides helper functions to create, edit and run Plant instances, Recipe instances, OrderList instances as well as the scheduler. commands provides a dict of tuples that map from an str representation to either a help str or to a function pointer, it is used to g...
from flask import Blueprint, request, jsonify, current_app from werkzeug.exceptions import BadRequestKeyError from crud import Crud api = Blueprint('api', __name__, url_prefix='/api/v1',) @api.route('/jobs', methods=['GET']) def getAll(): return Crud(current_app.config['REDIS_HOST'], current_app.config['REDIS_PORT'], ...
import requests res = requests.get("https://ssu.life/soongsiri/refresh") print(res.status_code)
import AlchemyAPI alchemyObj = AlchemyAPI.AlchemyAPI() alchemyObj.loadAPIKey("api_key.txt"); result = alchemyObj.URLGetRankedConcepts("http://www.techcrunch.com/"); print result result = alchemyObj.TextGetRankedConcepts("This thing has a steering wheel, tires, and an engine. Do you know what it is?"); print result htm...
""" .. dialect:: mysql+oursql :name: OurSQL :dbapi: oursql :connectstring: mysql+oursql://<user>:<password>@<host>[:<port>]/<dbname> :url: http://packages.python.org/oursql/ .. note:: The OurSQL MySQL dialect is legacy and is no longer supported upstream, and is **not tested as part of SQLAlchem...
print ("Welcome to the Video Game Program\n") points = float(input("What was your score?")) if points > 50000: message = "You completed the highest level." elif points > 35000: message = "You completed level 2." elif points > 20000: message = "You completed level 1." else: message = "You should not ...
"""Attributes common to PolyData and Grid Objects.""" import collections.abc import logging from abc import abstractmethod from pathlib import Path from typing import Union, Any, Dict, DefaultDict, Type import numpy as np import pyvista from pyvista import _vtk from pyvista.utilities import (FieldAssociation, fileio, a...
from __future__ import unicode_literals import ryaml import unittest class SafeLoadTests(unittest.TestCase): def test_load_simple(self): yaml = "result: 42" expected = {'result': 42} result = ryaml.safe_load(yaml) assert result == expected def test_load_key_is_number(self): ...
from qtpy import QtCore, QtGui class DataTreeModel(QtCore.QAbstractItemModel): def __init__(self, data_node, parent=None): super(DataTreeModel, self).__init__(parent) self.data_node = data_node self.rootItem = DataTreeItem(self.data_node) data_node.changed.connect(self.on_node_change...
class Solution: # @param root, a tree node # @return an integer def minDepth(self, root): if root == None: return 0 num = 0 stack = [] stack.append(root) flag = False while len(stack) != 0: nnext = [] for t in stack: ...
""" 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 mcrouter.test.MCProcess import Memcached from mcrouter.test.McrouterTestCase import McrouterTestCase class TestSlowWarmUp(McrouterTestCase): config = './mcrouter/test/test_slow_warmup.json' def setUp(self): self.memcached = self.add_server(Memcached()) self.mcrouter = self.add_mcrouter(self...
""" For personal use only. Do not abuse. """ import json import argparse import pytreebank.box_office if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("path") args = parser.parse_args() reviews = pytreebank.box_office.get_box_office_reviews() with open(args.path, "wt...
""" Classes for interpolating values. """ from __future__ import division, print_function, absolute_import __all__ = ['interp1d', 'interp2d', 'spline', 'spleval', 'splmake', 'spltopp', 'ppform', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly', 'RegularGridInterpolator', 'interpn'] import itertools import ...
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject class OperatingParticipant(IdentifiedObject): """An operator of multiple PowerSystemResource objects. Note multple OperatingParticipants may operate the same PowerSystemResource object. This can be used for modeling jointly owned units where each o...
import os import json import httplib import urlparse import urllib import logging from urllib2 import HTTPError import oauth2 as oauth import feedparser from version import __version__ CWD = os.path.join(os.path.expanduser('~'), '.ecog') client_id = '576416393937-rmcaesbkv0rfdcq71l5ol9p3sbmv1qf9.apps.googleusercont...
import os import logging import threading from flask import Flask, jsonify, render_template, Markup import mistune import kafka_connector.avro_loop_consumer as avro_loop_consumer from kafka_connector.avro_loop_consumer import AvroLoopConsumer __author__ = u'Stephan Müller' __copyright__ = u'2017, Stephan Müller' __lice...
from typing import List from test_framework import generic_test def search_smallest(A: List[int]) -> int: # TODO - you fill in here. return 0 if __name__ == '__main__': exit( generic_test.generic_test_main('search_shifted_sorted_array.py', 'search_shifted_sorte...
import numpy as np import cv2 class opencv_test: # 初期化 def __init__(self,parent = None): self.file = file self.cap = cv2.VideoCapture(0) #ファイルを読み込み、BGRをRGBに変換する関数 def open_pic(self,file): pic = cv2.imread(file) pic_color = cv2.cvtColor(pic,cv2.COLOR_BGR2RGB) return pic,pic_color #Canny処理してエッジ検出した後に、元の画像と...
import scrapy from scraper.items import NewsItem from scraper.media import uploadImg import datetime class ScienceDailySpider(scrapy.Spider): name = 'sciencedaily' allowed_domains = ['sciencedaily.com'] start_urls = [ "http://www.sciencedaily.com/terms/conflict_resolution.htm", ...
"""Retrieve journal article's HTML/XML and extract the text.""" import logging import urllib import bs4 from fake_useragent import UserAgent import requests logger = logging.getLogger(__name__) def text_from_soup( url, parser, find_args, check_for_open_access=None, between_children=None, escape_...
""" Django settings for wedding project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ import os, sys, simplemathcaptcha from django.utils._os import upath from dja...
import os.path as path import yaml from conjureup import utils from conjureup.app_config import app cred_path = path.join(utils.juju_path(), 'credentials.yaml') def __format_creds(creds): """ Formats the credentials into strings from the widgets values """ formatted = {} for k, v in creds.items(): ...
import os, pickle, tarfile, ntpath import numpy as np data_dir = "." image_size = 32 num_labels = 10 num_channels = 3 # RGB import functools def maybe_download(): dest_directory = data_dir if not os.path.exists(dest_directory): os.makedirs(dest_directory) DATA_URL = 'http://www.cs.toronto.edu/~kriz/...
""" https://github.com/hyves-org/p2ptracker Copyright (c) 2011, Ramon van Alteren MIT license: http://www.opensource.org/licenses/MIT """ from flask import Module, request, abort, make_response, Response, jsonify, g, send_from_directory, current_app from werkzeug import secure_filename from p2ptracker import bencode im...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class CBTInserter(object): def __init__(self, root): """ :type root: TreeNode """ self.__tree = [root] for i in self.__tree: if i.left: ...
import fileinput import matplotlib.pyplot as plt import re import itertools colors = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k']) def addToPlot(weights, indices, filename, index): totalOccurrence = sum(weights) normalized = [x / float(totalOccurrence) for x in weights] inds = [x + 1/3.0 * index for ...
from flask import Flask, render_template, session app = Flask(__name__) app.config['SECRET_KEY'] = 'top secret!' @app.route('/plus1') def index(): if 'count' not in session: session['count'] = 1 else: session['count'] += 1 return render_template('plus1.html', count=session['count']) if __nam...
import time import cv2 import numpy as np from threading import Thread import platform from imageprocess import ImageProcess import io import settings as SET try: from picamera import PiCamera # here cause warning import light except: PiCamera = object light = None class Camera(object): def __init__...
""" @brief test log(time=45s) """ import sys import os import unittest from pyquickhelper.loghelper import fLOG from pymyinstall.installcustom import install_chromedriver class TestChromeDriver(unittest.TestCase): def test_install_ChromeDriver(self): fLOG( __file__, self._testMe...
import struct from .exceptions import FileLengthTooLargeError class Header(object): _max_file_length = 0xFFFFFFFF def __init__(self, file_length): if file_length > self._max_file_length: raise FileLengthTooLargeError( 'File length cannot be larger than {} bytes (~{:.1f} GB). ...
from pyramid.view import view_config from ..Models import ( DBSession, Observation, ProtocoleType ) from ecoreleve_server.GenericObjets.FrontModules import (FrontModule,ModuleField) import transaction import json from datetime import datetime from sqlalchemy import func,select,and_, or_ from pyramid.sec...
from django.contrib import admin from .models import SettingsValue, LogRecord class SettingsValueAdmin(admin.ModelAdmin): fields = [ 'name', 'value' ] list_display = [ 'name', 'value' ] class LogRecordAdmin(admin.ModelAdmin): list_per_page = 250 list_filter = ( 'level', ...
from pyscipopt import Model verbose = False sdic = {0:"even",1:"odd"} def parity(number): try: assert number == int(round(number)) m = Model() m.hideOutput() ### variables are non-negative by default since 0 is the default lb. ### To allow for negative values, give None as lo...
from __future__ import print_function from random import gauss import sys import numpy as np import matplotlib.pyplot as plt from numpy import matrix from numpy import linalg DEBUG = False GRAPHS = True REDEF_SIGMA_PERP = True args = str(sys.argv) total = len(sys.argv) if(total==8): no_points = int(sys.argv[1]) loc_c...
import sys from gsh.plugin import BaseExecutionHook class DebuggerHook(BaseExecutionHook): def update_host(self, hostname, stream, line): print "Running update_host hook: ", (hostname, stream, line) def pre_host(self, *args): print "Running pre_host hook:", args def post_host(self, *args): ...
from pyquery import PyQuery as pq def parse_values(items): parsed = [] for item in items: if item.tag == 'input': parsed.append(item.value) else: parsed.append(item.text) return parsed def htmlx(data, extract=None, data_map=None, data_store=None, parsed=True): try...
import os from seleniumbase.fixtures import constants VISUAL_BASELINE_DIR = constants.VisualBaseline.STORAGE_FOLDER abs_path = os.path.abspath(".") visual_baseline_path = os.path.join(abs_path, VISUAL_BASELINE_DIR) def get_visual_baseline_folder(): return visual_baseline_path def visual_baseline_folder_setup(): ...
"""WiZ integration switch platform.""" from __future__ import annotations from typing import Any from pywizlight import PilotBuilder from pywizlight.bulblibrary import BulbClass from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import H...
STATUS_CHOICES = ( ('Pending', 'Pending'), ('Accepted', 'Accepted'), ('Declined', 'Declined'), ('Ended', 'Ended') ) RENT_CHOICES = ( ('Rent request', 'Rent request'), ('Rent accepted', 'Rent accepted'), ('Rent declined', 'Rent declined'), )
""" --- Day 17: No Such Thing as Too Much --- The elves bought too much eggnog again - 150 liters this time. To fit it all into your refrigerator, you'll need to move it into smaller containers. You take an inventory of the capacities of the available containers. For example, suppose you have containers of size 20, 15,...
from pika import BasicProperties from pika import BlockingConnection from pika import ConnectionParameters def producer(): connection = BlockingConnection(ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', type='fanou...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('moleculeci', '0002_auto_20160226_1150'), ] operations = [ migrations.CreateModel( name='GithubInfo', fields=[ ('i...
from argparse import Namespace from pathlib import Path from typing import Dict, Optional from fairseq.data import Dictionary def get_config_from_yaml(yaml_path: Path): try: import yaml except ImportError: print("Please install PyYAML: pip install PyYAML") config = {} if yaml_path.is_fil...
import operator from pyparsing import Forward, Group, Literal, nums, Suppress, Word expression_stack = [] def push_first(tokens): expression_stack.append(tokens[0]) """ atom :: '0'..'9'+ | '(' expression ')' term :: atom [ ('*' | '/') atom ]* expression :: term [ ('+' | '-') term ]* """ expression = Forwar...
from __future__ import unicode_literals from django.conf import settings import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ('tools',...
from ..exceptions.orm import ModelNotFound from ..utils import Null, basestring from ..query.expression import QueryExpression from ..pagination import Paginator, LengthAwarePaginator class Builder(object): _passthru = [ 'to_sql', 'lists', 'insert', 'insert_get_id', 'pluck', 'count', 'min', 'max', '...
from django import forms from symposion.proposals.models import PresentationKind, Proposal from bootstrap.forms import BootstrapForm from django.utils.translation import ugettext_lazy as _ class ProposalForm(BootstrapForm): title = forms.CharField(max_length=100, label=_("Title")) abstract = forms.CharField(wid...
""" Scan a list of hosts with a list of CGIs trying to exploit the ShellShock vulnerability with different methods and payloads (CVE-2014-6271, CVE-2014-6278) """ import httplib,sys,time import pprint import csv import argparse from threading import Thread from Queue import Queue SLEEP_TIME=9 SLEEP_DELAY=5 PING_PKTS=9...
from django.apps import AppConfig class RedsysGateway(AppConfig): name = 'redsys_gateway' verbose_name = "RedSys"
from keras.callbacks import Callback class MultiGPUModelCheckpoint(Callback): def __init__(self, save_path, cpu_model): self.save_path = save_path self.cpu_model = cpu_model def on_epoch_end(self, epoch, logs=None): val_loss = logs['val_loss'] self.cpu_model.save(self.save_path.f...
class InvalidOperationException(Exception): pass class ErrorResponseException(Exception): pass class DocumentDoesNotExistsException(Exception): pass class NonUniqueObjectException(Exception): pass class FetchConcurrencyException(Exception): pass class ArgumentOutOfRangeException(Exception): pass...
import tornado.web import tornado.escape import json from {{appname}}.config import myapp from {{appname}}.handlers.base import BaseHandler class PowHandler(BaseHandler): """ The Base PowHandler Place to put common stuff which will remain unaffected by any PoW Changes. Purely and only User o...
from jasy.asset.ImageInfo import ImgInfo from jasy.asset.sprite.Block import Block from jasy.asset.sprite.BlockPacker import BlockPacker from jasy.asset.sprite.File import SpriteFile from jasy.asset.sprite.Sheet import SpriteSheet from jasy.core.Config import writeConfig import jasy.core.Console as Console import os im...
import MySQLdb import MySQLdb.cursors import re import config def getMonuments(): fields = ['name', 'description', 'mainCategory', 'subCategory', 'province', 'town', 'street', 'zipCode'] db = getDatabase() db.execute('SELECT monument.id AS id, ' + ', '.join(fields) + ' FROM `monument`, `location` WHERE monu...
from contextlib import contextmanager from ..exceptions import UraniumException class Proxy(object): """ a proxy object takes a context stack, and proxies requests to whatever the context stack is currently referring to """ def __init__(self, context_stack): object.__setattr__(self, "_co...
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)...
"""Implementation of a trie data structure.""" class Trie(object): """A tree data structure... ...that groups related words in branches, which split where they differ from each other. insert(self, val): creates a new branch containing nodes that spell the value which diverges where the spelling ...
class LevelError(RuntimeError): pass
"""Class to gather and analyse various metal line statistics""" from __future__ import print_function import numpy as np from . import abstractsnapshot as absn from . import spectra class RandSpectra(spectra.Spectra): """Generate metal line spectra from simulation snapshot""" def __init__(self, num, base, MPI ...
savepng = False # Change to True if you want Clock to be saved as PNG from math import pi import numpy as np import csv import matplotlib as mpl import matplotlib.pyplot as plt import datetime import time from tkFileDialog import askopenfilename import os import Tkinter from Tkinter import * from Tkinter import Tk impo...
test.describe('Example Tests') InterlacedSpiralCipher = {'encode': encode, 'decode': decode } example1A = 'Romani ite domum' example1B = 'Rntodomiimuea m' test.assert_equals(InterlacedSpiralCipher['encode'](example1A), example1B) test.assert_equals(InterlacedSpiralCipher['decode'](example1B), example1A) example2A = 'S...
import os os.system('python runTrainer.py --agent=KerasNAFAgent --env=Detached2DCartPolev0Env --train-for=0 --test-for=10000000 --delay=0.005 --gui --show-test --load-file=checkpoints/KerasNAF-D2DCartPolev0-chkpt-1.h5')
import numpy as np import scipy.linalg as spl import scipy.sparse as sps import scipy.sparse.linalg as spsl def check_1d(inp): """ Check input to be a vector. Converts lists to np.ndarray. Parameters ---------- inp : obj Input vector Returns ------- numpy.ndarray or None ...
""" Created by Uğur Özyılmazel on 2012-08-20. Copyright (c) 2012 Fontronik. All rights reserved. """ import sys import os import re import subprocess import shlex import cgi TM_FILEPATH = os.environ['TM_FILEPATH'] TM_FILENAME = os.environ['TM_FILENAME'] TM_DIRECTORY = os.environ['TM_DIRECTORY'...
import unittest def insertion_sort(seq): for k in range(0, len(seq)): n = k - 1 while seq[k] < seq[n] and k >= 1: seq[n], seq[k] = seq[k], seq[n] k = k - 1 n = n - 1 return seq ''' Tempo de O(n**2) e memoria de O(1)''' class OrdenacaoTestes(unittest.TestCase):...
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('products', '0006_productfeatured_text_css_color'), ] operatio...
__author__ = 'cosven' import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest from api import NetEase from models import DataModel from widgets.login_dialog import LoginDialog try: from PyQt4.phonon import Phonon except ImportError: app ...
import random class Block: colorTable1 = [[0xFF, 0xFF, 0x00], [0x88, 0x88, 0x00], [0x00, 0x00, 0xCC], [0x66, 0x66, 0xFF]] colorTable2 = [[0xFF, 0xFF, 0xFF], [0xBB, 0xBB, 0xBB], [0x88, 0x88, 0x88], [0x44, 0x44, 0x44]] def __init__(self): self._active = 1 self._color1 = 0 se...
import sys,getopt,datetime,codecs if sys.version_info[0] < 3: import got else: import got3 as got def main(argv): if len(argv) == 0: print('You must pass some parameters. Use \"-h\" to help.') return if len(argv) == 1 and argv[0] == '-h': f = open('exporter_help_text.txt', 'r') print(f.read()) f.clo...
from HTMLParser import HTMLParser from htmlentitydefs import name2codepoint class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print('<%s>' % tag) def handle_endtag(self, tag): print('</%s>' % tag) def handle_startendtag(self, tag, attrs): print('<%s/>' % tag) ...
""" =============================== Test for qplotutils.chart.utils =============================== Autogenerated package stub. """ import unittest import logging import sys import os import numpy as np from qtpy.QtCore import * from qtpy.QtGui import * from qtpy.QtOpenGL import * from qtpy.QtWidgets import * from qplo...
import setuptools from distutils.core import setup from os import path def readFile(file): with open(file) as f: return f.read() CLASSIFIERS = [] VERSION = '0.3.4' CLASSIFIERS += [ 'Development Status :: 3 - Alpha', ] PACKAGES = [ 'spongemock' ] PACKAGE_DIR = { 'spongemock': 'src' } DATA_FILES ...
__author__ = 'samsung' def maxPoints(points): n = len(points) if n <= 2: return n mymax = 0 for i in xrange(n-1): slope = {'inf': 0} same = 1 result = 0 for j in xrange(i+1, n): x1 = points[i].x x2 = points[j].x y1 = points[i].y...
from setuptools import setup setup( name='rdio-cli', version='1.2', packages=[], include_package_data=True, scripts=['bin/rdio'], requires=['termtool', 'prettytable', 'progressbar', 'Rdio'], install_requires=['termtool>=1.1', 'prettytable>=0.7', 'progressbar', 'Rdio'], )
''' This is the main analyze script ''' import socket import sqlite3 import struct import pcapy import datetime import time import os import argparse import glob from exp_description import * import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import scipy as st...
from __future__ import absolute_import from celery import task from atados_core.emails import VolunteerMail, NonprofitMail from django.template.loader import get_template from django.template import Context from django.core.mail import EmailMultiAlternatives from atados_core.models import Project, User, Address, City, ...
""" The client core with the main function. """ import datetime import time import os from lib import IntervalTimer, HashSet, API, Airodump, Dump import parser import config def enable_scheduler_log(): """ Enables logging for apscheduler jobs. """ import logging log = logging.getLogger('apscheduler....
import unittest import json import re from base64 import b64encode from flask import url_for from app import create_app, db from app.models import User, Role, Post, Comment class APITestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context...
""" WSGI config for s3backups project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "s3backups.settings") from django.core.w...
"""Test for the defector strategy.""" import axelrod from .test_player import TestPlayer C, D = axelrod.Actions.C, axelrod.Actions.D class TestDefector(TestPlayer): name = "Defector" player = axelrod.Defector expected_classifier = { 'memory_depth': 0, 'stochastic': False, 'inspects_s...
"""" File : messaging_factory.py Author : ian Created : 20-04-2017 Last Modified By : ian Last Modified On : 20-04-2017 *********************************************************************** The MIT License (MIT) Copyright © 2016 Ian Cooper <ian_hammond_cooper@yahoo.co.uk> Permission is ...
class Solution: # @param root, a tree node # @return a boolean def isValidBST(self, root): return self.validate(root, float('-inf'), float('inf')) def validate(self, root, min_v, max_v): if root is None: return True if root.val <= min_v or root.val >= max_v: ...
from datetime import date, datetime, timedelta import csv import requests import itertools from slugify import slugify def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').rep...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline i...
class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int """ masks = [0] * len(words) result = 0 for i in range(len(words)): for c in words[i]: masks[i] |= 1 << (ord(c) - ord('a')) for ...
import itertools import random from collections import Counter hands = ['High Card', 'Pair', 'Two Pairs', 'Three Of A Kind','Straight', 'Flush', 'Full House', 'Poker', 'Straight Flush', 'Royal Flush'] def getPoints(player1Cards, player2Cards, player3Cards=None): # Case with 2 players if player3Cards is...