repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
Jozhogg/iris | lib/iris/tests/test_ff.py | Python | lgpl-3.0 | 13,420 | 0 | # (C) British Crown Copyright 2010 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... |
cubes = iris.load(self.filename)
while cubes:
cube = cubes.pop(0)
standard_name = cube.standard_name
cube_by_name[standard_name] += 1
filename | = '{}_{}.cml'.format(standard_name,
cube_by_name[standard_name])
self.assertCML(cube, ('FF', filename))
def test_raw_to_table_count(self):
filename = tests.get_data_path(('FF', 'n48_multi_field_table_count'))
cubes = iris.load_raw(filename)
... |
AfricanResearchCloud/gatekeeper | onboarding/views.py | Python | mit | 3,919 | 0.006634 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.template import loader
from gatekeeper.openstack import Openstack
from django.views.decorators.csrf import csrf_exempt
from gatekeeper.user import User
from gatekeeper.utils import... | nt.create_user_with_regex_filter(request.META.get(SHIB_EMAIL_ATTRIBUTE))
LOG.info("Creating user: %s" % (username))
return HttpResponse(json.dumps(User(username)), content_type="application/json")
@csrf_exempt
def createTrialProject(request):
username = request.META.get(SHIB_USER_ATTRIBUTE)
openstack_c... | esponse()
@csrf_exempt
def getWelcome(request):
welcome_markdown = open(os.path.join(BASE_DIR, 'onboarding/markdown/welcome.md'), 'r').read()
return HttpResponse(markdown.markdown(welcome_markdown))
@csrf_exempt
def getNotAllowedCreate(request):
not_allowed_markdown = open(os.path.join(BASE_DIR, 'onboardi... |
tjnapster555/django-edu | setup.py | Python | mit | 2,504 | 0.009185 | """
Based entirely on Django's setup.py
"""
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
import os
import sys
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is ... | t__('django-edu').VERSION
if version_tuple[2] is not None:
version = "%d.%d_%s" % version_tuple
else:
version = "%d.%d" % version_tuple[:2]
setup(
name = "django-edu",
version = ve | rsion,
url = 'http://www.example.com/',
author = 'Robert Myers',
author_email = 'myer0052@gmail.com',
description = 'Set of helper views and forms for EDU objects in Django.',
packages = packages,
data_files = data_files,
classifiers = ['Development Status :: 4 - Beta',
'E... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/orca/scripts/toolkits/CALLY/script.py | Python | gpl-3.0 | 73 | 0.013699 | ../../../../.. | /../../share/pyshared/orca/scripts/toolkits/CALLY/script | .py |
UdK-VPT/Open_eQuarter | mole/stat_corr/nrb_contemporary_base_uvalue_by_building_age_lookup.py | Python | gpl-2.0 | 2,378 | 0.172834 | # coding: utf8
# OeQ autogenerated lookup function for 'Non Residential Building Base U-Value of Buildings in correlation to year of construction, based on GEMOD
import math
import numpy as np
import oeqLookuptable as oeq
def get(*xin):
l_lookup = oeq.lookuptable(
[0,1.2,
1849,1.2,
1850,1.2,
1851,1.2,
1852,1.2,
... | 975,1.2,
1976,1.2,
1977,1.2,
1978,1.2,
1979,0.85,
1980,0.85,
1981,0.85,
1982,0.85,
1983,0.85,
1984,0.4,
1985,0.4,
1986,0.4,
1987,0.4,
1988,0.4,
1989,0.4,
1990,0.4,
1991,0.4,
1992,0.4,
1993,0.4,
1994,0.4,
1995,0.4,
1996,0.4,
1997,0.4,
1 | 998,0.4,
1999,0.4,
2000,0.4,
2001,0.4,
2002,0.4,
2003,0.4,
2004,0.4,
2005,0.4,
2006,0.4,
2007,0.4,
2008,0.4,
2009,0.4,
2010,0.4,
2011,0.4,
2012,0.4,
2013,0.4,
2014,0.4,
2015,0.4,
2016,0.4,
2017,0.4,
2018,0.4,
2019,0.4,
2020,0.4,
2021,0.15,
2022,0.15,
2023,0.15,
2024,0.15,
2025,0.15,
2026,0.15,
2027,0.15,
2028,0.15,
202... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.7/Lib/test/test_old_mailbox.py | Python | mit | 4,669 | 0.001071 | # This set of tests exercises the backward-compatibility class
# in mailbox.py (the ones without write support).
import mailbox
import os
import time
import unittest
from test import test_support
# cleanup earlier tests
try:
os.unlink(test_support.TESTFN)
except os.error:
pass
FROM_ = "From some.body@dummy.d... | "subject"], "Simple Test")
self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE))
self.assertEqual(n, 1)
class MboxTestCase(unittest.TestCase):
def setUp(self):
# create a new maildir mailbox to work with | :
self._path = test_support.TESTFN
def tearDown(self):
os.unlink(self._path)
def test_from_regex (self):
# Testing new regex from bug #1633678
f = open(self._path, 'w')
f.write("""From fred@example.com Mon May 31 13:24:50 2004 +0200
Subject: message 1
body1
From fred@e... |
dgjnpr/py-junos-eznc | tests/unit/facts/test_swver.py | Python | apache-2.0 | 4,029 | 0.000248 | __author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"
import unittest
from nose.plugins.attrib import attr
from mock import patch
import os
from jnpr.junos import Device
from jnpr.junos.facts.swver import facts_software_version as software_version, version_info
from ncclient.manager import Manager,... | ajor=(11, 4), '
'type=R, minor=7, build=5)')
def test_version_info_lt(self):
self.assertLess(version_info('13.3-20131120'), (14, 1))
def test_version_info_lt_eq(self):
self.assertLessEqual(version_info('13.3-20131120'), (14, 1))
def test_version_info_gt(self):
... | def test_version_info_gt_eq(self):
self.assertGreaterEqual(version_info('13.3-20131120'), (12, 1))
def test_version_info_eq(self):
self.assertEqual(version_info('13.3-20131120'), (13, 3))
def test_version_info_not_eq(self):
self.assertNotEqual(version_info('13.3-20131120'), (15, 3))
... |
skdaccess/skdaccess | skdaccess/geo/srtm/cache/data_fetcher.py | Python | mit | 10,677 | 0.006837 | # The MIT License (MIT)
# Copyright (c) 2016 Massachusetts Institute of Technology
#
# Authors: Cody Rude, Guillaume Rongier
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person obtaining ... | True,
store_geolocation_grids=False):
'''
Initialize Data Fetcher
@param lat_tile_start: Latitude of the southwest corner of the starting tile
@param lat_tile_end: Latitude of the southwset corner of the last tile
@param lon_tile_start: Long | itude of the southwest corner of the starting tile
@param lon_tile_end: Longitude of the southwest corner of the last tile
@param username: NASA Earth Data username
@param password: NASA Earth Data Password
@param arcsecond_sampling: Sample spacing of the SRTM data, either 1 arc-
... |
CallanIwan/Aranha | core/network/bluetooth_server.py | Python | gpl-2.0 | 3,131 | 0.003833 | """
network/bluetooth_server.py
Starts a bluetooth server with max 7 connections.
Receives and sends data from/to paired client.
PS3 controller: receive only
Android App: receive/send
"""
import base64
from threading import Thread
from bluetooth import *
import protocol
import thread
import atexit
PACKET_SIZE = 990
... | dapter
self.server_sock.listen(1) # server listens to accept 1 connection at a time
self.port = se | lf.server_sock.getsockname()[1] # socket is bound on this port
# advertise service
uuid = "9d7debbc-c85d-11d1-9eb4-006008c3a19a" # ID of the service
advertise_service(self.server_sock, "Aranha", # start service, so the app can connect
service_id=uuid,
... |
sjagoe/usagi | usagi/discoverer.py | Python | bsd-3-clause | 4,383 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
f... | f._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*... | for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
|
Oleh-Hrebchuk/OpenVPN-TryFalse | vpn/migrations/0046_grouppermisions.py | Python | gpl-3.0 | 624 | 0.001603 | # -*- coding: utf-8 -*-
# Generated b | y Django 1.9.8 on 2016-08-11 13:25
from __f | uture__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vpn', '0045_auto_20160811_1212'),
]
operations = [
migrations.CreateModel(
name='GroupPermisions',
fields=[
('id', m... |
emk/rust | src/etc/snapshot.py | Python | apache-2.0 | 7,384 | 0.01273 | # Copyright 2011-2014 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or ht... | h_dirs = os.environ["PATH"].split(os.pathsep)
for name in deps:
for dir in path_dirs:
filepath = os.path.j | oin(dir, name)
if os.path.isfile(filepath):
runtime_deps.append(filepath)
break
else:
raise Exception("Could not find runtime dependency: %s" % name)
return runtime_deps
def make_snapshot(stage, triple):
kernel = get_kernel(triple)
platform = get_platform(triple)
... |
participedia/pontoon | pontoon/base/tests/test_placeables.py | Python | bsd-3-clause | 3,308 | 0.00393 | from django_nose.tools import assert_equal
from pontoon.base.tests import TestCase
from pontoon.base.utils import NewlineEscapePlaceable, mark_placeables
class PlaceablesTests(TestCase):
def test_newline_escape_placeable(self):
"""Test detecting newline escape sequences"""
placeable = NewlineEsca... | u'Hello <mark class="placeable" title="Python format string">{name[0]}</mark>'
)
assert_equal(
mark_placeables(u'Hello {someone.name[0]}'),
u'Hello <mark class="placeable" title="Python format string">{someone.name[0]}</mark>'
)
def test_python_format_name... | t detection of format string with named placeables."""
assert_equal(
mark_placeables(u'Hello %(name)s'),
u'Hello <mark class="placeable" title="Python format string">%(name)s</mark>'
)
assert_equal(
mark_placeables(u'Rolling %(number)d dices'),
u'... |
eBrnd/i3pystatus | i3pystatus/weather/wunderground.py | Python | mit | 8,899 | 0.000225 | from i3pystatus import IntervalModule
from i3pystatus.core.util import internet, require
from datetime import datetime
from urllib.request import urlopen
import json
import re
GEOLOOKUP_URL = 'http://api.wunderground.com/api/%s/geolookup%s/q/%s.json'
STATION_QUERY_URL = 'http://api.wunderground.com/api/%s/%s/q/%s.jso... | except TypeError:
observation_time = 0
return dict(
city=_find('city', response['observation_location']),
condition=_find('weather'),
observation_time=datetime.fromtimestamp(observation_time),
| current_temp=_find('temp_' + temp_unit),
low_temp=low_temp,
high_ |
yarikoptic/NiPy-OLD | nipy/neurospin/bindings/tests/test_array.py | Python | bsd-3-clause | 2,134 | 0.009841 | #!/usr/bin/env python
#
# Test fff_array wrapping
#
from numpy.testing import assert_almost_equal, assert_equal
import numpy as np
import nipy.neurospin.bindings as fb
MAX_TEST_SIZE = 30
def random_shape(size):
"""
Output random dimensions in the range (2, MAX_TEST_SIZE)
"""
aux = np.random.randint... | _test_array_sub(x, y)
def _test_array_div(x, y):
z = fb.array_div(x, y)
assert_almost_equal(z, x/y)
def test_array_div():
d0, d1, d2, d3 = random_shape(4)
x = np.random.rand(d0, d1, d2, d3)-.5
y = np.random.rand(d0, d1, d2, d3)-.5
_test_array_div(x, y)
if _ | _name__ == "__main__":
import nose
nose.run(argv=['', __file__])
|
ActiveState/code | recipes/Python/552749_Create_singlefile_executables/recipe-552749.py | Python | mit | 353 | 0.016997 | @echo off
rem = """
py25 -x "%~f0"
goto e | ndofPython """
from distutils.core import setup
import py2exe
import shutil
import sys, os
sys.argv += ['py2exe', '-b1', '-d./']
setup(
# use "console = " for console-based apps
windows=["cron.py"],
zipfile=None
)
shutil.rmtree('build')
os.remove('w9xpop | en.exe')
rem = """
:endofPython """
|
pnigos/gyp | test/analyzer/gyptest-analyzer.py | Python | bsd-3-clause | 13,761 | 0.00436 | #!/usr/bin/env python
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for analyzer
"""
import json
import TestGyp
found = 'Found dependency'
found_all = 'Found dependency (all)'
not_found = 'No depend... | nalyzer4(*args, **kw):
"""Same as run_analyzer(), but passes in test3.gyp instead of test.gyp."""
args += CommonArgs()
test.run_gyp('test4.gyp', *args, **kw)
def EnsureContains(matched | =False, compile_targets=set(), test_targets=set()):
"""Verifies output contains |compile_targets|."""
result = _ReadOutputFileContents()
if result.get('error', None):
print 'unexpected error', result.get('error')
test.fail_test()
if result.get('invalid_targets', None):
print 'unexpected invalid_tar... |
TrapKingg/Tescha-books | manage.py | Python | mit | 809 | 0 | #!/usr/bin/env python
import os
import sys
|
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TeschaBooks.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django i... | :
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
... |
KonradBreitsprecher/espresso | samples/cellsystem_test.py | Python | gpl-3.0 | 2,497 | 0.002403 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013,2014,2015,2016 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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 v... | auto")
fene = interactions.FeneBond(k=10, d_r_max=1.5)
system.bonded_inter.add(fene)
polymer.create_polymer(N_P=1, bond_length=0.97, MPC=100, bond=fene)
n_steps = 1000
print("Testing without verlet lists...")
cs.set_domain_decomposition(use_verlet_lists=False)
for skin in np.arange(5, 15, 1):
p | rofile()
print("Testing with verlet lists...")
cs.set_domain_decomposition(use_verlet_lists=True)
for skin in np.arange(5, 15, 1):
profile()
cs.set_n_square(True)
print("Testing with N-squared ...")
for skin in np.arange(5, 15, 1):
profile()
print("Using automatic tuning...")
skin=cs.tune_skin(min_skin=0.5, ... |
lizardsystem/lizard5-apps | lizard_wms/testsettings.py | Python | lgpl-3.0 | 4,882 | 0 | import logging
import os
from lizard_ui.settingshelper import STATICFILES_FINDERS
logging.basicConfig(
level=logging.DEBUG,
format='%(name)s %(levelname)s %(message)s')
DEBUG = True
TEMPLATE_DEBUG = True
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'test.db'
SITE_ID = 1
INSTALLED_APPS = [
'lizard_wms',
... | ]
ROOT_URLCONF = 'lizard_wms.urls'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
DATABA | SES = {
'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db'},
}
TEMPLATE_CONTEXT_PROCESSORS = (
# Default items.
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.conte... |
CensoredUsername/dynasm-rs | tools/aarch64_gen_tests.py | Python | mpl-2.0 | 9,637 | 0.003839 |
import ast
import random
import re
def main():
import sys
infile = sys.argv[1]
attempts = int(sys.argv[2])
outfile = sys.argv[3]
with open(infile, "r", encoding="utf-8") as f:
templates = read_opdata_file(f)
buf = []
for template in templates:
for _ in range(attempts):
... | ue)
elif self.family in "BHSDQV":
return "{}{}".format(self.family.lower(), value)
else:
raise NotImplementedError(self.family)
def emit_dynasm(self, value, allow_dynamic=True):
# randomly choose dynamic vs static notation
if random.choice((True, False)) or n... | ow_dynamic or ('SP' in self.family and value != 31):
return self.emit_gas(value)
else:
if self.family == "WX":
self.family = random.choice("WX")
return "{}({})".format(self.family, value)
class Modifier(Arg):
def emit_gas(self, value):
return "{}... |
jacobian-archive/python-hdcloud | tests/test_base.py | Python | bsd-3-clause | 1,267 | 0.007893 | from __future__ import absolute_import
import hdcloud.base
from .fakeserver import FakeHDCloud
from hdcloud import Store
from hdcloud.base import Resource
from nose.tools import assert_equal, assert_not_equal, assert_raises
hdcloud = FakeHDCloud()
def test_resource_repr():
r = Resource(None, dict(foo="bar", baz=... | lahblah')
hdcloud.assert_called('GET', '/stores/1.json')
def test_eq():
# Two resources of the same type with the same id: equal
r1 = Resource(None, {'id':1, 'name':'hi'})
r2 = Resource(None, {'id':1, 'name':'hello'})
assert_equal(r1, r2)
# Two resoruces of different types: never equal
r1 ... | 1})
r2 = Store(None, {'id': 1})
assert_not_equal(r1, r2)
# Two resources with no ID: equal if their info is equal
r1 = Resource(None, {'name': 'joe', 'age': 12})
r2 = Resource(None, {'name': 'joe', 'age': 12})
assert_equal(r1, r2) |
mblakele/pygraylog | examples/test_users.py | Python | gpl-3.0 | 789 | 0.050697 | #! /usr/bin/env python
from pygraylog.users import User
john = User('dappsyslogapp1.pgs', 12900, 'dieux', | 'ad | min')
#if john.find_by_username('mathieu.grzybek') == True:
#print 'mathieu found'
#if john.find_by_username('john') == True:
#print 'john found'
#else:
#print 'john not found'
user = { u'username' : u'john', u'full_name' : u'john doe', u'email' : 'john@doe.net', u'password' : u'doejohn', u'permissions' : [ u'*' ... |
pobear/django-xadmin | xadmin/plugins/__init__.py | Python | bsd-3-clause | 659 | 0.010622 |
PLUGINS = ('actions', 'filters', 'bookmark', 'export', 'layout', 'refresh', 'sortable', 'details',
'editable', 'relate', 'chart', 'ajax', 'relfield', 'inline', 'topnav', 'portal | ', 'quickform',
'wizard', 'images', 'auth', 'multiselect', 'themes', 'aggregation', 'mobile', 'passwords',
'sitemenu', 'language', 'quickfilter')
def register_builtin_plugins(site):
from importlib import import_module
from django.conf import settings
print '+' * 40 + '\n', | site
exclude_plugins = getattr(settings, 'XADMIN_EXCLUDE_PLUGINS', [])
[import_module('xadmin.plugins.%s' % plugin) for plugin in PLUGINS if plugin not in exclude_plugins]
|
GoogleChrome/chromium-dashboard | pages/metrics_test.py | Python | apache-2.0 | 2,931 | 0.006141 | # Copyright 2022 Google 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 writing, s... | ing_config.CustomTestCase):
HANDLER_CLASS = metrics.CssPopularityHandler
def setUp(self):
self.request_path = self.HANDLER_CLASS.TEMPLATE_PATH
self.handler = self.HANDLER_CLASS()
with test_app.test_request_context(self.request_path):
self.template_data = self.handler.get_template_data(... | ml."""
template_text = self.handler.render(
self.template_data, self.full_template_path)
parser = html5lib.HTMLParser(strict=True)
document = parser.parse(template_text)
class CssAnimatedTemplateTest(testing_config.CustomTestCase):
HANDLER_CLASS = metrics.CssAnimatedHandler
def setUp(self): ... |
namcap/Digital-Image-Processing-in-Python | 4.Simple JPEG/Simple JPEG.py | Python | mit | 4,605 | 0.060369 | #! /usr/bin/python3
#This program performs simple JPEG compression (no Huffman coding) with
#different quantization tables, determines quality of the compressed image
#by computing PSNR and generates PSNR-size curve to see
#the impact of compression rate on image's quality
from PIL import Image
import numpy as np
from... | results=sorted_results[0:3]
#Sort the results by size 'num_fields'
sorted_results.sort(key=lambda x: x['num_fields'])
#Save results to files
for i in results:
Im | age.fromarray(i['RGB']).save(i['name'].replace(' ','_')+'.bmp')
#Show results
plt.figure(1),plt.imshow(image, interpolation="none")
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.figure(2),plt.imshow(results[0]['RGB'], interpolation="none")
plt.title(results[0]['name']), plt.xticks... |
cb1234/pynet-test | pyth_ansibel/class9/exercise1/mytest/simple.py | Python | apache-2.0 | 171 | 0.011696 | '''
Python class on writing r | eusable code
'''
def func2():
'''Simple test function'''
print " | Simple"
if __name__ == "__main__":
print "Main program - simple"
|
SeungGiJeong/SK_FastIR | filecatcher/windows2003ServerFiles.py | Python | gpl-3.0 | 475 | 0 | from __future__ import unicode_literals
from fileCatcher import _FileCatcher
class Windows2003ServerFiles(_FileCatcher):
def __init__(self, params):
super(Windows2003ServerFiles, self).__init__(params)
def _changeroot(self, dir):
return dir
def _list_files(self):
return super(Win... | ))
| |
onesfreedom/pybuilder | src/main/python/pybuilder/plugins/python/unittest_plugin.py | Python | apache-2.0 | 9,771 | 0.002661 | # -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# 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/l... | ort discover_modules_matching, render_report, fork_process
from pybuilder.ci_server_interaction import test_proxy_for
from pybuilder.terminal import print_text_line
from types import MethodType, FunctionType
from functools import reduce
use_plugin("python.core")
@init
def init_test_source_directory(project):
pro... | t-xml-reporting")
project.set_property_if_unset("dir_source_unittest_python", "src/unittest/python")
project.set_property_if_unset("unittest_module_glob", "*_tests")
project.set_property_if_unset("unittest_file_suffix", None) # deprecated, use unittest_module_glob.
project.set_property_if_unset("unitt... |
OiNutter/microbit-scripts | bopit/bopit.py | Python | mit | 2,325 | 0.002151 | # Import required modules
from microbit import compass, display, accelerometer, sleep, button_a, button_b, running_time, Image
import random
commands = ["bop it", "twist it", "shake it", "tilt it"]
score = 0
WAIT_TIME = 2000
if not compass.is_calibrated():
compass.calibrate()
#display.scroll("BOP IT")
display.s... | command = random.choice(commands)
display.scroll(command[:2])
start = running_time()
diff = 0
correct = False
# Get | current state for comparison
start_bearing = compass.heading()
start_x = accelerometer.get_x()
start_y = accelerometer.get_y()
while diff < WAIT_TIME:
if command == "bop it":
if button_a.is_pressed() and button_b.is_pressed():
correct = ... |
GabrielNicolasAvellaneda/dd-agent | checks.d/btrfs.py | Python | bsd-3-clause | 4,277 | 0.002104 | # stdlib
import array
from collections import defaultdict
import fcntl
import itertools
import os
import struct
# 3rd party
import psutil
# project
from checks import AgentCheck
MIXED = "mixed"
DATA = "data"
METADATA = "metadata"
SYSTEM = "system"
SINGLE = "single"
RAID0 = "raid0"
RAID1 = "raid1"
RAID10 = "raid10"
D... | eturn self.fd
class BTRFS(AgentCheck):
def __init__(self, name, init_config, agentConfig, instances=None):
AgentCheck.__init__(self, name, init_c | onfig, agentConfig, instances=instances)
if instances is not None and len(instances) > 1:
raise Exception("BTRFS check only supports one configured instance.")
def get_usage(self, mountpoint):
results = []
with FileDescriptor(mountpoint) as fd:
# Get the struct siz... |
thomasquintana/freepy | freepy/lib/actors/errors.py | Python | apache-2.0 | 1,220 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | T WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# Thomas Quintana <quintana.thomas@gmail.com>
CLASS_REGISTRATION_CONFLICT = "The actor %s has already been registered as " \
... | "a singleton actor."
INSTANCE_REGISTRATION_CONFLICT = "The actor %s has already been registered " \
"as a non singleton actor."
INVALID_ACTOR_CLASS = "The class %s is not a subclass of " \
"'freepy.lib.actors.actor.Actor'."
|
votervoice/openstates | openstates/ut/bills.py | Python | gpl-3.0 | 16,082 | 0.001181 | import re
import datetime
from pupa.scrape import Scraper, Bill, VoteEvent as Vote
from openstates.utils import LXMLMixin
import lxml.html
import scrapelib
SUB_BLACKLIST = [
"Second Substitute",
"Third Substitute",
"Fourth Substitute",
"Fifth Substitute",
"Sixth Substitute",
"Seventh Substit... | oc.xpath('//a[text()="Numbered Bills" and contains'
'(@href, "DynaBill/BillList")]/@href')
if replacement_session_url:
(session_url, ) = replacement_session_url
# Identify all the bill lists linked from a given session's page
bill_indices ... | of the bill lists
for bill_index in bill_indices:
if bill_index.startswith("H"):
chamber = 'lower'
elif bill_index.startswith("S"):
chamber = 'upper'
else:
raise AssertionError(
"Unknown bill type found: {}".... |
eviljeff/zamboni | sites/dev/settings_mkt.py | Python | bsd-3-clause | 5,258 | 0 | """private_mkt will be populated from puppet and placed in this directory"""
from mkt.settings import * # noqa
from settings_base import * # noqa
import private_mkt
DOMAIN = 'marketplace-dev.allizom.org'
SERVER_EMAIL = 'zmarketplacedev@addons.mozilla.org'
SITE_URL = 'https://marketplace-dev.allizom.org'
BROWSERID... | vate_mkt.WEBAPPS_RECEIPT_URL
WEBAPPS_UNIQUE_BY_DOMAIN = False
SENTRY_DSN = private_mkt.SENTRY_DSN
WEBAPPS_PUBLIC_KEY_DIRECTORY = NETAPP_STORAGE + '/public_keys'
PRODUCT_ICON_PATH = NETAPP_STORAGE + '/product-icons'
DUMPED_APPS_PATH = NETAPP_STORAGE + '/dumped-apps'
DUMPED_USERS_PATH = NETAPP_STORAGE + '/dumped-users... | t.SOLITUDE_OAUTH_SECRET}
VALIDATOR_TIMEOUT = 180
VALIDATOR_IAF_URLS = ['https://marketplace.firefox.com',
'https://marketplace.allizom.org',
'https://marketplace-dev.allizom.org']
# Override the limited marketplace ones with these ones from AMO. Because
# the base gets over... |
urbansearchTUD/UrbanSearch | tests/server/test_classify_documents.py | Python | gpl-3.0 | 3,035 | 0.000988 | from flask import json
from unittest.mock import patch, Mock
from urbansearch.gathering.indices_selector import IndicesSelector
from urbansearch.server.main import Server
from urbansearch.server import classify_documents
from urbansearch.server.classify_documents import _join_workers
from urbansearch.workers import Wo... | assert mock_rw.called
assert mock_jw.called
@patch('urbansearch.server.classify_documents._join_workers')
@patch.object(Workers, 'run_classifying_workers')
@patch.object(IndicesSelector, 'run_workers')
def test_classify_indices_to_db(mock_rcw, mock_rw, mock_jw):
with s.app.test_client() as c:
r... | ?directory=test')
assert mock_rcw.called
assert mock_rw.called
assert mock_jw.called
@patch('urbansearch.server.classify_documents._join_workers')
@patch('urbansearch.server.classify_documents.db_utils')
def test_classify_indices_to_db_no_connection(mock_db, mock_jw):
mock_db.connected_to... |
harvardinformatics/hex | hex/__init__.py | Python | gpl-2.0 | 1,265 | 0.003162 | """
@date : 2017-06-20 13:11:20
@author : Aaron Kitzmiller (aaron_kitzmiller@harvard.edu)
@cersion : $Id$
@copyright : 2017 The Presidents and Fellows of Harvard College. All rights reserved.
"""
import logging
from .config import Config
__version__ = "0.2.0"
DEFAULT_PDEF_PATH = "./config"
logging.basicConfig()
c... | m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
except ImportError:
return None
class UserException(Exception):
"""
Exceptions for known user errors
"""
def __init__( | self,message):
super(UserException,self).__init__(message)
self.user_msg = message
# __all__ = []
# import pkgutil
# import inspect
# for loader, name, is_pkg in pkgutil.walk_packages(__path__):
# module = loader.find_module(name).load_module(name)
# for name, value in inspect.getmembers(mo... |
aristanetworks/arista-ovs-nova | nova/virt/xenapi/firewall.py | Python | apache-2.0 | 4,708 | 0.000425 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you m... | None
else:
icmp_type_arg = '%s' % icmp_type
if not icmp_code == -1:
icmp_type_arg += '/%s' % icmp_code
if icmp_type_arg:
if version == 4:
args += ['-m', 'icmp', '--icmp-type',
... | args += ['-m', 'icmp6', '--icmpv6-type',
icmp_type_arg]
args += ['-j DROP']
fw_rules += [' '.join(args)]
return ipv4_rules, ipv6_rules
|
safwanrahman/linuxdesh | kitsune/search/urls.py | Python | bsd-3-clause | 337 | 0 | from django.conf.urls import patterns, url |
urlpatterns = patterns(
'kitsune.search.views',
url(r'^$', 'simple_search', name='search'),
url(r'^/advanced$', 'advanced_search', name='search.advanced'),
url(r'^/xml$', 'plugin', name='search.plugin'),
url(r'^/suggestions$', 'suggestions', name='search.suggestion | s'),
)
|
MizukiSonoko/iroha-cli | iroha_cli/libs/amount.py | Python | apache-2.0 | 1,298 | 0.006934 | from primitive_pb2 import Amount, uint256
UINT64_NUMBER = int(18446744073709551616)
def amount_to_int(amount):
"""
Translater Protobuf Amount -> python int type
Args:
amount ( `Amount` ) : protobuf amount type ( don't care precision )
Returns:
int: int value equal to arg amount.
""... | t structure equal to int_num
"""
value = uint256()
value.fourth = int(int_num % UINT64_NUMBER)
int_num //= UINT64_NUMBER
value.third = int(int_num % UINT64_NUMBER)
int_num //= UINT64_NUMBER
value.second = int(int_num % UI | NT64_NUMBER)
int_num //= UINT64_NUMBER
value.first = int(int_num)
return Amount(
value = value,
precision = precision
)
|
caseyching/Impala | common/function-registry/impala_functions.py | Python | apache-2.0 | 54,160 | 0.006001 | # Copyright 2012 Cloudera 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 writing, so... | int'], 'BIGINT', [],
'_ZN6impala11UdfBuiltins9MinBigIntEPN10impala_udf15FunctionContextE'],
[['is_nan'], 'BO | OLEAN', ['DOUBLE'],
'_ZN6impala11UdfBuiltins5IsNanEPN10impala_udf15FunctionContextERKNS1_9DoubleValE'],
[['is_inf'], 'BOOLEAN', ['DOUBLE'],
'_ZN6impala11UdfBuiltins5IsInfEPN10impala_udf15FunctionContextERKNS1_9DoubleValE'],
[['trunc'], 'TIMESTAMP', ['TIMESTAMP', 'STRING'],
'_ZN6impala11UdfBuiltins5TruncEPN... |
CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_rrbs/trackers/M3D.py | Python | mit | 402 | 0 | from CGATReport.Tracker import *
from rrbsReport import *
class M3DSum | maryTable(RrbsTracker):
# pattern = "^summary_table$"
def __call__(self, track, slice=None):
statement = '''
SELECT group1 as Group_1, group2 as Group_2,
total as Total, significant as Significant_Clusters
FROM summary_table
''' % locals()
return self.getAll(s... | |
tylertian/Openstack | openstack F/python-novaclient/novaclient/v1_1/flavors.py | Python | apache-2.0 | 5,790 | 0.000173 | # Copyright 2010 Jacob Kaplan-Moss
"""
Flavor interface.
"""
from novaclient import base
from novaclient import exceptions
from novaclient import utils
from novaclient.openstack.common.py3kcompat import urlutils
class Flavor(base.Resource):
"""
A flavor is an available hardware configuration for a server.
... | :
raise exceptions.CommandError("Ephemeral must be an integer.")
try:
rxtx_factor = float(rxtx_factor)
except (Ty | peError, ValueError):
raise exceptions.CommandError("rxtx_factor must be a float.")
try:
is_public = utils.bool_from_str(is_public)
except Exception:
raise exceptions.CommandError("is_public must be a boolean.")
body = {
"flavor": {
... |
socillion/exchangelib | btce/__init__.py | Python | mit | 61 | 0.016393 | #!/usr/b | in/env python
from exchangelib. | btce.data_v3 import * |
aforren1/toon | tests/input/test_mpdevice.py | Python | mit | 4,589 | 0.000436 | from time import sleep
from pytest import raises, approx
import numpy as np
from tests.input.mockdevices import (Dummy, Timebomb, DummyList,
SometimesNot, StructObs, Incrementing,
NoData, NpStruct)
from toon.util import mono_clock
from toon.input... | print(np.diff(time))
print(data.shape)
assert(data.shape[0] > 10)
assert(data.shape[0] == time.shape[0])
def test_err():
dev = MpDevice(Timebomb())
with dev:
sleep(0.2)
with raises(ValueError):
dat = dev.read()
def test_list():
dev = MpDevice(DummyList())
wit... | s():
dev = MpDevice(SometimesNot())
with dev:
sleep(0.2)
time, data = dev.read()
print(data.shape)
assert(data.shape[0] > 10)
assert(data.shape[0] == time.shape[0])
def test_struct():
dev = MpDevice(StructObs())
with dev:
sleep(0.2)
time, data = dev.read()
... |
tsl143/addons-server | src/olympia/accounts/urls.py | Python | bsd-3-clause | 1,619 | 0 | from django.conf.urls import include, url
from rest_framework.routers import SimpleRouter
from rest_framework_nested.routers import NestedSimpleRouter
from olympia.bandwagon.views import CollectionViewSet, CollectionAddonViewSet
from . import views
accounts = SimpleRouter()
accounts.register(r'account', views.Acco... | $',
views.LoginStartView.as_view(),
name='accounts.login_start'),
url(r'^session/$', views.SessionView.as_view(),
name='accounts.session'),
url(r'', include(accounts.urls)),
url(r'^profi | le/$', views.ProfileView.as_view(), name='account-profile'),
url(r'^super-create/$', views.AccountSuperCreate.as_view(),
name='accounts.super-create'),
url(r'', include(collections.urls)),
url(r'', include(sub_collections.urls)),
url(r'', include(notifications.urls)),
]
|
OpenNewsLabs/pybossa | test/test_model/test_model_task.py | Python | agpl-3.0 | 1,833 | 0.001637 | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa 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... | ask
from pybossa.model.category import Category
class TestModelTask(Test):
@with_context
def test_task_errors(self):
"""Test TASK model errors."""
user = User(
email_addr="john.doe@example.com",
name="johndoe",
| fullname="John Doe",
locale="en")
db.session.add(user)
db.session.commit()
user = db.session.query(User).first()
category = Category(name=u'cat', short_name=u'cat', description=u'cat')
project = Project(name='Application', short_name='app', description='desc',
... |
fukukami/electrum-exe-stealth | lib/network.py | Python | gpl-3.0 | 13,813 | 0.007819 | import threading, time, Queue, os, sys, shutil, random
from util import user_dir, appdata_dir, print_error, print_msg
from bitcoin import *
import interface
from blockchain import Blockchain
DEFAULT_PORTS = {'t':'50011', 's':'50012', 'h':'8181', 'g':'8282'}
DEFAULT_SERVERS = {
'server.electrum-exe.org': DEFAULT_P... | self.interface.send(sub, cb)
def subscribe(self, messages, callback):
with self.lock:
if self.subscriptions.get(callback) is None:
self.subscriptions[callback] = []
for message in messages:
| if message not in self.subscriptions[callback]:
self.subscriptions[callback].append(message)
if self.is_connected():
self.interface.send( messages, callback )
def send(self, messages, callback):
if self.is_connected():
self.interface.send( messag... |
luispedro/pymorph | docs/source/conf.py | Python | bsd-3-clause | 6,193 | 0.006459 | # -*- coding: utf-8 -*-
#
# pymorph documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 26 15:03:10 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't picklea... | alues that are commented out
# serve to show the default.
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'numpydoc',
'sphinx.ext.intersphinx', 'sphinx.ext.coverage',
'sphinx.ext.doctest',]
# If your extensions (or modules documented by autodoc) are in a | nother directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# General configuration
# ---------------------
# Add any paths that contain templates here, relative t... |
HiSPARC/station-software | user/python/Lib/test/test_turtle.py | Python | gpl-3.0 | 12,577 | 0.000875 | import pickle
import unittest
from test import test_support as support
turtle = support.import_module('turtle')
Vec2D = turtle.Vec2D
test_config = """\
width = 0.75
height = 0.8
canvwidth = 500
canvheight = 200
leftright = 100
topbottom = 100
mode = world
colormode = 255
delay = 100
undobuffersize = 10000
shape = cir... | 0), (1, 1)), (2.5, 1)),
]
self._assert_arithmetic_cases(test_cases, lambda x, y: x + y)
def test_vector_sub | traction(self):
test_cases = [
(((0, 0), (1, 1)), (-1, -1)),
(((10.625, 0.125), (10, 0)), (0.625, 0.125)),
]
self._assert_arithmetic_cases(test_cases, lambda x, y: x - y)
def test_vector_multiply(self):
vec1 = Vec2D(10, 10)
vec2 = Vec2D(0.5, 3)
... |
whereismyjetpack/ansible | lib/ansible/modules/network/nxos/nxos_nxapi.py | Python | gpl-3.0 | 9,509 | 0.00326 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distribut... | lable.
required: false
default: no
choices: ['yes', 'no']
aliases: ['enable_sandbox']
state:
description:
- The C(state) argument controls whether or not the NXAPI
fe | ature is configured on the remote device. When the value
is C(present) the NXAPI feature configuration is present in
the device running-config. When the values is C(absent) the
feature configuration is removed from the running-config.
choices: ['present', 'absent']
required: false
... |
thebarbershopper/Empire | lib/common/messages.py | Python | bsd-3-clause | 14,148 | 0.01145 | """
Common terminal messages used across Empire.
Titles, agent displays, listener displays, etc.
"""
import os, sys, textwrap
# Empire imports
# from helpers import *
# from lib.common.helpers import *
from helpers import *
###############################################################
#
# Messages
#
##########... | tions:")
headers = ['Name', 'Required', 'Value', 'Description']
data = []
for option,values in options.it | eritems():
# if there's a long value length, wrap it
data.append([option, values.get('Required', 'False'), values.get('Value'), values.get('Description', '')])
# if len(str(values['Value'])) > 33:
# print " %s%s%s" % ('{0: <18}'.format(option), '{0: <12}'.format(("True" if values['R... |
patriksletmo/podio-mirror | podiomirror/transactions/relation_transaction.py | Python | mit | 836 | 0.001196 | import json
from podiomirror.transactions.transaction import Transaction
class RelationTransaction(Transaction):
def __init__(self, transaction_type, app_id=N | one, field_id=None, parent_id=None, child_id=None):
super().__init__(transaction_type)
self.app_id = app_id
self.field_id = field_id
self.parent_id = parent_id
self.child_id = child_id
def serialize(self):
return json.d | umps({
'app_id': self.app_id,
'field_id': self.field_id,
'parent': self.parent_id,
'child': self.child_id
})
def deserialize(self, json_data):
data = json.loads(json_data)
self.app_id = data['app_id']
self.field_id = data['field_id']
... |
FernFerret/demobrowser | run.py | Python | mit | 379 | 0.005277 | #!/usr/bin/env pytho | n
from demobrowser import app, db
#db.drop_all()
db.create_all()
app.debug = app.config.get('DEBUG', False)
# This is required.
app.secret_key = app.confi | g.get('SECRET_KEY', None)
if app.secret_key is None:
print "ERROR: SECRET_KEY not found in settings.cfg. Please see README.md for help!"
else:
app.run(host=app.config.get('ADDRESS', '0.0.0.0'))
|
cfelton/rhea | test/test_cores/test_sdram/test_sdram.py | Python | mit | 3,406 | 0.001468 |
from __future__ import print_function, division
from argparse import Namespace
from random import randint
import myhdl
from myhdl import instance, delay, StopSimulation
from rhea import Clock, Reset, Global
from rhea.system import Wishbone
from rhea.cores.sdram import SDRAMInterface
from rhea.cores.sdram import sd... | read_data = ixbus.get_read_data()
assert read_data == data, "{:08X} != {:08X}".format(read_data, data)
yield delay(20*1000)
# verify all the addresses have the last written data
for addr, data in saved_addr_data.items():
yield ixb... | for ii in range(10):
yield delay(1000)
except AssertionError as err:
# if test check fails about let the simulation run more cycles,
# useful for debug
yield delay(20000)
raise err
raise StopSimulatio... |
sleepywhiskey/bestoon | web/migrations/0001_initial.py | Python | gpl-3.0 | 908 | 0.002203 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-28 10:25
from __future__ import unicode_literals
from django.conf import settings
from djang | o.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Expense',
fields=[... | ('date', models.DateTimeField()),
('amount', models.BigIntegerField()),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
Nextpertise/autorsyncbackup | src/lib/statusemail.py | Python | gpl-3.0 | 11,943 | 0.000084 | import datetime
from jinja2 import Environment, PackageLoader
from mailer import Mailer, Message
from models.config import config
from models.jobrunhistory import jobrunhistory
from lib.jinjafilters import jinjafilters
from lib.logger import logger
class statusemail():
jobrunhistory = None
history = None
... | ]:
addto = bad
ret = "error"
job_history['commanderror'] = 'ok'
if ret == "ok":
for c in job_history['commands']:
if c['returncode'] != 0 and not c['continueonerror']:
addto = bad
... | job_history['commanderror'] = "warning"
ret = "warning"
addto.append(job_history)
if not self.history:
ret = "error"
else:
self.history = bad + warning + good
return ret, good, warning, bad
def getBackupHost... |
SickGear/SickGear | lib/hachoir_py3/parser/misc/hlp.py | Python | gpl-3.0 | 2,932 | 0.001364 | """
Microsoft Windows Help (HLP) parser for Hachoir project.
Documents:
- Windows Help File Format / Annotation File Format / SHG and MRB File Format
written by M. Winterhoff (100326.2776@compuserve.com)
found on http://www.wotsit.org/
Author: Victor Stinner
Creation date: 2007-09-03
"""
from hachoir_py3.parser ... | ler, humanFilesize)
class FileEntry(FieldSet):
def __init__(self, *args, **kw):
FieldSet.__init__(self, *args, **kw)
self._size = self["res_space"].value * 8
def createFields(self):
yield displayHandler(UInt32(self, "res_space", "Reserved space"), humanFilesize)
yield display... |
yield Bits(self, "flags", 16)
yield displayHandler(UInt16(self, "page_size", "Page size in bytes"), humanFilesize)
yield String(self, "structure", 16, strip="\0", charset="ASCII")
yield NullBytes(self, "zero", 2)
yield UInt16(self, "nb_page_splits", "Number of page splits B+ tre... |
grahesh/Stock-Market-Event-Analysis | qstkfeat/features.py | Python | bsd-3-clause | 19,635 | 0.013242 | '''
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
Created on Nov 7, 2011
@author: John Cornwell
@contact: JohnWCornwellV@gmail.com
@summary: File containing various fea... | du.getNextOptionClose(today, tsPrice.index)
#get days between
| days_between = next_close - last_close
#get days since last close
days = today - last_close
# multiply by 2, divide by 365, subtract 1
tsRet[i] = float(days.days * 2) / days_between.days - 1
return dfRet
def featMA( dData, lLook... |
nth10sd/funfuzz | src/funfuzz/bot.py | Python | mpl-2.0 | 11,394 | 0.00316 | # coding=utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""Ensures a build is available, then forks a bunch of fuzz-reduce processes.
"""
import io
import m... | ("--timeout", type="int", dest="timeout",
help="Sets the timeout for loop. "
"Defaults to taking into account the speed of the computer and debugger (if any).")
| options, args = parser.parse_args()
if args:
print("Warning: bot does not use positional arguments")
if not options.useTreeherderBuilds and not build_options.DEFAULT_TREES_LOCATION.is_dir():
# We don't have trees, so we must use treeherder builds.
options.useTreeherderBuilds = True
... |
symbooglix/boogie-runner | BoogieRunner/Analysers/AnalyserBase.py | Python | bsd-3-clause | 1,536 | 0.010417 | # vim: set sw=2 ts=2 softtabstop=2 expandtab:
import abc
class AnalyserBaseClass(metaclass=abc.ABCMeta):
def __init__(self, resultDict):
# Quick sanity checks
assert isinstance(resultDict, dict)
assert 'exit_code' in resultDict
assert 'log_file' in resultDict
assert 'out_of_memory' in resultDict
... | @property
def ranOutOfMemory(self):
return self._resultDict['out_of_memory']
@property
def ranOutOfTime(self):
return | self._resultDict['backend_timeout']
def getAnalysesDict(self):
"""
Returns a dictionary of the results of
Analyser analyses. Subclasses should override
this if they provide additional analyses.
"""
results = self._resultDict
results['bug_found'] = self.foundBug
results['failed']... |
qiudebo/13learn | code/stat/stat_random.py | Python | mit | 1,303 | 0.001063 | # -*- coding: utf-8 -*-
import numpy as np
import numpy.random as random
# 设置随机数种子
random.seed(42)
# 产生一个1x3,[0,1)之间的浮点型随机数
# array([[ 0.37454012, 0.95071431, 0.73199394]])
# 后面的例子就不在注释中给出具体结果了
random.rand(1, 3)
# 产生一个[0,1)之间的浮点型随机数
random.random()
# 下边4个没有区别,都是按照指定大小产生[0,1)之间的浮点型随机数array
random... | 随机bytes序列并作为str返回
# '\x96\x9d\x | d1?\xe6\x18\xbb\x9a\xec'
random.bytes(9) |
dpo/opal | setup.py | Python | lgpl-3.0 | 495 | 0.00404 | from distutils.core import setup
setup(name='OPAL - OPtimization of ALgorithm',
version='1.3',
desc | ription='Algorithmic Parameter Optimization',
author='Charles Audet, Cong-Kien | Dang, Dominique Orban',
author_email='cong-kien.dang@polymtl.ca',
url='http://www.gerad.ca/~kiendc/build/hmtl',
packages=['opal',
'opal.core',
'opal.Platforms',
'opal.Solvers',
'opal.TestProblemCollections']
)
|
johntauber/MITx6.00.2x | Unit4/Lecture10Video1Notes.py | Python | mit | 1,486 | 0.015478 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 19 11:45:20 2016
@author: johnguttag
"""
import random, pylab, numpy
#set line width
pylab.rcParams['lines.linewidth'] = 4
#set font size for titles
pylab.rcParams['axes.titlesize'] = 20
#set font size for labels on axes
pylab.rcParams['axes.labelsize'] = 20
#set size ... | umbers on y-axis
pylab.rcParams['ytick.labelsize'] = 16
#set size of ticks on x-axis
pylab.rcParams['xtick.major.size'] = 7
#set size of ticks on y-axis
pylab.rcParams['ytick.major.size'] = 7
#set size of markers
pylab.rcParams['lines.markersize'] = 10
#set number of exam | ples shown in legends
pylab.rcParams['legend.numpoints'] = 1
def getData(fileName):
dataFile = open(fileName, 'r')
distances = []
masses = []
dataFile.readline() #discard header
for line in dataFile:
d, m = line.split()
distances.append(float(d))
masses.append(float(m))
... |
webostin/django-btc | tests/update_only_fields/tests.py | Python | bsd-3-clause | 9,780 | 0.001125 | from __future__ import unicode_literals
from django.db.models.signals import pre_save, post_save
from django.test import TestCase
from .models import Person, Employee, ProxyEmployee, Profile, Account
class UpdateOnlyFieldsTests(TestCase):
def test_update_fields_basic(self):
s = Person.objects.create(nam... | r='F',
employee_num=1, profile=profile_boss)
e1.name = 'Ian'
e1.gender = 'M'
e1.save(update_fields=['name'])
e2 = ProxyEmployee.objects.get(pk=e1.pk)
self.assertEqual(e2.name, 'Ian')
self.assertEqual(e2.gender, 'F')
self.assertEqual(e2.profile, profi... | oxyEmployee.objects.get(pk=e1.pk)
self.assertEqual(e3.name, 'Ian')
self.assertEqual(e3.profile, profile_receptionist)
def test_update_fields_signals(self):
p = Person.objects.create(name='Sara', gender='F')
pre_save_data = []
def pre_save_receiver(**kwargs):
pre... |
emotrix/Emotrix | emotrix/helpers.py | Python | bsd-2-clause | 934 | 0 | # -*- coding: utf-8 -*-
import m | ath
import random
def average(data):
return sum(data) * 1.0 / len(data)
def variance(data):
avg = average(data)
var = map(lambda x: (x - avg)**2, data)
return average(var)
def standard_deviation(data):
return math.sqrt(variance(data))
def get_variance_range(n, m, amplt):
| """
Gets an approximation of the bounds for the variance of a data set
whose amplitude is amplt.
The algorithm generates n random values betwen 0 and amplt. Over
this n random values, calculates the variance. Then, it repeats this
process m times and finally, gets the minimun and maximum calcul... |
alex-tug/conquer | gamemenu.py | Python | gpl-3.0 | 11,388 | 0.002986 | import pygame
from vec_2d import Vec2d
import time
from types import *
from graphics_helper import Plotter
#------------------------------------------------------------------------
#
# This file is part of Conquer.
#
# Conquer is free software: you can redistribute it and/or modify
# it under the terms of th... | innable colors
# Menu item color is white
cur_color = (0, 0, 0)
shadow = True
if i == self.pos:
# Selected menu item is red
shadow = False
cur_color = (255, 0, 0) |
# Text to be rendered
text = item_i[0]
# Check if menu items are value editors
if len(item_i[2]) >= 2:
if item_i[2][0] == "value_int_editor":
text = "%s (%d)" % (text, item_i[2][1])
if item_i[2][0] == "value_bool_editor... |
darrenbilby/grr | endtoend_tests/__init__.py | Python | apache-2.0 | 724 | 0 | #!/usr/bin/env python
"""End to end tests that run flows on actual clients."""
from grr.endtoend_tests import administrative
from grr.endtoend_tests import artifacts
from grr.endtoend_tests import base
from grr.endtoend_tests import checks
from grr.endtoend_tests import collectors
from grr.endtoend_tests import discov... | rr.endtoend_tests import filesystem
from grr.endtoend_tests import fingerprint
from | grr.endtoend_tests import grep
from grr.endtoend_tests import limits
from grr.endtoend_tests import memory
from grr.endtoend_tests import network
from grr.endtoend_tests import processes
from grr.endtoend_tests import registry
from grr.endtoend_tests import transfer
|
ff0000/django-sortable | sortable/models.py | Python | mit | 554 | 0.001805 | from django.db import models
| class Sortable(models.Model):
# Make instances reorderable
position = models.IntegerField(default=0)
def save(self, *args, **kwargs):
model = self.__class__
if self.position is None:
try:
last = model.objects.order_by('-position')[0]
self.position... | lass Meta:
abstract = True
ordering = ('position',)
|
anish/buildbot | master/buildbot/test/unit/test_data_forceschedulers.py | Python | gpl-2.0 | 7,609 | 0 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | 'maxsize': None,
'multiple': False,
'name': 'repository',
'regex': None,
'required': False,
'size': 10,
... | 'autopopulate': None,
'fullName': 'revision',
'hide': False,
'label': 'Revision:',
'maxsize': None,
'multiple': False,
'nam... |
tiagochiavericosta/edx-platform | common/djangoapps/student/tests/test_create_account.py | Python | agpl-3.0 | 20,139 | 0.002036 | """Tests for account creation"""
import json
import ddt
import unittest
from django.contrib.auth.models import User
from django.test.client import RequestFactory
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser
from django.utils.importli... | ofile | .get_meta(),
{
"extra1": "extra_value1",
"extra2": "extra_value2",
}
)
self.assertEqual(profile.year_of_birth, 2015)
@unittest.skipUnless(
"microsite_configuration.middleware.MicrositeMiddleware" in settings.MIDDLEWARE_CLASSES,
... |
NickShaffner/rhea | test/test_system/test_memmap_command_bridge.py | Python | mit | 4,179 | 0.000239 |
"""
Test and verify the memory-mapped command bridge (memmap_command_bridge).
Unlike the actual designs this test does not use a generic peripheral
but instead a specific peripheral / slave is used for each bus type,
other tests verify the generic ability.
"""
from __future__ import print_function, division
from ra... | ripheral_bb(clock, reset, bb):
""" Emulate Barebone memory-mapped reads and writes"""
assert isinstance(b | b, Barebone)
mem = {}
@always_seq(clock.posedge, reset=reset)
def beh_writes():
addr = int(bb.address)
bb.done.next = not (bb.write or bb.read)
if bb.write:
mem[addr] = int(bb.write_data)
@always_comb
def beh_reads():
addr = int(bb.address)
if bb... |
hadron-powered/si-site | si_site/util/i18n.py | Python | gpl-3.0 | 558 | 0 | from werkzeug.http import parse_accept_header
class I18NString:
default_lang = 'en'
def | __init__(self, default_lang='en', **kwargs):
self.default_lang = default_lang
self.translations = kwargs
def __ge | titem__(self, item):
return self.translations[item]
def parse_accept_language_header(value, default=(I18NString.default_lang,)):
try:
result = parse_accept_header(value)
result = [x[0].split('-', 1)[0] for x in result if x[0]]
return result
except IndexError:
return def... |
tugot17/Introduction-to-Algorithms | Algorithms/Sorts/InsertionSort.py | Python | bsd-2-clause | 325 | 0.009231 | class InsertionSort:
def sort(self, ar | ray):
length = len(array)
for j in range (1, length):
key = array[j]
i = j-1
while (i >=0) & (array[i] > key):
array[i+1] = array[i]
i = i-1
| array[i + 1] = key
return array
|
jkleckner/ansible | lib/ansible/runner/lookup_plugins/csvfile.py | Python | gpl-3.0 | 2,647 | 0.003022 | # (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com>
#
# This file is part of Ansible
#
# Ansible 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 ver... | ll be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for mor | e details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from ansible import utils, errors
import os
import codecs
import csv
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = b... |
fstagni/DIRAC | WorkloadManagementSystem/Agent/test/Test_Agent_SiteDirector.py | Python | gpl-3.0 | 9,622 | 0.011016 | """ Test class for SiteDirector
"""
# pylint: disable=protected-access
# imports
import datetime
import pytest
from mock import MagicMock
from DIRAC import gLogger
# sut
from DIRAC.WorkloadManagementSystem.Agent.SiteDirector import SiteDirector
mockAM = MagicMock()
mockGCReply = MagicMock()
mockGCReply.return_valu... | SiteDirector.CSGlobals.getSetup", side_effect=mockCSGlobalReply)
mocker.patch("DIRAC.WorkloadManag | ementSystem.Agent.SiteDirector.AgentModule", side_effect=mockAM)
sd = SiteDirector()
sd.log = gLogger
sd.am_getOption = mockAM
sd.log.setLevel('DEBUG')
sd.matcherClient = MagicMock()
sd.matcherClient.getMatchingTaskQueues.return_value = mockMatcherReturnValue
res = sd._ifAndWhereToSubmit()
assert res[0]... |
roxana-lafuente/POCs | random/exam_practice.py | Python | gpl-3.0 | 995 | 0.003015 | topic = "german"
definitions = {
"articles": [("Mann", "der"), ("Frau", "die")]
}
# Show options
print "Welcome | to the %s training center!" % topic
print "\nAvailable units are:"
for k in definitions.keys():
print "* %s" % k
# Get option
unit = raw_input("\nSelect which unit you would like to practice: | \n")
ok_answers = 0
i = 0
if unit in definitions.keys():
total = len(definitions[unit])
print "\nStarting testing mode."
for question, correct_answer in definitions[k]:
i += 1
answer = raw_input("Question %d out of %d: %s %s\n" % (i, total, "_" * len(correct_answer), question))
if a... |
openjck/kuma | kuma/wiki/models.py | Python | mpl-2.0 | 71,106 | 0.000197 | import hashlib
import json
import sys
import traceback
from datetime import datetime, timedelta
from functools import wraps
import newrelic.agent
import waffle
from constance import config
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.db.mo... | TaggedDocumentManager, TransformManager)
from .search import WikiDocumentType
from .signals import render_done
from .templatetags.jinja_helpers import absolutify
from .utils import tidy_content
def cache_with_field(field_name):
"""Decorator for generated content methods.
If the backing model field is null,... | |
wavefront-mike/python-client | wavefront_client/models/dashboard_metadata.py | Python | apache-2.0 | 12,375 | 0.000889 | # coding: utf-8
"""
Copyright 2016 SmartBear Software
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 applica... | iption = False
self._display_query_parameters = False
self._display_section_table_of_contents = False
self._is_favorite = False
self._last_update_time = None
sel | f._name = None
self._num_charts = None
self._num_favorites = None
self._trash = False
self._url = None
self._user_tags_with_counts = None
@property
def customer_tags_with_counts(self):
"""
Gets the customer_tags_with_counts of this DashboardMetadata.
... |
lerouxb/ni | editors/base/settings.py | Python | mit | 4,527 | 0.001546 | import os
import codecs
from ni.core.workspace import load_workspace
def load_settings_from_file(filename, klass):
settings = klass(filename)
try:
fle = open(filename)
try:
fields = set(settings.fields)
for line in fle.readlines():
try:
... | validators
def _val_indent_width(self, value):
value = int(value)
if not value in (2, 4, 6, 8):
raise Exception()
return value
def _val_tab_size(self, value):
value = int(value)
if not value in (2, 4, 6, 8):
raise Exception()
return valu... | , 'True')
def _val_file_encoding(self, value):
encoder = codecs.getencoder(value)
return value
def _val_linesep(self, value):
value = value.replace('\\n', '\n').replace('\\r', '\r')
if not value in ('\n', '\r', '\r\n'):
raise Exception()
return value
de... |
axinging/chromium-crosswalk | build/android/pylib/local/device/local_device_instrumentation_test_run.py | Python | bsd-3-clause | 11,330 | 0.009885 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import re
import time
from devil.android import device_errors
from devil.android import flag_changer
from devil.utils import rerais... | raise Exception('driver_apk does not exist. '
'Please build it and try again.')
def name_and_timeout(t):
n = self._GetTestName(t)
i = self._GetTimeoutFromAnnotations(t['annotations'], n)
return (n | , i)
test_names, timeouts = zip(*(name_and_timeout(t) for t in test))
test_name = ','.join(test_names)
test_display_name = test_name
target = '%s/%s' % (
self._test_instance.driver_package,
self._test_instance.driver_name)
extras.update(
self._test_instance.... |
essamjoubori/girder | plugins/oauth/server/providers/__init__.py | Python | apache-2.0 | 1,071 | 0.000934 | #!/usr/bin/env python
# -* | - coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 a | t
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gover... |
googleapis/python-test-utils | tests/unit/resources/bad_package/setup.py | Python | apache-2.0 | 1,256 | 0 | # Copyright 2021 Google LLC
#
# 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 writing, s... | classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
install_requires=requirements,
packages=setuptools.find_packa | ges(),
python_requires=">=3.6",
)
|
poremchuk/RefactorDMS | system/views.py | Python | gpl-3.0 | 98 | 0.010204 | from django.shortcuts import render
def index(request):
return ren | der(request, 'first.html') | |
praekelt/go-imali-yethu-js | python_scripts/ona.py | Python | bsd-3-clause | 2,303 | 0 | import json
import requests
class OnaApiClient(object):
"""
Client for Ona's API
:param string username: The username to log into Ona with.
:param string password: The password to log into Ona with.
:param string url:
The full URL of the Ona API. Defaults to ``https://ona.io/api/v1``.
... | rs)
r.raise_for_status()
return r.json()
def forms(self):
"""
Retrieve all forms. |
"""
return self._api_request("GET", "forms", "")
def get_form(self, formid):
"""
Retrieve a form with form ID ``formid``
"""
return self._api_request("GET", "forms", str(formid))
def get_form_information(self, formid):
"""
Retrieve all the form ... |
Wladislao/Python_Problems | 3xxx/34xx/345x/3451.py | Python | gpl-2.0 | 39 | 0 | print | ((int((str | (179**10))*4))**(1/10))
|
duahimanshu100/credit_computing_machine | credit_computing_machine/privateurl/migrations/0001_initial.py | Python | mit | 2,388 | 0.004606 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-21 06:33
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dep... | 'private url',
'verbose_name_plural': 'private urls',
'db_table': 'privateurl_privateurl',
'ordering': ('-created',),
},
),
migrati | ons.AlterUniqueTogether(
name='privateurl',
unique_together=set([('action', 'token')]),
),
]
|
unreal666/outwiker | src/test/core/test_treeloading.py | Python | gpl-3.0 | 16,335 | 0.00301 | # -*- coding: utf-8 -*-
import os.path
import unittest
from tempfile import mkdtemp
from outwiker.core.application import Application
from outwiker.core.attachment import Attachment
from outwiker.core.tree import WikiDocument
from outwiker.core.config import StringOption
from outwiker.pages.text.textpage import Text... | oin(self.path, "Страница 1")
fullpath = os.path.join(fullpath, "Страница 2")
self.assertEqual(self.root["Страница 1/Страница 2"].path, fullpath)
def testTags(self):
self.assertTrue("тест" in self.root["Страница 1"].tags)
self.assertTrue("test" in self.root["Страница 1"].tags, self.... | (len(self.root["Страница 1"].tags), 3)
self.assertTrue("test" in self.root["Страница 1/Страница 2"].tags)
self.assertEqual(len(self.root["Страница 1/Страница 2"].tags), 1)
self.assertTrue("test" in self.root["Страница 3"].tags)
self.assertTrue("тест" in self.root["Страница 3"].tags)
... |
lheagy/simpegem | docs/conf.py | Python | mit | 7,885 | 0.007483 | # -*- coding: utf-8 -*-
#
# SimPEG documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 30 18:42:44 2013.
#
# This file is execfile()d with the current directory set to its containing dir. |
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories ... | append('../')
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or y... |
tensorflow/tensorflow | tensorflow/python/kernel_tests/collective_ops_multi_worker_test.py | Python | apache-2.0 | 12,067 | 0.006464 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applicab... | self):
def worker_fn():
enable_collective_ops(cluster_resolver_lib.TFConfigClusterResolver())
# There may be some delays before the server startup. Check health should
# eventually be OK.
while True:
try:
for task in [
"/job:worker/replica:0/task:0",
... | alth(
task, timeout_in_ms=1000)
except (errors.UnavailableError, errors.DeadlineExceededError):
continue
break
multi_process_runner.get_barrier().wait()
cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)
mpr = multi_process_runner.MultiProce... |
CharityAdmin/CharityAdmin | setup.py | Python | mit | 774 | 0.003876 | from __future__ import with_statement
import distribute_setup
distribute_setup.use_setuptools()
import os
# disables creation of .DS_Store files inside tarballs on Mac OS X
os.environ['COPY_EXTENDED_ATTRIBUTES_DISABLE'] = 'true'
os.environ['COPYFILE_DISABLE'] = 'true'
def autosetup():
from setuptools import se... | 'setuptools.file_finders': [
'git = se | tuptools_git:gitlsfiles',
],
},
)
if(__name__ == '__main__'):
dist = autosetup()
|
vagabondcoder/nm_tools | test_auto_submit.py | Python | gpl-2.0 | 2,924 | 0.042066 | #!/usr/bin/env python3
import unittest
from mock import patch
import os
import auto_submit
import requests
import lxml
class AutoSubmitTest(unittest.TestCase):
message = None
url = None
def wifi_paths( self, p ):
return p == '/sys/class/net/wlp3s0/phy80211'
@patch.object( os, 'listdir' )
@patch.object( os.pa... | ue = ['lo', 'enp2s0']
self.assertEqual( [], auto_submit.get_wifi_ifaces())
mock_listdir.return_value = ['wlp3s0', 'lo', 'enp2s0']
self.assertEqual( expected, auto_submit.get_wifi_ifaces())
def open_url( self, url ):
self.url = url
def send_notify( self, msg ):
self.message = msg
@patch.object( auto_sub... | it_exception( self, mock_get, mock_open, mock_send ):
mock_open.side_effect = self.open_url
mock_send.side_effect = self.send_notify
mock_get.side_effect = Exception
self.url = None
self.message = None
auto_submit.auto_submit()
self.assertEqual( self.url, 'http://static.vagabondcoder.com/' )
@patch.obje... |
Azure/azure-storage-python | azure-storage-common/azure/storage/common/_http/__init__.py | Python | mit | 2,018 | 0.000496 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
class HT... | us
self.respheader = respheader
self.respbody = respbody
Exception.__init__(self, message)
class HTTPResponse | (object):
'''
Represents a response from an HTTP request.
:ivar int status:
the status code of the response
:ivar str message:
the message
:ivar dict headers:
the returned headers
:ivar bytes body:
the body of the response
'''
def __init__(self, stat... |
benoitsteiner/tensorflow-opencl | tensorflow/python/ops/nn.py | Python | apache-2.0 | 4,256 | 0 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.o | rg/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitatio... | {$python/nn} guide.
@@relu
@@relu6
@@crelu
@@swish
@@elu
@@leaky_relu
@@selu
@@softplus
@@softsign
@@dropout
@@bias_add
@@sigmoid
@@log_sigmoid
@@tanh
@@convolution
@@conv2d
@@depthwise_conv2d
@@depthwise_conv2d_native
@@separable_conv2d
@@atrous_conv2d
@@atrous_conv2d_transpose
@@conv2d_transpose
@@conv1d
@@conv3d
@@... |
aymeric-spiga/planetoplot | examples/ppclass_reference/function.py | Python | gpl-2.0 | 493 | 0.042596 | #! /usr/bin/env python
fr | om ppclass import pp
|
var1 = pp(\
file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",\
var="ps",\
x=None,\
y=10.,\
t=2.)
var1.get()
var2 = pp(\
file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",\
var="phisinit",\
x=None,\
y=10.,\
t=2.)
var2.get()
var2 = var2 / 3.72
S = var2.func(var1)
S.p[0].marker = 'o'
S.p[0].linestyle = ''
S.p[0].... |
ThomasJunk/ringo | ringo/alembic/versions/4ff2bc4eb9bf_.py | Python | gpl-2.0 | 1,013 | 0.009872 | """Removed nm_usergroup_roles table
Revision ID: 4ff2bc4eb9bf
Revises: 57c6ab33ad2f
Create Date: 2015-05-10 20:28:01.388673
"""
# revision identifiers, used by Alembic.
revision = '4ff2bc4eb9bf'
down_revision = '57c6ab33ad2f'
from alembic import op
import sqlalchemy as sa
UPGRADE = """"""
DOWNGRADE = """"""
def... | iter_statements(stmts):
for st in [x for x in stmts.split('\n') if x]:
op.execute(st)
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('nm_usergroup_roles')
### end Alembic commands ###
iter_statements(UPGRADE)
def downgrade():
### commands aut... | sa.Column('gid', sa.INTEGER(), nullable=True),
sa.Column('rid', sa.INTEGER(), nullable=True),
sa.ForeignKeyConstraint(['gid'], [u'usergroups.id'], ),
sa.ForeignKeyConstraint(['rid'], [u'roles.id'], )
)
### end Alembic commands ###
iter_statements(DOWNGRADE)
|
Wikidata/StrepHit | strephit/web_sources_corpus/spiders/chinese_bio.py | Python | gpl-3.0 | 887 | 0.003382 | # -*- coding: utf-8 -*-
from strephit.web_sources_corpus.spiders import BaseSpider
from strephit.web_sources_corpus.items import WebSourcesCorpusItem
class ChineseBioSpider(BaseSpider):
name = "chinese_bio"
allowed_domains = ["en.wikisource.org"]
start_urls = (
' | https://en.wikisource.org/wiki/A_Chinese_Biographical_Dictionary',
)
list_page_selectors = None
detail_page_selectors = 'xpath:.//div[@class="poem"]//a[not(@class="new" | )]/@href'
next_page_selectors = None
item_class = WebSourcesCorpusItem
item_fields = {
'name': 'clean:xpath://div[@id="headerContainer"]/following-sibling::div[1]//p/b[1]/text()',
'bio': 'clean:xpath:.//div[@id="headerContainer"]/following-sibling::div[1]//p//text()',
}
def refine_... |
snowch/biginsight-examples | examples/ElasticsearchIntegrationWithSpark/export_to_elasticsearch.py | Python | apache-2.0 | 2,079 | 0.007215 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | rrent/configuration.html
conf.se | t("es.nodes",host)
conf.set("es.port",str(port))
conf.set("es.net.http.auth.user",user)
conf.set("es.net.http.auth.pass",password)
conf.set("es.net.ssl","true")
conf.set("es.net.ssl.truststore.location","truststore.jks")
conf.set("es.net.ssl.truststore.pass","mypassword")
conf.set("es.nodes.... |
suizokukan/anceps | anceps.py | Python | gpl-3.0 | 1,215 | 0.001652 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
################################################################################
# Anceps Copyright (C) 2014 Suizokukan
# Contact: suizokukan _A.T._ orange dot fr
#
# This file is part of Anceps.
# Anceps is free software: you can redistribute it and/or modify
# ... | A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have | received a copy of the GNU General Public License
# along with Anceps. If not, see <http://www.gnu.org/licenses/>.
################################################################################
"""
❏Anceps❏ : ./anceps.py
(CLI) entry point to the project
"""
from anceps.cmdline.cmdline import get_input_d... |
squirrelo/plate-mapper | platemap/lib/plate.py | Python | bsd-3-clause | 11,253 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2016--, The Plate Mapper Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------... | tuple, | so called as plate[row, col] = Sample()
"""
# Need to get around postgres not having upsert in postgres < 9.5
# So do this slightly hacky workaround
# http://www.the-art-of-web.com/sql/upsert/
upsert_sql = """WITH upsert AS (
UPDATE barcodes.plates_sam... |
pdehaye/theming-edx-platform | common/djangoapps/student/views.py | Python | agpl-3.0 | 51,566 | 0.002793 | """
Student Views
"""
import datetime
import feedparser
import json
import logging
import random
import re
import string # pylint: disable=W0402
import urllib
import uuid
import time
from django.conf import settings
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.models impor... | ain=None is valid
if domain == False:
domain = request.META.get('HTTP_HOST')
courses = get_courses(None, domain=domain)
courses = sort_b | y_announcement(courses)
context = {'courses': courses}
context.update(extra_context)
return render_to_response('index.html', context)
def course_from_id(course_id):
"""Return the CourseDescriptor corresponding to this course_id"""
course_loc = CourseDescriptor.id_to_location(course_id)
retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.