code
stringlengths
1
199k
import sys sys.path.append('gen-py') from hello import HelloSvc from thrift.protocol import TJSONProtocol from thrift.server import THttpServer class HelloSvcHandler: def hello_func(self): print "Hello Called" return "hello from Python" processor = HelloSvc.Processor(HelloSvcHandler()) protoFactory = TJSONPro...
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext from django.contrib.comments import get_model from django.contrib.comments.views.m...
from runner.koan import * import jims import joes counter = 0 # Global class AboutScope(Koan): # # NOTE: # Look in jims.py and joes.py to see definitions of Dog used # for this set of tests # def test_dog_is_not_available_in_the_current_scope(self): try: fido = Dog() ...
from __future__ import unicode_literals import os from optparse import make_option from django.core.management.base import LabelCommand from django.utils.encoding import smart_text from django.contrib.staticfiles import finders class Command(LabelCommand): help = "Finds the absolute paths for the given static file(...
""" A collection of utility routines and classes used by the spatial backends. """ class SpatialOperation(object): """ Base class for generating spatial SQL. """ sql_template = '%(geo_col)s %(operator)s %(geometry)s' def __init__(self, function='', operator='', result='', **kwargs): self.fun...
"""Tests for methods defined in util/misc.py""" from xmodule.util.misc import escape_html_characters from unittest import TestCase class UtilHtmlEscapeTests(TestCase): """ Tests for methods exposed in util/misc """ final_content = " This is a paragraph. " def test_escape_html_comments(self): ...
""" Scrapy Item See documentation in docs/topics/item.rst """ from pprint import pformat from collections import MutableMapping from abc import ABCMeta import six from scrapy.utils.trackref import object_ref class BaseItem(object_ref): """Base class for all scraped items.""" pass class Field(dict): """Conta...
import os import sys import random import unittest sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../.."))) import base_test repo_root = os.path.abspath(os.path.join(__file__, "../../..")) sys.path.insert(1, os.path.join(repo_root, "tools", "webdriver")) from webdriver import exceptions class WindowSizeTest...
from pyasn1.type import base, tag, univ, char, useful from pyasn1.codec.ber import eoo from pyasn1.compat.octets import int2oct, oct2int, ints2octs, null, str2octs from pyasn1 import debug, error class Error(Exception): pass class AbstractItemEncoder: supportIndefLenMode = 1 def encodeTag(self, t, isConstructed...
from .templatetags.microsite import page_title_breadcrumbs
from typing import Union from django.contrib.auth.models import User from ..tokens import UntrustedToken, Token class BaseUserRepository: def get_user(self, username: str) -> Union[None, User]: # pragma: no cover raise NotImplementedError() class BasePublicKeyRepository: def attempt_to_verify_token(sel...
import re from django.template.backends.django import DjangoTemplates, Template from django.template.engine import _dirs_undefined try: from html.parser import HTMLParser except ImportError: from HTMLParser import HTMLParser class DjeffTemplates(DjangoTemplates): def get_template(self, template_name, dirs=_...
exec(open("statEmbedding/1_SingleNeuronCNNs.py").read()) exec(open("statEmbedding/2_Generate_embedding_spaces.py").read()) exec(open("statEmbedding/3_MetaParameterExtraction.py").read()) exec(open("elephant/config_elephant.py").read()) exec(open("elephant/1_load_data.py").read()) exec(open("elephant/2_model.py").read()...
from django.urls import reverse from ..models import Person, Event, EventRequest from .base import TestBase class TestAssignments(TestBase): def setUp(self): self._setUpUsersAndLogin() self._setUpEvents() def test_assign_user_to_event(self): """Check if `event_assign` correctly assigns s...
import numpy as np from pyml.utils import normalize_features from pyml.utils import normalize_inputs class LinearRegression(object): """A linear regression learning algorithm. Args: X (np.array): Matrix of features (training data). y (np.array): Vector of training labels. alpha (float): ...
''' Proxy API to make queries to popular blockchains explorer ''' import sys import logging from lib import config from lib.blockchain import blockr, insight, sochain, addrindex def check(): logging.info('Status: Connecting to block explorer.') return sys.modules['lib.blockchain.{}'.format(config.BLOCKCHAIN_SER...
from __future__ import absolute_import from __future__ import print_function import argparse import logging import boto3 from ebcli.lib import aws as ebaws from .commands.bgdeploy import apply_args as apply_args_bgdeploy from .commands.clonedeploy import apply_args as apply_args_clonedeploy from .commands.create import...
from __future__ import absolute_import from celery import Celery from celery.utils.log import get_task_logger celery = Celery() celery.config_from_object('backend.tasks.settings') logger = get_task_logger(__name__) import datetime import settings from backend.common.storage import nosql_database_connector _database_cac...
"""Check the current state of the log N log F.""" import numpy as np import matplotlib.pyplot as plt from frbpoppy import Frbcat, hist from tests.convenience import plot_aa_style, rel_path SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'askap-incoh') frbcat = Frbcat().df snrs = {s: frb...
import unittest from pyrake.http import Request from pyrake.item import BaseItem from pyrake.utils.spider import iterate_spider_output, iter_spider_classes from pyrake.contrib.spiders import CrawlSpider class MyBaseSpider(CrawlSpider): pass # abstract spider class MySpider1(MyBaseSpider): name = 'myspider1' cla...
import sys from PyQt5.QtWidgets import * class home_page(): def __init__(self, Widget): self.base_widget = QWidget(Widget) self.unranked_match_btn = QPushButton("Unranked match", self.base_widget) self.ranked_match_btn = QPushButton("Ranked match", self.base_widget) self.tournament_b...
''' Created on Jul 25, 2016 @author: Alex ''' import six from inspect import isfunction class DecortorMeta(type): def __new__(cls, name, parents, dct): """ only apply decorator to non abstract models """ abstract = dct.pop("abstract", None) cls = super(DecortorMeta, cls).__ne...
import os import re from distutils.core import setup __author__ = 'Justin Dane Vrana' __license__ = 'MIT' __package__ = "pillowtalk" __readme__ = "README" tests_require = [ 'pytest', 'pytest-runner', 'python-coveralls', 'pytest-pep8' ] install_requires = [ 'inflection', 'marshmallow', 'dill'...
from distance_builder import * from distance import * import numpy as np if __name__ == '__main__': builder = DistanceBuilder() builder.load_points(r'../data/data_iris_flower/iris.data') builder.build_distance_file_for_cluster(ConsineDistance(), r'../data/data_iris_flower/iris.forcluster')
import re class DefineUtils: def getJsVariablePattern(self, variableName): return '([^\.])(' + variableName + ')([^\w])' def cleanUpDefine(self, content, defineObj, toBeRenamedList = []): wrappedImports = map(self.wrap, defineObj['imports']) imports = ", ".join(wrappedImports) args = ", ".join(defin...
import logging import sys from divvy import config from divvy import handle from divvy import reply log = logging.getLogger(__name__) def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parame...
""" File: slNode.py Purpose: rit_lib struct based single linked node for CS1 LECTURE. Author: Sean Strout <sps@cs.rit.edu> Contributor: ben k steele <bks@cs.rit.edu> Contributor: Jeremy S. Brown <jsb@cs.rit.edu> Language: Python 3 Description: A representation of a single linked node intended for use as the building b...
from pylab import * from plotly.tools import FigureFactory as FF import plotly.graph_objs as go from scipy.spatial.distance import pdist, squareform, cdist from .riemannian_manifold import RManifold from ..data_attachment.measures import Measures, Measure class Landmarks(RManifold) : """ Encodes a Landmarks manifold ...
from django.conf import settings DJFEEDBACK_BACKENDS = getattr( settings, 'DJFEEDBACK_BACKENDS', ('feedbacks.backends.RedmineBackend',) ) DJFEEDBACK_REDMINE_URL = getattr(settings, 'DJFEEDBACK_REDMINE_URL', '') DJFEEDBACK_REDMINE_KEY = getattr(settings, 'DJFEEDBACK_REDMINE_KEY', None) DJFEEDBACK_REDMINE_PROJECT...
import asyncio from uuid import getnode from redbot.core import config from redbot.core.bot import Red from .core import GuildJoinRestrict __red_end_user_data_statement__ = ( "This cog persistently stores the minimum " "amount of data needed to restrict guild joins to those allowed by settings. " "It will n...
class wget(object): basecommand = 'wget' def __init__(self, urllocation=''): self.options = [] self.urllocation = urllocation def add_option(self, option): self.options.append(option) def build_command(self): command_bits = [] command_bits.append(self.basecommand)...
import os import tempfile from office365.sharepoint.client_context import ClientContext from tests import test_site_url, test_client_credentials ctx = ClientContext(test_site_url).with_credentials(test_client_credentials) files = ctx.web.lists.get_by_title("Documents").root_folder.files.get().execute_query() download_p...
import json import pika from pymongo import MongoClient from base.base_worker import BaseWorker from base.constantes import MONGO_HOST, MONGO_PORT, RABBIT_HOST, RABBIT_PORT class MainWorker(object): """ Main class To start script. """ def __init__(self): client = MongoClient(MONGO_HOST, MONGO_PO...
import shutil import pytest from six import PY2 from pre_commit_hooks.pretty_format_json import main from pre_commit_hooks.pretty_format_json import parse_num_to_int from testing.util import get_resource_path def test_parse_num_to_int(): assert parse_num_to_int('0') == 0 assert parse_num_to_int('2') == 2 as...
"""\ Maximum flow by Ford-Fulkerson jill-jenn vie et christoph durr - 2014-2018 """ from tryalgo.graph import add_reverse_arcs def _augment(graph, capacity, flow, val, u, target, visit): """Find an augmenting path from u to target with value at most val""" visit[u] = True if u == target: return val ...
""" @author: sharpdeep @file:setup.py @time: 2016-02-24 22:15 """ import codecs import os import sys try: from setuptools import setup except: from distutils.core import setup """ 打包的用的setup必须引入, """ def read(fname): return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read() NAME = "wxrobot" PACKAGES ...
from django.db import models from datetime import datetime from starbowmodweb.user.models import User from django.core.urlresolvers import reverse from django.conf import settings BATTLENET_REGION_UNKNOWN = 0 BATTLENET_REGION_NA = 1 BATTLENET_REGION_EU = 2 BATTLENET_REGION_KR = 3 BATTLENET_REGION_CN = 5 BATTLENET_REGIO...
""" Base version of package/tasks.py, created by package/root/dir> dk-tasklib install (it should reside in the root directory of your package) This file defines tasks for the Invoke tool: http://www.pyinvoke.org Basic usage:: inv -l # list all available tasks inv -e ... # echo comman...
import tornado.web import tornado.ioloop import requests import json from tornado.web import RequestHandler, Application from tornado.ioloop import IOLoop ioloop = IOLoop.instance() class ClassificationStatus(object): def __init__(self): self.terms = {} self.stopWords = [] self.punctuation =...
import math def trapezint1(f, a, b): return ((b-a)/2.0)*(f(a) + f(b)) print trapezint1(math.sin, 0, math.pi) print trapezint1(math.cos, 0, math.pi) print trapezint1(math.sin, 0, math.pi/2) def trapezint2(f, a, b): return (float((b-a))/4.0)*(f(a) + f(b) + 2*f((a+b)/2.0)) print trapezint2(math.sin, 0, math.pi) pr...
from __future__ import print_function, unicode_literals import json import os from medium import Client from nikola import utils from nikola.plugin_categories import Command from lxml import html, etree LOGGER = utils.get_logger("Medium") class CommandMedium(Command): """Publish to Medium.""" name = "medium" ...
from django.conf.urls import include from django.urls import path from django.shortcuts import redirect from duos_research import views urlpatterns = [ path("", views.index, name="index"), path("feedback/", include("feedback.urls")), path("search/", include("search.urls")), ]
from __future__ import unicode_literals, print_function import unittest import os from sys import stderr import datetime from pprint import pformat from ops.tram import minutes_data class TestDirectoryData(unittest.TestCase): def test_minutes(self): dt = datetime.datetime.now() path = minutes_data(d...
from dotmailer import Base from dotmailer.connection import connection class Survey(Base): """ """ end_point = '/v2/surveys' def __init__(self, **kwargs): self.required_fields = [] super(Survey, self).__init__(**kwargs) @classmethod def get_multiple(cls, assigned_to_address_book_...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import OrderedDict from future.utils import viewitems, viewkeys, viewvalues import logging import copy from multiprocessing import cpu_count from caffe2.python import \ model_helper, dyndep,...
""" Check health installed packages """ from os import path from .maindata import MainData from .pkgs import Pkgs from .utils import get_indent, get_line class CheckHealth: """ Check health installed packages """ def __init__(self): self.meta = MainData() self.pkgs = Pkgs() self....
"""Python implementation of a Graph Data structure.""" class Graph(object): """ Graph implementation. Graph data structure supports following methods: nodes(): return a list of all nodes in the graph. edges(): return a list of all edges in the graph. add_node(n): adds a new node 'n' to the graph...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('article', '0004_article_image'), ] operations = [ migrations.AlterField( model_name='article', name='image', field=models.ForeignKey(default=None, blank=True...
''' Forms ''' from flask_wtf import FlaskForm, RecaptchaField from wtforms import StringField from wtforms.validators import DataRequired class MessageForm(FlaskForm): ''' Validation for the message form ''' email = StringField('Email', validators=[DataRequired()]) message = StringField('Message', validator...
from __future__ import absolute_import import shutil import os import functools from mock import MagicMock, patch, call def rm_f(path): try: # Assume it's a directory shutil.rmtree(path, ignore_errors=True) except OSError: # Directory delete failed, so it's likely a file os.remov...
import sys if len(sys.argv) == 2: team_name=sys.argv[1] elif len(sys.argv) == 3: team_name=sys.argv[1]+" "+sys.argv[2] if team_name == "Tottenham": print(team_name+" will win the EPL!") else: print(team_name+" will NOT win the EPL.")
''' 问题: 实际中并不采用前端编码之类的?我觉得应该用字典方式,否则检索效率太低??? '''
from itertools import combinations as _combinations from queue import Queue from .pagerank_weighted import pagerank_weighted_scipy as _pagerank from .preprocessing.textcleaner import clean_text_by_word as _clean_text_by_word from .preprocessing.textcleaner import tokenize_by_word as _tokenize_by_word from .commons impo...
from django.contrib.sitemaps import Sitemap from wazimap.models import Geography from django.core.urlresolvers import reverse class JanagananaSitemap(Sitemap): changefreq = "yearly" priority = 0.5 def items(self): # http: // countingindia.com / profiles / district - 538 - mahbubnagar / geo_p...
import pytest import numpy as np import torch.nn as nn import torch as T from torch.autograd import Variable as var import torch.nn.functional as F from torch.nn.utils import clip_grad_norm_ import torch.optim as optim import numpy as np import sys import os import math import time import functools sys.path.insert(0, '...
FILE_NAME = 'fdic_failed_bank_list.csv' # open the csv # create the object that represents the data in the csv file # create a variable to represent the header row # output the value # output the length of the header row # output the type of the header row # loop through each item in the hea...
""" This is a fully functional do nothing backend to provide a template to backend writers. It is fully functional in that you can select it as a backend with import matplotlib matplotlib.use('Template') and your matplotlib scripts will (should!) run without error, though no output is produced. This provides a ni...
from wensleydale import cli from click.testing import CliRunner import json def test_run(): ''' The tool runs end to end. ''' runner = CliRunner() with runner.isolated_filesystem(): # Setup the test. with open('test.py', 'w') as file: file.write('1') # Run the tes...
"""Internal class for collection routing map implementation in the Azure Cosmos database service. """ import bisect from azure.cosmos.routing import routing_range from azure.cosmos.routing.routing_range import _PartitionKeyRange from six.moves import xrange class _CollectionRoutingMap(object): """Stores partition k...
""" Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all th...
from django.conf import settings from django.utils.timezone import utc import factory class UserFactory(factory.django.DjangoModelFactory): email = factory.Faker('email') password = factory.PostGenerationMethodCall('set_password', 'password') last_login = factory.Faker( 'date_time_between', ...
import numpy as np import functools from .deterministic import Deterministic from .gaussian import Gaussian, GaussianMoments from bayespy.utils import linalg class Add(Deterministic): r""" Node for computing sums of Gaussian nodes: :math:`X+Y+Z`. Examples -------- >>> import numpy as np >>> from...
from django.apps import apps as django_apps from django.shortcuts import render_to_response from django.template import RequestContext from django import http from bookmarks import handlers, signals, utils from bookmarks.templatetags import bookmarks_tags ERRORS = { 'model': u'Invalid model.', 'handler': u'Unre...
import time import serial def ctof(c): return int(c * 9.0 / 5.0 + 32) def binary(val, digits=4): return ('{0:0'+str(digits)+'b}').format(int(val)) class Mode(object): COOL = 1 DRY = 2 FAN = 3 ENERGY_SAVER = 4 class Fan(object): LOW = 1 MED = 2 HIGH = 3 class Controller(object): d...
import csv import optparse import shutil import subprocess import sys if __name__ == '__main__': parser = optparse.OptionParser(description="Chain together Inkscape extensions", usage="%prog [options] svgpath") parser.add_option('--id', dest='ids', action='append', type=str, d...
""" Program to calculate the amortization amount per month, given - Principal borrowed - Rate of interest per annum - Years to repay the loan Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment """ def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: ...
""" Created on Thu Jan 4 20:54:24 2018 @author: Stefan """ import numpy as np import matplotlib.pyplot as plt from Hashable import Hashable import os import time import random import sqlite3 from Filters import apply_filters_by_id import collections import io from TrainingDataFromSgf import TrainingDataSgfPass def ada...
from __future__ import print_function # In case we're running with python2 import sys import os import time import json import argparse import subprocess import requests import pystache import tweepy from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler twitter_api = None def getTw...
from distutils.core import setup __VERSION__ = '0.1.7' __URL__ = 'https://github.com/dbader/pytest-osxnotify' __DOWNLOAD_URL__ = (__URL__ + '/tarball/' + __VERSION__) setup( author='Daniel Bader', author_email='mail@dbader.org', version=__VERSION__, description='OS X notifications for py.test results.',...
from django.contrib import admin from models import UserProfile, Workout, Exercise, Rating admin.site.register(UserProfile) admin.site.register(Workout) admin.site.register(Exercise) admin.site.register(Rating)
""" lesscpy bootstrap3 tests. """ import unittest from test.core import find_and_load_cases @unittest.skip("Minor semantic issues left") class Bootstrap3TestCase(unittest.TestCase): pass class Bootstrap3ThemeTestCase(unittest.TestCase): pass find_and_load_cases( Bootstrap3TestCase, less_dir='bootstr...
from behave import * @then('I should get the HTTP status code {code:d}') def step_impl(context, code): assert context.customer.client().get_last_status() == code
""" mnist_loader ~~~~~~~~~~~~ A library to load the MNIST image data. For details of the data structures that are returned, see the doc strings for ``load_data`` and ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the function usually called by our neural network code. """ import pickle import gzip impor...
import unittest from katas.beta.pop_shift import pop_shift class PopShiftTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual( pop_shift('reusetestcasesbitcointakeovertheworldmaybewhoknowspe' 'rhaps'), ['spahrepswonkohwebyamdlroweht', 'reusetest...
from {{cookiecutter.app_name}}.models import db from {{cookiecutter.app_name}} import models from faker import Factory as Fake from factory.alchemy import SQLAlchemyModelFactory import factory import logging factory_log = logging.getLogger("factory") factory_log.setLevel(logging.WARNING) faker = Fake.create() class Cat...
"""steamapi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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-bas...
import numpy as np from ghx.base_properties import BasePropertiesClass from ghx.my_print import PrintClass from ghx.pipe import PipeClass from ghx.soil import SoilClass class BoreholeClass: def __init__(self, json_data, print_output): try: self.name = json_data['Name'] except: # pragma:...
from cms.models import CMSPlugin from django.db import models class IframePlugin(CMSPlugin): src = models.URLField(max_length=400)
from pi_trees_ros.pi_trees_ros import * from pi_trees_lib.task_setup import * from skills.dynamic_drive import DynamicDrive from consai_msgs.msg import Pose sys.path.append(os.pardir) from coordinate import Coordinate class TacticLookIntersection(ParallelAll): def __init__(self, name, my_role, target='Enemy_1', ...
from PyQt4 import QtGui import matplotlib.pyplot as plt from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas import orangecanvas.resources as resources import os import sys import numpy as np from orangewidget.settings import Setting from crystalpy.util.PolarizedPhotonBunch import PolarizedP...
import unittest from app.person import * class ThisPerson(unittest.TestCase): def test_register_returns_list(self): '''test that when user enters their registration details, they are stored in a list object''' a = 'anderson' b = 'kenyanya' c = 'andersonkenyanya' self....
''' describe views Copyright (c) 2017 Vanessa Sochat 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, copy, modify, merge, publis...
import os import sys from django.conf import settings from .models import Word def load_words(): proj_dir = settings.ROOT_PATH path = os.path.join(proj_dir, "scowl-7.1", "final", "american-words.35"); if not os.path.exists(path): print "Can't find word list file to load!" sys.exit(1) f =...
from __future__ import absolute_import, unicode_literals from aluno.model import Aluno from zen import router def index(_write_tmpl): url = router.to_path(form) values = {'aluno_form_url': url} _write_tmpl('templates/aluno_home.html', values) def form(_write_tmpl): url = router.to_path(salvar) value...
import numpy as np import warnings from astropy.coordinates import SkyCoord from astropy import units as u from MulensModel.utils import Utils class Coordinates(SkyCoord): """ A class for the coordinates (RA, Dec) of an event. Inherits from astropy.SkyCoord_. May be set as a *str*, pair of *str*, or *Sk...
'''File operations with pathname pattern expansion (remove, move and copy functionality of os and shutil together with glob) List of files/content (as os.listdir) filtered by pattern. Directories operations without error raising for existing/non-existing directories (mkdir, makedirs, rmdir, removedirs) os.remove -> osg...
import urllib, json from django.conf import settings from django.shortcuts import get_object_or_404, redirect, render_to_response, render from django.utils.translation import ugettext, ugettext_lazy as _ from django.core.urlresolvers import resolve, reverse from django.db.models import Count from django.db.models.signa...
import hashlib import string import sys import os import responses import shutil import tempfile from mock import Mock, patch from random import choice from tests.utils import FakeRepoDir from unittest2 import TestCase from hypothesis import given, assume from hypothesis.strategies import text, dictionaries, lists, int...
from __future__ import unicode_literals from django.db import models, migrations import tagging.fields class Migration(migrations.Migration): dependencies = [ ('recipe', '0003_recipe_name'), ] operations = [ migrations.AddField( model_name='recipe', name='tags', ...
from __future__ import unicode_literals import codecs import logging import os import random import sys import time import tweepy _API = None def main(): logging.basicConfig( level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') _CONSUMER_KEY = os.environ['CONSUMER_KEY'] _CONSUMER_SECRET = os.env...
<<<<<<< HEAD <<<<<<< HEAD """A parser for HTML and XHTML.""" import re import warnings import _markupbase from html import unescape __all__ = ['HTMLParser'] interesting_normal = re.compile('[&<]') incomplete = re.compile('&[a-zA-Z#]') entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]') charref = re.compile(...
""" FILE: sample_authentication_async.py DESCRIPTION: This sample demonstrates how to authenticate to the Form Recognizer service. There are two supported methods of authentication: 1) Use a Form Recognizer API key with AzureKeyCredential from azure.core.credentials 2) Use a token credential from azure-...
"""Creating Models for user profile.""" from django.db import models from django.contrib.auth.models import User from django.utils.encoding import python_2_unicode_compatible from django.db.models.signals import post_save from django.dispatch import receiver from multiselectfield import MultiSelectField import uuid DEV...
import logging import os import json from nose import tools import mock import six import phlawg from phlawg import config FULL_CONF_VAR = 'PHLAWG_LOG_CONFIG' LOG_FORMAT_VAR = 'PHLAWG_LOG_FORMAT' DATE_FORMAT_VAR = 'PHLAWG_LOG_DATE_FORMAT' METRIC_FIELDS_VAR = 'PHLAWG_METRIC_FIELDS' METRIC_PACKAGES_VAR = 'PHLAWG_METRIC_P...
"""Config flow for UniFi Network integration. Provides user initiated configuration flow. Discovery of UniFi Network instances hosted on UDM and UDM Pro devices through SSDP. Reauthentication when issue with credentials are reported. Configuration of options through options flow. """ import socket from urllib.parse imp...
import re from optparse import OptionParser import sys def fextract(text, start=None, end=None): """Return the text between regular expressions start and end.""" if type(text) is list: text = ''.join(text) if start is not None: text = re.split(start, text)[1] if end is not None: ...
from __future__ import print_function BOARD_SIZE = 9 ROW_SEPARATOR = "-------------" COLUMN_SEPARATOR = "|" PLAYER_MARKER = ["O", "X"] WINNING_POSITIONS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], # Horizontals [0, 3, 6], [1, 4, 7], [2, 5, 8], # Verticals [0, 4, 8], [2, 4, 6]] ...
import unittest from driftconfig.util import get_drift_config from drift.core.extensions.apikeyrules import get_api_key_rule from drift.tests import DriftTestCase from drift.systesthelper import setup_tenant class ApiKeyRulesTest(DriftTestCase): @classmethod def setUpClass(cls): config_size = { ...
from functools import lru_cache from pprint import pprint @lru_cache(maxsize=128) def num_digits(number): return max( 0, str(number)[::-1].find('.') )
import warnings import sys import argparse from etk.extractors.regex_extractor import RegexExtractor def add_arguments(parser): """ Parse arguments Args: parser (argparse.ArgumentParser) """ parser.description = 'Examples:\n' \ 'python -m etk regex_extrac...