code stringlengths 1 199k |
|---|
revision = 'e966a3afd100'
down_revision = '954c3c4caf32'
branch_labels = None
depends_on = None
import alembic
import sqlalchemy
import requests
import pytz
import dateutil.parser
import datetime
def upgrade():
patreon_users = alembic.op.create_table("patreon_users",
sqlalchemy.Column("id", sqlalchemy.Integer, prima... |
import HTMLParser
data = '''
<table cellspacing="0" class="table table-bordered table-hover table-condensed" id="data">
<thead>
<tr>
<th class="name">Name</th>
<th class="memory">Memory</th>
<th class="computeunits">
<abbr title="One EC2 Compute Unit provides the ... |
import logging
from collections import namedtuple
from see.interfaces import Hook
from see.helpers import lookup_class
HookParameters = namedtuple('HookParameters', ('identifier',
'configuration',
'context'))
def hooks_factory... |
import wlauto.core.signal as signal
from wlauto import Module
from wlauto.exceptions import DeviceError
class CpuidleState(object):
@property
def usage(self):
return self.get('usage')
@property
def time(self):
return self.get('time')
@property
def disable(self):
return se... |
'''
Integration Test Teardown case
@author: Youyk
'''
import zstacklib.utils.linux as linux
import zstacklib.utils.http as http
import zstackwoodpecker.setup_actions as setup_actions
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.clean_util as clean_util
import zstackwoodpecker.test_lib as test_... |
"""passlib.bcrypt -- implementation of OpenBSD's BCrypt algorithm.
TODO:
* support 2x and altered-2a hashes?
http://www.openwall.com/lists/oss-security/2011/06/27/9
* deal with lack of PY3-compatibile c-ext implementation
"""
from __future__ import with_statement, absolute_import
import os
import re
import logging; l... |
"""
The FilterScheduler is for creating shares.
You can customize this scheduler by specifying your own share Filters and
Weighing Functions.
"""
import operator
from manila import exception
from manila.openstack.common import importutils
from manila.openstack.common import log as logging
from manila.scheduler import d... |
"""Tests for the Mozilla Firefox history database plugin."""
import collections
import unittest
from plaso.lib import definitions
from plaso.parsers.sqlite_plugins import firefox_history
from tests.parsers.sqlite_plugins import test_lib
class FirefoxHistoryPluginTest(test_lib.SQLitePluginTestCase):
"""Tests for the M... |
from __future__ import absolute_import
from .factory import toolkit_factory
myTextEditor = toolkit_factory("text_editor", "myTextEditor") |
"""Context manager to help with Control-C handling during critical commands."""
import signal
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.core import log
from googlecloudsdk.test.lib import exit_code
class CancellableTestSection(object):
"""Cancel a test matrix if CTRL-C is typed during a secti... |
import sys, random
if len(sys.argv) != 3:
sys.stderr.write("Must provide file with list of filenames and number of files to pick\n")
sys.exit(1)
file_list = open(sys.argv[1])
file_array = []
for filepath in file_list:
file_array.append(filepath.strip())
try:
choices = int(sys.argv[2])
except:
sys.std... |
from __future__ import division
import json
import os
import copy
import collections
import argparse
import csv
import neuroglancer
import neuroglancer.cli
import numpy as np
class State(object):
def __init__(self, path):
self.path = path
self.body_labels = collections.OrderedDict()
def load(sel... |
"""
"""
from __future__ import absolute_import
from .StrStrHashMap import *
from ..msg.Field import *
from ..msg.ImportExportHelper import *
from ..msg.StructValue import *
from ..msg.Type import *
from ..msg.ValueFactory import *
from ..support.Class2TypeMap import *
from ..support.Validator_object import *
class StrS... |
"""
Support for MQTT vacuums.
For more details about this platform, please refer to the documentation at
https://www.home-assistant.io/components/vacuum.mqtt/
"""
import logging
import voluptuous as vol
from homeassistant.components.vacuum import DOMAIN
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from... |
import json
from idpproxy.social.oauth import OAuth
import oauth2 as oauth
import logging
logger = logging.getLogger(__name__)
__author__ = 'rohe0002'
class LinkedIn(OAuth):
def __init__(self, client_id, client_secret, **kwargs):
OAuth.__init__(self, client_id, client_secret, **kwargs)
def get_profile(s... |
import angr
class InterlockedExchange(angr.SimProcedure):
def run(self, target, value): #pylint:disable=arguments-differ
if not self.state.solver.symbolic(target):
old_value = self.state.memory.load(target, 4, endness=self.state.arch.memory_endness)
self.state.memory.store(target, va... |
import subprocess
from rstgen.utils import confirm
from django.core.management.base import BaseCommand
from django.conf import settings
def runcmd(cmd, **kw): # same code as in getlino.py
"""Run the cmd similar as os.system(), but stop when Ctrl-C."""
# kw.update(stdout=subprocess.PIPE)
# kw.update(stderr=... |
import shutil
import json
from rest_framework import routers, serializers, viewsets, parsers, filters
from rest_framework.views import APIView
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from django.core.exceptions import ValidationError
from django.core.files.uploade... |
from . import numeric as _nx
from .numeric import asanyarray, newaxis
def atleast_1d(*arys):
res = []
for ary in arys:
ary = asanyarray(ary)
if len(ary.shape) == 0 :
result = ary.reshape(1)
else :
result = ary
res.append(result)
if len(res) == 1:
... |
import rospy, yaml, tf
from spencer_tracking_msgs.msg import TrackedPersons, TrackedPerson
from nav_msgs.msg import GridCells
from math import cos, sin, tan, pi, radians
def createTrackedPerson(track_id, x, y, theta):
trackedPerson = TrackedPerson()
theta = radians(theta) + pi/2.0
trackedPerson.track_id = t... |
"""
Implements a simple, robust, safe, Messenger class that allows one to
register callbacks for a signal/slot (or event/handler) kind of
messaging system. One can basically register a callback
function/method to be called when an object sends a particular event.
The Messenger class is Borg. So it is easy to instanti... |
import unittest
from django.db import connection, migrations, models
from django.db.migrations.state import ProjectState
from django.test import override_settings
from .test_operations import OperationTestBase
try:
import sqlparse
except ImportError:
sqlparse = None
class AgnosticRouter(object):
"""
A r... |
import ipaddress
__all__ = [
'config_to_map',
'get_region'
]
def config_to_map(topology_config):
"""
args:
topology_config: dict
{
'region1': [
'10.1.1.0/24',
'10.1.10.0/24',
'172.16.1.0/24'
],
... |
from __future__ import unicode_literals
from django.db.models import Q
from djangobmf.utils import FilterQueryset
class GoalFilter(FilterQueryset):
def filter_queryset(self, qs, user):
if user.has_perm('%s.can_manage' % qs.model._meta.app_label, qs.model):
return qs
qs_filter = Q(referee... |
"""Command-line tool for starting a local Vitess database for testing.
USAGE:
$ run_local_database --port 12345 \
--topology test_keyspace/-80:test_keyspace_0,test_keyspace/80-:test_keyspace_1 \
--schema_dir /path/to/schema/dir
It will run the tool, logging to stderr. On stdout, a small json structure
can be ... |
"""
TutorialWorld - basic objects - Griatch 2011
This module holds all "dead" object definitions for
the tutorial world. Object-commands and -cmdsets
are also defined here, together with the object.
Objects:
TutorialObject
Readable
Climbable
Obelisk
LightSource
CrumblingWall
Weapon
WeaponRack
"""
from future.utils impo... |
class ResourceOptions(object):
"""
A configuration class for ``Resource``.
Provides sane defaults and the logic needed to augment these settings with
the internal ``class Meta`` used on ``Resource`` subclasses.
"""
allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
list_allowed_meth... |
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.permissions import SAFE_METHODS, BasePermission
from olympia.amo import permissions
from olympia.access import acl
class GroupPermission(BasePermission):
"""
Allow access depending on the result of action_allowed_user().
"""
def ... |
from __future__ import unicode_literals
from django.db import models, migrations
def create_site(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Site = apps.get_model('sites', 'Site')
db_alias = schema_editor.connection.ali... |
__version__=''' $Id: _fontdata.py 3052 2007-03-07 14:04:49Z rgbecker $ '''
__doc__="""
database of font related things
standardFonts tuple of the 14 standard string font names
standardEncodings tuple of the known standard font names
encodings a mapping object from standard encoding nam... |
import logging
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from corehq.apps.adm.dispatcher import ADMSectionDispatcher
from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport
from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSort... |
"""
This test will use the default permissions found in
flaskbb.utils.populate
"""
from flaskbb.utils.permissions import *
def test_moderator_permissions_in_forum(
forum, moderator_user, topic, topic_moderator):
"""Test the moderator permissions in a forum where the user is a
moderator.
"""
... |
""" md5s3stash
content addressable storage in AWS S3
"""
from __future__ import unicode_literals
import sys
import os
import argparse
import tempfile
import urllib2
import urllib
import urlparse
import base64
import logging
import hashlib
import basin
import boto
import magic
from PIL import Image
from collections ... |
"""Jinja2's i18n functionality is not exactly the same as Django's.
In particular, the tags names and their syntax are different:
1. The Django ``trans`` tag is replaced by a _() global.
2. The Django ``blocktrans`` tag is called ``trans``.
(1) isn't an issue, since the whole ``makemessages`` process is based on
co... |
import os.path as op
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from mne.parallel import parallel_func
from mne.utils import ProgressBar, array_split_idx, use_log_level
def test_progressbar():
"""Test progressbar class."""
a = np.arange(10)
pbar = ProgressBar(a)
assert... |
import inspect
from functools import partial
try:
from joblib.externals.cloudpickle import dumps, loads
cloudpickle = True
except ImportError:
cloudpickle = False
WRAP_CACHE = dict()
class CloudpickledObjectWrapper(object):
def __init__(self, obj, keep_wrapper=False):
self._obj = obj
sel... |
import math
import sys, re
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from utils import *
from matplotlib import pylab
from scipy.stats import scoreatpercentile
pkt_size = 256
train_length = 6
class boxplotter(object):
def __init__(self, median, top, bottom, whisk_top... |
from __future__ import unicode_literals, absolute_import
from mock import MagicMock
from ....unittest import TestCase
from oauthlib.oauth1 import RequestValidator
from oauthlib.oauth1.rfc5849 import errors
from oauthlib.oauth1.rfc5849.endpoints import AuthorizationEndpoint
class ResourceEndpointTest(TestCase):
def ... |
import Sea
from Connection import Connection
class ConnectionPoint(Connection):
"""
Class for point connections.
"""
def __init__(self, obj, system, components):
Connection.__init__(self, obj, system, components)
#obj.Sort = 'Point'
def updateComponents(self, obj):
connection... |
import doctest
import pytest
from datascience import predicates
from datascience import *
def test_both():
"""Both f and g."""
p = are.above(2) & are.below(4)
ps = [p(x) for x in range(1, 6)]
assert ps == [False, False, True, False, False]
def test_either():
"""Either f or g."""
p = are.above(3)... |
import optparse
import os
import sys
from telemetry.core import util
from telemetry.results import buildbot_output_formatter
from telemetry.results import chart_json_output_formatter
from telemetry.results import csv_output_formatter
from telemetry.results import csv_pivot_table_output_formatter
from telemetry.results ... |
''' Provide the standard 147 CSS (X11) named colors.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
log = logging.getLogger(__name__)
from .util import NamedColor
aliceblue = NamedColor("aliceblue", 240, 248, 255)
antiquewhite = Nam... |
"""
Class for representing hierarchical language structures, such as
syntax trees and morphological trees.
"""
from __future__ import print_function, unicode_literals
import re
from nltk.grammar import Production, Nonterminal
from nltk.probability import ProbabilisticMixIn
from nltk.util import slice_bounds
from nltk.c... |
from collections import defaultdict
import copy
import datetime
import json
from appengine_fixture_loader.loader import load_fixture
from google.appengine.ext import ndb
from helpers.event_details_manipulator import EventDetailsManipulator
from helpers.match_helper import MatchHelper
from helpers.match_manipulator impo... |
import test
import os
from os.path import join, exists
TEST_262_HARNESS = ['sta.js']
class Test262TestCase(test.TestCase):
def __init__(self, filename, path, context, root, mode, framework):
super(Test262TestCase, self).__init__(context, path, mode)
self.filename = filename
self.framework = framework
... |
"""
IAMService
"""
import time
import xml.sax.saxutils as saxutils
import sys, httplib
from lxml import etree
from cStringIO import StringIO
import toml
class IAMClient(object):
def __init__(self):
conf_fn = "config.toml"
with open(conf_fn) as conf_fh:
self.conf = toml.loads(conf_fh.read... |
from __future__ import print_function
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(co... |
from __future__ import print_function, unicode_literals
from nltk.probability import FreqDist
from nltk.compat import python_2_unicode_compatible
@python_2_unicode_compatible
class ConfusionMatrix(object):
"""
The confusion matrix between a list of reference values and a
corresponding list of test values. ... |
__author__ = "Jon Dawson"
__copyright__ = "Copyright (C) 2012, Jonathan P Dawson"
__version__ = "0.1"
class Allocator:
"""Maintain a pool of registers, variables and arrays. Keep track of what they are used for."""
def __init__(self, reuse):
self.registers = []
self.all_registers = {}
se... |
from tkinter.scrolledtext import ScrolledText
import tkinter as tk
from trace_json import traceparse
from parsley_json import jsonGrammar
jsonData = open('337141-steamcube.json').read()
class Tracer(object):
def __init__(self, grammarWin, inputWin, logWin, trace):
self.grammarWin = grammarWin
self.i... |
from sys import argv,exit
from os import getuid
from PyQt4.QtGui import QApplication,QIcon
from Core.Privilege import frm_privelege
from Core.Main import Initialize
from Core.check import check_dependencies
from Modules.utils import Refactor
def ExecRootApp():
check_dependencies()
root = QApplication(argv)
... |
"""
This module provides classes to interface with the Crystallography Open
Database. If you use data from the COD, please cite the following works (as
stipulated by the COD developers)::
Merkys, A., Vaitkus, A., Butkus, J., Okulič-Kazarinas, M., Kairys, V. &
Gražulis, S. (2016) "COD::CIF::Parser: an error-corr... |
"""foo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based view... |
from __future__ import unicode_literals
"""
Create a new document with defaults set
"""
import webnotes
from webnotes.utils import nowdate, nowtime, cint, flt
import webnotes.defaults
def get_new_doc(doctype, parent_doc = None, parentfield = None):
doc = webnotes.doc({
"doctype": doctype,
"__islocal": 1,
"owner"... |
"""LCM type definitions
This file automatically generated by lcm.
DO NOT MODIFY BY HAND!!!!
"""
try:
import cStringIO.StringIO as BytesIO
except ImportError:
from io import BytesIO
import struct
class vortex_sensor_t(object):
__slots__ = ["sensor1", "sensor2", "velocity"]
def __init__(self):
sel... |
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standard_transformations import \
SubstitutionTransformation, RemoveSpeciesTransformation, \
OrderDisorderedS... |
import unittest
import numpy as np
from chainermn.datasets import create_empty_dataset
import chainerx as chx
class TestEmptyDataset(unittest.TestCase):
def setUp(self):
pass
def check_create_empty_dataset(self, original_dataset):
empty_dataset = create_empty_dataset(original_dataset)
se... |
"""
Snowball stemmers
This module provides a port of the Snowball stemmers
developed by Martin Porter.
There is also a demo function: `snowball.demo()`.
"""
from __future__ import unicode_literals, print_function
from nltk import compat
from nltk.corpus import stopwords
from nltk.stem import porter
from nltk.stem.util ... |
from __future__ import print_function
from acq4.util import Qt
import acq4.pyqtgraph as pg
from .CanvasItem import CanvasItem
from .itemtypes import registerItemType
class GridCanvasItem(CanvasItem):
_typeName = "Grid"
def __init__(self, **kwds):
kwds.pop('viewRect', None)
item = pg.GridItem()
... |
"""
Django settings for kboard project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
BASE... |
"""Test for the once bitten strategy."""
import random
import axelrod
from .test_player import TestPlayer
C, D = 'C', 'D'
class TestOnceBitten(TestPlayer):
name = "Once Bitten"
player = axelrod.OnceBitten
expected_classifier = {
'memory_depth': 12,
'stochastic': False,
'inspects_sour... |
""" Windows Registry Network Query
Lists the network name and MAC addresses of the networks that
this computer has connected to. If the location command is given
print the coordinates of the network if they are in the wigile
datebase
Don't be a moron, please don't use this for something illegal.
... |
import sys
from bs4 import BeautifulSoup
class Injector:
def __init__(self, iframe_url):
self.iframe_url = iframe_url
def response(self, flow):
if flow.request.host in self.iframe_url:
return
html = BeautifulSoup(flow.response.content, "html.parser")
if html.body:
... |
import re
class Templates:
TOKENS = re.compile('([A-Za-z]+|[^ ])')
SIMPLE = {
'l': '_n.l.ptb()',
'r': '_n.r.ptb()',
'<': 'addr(_n)',
'>': 'addl(_n)',
}
def compile(self, template):
python = self.parse(self.TOKENS.findall(template))
return eval("lambda _n: %s" % python)
def parse(self, ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_compute_backend_service
description:
- A Backend Service defines a group of virtual machines that w... |
import os
from watermark.config import config as conf
from watermark import connect
config_name = os.getenv('WM_CONFIG_ENV') or 'default'
config = conf[config_name]()
conn = connect.get_connection(config)
conn.message.create_queue(name=config.NAME)
print("{name} queue created".format(name=config.NAME)) |
"""Test BIP68 implementation."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.blocktools import *
SEQUENCE_LOCKTIME_DISABLE_FLAG = (1<<31)
SEQUENCE_LOCKTIME_TYPE_FLAG = (1<<22) # this means use time (0 means height)
SEQUENCE_LOCKTIME_GRANULARITY = ... |
import unittest
import testRObject
import testVector
import testArray
import testDataFrame
import testFormula
import testFunction
import testEnvironment
import testRobjects
import testMethods
import testPackages
import testHelp
import testLanguage
import testNumpyConversions
def suite():
suite_RObject = testRObject... |
from sos.cleaner.archives import SoSObfuscationArchive
import os
import tarfile
class DataDirArchive(SoSObfuscationArchive):
"""A plain directory on the filesystem that is not directly associated with
any known or supported collection utility
"""
type_name = 'data_dir'
description = 'unassociated di... |
"""Payment Flow History Report Dialog"""
from storm.expr import And, Eq, Or
from stoqlib.database.expr import Date
from stoqlib.gui.dialogs.daterangedialog import DateRangeDialog
from stoqlib.gui.utils.printing import print_report
from stoqlib.lib.message import info
from stoqlib.lib.translation import stoqlib_gettext
... |
# -*- coding: utf-8 -*-
"""DocExtract REST and Web API
Exposes document extration facilities to the world
"""
from tempfile import NamedTemporaryFile
from invenio.webinterface_handler import WebInterfaceDirectory
from invenio.webuser import collect_user_info
from invenio.webpage import page
from invenio.config impo... |
'''
pkgdb tests for the Collection object.
'''
__requires__ = ['SQLAlchemy >= 0.7']
import pkg_resources
import json
import unittest
import sys
import os
from mock import patch
sys.path.insert(0, os.path.join(os.path.dirname(
os.path.abspath(__file__)), '..'))
import pkgdb2
import pkgdb2.lib.model as model
from tes... |
"""
Geant4 support, implemented as an easyblock.
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
import os
import shutil
import re
from distutils.ve... |
import datetime
import os
from . import core
from .metadata import __version__, version_formatter
time_string = datetime.datetime.now().strftime('%A, %d %B %Y %I:%M%p')
pid = os.getpid()
def sizeof_fmt(num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
r... |
from migrate.versioning.shell import main
if __name__ == '__main__':
main(debug='False', repository='.') |
icon_outputs = b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAA'\
b'BHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAA'\
b'CuNJREFUaIHVmltsXcd1hr+Z2ftceZVoi4xFS6KdSlHkooGr'\
b'JgpyqWQEKFwkqNvaemrhINVDCxfpS4HW7YP8UD+5ShEbiuJL'\
b'0LhGW0Bx/ZDGdYwiiA2bVS624jqOqBs... |
import unittest
from webkitpy.common.net.git_cl import GitCL
from webkitpy.common.system.executive_mock import MockExecutive2
from webkitpy.common.host_mock import MockHost
class GitCLTest(unittest.TestCase):
def test_run(self):
host = MockHost()
host.executive = MockExecutive2(output='mock-output')... |
from __future__ import with_statement
__license__ = 'GPL 3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from itertools import izip
from calibre.customize import Plugin as _Plugin
FONT_SIZES = [('xx-small', 1),
('x-small', None),
('small',... |
class MasteryAbility(object):
@staticmethod
def build_from_xml(elem):
f = MasteryAbility()
f.rank = int(elem.attrib['rank'])
f.rule = elem.attrib['rule'] if ('rule' in elem.attrib) else None
f.desc = elem.text
return f
class SkillCateg(object):
@staticmethod
def b... |
'''
*** SHED SKIN Python-to-C++ Compiler ***
Copyright 2005-2013 Mark Dufour; License GNU GPL version 3 (See LICENSE)
graph.py: build constraint graph used in dataflow analysis
constraint graph: graph along which possible types 'flow' during an 'abstract execution' of a program (a dataflow analysis). consider the assig... |
import sys
from time import time
from plasma.lib.ast import (Ast_Branch, Ast_Goto, Ast_Loop, Ast_If_cond,
Ast_IfGoto, Ast_Ifelse, Ast_AndIf, Ast_Comment)
from plasma.lib.utils import BRANCH_NEXT, BRANCH_NEXT_JUMP, debug__
from plasma.lib.exceptions import ExcIfelse
from plasma.lib.colors imp... |
import collections
class AsaList(object):
@classmethod
def flatten(cls, lst):
"""
Returns Generator of non-iterable values
"""
for x in lst:
if not isinstance(x, collections.Iterable):
yield x
else:
for x in AsaList.flat... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .util import Specification
from . import compat
class Field(Specification):
"""
Field object for adding fields to a resource schema.
Currently this is bui... |
__author__ = 'Sun'
from sandbox.dynamic_title.creator.char_corpus import CharacterCorpus
import cPickle
import click
@click.command()
@click.argument("text_file", type=click.File(mode='r', encoding='gb18030'))
@click.argument("char_cropus_file", type=click.File(mode='wb'))
def make_char_corpus(text_file, char_cropus_fi... |
def replace_0_5_iterative(user_input):
modified = []
for i in user_input:
if i == "0":
modified.append("5")
else:
modified.append(i)
return "".join(modified)
def replace_0_5_pythonic(user_input):
return user_input.replace("0", "5")
user_input = input("Enter the nu... |
'''Core plugins unit tests'''
import os
import tempfile
import unittest
import time
from contextlib import contextmanager
from tempfile import mkdtemp
from shutil import rmtree
from hashlib import md5
import gzip_cache
@contextmanager
def temporary_folder():
"""creates a temporary folder, return it and delete it af... |
import base64
import logging
import re
from urllib import urlencode
from urlparse import urljoin
from openerp import tools
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp.osv.orm import except_orm
from openerp.tools.translate import _
_logger = logging.getLogger(__name__)
class mail_ma... |
"""
Unit tests for user messages.
"""
import warnings
import ddt
from django.contrib.messages.middleware import MessageMiddleware
from django.test import RequestFactory, TestCase
from common.test.utils import normalize_repr
from openedx.core.djangolib.markup import HTML, Text
from common.djangoapps.student.tests.factor... |
from . import CuraProfileReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "Cura Profile Reader"),
"author": "Ultimaker",
"version": "1.0",
"description": catalog.i18nc(... |
from __future__ import unicode_literals
import time
from django import forms
from django.conf import settings
from django.core.management import call_command
from django.http.response import HttpResponse, JsonResponse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView
from... |
"""Offers a simple XML-RPC dispatcher for django_xmlrpc
Author::
Graham Binns
Credit must go to Brendan W. McAdams <brendan.mcadams@thewintergrp.com>, who
posted the original SimpleXMLRPCDispatcher to the Django wiki:
http://code.djangoproject.com/wiki/XML-RPC
New BSD License
===============
Copyright (c) 2007, Gra... |
import wizard |
import logging
from lxml import etree, html
from odoo import api, models
_logger = logging.getLogger(__name__)
class IrFieldsConverter(models.AbstractModel):
_inherit = "ir.fields.converter"
@api.model
def text_from_html(self, html_content, max_words=None, max_chars=None,
ellipsis=u"…... |
"""
Test the style of toggle and radio buttons inside a palette. The buttons
contains only an icon and should be rendered similarly to the toolbar
controls. Ticket #2855.
"""
from gi.repository import Gtk
from sugar3.graphics.palette import Palette
from sugar3.graphics.icon import Icon
from sugar3.graphics import style... |
import gobject
import gst
import gst.interfaces
from twisted.internet.threads import deferToThread
from twisted.internet import defer
from flumotion.common import gstreamer, errors, log, messages
from flumotion.common.i18n import N_, gettexter
from flumotion.twisted import defer as fdefer
from flumotion.worker.checks i... |
from spack import *
class Libice(AutotoolsPackage):
"""libICE - Inter-Client Exchange Library."""
homepage = "http://cgit.freedesktop.org/xorg/lib/libICE"
url = "https://www.x.org/archive/individual/lib/libICE-1.0.9.tar.gz"
version('1.0.9', '95812d61df8139c7cacc1325a26d5e37')
depends_on('xproto... |
from spack import *
class FontIsasMisc(Package):
"""X.org isas-misc font."""
homepage = "http://cgit.freedesktop.org/xorg/font/isas-misc"
url = "https://www.x.org/archive/individual/font/font-isas-misc-1.0.3.tar.gz"
version('1.0.3', 'ecc3b6fbe8f5721ddf5c7fc66f73e76f')
depends_on('font-util')
... |
try:
import setuptools
except ImportError:
import ez_setup
ez_setup.use_setuptools()
import setuptools
setuptools.setup(
name='api',
version='0.1',
description='',
author='',
author_email='',
install_requires=[
"pecan",
],
test_suite='api',
zip_safe=False,
... |
import os
import sys
from nova import flags
import sqlalchemy
from migrate.versioning import api as versioning_api
try:
from migrate.versioning import exceptions as versioning_exceptions
except ImportError:
try:
# python-migration changed location of exceptions after 1.6.3
# See LP Bug #717467
... |
from __future__ import absolute_import
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('podcasts', '0014_auto_20160503_0247'),
]
operations = [
migrations.RemoveField(
model_name='podcast',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.