content stringlengths 4 20k |
|---|
import os
import numpy as np
import soundfile as sf
import argparse
from commonfate import decompose
def export(input, input_file, output_path, samplerate):
if not os.path.exists(output_path):
os.makedirs(output_path)
basepath = os.path.join(
output_path, os.path.splitext(os.path.basename(inp... |
from openerp.osv import osv
class pos_payment_report(osv.osv_memory):
_name = 'pos.payment.report'
_description = 'Payment Report'
def print_report(self, cr, uid, ids, context=None):
"""
To get the date and print the report
@param self: The object pointer.
@param cr: A d... |
# Tests for rich comparisons
import unittest
from test import test_support
import operator
class Number:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return self.x < other
def __le__(self, other):
return self.x <= other
def __eq__(self, other):
return... |
""" Clean up unused drivers """
from jobs.helpers import *
import logging
import os
import shutil
import subprocess
def job_cleanup_drivers(self):
msg_job_start('job_cleanup_drivers')
###########################################################################
# CLEANUP XORG DRIVERS
#########################... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from .iosxr_module import TestIosxrModule, load_fixture, set_module_args
from ansible.modules.network.iosxr import iosxr_facts
class TestIosxrFacts(TestIosxrModule):
m... |
"""
Demostrative PURL implementing a redirection to the very last record
(of a collection)
"""
from invenio.config import CFG_SITE_NAME, CFG_SITE_RECORD
from invenio.search_engine import perform_request_search
from invenio.bibdocfile import BibRecDocs, InvenioBibDocFileError
def goto(cc=CFG_SITE_NAME, p='', f='', sf=... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Unit test for the linux distribution parser."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import io
import os
from absl import app
from grr_response_core.lib.parsers import linux_release_parser
fr... |
from django.core.urlresolvers import reverse
from django.test import Client
from mozillians.common.tests import TestCase, requires_login
from mozillians.users.tests import UserFactory
class LoginTests(TestCase):
@requires_login()
def test_login_anonymous(self):
client = Client()
client.get(r... |
class ModuleDocFragment(object):
# Docker doc fragment
DOCUMENTATION = '''
options:
docker_host:
description:
- "The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the
TCP connection string. For example, 'tcp://192.0.2.23:2... |
import os
from botocore.docs.service import ServiceDocumenter
def generate_docs(root_dir, session):
"""Generates the reference documentation for botocore
This will go through every available AWS service and output ReSTructured
text files documenting each service.
:param root_dir: The directory to w... |
import pytest
import numpy as np
from cycleindex.cyclecount import (
cycle_count
)
@pytest.mark.parametrize("A, expected", [
(
np.array([[0, 0.5, 0],
[0, 0, -0.5],
[0.5, 0, 0]]),
([0, 0, -0.12500, 0, 0, 0, 0], [0, 0, 0.12500, 0, 0, 0, 0])
),
(
... |
from flask import Blueprint, jsonify, request
from app import db
from app.api import InvalidUsage, LinkHeaderBuilder, parse_json, parse_arg, \
parse_pagination_args, sql_ordering, handle_invalid_usage
from app.api.auth import require_authorization
from app.api.comment_validators import validate_name
from app.mode... |
"""checker for use of Python logging
"""
import six
import astroid
from pylint import checkers
from pylint import interfaces
from pylint.checkers import utils
from pylint.checkers.utils import check_messages
MSGS = {
'W1201': ('Specify string format arguments as logging function parameters',
'lo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Written in place of AboutBlocks in the Ruby Koans
#
# Note: Both blocks and generators use a yield keyword, but they behave
# a lot differently
#
from runner.koan import *
class AboutGenerators(Koan):
def test_generating_values_on_the_fly(self):
... |
"""
A simple example demonstrating basic Spark SQL features.
Run with:
./bin/spark-submit examples/src/main/python/sql/basic.py
"""
from __future__ import print_function
# $example on:init_session$
from pyspark.sql import SparkSession
# $example off:init_session$
# $example on:schema_inferring$
from pyspark.sql imp... |
import pygame
from pygame.locals import *
class Font(object):
def __init__(self, font, color=(255, 255, 255)):
#Dict to hold the letter images
self.letters = {}
import os
letters = {}
format = " abcdefghijklmnopqrstuvwxyz0123456789-+:,.=!)(?><"
... |
import os, sys
from nox.lib.core import *
from nox.coreapps.testharness.testdefs import *
class ModTestCase(Component):
def __init__(self, ctxt):
Component.__init__(self, ctxt)
def configure(self, configuration):
pass
def getInterface(self):
return str(ModTestCase)
def ... |
"""
The module for some general debug tools
"""
import numpy as np
def checkFinite(arr, name=None):
if name is None:
name = 'Array with ID['+str(id(arr))+']'
if np.any(np.logical_not(np.isfinite(arr))):
idx = np.where(np.logical_not(np.isfinite(arr)))[0]
print(name+' at indices '+str(... |
# Abstract classes.
class Event(object):
def __init__(self, start_mark=None, end_mark=None):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
if hasattr(self, key)]
argum... |
"""Provides type checking routines.
This module defines type checking utilities in the forms of dictionaries:
VALUE_CHECKERS: A dictionary of field types and a value validation object.
TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing
function.
TYPE_TO_SERIALIZE_METHOD: A dictionary with fiel... |
import unittest
from airflow import DAG
from airflow.contrib.operators.slack_webhook_operator import SlackWebhookOperator
from airflow.utils import timezone
DEFAULT_DATE = timezone.datetime(2017, 1, 1)
class TestSlackWebhookOperator(unittest.TestCase):
_config = {
'http_conn_id': 'slack-webhook-default'... |
import errno
import json
import os
import re
import shutil
import subprocess
import sys
from contextlib import contextmanager
import click
import yaml
from setuptools import find_packages
def fail(message, *args, **kwargs):
click.echo(click.style('Error: ' + message.format(*args), fg='red', bold=True), err=True)... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ComicSite.description'
db.add_column('comicsite_comicsite', 'description',
... |
""" Vehicles program.
This program can be used to identify the start and the end of a vehicle's trajectory.
"""
import os
import wx
import inspect
from PIL import Image
from collections import deque
from abstractframe import AbstractFrame
from convert import Convert
from imageoperations import ImageOperations
from ... |
# -*- coding: utf-8 -*-
"""
flask_oauth
~~~~~~~~~~~
Implements basic OAuth support for Flask.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import httplib2
from functools import wraps
from urlparse import urljoin
from flask import request, session, json, ... |
import os
from nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription
# the sub-experiment configuration
config = \
{
'dataSource': 'file://' + os.path.join(os.path.dirname(__file__),
'../datasets/simple_0.csv'),
... |
from south.db import db
from django.db import models
from mysite.profile.models import *
class Migration:
def forwards(self, orm):
# Adding field 'Person.dont_guess_my_location'
db.add_column('profile_person', 'dont_guess_my_location', orm['profile.person:dont_guess_my_location'])
... |
"""
=============================================
Integration and ODEs (:mod:`scipy.integrate`)
=============================================
.. currentmodule:: scipy.integrate
Integrating functions, given function object
============================================
.. autosummary::
:toctree: generated/
quad ... |
# April 24, 2009
# S.D. Peckham
import wx
#----------------------------------------------------------------
class Plot_Window(wx.Window):
def __init__(self, parent, title, labels):
wx.Window.__init__(self, parent)
self.title = title
self.labels = labels
self.data = [0.0] ... |
try:
import boto
import boto.ec2
import boto.vpc
from boto.exception import BotoServerError
HAS_BOTO=True
except ImportError:
HAS_BOTO=False
def boto_exception(err):
'''generic error message handler'''
if hasattr(err, 'error_message'):
error = err.error_message
elif hasattr(... |
"""A PEP 517 interface to setuptools
Previously, when a user or a command line tool (let's call it a "frontend")
needed to make a request of setuptools to take a certain action, for
example, generating a list of installation requirements, the frontend would
would call "setup.py egg_info" or "setup.py bdist_wheel" on t... |
from ige.Const import *
## additional object types
T_GALAXY = 100
T_SYSTEM = 101
T_PLANET = 102
T_FLEET = 103
T_ALLIANCE = 104
T_TECHNOLOGY = 105
T_ASTEROID = 106
T_NATURE = 107
T_AIPLAYER = 108
T_AIRENPLAYER = 109
T_AIMUTPLAYER = 110
T_AIPIRPLAYER = 111
T_AIEDENPLAYER = 112
T_PIRPLAYER = 113
T_WORMHO... |
#! /usr/bin/env python
from subprocess import Popen,PIPE,STDOUT
import collections
import os
import sys
import time
import math
import os
from urllib2 import urlopen
SERVER_IP = urlopen('https://api.ipify.org/').read()
NODE_LIST = urlopen('https://pastebin.com/raw/haX0XxCA').read()
BOOTSTRAP_URL = "https://mega.nz/#!5... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Seunghyun Yoo (<EMAIL>)
"""
from . import htmlparser, textparser
class Tokenizer(object):
def __init__(self):
pass
@staticmethod
def feature(parser_type, raw_string):
parser = Tokenizer.create_parser(parser_type)
pa... |
from django.db import models
from django.db.models.deletion import Collector
from django.db.models.related import RelatedObject
from django.forms.forms import pretty_name
from django.utils import formats
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.text import cap... |
""" Test script for the unicodedata module.
Written by Marc-Andre Lemburg (<EMAIL>).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import sys
import unittest
import hashlib
import subprocess
import test.test_support
encoding = 'utf-8'
### Run tests
class UnicodeMethodsTest(unittest.TestCase)... |
"""
Docutils component-related transforms.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import re
import time
from docutils import nodes, utils
from docutils import ApplicationError, DataError
from docutils.transforms import Transform, TransformError
class Filter(Transform):
"""
Include or e... |
"""Unit tests for the Paver server tasks."""
import os
from paver import tasks
from unittest import TestCase
class PaverTestCase(TestCase):
"""
Base class for Paver test cases.
"""
def setUp(self):
super(PaverTestCase, self).setUp()
# Show full length diffs upon test failure
... |
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"return_address.c:63",
"kprobes.c:1493",
"rcutree.c:1614",
"af_unix.c:893",
... |
import sys, os
# Quick hack to put frontendadmin from the parent directory into pythonpath
# If this is not working correctly, uncomment these lines and put
# frontendadmin manually into pythonpath.
sys.path.append(
os.path.abspath(
os.path.normpath('%s/../' % os.path.dirname(__file__))
)
)
PROJECT_RO... |
# Test sensors.py ability to read from two sensor boards.
import pytest
import responses
from panoptes.pocs.sensor import remote
from panoptes.pocs.sensor import power
from panoptes.utils import error
@pytest.fixture
def remote_response():
return {
"data": {
"source": "sleeping",
... |
from setuptools import setup, find_packages
import re
module_file = open("teuthology/__init__.py").read()
metadata = dict(re.findall(r"__([a-z]+)__\s*=\s*['\"]([^'\"]*)['\"]", module_file))
long_description = open('README.rst').read()
setup(
name='teuthology',
version=metadata['version'],
packages=find_pa... |
__author__ = '<EMAIL> (Jeff Scudder)'
import StringIO
import pickle
import os.path
import tempfile
import atom.http_core
class Error(Exception):
pass
class NoRecordingFound(Error):
pass
class MockHttpClient(object):
debug = None
real_client = None
last_request_was_live = False
# The following membe... |
import numpy
import random
from api import *
from util import *
class KMeansClusterer(VectorSpaceClusterer):
"""
The K-means clusterer starts with k arbitrary chosen means then allocates
each vector to the cluster with the closest mean. It then recalculates the
means of each cluster as the centroid of... |
#!/usr/bin/env python
import json
from profanity import profanity
# Too many false positives with "cockroaches".
profanity.get_words()
profanity.words.remove('cock')
import db
# note that this file is relative to the root of the project, not this file.
OUT_FILE = 'site/frontend_data/summaries.json'
def summarize_by... |
"""
Simulation of a rotating 3D Cube
Developed by Leonel Machava <<EMAIL>>
http://codeNtronix.com
"""
import sys, math, pygame
from operator import itemgetter
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from quad.motor import calculate_dc_for_motor
clas... |
#!/usr/bin/python
"""
Read the deepSNV res (the concatenated one, where the sample name is the first column)
And convert it to VCF, to feed it into Vagrent
"""
import sys
import math
import decimal
class Vari:
def __init__(self):
self.chr = ""
self.pos = 0
self.ref = ""
self.alt = ""
self.pval = lis... |
from django.conf import settings
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.admin.options import IS_POPUP_VAR
from django.contrib.admin.utils import unquote
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import (
AdminPass... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
from django.db import migrations, models
def create_course(Commander, Course, data):
cmdr, _ = Commander.objects.get_or_create(
name=data['created_by']
)
course, _ = Course.objects.get_or_create(
title=... |
import argparse
import logging
from config.tag.list_tag import ListTag
LOG = logging.getLogger(__name__)
def add_subparser(subparsers: argparse._SubParsersAction):
"""
Add a command line subparser for displaying a list of available tags.
:param subparsers: Object that will contain the argument definiti... |
import os
import sys
import imp
import json
import logging
import requests
import prettytable
from os.path import expanduser
from cliff.command import Command
try:
home = expanduser("~")
filename = os.path.join(home, '.bitbucket.py')
creds = imp.load_source('.bitbucket', filename)
user = creds.usernam... |
"""
Account cron jobs
"""
import codecs
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.db.models import Q
from django.utils.html import strip_tags
from django.contrib.sites.models import Site
from datetime import datetime, timedelta
from treeio.core.mail imp... |
import os
import warnings
from collections import Counter, OrderedDict
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache
from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango110Warni... |
'''
Tests for fileinput module.
Nick Mathewson
'''
import unittest
from test.test_support import verbose, TESTFN, run_unittest
from test.test_support import unlink as safe_unlink
import sys, re
from StringIO import StringIO
from fileinput import FileInput, hook_encoded
# The fileinput module has 2 interfaces: the Fil... |
"""Tests for calculator strategies."""
import random
import axelrod
from .test_player import TestPlayer
C, D = axelrod.Actions.C, axelrod.Actions.D
class TestCalculator(TestPlayer):
name = "Calculator"
player = axelrod.Calculator
expected_classifier = {
'memory_depth': float('inf'),
'... |
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from simple_salesforce import Salesforce
import base64
import hashlib
import hmac
import json
@csrf_exempt
def index(request):
"""
When this view is loaded in a canvas app, Salesforce send... |
# -*- coding: utf-8 -*-
import httplib as http
from flask import request
from framework.exceptions import HTTPError
from website.util.sanitize import escape_html
from website.project.decorators import ( # noqa
must_be_contributor_or_public,
must_have_addon, must_not_be_registration,
must_be_valid_projec... |
"""Common operations on Posix pathnames.
Instead of importing this module directly, import os and refer to
this module as os.path. The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is a... |
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.uic import *
from blur.Stonegui import *
from farmreport import Types
from reportwindow import *
ReportWindows = []
class ReportSelectorDialog(QDialog):
def __init__(self,parent=None):
QDialog.__init__(self,parent)
loadUi("reportselectordialogui.ui"... |
__author__ = 'bromix'
import time
def process(mode, provider, context, re_match, needs_tv_login=True):
def _do_login(_for_tv=False):
_client = provider.get_client(context)
json_data = {}
if _for_tv:
json_data = _client.generate_user_code_tv()
pass
else:
... |
# -*- coding: utf-8 -*-
import pytest
from django.core.exceptions import ImproperlyConfigured
from algolia import AlgoliaIndexer
@pytest.fixture()
def configs_success():
return {
'API_KEY': 'some-api-key',
'API_SECRET': 'some-api-secret',
}
@pytest.fixture()
def configs_wrong():
return... |
# -*- coding: utf-8 -*-
import datetime
from openerp import http
from openerp.http import request
from openerp.addons.website_portal.controllers.main import website_account
class website_account(website_account):
@http.route(['/my/home'], type='http', auth="user", website=True)
def account(self, **kw):
... |
import re
import os.path
import urllib2
import tempfile
def is_pubkey(string):
"""Verifies if string is a pubkey"""
pgp_regex = ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*"
return re.match(pgp_regex, string, re.DOTALL)
class RpmKey:
def __init__(self, module):
... |
"""Makes sure that all EXE and DLL files in the provided directory were built
correctly.
In essense it runs a subset of BinScope tests ensuring that binaries have
/NXCOMPAT, /DYNAMICBASE and /SAFESEH.
"""
import os
import optparse
import sys
# Find /third_party/pefile based on current directory and script path.
sys.... |
"""
Error checking functions for GEOS ctypes prototype functions.
"""
from ctypes import c_void_p, string_at
from django.contrib.gis.geos.error import GEOSException
from django.contrib.gis.geos.libgeos import GEOSFuncFactory
# Getting the `free` routine used to free the memory allocated for
# string pointers returne... |
"""
The Keys implementation.
"""
from inspect import getmembers
class Keys(object):
"""
Set of special keys codes.
See also https://w3c.github.io/webdriver/webdriver-spec.html#h-keyboard-actions
"""
NULL = u"\ue000"
CANCEL = u"\ue001" # ^break
HELP = u"\ue002"
BACKSPACE = u"\ue003"... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import keyword
import random
import uuid
from json import dumps
from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.module_utils.six import ite... |
# -*- coding: utf-8 -*-
"""WebSocketBaseTestCase is based on combination of Tornado
and Django test systems. It require to use decorator '@gen.coroutine'
for each test case method( see documentation: http://www.tornadoweb.org/en/stable/testing.html).
It requires implementation of 'get_app' method to initialize tornado... |
"""
Compression implementations for a Transport.
"""
import zlib
class ZlibCompressor (object):
def __init__(self):
self.z = zlib.compressobj(9)
def __call__(self, data):
return self.z.compress(data) + self.z.flush(zlib.Z_FULL_FLUSH)
class ZlibDecompressor (object):
def __init__(self):... |
"""
잔고확인
"""
import base64
import simplejson as json
import hashlib
import hmac
import httplib2
import time
ACCESS_KEY = ''
SECRET_KEY = ''
def get_encoded_payload(payload):
dumped_json = json.dumps(payload)
encoded_json = base64.b64encode(dumped_json)
return encoded_json
def get_signature(encoded_payload, sec... |
from __future__ import absolute_import
from __future__ import print_function
import mock
from twisted.internet import defer
from twisted.trial import unittest
from buildbot.data import workers
from buildbot.test.fake import fakedb
from buildbot.test.fake import fakemaster
from buildbot.test.util import endpoint
from... |
# coding=utf-8
"""
Uses /sys/fs/vmsfs to collect host-global data on VMS memory usage
#### Dependencies
* /sys/fs/vmsfs <- vmsfs package, vmsfs mounted
"""
import diamond.collector
import os
class VMSFSCollector(diamond.collector.Collector):
SYSFS = '/sys/fs/vmsfs'
VMSFS_STATS = {
'resident': ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Custom filters for use in openshift_aws
'''
from ansible import errors
class FilterModule(object):
''' Custom ansible filters for use by openshift_aws role'''
@staticmethod
def subnet_count_list(size, subnets):
"""This function will modify create a l... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from ansible.module_utils.network.nxos.nxos import get_config, load_config
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.mo... |
# This list of English stop words is taken from the "Glasgow Information
# Retrieval Group". The original list can be found at
# http://ir.dcs.gla.ac.uk/resources/linguistic_utils/stop_words
ENGLISH_STOP_WORDS = frozenset([
"a", "about", "above", "across", "after", "afterwards", "again", "against",
"all", "almo... |
from django.contrib.gis.db import models
class State(models.Model):
name = models.CharField(max_length=20)
objects = models.GeoManager()
class County(models.Model):
name = models.CharField(max_length=25)
state = models.ForeignKey(State)
mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in... |
"""Component to integrate the Home Assistant cloud."""
from hass_nabucasa import Cloud
import voluptuous as vol
from homeassistant.components.alexa import const as alexa_const
from homeassistant.components.google_assistant import const as ga_c
from homeassistant.const import (
CONF_MODE,
CONF_NAME,
CONF_RE... |
"""GDB command for working with extended prompts."""
import gdb
import gdb.prompt
class _ExtendedPrompt(gdb.Parameter):
"""Set the extended prompt.
Usage: set extended-prompt VALUE
Substitutions are applied to VALUE to compute the real prompt.
The currently defined substitutions are:
"""
# Add the prompt... |
import abc
import six
from neutron.api import extensions
from neutron.api.v2 import base
from neutron import manager
SYSTEM = 'system'
SYSTEMS = '%ss' % SYSTEM
RESOURCE_ATTRIBUTE_MAP = {
SYSTEMS: {
'state': {'allow_post': False, 'allow_put': True,
'validate': {'type:values': ['UPGRADE... |
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe import _
from frappe.desk.search import sanitize_searchfield
class BankGuarantee(Document):
def validate(self):
if not (self.customer or self.supplier):
frappe.throw(_("Select the customer or suppli... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, 'shadowsocks')
import os
import signal
import select
import time
from subprocess import Popen, PIPE
p1 = Popen(['sudo', sys.executable, 'shadowdns/dnsrelay.py', '-c', sys.argv[-1]],
shell=False, bufsize=0, stdin=PIPE, stdout=PIPE, stde... |
#!/usr/bin/env python
import subprocess
import os
import errno
import collections
import glob
import argparse
class Platform(object):
pass
class simulator_platform(Platform):
directory = 'darwin_ios'
sdk = 'iphonesimulator'
arch = 'i386'
triple = 'i386-apple-darwin11'
version_min = '-miphoneos... |
"""
click._termui_impl
~~~~~~~~~~~~~~~~~~
This module contains implementations for the termui module. To keep the
import time of Click down, some infrequently used functionality is placed
in this module and only imported as needed.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, se... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
if sys.version_info < (2, 7):
print('thefuck requires Python version 2.7 or later' +
' ({}.{} detected).'.format(*sys.version_info[:2]))
sys.exit(-1)
elif (3, 0) < sys.version_info < (3, 3):
print('thefuck requires Pytho... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python import learn
from tensorflow.contrib.learn.python.learn import datasets
class RegressionTest(tf.test.TestCase):
... |
"""
This module contains function to analyse dynamic library
headers to extract system information
Currently only for MacOSX
Library file on macosx system starts with Mach-O or Fat field.
This can be distinguish by first 32 bites and it is called magic number.
Proper value of magic number is with suffix _MAGIC. Suffi... |
import time
from datetime import datetime
from ._compat import text_type
from .encoding import base64_decode
from .encoding import base64_encode
from .encoding import bytes_to_int
from .encoding import int_to_bytes
from .encoding import want_bytes
from .exc import BadSignature
from .exc import BadTimeSignature
from .e... |
"""Basic classes and interfaces for journal."""
from __future__ import nested_scopes
# system imports
import os, time
try:
import cPickle as pickle
except ImportError:
import pickle
# twisted imports
from zope.interface import implements, Interface
class Journal:
"""All commands to the system get rout... |
"""
Make sure to check out the TwiML overview and tutorial
"""
import xml.etree.ElementTree as ET
class TwimlException(Exception):
pass
class Verb(object):
"""Twilio basic verb object.
"""
GET = "GET"
POST = "POST"
nestables = None
def __init__(self, **kwargs):
self.name = self... |
import datetime
import logging
import guessit
from slugify import slugify
from sqlalchemy import Boolean, Column, Date, DateTime, ForeignKey, Integer, Interval, JSON, SmallInteger, String
from sqlalchemy.event import listen
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack im... |
#!/usr/bin/env python
#
# Serial firmware uploader for the SiK bootloader
#
import sys, argparse, binascii, serial, glob
class firmware(object):
'''Loads a firmware file'''
# parse a single IntelHex line and obtain the byte array and address
def __parseline(self, line):
# ignore lines not beginni... |
"""
Hard links cobbler content together to save space.
Copyright 2009, Red Hat, Inc
Michael DeHaan <<EMAIL>>
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 2 of the License, or
(at y... |
from openerp import models, fields, api, _
class ResPartner(models.Model):
_inherit = 'res.partner'
locations_count = fields.Integer(
compute='_compute_locations_count', store=False)
location_ids = fields.One2many(
'stock.location', 'partner_id', string='Locations')
@api.depends('lo... |
from unittest import skipUnless
from django import http
from django.apps import apps
from django.conf import global_settings
from django.contrib.messages import constants, utils, get_level, set_level
from django.contrib.messages.api import MessageFailure
from django.contrib.messages.constants import DEFAULT_LEVELS
fro... |
"""Miscellaneous utility functions and classes."""
from __future__ import absolute_import, print_function
import errno
import os
import pipes
import pkgutil
import shutil
import subprocess
import re
import sys
import time
def is_shippable():
"""
:rtype: bool
"""
return os.environ.get('SHIPPABLE') ==... |
import logging
from django.contrib.auth.models import User
from django.http import Http404
from edx_rest_api_client import exceptions
from edx_rest_framework_extensions.authentication import JwtAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.generics import ListAPIVie... |
"""Test configuration utilities."""
from flask import Flask
from flask_extras.filters import config
class TestGetFuncs:
"""All tests for get funcs function."""
def test_get_module_funcs(self, client):
"""Test the return value."""
assert isinstance(config._get_funcs(config), dict)
def t... |
"""
Command to load course overviews.
"""
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps... |
# -*- coding: utf-8 -*-
"""An LL(1) lexer. This lexer is very tolerant of errors and can resync.
This lexer is originally copied from the GRR project:
https://code.google.com/p/grr
"""
import logging
import re
from plaso.lib import errors
class Token(object):
"""A token action."""
def __init__(self, state_reg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.