content stringlengths 4 20k |
|---|
# pylint: disable=no-self-use,invalid-name
from flaky import flaky
import pytest
import numpy
from numpy.testing import assert_almost_equal
import torch
from torch.autograd import Variable
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.common.testing import Model... |
# -*- coding: utf-8 -*-
import os, sys, time, random, fcntl, socket, math
from conf import *
term = os.getenv("TERM")
if 'color' in term or term == 'rxvt':
MESSAGE_SUCCESS = '\033[0;48;36m Success \033[0m' # Blue
MESSAGE_FAILED = '\033[0;48;31m Failed \033[0m' # Red
MESSAGE_SKIPPED = '\033[0;48;33... |
import httpretty
from six.moves import urllib
from keystoneclient.auth.identity import v2
from keystoneclient import exceptions
from keystoneclient import session
from keystoneclient.tests import utils
class V2IdentityPlugin(utils.TestCase):
TEST_ROOT_URL = 'http://127.0.0.1:5000/'
TEST_URL = '%s%s' % (TEST... |
from keras.models import model_from_config
from keras.preprocessing import sequence
from sklearn import preprocessing
from python_speech_features import logfbank
import scipy.io.wavfile as wav
from subprocess import call
import numpy as np
import json
import os.path
import sys
def load_model(model_name="model"):
... |
# -*- coding: utf-8 -*-
__title__ = "Save families"
__doc__ = """Saves chosen families from the project
1. Run the script.
2. Choose families from the list.
3. Pick a folder to save the families
Voila!
"""
from pyrevit import revit, script, DB, forms
import os.path as op
selection = revit.get_selection()
logger = sc... |
__author__ = 'Anindya Guha (<EMAIL>)'
from numpy import *
import networkx as nx
from networkx.algorithms.approximation import *
import matplotlib.pyplot as plt
from scipy.stats import rv_discrete
def is_infected(edge_weight, percentage_infected, timestep):
prob = 1 - (1 - edge_weight*percentage_infected/10... |
#!/usr/bin/env python3
from reporter.core import Schedule, SqlReport
from reporter.emailing import RECIPIENT_BIORESOURCE_ADMIN
from reporter.uhl_reports.civicrm import get_contact_id_search_link
class BioresourceConsentedNotRecruited(SqlReport):
def __init__(self):
super().__init__(
... |
"""Test suite for the profile module."""
import sys
import pstats
import unittest
import os
from difflib import unified_diff
from io import StringIO
from test.support import TESTFN, run_unittest, unlink
from contextlib import contextmanager
import profile
from test.profilee import testfunc, timer
from test.support.sc... |
#! /usr/bin/env python
"""
Sample for python PCSC wrapper module: illustrate reader groups functions
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:<EMAIL>
Copyright 2010 Ludovic Rousseau
Author: Ludovic Rousseau, mailto:<EMAIL>
This file is part of pyscard.
pys... |
from PyQt4.Qt import Qt
from PyQt4.QtCore import QTimer, pyqtSlot
from PyQt4.QtGui import QIcon, QMainWindow, QMessageBox
from Subscriber import SubscriberApplication
from PilotInfo import PilotInfo
from Remote import Scheduler
from PositionsDock import PositionsDock
from TelemetryDock import TelemetryDock
from Util im... |
import textwrap
import mock
from twisted.internet import defer
from twisted.trial import unittest
from buildbot.process.properties import Interpolate
from buildbot.process.results import CANCELLED
from buildbot.process.results import EXCEPTION
from buildbot.process.results import FAILURE
from buildbot.process.result... |
import os
import sys
import argparse
from django.conf import settings
class QuickDjangoTest(object):
"""
A quick way to run the Django test suite without a fully-configured project.
Example usage:
>>> QuickDjangoTest('app1', 'app2')
Based on a script published by Lukasz Dziedzia at:
http... |
#!/usr/bin/env python
import unittest
import numpy as np
import rospy
import rostest
import os
from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface
class RobotStateUpdateTest(unittest.TestCase):
PLANNING_GROUP = "manipulator"
@classmethod
def setUpClass(self):
... |
# -*- coding: UTF-8 -*-
#
# Description:
# Downloads all voices from the atpages page.
#
# This script is only used for pulling old abyssal voices
# (because many are not on the servers anymore)
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os
import re
import cfscrape
from kcinit import *
def scrapeA... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
from lib.util import execute, get_out_dir
LINUX_BINARIES_TO_STRIP = [
'electron',
'libffmpeg.so',
'libGLESv2.so',
'libEGL.so',
'swiftshader/libGLESv2.so',
'swiftshader/libEGL.so',
'swiftshader/libvulkan.so'
... |
'''
Collison Checking class for robot singulation policy
Author: Michael Laskey
'''
import math
import IPython
import numpy as np
import cv2
from alan.rgbd.basic_imaging import sin, cos
from alan.rgbd.conversions import gripperLenPixels
def findValidPlacement(bgMat, robotState, searchDim = 0):
"""
Find th... |
from relna.features.relations import EdgeFeatureGenerator
class BiGramFeatureGenerator(EdgeFeatureGenerator):
"""
For each edge, we consider all the intermediate tokens between the two
entities. For all the tokens between the entities, we construct an n-gram
representation.
:param feature_set: the... |
import csv
import subprocess
import json
import shlex
import os
import sys
import getopt
import urllib
DOCCNV_BASEURL='https://gateway.watsonplatform.net/document-conversion/api'
DOCCNV_CREDS='username:password'
DOCCNV_CNVURL = '%s/v1/convert_document?version=2015-12-15' % (DOCCNV_BASEURL)
CSV_FILE=''
O... |
# -*- coding: utf-8 -*-
__version__ = '0.5.0'
__doc__ = """
Bitbucket has a REST API publicly available, this package provide methods to interact with it.
It allows you to access repositories and perform various actions on them.
Various usages : ::
from bitbucket.bitbucket import Bitbucket
# Access a public... |
"""
StorageBackend
"""
import os
import time
import hmac
import hashlib
import logging
import collections
import ConfigParser
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
from xml.etree import ElementTree
from xml.dom import minidom
logger = logging.getLogger(__name__)
class Me... |
import sys, os, time, gc
from cStringIO import StringIO
from zope.interface import implements, Interface
from twisted.python.versions import Version
from twisted.trial import unittest
from twisted.spread import pb, util, publish, jelly
from twisted.internet import protocol, main, reactor
from twisted.internet.error i... |
# -*- coding: iso-8859-15 -*-
__revision__ = '$Id: PluginMovieCulturalia.py 389 2006-07-29 18:43:35Z piotrek $'
# Copyright (c) 2006 Pedro D. Sánchez
#
# 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 Foun... |
"""abuselist.py
Abuse List Class file
"""
# define target object
class abuseEvent:
"""Abuse Event Object:
Attributes:
startTime -- the time of the first abuse event for the source IP
endTime -- the time last seen for abuse events for the source IP
source -- the sou... |
"""Constants for Glances component."""
from homeassistant.const import TEMP_CELSIUS
DOMAIN = "glances"
CONF_VERSION = "version"
DEFAULT_HOST = "localhost"
DEFAULT_NAME = "Glances"
DEFAULT_PORT = 61208
DEFAULT_VERSION = 3
DEFAULT_SCAN_INTERVAL = 60
DATA_UPDATED = "glances_data_updated"
SUPPORTED_VERSIONS = [2, 3]
SE... |
import sys, os , re
import datetime, string
from glob import glob
if len(sys.argv) < 2: print 'python find_bad.py CLUSTER_NAME'
cluster = sys.argv[1]
subdir = '/nfs/slac/g/ki/ki05/anja/SUBARU/'
list = glob(subdir + '/' + cluster + '/*_*/SCIENCE/')
backmask_list = []
blank_list = []
good_list = []
for dir in list:
... |
from setuptools import setup
import re
import os
import ConfigParser
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
config = ConfigParser.ConfigParser()
config.readfp(open('tryton.cfg'))
info = dict(config.items('tryton'))
for key in ('depends', 'extras_depend', 'xml'):
i... |
import os
from gettext import gettext as _
from katello.client.api.organization import OrganizationAPI
from katello.client.api.product import ProductAPI
from katello.client.config import Config
from katello.client.core.base import BaseAction, Command
from katello.client.core.utils import test_record, run_spinner_in_bg... |
import click
from proscli.utils import default_cfg
import os
import os.path
import subprocess
import sys
import json
@click.group()
def upgrade_cli():
pass
def get_upgrade_command():
if getattr(sys, 'frozen', False):
if sys.platform == 'win32':
cmd = os.path.abspath(os.path.join(sys.exec... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
from __future__ import unicode_literals
import boto
import sure # noqa
from freezegun import freeze_time
from boto.exception import JSONResponseError
from moto import mock_dynamodb2
from tests.helpers import requires_boto_gte
try:
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Tabl... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Photo'
db.create_table(u'accounts_photo', (
(... |
# -*- coding: utf-8 -*-
# configurations for the production server
# https://docs.djangoproject.com/en/dev/ref/settings/
DEBUG = False
TEMPLATE_DEBUG = DEBUG
TIMTEC_THEME = 'timtec'
SITE_ID = 2
ALLOWED_HOSTS = [
'mooc.timtec.com.br',
'.timtec.com.br',
]
DATABASES = {
'default': {
'ENGINE': 'djan... |
"""Packaging settings."""
from codecs import open
from os.path import abspath, dirname, join
from subprocess import call
from setuptools import Command, setup
from cmapp import __version__
"""
The script uses README.rst file for documentation
"""
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'R... |
"""
This DAG will use Papermill to run the notebook "hello_world", based on the execution date
it will create an output notebook "out-<date>". All fields, including the keys in the parameters, are
templated.
"""
import os
from datetime import timedelta
import scrapbook as sb
from airflow import DAG
from airflow.linea... |
'''
Created on 24.09.2015
@author: michi
'''
from mathx import formula
from mathx import ast
from copy import deepcopy
import os
import logging
log = logging.getLogger('mathx.gleichungslöser')
#handler = logging.StreamHandler(open('/dev/stderr', 'w'))
#formatter = logging.Formatter( '%(asctime)s %(levelname)s %(mes... |
import random
words = [line.strip() for line in open("words.txt")]
word = random.choice(words)
def game():
wordlist = list(word)
dashes = list('_'*len(word))
print "".join(wordlist)
print "".join(dashes)
#play = "yes"4
dick_figures = 0
hang_figures = [
"""
______
|
|
|
|
|
""... |
import textwrap
from StringIO import StringIO
from pykit.p3json.test import PyTest
class TestIndent(object):
def test_indent(self):
h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
{'nifty': 87}, {'field': 'yes', 'morefield': False} ]
expect = textwrap.deden... |
from web.ext.db import DatabaseExtension
from web.db.sa import SQLAlchemyConnection
from web.app.djrq.model.lastplay import DJs
class FakeContext:
""" A fake session, just used to query the database """
def __init__(self):
self.db = {}
class DJDatabaseExtension(DatabaseExtension):
_needs = {'djho... |
from qtype import * # @UnusedWildImport
from qpython import MetaData
from qpython.qtemporal import qtemporal, from_raw_qtemporal, to_raw_qtemporal
class QList(numpy.ndarray):
'''An array object represents a q vector.'''
def _meta_init(self, **meta):
'''Initialises the meta-information.'''
se... |
import io
import os
import re
import abc
import csv
import sys
import email
import pathlib
import zipfile
import operator
import functools
import itertools
import posixpath
import collections
from configparser import ConfigParser
from contextlib import suppress
from importlib import import_module
from importlib.abc im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
TODO: Write this missing docstring
"""
import h5py
import numpy
class HDF5Handler(object):
"""
The idea is that the HDF5Handler mimics the behaviour of 'open' used as a
context manager using the 'with' statement:
>>> with open('myfile.txt','w') as fil... |
import math
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QLinearGradient,QPainter,QFont,QColor,QPen
from PyQt5.QtCore import pyqtSignal
class radiobutton(QWidget):
changed = pyqtSignal()
def __init__(self):
super(radiobutton, self).__init__()
self.setMi... |
import random,sys,argparse
#chooses a word at random from words
def getWord(words):
wordPos=random.randint(0,len(words)-1)
word=words[wordPos]
return word
#turns a file into a list, with each line as an element
def toList(f):
fList=[]
for line in f:
if line!='':
fList.append(li... |
import os
import vcr
import unittest
import beyonic
from beyonic.api_client import RequestsClient, UrlFetchClient
# Test on staging
TEST_API_KEY = '312726d359422c52d986e6a67f713cdf42eb9f96'
TEST_BASE_URL = 'https://staging.beyonic.com/api/'
TEST_API_VERSION = None
# Test on localhost
TEST_API_KEY = 'ceb16a7353367f093... |
"""
Reads in metsrv.dll, patches it with appropriate options for a
meterpreter reverse_https payload compresses/bas64 encodes it
and then builds a python injection wrapper to inject the contained
meterpreter dll into memory.
Concept and module by @harmj0y
"""
import struct, string, random, sys, os
from modules.... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
# encoding: 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):
# Changing field 'Document.type'
db.alter_column('briefcase_document', 'type_id', self.gf('django.db.model... |
import calendar
import grp
import hashlib
import json
import os
import pwd
import passlib.hash
from keystone.common import config
from keystone.common import environment
from keystone import exception
from keystone.openstack.common import log as logging
CONF = config.CONF
LOG = logging.getLogger(__name__)
def re... |
import json
import urllib
from tempest.api_schema.response.compute import flavors as common_schema
from tempest.api_schema.response.compute import flavors_access as schema_access
from tempest.api_schema.response.compute import flavors_extra_specs \
as schema_extra_specs
from tempest.api_schema.response.compute.v2 ... |
"""Test function :func:`iris.util.demote_dim_coord_to_aux_coord`."""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip
import unittest
import iris
import iris.tests.stock as stock
from iris.util import demote_dim_coord_to_aux_c... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ===========================================================================
# Bloque para el iDevice Destacado creado para la FPD por
# José Ramón Jiménez Reyes
# ===========================================================================
"""
Destacado bloque
"""
import log... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# tvalacarta - XBMC Plugin
# Canal para Argia Multimedia
# http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/
#------------------------------------------------------------
import urlparse,re
import urllib
try:
from core import l... |
import os
import unittest
import pymonetdb
MAPIPORT = int(os.environ.get('MAPIPORT', 50000))
TSTDB = os.environ.get('TSTDB', 'demo')
TSTHOSTNAME = os.environ.get('TSTHOSTNAME', 'localhost')
TSTUSERNAME = os.environ.get('TSTUSERNAME', 'monetdb')
TSTPASSWORD = os.environ.get('TSTPASSWORD', 'monetdb')
class TestUnicod... |
from __future__ import absolute_import
import signal
import six
from autobahn.wamp import protocol
from autobahn.wamp.types import ComponentConfig
from autobahn.websocket.util import parse_url
from autobahn.asyncio.websocket import WampWebSocketClientFactory
try:
import asyncio
except ImportError:
# Trollius... |
"""
Script to show summery of medical record of a subject.
"""
from get_sample import Mimic2, PatientData
from mutil import Graph, Csv, intersection
from get_sample import SeriesData
from alg.continuous import gaussian_process_regression
from patient_classification import ControlExperiment
import numpy as np
mimic2d... |
from __future__ import print_function
import sys
import numpy as np
import SimpleITK as sitk
if len(sys.argv)<2:
print('Wrong number of arguments.', file=sys.stderr)
print('Usage: ' + __file__ + ' image_file_name', file=sys.stderr)
sys.exit(1)
# Read image information without reading the bulk data.
file... |
from functools import partial
import struct
import numpy as np
from scipy import sparse
from .constants import (FIFF, _dig_kind_named, _dig_cardinal_named,
_ch_kind_named, _ch_coil_type_named, _ch_unit_named,
_ch_unit_mul_named)
from ..utils.numerics import _julian_to_c... |
from bs4 import BeautifulSoup
from crawler import Crawler
class Crawler8glw(Crawler):
def __init__(self):
Crawler.__init__(self)
self.HOST = "http://www.8glw.com"
self.prefix = "/main_info.asp?id=1&page="
def uniform(self, page):
soup = BeautifulSoup(page, "html.parser") # lx... |
import mock
from nova import db
from nova.openstack.common import jsonutils
from nova.tests.integrated.v3 import api_sample_base
from nova.tests.integrated.v3 import test_servers
fake_db_dev_1 = {
'created_at': None,
'updated_at': None,
'deleted_at': None,
'deleted': None,
'id': 1,
'compute_n... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
from lib.core.common import singleTimeWarnMessage
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOW
def dependencies... |
import os
import sys
import re
import gettext
import datetime
import subprocess
import shlex
import locale
import logging
def set_utf8_locale():
"""Make sure we read/write all text files in UTF-8"""
lang, encoding = locale.getlocale()
if encoding != 'UTF-8':
locale.setlocale(locale.LC_CTYPE, (lang... |
#-----------------------------Startup----------------------------#
from random import choice
from random import randint
words = [line.rstrip().upper() for line in open("wordsLong.txt")]
def startup():
global name
name = input("Greetings traveller!\nWhat is your name?\n--> ")
print(name + "... Ahh, yes. The... |
# -*- coding: utf-8 -*-
# vim: ft=python
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = '/var/lib/dbs'
# SECURITY WARNING: keep the se... |
"""Tests for SoftmaxCrossEntropyWithLogits op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import sys
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.compat import compat
from tensorflow.pytho... |
# ccm clusters
from __future__ import absolute_import
import os
import shutil
import signal
import subprocess
import sys
from six import iteritems, print_
from ccmlib import common, repository
from ccmlib.cluster import Cluster
from ccmlib.dse_node import DseNode
try:
import ConfigParser
except ImportError:
... |
import unittest
from conans.test.utils.tools import TestClient, GenConanfile
class LoopDetectionTest(unittest.TestCase):
def test_transitive_loop(self):
client = TestClient()
client.save({
'pkg1.py': GenConanfile().with_require('pkg2/0.1@lasote/stable'),
'pkg2.py': GenCon... |
import logging
# backend constants
WX = "wx"
PYSIDE2 = "qt-pyside2"
PYQT5 = "qt-pyqt5"
# backend module
HAVE_PYQT5, HAVE_PYSIDE2, HAVE_WX = False, False, False
# is any backend imported?
HAVE_BACKEND = False
BACKEND_MODULE = "No backend loaded"
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
def loa... |
# -*- coding: utf-8 -*-
import json
import random
import time
import datetime
import math
import re
import zulip
from .utils import ordinal
__version__ = '0.0.1'
class Lunchbot():
"""
On Zulip create a bot under "settings" and use the username and API key to initialize this bot.
Stream is the stream t... |
'''
Ultimate Whitecream
Copyright (C) 2016 mortael
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 License, or
(at your option) any later version.
... |
#!/usr/bin/python2.7
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from setuptools import setup, find_packages
NAME = "pycopia-fepy"
VERSION = "1.0"
setup (name=NAME, version=VERSION,
namespace_packages = ["pycopia"],
packages = find_packages(),
# install_requires = ['pycopia-aid>=1.0,==dev'],
de... |
"""
# Partial Duolingo API reference: http://tschuy.com/duolingo/
# More possibly interesting data fields:
print json_data[u'language_data'][u'ru'][u'level_points']
print json_data[u'language_data'][u'ru'][u'level_progress']
print json_data[u'language_data'][u'ru'][u'max_depth_learned']
print json_data[u'language_data... |
import cadquery as cq
# All dimensions are in millimeters
# Sets the pitch of the header pin spacing
pin_spacing = 2.54
# Individual header pin dimensions
pin_width = 0.63
pin_height = 0.63
pin_length = 12.0
body_height = 2.5
body_length = 2.5
# Array of pin dimensions (rows by columns)
rows = 2
columns = 3
# The ... |
"""Merges multiple OS-specific gyp dependency lists into one that works on all
of them.
The logic is relatively simple. Takes the current conditions, add more
condition, find the strict subset. Done.
"""
import logging
import os
import sys
import isolate_format
from utils import tools
def load_isolates(items):
... |
from IPython import embed
import numpy as np
import scipy.stats as stats
import pandas as pd
import os
import sys
networks_path = os.path.abspath(os.path.join((os.path.abspath(__file__)), '../../networks'))
NNDB_path = os.path.abspath(os.path.join((os.path.abspath(__file__)), '../../NNDB'))
training_path = os.path.abs... |
"""Rename the prebuilt OCHamcrest framework to not use the IOS suffix.
Script to rename 'OCHamcrestIOS' to 'OCHamcrest' in the
OCHamcrestIOS framework. We use 'OCHamcrest' as our imports in EarlGrey
and using the OCHamcrestIOS.framework breaks these imports. This changes
the name of the framework and the public files ... |
## Graphite local_settings.py
# Edit this file to customize the default Graphite webapp settings
#
# Additional customizations to Django settings can be added to this file as well
#####################################
# General Configuration #
#####################################
# Set this to a long, random unique s... |
"""
Stacked Bar chart: Like a bar chart but with all series stacking
on top of the others instead of being displayed side by side.
"""
from __future__ import division
from pygal.adapters import none_to_zero
from pygal.graph.bar import Bar
class StackedBar(Bar):
"""Stacked Bar graph class"""
_adapters = [n... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('mhcdashboardapp', '0011_auto_20150210_1514'),
]
operations = [
migrations.AlterField(
... |
import traceback
import sys
debugnum=0
class VSException(Exception):
pass
def _devnull(msg, *fmtargs): # == /dev/null
pass
def prettyfile(fil):
lasttwo=str(fil).split('/')[-2:]
if len(lasttwo)<2: return fil
return '%s/%s' % (lasttwo[0][0],lasttwo[1])
def _withlineno(msg, *fmtargs): # Simple li... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from apps.pedido.models import Pedido
from apps.produto.models import Produto, Tamanho
'''
class AdminInlineItemPedido(admin.TabularInline):
extra = 1
model = ItemPedido
'''
class AdminPedido(admin.ModelAdmin):
def cancelar_pedido(modeladmin, request... |
"""
Tests for course verification sock
"""
from __future__ import absolute_import
import mock
import ddt
from course_modes.models import CourseMode
from lms.djangoapps.commerce.models import CommerceConfiguration
from openedx.core.djangoapps.waffle_utils.testutils import override_waffle_flag
from openedx.core.django... |
import ddt
from django.contrib.auth.models import User
import django.http
import json
from mock import patch
import test_common
import edx2canvas.populate as populate
import edx2canvas.models as models
def create_request(canvas_user_id, post_params):
session = {'LTI_LAUNCH': {
'user_id': canvas_user_id
... |
"""Component to interact with Hassbian tools."""
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.http import HomeAssistantView
from homeassistant.config import async_check_ha_config_file
from homeassistant.const import CONF_UNIT_SYSTEM_IMPERIAL, CONF_UNIT_SYST... |
from messenger.pi_ager_cl_messenger import cl_fact_logic_messenger
from main.pi_ager_cx_exception import *
from main.pi_ager_cl_logger import cl_fact_logger
"""
try:
logger = cl_fact_logger.get_instance()
logger.debug('logging initialised')
raise cx_Sensor_not_defined
except Exception as cx_error:
cl_... |
"""
vp.py
Decision Level module : Velocity Planning
Executes the velocity plan while handeling emergency brake
if requested by the oa module.
"""
#!/usr/bin/python3.5
#-*- coding: utf-8 -*-
###Standard imports :
import time
from os import path
###Specific imports :
##robotBasics:
#Constants:
from ro... |
import mock
import requests
from openstack.common.apiclient import auth
from openstack.common.apiclient import client
from openstack.common.apiclient import exceptions
from openstack.common import test
class TestClient(client.BaseClient):
service_type = "test"
class FakeAuthPlugin(auth.BaseAuthPlugin):
aut... |
#!/usr/bin/env python
''' Copyright (c) 2013 Potential Ventures Ltd
Copyright (c) 2013 SolarFlare Communications Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code ... |
import netaddr
from django.conf import settings # noqa
from django.core.urlresolvers import reverse # noqa
from django.core import validators
from django.forms import ValidationError # noqa
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from horizon import forms
from... |
"""
Camera that loads a picture from an MQTT topic.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.mqtt/
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.components import camera, mqtt
from homeassistant.components.... |
import os
from tempfile import gettempdir
DEBUG = True
SECRET_KEY = 'x'
USE_I18N = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'tests',
]
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE':... |
from __future__ import absolute_import, unicode_literals
import json
from dash.orgs.models import Org
from dash.utils import random_string
from django.core.cache import cache
from enum import Enum
class TaskType(Enum):
sync_contacts = 1
fetch_runs = 2
LAST_TASK_CACHE_KEY = 'org:%d:task_result:%s'
LAST_TAS... |
from asap3 import *
from cPickle import *
from numpy import *
from asap3.testtools import ReportTest
from OpenKIM_modelname import openkimmodel
timeunit = 1.018047e-14 # Seconds
femtosecond = 1e-15 / timeunit # Marginally different from units.fs
print_version(1)
if OpenKIMsupported:
data = load(... |
from collections import defaultdict
from itertools import groupby, chain
from typing import Iterable, Type
from venom import Message
from venom.fields import FieldDescriptor
from venom.message import fields, is_empty
from venom.protocol import JSONProtocol, Protocol
from venom.protocol.transcode import JSONTimestampT... |
import argparse
import logging
import os
from phabtalk.phabtalk import PhabTalk
from buildkite_utils import format_url, BuildkiteApi, strip_emojis
import test_results_report
from benedict import benedict
def get_failed_jobs(build: benedict) -> []:
failed_jobs = []
for j in build.get('jobs', []):
j = ... |
import gc
import math
import os
import time
import numpy as np
import tensorflow as tf
from tentacle.board import Board
from tentacle.data_set import DataSet
from tentacle.ds_loader import DatasetLoader
DATASET_CAPACITY = 16 * 8000
BATCH_SIZE = 32
class ValueNet(object):
def __init__(self, brain_dir, summary_d... |
from __future__ import print_function
import os
import json
import unittest
import abc
import riotwatcher
import data_path
default_report_freq = 100
default_report_callback = print
default_summoner_id = 30890339
default_n_ids_min = 10
default_summoner_ids_directory = data_path.summoner_ids_dir
default_champions_us... |
# -*- coding: utf-8 -*-
import re
import time
from module.plugins.internal.Account import Account
from module.plugins.internal.SimpleHoster import set_cookies
class UploadingCom(Account):
__name__ = "UploadingCom"
__type__ = "account"
__version__ = "0.13"
__description__ = """Uploading.com ac... |
from Timeline.Server.Constants import TIMELINE_LOGGER, LOGIN_SERVER, WORLD_SERVER
from Timeline import Username, Password, Inventory
from Timeline.Utils.Events import Event, PacketEventHandler, GeneralEvent
from Timeline.Utils.Crumbs.Items import Pin, Award
from Timeline.Server.Room import Igloo as IglooRoom
fro... |
# coding=utf-8
__author__ = 'jiataogu'
from emolga.dataset.build_dataset import deserialize_from_file, serialize_to_file
import numpy.random as n_rng
class BSTnode(object):
"""
Representation of a node in a binary search tree.
Has a left child, right child, and key value, and stores its subtree size.
"""
def ... |
# coding: utf-8
import networkx as nx
from Agent import Agent
from Statistic import Statistic
class Graph:
def __init__(self, nodesAmount):
"""Create a pre-populated Barabási-Albert graph."""
from Configuration import INITIAL_CONNECTIONS
self.graph = nx.barabasi_albert_graph(nodesAmount, INITIAL_CONNEC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.