code stringlengths 1 199k |
|---|
import base64
import calendar
import json
import logging
import re
import sqlparse
import uuid
from collections import OrderedDict
from datetime import datetime
from io import BytesIO
from django.conf import settings
from django.db import models, DatabaseError, connection
from django.db.models import signals
from djang... |
"""Trac Environment model and related APIs."""
import hashlib
import os.path
import setuptools
import shutil
import sys
from urlparse import urlsplit
from trac import db_default, log
from trac.admin import AdminCommandError, IAdminCommandProvider
from trac.cache import CacheManager, cached
from trac.config import BoolO... |
import datetime
import json
from json.decoder import JSONDecodeError
from cumulusci.core.config import OrgConfig
from cumulusci.core.exceptions import SfdxOrgException
from cumulusci.core.sfdx import sfdx
from cumulusci.utils import get_git_config
nl = "\n" # fstrings can't contain backslashes
class SfdxOrgConfig(OrgC... |
VERSION = (1,10,0)
__version__ = "1.10.0" |
from __future__ import unicode_literals
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from cms.admin.placeholderadmin import (
FrontendEditableAdminMixin,
)
from parler.forms import TranslatableModelForm
from parler.admin import TranslatableAdmin
from aldryn_apphooks_confi... |
from __future__ import absolute_import
from linode.objects import DerivedBase, MappedObject, Property
from .disk import Disk
from .kernel import Kernel
class Config(DerivedBase):
api_endpoint="/linode/instances/{linode_id}/configs/{id}"
derived_url_path="configs"
parent_id_name="linode_id"
properties = ... |
from ..adapters.mysql import MySQL
from ..helpers.methods import varquote_aux
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(MySQL)
class MySQLDialect(SQLDialect):
quote_template = '`%s`'
@sqltype_for('text')
def type_text(self):
return 'LONGTEXT'
@sqltyp... |
from pythonpic import plotting_parser
from pythonpic.configs.run_laser import (initial, impulse_duration,
n_macroparticles)
args = plotting_parser("Hydrogen shield")
perturbation_amplitude = 0
intensities = [5e20, 1e21, 5e21, 1e21, 5e21, 1e22, 5e22, 1e23]
scalings = [0.5, 0.9, 1... |
from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
from django.core.urlresolvers import NoReverseMatch
from modelcluster.models import get_all_child_relations
from rest_framework import relations, serializers
from rest_framework.fields import Field, SkipField
from taggit.manage... |
from __future__ import absolute_import
def standard_setup():
"""Non-standalone user setup."""
import traceback
import os
import nuke
import metatools.imports
import sgfs.nuke.menu
def callback():
try:
metatools.imports.autoreload(sgfs.nuke.menu)
sgfs.nuke.menu... |
from __future__ import unicode_literals
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
intersphinx_mapping = {
'python': ('http://python.readthedocs.org/en/latest/', None),
'django': ('http://django.readthedocs.org/en/latest/', None),
'sphinx': ('http://sphinx.readthedocs.org/en/late... |
import subprocess
import sys
import os
PIP_INSTALLED = True
try:
import pip
except ImportError:
PIP_INSTALLED = False
if not PIP_INSTALLED:
raise ImportError('pip is not installed.')
def install_and_import(package):
import importlib
try:
importlib.import_module(package)
except ImportErro... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('backoffice', '0002_auto_20150112_2215'),
]
operations = [
migrations.RenameModel(
old_name='Image',
new_name='Picture',
)... |
import os
import time
import pickle
import random
import string
from .. import SAMP_STATUS_OK
TEST_REPLY = {"samp.status": SAMP_STATUS_OK,
"samp.result": {"txt": "test"}}
def write_output(mtype, private_key, sender_id, params):
filename = params['verification_file']
f = open(filename, 'wb')
pi... |
"""
TTYPE (MTTS) - Mud Terminal Type Standard
This module implements the TTYPE telnet protocol as per
http://tintin.sourceforge.net/mtts/. It allows the server to ask the
client about its capabilities. If the client also supports TTYPE, it
will return with information such as its name, if it supports colour
etc. If the... |
__author__ = 'Robbert Harms'
__date__ = "2015-05-14"
__maintainer__ = "Robbert Harms"
__email__ = "robbert.harms@maastrichtuniversity.nl" |
""" Create a HDF5 file with objects using the latest library version. """
import h5py
import numpy as np
f = h5py.File('latest.hdf5', 'w', libver='latest')
f.attrs.create('attr1', -123, dtype='<i4')
dset1 = f.create_dataset(
'dataset1', shape=(4, ), dtype='<i4', data=np.arange(4), track_times=False)
dset1.attrs.cre... |
from datetime import datetime
from dateutil.tz import tzlocal
import numpy as np
import pytest
from pandas.compat import IS64
import pandas as pd
from pandas import (
DateOffset,
DatetimeIndex,
Index,
Series,
Timestamp,
bdate_range,
date_range,
)
import pandas._testing as tm
from pandas.tser... |
from __future__ import absolute_import
def safe_get_or_create(klass, **kwargs):
"""
Similar to :meth:`~django.db.models.query.QuerySet.get_or_create` but uses
the methodical get/save including a full_clean() call to avoid problems with
models which have validation requirements which are not strictly enf... |
from django import template
from django.utils.http import urlquote
from filebrowser.settings import SELECT_FORMATS
register = template.Library()
@register.inclusion_tag('filebrowser/include/_response.html', takes_context=True)
def query_string(context, add=None, remove=None):
"""
Allows the addition and removal... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import GmailTwoStepVerificationBug
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Gmail check for two step verif... |
from django.contrib import admin
from blog.models import *
admin.site.register(Post) |
from .simpledbf import Dbf5
__all__ = ['Dbf5',] |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
__author__ = "William Dabney"
from rlpy.Domains import GridWorld
from rlpy.MDPSolvers import Traject... |
import optparse
import unittest
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.layout_tests.port.base import Port
from webkitpy.layout_tests.port.driver import Driver
from webkitpy.layout_tests.port.port_testcase import TestWebKitPort
from webkitpy.layout_tests.port.server_process_mock ... |
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
from sentry.constants import RESERVED_TEAM_SLUGS
from sentry.models import slugify_instance
for team in orm['sentry.Team'].objects.... |
"""
JPLHorizons
-----------
:author: Michael Mommert (mommermiscience@gmail.com)
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.jplhorizons`.
"""
# server settings
horizons_server = _config.ConfigItem(
'https://ssd.... |
"""
Classes corresponding to Pandoc Table elements
"""
from .utils import decode_ica, check_group, check_type, check_type_or_value, encode_dict, debug
from .containers import ListContainer
from .base import Element, Block, Inline
class Table(Block):
"""Table, composed of a table head, one or more table bodies, and ... |
__all__ = ["GeolocationOverrideManager"]
from devtools_event_listener import DevToolsEventListener
from misc.geoposition import Geoposition
from status import *
import copy
class GeolocationOverrideManager(DevToolsEventListener):
def __init__(self, client):
DevToolsEventListener.__init__(self)
self.client = c... |
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
... |
from multiconf import mc_config
from multiconf.envs import EnvFactory
from .utils.tstclasses import BuilderWithAA
ef = EnvFactory()
pp = ef.Env('pp')
prod = ef.Env('prod')
class MeSetterBuilder(BuilderWithAA):
def mc_build(self):
pass
def setme(self, name, mc_overwrite_property=False, mc_set_unknown=Fal... |
from . import tracker
class TrackHistoryMiddleware(object):
"""
This middleware sets user as a local thread variable, making it
available to the model-level utilities to allow tracking of the
authenticated user making a change.
"""
def __init__(self, get_response):
self.get_response = ge... |
"""
raven.contrib.django.raven_compat.middleware.wsgi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from raven.contrib.django.middleware.wsgi import * # NOQA |
from __future__ import absolute_import, print_function
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth import login
from django.db import transaction
from django.http import HttpResponseRedirect
from django.utils i... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sms', '0003_add_backend_models'),
]
operations = [
migrations.CreateModel(
name='SQLIVRBackend',
fields=[
],
opti... |
"""Module to manage a setup of moblab and its DUT VMs."""
from __future__ import print_function
import collections
import contextlib
import json
import os
import random
import shutil
import sys
from chromite.lib import chroot_util
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.... |
__all__ = ["c", "cpp"]
import cpp
import c
from sln import Solution
def getProjectGroupDict():
return {
"c": c,
"cpp": cpp,
"Solution": Solution
} |
from __future__ import unicode_literals
from django.forms import ModelForm, modelformset_factory
from django.forms.models import BaseModelFormSet
class BaseArbitraryInlineFormSet(BaseModelFormSet):
"""
A formset for generic inline objects to a parent.
"""
def __init__(self, data=None, files=None, instan... |
from Chip import OpCodeDefinitions
from Tests.OpCodeTests.OpCodeTestBase import OpCodeTestBase
class TestPlpOpCode(OpCodeTestBase):
def test_execute_plp_implied_command_calls_plp_method(self):
self.assert_opcode_execution(OpCodeDefinitions.plp_implied_command, self.target.get_plp_command_executed) |
import util
@auth.requires_login()
def index():
"""Index of user list one can manage or use."""
# Reads the list of ids of lists managed by the user.
list_ids_l = db(db.user_properties.user == get_user_email()).select(db.user_properties.managed_user_lists).first()
if list_ids_l == None:
list_ids... |
import time
from threading import Thread
from itertools import cycle
class Billboard(Thread):
def __init__(self, display, sources, period):
super(Billboard, self).__init__()
self.display = display
self.sources = sources
self.period = period
self.daemon = True
def run(self... |
import logging
import os
from StringIO import StringIO
import sys
from appengine_wrappers import webapp
from appengine_wrappers import memcache
from appengine_wrappers import urlfetch
from api_data_source import APIDataSource
from api_list_data_source import APIListDataSource
from appengine_blobstore import AppEngineBl... |
from app import app, db
from flask import render_template, url_for, session, redirect, flash, abort
from app.models import User, Page, Post, SocialIcon
from app.forms import ContactForm
from app.email import send_email
from config import MAIL_USERNAME
@app.route('/')
def index():
user = User.query.first()
pages... |
def get_people(self):
return self.execute("select * from person order by name")
def get_person_for_song(self, sound_name):
return self.execute("select * from person where theme_song = ? order by name", [sound_name, ]).fetchall()
def add_person(self, name):
self.execute("insert into person (name) values (?)"... |
class GenericError(Exception):
"""Generic API error."""
status_code = 500
class TransferError(GenericError, Exception):
"""Generic transfer error"""
pass
class AccountNotFoundError(TransferError):
"""Account not found"""
status_code = 404
class InputError(TransferError):
"""Client gave wrong... |
NC_SYSTEM_TEXT = {
'10': 'Authentication System',
'20': 'Validation Error',
'25': 'Payment Error / Order creation Error',
'30': 'Provider Error',
'35': 'Policy Error',
'40': 'System Error',
'50': 'Unknown Exceptions',
}
NC_ERROR_TEXT = {
'10': 'Missing',
'11': 'Invalid',
'12': 'T... |
import openmc
batches = 20
inactive = 10
particles = 10000
fuel = openmc.Material(material_id=1, name='fuel')
fuel.set_density('g/cc', 4.5)
fuel.add_nuclide('U235', 1.)
moderator = openmc.Material(material_id=2, name='moderator')
moderator.set_density('g/cc', 1.0)
moderator.add_element('H', 2.)
moderator.add_element('O... |
"""
Schema differencing support.
"""
import logging
import sqlalchemy
from migrate.changeset import SQLA_06
from sqlalchemy.types import Float
log = logging.getLogger(__name__)
def getDiffOfModelAgainstDatabase(metadata, engine, excludeTables=None):
"""
Return differences of model against database.
:retu... |
from pygame.constants import K_LEFT
from pygame_player import PyGamePlayer, function_intercept
import games.tetris
class TetrisPlayer(PyGamePlayer):
def __init__(self):
"""
Example class for playing Tetris
"""
super(TetrisPlayer, self).__init__(force_game_fps=5)
self._toggle_... |
class _ProjectStatuses:
def __init__(self, client=None):
self.client = client
def create_project_status_for_project(self, project_gid, params=None, **options):
"""Create a project status
:param str project_gid: (required) Globally unique identifier for the project.
:param Object ... |
class Solution:
def _com(self, digits, d):
if not digits: return ['']
x = d[digits[0]]
y = self._com(digits[1:], d)
r = []
for p in x:
for q in y:
r.append(p + q)
return r
# @return a list of strings, [s1, s2]
def letterCombinations... |
from functools import wraps
from flask import abort
from flask.ext.login import current_user
from .models import Permission
def permission_required(permission):
"""Restrict a view to users with the given permission."""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
... |
from django import template
from django.utils.html import mark_safe, format_html
register = template.Library()
@register.filter
def pytricon(value):
if value:
color = '#008000'
ret = 'ok'
elif value is None:
color = 'black'
ret = 'minus'
else:
ret = 'remove'
c... |
import mysqlhack #pylint: disable = unused-import
import thread
from re import match
from com.ziclix.python.sql import zxJDBC
from helpers import *
from secrets import *
from random import randrange
def mysql_query(query, args, fetch = True):
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mys... |
def lmax(X, i, j):
maxSum = (X[i], i)
s = X[i]
# sum up from the lower index going up
# (from left to right)
for k in range(i+1, j+1):
s += X[k]
if s > maxSum[0]:
maxSum = (s, k)
return maxSum |
from __future__ import absolute_import
from weblib.logs import default_logging # noqa
from grab.error import (GrabError, DataNotFound, GrabNetworkError, # noqa
GrabMisuseError, GrabTimeoutError)
from grab.upload import UploadContent, UploadFile # noqa
from grab.base import Grab # noqa
__vers... |
import sys, os
if len(sys.argv) > 1:
folder = sys.argv[1]
files = os.listdir(folder)
ids = sorted(set(map(lambda file: int(file.split('.')[0]), files))) |
import time
import demistomock as demisto
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
def get_opened_iot_incidents():
resp = demisto.executeCommand('getIncidents', {
'query': '-status:Closed and (type... |
'''
Created on 31 Mar 2015
@author: WMOORHOU
'''
from os import name
from pypomvisualiser.display.TKinterDisplay import TKinterDisplay
class DisplayFactory(object):
'''
classdocs
'''
@staticmethod
def getDisplayMechanism():
if name is "nt":
display = TKinterDisplay()
... |
"""Hadoop Simulator
This simulator takes three configuration files, topology.xml, metadata.xml,
and job.xml, describing a Hadoop job and the topology it will run on.
Two tcl files, topology.tcl and events.tcl, will be generated as input
for ns-2 for further simulation.
"""
import xml.dom.minidom
import sys
from optpars... |
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import openslides.utils.models
def move_custom_slides_to_topics(apps, schema_editor):
"""
Move all custom slides to new topic model.
"""
# We get the model f... |
from micropython import const
import framebuf
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_plasma_bandit.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/intangible/pet/shared_veermok_hue.iff"
result.attribute_template_id = -1
result.stfName("","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import sqlalchemy as sa
from .. import exc as sa_exc
from ..util import compat
_repr_stack = set()
class BasicEntity(object):
def __init__(self, **kw):
for key, value in kw.items():
setattr(self, key, value)
def __repr__(self):
if id(self) in _repr_stack:
return object.__... |
import os
import sys
def run():
from django.core.management import execute_from_command_line
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.testapp.testapp.settings'
sys.path.append(os.path.join('tests', 'testapp'))
execute_from_command_line([sys.argv[0], 'test'] + sys.argv[1:])
if __name__ == '__main__'... |
from .base import Pool
from .. import event
from ..engine.base import Engine
class PoolEvents(event.Events):
"""Available events for :class:`_pool.Pool`.
The methods here define the name of an event as well
as the names of members that are passed to listener
functions.
e.g.::
from sqlalchemy... |
from distutils.core import setup
setup(
name='SecFS',
version='0.1.0',
description='6.858 final project --- an encrypted and authenticated file system',
long_description= open('README.md', 'r').read(),
author='Jon Gjengset',
author_email='jon@thesquareplanet.com',
maintainer='MIT PDOS',
... |
"""String class.
Represents a unicode string using a widget.
"""
from .domwidget import DOMWidget
from .widget import CallbackDispatcher, register
from traitlets import Unicode, Bool
from warnings import warn
class _String(DOMWidget):
"""Base class used to create widgets that represent a string."""
_model_modul... |
from __future__ import unicode_literals
import mistune
from .block import BlockLexer
from .inline import InlineLexer
from .renderer import Renderer
class Markdown(mistune.Markdown):
def __init__(self, no_follow=True):
renderer = Renderer(
escape=True,
hard_wrap=True,
no_f... |
import numpy as np
from numba import jit
@jit
def aprox_pi(N):
points = 2 * np.random.rand(N, 2) - 1
M = 0
for k in range(N):
if points[k,0]**2 + points[k,1]**2 < 1.:
M += 1
return 4.*M/N
print(aprox_pi(1e8)) |
import os.path as op
import pytest
import tempfile
@pytest.fixture(scope='module')
def test_files_tempdir(test_files):
# /tmp/
return tempfile.gettempdir()
@pytest.fixture(scope='module')
def test_files():
return 'test_files'
@pytest.fixture(scope='module')
def test_files_sequences(test_files):
"""Seque... |
from tinydb import TinyDB, where
import os
import requests
import json
from ltk.constants import CONF_DIR, DB_FN, FOLDER_DB_FN
from ltk.apicalls import ApiCalls
from ConfigParser import ConfigParser, NoOptionError
class DocumentManager:
def __init__(self, path):
self.db_file = os.path.join(path, CONF_DIR, D... |
def tag_clean(tagstring):
return ' '.join(filter(lambda x: x != u'', tagstring.split(' '))) |
import io
import os
import IOOperations
import PreProc
''' CallBacks '''
def cbIncCondition( item ):
return 'define' in item
def cbAsmCondition( item ):
return 'ifdef' in item or 'ifndef' in item
''' CallBacks '''
def cbIncGetFileList( dirForFound, typeInFile ):
# поис и среди исходных файлов
for dir in dirForFound... |
def example_function():
print("This can be called using:\n from matasano.util.example import example_function\n example_function()") |
from django import template
register = template.Library()
@register.simple_tag(takes_context = True)
def cookie(context, cookie_name):
request = context['request']
result = request.COOKIES.get(cookie_name,'')
if result == 'accepted':
return True
return False
@register.tag(name='captureas')
def ... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/component/dna/shared_dna_template_guf_drolg.iff"
result.attribute_template_id = -1
result.stfName("craft_dna_components_n","dna_template_guf_drolg")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
re... |
from broca import Pipe
class PreProcessor(Pipe):
input = Pipe.type.docs
output = Pipe.type.docs
def __call__(self, docs):
return self.preprocess(docs)
def preprocess(self, docs):
raise NotImplementedError
from .clean import BasicCleaner
from .html import HTMLCleaner |
from unittest import TestCase
import mock
from json import loads, dumps
import hashlib
from preggy import expect
import pylibmc
from thumbor_memcached.storage import (
Storage
)
class MemcacheStorageTestCase(TestCase):
def setUp(self, *args, **kw):
super(MemcacheStorageTestCase, self).setUp(*args, **kw)... |
""" Handles operation related to files. """
import os
def file_reader(file_path, file_name):
"""
Reads from a file.
:param file_path: str the path to the file.
:param file_name: str the name of the file.
:return: list of lines or None if no file exists.
"""
file_content = []
try:
... |
'''OpenGL extension ARB.vertex_shader
This module customises the behaviour of the
OpenGL.raw.GL.ARB.vertex_shader to provide a more
Python-friendly API
Overview (from the spec)
This extension adds programmable vertex level processing to OpenGL. The
application can write vertex shaders in a high level language as defi... |
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/intangible/pet/shared_bearded_jax_hue.iff"
result.attribute_template_id = -1
result.stfName("","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
from msrest.paging import Paged
class VirtualNetworkPeeringPaged(Paged):
"""
A paging container for iterating over a list of :class:`VirtualNetworkPeering <azure.mgmt.network.v2016_09_01.models.VirtualNetworkPeering>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},... |
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0)
t.write("Jamroot.jam", """\
import param ;
import assert ;
import errors : try catch ;
rule test1 ( )
{
param.handle-named-params ;
}
test1 ;
rule test2 ( sources * )
{
param.handle-named-params sources ;
return $(sources) ;
}
assert.result : test2 ;
a... |
class Cast: |
def a(x, y):
x = x + 1
print 'a returning x * y =', x * y
return x * y
def b(z):
print 'calling a with x =', z, 'and y =', z
prod = a(z,z)
#print z, prod
print 'b returning a(z, z) =', prod
return prod
def c(x, y, z):
total = x + y + z
print 'calling b with z =', total
square... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PhotoManager', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='photo',
name='origin_source',
fie... |
from __future__ import absolute_import
import logging
import os
from pip._vendor.six.moves import configparser
from pip._internal.exceptions import BadCommand, InstallationError
from pip._internal.utils.misc import display_path
from pip._internal.utils.subprocess import make_command
from pip._internal.utils.temp_dir im... |
import pytest
from flexget.components.imdb.utils import ImdbParser
@pytest.mark.online
class TestImdbParser:
def test_parsed_data(self):
parser = ImdbParser()
parser.parse('tt0114814')
assert parser.actors == {
'nm0000592': 'Pete Postlethwaite',
'nm0261452': 'Christin... |
"""This client pushes PCAPs -> MetaDaa -> ELS Indexer."""
import zerorpc
import os
import client_helper
def run():
"""This client pushes PCAPs -> MetaDaa -> ELS Indexer."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=3... |
import gym, gym.spaces, gym.utils, gym.utils.seeding
import numpy as np
import pybullet
from pybullet_utils import bullet_client
from pkg_resources import parse_version
class MJCFBaseBulletEnv(gym.Env):
"""
Base class for Bullet physics simulation loading MJCF (MuJoCo .xml) environments in a Scene.
These environmen... |
import functools
def memoize(fn):
known = dict()
@functools.wraps(fn)
def memoizer(*args):
if args not in known:
known[args] = fn(*args)
return known[args]
return memoizer
@memoize
def nsum(n):
'''Returns the sum of the first n numbers'''
assert(n >= 0), 'n must be >=... |
from P4 import P4, P4Exception # Import the module
p4 = P4() # Create the P4 instance
p4.port = 'localhost:1666'
p4.user = 'fred'
p4.client = 'fred-ws' # Set some environment variables
try: # Catch exceptions with try/except
p4.connect() ... |
import logging
import os.path
import shutil
import tempfile
import zipfile
from sys import version_info
import lxml.html
from lxml import etree
import epubinfo
class Epub(object):
def __init__(self, _file):
"""
_file: can be either a path to a file (a string) or a file-like object.
"""
... |
import os
import sys
"""Plugins basic structure."""
class Plugin(object):
"""
Base class for plugins.
You'll inherit from this to write you own plugins.
"""
name = 'noname'
enabled = False
priority = 3
parser = None
def __init__(self, name=None, enabled=None):
"""Creates a ne... |
"""Instructions for automated testing, building of pydicom using Fabric"""
from fabric.api import local, settings, abort
from fabric.contrib.console import confirm
import os.path
import pydicom
pydicompath = pydicom.__path__[0]
tox_ini = os.path.join(pydicompath, "../tox.ini")
def syntax():
local("reindent -r " + p... |
from datetime import datetime, timedelta, tzinfo
from dateutil import tz
import pytz
LOCAL_TZ = pytz.timezone("Asia/Shanghai")
def to_utc(dt):
local_dt = LOCAL_TZ.localize(dt, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
return utc_dt
def to_local(dt):
with_tz = pytz.UTC.localize(dt)
local_dt... |
"""
The Python Debugger Pdb
=======================
To use the debugger in its simplest form:
>>> import pdb
>>> pdb.run('<a statement>')
The debugger's prompt is '(Pdb) '. This will stop in the first
function call in <a statement>.
Alternatively, if a statement terminated with an unhandled exception,
... |
from PyQt4.QtCore import pyqtSlot, QSettings
from PyQt4.QtGui import QApplication, QDialog, QDialogButtonBox, QTableWidgetItem
from PyQt4.QtXml import QDomDocument
import ui_catarina
import ui_catarina_addgroup
import ui_catarina_removegroup
import ui_catarina_renamegroup
import ui_catarina_addport
import ui_catarina_r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.