content stringlengths 4 20k |
|---|
""" fgdc.py
Processing functions for processing FGDC
Spec: http://www.fgdc.gov/metadata/csdgm/00.html
Relevant Section: http://www.fgdc.gov/metadata/csdgm/08.html
Dataset creators are stored in the <origin> field.
<idinfo>
<citeinfo>
<origin> <- Originator free text here
... |
import os
import csv
class Airport(object):
"""Represents an airport.
@todo merge with geo lib"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def csv(self):
return [self.code, self.lat, self.lon]
def __repr__(self):
return self.code
#keys = sorted(... |
"""
Copyright (c) 2014, William Stein
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the followi... |
from rest_framework import serializers
from builds.models import Version
from projects.models import Project
class ProjectSerializer(serializers.ModelSerializer):
downloads = serializers.CharField(source='get_downloads', read_only=True)
class Meta:
model = Project
fields = (
'id',... |
# coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de um JOIN',
'%Y-%m-%d': '%d-%m-%Y ',
'%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:... |
import logging
from PropertyEditor import FieldEditor, registerFieldEditorFactory, FieldEditorFactory
from FieldEditorControls import *
from PyQt4 import QtGui, QtCore, uic
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QEventLoop, QEvent, QObject
from gii.qt.helpers import addWidgetWithLayout, restrainWidg... |
"""
Plugin Name : Manage
Plugin Version : 3.2.0
Description:
Gives basic commands to the bot to manage and examine itself.
Contributors:
- Patrick Hennessy
- Euklyd / Popguin
License:
Arcbot is free software: you can redistribute it and/or modify it
under t... |
import os
import sys
from utils import *
import re
import itertools
import numpy as np
from collections import Counter
import operator
### create a dict of original to comma replaced seeds entries. Would make life much easier.
#cd ~/Morgun_Lab/richrr/Type2_Diabetes/DNAShotgunMetagenome/analysis/t2-corr... |
import getpass
import grp
import os
import pwd
import shutil
import subprocess
from abc import abstractmethod, abstractproperty
from twitter.common import log
from twitter.common.dirutil import safe_mkdir, safe_rmtree, touch
from twitter.common.lang import Interface
from gen.apache.aurora.api.constants import TASK_FI... |
"""
=========================
Train error vs Test error
=========================
Illustration of how the performance of an estimator on unseen data (test data)
is not the same as the performance on training data. As the regularization
increases the performance on train decreases while the performance on test
is optim... |
#!/usr/bin/env python3
"""
Module documentation.
"""
# Imports
import yaml
from colorama import Fore
from os import makedirs, path, listdir, chdir, getcwd
from shutil import copyfile
from python_terraform import Terraform, IsNotFlagged
import argparse
from time import sleep
# Parse arguments
parser = argparse.Argumen... |
import sys
from OpenGL.GL import *
from OpenGL.GLU import *
import random
import numpy as np
from math import pi,acos,sin,cos
from gl_scale import scale_get_xmul
from gl_scale import scale_get_ymul
from gl_scale import scale_get_zmul
from gl_base_object import gl_base_object
from triangle import vec
from triangle_i... |
'''
Encryption.Using your solution to the previous problem, and create a "rot13" translator.
"rot13" is an old and fairly simplistic encryption routine where by each letter of the alphabet is
rotated 13 characters. Letters in the first half of the alphabet will be rotated to the equivalent
letter in the second half and... |
"""
Table of Contents Extension for Python-Markdown
===============================================
See <https://pythonhosted.org/Markdown/extensions/toc.html>
for documentation.
Oringinal code Copyright 2008 [Jack Miller](http://codezen.org)
All changes Copyright 2008-2014 The Python Markdown Project
License: [BSD... |
SERVER_TOKEN_TYPE = 'Token'
OAUTH_TOKEN_TYPE = 'Bearer'
AUTHORIZATION_CODE_GRANT = 'authorization_code'
CLIENT_CREDENTIAL_GRANT = 'client_credentials'
IMPLICIT_GRANT = 'implicit'
REFRESH_TOKEN = 'refresh_token'
AUTH_HOST = 'login.uber.com.cn'
ACCESS_TOKEN_PATH = 'oauth/token'
AUTHORIZE_PATH = 'oauth/authorize'
REVOKE_P... |
#!/usr/bin/env python
"""
Flask script aka CLI entry module.
"""
import distutils.dir_util
import logging
import os
from flask_script import Manager, prompt
from logging.handlers import RotatingFileHandler
from putio_automator import create_app, APP_NAME, APP_AUTHOR
import appdirs
app = create_app()
manager = Mana... |
import os
import numpy as np
import scipy.io as sio
import sys
from computation.utils.loadAdjMatrix import loadAdjMat # for loading the LCC
def getDiff(graph_dir, lcc_dir):
csv = "Sample, Full nodes, LCC nodes, Full edges, LCC edges\n"
full_vert = []
full_edge = []
lcc_vert = []
lcc_edge = []
for fn in o... |
import os, AppCore
from Qt import QtCore, QtGui
Data = {
#'*NWSTORAGE' : 'C:/',
'*NWSTORAGE' : os.getenv('*NWSTORAGE'),
'*BLACK' : None,
'AppFont' : QtGui.QFont('Times', 10, QtGui.QFont.Bold),
'AppIconColor1' : QtGui.QColor(17,17,17),
'AppIconColor2' : QtGui.QColor(34,34,34),
'AppIconColor3' : QtGui.QColor... |
"""Classes used in pickling tests, need to be at the module level for
unpickling.
"""
from . import fixtures
class User(fixtures.ComparableEntity):
pass
class Order(fixtures.ComparableEntity):
pass
class Dingaling(fixtures.ComparableEntity):
pass
class EmailUser(User):
pass
class Address(fixt... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from abc import ABCMeta
import paramiko
import os
import ConfigParser
import time
class FTPInfo(object):
def __init__(self):
basedir = os.path.dirname(os.path.dirname(
os.path.abspath(os.path.dirname(__file__))))
self.ft... |
import pprint
from .sixs_exceptions import *
class Outputs(object):
"""Stores the output from a 6S run.
Attributes:
* ``fulltext`` -- The full output of the 6S executable. This can be written to a file with the write_output_file method.
* ``values`` -- The main outputs from the 6S run, stored in ... |
"""
Proxy class for the Gramps databases. Caches lookups from handles.
"""
from gramps.gen.utils.lru import LRU
class CacheProxyDb:
"""
A Proxy for a database with cached lookups on handles.
Does not invalid caches. Should be used only in read-only
places, and not where caches are altered.
"""
... |
# -*- coding: utf-8 -*-
import pywinauto
import pywinauto.clipboard
from . import grid_strategies
from . import clienttrader
class HTClientTrader(clienttrader.BaseLoginClientTrader):
grid_strategy = grid_strategies.Xls
@property
def broker_type(self):
return "ht"
def login(self, user, pass... |
"""Publication workflows."""
from .errors import InvalidPublicationStateError
def review_and_publish_workflow(previous_model, new_deposit):
"""Workflow publishing the deposits on submission."""
from b2share.modules.deposit.api import PublicationStates
new_state = new_deposit['publication_state']
previ... |
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions # type: ignore
from google.api_core import gapic_v1... |
from argparse import ArgumentParser
CONFIG_OPT_DEST = 'config_file_path'
def path_to_cmd_opt(path):
return '--' + '-'.join(map(str.lower, path))
def path_to_dest(path):
return '_'.join(path)
def get_parser(path_n_params, config_file_cmd_line):
parser = ArgumentParser()
parser.add_argument(*config... |
import warnings
import pytz
from werkzeug import abort, redirect
from werkzeug.routing import Map, Submount
from flask_wtf import Form
from wtforms import TextField, PasswordField, validators, BooleanField
from flask.ext.login import login_user, logout_user
from nereid import jsonify, flash, render_template, url_for,... |
##
#
# @author Alexandre Benoit, LISTIC Lab, IUT Annecy le vieux, FRANCE
# @brief a set of generic functions for data management
"""
# a variable
a=1 # default type : int
# an empty list
mylist = []
#a filled list
mylist2=[1,2,3]
#append to a list
mylist.append(10)
# a buggy list
mybuggylist=[1,'a', "Hi"]
#operat... |
"""
The module file for vyos_facts
"""
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': [u'preview'],
'supported_by': 'network'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.vyos.argspec.facts.facts import FactsArgs
from ansib... |
#!/usr/bin/env python
'''
Specific testing of arrays.
'''
__author__ = 'Edna Donoughe'
import unittest
import json
from base64 import b64encode
from flask import url_for
from ooiservices.app import create_app, db
from ooiservices.app.models import Array, User, UserScope, Organization
'''
These tests are additional t... |
import copy
def javascript_date_format(python_date_format):
format = python_date_format.replace(r'Y', 'yyyy')
format = format.replace(r'm', 'mm')
format = format.replace(r'd', 'dd')
if not format:
format = 'yyyy-mm-dd'
return format
def duplicate(obj, changes=None):
""" Duplicates any ... |
#!/usr/bin/env python
"""Bootstrap setuptools installation
To use setuptools in your package's setup.py, include this
file in the same directory and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
To require a specific version of setuptools, set a download
mirror, ... |
import random as rnd
import numpy.random
poisson = numpy.random.poisson
from util import *
from layout import *
from graphics import CardImage, WoundTokenImage
class Card:
def __init__(self, name, imageFileName=None):
self.name = name
self.owner = None
self.controller = None
self.... |
import filediff
from gettext import gettext as _
import gtk
import merge
MASK_SHIFT, MASK_CTRL = 1, 2
class FileMerge(filediff.FileDiff):
differ = merge.AutoMergeDiffer
def __init__(self, prefs, num_panes):
filediff.FileDiff.__init__(self, prefs, num_panes)
self.hidden_textbuffer = gtk.Text... |
#!/usr/bin/env python
import re
pair = re.compile(r'(.)\1')
def contains_two_pairs(string):
return len(re.findall(pair, string)) >= 2
def contains_iol(string):
banned_letters = ['i','o','l']
for letter in banned_letters:
if letter in string:
return True
return False
def contains_abc_string(string... |
from setuptools import setup, find_packages
desc = '''
tmux2html captures full tmux windows or individual panes
then parses their contents into HTML.
'''.strip()
setup(
name='tmux2html',
version='0.1.11',
author='Tommy Allen',
author_email='<EMAIL>',
description=desc,
packages=find_packages(),... |
"""Compatibility with the nrpe-external-master charm"""
# Copyright 2012 Canonical Ltd.
#
# Authors:
# Matthew Wedgwood <<EMAIL>>
import subprocess
import pwd
import grp
import os
import re
import shlex
import yaml
from charmhelpers.core.hookenv import (
config,
local_unit,
log,
relation_ids,
rel... |
from search import Search
class SmokeSearch(Search):
def __init__(self, odota_file, tick_offset):
super().__init__(odota_file, tick_offset)
self.search_phrase = "smoketimings"
def find_interesting_ticks_line(self, j_line, match_id, heroes_dict):
"""
:param line: String. log ... |
import unittest
import testutil
import shutil
import os
import time
import datetime
import hdbfs
import hdbfs.ark
import hdbfs.model
hdbfs.imgdb.MIN_THUMB_EXP = 4
class ThumbCases( testutil.TestCase ):
def setUp( self ):
self.init_env()
def tearDown( self ):
self.uninit_env()
def tes... |
from numpy import *
import netCDF4, datetime
from dateutil.parser import parse
from pylab import date2num,num2date
from pyroms import Dataset
class ocean_time (ndarray):
_unit2sec={}
_unit2sec['seconds'] = 1.0
_unit2sec['minutes'] = 60.0
_unit2sec['hours'] = 3600.0
_unit2sec['days'] = 3600.0*2... |
class ModuleDocFragment(object):
# GCP doc fragment.
DOCUMENTATION = r'''
options:
project:
description:
- The Google Cloud Platform project to use.
type: str
auth_kind:
description:
- The type of credential used.
type: str
required: true
... |
import json
import logging
import os
import re
from typing import Dict, Tuple
from django.conf import settings
from onelogin.saml2.settings import OneLogin_Saml2_Settings
from .exceptions import SamlException
logger = logging.getLogger(__name__)
README = """\
Take care of this folder that could contain private ke... |
"""
TestRuntest.py: a testing framework for the runtest.py command used to
invoke SCons tests.
A TestRuntest environment object is created via the usual invocation:
test = TestRuntest()
TestRuntest is a subclass of TestCommon, which is in turn is a subclass
of TestCmd), and hence has available all of the method... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import threading
from six import StringIO
class _RWBuf(object):
"""An unbounded read-write buffer.
Can be used as a file-like object for reading and writing.
... |
"""Handles parsing of Python code.
Parsing to AST is done via _ast on Python > 2.5, otherwise the compiler
module is used.
"""
from StringIO import StringIO
from mako import exceptions, util
import operator
if util.py3k:
# words that cannot be assigned to (notably
# smaller than the total keys i... |
#! /usr/bin/python
import os
from os.path import join
from os import path
from subprocess import call
PROVISION_DIR = path.dirname(path.realpath(__file__))
REPO_DIR = path.dirname(PROVISION_DIR)
TEMPLATE_DIR = path.join(PROVISION_DIR, 'templates')
SERVER_DIR = path.join(REPO_DIR, 'server')
call('yum update -y'.split... |
#!/usr/bin/python
#########################################################################
# Created Time: 2013-10-27 20:09:01
# File Name: ./latency.py
# Description:
#########################################################################
class CacheEntry:
def __init__(self, path):
self.next_entry = No... |
from pymongo.cursor import Cursor as PymongoCursor
from mongolite.mongo_exceptions import StructureError
from collections import deque
class Cursor(PymongoCursor):
def __init__(self, *args, **kwargs):
self.__wrap = None
if kwargs:
self.__wrap = kwargs.pop('wrap', None)
super(Cur... |
"""Controller class for Vessels
Common functions that will gather information about the cluster
"""
import os
import subprocess
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from kubernetes import Kubernetes
class Controller():
def __init__(self):
# Kubernetes... |
"""
Utilities for working with pandas objects.
"""
from contextlib import contextmanager
from copy import deepcopy
from itertools import product
import operator as op
import warnings
import pandas as pd
from distutils.version import StrictVersion
pandas_version = StrictVersion(pd.__version__)
def july_5th_holiday_o... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... |
from pymongo import MongoClient, ReadPreference, uri_parser
import six
from mongoengine.python_support import IS_PYMONGO_3
__all__ = ['MongoEngineConnectionError', 'connect', 'register_connection',
'DEFAULT_CONNECTION_NAME']
DEFAULT_CONNECTION_NAME = 'default'
if IS_PYMONGO_3:
READ_PREFERENCE = Read... |
# -*- coding: utf-8 -*-
from __future__ import division
import math
from .base import BasePaginator
from ..support.collection import Collection
from ..utils import deprecated
class LengthAwarePaginator(BasePaginator):
def __init__(self, items, total, per_page, current_page=None, options=None):
"""
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import App, Release, Tag, Comment, Screenshot, Download
from markdownx.utils import markdownify
from .forms import Comm... |
"""This is very basic skeleton for data processing application implementing
consumer pattern.
"""
__author__ = '<EMAIL>'
from concurrent.futures import ThreadPoolExecutor
import functools
import logging
import signal
import threading
DEFAULT_NUM_WORKERS = 16
class ConsumerAppBase(object):
"""Base class for t... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# Cinefix
#------------------------------------------------------------
# Licença: GPL (http://www.gnu.org/licenses/gpl-3.0.html)
# Baseado no código do addon youtube
#------------------------------------------------------------
imp... |
from __future__ import print_function
import os
import gzip
from six.moves import cPickle as pickle
from importlib import import_module
from time import time
from weakref import WeakKeyDictionary
from email.utils import mktime_tz, parsedate_tz
from w3lib.http import headers_raw_to_dict, headers_dict_to_raw
from scrapy.... |
from __future__ import print_function
import sys
import os
def RunWithOptions(options):
start_directory = os.getcwd()
from .config import config, SetInitialOptions, LoadLanguages
from .debug import Debug
SetInitialOptions(options)
Debug("Running types highlighter generator", "Information")
De... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Ipv6Gateway(A10BaseClass):
"""Class Description::
IPv6 Gateway.
Class ipv6-gateway supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param ipv6_address: {"optional... |
from test.picardtestcase import PicardTestCase
from picard.util import natsort
class NatsortTest(PicardTestCase):
def test_natkey(self):
self.assertTrue(natsort.natkey('foo1bar') < natsort.natkey('foo02bar'))
self.assertTrue(natsort.natkey('foo1bar') == natsort.natkey('foo01bar'))
self.as... |
__revision__ = "test/MSVS/vs-8.0Exp-exec.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Test that we can actually build a simple program using our generated
Visual Studio 8.0 project (.vcproj) and solution (.sln) files
using Visual C++ 8.0 Express edition.
"""
import os
import sys
import TestSConsM... |
from itertools import repeat
from collections import Counter
import pytest
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from eli5.sklearn.unhashing import InvertableHashingVectorizer
from eli5.sklearn.utils import sklearn_version
@pytest.mark.parametrize(
['always_signed', 'bi... |
from Utils import *
import urllib
import itertools
YT_KEY = 'AIzaSyB-BOZ_o09NLVwq_lMskvvj1olDkFI4JK0'
BASE_URL = "https://www.googleapis.com/youtube/v3/"
PLUGIN_BASE = "plugin://script.extendedinfo/?info="
def handle_videos(results, extended=False):
videos = []
for item in results:
thumb = ""
... |
# -*- coding: utf-8 -*-
# !/usr/bin/python
################################### PART0 DESCRIPTION #################################
# Description:
#
# E-mail: <EMAIL>
# Create: 2015-12-02 19:50:45
# Last:
__author__ = 'yuens'
################################### PART1 IMPORT ######################################
impo... |
import httplib2
class fake_httplib2(object):
def __init__(self, return_type=None):
self.return_type = return_type
def request(self, uri, method="GET", body=None, headers=None,
redirections=5, connection_type=None):
if not self.return_type:
fake_headers = httplib2.... |
import bpy
from bpy.props import FloatProperty
import bmesh
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, repeat_last, fullList
from sverchok.utils.sv_bmesh_utils import bmesh_from_pydata
# by Linus Yng
def solidify(vertices, faces, t):
if not faces or not v... |
from django.db import models
from django.db import connection
from .PUC import PUC
from .common_info import CommonInfo
from .product import Product
from django.utils.translation import ugettext_lazy as _
DEFAULT_CLASSIFICATION_METHOD_CODE = "MA"
class ProductToPUC(CommonInfo):
"""
Each product can be assign... |
import lxml.etree as etree
from translate.storage import base
from translate.misc.typecheck import accepts, IsCallable
from translate.misc.typecheck.typeclasses import Number
from translate.storage.xml_extract import misc
from translate.storage.xml_extract import extract
from translate.storage.xml_extract import unit... |
"""
Logging to memory.
"""
import weakref
from itertools import chain, ifilter
from collections import defaultdict
from Exscript.Log import Log
logger_registry = weakref.WeakValueDictionary() # Map id(logger) to Logger.
class Logger(object):
"""
A QueueListener that implements logging for the queue.
Logs ... |
'''
Probe sysfs: Create input entry for each Multitouch hardware found (linux only).
Thanks to Marc Tardif for the probing code, used from scan-for-mt-device script.
The device discovery is done by this provider. However, the reading of input can
be made by 2 other providers: hidinput or mtdev. mtdev is used prior to... |
import zerorpc
import gevent
import time
import typing
import logbook
class DiscoveryService:
timeout = 15
_log = logbook.Logger("Discovery")
def __init__(self):
self._discovered = {}
self._endpoints = set()
self._tags = []
self._pub = zerorpc.Publisher()
self._su... |
# -*- coding: utf-8 -*-
################################################
from haystack.indexes import *
from haystack import site
from reanalyseapp.models import *
################################################
# For the most basic usage, you can simply register a model with the `site`.
# It will get a `haystack.ind... |
from nova.tests.functional.api_sample_tests import test_servers
class ServersMetadataJsonTest(test_servers.ServersSampleBase):
sample_dir = 'server-metadata'
def _create_and_set(self, subs):
uuid = self._post_server()
response = self._do_put('/servers/%s/metadata' % uuid,
... |
"""
The default command parser. Use your own by assigning
settings.ALTERNATE_PARSER to a Python path to a module containing the
replacing cmdparser function. The replacement parser must matches
on the sme form as the default cmdparser.
"""
from src.utils.logger import log_trace
from django.utils.translation import uge... |
import os
from alembic import command as alembic_command
from alembic import config as alembic_config
from alembic import util as alembic_util
from oslo.config import cfg
_core_opts = [
cfg.StrOpt('core_plugin',
default='',
help=_('Quantum plugin provider module')),
]
_quota_opts =... |
from pogle_opengl import *
from pogle_gltexture import Texture2D, Texture3D
__author__ = 'Clement JACOB'
__copyright__ = "Copyright 2013, The Python OpenGL Engine"
__license__ = "Closed Source"
__version__ = "0.0.1"
__email__ = "<EMAIL>"
__status__ = "Prototype"
class Texture3DAttachment(object):
def _... |
from celery.task import Task
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.crypto import get_random_string
from django.utils.translation import ugettext as _
from documents.models import Document
from projects.models import Export
import os
import requests
import te... |
"""
Spatial lag operations.
"""
__author__ = "Sergio J. Rey <<EMAIL>>, David C. Folch <<EMAIL>>, Levi John Wolf <<EMAIL>"
__all__ = ['lag_spatial', 'lag_categorical']
import numpy as np
from pysal.common import iteritems as diter
def lag_spatial(w, y):
"""
Spatial lag operator.
If w is row standardized, ... |
#!/usr/bin/env python
"""Provides some common functionality for the Labeler site."""
from flask import jsonify, render_template
from flask.ext.restful import reqparse
import database
from server_common import create_app, database_session
import smtplib
from email.mime.text import MIMEText
from email.mime.multipar... |
from . import *
import ft
from sqlitehelper import *
from time import time
def edit_reminder_entry(Id, name=None, amount=None, cat=None):
edit_dict = init_edit_dict([
{
"name": "name",
"value": name,
"type": "string"
},
{
"name": "cat",
"value": cat,
"type": "string"
... |
import unittest
import werks.bus
class TestCountingRelay(object):
def __init__(self, event_bus, out_channel):
self.bus = event_bus
self.ch = out_channel
self.count = 0
def callback(self, arg):
self.count += 1
self.bus.publish(self.ch, arg)
class TestQueuingEventHand... |
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "packaging"
__summary__ = "Core utilities for Python packages"
__uri__ = "https://github.com/pypa/packagin... |
from flask import json, url_for
import pytest
import requests_mock
from app.comms.encryption import encrypt
class WhenGettingLegacyImages:
@pytest.fixture
def mock_storage(self, mocker):
mocker.patch("app.utils.storage.Storage.__init__", return_value=None)
def it_gets_a_standard_image(self, clie... |
from django.conf import settings
from django.utils.translation import get_supported_language_variant
from django.utils.translation.trans_real import language_code_re
from . import Error, Tags, register
E001 = Error(
'You have provided an invalid value for the LANGUAGE_CODE setting: {!r}.',
id='translation.E00... |
# -*- coding: utf-8 -*-
"""Factories to help in tests."""
from datetime import date, timedelta as td
from factory import PostGenerationMethodCall, Sequence
from factory.alchemy import SQLAlchemyModelFactory
from ifc.database import db
from ifc.models import User, Preuser, Role, Fraternity, Party, Guest, School, \
... |
#!/usr/bin/python
import argparse
import sys
def check_negative(value):
dvalue = float(value)
if dvalue < 0.0:
raise argparse.ArgumentTypeError("%s is an invalid value" % value)
return dvalue
def initialize():
parser = argparse.ArgumentParser(description='Generate a dive profile.')
parser.... |
from lxml import html
import requests
import csv
POSITIONS = ['RB', 'WR', 'TE', 'K', 'DST']
YEARS = ['2010', '2011', '2012', '2013', '2014']
WEEKS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17']
URL = 'http://www.footballdb.com/fantasy-football/index.html?pos={0}&yr={1}... |
"""The tests for the demo light component."""
# pylint: disable=protected-access
import unittest
from homeassistant.bootstrap import setup_component
import homeassistant.components.light as light
from tests.common import get_test_home_assistant
ENTITY_LIGHT = 'light.bed_light'
class TestDemoClimate(unittest.TestCa... |
import json, CoolProp.CoolProp as CP
with open('Bell2016Fluids.txt','r') as fp:
lines = fp.readlines()
name2CAS = {}
for line in lines:
Name, longname, CAS, N = line.strip().split(' ')
name2CAS[Name] = CAS
with open('Bell2016Coefficients.txt','r') as fp:
lines = fp.readlines()
with open('mixture_bina... |
import os.path
from tornado import web
import IPython
from nbx.handlers import NBXHandler
import nbx.kernel_client as kernel_client
from notebook.base.handlers import path_regex as notebook_path_regex
CODE_FMT = """
from nbx.handlers.standalone import get_html
get_html({html_obj}, "{attr}")
"""
def autolink(obj):
... |
import hashlib
import logging
import random
import re
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_resp... |
# -*- coding: utf-8 -*-
"""
Display and control a Pomodoro countdown.
Configuration parameters:
- format: define custom display format. See placeholders below
- display_bar: display time in bars when True, otherwise in seconds
- max_breaks: maximum number of breaks
- num_progress_bars: number of progre... |
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling.models import Shift, Rotation2D, Gaussian1D, Identity, Mapping
from astropy.utils import NumpyRNGContext
try:
from scipy import optimize # pyli... |
"""This module implements pluginpod."""
import logging
from swak.datarouter import DataRouter
from swak.plugin import create_plugin_by_name, Input, Output, ProxyInput
MAX_BUFFER_RECORD = 10
MAX_BUFFER_TIME = 1.0
class PluginPod(object):
"""Plugin pod class."""
def __init__(self, def_output):
"""I... |
import json
import pytest
from flask import Flask, jsonify
from flask_api_awesomesauce.api_decorators import (
api_declaration, json_response)
@pytest.fixture
def flask_app():
app = Flask(__name__)
app.config['TESTING'] = True
@app.route('/', methods=['GET'])
@api_declaration('1.0')
def bas... |
import numpy as np
class VectorField:
def __init__(self, data):
self.data = data
def divergence():
def curl():
def gradient():
class Turbine:
def __init__(self, turb):
self.x = turb[0]
self.y = turb[1]
self.H = turb[2]
self.r = turb[4]
def load_wind... |
from msrest.serialization import Model
class Provider(Model):
"""Resource provider information.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: The provider ID.
:vartype id: str
:param namespace: The namespace of the resource provider.
:t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
External inventory script for Scaleway
====================================
Shamelessly copied from an existing inventory script.
This script generates an inventory that Ansible can understand by making API requests to Scaleway API
Requires some python libraries, en... |
from openstack import resource
class FirewallRule(resource.Resource):
resource_key = 'firewall_rule'
resources_key = 'firewall_rules'
base_path = '/fwaas/firewall_rules'
# capabilities
allow_create = True
allow_fetch = True
allow_commit = True
allow_delete = True
allow_list = True... |
"""
Implements non-blocking search operation(s) in a separate non-modal window
that tracks progress while searches are running. For each search that finishes,
the main thread updates the progress bar to provide the user with an
indication of overall progress.
"""
from tkinter import *
from tkinter import ttk
import th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.