code stringlengths 1 199k |
|---|
from psycopg2 import *
from psycopg2.extras import *
from lxml.etree import *
import re
import configparser
import requests
import base64
import sys
import os
def delete( doiauth, full_doi ):
headers={
'Content-Type' : "application/xml;charset=UTF-8",
"Authorization" : "Basic " + doiauth
}
# print(head... |
"""
Django Unit Test and Doctest framework.
"""
from django.test.client import Client, RequestFactory
from django.test.testcases import (
LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase,
skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature,
)
from django.test.utils import (
ignore_... |
def extractWwwFringeoctopusCom(item):
'''
Parser for 'www.fringeoctopus.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('TWQQF', 'Transmigration with... |
import numpy as np
class RobustNorm(object):
"""
The parent class for the norms used for robust regression.
Lays out the methods expected of the robust norms to be used
by scikits.statsmodels.RLM.
Parameters
----------
None :
Some subclasses have optional tuning constants.
Refere... |
"""Utility functions for gcloud pubsub emulator."""
import os
from googlecloudsdk.api_lib.emulators import util
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import execution_utils
from googlecloudsdk.core import log
from googlecloudsdk.core.util import platforms
PUBSUB = 'pubsub'
PUBSUB_TITLE = '... |
import threading
import numpy
import time
import os.path
from ginga.gw import Widgets, Viewers
from ginga.misc import Bunch
from ginga.util import iqcalc, plots, wcs
from ginga import GingaPlugin
from ginga.util.six.moves import map, zip, filter
try:
from ginga.gw import Plot
have_mpl = True
except ImportError:... |
"""
Script for uploading securely built distributions (artifacts) to private
Dropbox directory.
Dropbox authorization token should be provided only as environment variable
in a secure form. In case of CI systems (AppVeyor, Travis CI) this should
be provided as encrypted value in CI configuration file.
We prefer to use ... |
"""
mixin.py
"""
from trytond.model import fields, ModelView
from trytond.pool import Pool
from trytond.pyson import Eval, Or, Bool
from trytond.transaction import Transaction
from trytond.modules.stock_package.stock import PackageMixin
__all__ = ['ShipmentCarrierMixin']
class ShipmentCarrierMixin(PackageMixin):
... |
from naman.naman.pypelib.resolver import Resolver
try:
import cPickle as pickle
except:
import pickle
from threading import Lock
'''
@author: lbergesio,omoya,cbermudo
@organization: i2CAT, OFELIA FP7
RAWFile
Implementes persistence engine to a raw file for RuleTables
'''
class RAWFile():
... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_noop
from django.utils.translation import ugettext as _
from corehq.apps.es import users as user_es, filters
from corehq.apps.domain.models import Domain
from corehq.apps.groups.hierarchy import get_user_data_from_hierarchy
from ... |
import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
lo... |
import sys
from PttWebCrawler.crawler import *
def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
PttWebCrawler(args)
# Do argument parsing here (eg. with argparse) and anything else
# you want your project to do.
if __name__ == "__main__":
main() |
import json
import logging
import types
import datetime
import collections
import tornado.template
import tornado.gen
import tornado.web
import tornado.websocket
import datetime
import re
def md(s):
if s is None: s = ''
return markdown.markdown(s, extensions=['markdown.extensions.nl2br'])
class DatetimeEncoder(... |
"""
The scene_graph module provides two core data structures that form the
foundation of how the scene is presented and manipulated. Chief of these is
the GameObject, which can be any entity with an audio or visual
representation. Paired with the GameObject is the Component, which implements
behavior for the GameObject... |
import os
def gundo(matcher_info):
name = matcher_info['buffer'].name
return name and os.path.basename(name) == '__Gundo__'
def gundo_preview(matcher_info):
name = matcher_info['buffer'].name
return name and os.path.basename(name) == '__Gundo_Preview__' |
"""
Blueprint for the flatpages
"""
import os.path
from logging import getLogger
import json
from flask import Blueprint, render_template, redirect, current_app
from flask_login import current_user
from sipa.backends.extension import backends
logger = getLogger(__name__)
bp_pages = Blueprint('pages', __name__, url_pref... |
from functionaltest import FunctionalTest
from textwrap import dedent
import key_codes
class Test_2550_EdittableSheetName(FunctionalTest):
def test_sheet_name_edittable(self):
# * Harold logs in and creates a new sheet
self.login_and_create_new_sheet()
# * He notes that the sheet has a name ... |
from __future__ import print_function, division
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import crossentropy, mse... |
from flask import Blueprint
main = Blueprint("main", __name__)
from . import views, errors |
"""
A miscellany of code used to run Trial tests.
Maintainer: Jonathan Lange
"""
__all__ = [
'suiteVisit', 'TestSuite',
'DestructiveTestSuite', 'DocTestCase', 'DryRunVisitor',
'ErrorHolder', 'LoggedSuite', 'PyUnitTestCase',
'TestHolder', 'TestLoader', 'TrialRunner', 'TrialSuite',
'filenameToModule',... |
import os
import unittest
from unittest import TestCase
import pytest
try:
from transformers import RobertaForMaskedLM
from deepchem.feat.smiles_tokenizer import SmilesTokenizer
has_transformers = True
except:
has_transformers = False
class TestSmilesTokenizer(TestCase):
"""Tests the SmilesTokenizer to load t... |
import os
import pwd
import re
import struct
import subprocess
import sys
import time
from collections import namedtuple
from logging import getLogger
log = getLogger('butterfly')
def get_hex_ip_port(remote):
ip, port = remote
if ip.startswith('::ffff:'):
ip = ip[len('::ffff:'):]
splits = ip.split('... |
"""
Test suite for parselib.grammar module.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import sys
sys.path.insert(0, '.')
import pytest
from cxml.lib.grammar import (
NonterminalSymbol, Production, Productions, _Symbol, TerminalSymbol
)
class Describe_Symbol(objec... |
width = int(input())
while True:
in_str = input()
if in_str == "END":
break
else:
total_dots = width - len(in_str)
left_dots = 0
right_dots = 0
if (total_dots % 2) != 0:
left_dots = total_dots // 2 + 1
right_dots = total_dots // 2
else:... |
from ._registration_definitions_operations import RegistrationDefinitionsOperations
from ._registration_assignments_operations import RegistrationAssignmentsOperations
from ._marketplace_registration_definitions_operations import MarketplaceRegistrationDefinitionsOperations
from ._marketplace_registration_definitions_w... |
from __future__ import division
import sys
import time
import logging
import numpy as np
sys.path.append('../../mushu')
sys.path.append('../')
import libmushu
from wyrm.types import RingBuffer
import wyrm.processing as proc
from wyrm import io
logging.basicConfig(format='%(relativeCreated)10.0f %(threadName)-10s %(name... |
from collections import OrderedDict
ud = dict([('a', 1), ('b', 1), ('c', 1)])
print(ud)
od = OrderedDict([('a', 1), ('b', 1), ('c', 1)])
print(od) |
"""
Combine shape objects to create a composite object
"""
from __future__ import print_function
import argparse
import time
import sys
import re
from icqsol.shapes.icqShapeManager import ShapeManager
from icqsol import util
tid = re.sub(r'\.', '', str(time.time()))
parser = argparse.ArgumentParser(description='Compose... |
import glob
import logging
import os
import re
import yaml
from plugins import BasePreprocessor
from yapsy.IPlugin import IPlugin
class BhammerPreprocessor(BasePreprocessor, IPlugin):
def run(self):
"""
Build the command and run.
Return list of contig file(s)
SPAdes takes as input fo... |
import sys
import time
class Dbg():
def __init__(self, verbose, bar_length=40):
self._verbose = verbose
self._bargraph_msg = None
self._bargraph_min = None
self._bargraph_max = None
self._newline = True
self._bar_length = bar_length
self._prev_percent = None
... |
from validr import T
from datetime import time
from . import case
@case({
T.time: [
(time(0, 0, 0), '00:00:00'),
('12:00:59', '12:00:59'),
('23:59:59', '23:59:59'),
[
'59:59',
'24:00:00',
'23:30:60',
'23:60:30',
'2016-07-09T... |
import netdb,os,random
'''
def test_inspect():
netdb.inspect()
'''
def test_sha256():
assert('d2f4e10adac32aeb600c2f57ba2bac1019a5c76baa65042714ed2678844320d0' == netdb.netdb.sha256('i2p is cool', raw=False))
def test_address_valid():
invalid = netdb.netdb.Address()
valid = netdb.netdb.Address()
valid.cost = 10
v... |
from __future__ import absolute_import, print_function, division
import platform
import urwid
from mitmproxy import filt
from mitmproxy.console import common
from mitmproxy.console import signals
from netlib import version
footer = [
("heading", 'mitmproxy {} (Python {}) '.format(version.VERSION, platform.python_ve... |
from twisted.internet import gtk3reactor
gtk3reactor.install()
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from doubanfm.client.gtk import Protocol
from doubanfm.utils import run_client
run_client(Protocol()) |
from thriftrw.spec.list import ListTypeSpec
from thriftrw.spec.map import MapTypeSpec
from thriftrw.spec.struct import StructTypeSpec
from thriftrw.spec.set import SetTypeSpec
from thriftrw.idl import Parser
from thriftrw.compile.scope import Scope
parse_struct = Parser(start='struct', silent=True).parse
def sstruct(fi... |
import git
from fabrik.utils.elocal import elocal
def get_reverse_path():
try:
return elocal('git rev-parse --show-toplevel', capture=True)
except:
return False
def has_git_repro(path=None):
try:
repo = git.Repo(path) # NOQA
except git.exc.NoSuchPathError:
return False
... |
import numpy as np
file = "Animalia_mtDNA_ClassInsecta.txt"
fin = open(file,"r")
dt = fin.readlines()
groupsAvailable = map(int,dt[0].split(","))
totseq = np.sum(groupsAvailable)
names1 = dt[5].strip().split(",")
print groupsAvailable
print totseq
print names1
filenamesets = "["
for i in names1:
filenamesets += '"'+i... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import subprocess
import pwndbg.commands
parser = argparse.ArgumentParser(description='Launches radare2',
epilog="Example:... |
from scrapy.contrib.spiders import CrawlSpider
class todosnombresSpider(CrawlSpider):
name = 'todosnombres'
allowed_domains = ['todosnombres.org']
start_urls = ['http://todosnombres.org/'] |
import email
from email.errors import MessageParseError # noqa: F401
class EmailTransport:
def get_email_from_bytes(self, contents):
message = email.message_from_bytes(contents)
return message |
"""The influence of windowing of lin. sweep signals when using a
Kaiser Window by fixing beta (=7) and fade_in (=0).
fstart = 1 Hz
fstop = 22050 Hz
FIR-Filter: Bandstop
Deconvolution: Unwindowed Excitation
"""
import sys
sys.path.append('..')
import measurement_chain
import plotting
import calculation
im... |
from collections import OrderedDict
import io
import os.path
import zipfile
from django.core.management.base import CommandError
from django.db import transaction, DatabaseError, IntegrityError
import requests
from .models import (RodzajMiejscowosci, JednostkaAdministracyjna,
Miejscowosc, Ulica)
fro... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('symposion_proposals', '__first__'),
]
operations = [
migrations.CreateModel(
name='TalkProposal',
fields=[
('prop... |
from __future__ import unicode_literals
import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import AzureProvider
LOGIN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0"
GRAPH_URL = "https://graph.microsoft... |
"""
pygments.lexers.jvm
~~~~~~~~~~~~~~~~~~~
Pygments lexers for JVM languages.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from ..lexer import Lexer, RegexLexer, include, bygroups, using, \
this, combined, default, word... |
"""
Test suite for pycoin library: check validity of txs in files
tx_valid.json and tx_invalid.json. Adapted from Bitcoin Core
transaction_tests.cpp test suite.
The MIT License (MIT)
Copyright (c) 2015 by Marek Miller
Copyright (c) 2015 by Richard Kiss
Copyright (c) 2015 by The Bitcoin Core Developers
Permission is her... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/furniture/decorative/shared_slave_brazier.iff"
result.attribute_template_id = 6
result.stfName("frn_n","slave_brazier")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
"""
SoftLayer.ssl
~~~~~~~~~~~~~
SSL Manager/helpers
:license: MIT, see LICENSE for more details.
"""
class SSLManager(object):
"""Manages SSL certificates in SoftLayer.
See product information here: http://www.softlayer.com/ssl-certificates
Example::
# Initialize the Manager.
#... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dddp', '0003_auto_20150413_1328'),
]
operations = [
migrations.AddField(
model_name='connection',
name='server_addr',
... |
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import sys
from multiprocessing import Process
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
pp = pprint.PrettyPrinter(indent=4)
class DigiByteRPC:
OBJID = 1
def __init__(self, host, port, username, password)... |
"""
The `~astropy.vo` subpackage provides virtual observatory (VO) related
functionality.
"""
from .. import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.vo`.
"""
vos_baseurl = _config.ConfigItem(
'http://stsdas.stsci.edu/astrolib/vo_databases/... |
from CommonServerPython import *
''' IMPORTS '''
import requests
import dateparser
from datetime import datetime, timedelta
import enum
requests.packages.urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
BASE_URL = 'https://api.cymulate.com/v1/'
DEFAULT_LIMIT = 20
""" Helper functions """
... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/medicine/crafted/shared_medpack_enhance_quickness_a.iff"
result.attribute_template_id = 7
result.stfName("medicine_name","medpack_enhance_quickness_a")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
... |
"""Fabfile for release management."""
import codecs
import glob
import os
import re
from fabric.api import local, abort, lcd
import tests
HERE = os.path.dirname(__file__)
ROOT = HERE
def _readfile(fname, strip="\n"):
"""Shortcut for reading a text file."""
with codecs.open(fname, 'r', 'UTF8') as fp:
con... |
import sys
sys.path.insert(0, '../')
from commander import *
import serial
from pyalertme.zbhub import *
import logging
import pprint
class TestCmd(Command):
"""
This sets up the commands that commander will look for and what to do. The commands are
- discovery
- broadcast
- nodes list
* no... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/droid_interface/shared_base_droid_interface_subcomponent.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","base_droid_interface_subcomponent")
#### BEGIN MODIFICATIONS ####
###... |
import sys, os
import code
import string
import win32ui
import win32api
import win32clipboard
import win32con
import traceback
import afxres
import array
import __main__
import pywin.scintilla.formatter
import pywin.scintilla.control
import pywin.scintilla.IDLEenvironment
import pywin.framework.app
ID_EDIT_COPY_CODE = ... |
from .base import SampleSpiderBase
from scrapy.exceptions import CloseSpider
__all__ = ['SampleLoginSpider']
class SampleLoginSpider(SampleSpiderBase):
name = 'sample'
pipelines_allowed = ['sample', ]
def __init__(self, some_arg=None, arg_required=None, *args, **kwargs):
super(SampleLoginSpider, sel... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('stats', '0005_auto_20150919_1832'),
]
operations = [
migrations.AlterField(
model_name='candidate',
name='supported_by',
... |
from django import forms
from CommentRecaptcha.fields import ReCaptchaField
class RecaptchaForm(forms.Form):
recaptcha = ReCaptchaField() |
import json, os, time, unittest
import dxpy
import dxpy.app_builder
from dxpy.exceptions import DXAPIError
src_dir = os.path.join(os.path.dirname(__file__), "..")
test_resources_dir = os.path.join(src_dir, "test", "resources")
def makeInputs():
# Please fill in this method to generate default inputs for your app.
... |
'''https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid'''
class Node:
def __init__(self,i,j):
self.id= str(i)+str(j)
self.isVisited = False
def get_neigbours(i,j,grid,count):
row_length = len(grid[0])
col_length = len(grid)
count = isValid(i-1,j-1,grid,count)
count = ... |
import mcpy.activate
import demo |
"""
uBiome fastq data extraction.
Copyright (C) 2016 PersonalGenomes.org
This software is shared under the "MIT License" license (aka "Expat License"),
see LICENSE.TXT for full license text.
"""
import os
import shutil
import zipfile
from cStringIO import StringIO
from base_source import BaseSource
class UBiomeSource(B... |
from . import FixtureTest
class PublicTransportStationTest(FixtureTest):
def test_station_node(self):
import dsl
z, x, y = (16, 10522, 25402)
self.generate_fixtures(
# https://www.openstreetmap.org/node/2160213344
dsl.point(2160213344, (-122.197968, 37.464501), {
... |
from scapy.packet import *
from scapy.fields import *
from scapy.layers.dot11 import *
AVSWLANPhyType = { 0 : "Unknown",
1 : "FHSS 802.11 '97",
2 : "DSSS 802.11 '97",
3 : "IR Baseband",
4 : "DSSS 802.11b",
5 : "PBCC 802... |
import argparse
import re
import yaml
import urllib
import urllib2
SEARCH_URL = 'http://%s.wikipedia.org/w/api.php?action=query&list=search&srsearch=%s&sroffset=%d&srlimit=%d&format=yaml'
class Wikipedia:
def __init__(self, lang='en'):
self.lang = lang
def _get_content(self, url):
request = urll... |
from enigma import eComponentScan, iDVBFrontend, eTimer
from Components.NimManager import nimmanager as nimmgr
from Tools.Transponder import getChannelNumber
class ServiceScan:
Idle = 1
Running = 2
Done = 3
Error = 4
DonePartially = 5
Errors = {
0: _("error starting scanning"),
1: _("error while scanning"),
... |
def FooBar():
return "BarFoo" |
import os
import glob
from hashlib import md5
from datetime import datetime
import json
import logging
try:
from markdown import markdown
from markdown.extensions import Extension
class EscapeHtml(Extension):
def extendMarkdown(self, md, md_globals):
del md.preprocessors['html_block']
... |
from numpy import where
from urbansim.datasets.dataset import Dataset as UrbansimDataset
class ConsumptionMfDataset(UrbansimDataset):
"""Set of Bellevue data."""
id_name_default = ['grid_id', 'month', 'year']
### TODO: non-integer id_names cannot be used. This is bad because this
### dataset depen... |
"""
Distance based spatial weights
"""
__author__ = "Sergio J. Rey <srey@asu.edu> "
import pysal
import scipy.spatial
from pysal.common import KDTree
from pysal.weights import W
import scipy.stats
import numpy as np
__all__ = ["knnW", "Kernel", "DistanceBand"]
def knnW(data, k=2, p=2, ids=None, pct_unique=0.25):
""... |
import logging
import time
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count, Max
from texttable import Texttable
from apps.core.models import FileLog, Job, JobTemplate, Recipe
from apps.core.utils.beaker import Beaker
from apps.taskoma... |
"""Spreedsheet Exporter Dialog"""
import gio
import gtk
from stoqlib.api import api
from stoqlib.exporters.xlsexporter import XLSExporter
from stoqlib.lib.message import yesno
from stoqlib.lib.translation import stoqlib_gettext
_ = stoqlib_gettext
class SpreadSheetExporter:
"""A dialog to export data to a spreadshe... |
import Atmosphere as AA
import numpy as np
reload(AA)
def abmag_to_flambda(AB, lam_ang):
'''Convert AB Magnitude to erg/s/cm^2/ang
Arg:
AB: AB Magnitude
lam_ang: Wavelength [angstrom]
Return:
erg/s/cm^2/Ang'''
c = 2.9979e18 # Angstrom / s
if not (2000 < lam_ang < 20000):
... |
"""
This module contains the CodeField class.
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GtkSource
from harpia.GUI.components.field import Field
class CodeField(Field, Gtk.VBox):
"""
This class contains methods related the CodeField class.
"""
... |
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView, ListView
from django.views.generic.base import TemplateView
from django_ajax.decorators import ajax
from mercury.graphing import NodeGraphBuilder
from mercury.models import (
Application,
ApplicationTraffic,
Node,
)
... |
import cgi, sys
print("Content-type: text/html\n") # HTML form uploads a file
print("<pre>")
sys.stderr = sys.stdout # route errors to reply page
form = cgi.FieldStorage() # fails if any incompatible text file uploads
fileinfo = form['clientfile'] # errors in web server console is stderr no... |
import threading
import sys
from libs.Event import Event as EVNT
class BackEnd(object):
onRead = EVNT()
def __init__(self):
pass
def run(self):
def rund():
while True:
self.on_read(raw_input())
t = threading.Thread(target=rund)
t.start()
def wr... |
import turtle
import random
import time
import sys
import math
import mymodule # Error with import mymodule.py
def main():
i = 5
print(i)
i = i + 1
print('value of i is', i)
############### Testing the method of application of string output
s = '''This is a multi-line string.
This is the second l... |
import numpy as np
from . import HiddenLayer
class FlatteningLayer(HiddenLayer):
n_parameters = 0
lr_multiplier = []
def __init__(self, n_in, n_filters,
l1_penalty_weight=0., l2_penalty_weight=0.):
self.n_in = n_in
self.n_filters = n_filters
self.n_units = n_in * n_f... |
from MarkersStorage import MarkersStorage
from DirectionIndicator import DirectionIndicator
from DirectionIndicatorCtrl import DirectionIndicatorCtrl
from VehicleMarkers import VehicleMarkers
from gui.app_loader import g_appLoader
import BigWorld
from debug_utils import LOG_ERROR, LOG_CURRENT_EXCEPTION, LOG_DEBUG, LOG_... |
import os
import sys
import shutil
import logging
import gtk
import httplib2
import wordpresslib #TODO remove need for this library
from pytrainer.extensions.googlemaps import Googlemaps
import pytrainer.lib.points as Points
from pytrainer.lib.date import Date
class wordpress:
def __init__(self, parent = None, ... |
from functools import partial
from collections import OrderedDict
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import Form, Radio, Select, Table, accordion, fill,\
flash, form_buttons, menu, tabstrip, DHTMLSelect, Input, Tree, AngularSelect
from cfme.web_ui import toolbar as tb
from utils.updat... |
import re
def split_string(string, seperator=None, maxsplit=-1):
try:
return string.split(seperator, maxsplit)
except:
return list(string)
def split_regex(string, seperator_pattern):
try:
return re.split(seperator_pattern, string)
except:
return list(string)
class FilterM... |
""" Class that contains client access to the production DB handler. """
__RCSID__ = "$Id$"
from DIRAC import gLogger, S_OK, S_ERROR
from DIRAC.Core.Base.Client import Client
from DIRAC.ProductionSystem.Utilities.StateMachine import ProductionsStateMachine
class ProductionClient(Client):
""" Exposes the functionality ... |
from builtins import object
from datetime import datetime
class Timer(object):
""" A timer to account the elapsed playing.
"""
def __init__(self, accuracy=0):
"""
Arguments:
- `accuracy`:The accuracy of the time provided by players.
If the difference between the time provid... |
from module.plugins.internal.XFSHoster import XFSHoster, create_getInfo
class SafesharingEu(XFSHoster):
__name__ = "SafesharingEu"
__type__ = "hoster"
__version__ = "0.05"
__pattern__ = r'https?://(?:www\.)?safesharing\.eu/\w{12}'
__description__ = """Safesharing.eu hoster plugin"""
__lice... |
from __future__ import unicode_literals
from indico.core.db import db
from indico.util.string import format_repr, return_ascii
class LegacyContributionMapping(db.Model):
"""Legacy contribution id mapping
Legacy contributions had ids unique only within their event.
Additionally, some very old contributions h... |
"""Setup file for python repo."""
from distutils.core import setup
setup(name='source',
version='1.0',
py_modules=['source'],
) |
"""
Unit tests for `dot` module.
"""
import unittest
import numpy as np
import scipy
from numpy import testing
from ..node import Node, Moments
from ...vmp import VB
from bayespy.utils import utils
class TestMoments(unittest.TestCase):
def test_converter(self):
"""
Tests complex conversions for mome... |
import clr
import System
import System.IO.Ports
from serial.serialutil import *
def device(portnum):
"""Turn a port number into a device name"""
return System.IO.Ports.SerialPort.GetPortNames()[portnum]
sab = System.Array[System.Byte]
def as_byte_array(string):
return sab([ord(x) for x in string]) # XXX wi... |
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
n_input = 10 # Number of inputs
n_coded = 6 # Number of nodes in encoder
learning_rate = 0.001
beta1 = 0.9
beta2 = 0.999
epsilon = 1e-8
ins = tf.placeholder("float", shape=(n_input,None)) # Initialize inputs as variables. None de... |
import sys
import os
import csv
PATH_distinct_file_hashes = 'distinct-file-hashes'
if os.path.exists(PATH_distinct_file_hashes):
print 'ERROR - Folder ['+PATH_distinct_file_hashes+'] already exists!'
sys.exit()
else:
os.makedirs(PATH_distinct_file_hashes)
set_ids = set()
set_hashes = set()
for file in os.listd... |
import tempfile
import os
import sys
import zmq
import time
import threading
import uuid
from collections import defaultdict
from .utils import env, ProcessKilled, get_localhost_ip, get_open_files_and_connections
from .signatures import StepSignatures, WorkflowSignatures
from .messages import encode_msg, decode_msg
EVE... |
import ctypes
class Array1D:
# Creates an array with size.
def __init__(self, size):
assert size > 0, "Array size must be > 0"
self._size = size
# Create the array structure using the ctypes module
PyArrayType = ctypes.py_object * size
self._elements = PyArrayType()
... |
from django.forms import widgets
from django.forms.util import flatatt
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
class DatePicker(widgets.Widget):
def __init__(self, attrs=None):
default_attrs = {}
super(DatePicker, self).__init__(default_attrs)... |
try:
import openid
CAN_USE = True
except:
CAN_USE = False |
"""Planck radiation equation."""
import numpy as np
import logging
try:
import dask.array as da
except ImportError:
da = np
LOG = logging.getLogger(__name__)
H_PLANCK = 6.62606957 * 1e-34 # SI-unit = [J*s]
K_BOLTZMANN = 1.3806488 * 1e-23 # SI-unit = [J/K]
C_SPEED = 2.99792458 * 1e8 # SI-unit = [m/s]
EPSILON ... |
import lldb
class jasSynthProvider:
def __init__(self, valobj, dict):
self.valobj = valobj;
def num_children(self):
return 2;
def get_child_at_index(self, index):
child = None
if index == 0:
child = self.valobj.GetChildMemberWithName('A');
if inde... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.