code stringlengths 1 199k |
|---|
import os
from flask import Flask, render_template_string, request
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_user import login_required, SQLAlchemyAdapter, UserManager, UserMixin
from flask_user import roles_required
class ConfigClass(object):
# Flask settings
SECRET_KEY = ... |
"""distutils.cygwinccompiler
Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
handles the Cygwin port of the GNU C compiler to Windows. It also contains
the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
cygwin in no-cygwin mode).
"""
import os
import sys
import copy
from sub... |
from pyasn1.type import univ
from pyasn1.codec.cer import decoder
__all__ = ['decode']
class BitStringDecoder(decoder.BitStringDecoder):
supportConstructedForm = False
class OctetStringDecoder(decoder.OctetStringDecoder):
supportConstructedForm = False
RealDecoder = decoder.RealDecoder
tagMap = decoder.tagMap.c... |
import pytest
import u_boot_utils
@pytest.mark.buildconfigspec('cmd_memory')
def test_md(u_boot_console):
"""Test that md reads memory as expected, and that memory can be modified
using the mw command."""
ram_base = u_boot_utils.find_ram_base(u_boot_console)
addr = '%08x' % ram_base
val = 'a5f09876'... |
import sys
import json
import binascii
import xbmc
from lib.yd_private_libs import util, servicecontrol, jsonqueue
sys.path.insert(0, util.MODULE_PATH)
import YDStreamExtractor # noqa E402
import threading # noqa E402
class Service(xbmc.Monitor):
def __init__(self):
self.downloadCount = 0
self.con... |
"""
This sphinx extension builds off of `sphinx.ext.autosummary` to
clean up some issues it presents in the Astropy docs.
The main issue this fixes is the summary tables getting cut off before the
end of the sentence in some cases.
Note: Sphinx 1.2 appears to have fixed the the main issues in the stock
autosummary exte... |
""" Python Character Mapping Codec cp437 generated from 'VENDORS/MICSFT/PC/CP437.TXT' with gencodec.py.
"""#"
import codecs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return co... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from argparse import ArgumentParser
from units.compat import unittest
from units.compat.mock import patch
from ansible.errors import AnsibleError
from ansible.module_utils import six
from ansible.plugins.lookup.lastpass import Looku... |
"""
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.test... |
def main():
with open('file.txt'):
print(42) |
"""GRPCAuthMetadataPlugins for standard authentication."""
import inspect
from concurrent import futures
import grpc
def _sign_request(callback, token, error):
metadata = (('authorization', 'Bearer {}'.format(token)),)
callback(metadata, error)
def _create_get_token_callback(callback):
def get_token_callbac... |
from __future__ import absolute_import
from . import _bigquery
__all__ = ['_bigquery'] |
"""Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
import sys; sys.path.insert(0, "..")
from pgu import gui
app = gui.Desktop()
app.connect(gui.QUIT,app.quit,None)
c = gui.Table()
c.tr()
c.td(gui.Label("Gui Widgets"),colspan=4)
def cb():
... |
from .pidSVG import * |
import sys
import xml.dom.minidom
from libglibcodegen import escape_as_identifier, \
get_docstring, \
NS_TP, \
Signature, \
type_to_gtype, \
xml_escape
def types_to_gtypes(types):
r... |
import json
from odoo import fields
def monkey_patch(cls):
""" Return a method decorator to monkey-patch the given class. """
def decorate(func):
name = func.__name__
func.super = getattr(cls, name, None)
setattr(cls, name, func)
return func
return decorate
fields.Field.__doc... |
import getpass
import os
from flask_script.commands import ShowUrls, Clean
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from sleepypuppy.admin.admin.models import Administrator
from sleepypuppy import app, db
from js_strings import default_script, alert_box, console_log, de... |
from django.core.management.base import NoArgsCommand
from optparse import make_option
from video.management.commands.sub_commands.AddVideo import AddVideo
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--video-link',action='store',dest='video-link',
help=... |
from __future__ import division
__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Greg Caporaso", "Kyle Bittinger", "Justin Kuczynski",
"Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Greg Caporaso"
__email__ = "gregcaporas... |
from __future__ import print_function
import os
import sys
import random
import subprocess
import time
import types
import pexpect
DEFAULT_TIMEOUT = 5
class Strategy(object):
def __init__(self, func=None):
if func is not None:
if sys.version_info < (3,):
self.__class__.execute = ... |
"""Keras Applications are canned architectures with pre-trained weights."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.keras.applications import inception_v3
from tensorflow.python.keras.applications import mobilenet
from tensorflo... |
"""Extra dhcp opts support
Revision ID: 53bbd27ec841
Revises: 40dffbf4b549
Create Date: 2013-05-09 15:36:50.485036
"""
revision = '53bbd27ec841'
down_revision = '40dffbf4b549'
migration_for_plugins = [
'neutron.plugins.openvswitch.ovs_neutron_plugin.OVSNeutronPluginV2'
]
from alembic import op
import sqlalchemy as ... |
"""The Half Normal distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from te... |
import sys, copy
from itertools import *
import benchbase
from benchbase import (with_attributes, with_text, onlylib,
serialized, children, nochange)
class BenchMark(benchbase.TreeBenchMark):
repeat100 = range(100)
repeat1000 = range(1000)
repeat3000 = range(3000)
def __init__(se... |
import abc
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.utils import validators
from openstack_dashboard import api
port_validator = validators.valida... |
tests = r"""
>>> from django.contrib.localflavor.cz.forms import CZPostalCodeField
>>> f = CZPostalCodeField()
>>> f.clean('84545x')
Traceback (most recent call last):
...
ValidationError: [u'Enter a postal code in the format XXXXX or XXX XX.']
>>> f.clean('91909')
u'91909'
>>> f.clean('917 01')
u'91701'
>>> f.clean('1... |
"""passlib.ext.django.models -- monkeypatch django hashing framework"""
import logging; log = logging.getLogger(__name__)
from warnings import warn
from django import VERSION
from django.conf import settings
from passlib.context import CryptContext
from passlib.exc import ExpectedTypeError
from passlib.ext.django.utils... |
"""
The NetworkCollector class collects metrics on network interface usage
using /proc/net/dev.
* /proc/net/dev
"""
import diamond.collector
from diamond.collector import str_to_bool
import diamond.convertor
import os
import re
try:
import psutil
except ImportError:
psutil = None
class NetworkCollector(diamond... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import string
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch
from ansible.inventory.manager import InventoryManager, split_host_pattern
from ansible.vars.manager import VariableManager
from uni... |
import unittest
from scrapy.contrib.downloadermiddleware.redirect import RedirectMiddleware
from scrapy.spider import BaseSpider
from scrapy.exceptions import IgnoreRequest
from scrapy.http import Request, Response, HtmlResponse, Headers
class RedirectMiddlewareTest(unittest.TestCase):
def setUp(self):
self... |
import unittest
class StringProcessingTestBase(unittest.TestCase):
# The backslash character. Needed since there are limitations when
# using backslashes at the end of raw-strings in front of the
# terminating " or '.
bs = "\\"
# Basic test strings all StringProcessing functions should test.
tes... |
from __future__ import absolute_import
import pytest
from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleFailJson, AnsibleExitJson
from ansible.module_utils import basic
from ansible.module_utils.network.ftd.common import FtdConfigurationError, FtdServerError, FtdUnexpectedResponse
from ansibl... |
__doc__="""Use OpenDocument to generate your documents."""
import zipfile, time, sys, mimetypes, copy
from cStringIO import StringIO
from namespaces import *
import manifest, meta
from office import *
import element
from attrconverters import make_NCName
from xml.sax.xmlreader import InputSource
from odfmanifest import... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleParserError, AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import iteritems, string_types
from ansible.playbook.attribute import Attribute, Fi... |
import abc
import importlib
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
class BaseEventsPushBackend(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def emit_event(self, message:str, *, routing_key:str, channel:str="events"):
pass
def load_class(path):
... |
""" drizzled.py: code to allow a serverManager
to provision and start up a drizzled server object
for test execution
"""
import os
from lib.server_mgmt.server import Server
class drizzleServer(Server):
""" represents a drizzle server, its possessions
(datadir, ports, etc), and methods for controlli... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
from frappe import _
from frappe.model.document import Document
class CForm(Document):
def validate(self):
"""Validate invoice that c-form is applicable
and no other c-form is received for that"""
for d in self.get('invoice_detai... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
float_or_none,
parse_age_limit,
)
class TvigleIE(InfoExtractor):
IE_NAME = 'tvigle'
IE_DESC = 'Интернет-телевидение Tvigle.ru'
_VALID_URL = r'http://(?:www\.)?tvigle\.ru/(?:[^/]+/)+(?P<id>[^/]+)/$'
_T... |
import mock
import pytest
import yaml
import inspect
import collections
from ansible.module_utils.six import string_types
from ansible.modules.cloud.openstack import os_server
class AnsibleFail(Exception):
pass
class AnsibleExit(Exception):
pass
def params_from_doc(func):
'''This function extracts the docst... |
import numpy as np
import scipy as sp
from scipy import ndimage
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_raises
from sklearn.feature_extraction.image import (
img_to_graph, grid_to_graph, extract_patches_2d,
reconstruct_from_patches_2d, PatchExtractor, extract_patches)
f... |
type='TrueType'
name='Calligrapher-Regular'
desc={'Ascent':899,'Descent':-234,'CapHeight':731,'Flags':32,'FontBBox':'[-50 -234 1328 899]','ItalicAngle':0,'StemV':70,'MissingWidth':800}
up=-200
ut=20
cw={
'\x00':800,'\x01':800,'\x02':800,'\x03':800,'\x04':800,'\x05':800,'\x06':800,'\x07':800,'\x08':800,'\t':800,'\n':80... |
'''
Functions to load the test cases ("koans") that make up the
Path to Enlightenment.
'''
import io
import unittest
KOANS_FILENAME = 'koans.txt'
def filter_koan_names(lines):
'''
Strips leading and trailing whitespace, then filters out blank
lines and comment lines.
'''
for line in lines:
l... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_mariadbdatabase_info
version_added: "2.9"
short_descri... |
from . import models
from . import wizard |
DOCUMENTATION = '''
---
module: vca_fw
short_description: add remove firewall rules in a gateway in a vca
description:
- Adds or removes firewall rules from a gateway in a vca environment
version_added: "2.0"
options:
username:
description:
- The vca username or email address, if not set the enviro... |
import copy
from mongoengine.errors import InvalidQueryError
from mongoengine.queryset import transform
__all__ = ('Q',)
class QNodeVisitor(object):
"""Base visitor class for visiting Q-object nodes in a query tree.
"""
def visit_combination(self, combination):
"""Called by QCombination objects.
... |
"""Constants for the Bluesound HiFi wireless speakers and audio integrations component."""
DOMAIN = "bluesound"
SERVICE_CLEAR_TIMER = "clear_sleep_timer"
SERVICE_JOIN = "join"
SERVICE_SET_TIMER = "set_sleep_timer"
SERVICE_UNJOIN = "unjoin" |
"""Unit tests of the tfdbg Stepper."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.client import session
from tensorflow.python.debug.lib.stepper import NodeStepper
from tensorflow.python.framework import constant_op
from tensorflow... |
from httplib import FakeSocket, HTTPConnection, HTTP
import socket
import string
import xmlrpclib
from types import StringTypes
from sys import hexversion
try:
import SSHTransport
ssh_enabled = True
except ImportError:
# SSHTransport is disabled on Python <2.4, because it uses the subprocess
# package.
... |
import os #@UnusedImport
import sys #@UnusedImport
import sre_compile
from nsiqcppstyle_util import * #@UnusedWildImport
class RuleManager :
def __init__(self, runtimePath) :
self.availRuleNames = []
basePath = os.path.join(runtimePath, "rules")
ruleFiles = os.listdir(basePath)
ruleP... |
import signal
import subprocess
import io
import os
import re
import locale
import tempfile
import warnings
from luigi import six
class FileWrapper(object):
"""
Wrap `file` in a "real" so stuff can be added to it after creation.
"""
def __init__(self, file_object):
self._subpipe = file_object
... |
"""GSSAPI authentication mechanism for PyXMPP SASL implementation.
Normative reference:
- `RFC 4752 <http://www.ietf.org/rfc/rfc4752.txt>`__
"""
__docformat__ = "restructuredtext en"
import base64
import kerberos
import logging
from .core import ClientAuthenticator, Response, Success
from .core import sasl_mechanism
... |
"""
Some scripts define objects that we want to import via yaml files
that we pass to the script, so this directory must be a python
module, rather than just a directory full of scripts.
""" |
{
'name': 'Invoicing Journals',
'version': '1.0',
'category': 'Sales Management',
'description': """
The sales journal modules allows you to categorise your sales and deliveries (picking lists) between different journals.
==================================================================================... |
""" A code generator (needed by ModToolAdd) """
from templates import Templates
import Cheetah.Template
from util_functions import str_to_fancyc_comment
from util_functions import str_to_python_comment
from util_functions import strip_default_values
from util_functions import strip_arg_types
from util_functions import ... |
"""
Implementation of RFC2617: HTTP Digest Authentication
@see: U{http://www.faqs.org/rfcs/rfc2617.html}
"""
from zope.interface import implements
from twisted.cred import credentials
from twisted.web.iweb import ICredentialFactory
class DigestCredentialFactory(object):
"""
Wrapper for L{digest.DigestCredential... |
"""Astroid hooks for six.moves."""
import sys
from textwrap import dedent
from astroid import MANAGER, register_module_extender
from astroid.builder import AstroidBuilder
def six_moves_transform_py2():
return AstroidBuilder(MANAGER).string_build(dedent('''
import urllib as _urllib
import urllib2 as _urllib2... |
import cgi
import errno
import io
import mimetypes
import os
import posixpath
import re
import shutil
import stat
import sys
import tempfile
from os import path
import django
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.core.management.utils import handl... |
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 5000 RTP/SAVP 0
a=crypto:1 aes_cm_128_hmac_sha1_80 inline:WnD7c1ksDGs+dIefCEo8omPg4uO8DYIinNGL5yxQ
m=audio 4000 RTP/AVP 0
"""
pjsua_args = "--null-audio --auto-answer 200 --use-srtp 0"
extra_headers... |
"""
Verifies simple rules when using an explicit build target of 'all'.
"""
import TestGyp
import os
import sys
test = TestGyp.TestGyp(formats=['make', 'ninja', 'android', 'xcode', 'msvs'])
test.run_gyp('actions.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('actions.gyp', chdir='relocate/src')
expe... |
"""
This module implements connections for MySQLdb. Presently there is
only one class: Connection. Others are unlikely. However, you might
want to make your own subclasses. In most cases, you will probably
override Connection.default_cursor with a non-standard Cursor class.
"""
from MySQLdb import cursors
from _mysql_e... |
class A:
def __init__(self, a:int, b:float, *args:tuple, c:complex, **kwargs:dict) -> None:
pass
class B(A):
def <warning descr="Call to __init__ of super class is missed">__i<caret>nit__</warning>(self, d:str, *, e:bytes) -> list:
pass |
def FOUR_CHAR_CODE(x): return x
true = True
false = False
rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1
asiAliasName ... |
class C(object):
def f(self, name):
return name
__getattr__ = f
c = C()
print(c.foo) #pass |
a = [1 2 3] |
class A:
def <weak_warning descr="Function name should be lowercase">fooBar</weak_warning>(self): pass
class B(A):
def fooBar(self): pass |
def x():
print "bar"
print "foo"
print "xyzzy" |
__all__ = [
'Charset',
'add_alias',
'add_charset',
'add_codec',
]
import email.base64mime
import email.quoprimime
from email import errors
from email.encoders import encode_7or8bit
QP = 1 # Quoted-Printable
BASE64 = 2 # Base64
SHORTEST = 3 # the shorter of QP and base64, but only fo... |
"""
This package contains Docutils parser modules.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import Component
if sys.version_info < (2,5):
from docutils._compat import __import__
class Parser(Component):
component_type = 'parser'
config_section = 'parsers'
def parse(self, inputstri... |
"""
Generic relations
Generic relations let an object have a foreign key to any object through a
content-type/object-id field. A ``GenericForeignKey`` field can point to any
object, be it animal, vegetable, or mineral.
The canonical example is tags (although this example implementation is *far*
from complete).
"""
from... |
from contextlib import contextmanager
from .termui import get_terminal_size
from .parser import split_opt
from ._compat import term_len
FORCED_WIDTH = None
def measure_table(rows):
widths = {}
for row in rows:
for idx, col in enumerate(row):
widths[idx] = max(widths.get(idx, 0), term_len(col... |
from datetime import datetime
from lxml import etree
from flask import Flask, Response
from Adafruit_BBIO import ADC
app = Flask(__name__)
def get_current():
voltage = get_adc_voltage()
current = 109.2 * voltage + 5.3688
return current
def get_adc_voltage():
# Read a value from the ADC
value = ADC.r... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
TIME_ZONE = 'Etc/UTC'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY... |
from flatten import *
POS_SIZE = 2**23 - 1
NEG_SIZE = -2**23
OPTIMIZE = True
OPTIMIZERS = {
'set': 'SET',
'setglobal': 'SET_GLOBAL',
'local': 'SET_LOCAL',
'get': 'GET',
'getglobal': 'GET_GLOBAL',
'return': 'RETURN',
'recurse': 'RECURSE',
'drop': 'DROP',
'dup': 'DUP',
'[]': 'NEW_LIST',
'{}': 'NEW_DICT',
'swa... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0020_auto_20200421_0851'),
]
operations = [
migrations.AddField(
model_name='localconfig',
name='need_dovecot_update',
field=models.BooleanField(defa... |
from . import meta_selector # noqa
from .pg import PatternGenerator
from .selector import Selector
PatternGenerator('')
Selector('') |
import subprocess
import os
from pathlib import Path
cwd = os.getcwd()
try:
print(os.getcwd())
subprocess.call(['make'])
# res = subprocess.check_output('uname -a',shell=True)
res = subprocess.check_output(
r"./darknet detector test cfg/coco.data cfg/yolo.cfg yolo.weights /home/zaki/NoooDemo/000... |
from loguru import logger
from pathlib import Path
def check_meta_yaml_for_noarch(fn:Path, text=None):
import re
logger.debug("Checking for noarch")
if text is None:
with open(fn, "rt") as fl:
text = fl.read()
mo = re.search(r"\n\s*noarch_python:\s*True", text)
if mo:
log... |
from __future__ import unicode_literals
import re
import os
from django.shortcuts import render
from django.conf import settings
def index(request):
p = re.compile(r'^app\d+_')
apps = (a.split('_') for a in settings.INSTALLED_APPS if p.match(a))
return render(request, 'ignore_me/index.html',
... |
from __future__ import print_function, division, absolute_import
from george import kernels, GP
import numpy as np
from kglib import fitters
from scipy.integrate import quad
from scipy.optimize import minimize
class HistFitter(fitters.Bayesian_LS):
def __init__(self, mcmc_samples, bin_edges):
"""
Hi... |
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
from roppy import SGrid
from roppy.mpl_util import landmask
from roppy.trajectories import curly_vectors
ncfile = "data/ocean_avg_example.nc"
timeframe = 3 # Fourth time frame
subgrid = (110, 170, 35, 90)
z = 25
stride = 2
speedlevels = np.... |
from __init__ import redis_db
from werkzeug.security import generate_password_hash, check_password_hash
from os import urandom
from base64 import b64encode
class User(object):
def __init__(self):
self.username = "" # required
self.password_hash = "" # required
self.phone_number = "" # requir... |
import functions
import heapq
import vtbase
registered = True
class StreamExcept(vtbase.VT):
def BestIndex(self, constraints, orderbys):
return (None, 0, None, True, 1000)
def VTiter(self, *parsedArgs, **envars):
largs, dictargs = self.full_parse(parsedArgs)
if len(largs) < 1:
... |
import json, logging, os, re, subprocess, shlex
from tools import get_category_by_status
log = logging.getLogger()
meta_files = ['Disassembly', 'Stacktrace', 'Registers',
'SegvAnalysis', 'ProcMaps', "BootLog" , "CoreDump",
"BootDmesg", "syslog", "UbiquityDebug.gz", "Casper.gz",
"UbiquityPartman.... |
import hashlib
import os
import sys
if len(sys.argv) < 3: #1
print("You need to specify two directories:") #1
print(sys.argv[0], "<directory 1> <directory 2>") #1
sys.exit() #1
directory1 = sys.argv[1] ... |
"""
本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法
class, method, func, exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from sqlite4dummy import *
from sqlite4dummy.tests.basetest import *
from datetime import datetime, date
import unittest
class MetaDataUnittest(un... |
import sys
def solve(X, Y, N):
r = []
for i in range(1, N + 1):
if i % X == 0 and i % Y == 0:
r.append('FB')
elif i % X == 0:
r.append('F')
elif i % Y == 0:
r.append('B')
else:
r.append(str(i))
print ' '.join(r)
def main():
... |
import ConfigParser
import sys, traceback
from slackclient import SlackClient
from chatterbot import ChatBot
import os
from os import listdir
from os.path import isfile, join
from chatterbot.trainers import ChatterBotCorpusTrainer
config = ConfigParser.SafeConfigParser({"host": "searchhub.lucidworks.com", "port":80})
c... |
"""
filename: controllers.py
description: Controllers for committee notes.
created by: Chris Lemelin (cxl8826@rit.edu)
created on: 04/20/18
"""
from flask_socketio import emit
from app.decorators import ensure_dict
from app import socketio, db
from app.committee_notes.models import *
from app.committees.models import *... |
import uuid
from typing import Optional, Union
from mitmproxy import connection
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import tcp
from mitmproxy import websocket
from mitmproxy.test.tutils import treq, tresp
from wsproto.frame_protocol import Opcode
def ttcpflow(client_conn=True, server_co... |
from django.test import Client
import mock as mock
from image_converter.tests.base import ImageConversionBaseTestCase
from image_converter.utils.convert_image import convert_image_to_jpeg
__author__ = 'Dominic Dumrauf'
class ViewsTestCase(ImageConversionBaseTestCase):
"""
Tests the 'views'.
"""
def test... |
from pydub import AudioSegment, scipy_effects, effects
import os
import settings, util
def combine_samples(acc, file2, CROSSFADE_DUR=100):
util.debug_print('combining ' + file2)
sample2 = AudioSegment.from_wav(file2)
output = acc.append(sample2, crossfade=CROSSFADE_DUR)
output = effects.normalize(output... |
from ctypes import (windll, CDLL, Structure, byref, sizeof, POINTER,
c_char, c_short, c_ushort, c_int, c_uint, c_ulong,
c_void_p, c_long, c_char_p)
from ctypes.wintypes import HANDLE, DWORD
import socket, time, os, struct, sys
from optparse import OptionParser
usage = "%prog -O ... |
from pathlib import Path
class MarkdownParser():
def __init__(self, text):
self.text = text
self.lines = text.split('\n')
def title(self):
return self.lines[0].split(' ')[1]
def header(self, name, level, include_header=False):
start = False
end = False
content... |
import functools
from common.tornado_cookies import get_secure_cookie, generate_secure_cookie
from core import cookies
class Perms(object):
NONE = None
READ = 'r'
WRITE = 'w'
def _permission_level(user, room):
"""
`user`'s permission level on `room`, ignoring cookies
"""
if not user.is_authe... |
from difflib import get_close_matches
from thefuck.utils import sudo_support, get_all_executables, get_closest
@sudo_support
def match(command, settings):
return 'not found' in command.stderr and \
bool(get_close_matches(command.script.split(' ')[0],
get_all_executables(... |
from __future__ import division
__author__ = "Jon Sanders"
__copyright__ = "Copyright 2014, Jon Sanders"
__credits__ = ["Jon Sanders"]
__license__ = "GPL"
__version__ = "1.9.1"
__maintainer__ = "Jon Sanders"
__email__ = "jonsan@gmail.com"
__status__ = "Development"
from qiime.util import load_qiime_config, parse_comman... |
"""
Load the CCGOIS datasets into a CKAN instance
"""
import dc
import json
import slugify
import ffs
def make_name_from_title(title):
# For some reason, we're finding duplicate names
name = slugify.slugify(title).lower()[:99]
if not name.startswith('ccgois-'):
name = u"ccgois-{}".format(name)
r... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from .base import FunctionalTest
class RecipeEditTest(FunctionalTest):
def test_can_add_a_recipe(self):
# Ben goes to the recipe website homepage
self.browser.get(self.server_url)
# He notices the page title menti... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.