content stringlengths 4 20k |
|---|
'''
Created on Nov 30, 2014
@author: gearsad
'''
from scene.RoverBot import RoverBot
class BotManager(object):
'''
The overall controller for all the bots in the environment.
'''
def __init__(self):
'''
Create the bots structure.
'''
self.__botsLCM = []
... |
#This script tests out the horseshoe prior for variable selection based on Piironen and Vehtari (2017).
import scipy.io as spio
import numpy as np
import pystan
from scipy.stats import cauchy, norm
from matplotlib import pyplot as plt
import csv
#Load the data
mat = spio.loadmat('colon.mat', squeeze_me=True) #or 'p... |
#Solution from: http://www.cnblogs.com/zuoyuan/p/3785421.html
#use "count" to check whether there's a match
#one dictionary should be enough for this problem
class Solution:
# @return a string
def minWindow(self, S, T):
maxlength = 10 ** 10
result = ""
start = 0
count = len(T)
... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=1>
# Reading outputs from E+
# <codecell>
# some initial set up
# if you have not installed epp, and only downloaded it
# you will need the following lines
import sys
# pathnameto_eppy = 'c:/eppy'
pathnameto_eppy = '../'
sys.path.append(pathnam... |
from __future__ import division
import textwrap
from .. import qtall as qt4
from .. import setting
from .. import utils
from .. import document
from . import widget
from . import controlgraph
def _(text, disambiguation=None, context='Graph'):
"""Translate text."""
return qt4.QCoreApplication.translate(contex... |
from hamcrest import assert_that, equal_to, has_item
from rip import error_types
from tests import request_factory
from tests.integration_tests.person_base_test_case import \
PersonResourceBaseTestCase
from tests.integration_tests.person_resource import PersonResource, PersonEntity
class PutCrudResourceIntegrati... |
import hashlib
from google.appengine.api import users
from google.appengine.ext.ndb import Cursor, Model
import webapp2
from webapp2_extras import json
__author__ = 'ilewis'
DEFAULT_LIMIT = 100
QUERY_PARAM_LIMIT = 'maxResults'
QUERY_PARAM_PAGE_TOKEN = 'pageToken'
QUERY_PARAM_TERSE = 'deep'
class RestApp(webapp2.WS... |
"""Transciption components
The main base class which is responsible for performing transcription is
:class:`Transcriber`.
"""
import asyncio
import base64
from contextlib import contextmanager
import json
import os
import websockets
try:
import pocketsphinx
except ImportError:
# This is a workaround for doc ... |
from bigdl.util.common import *
from zoo.common.utils import callZooFunc
from bigdl.dataset.dataset import DataSet
from pyspark.serializers import CloudPickleSerializer
import sys
import math
import warnings
if sys.version >= '3':
long = int
unicode = str
class Relation(object):
"""
It represents the... |
import json
from . import db
SESSION_FORM = {
"title": {"include": 1, "require": 1},
"subtitle": {"include": 0, "require": 0},
"short_abstract": {"include": 1, "require": 0},
"long_abstract": {"include": 0, "require": 0},
"comments": {"include": 1, "require": 0},
"track": {"include": 0, "requi... |
# coding: utf-8
from tests.shared import assertException, getEmptyCol
def test_basic():
deck = getEmptyCol()
# we start with a standard deck
assert len(deck.decks.decks) == 1
# it should have an id of 1
assert deck.decks.name(1)
# create a new deck
parentId = deck.decks.id("new deck")
... |
import logging
import webapp2
from google.appengine.ext.webapp import util
import json as simplejson
from model import get_current_youtify_user_model
from model import get_display_name_for_youtify_user_model
from model import get_playlist_struct_from_playlist_model
from model import get_playlist_structs_by_id
from mode... |
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
max_num = -1e9
tag = False
for i in range(1, len(nums)+1):
if nums[-i] < max_num:
tag= ... |
import kid_readout.equipment.lockin_controller
import fts_motor
from scipy.constants import c
import numpy as np
import time
li = kid_readout.equipment.lockin_controller.lockinController(serial_port='COM4')
motor = fts_motor.FtsMotorController(port='COM5')
motor.go_to_position(0)
counts_per_mm = 2000.0
freq_resolu... |
import os
import time
import warnings
from asgiref.local import Local
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.db import connections, router
from django.db.utils import ConnectionRouter
from django.dispatch import ... |
import numpy as np
import rospy
from nav_msgs.msg import Odometry
class OdometryHandler(object):
"""
Handler for ROS topics of type: nav_msgs/Odometry
Args:
topic_name: Name of ROS topic to be subscribed
buffer_size: Variable buffer, depend on frame rate of topic, default: 500
queu... |
#!/usr/bin/python
"""
Convert a set of junction reads into exon reads.
There are several choices for how to convert a junction read -
see command line options below
Copyright (C) 2010
University of Southern California,
Philip J. Uren,
Jin H. Park,
Andrew D. Smith
Authors: Philip J. Uren, Jin H. P... |
"""
Copyright and licenes of perl library which inspired this python library:
Copyright (C) 2003 Peter Blaiklock, <EMAIL> This module
may be distributed under the same terms as Perl itself.
Source code available from: http://restrictionmapper.org/code.html
# DESCRIPTION
PyRemoteRestMap.digest.Digest(html) parses... |
"""Test the -uacomment option."""
import re
from test_framework.test_framework import BitcoinTestFramework
from test_framework.test_node import ErrorMatch
class UacommentTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def run_test(self... |
"""
grid_objs
=========
"""
from __future__ import absolute_import
import _plotly_utils.exceptions
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
import json as _json
from _plotly_utils.optional_imports import get_module
from chart_studio import... |
#! /usr/bin/env python
import os
import sys
import pygame
import pygame.locals as pl
import random
import events
import controllers
if not pygame.font:
print 'Warning, fonts disabled'
if not pygame.mixer:
print 'Warning, sound disabled'
def create_all(evManager):
human = Man(evManager, (650, 690))
d... |
import sys
import papyon
import logging
from amsn2 import protocol
from amsn2.backend import aMSNBackendManager
from account_manager import aMSNAccount, aMSNAccountManager
from contactlist_manager import aMSNContactListManager
from conversation_manager import *
from oim_manager import *
from theme_manager import *
fro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('volunteering', '0019_auto_20140805_1240'),
]
operations = [
migrations.AlterField(
model_name='activity',
... |
import os.path
import edgedb
from edb.testbase import server as tb
class TestEdgeQLEnums(tb.QueryTestCase):
SCHEMA = os.path.join(os.path.dirname(__file__), 'schemas',
'enums.esdl')
async def test_edgeql_enums_cast_01(self):
await self.assert_query_result(
r'''... |
from family_tree.models import Relation
from family_tree.models.relation import PARTNERED, RAISED, RAISED_BY
import random
def get_first_relation_suggestion(person):
'''
Gets a relation person suggestion to be related
'''
suggestions = get_relation_suggestions(person)
if len(suggestions) == 0:
... |
def cleanLabel(s):
s = "".join(c for c in s if c.isalpha() or c == ' ')
return s.replace(' ', '_')
def loadTableHeader(targetpath, headerlines=1, cleaned=True):
"""
Returns the header of an input table
"""
f = open(targetpath, 'r')
properties = []
for i in range(0, headerlines):
... |
"""
Deployment for Mozillians in production.
Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""
import os
import random
import re
import sys
import urllib
import urllib2
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from commander.deploy import ... |
#!/usr/bin/env python
import sys, os
import fontforge
import optparse
# print 'ARGV :', sys.argv[1:]
parser = optparse.OptionParser()
parser.add_option('-w', '--woff',
dest="woff",
action="store_true",
default=False,
help='Save in WOFF for... |
__revision__ = "$Id$"
__author__ = "Nahuel Riva"
__contact__ = "<EMAIL>"
__license__ = "BSD 3-Clause"
"""
TODO:
[] Implementar los writeElf*() en la clase WriteData.
"""
import elfdatatypes
from StringIO import StringIO
from struct import pack, unpack
def ELF32_ST_BIND(i):
return i >> 4
def ELF32_ST_TYPE(i... |
"""Models of the ``django-crowdsourced-fields`` app."""
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import ugettext_lazy as _
def add_crowdsourced_method(cls, field_name, settings):
"""
Dy... |
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class App:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.procedures = []
self.subscriptions = []
self.event_handlers = {}
def run(self, url="ws://127.0.0.1:808... |
import html
from iso8601.iso8601 import UTC
from amcat.models import Article, word_len
from amcat.models import PropertyMapping
from amcat.tools import amcattest
from amcat.tools import amcates
from amcat.tools.amcattest import create_test_article, create_test_set
import datetime
import random
def _setup_highlighti... |
import gtk, gobject, cairo
from pandac.PandaModules import WindowProperties
import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject
#from direct.showbase.ShowBase import ShowBase
from direct.task.Task import Task
from pandac.PandaModules import *
from direct.distributed.PyDatagram im... |
from unittest import TestCase
import numpy
from chainer import cuda, Variable
from chainer.cuda import to_gpu
from chainer.gradient_check import assert_allclose, numerical_grad
from chainer.functions import lstm
cuda.init()
def _sigmoid(x):
return 1 / (1 + numpy.exp(-x))
class TestLSTM(TestCase):
def se... |
# -*- coding: utf-8 -*-
import teradata
import pandas as pd
class Teradata(object):
"""Teradata connection tools use teradata and pandas (for python 2.7)
"""
pooling = True
config = {
"appName": __name__ + '.Teradata',
"version": '1.0',
"runNumber": "0",
"configureLog... |
# CTCI 9.5
# Write a function to generate all permuations of a string.
import unittest
# will there be duplicates?
def gen_perms(s):
if len(s) == 0:
return set()
if len(s) == 1:
return {s}
# return gen_perms_helper(s)
return gen_perms_helper2(s)
def gen_perms_helper(s):
pe... |
from setuptools import setup, find_packages
import os
with open(os.path.join('version.txt')) as version_file:
version_from_file = version_file.read().strip()
with open('requirements.txt') as f_required:
required = f_required.read().splitlines()
with open('test_requirements.txt') as f_tests:
required_for_... |
"""
Views that handle course updates.
"""
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.decorators import method_d... |
import os.path
import sys
from argparse import ArgumentParser
from ucca.convert import from_text, to_json
from uccaapp.api import ServerAccessor
desc = """
Read input file as one line per paragraph, where paragraphs are separated by multiple newlines and an optional
<DELIMITER>.
Tokenize and upload as submitted token... |
"""
Support for functionality to have conversations with Home Assistant.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/conversation/
"""
import asyncio
import logging
import re
import warnings
import voluptuous as vol
from homeassistant import core
f... |
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""),... |
#!/usr/bin/env python
"""SensorsInterface.py: Controls the various sensors and modules on the Sensorian Shield"""
from ctypes import *
import time
import calendar
## @var lib_sensorian
# Points to the C Shared Object DLL which is used to call the Sensorian C functions
lib_sensorian = CDLL("./libsensorianplus.so")
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
GdalAlgorithm.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*************************... |
def get_residents(room):
"""Get people in room
Returns:
Array of names of the people in the room
"""
people = []
for person in room.residents:
people.append(person.get_fullname())
return people
def remove_person(person, room):
"""Removes a person from a room
Args:
... |
from autosportlabs.racecapture.views.setup.introview import IntroView
from autosportlabs.racecapture.views.setup.selectdeviceview import SelectDeviceView
from autosportlabs.racecapture.views.setup.selectconnectionview import SelectConnectionView
from autosportlabs.racecapture.views.setup.selectpresetview import SelectP... |
import sys
import os
import numpy as np
import cv2
sys.path.append('/path/to/caffe/python')
import caffe
WEIGHTS_FILE = 'open_nsfw/nsfw_model/resnet_50_1by2_nsfw.caffemodel'
DEPLOY_FILE = 'deploy_global_pooling.prototxt'
FEATURE_MAPS = 'eltwise_stage3_block2'
FC_LAYER = 'fc_nsfw'
SHORT_EDGE = 320
MOSAIC_RANGE = [5, 1... |
import sys, re
tbl = open(sys.argv[1])
OPCODE_MAX = 11
types = {
"rr": (11, "SPU_INSTR_RR", "spe_ctx_t *ctx, uint32_t rt, uint32_t ra, uint32_t rb"),
"rrr": (4, "SPU_INSTR_RRR", "spe_ctx_t *ctx, uint32_t rt, uint32_t ra, uint32_t rb, uint32_t rc"),
"ri7": (11, "SPU_INSTR_RI7", "spe_ctx_t *ctx,... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
# encoding: utf-8
# Import Python libs
from __future__ import absolute_import
import os
# Import Salt Testing libs
from integration import TMP_CONF_DIR
from salttesting import TestCase
# Import Salt libs
import salt.config
import salt.netapi
class NetapiClientTest(TestCase):
eauth_creds = {
'username':... |
import sys
#####################################
# Calculates the determinant of a 3x3 matrix
def det3(mat):
return ((mat[0][0]*mat[1][1]*mat[2][2]) + (mat[0][1]*mat[1][2]*mat[2][0]) + (mat[0][2]*mat[1][0]*mat[2][1]) - (mat[0][2]*mat[1][1]*mat[2][0]) - (mat[0][1]*mat[1][0]*mat[2][2]) - (mat[0][0]*mat[1][2]*mat[2][1]... |
from addondev import testing
import unittest
import xbmc
import os
# Testing specific imports
from codequick import search, route, storage, localized
from codequick.support import dispatcher
from codequick.listing import Listitem
# Link to search own hash params for testing
hash_params = search.Search.hash_params
c... |
import socket
import string
def acceptClient(sock):
client, address = sock.accept()
nickInfo = client.recv(1000) #assumes that NICK is the first message received
userInfo = client.recv(1000) #assumes that USER is the second message received
nick = nickInfo.split()[1]
userSplit = userInfo.split()
... |
'''
Copyright 2017, Fujitsu Network Communications, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... |
import sys
import config, util, constants
from util import emit
from declarative import ModelFactory
def main():
config.configure()
options = config.options
if options.declarative:
config.interactive = None
if options.interactive:
config.interactive = True
config.schema... |
#__author__ = 'gijspeters'
"""
This module contains a PostgreSQL connection handler and require info.
"""
import psycopg2
DB_DRIVER = 'org.postgresql.Driver'
class Config:
"""
Configurations container
"""
def __init__(self, name="upair", host="localhost", user="teammaja", passw="maja", port="5432")... |
from __future__ import division
import mock
import numpy as np
import unittest
import chainer
from chainer import backends
from chainer import testing
from chainer.testing import attr
from chainercv.links.model.fpn import BboxHead
from chainercv.links.model.fpn import FasterRCNN
from chainercv.links.model.fpn import... |
import csv
import datetime
import logging
import re
import sys
from dateutil.parser import parse
from django.db import transaction
import reversion
from medlem.models import KONTI
from medlem.models import Medlem, Lokallag, Giro
logger = logging.getLogger(__name__)
class AccessImporter(object):
# REGISTERKODE,... |
from __future__ import absolute_import
from chart_studio.api.v2 import files
from chart_studio.tests.test_plot_ly.test_api import PlotlyApiTestCase
class FilesTest(PlotlyApiTestCase):
def setUp(self):
super(FilesTest, self).setUp()
# Mock the actual api call, we don't want to do network tests he... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2013-03-19
@author: Martin H. Bramwell
'''
from OErpModel import OErpModel
OPENERP_MODULE_NAME = 'base.language.install'
class BaseLanguageInstall(OErpModel):
def __init__(self):
super(BaseLanguageInstall, self).__init__()
self.metho... |
from Hindlebook.models import Post, Category, Node, Author
from api.serializers import PostSerializer
from api.serializers.utils import get_author
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions, status, exceptions, HTTP_HEADER... |
from eventlet.timeout import Timeout
from oslo_log import log as logging
from trove.common import cfg
from trove.common.i18n import _
from trove.common.strategies.cluster import base
from trove.common.strategies.cluster.vertica.api import \
VerticaCluster
from trove.instance.models import DBInstance
from trove.ins... |
"""Spectrogram extraction command"""
import importlib
import math
from pathlib import Path
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from cliff.command import Command
from audeep.backend.data.data_set import empty
from audeep.backend.enum_parser import EnumType
from audeep.backend.fo... |
# -*- coding: utf8 -*-
__all__ = ('TravisHook',)
import json
from hashlib import sha256
import flask_wtf as wtf
from notifico.services.hooks import HookService
from notifico.services.hooks.github import GithubHook
class TravisConfigForm(wtf.Form):
gh_user = wtf.TextField('GitHub username', validators=[
... |
import os
import tempfile
import unittest
import logging
import sys
from pyprint.ClosableObject import close_objects
from pyprint.NullPrinter import NullPrinter
import pytest
from coalib.bearlib.aspects.Metadata import CommitMessage
from coalib.bearlib.languages import Language
from coalib.misc import Constants
from ... |
import thread
import time
import socket
import re
import math
import signal
import os
############# CONFIGURE SIMULATOR ###########################
# Configure ip and port
ip = '127.0.0.1'
port = 20081
# Max connections using the simulator
maxClients = 2
# Configure log
# If log is enabled, logInput and logOuput... |
from struct import pack
from .byte_order import *
import os
class Writer:
""" Writer lets an application write primitive data types to an underlying output file. """
# Output file.
file = None
# The number of bytes written to the output file so far.
written = 0
is_closed_flag = False
# By... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import difflib
import os
import re
from collections import defaultdict
from pants.backend.core.tasks.task import Task
class BuildLint(Task):
@classmethod
def re... |
from matplotlib.pyplot import plot, show, xticks, xlabel, ylabel, legend, yscale, title, savefig, rcParams, figure, hist, text, bar, subplots
import matplotlib.pyplot as plt
import Image
from scipy import stats
import pandas as pd
import numpy as np
from datetime import datetime as dt
def read_ts_csv(fname, dindex="D... |
from google.protobuf import message
from recipe_engine import recipe_test_api
class ProtoTestApi(recipe_test_api.RecipeTestApi):
@recipe_test_api.placeholder_step_data
@staticmethod
def output(proto_msg, retcode=None, name=None):
"""Supplies placeholder data for a proto.output.
Args:
* proto_ms... |
from dqm.check_bricks import (
Check,
DataType,
GaLevel,
Parameter,
Platform,
Result,
ResultField,
Theme,
)
from dqm.helpers import analytics
class CheckCustomDimensions(Check):
"""Verify a list of custom dimensions to be tracked in GA.
GIVEN
An Event
WHEN
A query to GA Reporting API v4, fi... |
import sys
import gdcm
if __name__ == "__main__":
# Check arguments
if (len(sys.argv) < 2):
# No filename passed
print "No input filename found"
quit()
filename = sys.argv[1]
# Read file
reader = gdcm.Reader()
reader.SetFileName(filename)
if (not r... |
import logging
from abc import (ABCMeta,
abstractmethod)
from treeherder.model.models import MatcherManager
logger = logging.getLogger(__name__)
class Detector(object):
__metaclass__ = ABCMeta
name = None
"""Class that is called with a list of lines that correspond to
unmatched, in... |
import sys
import optparse
import os
scripts_path = os.path.abspath(os.path.dirname(os.path.abspath(sys.argv[0])))
lib_path = os.path.abspath(scripts_path + '/../lib')
sys.path = sys.path + [lib_path]
import scriptpath
# For importing the following modules
bitbakepath = scriptpath.add_bitbake_lib_path()
if not bitb... |
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from tempfile import mktemp
from numpy import array,transpose
from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal, \
assert_equal, rand
import scipy.sparse
from scipy.io.mmio import mminfo,mm... |
""" The production package is responsible for classes which describe various kinds of generators. These classes also provide production costing information which is used to economically allocate demand among committed units and calculate reserve quantities.
"""
from google.appengine.ext import db
ns_prefix = "cim"
n... |
import pytest
from conans.model.build_info import CppInfo
from conans.model.new_build_info import NewCppInfo, _DIRS_VAR_NAMES, _FIELD_VAR_NAMES, \
fill_old_cppinfo, from_old_cppinfo
def test_components_order():
cppinfo = NewCppInfo()
cppinfo.components["c1"].requires = ["c4", "OtherPackage::OtherComponen... |
__version__ = '$Id$'
import re
import sys
import threading
import time
import tkMessageBox, tkSimpleDialog
from Tkinter import *
from gui import EditBoxWindow
color_pattern = re.compile(r"%s\{(?P<colorname>\w+)\}" % "\x03")
# we run the Tkinter mainloop in a separate thread so as not to block
# the main bot code; h... |
#!/ebio/ag-neher/share/programs/EPD/bin/python
'''
author: Taylor Kessinger & Richard Neher
date: 10/07/2014
content: generate beta coalescent trees and calculate their SFS
'''
import os
import numpy as np
import random as rand
import scipy.special as sf
from Bio import Phylo
from betatree import *
def lo... |
import multiprocessing
import os
import shutil
import sys
import board
import bsettings
from builder import Builder
import gitutil
import patchstream
import terminal
from terminal import Print
import toolchain
import command
import subprocess
def GetPlural(count):
"""Returns a plural 's' if count is not 1"""
... |
"""A tool to extract size information for chrome, executed by buildbot.
When this is run, the current directory (cwd) should be the outer build
directory (e.g., chrome-release/build/).
For a list of command-line options, call this script with '--help'.
"""
import errno
import json
import platform
import optpar... |
from __future__ import absolute_import, division, print_function, \
with_statement
import unittest
from miserable.dns.utils import *
class HostnameTestCase(unittest.TestCase):
def test_hostname(self):
addr = Address('www.baidu.com', 80)
self.assertTrue(addr.ipaddr is None)
self.asser... |
import unittest
import numpy as np
import scrapenhl2.scrape.scrape_setup as ss
class SSTest_check_types(unittest.TestCase):
"""Tests for scrape_setup.check_types()"""
def test_int(self):
self.assertTrue(ss.check_types(8471214))
def test_str(self):
self.assertTrue(ss.check_types('847121... |
from django.http import QueryDict, HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.db import models, transaction
import logging
import re
from django_facebook import settings as facebook_settings
from django.utils.encoding import iri_to_uri
from django.template.loader import render_to_st... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from specparser import HadoopRuntime
from pysqoop2 import MySqoop, pp
def main():
hr = HadoopRuntime()
settings = hr.settings
print(settings)
hr.clean_working_dir()
output_dir = hr.get_hdfs_working_dir("dump_dir")
sqoop = MySqoop(settings.Param.Sq... |
"""Unsplash
"""
from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl
from json import loads
from searx import logger
logger = logger.getChild('unsplash engine')
# about
about = {
"website": 'https://unsplash.com',
"wikidata_id": 'Q28233552',
"official_api_documentation": 'https://unsplash... |
# New contrast/bias mode that operates on viewers with state objects
from __future__ import absolute_import, division, print_function
from glue.external.echo import delay_callback
from glue.config import viewer_tool
from glue.viewers.common.qt.mouse_mode import MouseMode
@viewer_tool
class ContrastBiasMode(MouseMod... |
"""Hyperparameter sweep to retrain on train+val. the hyper-deep ensemble."""
DEFAULT_L2 = 1e-4
TRAIN_SET_SIZE = 0.95 * 50000
# NOTE: below, we normalize by TRAIN_SET_SIZE because the models from the random
# search used a custom convention for l2, normalized by the train dataset size.
SELECTED_HPS = [
{
... |
from __future__ import absolute_import
"""Threaded based executor.
Blocked tasks may be discarded, and the worker pool is automatically
replenished."""
import collections
import functools
import logging
import threading
from vdsm.common import time
from . import concurrent
class NotRunning(Exception):
"""Execu... |
"""Ground-truth state 2-step Agent."""
import time
import numpy as np
from ravens import utils
from ravens.agents import GtState6DAgent
from ravens.agents import GtStateAgent
from ravens.models import mdn_utils
from ravens.models import MlpModel
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
class G... |
from math import ceil
from os.path import dirname, isfile, join, realpath
from sys import exit as sys_exit
from sys import path
path.append("..")
from platformio import util
from platformio.platforms.base import PlatformFactory, get_packages
def is_compat_platform_and_framework(platform, framework):
p = Platfor... |
import string
from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR
import CCSDS.PACKET
import UTIL.SYS
#############
# constants #
#############
ENABLE_ACK = 0
ENABLE_NAK = 1
DISABLE_ACK = 2
ACK_STRS = ["ENABLE_ACK", "ENABLE_NAK", "DISABLE_ACK"]
RPLY_PKT = 0 # replay file TM packet entry
RPLY_RAWPKT =... |
"""This module isn't mine, it's at 99% inspired from https://github.com/gurch101/StockScraper written by Gurchet Rai.
So all rigts reserved to Gurchet Rai.
Documentation http://www.gurchet-rai.net/dev/yahoo-finance-yql
"""
from __future__ import absolute_import
import re
import json
from datetime import date, timedel... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# Soubor: bombardier.py
# Datum: 7.5.2014
# Autor: Marek Nožka, nozka <@t> spseol <d.t> cz
# Licence: GNU/GPL
# Úloha: malá zábavná hra.
###################################################
import random
import pylab as lab
import matplotlib.animation as animation
##... |
# -*- coding: utf-8 -*-
"""
Read beehive's JSON output files and store retrieved information in
:mod:`beehive.model` elements.
Utility to retrieve runtime information from beehive's JSON output.
REQUIRES: Python >= 2.6 (json module is part of Python standard library)
"""
__author__ = "Jens Engel"
# -- IMPORTS:
fro... |
#!/usr/bin/env python
"""
In cryptography, a scytale (rhymes with Italy) is a tool used to
perform a transposition cipher, consisting of a cylinder with a
strip of parchment wound around it on which is written a message.
The ancient Greeks, and the Spartans in particular, are said to
have used this cipher to co... |
from operator import attrgetter
from ryu.app import simple_switch_13
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.lib import hub
class MyMonitor13(simple_switch_13.SimpleSwitch13):
def __init__(self... |
from io import BytesIO
from zlib import compress, decompress
from binary import Struct, Magic, Format, ContainerField, BaseField, BaseArray, Blob, String, FakeWriteStream
from collections import OrderedDict
from swf_abc import ABCFile
class ZlibField(ContainerField):
def __init__(self, unpacked_size_field, field)... |
import pytest
from diffoscope.comparators.json import JSONFile
from utils.data import data, load_fixture
from utils.nonexisting import assert_non_existing
json1 = load_fixture('test1.json')
json2 = load_fixture('test2.json')
json3a = load_fixture('order1a.json')
json3b = load_fixture('order1b.json')
def test_ident... |
import mock
from oslo_config import cfg
import six
from six.moves import builtins as __builtin__
from six.moves import http_client
from swiftclient import client as swift_client
from swiftclient import exceptions as swift_exception
from swiftclient import utils as swift_utils
from ironic.common import exception
from i... |
"""Tests the LocationRulesEngine."""
import unittest.mock as mock
import tempfile
import unittest
from tests.unittest_utils import ForsetiTestCase
from google.cloud.forseti.scanner.audit import location_rules_engine
from tests.scanner.test_data import fake_location_scanner_data as data
rule_tmpl = """
rules:
- na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.