code stringlengths 1 199k |
|---|
__all__ = ['view_as_blocks', 'view_as_windows']
import numpy as np
from numpy.lib.stride_tricks import as_strided
def view_as_blocks(arr_in, block_shape):
"""Block view of the input n-dimensional array (using re-striding).
Blocks are non-overlapping views of the input array.
Parameters
----------
ar... |
from unittest import TestCase
from machete.base.tests import IntegrationTestCase
from machete.wiki.models import Wiki, Page
class CreatePageTest(TestCase):
def test_create_page(self):
wiki = Wiki.create()
page = wiki.create_page("test name [Some link]",
"/index.html",... |
"""
sentry.interfaces.exception
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
__all__ = ('Exception',)
from django.conf import settings
from sentry.interfaces.base import Int... |
"""
GraphLab Create offers several data structures for data analysis.
Concise descriptions of the data structures and their methods are contained in
the API documentation, along with a small number of simple examples. For more
detailed descriptions and examples, please see the `User Guide
<https://dato.com/learn/usergu... |
from datetime import datetime
from django.http import HttpResponse
from smsbrana import SmsConnect
from smsbrana import signals
from smsbrana.const import DELIVERY_STATUS_DELIVERED, DATETIME_FORMAT
from smsbrana.models import SentSms
def smsconnect_notification(request):
sc = SmsConnect()
result = sc.inbox()
... |
import os
import os.path
from nipype.interfaces.utility import IdentityInterface, Function
from nipype.interfaces.io import SelectFiles, DataSink, DataGrabber
from nipype.pipeline.engine import Workflow, Node, MapNode
from nipype.interfaces.minc import Resample, BigAverage, VolSymm
import argparse
def create_workflow(
... |
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
Th... |
import Gaffer
import GafferUI
import GafferScene
Gaffer.Metadata.registerNodeDescription(
GafferScene.Transform,
"""Modifies the transforms of all locations matched by the filter.""",
"space",
"""The space in which the transform is applied.""",
"transform",
"""The transform to be applied.""",
)
GafferUI.PlugValueWidget... |
import unittest
import os
import time
import difflib
import subprocess
import MySQLdb
servers = None
class mysqlBaseTestCase(unittest.TestCase):
def setUp(self):
""" If we need to do anything pre-test, we do it here.
Any code here is executed before any test method we
may execute
... |
from maintenance.async_jobs import BaseJob
from maintenance.models import RemoveInstanceDatabase
__all__ = ('RemoveInstanceDatabase',)
class RemoveInstanceDatabaseJob(BaseJob):
step_manger_class = RemoveInstanceDatabase
get_steps_method = 'remove_readonly_instance_steps'
success_msg = 'Instance removed with... |
import json
import argparse
import logging
import glob
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s: %(message)s')
fh = logging.FileHandler('test_hashes.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.Stre... |
import json
import urllib
import urllib2
from django.core.files import File
from django.conf import settings
from django.contrib.gis.geos import Point
from .models import FloodMap, ReturnPeriod
def get_geoserver_baseurl():
'''
Just input the layer name, height, width and boundarybox
'''
url = settings.N... |
import operator
from copy import deepcopy
import matplotlib
import numpy as np
import pytest
from astropy import units as u
from marvin.core.exceptions import MarvinError
from tests import marvin_test_if
from marvin.tools.maps import Maps
from marvin.tools.quantities import EnhancedMap, Map
from marvin.utils.datamodel.... |
from ...api import generate_media, prepare_media
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Combines and compresses your media files and saves them in _generated_media.'
requires_model_validation = False
def handle(self, *args, **options):
prepare_media()... |
from equity import EquityPricer
class FuturePricer(EquityPricer):
def __init__(self):
super(FuturePricer,self).__init__() |
import sys,logging,optparse
from AlpgenArgoJob import AlpgenArgoJob
sys.path.append('/users/hpcusers/balsam/argo_deploy/argo_core')
from MessageInterface import MessageInterface
def main():
parser = optparse.OptionParser(description='submit alpgen job to ARGO')
parser.add_option('-e','--evts-per-iter',dest='evts_... |
try:
import unittest2 as unittest
except ImportError:
import unittest
import dns.name
import dns.namedict
class NameTestCase(unittest.TestCase):
def setUp(self):
self.ndict = dns.namedict.NameDict()
n1 = dns.name.from_text('foo.bar.')
n2 = dns.name.from_text('bar.')
self.ndic... |
from django.contrib import admin |
import scrapy
class PictureItem(scrapy.Item):
# define the fields for your item here like:
image_urls = scrapy.Field()
images = scrapy.Field() |
from opendata.settings.dev import * |
import sys; sys.path += ['../../']
import traceback, time, thread, threading, random, copy
from i2p import socket, select
def test_passed(s, msg='OK'):
"""Notify user that the given unit test passed."""
print ' ' + (s + ':').ljust(50) + msg
def verify_html(s):
"""Raise an error if s does not end with </html>"""
... |
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a down... |
import frappe
import unittest
import json
class TestPreparedReport(unittest.TestCase):
def setUp(self):
self.report = frappe.get_doc({
"doctype": "Report",
"name": "Permitted Documents For User"
})
self.filters = {
"user": "Administrator",
"doctype": "Role"
}
self.prepared_report_doc = frappe.get... |
from string import join
from array import array
try:
import hashlib as sha
except:
import sha
from time import time
class CryptError(Exception): pass
def _hash(str): return sha.new(str).digest()
_ivlen = 16
_maclen = 8
_state = _hash(`time()`)
try:
import os
_pid = `os.getpid()`
except ImportError, Attr... |
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, SubsampleLayer, DimshuffleLayer
from lasagne.nonlinearities import sigmoid, rectify
from lasagne.objectives import c... |
try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... |
"""
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left
and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces
' ' when necessary so that each line has exactly L char... |
import unittest
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class MyTest(TestCommand):
def run_tests(self):
tests = unittest.TestLoader().discover('tests', pattern='test_*.py')
unittest.TextTestRunner(verbosity=1).run(tests)
setup(
... |
from django.conf.urls import url
from .views import (homepage, aboutpage, newspage, gallerypage, hellopage,
embedpage, widgetpage, newsdetailpage, apps_landing_page,
border_adjustment_plot, docspage, gettingstartedpage)
urlpatterns = [
# url(r'^apps/$', apps_landing_page, nam... |
_first = dict()
_follow = dict()
_table = dict()
_endsymbol = '$'
_emptysymbol = '#'
def recursion(grammar):
section = grammar[0][0]
nonrecursivegrammar = [[item for item in rule] + [section + 'bar'] for rule in grammar if rule[0] != rule[1]]
recursivegrammar = [rule for rule in grammar if rule[0] == rule[1]]
retur... |
from __future__ import absolute_import
import os
import zipfile
DEV_DATA_PATH = os.path.join(
os.path.dirname(__file__),
'..',
'dev_data',
)
def data_path(*args):
"""
Returns a path to dev data
"""
return os.path.join(DEV_DATA_PATH, *args)
def words100k():
zip_name = data_path('words100k... |
"""
Tests to check if basic electrum server integration works
"""
import random
from test_framework.util import waitFor, assert_equal
from test_framework.test_framework import BitcoinTestFramework
from test_framework.loginit import logging
from test_framework.electrumutil import compare, bitcoind_electrum_args
class El... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/weapon/missile/shared_wpn_seismic_missile_mk1.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","wpn_seismic_missile_mk1")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ... |
import urllib
import urllib2
import json
import serial
import time
import gpio
import re
import binascii
import threading
import datetime
import sys
deviceID="xxxxxxxxxx"
apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
key_pin = "gpio12"
s = ""
door = ""
PIR = ""
Leak = ""
Smoke = ""
Remote = ""
Door_mac = ""
PIR_mac = ""
Lea... |
from collections import OrderedDict
def to_odv(df, odv_file_name, vars=None):
'''Output biofloat DataFrame in Ocean Data View spreadsheet format to
file named odv_file_name. Pass in a OrderedDict named vars to override
the default variable list of TEMP_ADJUSTED, PSAL_ADJUSTED, DOXY_ADJUSTED.
'''
fix... |
from CommonServerPython import *
''' STANDALONE FUNCTION '''
def get_threat_indicator_list(args: Dict[str, Any]) -> list:
"""
Executes cofense-threat-indicator-list command for given arguments.
:type args: ``Dict[str, Any]``
:param args: The script arguments provided by the user.
:return: List of re... |
"""
syntax
entity ::= {id(utc millisecond), type, id_from, id_to, status, data, source, note}
data example1: search wikipedia
{ "id":1378327851001,
"type":"name-name",
"id-from":"MIT",
"id-to":"Massachusetts Institute of Technology",
"status":"auto",
"date":"2013-09-04",
"source":"wikipedia+db... |
from . import strip
class Segment(strip.Strip):
"""Represents an offset, length segment within a strip."""
def __init__(self, strip, length, offset=0):
if offset < 0 or length < 0:
raise ValueError('Segment indices are non-negative.')
if offset + length > len(strip):
rais... |
import ctypes
import os
import subprocess
DEFAULT_CONFIG_FILE = 'codedeploy.onpremises.yml'
class System:
UNSUPPORTED_SYSTEM_MSG = (
'Only Ubuntu Server, Red Hat Enterprise Linux Server and '
'Windows Server operating systems are supported.'
)
def __init__(self, params):
self.session... |
from .. import x64dbg
class HardwareType:
HardwareAccess = x64dbg.HardwareAccess
HardwareWrite = x64dbg.HardwareWrite
HardwareExecute = x64dbg.HardwareExecute
def Wait():
x64dbg.Wait()
def Run():
x64dbg.Run()
def Stop():
x64dbg.Stop()
def StepIn():
x64dbg.StepIn()
def StepOver():
x64dbg.... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crowdsourcing', '0007_auto_20151208_1957'),
]
operations = [
migrations.RunSQL('''
CREATE OR REPLACE FUNCTION get_requester_ratings(IN worker_profile_id INTEGER)
RETURNS TAB... |
from rest_framework import status, views
from rest_framework.response import Response
from waldur_core.core.utils import get_lat_lon_from_address
from . import serializers
class GeocodeViewSet(views.APIView):
def get(self, request):
serializer = serializers.GeoCodeSerializer(data=request.query_params)
... |
"""
Support for monitoring the local system..
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.systemmonitor/
"""
import logging
import homeassistant.util.dt as dt_util
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.en... |
from __future__ import absolute_import, unicode_literals
import pytest
import logging
from psd_tools.psd.effects_layer import (
CommonStateInfo,
ShadowInfo,
InnerGlowInfo,
OuterGlowInfo,
BevelInfo,
SolidFillInfo,
)
from ..utils import check_write_read, check_read_write
logger = logging.getLogger... |
"""Test behavior of -maxuploadtarget.
* Verify that getdata requests for old blocks (>1week) are dropped
if uploadtarget has been reached.
* Verify that getdata requests for recent blocks are respected even
if uploadtarget has been reached.
* Verify that the upload counters are reset after 24 hours.
"""
from collection... |
"""
Goal: Implement the application entry point.
@authors:
Andrei Sura <sura.andrei@gmail.com>
"""
import argparse
from olass.olass_client import OlassClient
from olass.version import __version__
DEFAULT_SETTINGS_FILE = 'config/settings.py'
def main():
""" Read args """
parser = argparse.ArgumentParser()
... |
import subprocess
import unittest
import urllib2
import shutil
import json
import ast
import os
from flask import Flask
from flask.ext.testing import LiveServerTestCase
from lwp.app import app
from lwp.utils import connect_db
token = 'myrandomapites0987'
class TestApi(LiveServerTestCase):
db = None
type_json = ... |
'''Make sure the Riak client is sane'''
import unittest
from test import BaseTest
from simhash_db import Client
class RiakTest(BaseTest, unittest.TestCase):
'''Test the Riak client'''
def make_client(self, name, num_blocks, num_bits):
return Client('riak', name, num_blocks, num_bits)
if __name__ == '__m... |
import boto3
import logging
import time
from string import Template
from pyhocon import ConfigTree
from botocore.exceptions import ClientError
from typing import List, Any, Tuple, Dict
from . import Instance
from .instancemanager import InstanceManager
from ..utils import random_str, random_int
log = logging.getLogger(... |
from flask import Blueprint, render_template, request
from werkzeug.exceptions import NotFound
from grano.lib.pager import Pager
from grano.model import Relation
relations = Blueprint('relations', __name__, static_folder='../static', template_folder='../templates')
@relations.route('/relations/<id>')
def view(id):
... |
from .resource import Resource
from .error_detail import ErrorDetail
from .error_response import ErrorResponse
from .error_response_wrapper import ErrorResponseWrapper, ErrorResponseWrapperException
from .storage_account_properties import StorageAccountProperties
from .container_registry_properties import ContainerRegi... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/weapon/shared_quick_shot_upgrade_mk4.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","quick_shot_upgrade_mk4")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
ret... |
from setuptools import setup
setup(name='awstools',
version='0.1',
description='Simple API for AWS IoT',
url='https://github.com/h314to/awstools',
author='Filipe Agapito',
author_email='filipe.agapito@gmail.com',
license='MIT',
packages=['awstools'],
install_requires=[
... |
"""
The SNMPRawCollector is designed for collecting data from SNMP-enables devices,
using a set of specified OIDs
Below is an example configuration for the SNMPRawCollector. The collector
can collect data any number of devices by adding configuration sections
under the *devices* header. By default the collector will co... |
"""
Test compiling and executing using the dmd tool.
"""
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
from Common.singleStringCannotBeMultipleOptions import testForTool
testForTool('dmd') |
import re
import os
import errno
import shutil
import hashlib
from collections import namedtuple
from uuid import uuid4
import psycopg2
import core.db.query_rewriter
from psycopg2.extensions import AsIs
from psycopg2.pool import ThreadedConnectionPool
from psycopg2 import errorcodes
from core.db.licensemanager import L... |
import sys
sys.path = ['../src/'] + sys.path
import unittest
from mlab.mlabwrap import MatlabReleaseNotFound
class TestMlabUnix(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_version_discovery(self):
import mlab
instances = mlab.releases.MatlabVer... |
import random
import functools
import logging
from binascii import crc32
from botocore.vendored.requests import ConnectionError, Timeout
from botocore.vendored.requests.packages.urllib3.exceptions import ClosedPoolError
from botocore.exceptions import ChecksumError, EndpointConnectionError
logger = logging.getLogger(__... |
""" The provider bits of TileStache.
A Provider is the part of TileStache that actually renders imagery. A few default
providers are found here, but it's possible to define your own and pull them into
TileStache dynamically by class name.
Built-in providers:
- mapnik (Mapnik.ImageProvider)
- proxy (Proxy)
- vector (Til... |
import sys
import os
import platform
from read_ndvi import *
import raster_process as rp
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
if len(sys.argv) != 7:
print "input arguments are: flist_ndvi, flist_bq, ulx,uly,lrx,lry"
sys.exit(1)
flist_ndvi=sys.argv[1]
flist_... |
import contextlib
import sqlite3
@contextlib.contextmanager
def sqlite3_connection(db_name):
connection = sqlite3.connect(db_name)
yield connection
connection.close()
with sqlite3_connection('dhcp_snooping.db') as conn:
for row in conn.execute('select * from dhcp'):
print(row)
try:
conn.exec... |
from twilio.twiml.voice_response import Gather, VoiceResponse
response = VoiceResponse()
response.gather()
print(response) |
from .namespace import RBoxNameSpaceListener
from .completion import RBoxCompletionListener, RBoxAutoComplete
from .popup import RBoxPopupListener, RBoxShowPopup
from .main_menu import RBoxMainMenuListener, RBoxPackageSendCodeCommand
from .render import RBoxRenderRmarkdownCommand, RBoxSweaveRnwCommand, RBoxKnitRnwComma... |
class DataType(object):
def __init__(self, type, preprocessor=None):
self.type = type
self.preprocessor = preprocessor
def preprocess(self, value):
return self.preprocessor(value) if self.preprocessor else value
def serialize(self, value):
return value
def unserialize(sel... |
"""Module to help with parsing and generating configuration files."""
import asyncio
import logging
import os
import shutil
from types import MappingProxyType
from typing import Any, Tuple # NOQA
import voluptuous as vol
from homeassistant.const import (
CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_UNIT_SYSTEM,
... |
""" Daemon runner library.
"""
import sys
import os
import signal
import errno
from . import pidlockfile
from .daemon import DaemonContext
if sys.version_info >= (3, 0):
unicode = str
basestring = str
class DaemonRunnerError(Exception):
""" Abstract base class for errors from DaemonRunner. """
class Dae... |
from Components.Pixmap import MovingPixmap, MultiPixmap
from Tools.Directories import resolveFilename, SCOPE_SKIN
from xml.etree.ElementTree import ElementTree
from Components.config import config, ConfigInteger
from Components.RcModel import rc_model
from boxbranding import getBoxType
config.misc.rcused = ConfigIntege... |
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
import docutils
from docutils.core import publish_cmdline, default_description
if True: # this is still required in the distutils trunk as-at June 2008.
from docutil... |
from xcrawler.compatibility.string_converter.compatible_string_converter import CompatibleStringConverter
class StringConverterPython3(CompatibleStringConverter):
"""A Python 3 compatible class for converting a string to a specified type.
"""
def convert_to_string(self, string):
string = self.try_co... |
__author__ = 'shenshijun'
import copy
class Queue(object):
"""
使用Python的list快速实现一个队列
"""
def __init__(self, *arg):
super(Queue, self).__init__()
self.__queue = list(copy.copy(arg))
self.__size = len(self.__queue)
def enter(self, value):
self.__size += 1
self._... |
"""Module for parsing main configuration file (nagios.cfg)."""
from pynag.Utils import paths
class MainConfig(object):
""" Generic parser for files in the format of key=value.
This is the format used by nagios.cfg and many other unix configuration files.
"""
def __init__(self, filename=None):
if... |
"""Global lock to ensure plover only runs once."""
import sys
class LockNotAcquiredException(Exception):
pass
if sys.platform.startswith('win32'):
from ctypes import windll
class PloverLock:
# A GUID from http://createguid.com/
guid = 'plover_{F8C06652-2C51-410B-8D15-C94DF96FC1F9}'
d... |
from pycvsanaly2.Database import (SqliteDatabase, MysqlDatabase,
TableAlreadyExists, statement)
from pycvsanaly2.extensions import (Extension, register_extension,
ExtensionRunError)
from pycvsanaly2.extensions.file_types import guess_file_type
from pycvsanaly2.utils import to_utf8, uri_to_filename
class DBFileT... |
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match in twitter.
Copyrigh... |
import copy
import json
import math
from functools import partial
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, pyqtSignal, QObject, pyqtSlot, Qt, QUrl, \
QRectF, SIGNAL, QPointF, QLineF
from PyQt4.QtGui import QAction, QIcon, QPainter, QPen, QBrush, QColor, QPixmap, QCursor, QPolygon... |
"""
Created on Wed Mar 2 12:13:32 2016
@author: Zahari Kassabov
""" |
from devassistant.command_runners import CommandRunner
from devassistant.logger import logger
class CR1(CommandRunner):
@classmethod
def matches(cls, c):
return c.comm_type == 'barbarbar'
@classmethod
def run(cls, c):
logger.info('CR1: Doing something ...')
x = c.input_res + 'bar... |
from boxbranding import getBoxType, getMachineName, getMachineBuild, getBrandOEM, getMachineBrand
from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from Components.AVSwitch import iAVSwitch
from Screens.Screen import Screen
from Components.Pixmap import... |
import string
import empDb
import empSector
import math
move_directions = "ujnbgy"
move_reverse_directions ="bgyujn"
def norm_coords( coords, world_size ) :
""" normalize coordinates according to world size"""
x , y = coords
size_x, size_y = world_size
return ( ( x + size_x / 2 ) % size_x - size_x / 2... |
"""
Clopath Rule: Spike pairing experiment
--------------------------------------
This script simulates one ``aeif_psc_delta_clopath`` neuron that is connected with
a Clopath connection [1]_. The synapse receives pairs of a pre- and a postsynaptic
spikes that are separated by either 10 ms (pre before post) or -10 ms (p... |
__all__ = ['Parser']
import os
import struct
import logging
import stat
from .exceptions import ParseError
from . import core
from six import byte2int, indexbytes
log = logging.getLogger(__name__)
START_CODE = {
0x00: 'picture_start_code',
0xB0: 'reserved',
0xB1: 'reserved',
0xB2: 'user_data_start_code'... |
from collections import defaultdict
from datetime import time
from sqlalchemy import func
from indico.core.db import db
from indico.modules.rb.models.aspects import Aspect
from indico.util.caching import memoize_request
from indico.util.decorators import classproperty
from indico.util.i18n import _
from indico.util.loc... |
import os
from . import version
def detect_version():
"""Emit GIPS' software version. May be overridden for testing purposes.
To override version.py, put a desired version string in the environment
variable GIPS_OVERRIDE_VERSION."""
return os.environ.get('GIPS_OVERRIDE_VERSION', version.__version__)
__... |
"""
Created on Sun Mar 27 01:20:46 2016
@author: caioau
"""
import matplotlib.pyplot as plt
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
def main():
G = nx.DiGraph() # G eh um grafo direcionado
# gera o grafo apartir de suas arestas
G.add_weighted_edges_from([(1,2,2.0),(1,3,... |
from __future__ import absolute_import
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from wiki.core.plugins import registry
from wiki.core.plugins.base import BasePlugin
from wiki.plugins.macros import settings
from wiki.plugins.macros.mdx.macro import MacroExtension
from wi... |
from datetime import datetime, timedelta
from perceval.backends.core.gerrit import Gerrit
hostname = 'gerrit.opnfv.org'
user = 'd.arroyome'
from_date = datetime.now() - timedelta(days=1)
repo = Gerrit(hostname=hostname, user=user)
for review in repo.fetch(from_date=from_date):
print(review['data']['number']) |
"""Bitcoin Core RPC support"""
from __future__ import absolute_import, division, print_function, unicode_literals
try:
import http.client as httplib
except ImportError:
import httplib
import base64
import binascii
import decimal
import json
import os
import platform
import sys
try:
import urllib.parse as ur... |
import macosx_native
def main():
macosx_native.probe_coreaudio(True,True) |
from rocketlander import RocketLander
from constants import LEFT_GROUND_CONTACT, RIGHT_GROUND_CONTACT
import numpy as np
import pyglet
if __name__ == "__main__":
# Settings holds all the settings for the rocket lander environment.
settings = {'Side Engines': True,
'Clouds': True,
... |
def agts(queue):
d = queue.add('dipole.py', ncpus=4, walltime=60)
queue.add('plot.py', deps=d, ncpus=1, walltime=10,
creates=['zero.png', 'periodic.png', 'corrected.png',
'slab.png'])
queue.add('check.py', deps=d, ncpus=1, walltime=10) |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_vmkernel_facts
short_description: Gathers VMKernel facts about an ESXi host
descr... |
nproc = 1 # Number of processors to use
from boututils import shell, launch, plotdata
from boutdata import collect
import numpy as np
from sys import argv
from math import sqrt, log10, log, pi
from matplotlib import pyplot
gamma = 3.
if len(argv)>1:
data_path = str(argv[1])
else:
data_path = "data"
electron_mass =... |
from .cached_property import cachedproperty
from .eve_normalize import EveNormalizer
from .resource_browser import ResourceBrowser
from .translator import Translator |
import pytest
from megaradrp.processing.fibermatch import generate_box_model
from megaradrp.processing.fibermatch import count_peaks
PEAKS = [
3.806000000000000000e+03,
3.812000000000000000e+03,
3.818000000000000000e+03,
3.824000000000000000e+03,
3.830000000000000000e+03,
3.836000000000000000e+0... |
from timelinelib.wxgui.framework import Controller
class SetCategoryDialogController(Controller):
def on_init(self, db, selected_event_ids):
self._db = db
self._selected_event_ids = selected_event_ids
self.view.PopulateCategories()
self._set_title()
def on_ok_clicked(self, event)... |
"""
Weblate wrapper around translate-toolkit formats to add missing
functionality.
"""
import json
from translate.storage.jsonl10n import JsonFile as JsonFileTT
class JsonFile(JsonFileTT):
"""
Workaround ttkit bug on not including added units in saved file.
This is fixed in 1.13.0
"""
def __str__(se... |
import nltk
from pypln.backend.workers.bigrams import Bigrams
from utils import TaskTest
bigram_measures = nltk.collocations.BigramAssocMeasures()
class TestBigramWorker(TaskTest):
def test_bigrams_should_return_correct_score(self):
# We need this list comprehension because we need to save the word list
... |
def bits_set(x):
bits = 0
for i in range(0,8):
if (x & (1<<i))>0:
bits += 1
return bits
def find_ber(sent, received):
assert(len(received)<=len(sent))
if len(received) < len(sent)/2:
print "frame detection error, more than half of the frames were lost!"
return 0.5
errors = 0
for i in range(0,len(receive... |
from PyQt5.QtCore import QObject, pyqtSignal
from model.player import Player
class Playerset(QObject):
"""
Wrapper for an id->Player map
Used to lookup players either by id or by login.
"""
playerAdded = pyqtSignal(object)
playerRemoved = pyqtSignal(object)
def __init__(self):
QObjec... |
""" This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h values.
Example:
as import:
from getERA import era_prep as prep
prep.main(wd, config['main']['startDate'], config['main']['endDate'])
Attributes:
wd = "/home/jo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.