code stringlengths 1 199k |
|---|
"""
Sysconfig - files in ``/etc/sysconfig/``
========================================
This is a collection of parsers that all deal with the system's configuration
files under the ``/etc/sysconfig/`` folder. Parsers included in this module
are:
ChronydSysconfig - file ``/etc/sysconfig/chronyd``
-----------------------... |
"""Utility library for displaying arbitrary content on a machine."""
import jinja2
import tempfile
from common import pattern
from utils import app
class Display(pattern.Closable):
"""Class for displaying arbitrary content on a machine.
The implementation assumes Chrome browser is available on given machine and
u... |
"""Pre-commit script for Oppia.
This script lints Python and JavaScript code, and prints a
list of lint errors to the terminal. If the directory path is passed,
it will lint all Python and JavaScript files in that directory; otherwise,
it will only lint files that have been touched in this commit.
This script ignores a... |
from locust import HttpLocust, TaskSet, task
class WebsiteTasks(TaskSet):
@task
def page1(self):
self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/")
@task
def page2(self):
self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/")
@task
def page3(... |
"""
Fitmarket
Mali broj ljudi - donori - dijele dnevna mjerenja svoje težine. Iz dnevne težine jednog donora određujemo vrijednosti dviju dionica: - dionica X ima vrijednost koja odgovara težini donora na taj dan. - inverzna dionica ~X ima vrijednost (150 kg - X). Primjetimo da: - kako X raste, ~X pada. - X... |
import json
import django
import urllib3
if __name__ == '__main__':
django.setup()
from infrastructure.models import Server, CustomField
from resourcehandlers.aws.models import AWSHandler
from common.methods import set_progress
from django.core.serializers.json import DjangoJSONEncoder
def fetch_arns_for_findings(i... |
from flask_restful import Resource
from flask import request, g
from v.tools.exception import ExceptionRest
from v.tools.v import processing_rest_exception, processing_rest_success, \
type_of_insert_rest, type_of_update_rest
from v.tools.validate import validate_rest
from v.buy.model.pendingMdl import PendingMdl
cl... |
import os
import time
import yaml
import random
import argparse
from rackattack.physical import pikapatch
from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)}
rangesProbabilities = intervalRanges.keys()
rangesProbabili... |
import datetime
class FakeHeatTemplateManager(object):
def __init__(self):
self.templates = {
1: 'Dummy description #1.',
3: 'Dummy description #3.',
4: 'Dummy description #4.',
6: 'Dummy description #6.'}
def get_description(self, template_id):
re... |
import sqlalchemy as sa
from ibis.sql.alchemy import unary, varargs, fixed_arity
import ibis.sql.alchemy as alch
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
import ibis.expr.types as ir
import ibis.common as com
_operation_registry = alch._operation_registry.copy()
def _cast(t, expr):
# It's... |
from google.appengine.ext import ndb
class Tirage(ndb.Model):
nomtirage = ndb.StringProperty()
datecreation = ndb.DateTimeProperty(auto_now_add=True) |
import sys
import unittest
from string import ascii_letters
from random import randint, choice
import logging
from influxgraph.templates import parse_influxdb_graphite_templates
from influxgraph.utils import parse_series as parse_py_series
try:
from influxgraph.ext.nodetrie import Node
from influxgraph.ext.temp... |
from openprocurement.auctions.core.utils import (
apply_patch,
context_unpack,
get_now,
json_view,
opresource,
save_auction,
)
from openprocurement.auctions.core.validation import (
validate_lot_data,
validate_patch_lot_data,
)
from openprocurement.auctions.core.views.mixins import Aucti... |
import sys
from cool_commits import info, find
if __name__ == '__main__':
command = sys.argv[1]
if command == 'find':
print(*find(sys.argv[2]))
elif command == 'info':
for info_text in info(sys.argv[2]):
print('='*60)
print(info_text)
print('='*60)
else:
... |
extensions = dict(
required_params=[], # empty to override defaults in gen_defaults
validate_required_params="""
if (is.null(model_key) && is.null(path)) stop("argument 'model_key' or 'path' must be provided")
""",
set_required_params="",
)
doc = dict(
preamble="""
Imports a generic model into H2O. Suc... |
"""
TOKEN-BASED AUTH MIDDLEWARE
This WSGI component:
* Verifies that incoming client requests have valid tokens by validating
tokens with the auth service.
* Rejects unauthenticated requests UNLESS it is in 'delay_auth_decision'
mode, which means the final decision is delegated to the downstream WSGI
component (u... |
"""ThreatConnect TI Email"""
from typing import TYPE_CHECKING
from tcex.api.tc.v2.threat_intelligence.mappings.group.group import Group
if TYPE_CHECKING:
# first-party
from tcex.api.tc.v2.threat_intelligence.threat_intelligence import ThreatIntelligence
class Tactic(Group):
"""Unique API calls for Tactic AP... |
import os
PUPPETDB_HOST = 'localhost'
PUPPETDB_PORT = 8080
PUPPETDB_SSL_VERIFY = True
PUPPETDB_KEY = None
PUPPETDB_CERT = None
PUPPETDB_TIMEOUT = 20
SECRET_KEY = os.urandom(24)
DEV_LISTEN_HOST = '127.0.0.1'
DEV_LISTEN_PORT = 5000
DEV_COFFEE_LOCATION = 'coffee'
UNRESPONSIVE_HOURS = 2
ENABLE_QUERY = True
LOCALISE_TIMESTA... |
from unittest import TestCase
from django.conf import settings
from polycommon.options.exceptions import OptionException
from polycommon.options.feature import Feature
from polycommon.options.option import NAMESPACE_DB_OPTION_MARKER, OptionStores
class DummyFeature(Feature):
pass
class TestFeature(TestCase):
de... |
import argparse
from aria_cli import commands as aria
from aria_cli.config import argument_utils
from argcomplete import completers
yaml_files_completer = completers.FilesCompleter(['*.yml', '*.yaml'])
archive_files_completer = completers.FilesCompleter(
['*.zip', '*.tar', '*.tar.gz', '*.tar.bz2'])
FORMAT_INPUT_AS_... |
"""
decorstate
~~~~~~~~~~
Simple "state machines" with Python decorators.
:copyright: (c) 2015-2017 Andrew Hawker
:license: Apache 2.0, see LICENSE for more details.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='decorstate',
v... |
"""Unittests for ofstats.py.
"""
import struct
import unittest2
from openfaucet import buffer
from openfaucet import ofaction
from openfaucet import ofmatch
from openfaucet import ofstats
class TestDescriptionStats(unittest2.TestCase):
def setUp(self):
self.buf = buffer.ReceiveBuffer()
self.mfr_desc... |
"""Support for Streamlabs Water Monitor Usage."""
from datetime import timedelta
from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN
from homeassistant.const import VOLUME_GALLONS
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
DEPENDENCIES = ["s... |
"""File containing a Windows Registry plugin to parse the AMCache.hve file."""
from __future__ import unicode_literals
import pyregf
from dfdatetime import filetime
from dfdatetime import posix_time
from dfwinreg import definitions as dfwinreg_definitions
from plaso.containers import events
from plaso.containers import... |
import logging
from cliff.lister import Lister
from service_registry_cli.utils import BaseListCommand, get_client
class ListCommand(BaseListCommand, Lister):
"""
Return a list of the configuration values.
"""
log = logging.getLogger(__name__)
def get_parser(self, prog_name):
parser = super(L... |
import functools
import inspect
import itertools
import os
import unittest
import warnings
from .actions import ReadyToTest
def slim_formatwarning(msg, *args, **kwargs):
return 'Warning: ' + str(msg) + os.linesep
warnings.formatwarning = slim_formatwarning
def _normalize_ld(launch_description_fn):
# A launch de... |
from __future__ import print_function
import os
import re
import random
import argparse
from grammar import Grammar
from svg_tags import _SVG_TYPES
from html_tags import _HTML_TYPES
_N_MAIN_LINES = 1000
_N_EVENTHANDLER_LINES = 500
_N_ADDITIONAL_HTMLVARS = 5
def generate_html_elements(ctx, n):
for i in range(n):
... |
import random
import glob
from os import path
import biohex
import math
import traceback
class locals():
class distanceLookup():
RING_CACHE = 0
BIT_LISTER = 1
try:
# load up bit graphic asset names
bitList = []
for file in glob.glob("biohex/bitGraphics/*.png"):
bitList.append(pat... |
from unittest.mock import patch
from unittest.mock import MagicMock
from django.test import override_settings
from django.test import TestCase
from django.conf import settings
from orchestra.google_apps.convenience import _get_image_mimetype
from orchestra.google_apps.convenience import create_document_from_template
fr... |
"""
Linux kernel system control from Python.
""" |
import json
class Client():
def __init__(self, clientHostName, clientPort, channel):
self.clientHostName = clientHostName
self.clientPort = clientPort
self.clientType = self.getClientType()
self.channel = channel
# TO DO implement this method properly
def getClientType(self):... |
"""Queue definitions.
This module defines the queues where a worker may look for work.
"""
from grr_response_core.lib import rdfvalue
WORKER_LIST = list(map(rdfvalue.RDFURN, ["CA", "W", "E", "F", "H", "S"]))
ENROLLMENT = rdfvalue.RDFURN("E")
FLOWS = rdfvalue.RDFURN("F")
HUNTS = rdfvalue.RDFURN("H")
STATS = rdfvalue.RDF... |
"""Concordance Checking."""
import logging
import os
import functools
from sklearn.cluster import MiniBatchKMeans
from scipy.stats import ks_2samp
import numpy as np
import pandas as pd
from submission_criteria import common
def has_concordance(P1, P2, P3, c1, c2, c3, threshold=0.12):
"""Checks that the clustered s... |
from lxml import etree
from lxml.builder import E
from jnpr.junos.cfg import Resource
from jnpr.junos import jxml as JXML
from jnpr.junos.cfg.srx.shared_ab_addr import SharedAddrBookAddr
from jnpr.junos.cfg.srx.shared_ab_set import SharedAddrBookSet
class SharedAddrBook(Resource):
"""
[edit security address-boo... |
import socket
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCase):
""" VXLAN Test Cas... |
import time
from pymongo import MongoClient
from datetime import datetime, timedelta
import json
from bson import Binary, Code
from bson.json_util import dumps
client = MongoClient('localhost', 27017)
db = client['election-2016']
def dumpData(yesterdayStr):
collectionName = 't' + yesterdayStr
cursor = db[collec... |
"""Cinder OS API WSGI application."""
import sys
import warnings
from jacket.objects import storage
warnings.simplefilter('once', DeprecationWarning)
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import wsgi
from jacket.storage import i18n
i18n.enable_lazy()
from jacket.common.storag... |
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n")
print("a command ... |
r"""Training an pixel_cnn model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import time
from absl import app
from absl import flags
import tensorflow.compat.v1 as tf
from genomics_ood.images_ood import pixel_cnn
from genomics_oo... |
import itertools
from ceilometer.alarm import evaluator
from ceilometer.i18n import _
from ceilometer.openstack.common import log
LOG = log.getLogger(__name__)
COMPARATORS = {'and': all, 'or': any}
class CombinationEvaluator(evaluator.Evaluator):
def _get_alarm_state(self, alarm_id):
try:
alarm ... |
import os
def get_secret():
if os.path.exists("/etc/tower/SECRET_KEY"):
return open('/etc/tower/SECRET_KEY', 'rb').read().strip()
ADMINS = ()
STATIC_ROOT = '/var/lib/awx/public/static'
PROJECTS_ROOT = '/var/lib/awx/projects'
AWX_ANSIBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/awx_ansible_collections'
JOBOU... |
"""The Autoregressive distribution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.ops.distributions import distribution as distribution_lib
from tensorflow.python.ops.d... |
__revision__ = "src/engine/SCons/Tool/MSCommon/vc.py bee7caf9defd6e108fc2998a2520ddb36a967691 2019-12-17 02:07:09 bdeegan"
__doc__ = """Module for Visual C/C++ detection and configuration.
"""
import SCons.compat
import SCons.Util
import subprocess
import os
import platform
import sys
from string import digits as strin... |
from zope.interface import classImplements
from pyramid.config import Configurator
from clld.interfaces import ILanguage, IMapMarker, IValueSet, IValue
from clld.web.app import MapMarker
from clld.db.models.common import Parameter_files
from tsammalex import models
from tsammalex.interfaces import IEcoregion, IImage
cl... |
from hashlib import sha256
from .etl import ETL
from kombu.mixins import ConsumerMixin
from kombu import Connection
import traceback
import Queue
import json
import time
import pytz
from datetime import datetime
from tzlocal import get_localzone
import socket
import logging
import os
class KnownHosts(object):
HOST_... |
from nova.api.openstack.api_version_request \
import MAX_IMAGE_META_PROXY_API_VERSION
from nova.api.openstack.api_version_request \
import MAX_PROXY_API_SUPPORT_VERSION
from nova.api.openstack.api_version_request \
import MIN_WITHOUT_IMAGE_META_PROXY_API_VERSION
from nova.api.openstack.api_version_request \... |
'''
Import command for Winthrop team's spreadsheet. It can be invoked using::
python manage.py import_nysql [--justsammel] /path/to/csv
The ``--justsammel`` flag skips import of records to avoid
reproducing duplicates, but rebuilds the ``is_sammelband`` flag set and
produces an output list.
The expect behavior is d... |
import base64
from cloudify.state import ctx_parameters as inputs
from cloudify.manager import get_rest_client
client = get_rest_client()
client.secrets.create(
'kubernetes_token',
base64.b64decode(inputs['kube_token']),
update_if_exists=True) |
from functools import wraps
from flask import abort
from flask.ext.login import current_user
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_admin():
abort(403)
return f(*args, **kwargs)
return decorated_function |
import sys
from modules.ClipRead import *
import os
if __name__ == '__main__':
from optparse import OptionParser
usage = "usage: ./%prog [options] data_file"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose", action = 'store_true', default = False, help="verbose output")
parser... |
import eventlet
from oslo_config import cfg
from oslo_config import types
from oslo_log import log as logging
from oslo_utils import excutils
import six
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder.objects import fields
from cinder.volume import driver
from cinder.volume.drivers.del... |
"""Tests for cond_v2."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.eager import context
from tensorflow.python.eager import function
from tensorflow.python.framework import constant_... |
class ProxyPoolError(Exception):
"""proxypool error base"""
class CrawlerRuleImplementionError(ProxyPoolError):
def __str__(self):
return 'crawler rule required "start_url", "ip_xpath" and "port_xpath".'
class CrawlerRuleBaseInstantiateError(ProxyPoolError):
def __str__(self):
return "crawle... |
"""Accesses the google.monitoring.v3 MetricService API."""
import functools
import pkg_resources
import warnings
from google.oauth2 import service_account
import google.api_core.client_options
import google.api_core.gapic_v1.client_info
import google.api_core.gapic_v1.config
import google.api_core.gapic_v1.method
impor... |
import copy
import logging
from strategy import Strategy
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger(__name__)
class PersistenceStrategy(Strategy):
def __init__(self, strategy):
self.__dict__ = copy.deepcopy(strategy.__dict__)
def compatible(self, event):
if event is None:
... |
import abc
import webob.exc
from neutron.api import extensions
from neutron.api.v2 import base
from neutron.api.v2 import resource
from neutron.common import constants
from neutron.common import exceptions
from neutron.common import rpc as n_rpc
from neutron.extensions import agent
from neutron.i18n import _LE
from neu... |
class CMEModule:
name = 'runasppl'
description = "Check if the registry value RunAsPPL is set or not"
supported_protocols = ['smb']
opsec_safe = True
multiple_hosts = True
def options(self, context, module_options):
'''
'''
def on_admin_login(self, context, connection):
... |
from functools import reduce
def vartype(var):
if var.is_discrete:
return 1
elif var.is_continuous:
return 2
elif var.is_string:
return 3
else:
return 0
def progress_bar_milestones(count, iterations=100):
return set([int(i*count/float(iterations)) for i in range(itera... |
"""
@package mi.instrument.seabird.sbe16plus_v2.test.test_driver
@file mi/instrument/seabird/sbe16plus_v2/test/test_driver.py
@author David Everett
@brief Test cases for InstrumentDriver
USAGE:
Make tests verbose and provide stdout
* From the IDK
$ bin/test_driver
$ bin/test_driver -u
$ bin/tes... |
import my_path
import time
import zmq.green as zmq
import pprint
import algobroker
import msgpack
class Dispatcher(algobroker.Broker):
def __init__(self):
algobroker.Broker.__init__(self, "dispatcher")
# send work
self.sms_sender = self.socket(zmq.PUSH)
self.sms_sender.connect(algobr... |
import libsedml
def create_nested_task(file_name):
doc = libsedml.SedDocument(1, 4)
# create simulation
sim = doc.createSteadyState()
sim.setId("steady1")
# need to set the correct KISAO Term
alg = sim.createAlgorithm()
alg.setKisaoID("KISAO:0000282")
# create model
model = doc.creat... |
import os
import sys
import unittest
from unittest.mock import patch
import mkdocs
from mkdocs.config import config_options
from mkdocs.config.base import Config
from mkdocs.tests.base import tempdir
class OptionallyRequiredTest(unittest.TestCase):
def test_empty(self):
option = config_options.OptionallyReq... |
from io import StringIO
from coaster.logger import RepeatValueIndicator, filtered_value, pprint_with_indent
def test_filtered_value():
"""Test for filtered values."""
# Doesn't touch normal key/value pairs
assert filtered_value('normal', 'value') == 'value'
assert filtered_value('also_normal', 123) == 1... |
"""
IMPORTANT - COLOUR SUPPORT IS CURRENTLY EXTREMELY EXPERIMENTAL. THE API MAY CHANGE, AND NO DEFAULT
WIDGETS CURRENTLY TAKE ADVANTAGE OF THEME SUPPORT AT ALL.
"""
import curses
from . import global_options
def disable_color():
global_options.DISABLE_ALL_COLORS = True
def enable_color():
global_options.DISABL... |
"""
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.
Written (W) 2013 Heiko Strathmann
"""
from kameleon_mcmc.distribution.Gaussi... |
__author__ = "Konstantin Osipov <kostja.osipov@gmail.com>"
import socket
import yaml
import sys
import re
from tarantool_connection import TarantoolConnection
ADMIN_SEPARATOR = '\n'
class AdminConnection(TarantoolConnection):
def execute_no_reconnect(self, command, silent):
if not command:
retur... |
import setuptools
import os
with open("src/lsi/__init__.py") as f:
exec(f.read())
setuptools.setup(
name='lsi',
version=__version__,
author="Narrative Science",
author_email="anelson@narrativescience.com",
url="https://github.com/NarrativeScience/lsi",
package_dir={'': 'src'},
packages=s... |
from unittest import mock
import pytest
import stripe
from model_mommy import mommy
from rest_framework.reverse import reverse
from restframework_stripe import models
from restframework_stripe.test import get_mock_resource
@mock.patch("stripe.Customer.save")
@mock.patch("stripe.Customer.retrieve")
@pytest.mark.django_d... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import time
from barf import BARF
from barf.arch import ARCH_ARM
from barf.arch import ARCH_X86
from barf.arch import ARCH_X86_MODE_32
from barf.arch import ARCH_X86_MODE_64
from barf.core.symbols import load_symbols
from barf.utils... |
"""Primary container for radio interferometer calibration solutions."""
import copy
import numpy as np
import threading
import warnings
from ..uvbase import UVBase
from .. import parameter as uvp
from .. import telescopes as uvtel
from .. import utils as uvutils
from ..uvdata import UVData
__all__ = ["UVCal"]
class UVC... |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AuthConfig(AppConfig):
name = 'esia_auth'
verbose_name = _('Esia META') |
import os, unicodedata
from django.utils.translation import ugettext_lazy as _
from django.core.files.storage import FileSystemStorage
from django.db.models.fields.files import FileField
from django.core.files.storage import default_storage
from django.conf import settings
from django.utils.safestring import mark_safe
... |
class AbstractSearcher(object):
def setOptions(self, **kwargs):
for k in kwargs:
setattr(self, k, kwargs[k])
return self
def fileExists(self, mibname, mtime, rebuild=False):
raise NotImplementedError() |
"""
Test rest_framework_json_api's utils functions.
"""
from rest_framework_json_api import utils
from ..serializers import EntrySerializer
from ..tests import TestBase
class GetRelatedResourceTests(TestBase):
"""
Ensure the `get_related_resource_type` function returns correct types.
"""
def test_revers... |
import socket
import os
import json
import my_traceroute
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '130.56.253.43'
port = 5201 # Change port (must enable security settigns of server)
s.bind((host,port))
s.listen(5)
MAX_HOPS = 30 # max hops for traceroute
while True:
c, addr = s.accept() #accept i... |
from datetime import timedelta
from propeller.cookie import Cookie
from propeller.options import Options
from propeller.template import Template
from propeller.util.dict import MultiDict
from urllib import quote
import httplib
import propeller
class Response(object):
def __init__(self, body='', status_code=200, con... |
import imp
import os.path
import pkgutil
import six
import unittest
import streamlink.plugins
from streamlink import Streamlink
class PluginTestMeta(type):
def __new__(mcs, name, bases, dict):
plugin_path = os.path.dirname(streamlink.plugins.__file__)
plugins = []
for loader, pname, ispkg in... |
"""Shortest game.
When we play games, we always bet in one of two ways in each game:
- betting one chip
- betting all-in
Wins are paid equal to the wager, so if we bet C chips and wins,
we get 2C chips back.
Suppose yesterday was a lucky day for us, we won every game we played.
Starting with 1 chip and leaving the game... |
import hashlib
import inspect
import json
import logging
import re
from xml.sax.saxutils import escape as xml_escape
import webob
from wsgiservice import xmlserializer
from wsgiservice.decorators import mount
from wsgiservice.exceptions import (MultiValidationException, ResponseException,
... |
try:
import json
except ImportError:
import simplejson as json
from UserList import UserList
class Resource(object):
"""Object wrapper for resources.
Provides an object interface to resources returned by the Soundcloud API.
"""
def __init__(self, obj):
self.obj = obj
def __getstate__... |
import unittest
import unittest.mock as mock
import bson
import pymongo.collection
import database.client
import batch_analysis.task_manager as manager
import batch_analysis.tasks.import_dataset_task as import_dataset_task
import batch_analysis.tasks.generate_dataset_task as generate_dataset_task
import batch_analysis.... |
import telnetlib
import time
import sys
import socket
TEL_PORT = 23
TEL_TO = 3
def write_cmd(cmd, conn):
cmd = cmd.rstrip()
conn.write(cmd + '\n')
time.sleep(1)
return conn.read_very_eager()
def telnet_conn(ip, port, timeout):
try:
conn = telnetlib.Telnet(ip, port, timeout)
except socket... |
import json
import sys
if sys.version_info < (3, 0, 0):
from codecs import open
def build_index(posts, path):
index = []
for post in posts:
index.append({
"episode": post["episode"],
"date": post["date"],
"title": post["title"],
"subtitle": post["subtitle"],
"content": post["content"]
})
with ope... |
__author__ = 'Frank Sehnke, sehnke@in.tum.de'
from environment import Environment
class GraphicalEnvironment(Environment):
""" Special type of environment that has graphical output and therefore needs a renderer.
"""
def __init__(self):
self.renderInterface = None
def setRenderInterface(self, re... |
import copy
import sys
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast
def explain_c_declaration(c_decl, expand_struct=False, expand_typedef=False):
""" Parses the declaration in c_decl and returns a text
explanation as a string.
The last external node of the string is used, to al... |
from glfwpy.glfw import *
import sys
import numpy as np
from OpenGL.GL import *
from OpenGL.arrays import ArrayDatatype
import ctypes
vertex = """
in vec3 vin_position;
in vec3 vin_color;
uniform vec3 vu_displacement[2];
out vec3 vout_color;
void main(void)
{
vout_color = vin_color;
gl_Position = vec4(vin_posit... |
from typing import Callable, List, Dict, Optional
import numpy as np
from typeguard import check_argument_types
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.decoders.beam_search_decoder import (BeamSearchDecoder,
SearchStepOutput)
from neur... |
import fileinput
for line in fileinput.input():
_line = line.strip()
# super dumb...
if _line.startswith('//') or _line.startswith('/*') or _line.startswith('*') or _line.startswith('*/'):
continue
print line.rstrip() |
"""
-- Policy Network for decision making [more general]
"""
from nmt_uni import *
from layers import _p
import os
import time, datetime
import cPickle as pkl
TINY = 1e-7
PI = numpy.pi
E = numpy.e
A = 0.2
B = 1
class Controller(object):
def __init__(self, trng,
options,
... |
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import pandas as pd
import os
import yaml
import astropy.io.votable as votable
import astropy.units as u
import urllib.request, urllib.error, urllib.parse
import xml.etree.ElementTree... |
from django.conf.urls.defaults import *
urlpatterns = patterns('transaction.views',
(r'^create/(?P<pid>.*)$', 'create'),
(r'^edit/(?P<tid>.*)$', 'edit'),
) |
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
testinfo = "s, t 1, s, t 2, s, t 3, s, t 4.1, s, t 4.2, s, q"
tags = "FadeIn, FadeOut, ColorLayer"
import pyglet
from pyglet.gl import *
import cocos
from cocos.director import director
from cocos.actions import *
from cocos.layer im... |
"""
Implement the declarative descriptor.
"""
from __future__ import absolute_import
import warnings
import weakref
from .events import _DescriptorEvent, _KeywordEvent
from .utils import descriptor__get__, hybridmethod
from ...utils import ReferenceError
from ...exc import CauldronException, CauldronWarning
__all__ = [... |
__author__ = 'flaviocaetano'
from django.utils.translation import ugettext_lazy as _
from admin_tools.dashboard import modules
import psutil
class PelicanAdmin(modules.DashboardModule):
"""Dashboard module for Pelican service administration.
"""
title = 'Pelican Admin'
template = 'pelican_admin.html'
... |
import os, sys
sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python')
import slpsns, BGF3
import xml.etree.ElementTree as ET
cx = {}
class TopModel:
def getData(self, id):
if id in self.data.keys():
return self.data[id]
else:
return None
def who(self):
return self.__class__.__name__
def parse... |
"""
test_sphinx
~~~~~~~~~~~
General Sphinx test and check output.
"""
import sys
import pytest
import sphinx
from ipypublish.sphinx.tests import get_test_source_dir
from ipypublish.tests.utils import HTML2JSONParser
@pytest.mark.sphinx(buildername="html", srcdir=get_test_source_dir("bibgloss_basic"))
def te... |
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
import os
from .common import * # noqa
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
SECRET_KEY = env("DJANGO_SECRET_KEY", default='CHANGEME!!!... |
"""
sentry.models.event
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import logging
from django.db import models
from django.utils import timezone
from django.utils.datastructures import SortedDict
from django.utils.tran... |
import pytest
from porcupy.compiler import compile as compile_
def test_consts():
assert compile_('X = 4') == ''
assert compile_('X = 4; y = X') == 'p1z 4'
assert compile_('X = 4; Y = X; z = Y') == 'p1z 4'
with pytest.raises(ValueError) as exc_info:
compile_('X = 4; X = 5')
assert 'cannot re... |
import os
from pvfactors.geometry.timeseries import TsPointCoords, TsLineCoords
from pvfactors.geometry.pvrow import TsPVRow
from pvfactors.geometry.pvground import TsGround, TsGroundElement
import pandas as pd
import numpy as np
from pvfactors.geometry.pvrow import PVRow
from pvfactors.geometry.base import \
BaseS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.