content string |
|---|
"""
Basic SSH connectivity.
"""
from twisted.python import log
from twisted.internet import defer, protocol, reactor, endpoints
from twisted.conch import error as concherror
from twisted.conch.ssh import transport, keys, userauth, connection, channel
LOG_SYSTEM = 'opennsa.SSH'
class SSHClientTransport(transport.S... |
def fix_radec(SUPA,FLAT_TYPE):
NUMS = []
at_least_one = False
print dict['file']
for image in dict['files']:
params = copy(search_params)
ROOT = re.split('\.',re.split('\/',image)[-1])[0]
params['ROOT'] = ROOT
BASE = re.split('O',ROOT)[0]
params['BASE'] = BA... |
import shelve
import sys
import os
import random
import csv
def main(argv):
if '-name' in argv:
name = argv[argv.index('-name')+1]
filename_idlist = 'user_id_' + name +'.txt'
outfile = 'user_sample0_' + name + '.csv'
filelist = os.listdir(os.getcwd())
counter = 0
while outfile in filelist... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Database utilities.
"""
import logging
import re
import psycopg2
from psycopg2.extras import execute_values, NumericRange, register_composite, Json
# TODO: use django settings instead?
from .params.db.default import _PARAMS
logger = logging.getLogger(__name__)
logge... |
#!/usr/bin/env python
"""Segmentation using DBSCAN.
Segments a pointcloud into clusters using a DBSCAN algorithm.
Usage:
dbscan [-r <weight>] [-f <format>] [-o <dir>] <epsilon> <minpoints> <file>
Options:
-r <weight>, --rgb_weight <weight> weight assigned to color space
... |
APP_NAME = "zenmap"
APP_DISPLAY_NAME = "Zenmap"
APP_WEB_SITE = "http://nmap.org/zenmap"
APP_DOWNLOAD_SITE = "http://nmap.org/download.html"
APP_COPYRIGHT = "Copyright 2005-2008 Insecure.Com LLC"
NMAP_DISPLAY_NAME = u"Nmap"
NMAP_WEB_SITE = "http://nmap.org"
UMIT_DISPLAY_NAME = "Umit"
UMIT_WEB_SITE = "http://www.umitpr... |
"""
This module is used for the master thesis of Tobias Sebastian Finn
It is used to load the weights of an ensemble Kalman filter and to process
these.
"""
# System modules
import logging
import os
import datetime
import re
from collections import OrderedDict
# External modules
import numpy as np
import xarray as x... |
from hashlib import md5
from app import db
from app import app
import flask.ext.whooshalchemy as whooshalchemy
from config import WHOOSH_ENABLED
ROLE_USER = 0
ROLE_ADMIN = 1
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Intege... |
import cv2
import sys
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
print(major_ver, minor_ver)
if __name__ == '__main__':
# Set up tracker.
# Instead of MIL, you can also use
tracker_types = ['BOOSTING', 'MIL', 'KCF', 'TLD', 'MEDIANFLOW', 'GOTURN']
tracker_type = tracker_type... |
import logging
from pajbot.models.command import Command
from pajbot.models.command import CommandExample
from pajbot.modules import BaseModule
from pajbot.modules import ModuleSetting
from pajbot.modules.clr_overlay import CLROverlayModule
log = logging.getLogger(__name__)
class ShowEmoteModule(BaseModule):
ID... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
dict_get,
float_or_none,
)
class PlaywireIE(InfoExtractor):
_VALID_URL = r'https?://(?:config|cdn)\.playwire\.com(?:/v2)?/(?P<publisher_id>\d+)/(?:videos/v2|embed|config)/(?P<id>\d+)'
_TESTS = [{
'url': '... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime, date
from decimal import Decimal
from base import GAETestCase
from produto_app.produto_model import Produto
from routes.produtos import rest
from gaegraph.model import Node
from mock import Mock
from mommygae... |
#! /usr/bin/env python
#coding=utf-8
#
"""Module findcnt provides objects for investigation of files
Author: sl0
Date: February 7th, 2012
License: GNU General Public License Version 3 or newer
Input-Parameter
===============
-d für den Pfad (zu den Dateien, soll rekursiv durchsucht werden)
-t für den Dateityp (we... |
from data_reader.reader import CsvReader
from util import *
import numpy as np
import matplotlib.pyplot as plt
import copy as cp
class SoftmaxRegression(object):
def __init__(self, learning_rate=0.01, epochs=50):
self.__epochs= epochs
self.__learning_rate = learning_rate
def fit(self, X, y):
... |
# Equipment, items, weapons, and armor
# This is going to hold separate classes for items, equipments, armor, and weapons as these three act very
# differently from each other, if there are better ideas we can handle them, this is just a seed afterall.
# this currently also holds enchantments for arms and armor.
# T... |
import logging
import ConfigParser
from IGWrapper import IGWrapper
import DeepThaw
from urllib import urlencode
config = ConfigParser.RawConfigParser()
config.read('config.cfg')
logging.basicConfig(level=config.getint('logs', 'level'))
print "Using client id: " + config.get('API', 'client_id')
print "Using access t... |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to u... |
from test_framework.test_framework import DankcoinTestFramework
from test_framework.util import *
# Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(DankcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = False
... |
#!/usr/bin/python3
#A simple script to check for AUR package updates
#By Charles Bos
from subprocess import Popen, PIPE
from bs4 import BeautifulSoup
import requests
import os
def versionCheck(localVer, aurVer) :
if localVer == aurVer : return 0
if (aurVer.find(":") != -1) and (localVer.find(":") == -1) : ret... |
import requests
from urllib import urlencode
from urllib import quote
class PhreakSummoners:
def __init__(self, api_key, region=None):
self._name_to_id = {}
self._api_key = api_key
self._version = '1.4'
if region is not None:
self._region = region
else:
self._region = 'na'
self._connection_string =... |
import pandas as pd
from numba import njit
@njit
def series_abs():
s = pd.Series([-1.10, 2, -3.33])
out_series = s.abs()
return out_series # Expect series of 1.10, 2.00, 3.33
print(series_abs()) |
import os
import subprocess
from . import errors
from ._base import Base
class Subversion(Base):
def __init__(self, source, source_dir, source_tag=None, source_commit=None,
source_branch=None, source_depth=None, source_checksum=None):
super().__init__(source, source_dir, source_tag, sou... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ReleaseFile.hidden'
db.add_column('packages_releasefile', 'hidden',
se... |
class SourceBuilder:
"""This class should be used to build .py source files"""
def __init__(self, out_stream, indent_size=4):
self.current_indent = 0
self.on_new_line = False
self.indent_size = indent_size
self.out_stream = out_stream
# Was a new line added automaticall... |
import pytest
from pycroft.helpers.interval import IntervalSet, closed, openclosed
class TestTypeMangling:
def test_type_mangling(self):
# TODO one test per assertion and `target` / `base` as fixtures
target = IntervalSet([closed(0, 1)])
# Creation
assert target == IntervalSet(clo... |
import pleasant.base as _base
# types
atom_t = _base.atom_t
constant_t = _base.Type("constant_t")
logic_t = _base.Type("logic_t")
expr_t = _base.Type("expr_t")
reg_t = _base.Type("reg_t")
wire_t = _base.Type("wire_t")
bundle_t = _base.Type("bundle_t")
array_t = _base.Type("array_t")
syncable_t = _base.Type("syncable_t... |
#!/usr/bin/env python
from setuptools import setup,find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
#Dependencies - python eggs
install_requires = [
'setuptools',
'Django',
]
setup(name='django-toast-messages',
version='0.1',
de... |
"""The finders we wish we had in setuptools.
As of setuptools 3.3, the only finder for zip-based distributions is for eggs. The path-based
finder only searches paths ending in .egg and not in .whl (zipped or unzipped.)
pex.finders augments pkg_resources with additional finders to achieve functional
parity between wh... |
import numpy as np
import pytest
from numpy.testing import assert_allclose
import gpflow
from gpflow.kernels import SquaredExponential
from gpflow.likelihoods import Gaussian
from tests.gpflow.kernels.reference import ref_rbf_kernel
rng = np.random.RandomState(1)
# ------------------------------------------
# Helper... |
"""
Adminstration.py allows users to control ArcGIS Server 10.1+
through the Administration REST API
"""
from .._abstract.abstract import BaseAGSServer
from datetime import datetime
import csv
import os
import json
import _machines, _clusters
import _data, _info
import _kml, _logs
import _security, _services
imp... |
import six
from kmip.core import enums
from kmip.core import objects
from kmip.core import primitives
from kmip.core import utils
from kmip.core.messages.payloads import base
class RekeyRequestPayload(base.RequestPayload):
"""
A request payload for the Rekey operation.
Attributes:
unique_identif... |
# -*- coding: utf-8 -*-
"""Define the Grant ABI.
Copyright (C) 2021 Gitcoin Core
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later... |
#!/usr/bin/python
import sys
import struct
import subprocess
import termcolor
termcolor.cprint("32-bit ELF Exploitation -- Format string without ASLR -- Arbitrary Read","white",attrs=["bold"])
subprocess.run(["sudo","sysctl","kernel.randomize_va_space=0"], stdout=subprocess.DEVNULL)
termcolor.cprint("0x00 - Fuzz th... |
from twisted.internet import defer
from twisted.internet.interfaces import IStreamServerEndpoint
from twisted.protocols.haproxy._wrapper import HAProxyWrappingFactory
from twisted.protocols.tls import TLSMemoryBIOFactory
from zope.interface import implementer
@implementer(IStreamServerEndpoint)
class HAProxyServerEnd... |
"""
pyequib - Python Package for Plasma Diagnostics and Abundance Analysis
"""
__all__ = ["calc_temperature", "calc_density",
"calc_populations", "calc_crit_density",
"calc_emissivity", "calc_abundance",
"print_ionic", "get_omij_temp",
"calc_emiss_h_i", "calc_emiss_h_be... |
import re # importing regular expression package
import csv
## napln list slovnikama z csvcka
list =[] # list
a=0 # pocitadlo
with open('app_hosts_withregex', 'rb') as csvfile:
reader=csv.DictReader(csvfile)
for row in reader:
a = a+1
row ['host'] = '.*\.'+row['host']+"\... |
"""
Tests for ReducePyScalersTable module.
"""
# This file is part of MAUS: http://micewww.pp.rl.ac.uk:8080/projects/maus
#
# MAUS 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 L... |
"""Test covariance and correlation on 2 columns, matrices on 400x1024 matric"""
import unittest
import numpy
from sparktkregtests.lib import sparktk_test
class CovarianceTest(sparktk_test.SparkTKTestCase):
def setUp(self):
"""Build test frames"""
super(CovarianceTest, self).setUp()
data_i... |
#!coding-utf-8
import os
import sys
import glob
import logging
COLUMS = ["date","open","high","close","low","volume","amount"]
class CalMoreInfo(object):
"""docstring for CalMoreInfo
"""
def __init__(self):
self.stockid = ""
self.current_day = ""
self.outcolums = ""
def ... |
from amdevice import *
from plistservice import *
from ctypes import *
from datetime import datetime
import socket
class iptap_hdr_t(BigEndianStructure):
_pack_ = 1
_fields_ = [
(u'hdr_length', c_uint32),
(u'version', c_uint8),
(u'length', c_uint32),
(u'type', c_uint8),
... |
"""Function for loading AndroidEnv."""
import os
from android_env import environment
from android_env.components import coordinator as coordinator_lib
from android_env.components import emulator_simulator
from android_env.components import task_manager as task_manager_lib
from android_env.proto import task_pb2
from ... |
"""
Support for Fido.
Get data from 'Usage Summary' page:
https://www.fido.ca/pages/#/my-account/wireless
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.fido/
"""
from datetime import timedelta
import logging
from pyfido import FidoClient
from p... |
from __future__ import unicode_literals
import frappe
import copy
from frappe import _
from frappe.utils import nowdate, cint, cstr
from frappe.utils.nestedset import NestedSet
from frappe.website.website_generator import WebsiteGenerator
from frappe.website.utils import clear_cache
from frappe.website.doctype.website_... |
import pysb, pysb.bng, warnings, re, sympy
class JacobianGenerator(object):
def __init__(self, model):
self.model = model
self.indent_level = 0
self.__content = None
def get_content(self, sim_length=1):
if self.__content == None:
self.generate_content(sim_length=s... |
__author__ = 'casey'
from nose.plugins.attrib import attr
import numpy as np
import os, shutil, tempfile
import unittest
import shutil, tempfile
from pyon.core.bootstrap import CFG
from pyon.datastore.datastore_common import DatastoreFactory
import psycopg2
import psycopg2.extras
from coverage_model import *
from cov... |
# -*- coding: utf-8 -*-
import logging
import os
from django.db import models
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from filer.utils.filer_easy_thumbnails import FilerThumbnailer
from filer.utils.pil_exif import get_exif_for_file
from .. import settings as filer_settings... |
import argparse
import os
import sys
from fabric.api import *
from fabric.colors import red
from fabric.contrib import files
from fabric.network import disconnect_all
from playback import __version__, common
from playback.templates.glance_api_conf import conf_glance_api_conf
from playback.templates.glance_... |
"""Shared library for `eight_schools_hmc_{graph,eager}_test.py`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
import tensorflow_pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import web
from gothonweb import map
### Session example starts. ###
#web.config.debug = False
#
#urls = (
# "/count", "count",
# "/reset", "reset"
#)
#app = web.application(urls, locals())
#store = web.session.DiskStore('sessions')
#session = web.session.Session(ap... |
#!/usr/bin/python
# Imports
import sys
import os
import logging
import traceback
import tempfile
import shutil
import pwd
from optparse import OptionParser
from StringIO import StringIO
import common_utils as utils
import types
import basedefs
# Consts
BASE_NAME = "ovirt-engine"
PREFIX = "engine"
PROD_NAME = "oVirt E... |
from config_manager.eucalyptus.topology.cluster.nodecontroller import NodeController
class Xen(NodeController):
def __init__(self,
name,
description=None,
read_file_path=None,
write_file_path=None,
property_type=None,
... |
"""
test_ajax.py: Unit tests for ``bottle_utils.ajax`` module
Bottle Utils
2014-2015 Outernet Inc <<EMAIL>>
All rights reserved
Licensed under BSD license. See ``LICENSE`` file in the source directory.
"""
from __future__ import unicode_literals
try:
from unittest import mock
except ImportError:
import mock... |
# encoding: utf-8
from __future__ import print_function
import cmd
import codecs
import datetime
import errno
import os
import sqlite3
from subprocess import call
from threading import Lock
from urllib import unquote
from stevedore import dispatch
from osint.utils.analyser import Analyser
from osint.utils.db_helpers... |
"""Produces ratations for input images.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import google3.learning.brain.research.dune.experimental.representation.datasets as datasets
import google3.learning.brain.research.dune.ex... |
from papyon.media import *
from papyon.event.media import *
import pygst
pygst.require('0.10')
import farsight
import gobject
import gst
import logging
import sys
logger = logging.getLogger("papyon.media.conference")
codecs_definitions = {
"audio" : [
(114, "x-msrta", farsight.MEDIA_TYPE_AUDIO, 16000),
... |
from django.views.generic.edit import (FormMixin, ProcessFormView,
ModelFormMixin, DeletionMixin)
from django_modalview.generic.base import (ModalContextMixin, ModalView,
ModalTemplateMixin, ModalUtilMixin)
from django_modalview.generic.... |
"""
Implement Dominance-Fronter-based SSA by Choi et al described in Inria SSA book
References:
- Static Single Assignment Book by Inria
http://ssabook.gforge.inria.fr/latest/book.pdf
- Choi et al. Incremental computation of static single assignment form.
"""
import logging
import operator
import warnings
from func... |
import logging
import os
import unittest
import cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger
import cmapPy.set_io.gmt as gmt
logger = logging.getLogger(setup_logger.LOGGER_NAME)
FUNCTIONAL_TESTS_DIR = "cmapPy/set_io/tests/functional_tests/"
class TestGMT(unittest.TestCase):
@classmethod
def setUpClass... |
# -*- encoding: utf-8 -*-
from . import FixtureTest
class AerodromeSortTest(FixtureTest):
def test_sort_order(self):
import dsl
z, x, y = (16, 0, 0)
poly = dsl.tile_box(z, x, y)
line = dsl.tile_diagonal(z, x, y)
def _src(props):
p = {'source': 'openstreetmap... |
from __future__ import unicode_literals
from __future__ import print_function
import pytest
from optparse import OptionError
from textwrap import dedent
from wharfee.options import parse_command_options, format_command_help, \
format_command_line
from wharfee.utils import shlex_split
from wharfee.completer import ... |
import os
from conary.build import nextversion
from conary.deps import deps
from conary.repository import changeset
from conary.repository import trovesource
from conary import trove
from conary import versions
def makePathId():
"""returns 16 random bytes, for use as a pathId"""
return os.urandom(16)
class C... |
import furl
from modularodm import Q
from rest_framework import serializers as ser
from website import settings
from framework.auth.core import User
from website.files.models import FileNode
from api.base.utils import absolute_reverse
from api.base.serializers import NodeFileHyperLinkField, WaterbutlerLink, format_re... |
from shinken_test import *
from shinken.log import logger
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/nagios_1r_1h_1s.cfg')
# Try to raise an utf8 log message
def test_utf8log(self):
sutf = 'h\351h\351' # Latin Small Letter E with acute in Latin-1
l... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from textwrap import dedent
from pants.backend.codegen.thrift.java.apache_thrift_java_gen import ApacheThriftJavaGen
from pants.backend.codegen.thrift.java.java_thrif... |
'''
Interface object for working with the Cambridge Gestures Data Set
Created on Oct 14, 2010
Updated April 2011
@author: Stephen O'Hara
'''
from evaluation.action_data_sets.common.DataSource import AbstractActionData
import os
import pyvision as pv
import numpy
import cPickle
import glob
import proximityforest as pf
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
__author__ = 'Tim Schneider <<EMAIL>>'
__copyright__ = "Copyright 2016, Northbridge Development Konrad & Schneider GbR"
__credits__ = ["Tim Schneider", ]
__maintainer__ = "Tim Schneider"
__email__ = "<EMAIL>"
__status__ = "Development"
logger = logging.getL... |
from forum.models import Question, Answer, QuestionVote, AnswerVote
from rest_framework import serializers
class QuestionSerializer(serializers.ModelSerializer):
votes = serializers.SerializerMethodField('count_votes')
username = serializers.SerializerMethodField('get_username')
user_obj = serializers.Se... |
import asyncio
class PacketHooks:
def __init__(self, *, loop=None):
super().__init__()
self._loop = loop
self._map = dict()
def _setdefault(self, key):
return self._map.setdefault(key, (set(), set()))
def __contains__(self, key):
try:
queues, futures = ... |
import csv
import os.path
import logging
from .endpoints import DataTarget
logger = logging.getLogger(__name__)
class TextLogger(DataTarget):
def __init__(self, filename, fields, mode='a', *args, **kwargs):
super().__init__(*args, fields=fields, **kwargs)
self._filename = filename
... |
from __future__ import unicode_literals
from indico.core.db import db
from indico.core.db.sqlalchemy.attachments import AttachedItemsMixin
from indico.core.db.sqlalchemy.descriptions import DescriptionMixin, RenderMode
from indico.core.db.sqlalchemy.notes import AttachedNotesMixin
from indico.core.db.sqlalchemy.util.q... |
import warnings
from collections import deque
from functools import total_ordering
from django.db.migrations.state import ProjectState
from django.utils.datastructures import OrderedSet
from .exceptions import CircularDependencyError, NodeNotFoundError
RECURSION_DEPTH_WARNING = (
"Maximum recursion depth exceede... |
from msrest.serialization import Model
class AadMetadataObject(Model):
"""Azure Active Directory metadata object used for secured connection to
cluster.
:param type: The client authentication method.
:type type: str
:param metadata:
:type metadata: :class:`AadMetadata
<azure.servicefabri... |
from pyparsing import *
import collections
Term = collections.namedtuple('Term', 'term')
Term.__hash__ = lambda self: hash(self.term)
Term.__str__ = lambda self: str(self.term)
Term.__repr__ = Term.__str__
Triple = collections.namedtuple('Triple', 'term1 relation term2')
Triple.__str__ = lambda self: '%s %s %s' % (st... |
import requests_mock
from allauth.account.models import EmailAddress
from allauth.socialaccount.providers import registry
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.models import SocialApp
from django.conf import settings
from django.contrib.auth import get_u... |
import argparse
import os
from util import util
import torch
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.initialized = False
def initialize(self):
self.parser.add_argument('--dataroot', typ... |
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.orm import relationship, backref
import sqlalchemy.types
from sqlalchemy.types import *
from camelot.admin.entity_admin import EntityAdmin
from camelot.core.orm import Entity
from camelot.types import File
class Creator( Entity ):
"""Arkivbildar... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 20:44:11 2015
Simulations of dynamics, belief dynamics and real trajectories
@author: plim
"""
import numpy as np
from numpy.random import multivariate_normal as normal
from dynamics import *
from optimization import *
# %% ==========================================... |
import logging
from urllib.parse import urlencode
from flask_babel import gettext
from flask import Blueprint, redirect, request, session
from authlib.common.errors import AuthlibBaseError
from werkzeug.exceptions import Unauthorized, BadRequest
from aleph import settings
from aleph.core import db, url_for, cache
from... |
"""
A module for the Bernoulli distribution node
"""
import numpy as np
from .binomial import (BinomialMoments,
BinomialDistribution)
from .expfamily import ExponentialFamily
from .beta import BetaMoments
from .node import Moments
class BernoulliMoments(BinomialMoments):
"""
Class for... |
from django import forms
from .models import Candidate, Interview
class CandidateForm(forms.ModelForm):
interview = forms.ModelChoiceField(queryset=Interview.objects.all(), required=False)
class Meta:
model = Candidate
widgets = {
'comment': forms.Textarea(attrs={'cols': 100, 'ro... |
from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
author = 'Your name here'
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'voiture_autonome_assurance'
players_per_group = None
num_rou... |
#
# basic_psbt.py - yet another PSBT parser/serializer but used only for test cases.
#
# - history: taken from coldcard-firmware/testing/psbt.py
# - trying to minimize electrum code in here, and generally, dependancies.
#
import io
import struct
from base64 import b64decode
from binascii import a2b_hex, b2a_hex
from st... |
import test # get ../lib/ in path
import gglobals
import time, gtk
gglobals.gourmetdir = '/tmp/'
gglobals.dbargs['file'] = '/tmp/recipes.db'
VERBOSE = True
import GourmetRecipeManager
from reccard import add_with_undo
def assert_with_message (callable,
description):
try:
assert(c... |
from types import NoneType
from rogerthat.dal.messaging import get_service_user_inbox_keys_query
from rogerthat.models import Message
from rogerthat.rpc import users
from google.appengine.ext import deferred, db
from mcfw.rpc import arguments, returns
@returns(NoneType)
@arguments(service_identity_user=users.User, h... |
import zmq
import threading
import json
import time
from collections import defaultdict
from .log import getLogger
moduleLogger = getLogger(__name__)
_log = moduleLogger
class HandlerNotFound(Exception):
pass
class InvalidArguements(Exception):
pass
class RPCError(Exception):
pass
class Message(object):
def __in... |
import unittest
import wios
class TestFlatten(unittest.TestCase):
def test_flatten_not_dict(self):
self.assertEqual({}, wios.flatten('some string'))
def test_flatten_single_level(self):
self.assertEqual({'a': 1, 'b': 2, 'c': 3}, wios.flatten({'a': 1, 'b': 2, 'c': 3}))
def test_flatten_t... |
from __future__ import (absolute_import, division, print_function)
import numpy as np
from scipy import constants
from mantid.kernel import CompositeValidator, Direction, FloatBoundedValidator
from mantid.api import AlgorithmFactory, CommonBinsValidator, HistogramValidator, MatrixWorkspaceProperty, PythonAlgorithm
fro... |
#!/usr/bin/env python
from common import *
import requests
import os
import os.path
from xml.etree.ElementTree import Element, SubElement, tostring, fromstring
# Delete table if it exists
request = requests.get(hbaseBaseURL + "/" + hbaseTableName + "/schema", headers={"Accept" : "application/json"})
if issuccessful(r... |
import json
import operator
from functools import reduce
from django.core.exceptions import PermissionDenied
from django.db.models import ProtectedError, Q
from django.forms.models import modelform_factory
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.functional impor... |
"""Markdown support"""
# pylint: disable=W0702
# pylint: disable=W0703
import os.path
import mistune
from pygments import highlight
from pygments.lexers import get_lexer_by_name, get_lexer_for_mimetype
from pygments.formatters import HtmlFormatter
from utils.fileutils import getMagicMimeFromBuffer
from .settings impo... |
import unittest
import jpype
import logging
import os.path
import pkgutil
import sys
def suite() :
loader = unittest.defaultTestLoader
if len(sys.argv) > 1:
names = sys.argv[1:]
test_suite = loader.loadTestsFromNames(names)
else:
import jpypetest
pkgpath = os... |
from django.db import models
class DegreeManager(models.Manager):
def addDegree(self, request):
""" add new degree programme """
D = Degree(
degreeCode=request['degreeCode'],
degreeName=request['degreeName'],
degreeType=request['degreeType'],
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the log2timeline (l2t) CSV output module."""
import io
import unittest
from dfvfs.path import fake_path_spec
from plaso.containers import events
from plaso.lib import definitions
from plaso.output import l2t_csv
from tests.containers import test_lib as con... |
from __future__ import unicode_literals
import six
import time
from colorama import init as colorama_init, Fore, Style
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from temba.a... |
"""
Email backend that writes messages to console instead of sending them.
"""
import sys
import threading
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
self.stream = kwargs.pop('stream', sys.stdout)
self._loc... |
"""
Automated test to reproduce the results of Mihalcea and Tarau (2004).
Mihalcea and Tarau (2004) introduces the TextRank summarization algorithm.
As a validation of the gensim implementation we reproduced its results
in this test.
"""
import os.path
import logging
import unittest
from gensim import utils
from ge... |
import inspect
from collections import namedtuple
CallstackEntry = namedtuple('CallstackEntry', ('index', 'module', 'name'))
def _default_formatter(callstack_entries):
max_module_name_length = max(len(callstack_entry.module)
for callstack_entry in callstack_entries)
fmt = '{... |
import pexpect
from ftfy import fix_text
import re
def get_repl(language, repl_def):
if repl_def.get("cmd") is not None:
return Repl(repl_def.pop("cmd"), **repl_def)
raise ReplStartError("No worksheet REPL found for " + language)
class ReplResult():
def __init__(self, text="",
i... |
import traceback
from json import dumps
class Application(object):
def __init__(self):
self.buffer = []
self.users = set()
def __call__(self, environ, start_response):
socket = environ.get('websocket')
if socket is not None:
self.handle_websocket(socket)
e... |
"""
This script stress tests deadlock detection.
Usage: rocksdb_deadlock_stress.py user host port db_name table_name
num_iters num_threads
"""
import hashlib
import MySQLdb
from MySQLdb.constants import ER
import os
import random
import signal
import sys
import threading
import time
import string
import traceba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.