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 |
|---|---|---|---|---|---|---|---|---|
PXke/invenio | invenio/legacy/docextract/utils.py | Python | gpl-2.0 | 1,606 | 0.010585 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 2 of t... | useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th | e GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from __future__ import print_function
VERBOSITY = None
impor... |
dalf/searx | searx/engines/google_scholar.py | Python | agpl-3.0 | 4,416 | 0.003397 | # SPDX-License-Identifier: AGPL-3.0-or-later
# lint: pylint
"""Google (Scholar)
For detailed description of the *REST-full* API see: `Query Parameter
Definitions`_.
.. _Query Parameter Definitions:
https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
"""
# pylint: dis... | omain'] + '/scholar' + "?" + urlencode({
'q': query,
'hl': lang_info['hl'],
'lr': lang_info['lr'],
'ie': "utf8",
| 'oe': "utf8",
'start' : offset,
})
query_url += time_range_url(params)
logger.debug("query_url --> %s", query_url)
params['url'] = query_url
logger.debug("HTTP header Accept-Language --> %s", lang_info['Accept-Language'])
params['headers']['Accept-Language'] = lang_info['Accept-Lan... |
jeroanan/Aquarius | tests/output/console/ConsoleTestBase.py | Python | gpl-3.0 | 257 | 0.003891 | import unittest
from aquarius.Aquarius import Aquarius
class ConsoleTestBase(unittest.TestCase):
| def initialise_a | pp_mock(self):
self.app = Aquarius(None, None, None)
def assert_called(self, method):
self.assertTrue(method.called) |
ROSbots/rosbots_setup_tools | rpi_setup/fabfile.py | Python | gpl-3.0 | 34,336 | 0.006291 | #
# This file is part of ROSbots Setup Tools.
#
# Copyright
#
# Copyright (C) 2017 Jack Pien <jack@rosbots.com>
#
# License
#
# This program 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 Foundatio... | isolate | d --pkg rosbots_driver --install -DCMAKE_BUILD_TYPE=Release --install-space " + install_dir + " -j2")
old_shell = env.shell
env.shell = '/bin/bash -l -c -i'
#run(main_ros_ws_dir + "/src/catkin/bin/catkin_make -j1 --pkg nav_msgs")
#run(main_ros_ws_dir + "/src/catkin/bin/catkin_ma... |
BhallaLab/moose | moose-gui/suds/xsd/__init__.py | Python | gpl-3.0 | 2,613 | 0.004592 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will b... | Boston, MA 02110-1301, USA.
# written by: Jeff Ortel ( jortel@redhat.com )
from suds import *
from suds.sax import Namespace, splitPrefix
def qualify(ref, resolvers, defns=Namespace.default):
"""
Get a reference that is I{qualified} by namespace.
@param ref: A referenced schema type name.
@type ref:... | x.element.Element},]
@param defns: An optional target namespace used to qualify references
when no prefix is specified.
@type defns: A default namespace I{tuple: (prefix,uri)} used when ref not prefixed.
@return: A qualified reference.
@rtype: (name, namespace-uri)
"""
ns = None
p, n... |
denverfoundation/storybase | apps/storybase_user/migrations/0006_auto__add_contact.py | Python | mit | 14,929 | 0.007636 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Contact'
db.create_table('storybase_user_contact', (
('id', self.gf('django.db... | __model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),... | gth': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
... |
lorian1333/netcopy | netcopy.py | Python | mit | 5,187 | 0.04492 | #!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt... | (num_files, receiver))
metadata = bytearray()
metadata += encodeInt(num_files, 4)
for (fn, f) in open_files:
metadata += encodeString(fn[fn.rfind(sep)+1:])
f.seek(0,2)
size = f.tell()
print("- Sending {0} ({1} bytes)".format(fn, size))
metadata += encodeInt(size, 8)
client.sendall(metadata)
metadata =... | 0:
bytebuf = bytearray(f.read(BUFSIZE))
client.sendall(bytebuf)
size -= BUFSIZE
f.close()
client.close()
def recieve():
port = DEFAULT_PORT
i = 2
while i < len(sys.argv):
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = i... |
SaschaMester/delicium | tools/telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | Python | bsd-3-clause | 1,492 | 0.005362 | # Copyright 2013 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 os
import subprocess
from telemetry.core.platform import profiler
from telemetry.core import util
from telemetry.internal.backends.chrome import andr... | rofiler):
"""Captures a screen recording on Android."""
def __init__(self, browser_backend, platform_backend, | output_path, state):
super(AndroidScreenRecordingProfiler, self).__init__(
browser_backend, platform_backend, output_path, state)
self._output_path = output_path + '.mp4'
self._recorder = subprocess.Popen(
[os.path.join(util.GetChromiumSrcDir(), 'build', 'android',
'scr... |
TurboTurtle/sos | sos/policies/init_systems/systemd.py | Python | gpl-2.0 | 1,563 | 0 | # Copyright (C) 2020 Red Hat, Inc., Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project | : https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.
from sos.pol... | r SystemD systems"""
def __init__(self):
super(SystemdInit, self).__init__(
init_cmd='systemctl',
list_cmd='list-unit-files --type=service',
query_cmd='status'
)
self.load_all_services()
def parse_query(self, output):
for line in output.split... |
tarvitz/djtp | app/settings/test.py | Python | bsd-3-clause | 721 | 0.001387 | # coding: utf-8
f | rom app.setti | ngs.dist import *
try:
from app.settings.local import *
except ImportError:
pass
from app.settings.messages import *
from app.settings.dist import INSTALLED_APPS
DEBUG = True
DEV_SERVER = True
USER_FILES_LIMIT = 1.2 * 1024 * 1024
SEND_MESSAGES = False
DATABASES = {
'default': {
'ENGINE': 'django.d... |
masom/shopify-trois | setup.py | Python | mit | 1,267 | 0 | """
Shopify Trois
---------------
Shopify API for Python 3
"""
from setuptools import setup
setup(
name='shopify-trois',
version='1.1-dev',
url='http://masom.github.io/shopify-trois',
license='MIT',
author='Martin Samson',
author_email='pyrolian@gmail.com',
maintainer='Martin Samson',
... | mail='pyrolian@gmail.com',
description='Shopify API for Python 3',
long_description=__doc__,
packages=[
'shopify_trois', 'shopify_trois.models', 'shopify_trois.engines',
| 'shopify_trois.engines.http'
],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'requests>=1.2.3'
],
test_suite='nose.collector',
tests_require=[
'pytest', 'nose', 'mock'
],
classifiers=[
'Development Status :: 4 - Beta... |
mikadam/LadderiLogical | tests/node.py | Python | mit | 1,030 | 0.067961 |
class node:
def __init__(self):
self.outputs=[]
def set(self):
for out in self.outputs:
out.set()
def clear(self):
for out in self.outputs:
out.clear()
class switch:
def __init__(self):
self.outputs=[]
self.state=False
self.input=False
def set(self):
self.input=True
if(self.state):
... | out.set()
class light:
def __init__(self):
self.outputs=[]
def set(self):
print('light set')
for out in self.outputs:
out.set()
def clear(self):
print('light cleared')
for out in self.outputs:
out.clear()
if __name__ == '__main__':
a=node()
s=switch()
b=node()
l | =light()
a.outputs.append(s)
s.outputs.append(b)
b.outputs.append(l)
a.set()
s.close()
print('switch close')
s.open() |
bgris/ODL_bgris | lib/python3.5/datetime.py | Python | gpl-3.0 | 75,899 | 0.000751 | """Concrete date/time and related types.
See http://www.iana.org/time-zones/repository/tz-link.html for
time zone and DST data sources.
"""
import time as _time
import math as _math
def _cmp(x, y):
return 0 if x == y else 1 if x > y else -1
MINYEAR = 1
MAXYEAR = 9999
_MAXORDINAL = 3652059 # date.max.toordinal(... | lt += ".%06d" % us
return result
# Correctly substitute for %z and %Z escapes in strft | ime formats.
def _wrap_strftime(object, format, timetuple):
# Don't call utcoffset() or tzname() unless actually needed.
freplace = None # the string to use for %f
zreplace = None # the string to use for %z
Zreplace = None # the string to use for %Z
# Scan format for %z and %Z escapes, replacing... |
neutronest/eulerproject-douby | e35/35.py | Python | mit | 586 | 0.006826 | from math | import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = s | tr(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if ... |
badele/home-assistant | homeassistant/components/mqtt/__init__.py | Python | mit | 9,508 | 0 | """
homeassistant.components.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT component, using paho-mqtt.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/
"""
import json
import logging
import os
import socket
import time
from homeassistant.exceptions impo... | LIVE)
username = util.convert(conf.get(CONF_USERNAME), str)
password = util.convert(conf.get(CONF_PASSWORD), str)
certificate = util.convert(conf.get(CONF_CERTIFICATE), str)
# For cloudmqtt.com, secured connection, auto fill in certificate
if certificate is None and 19999 < port < 30000 and \
... | nalcaroot.crt')
global MQTT_CLIENT
try:
MQTT_CLIENT = MQTT(hass, broker, port, client_id, keepalive, username,
password, certificate)
except socket.error:
_LOGGER.exception("Can't connect to the broker. "
"Please check your settings and t... |
fallisd/validate | unittests/__init__.py | Python | gpl-2.0 | 14 | 0 | """
| Empty |
"""
|
a-harper/RedditorProfiler | tasks.py | Python | gpl-3.0 | 532 | 0.00188 | from __future__ import absolute_import
from celery import shared_task
import praw
from .commonTasks import *
from .models import Redditor, RedditorStatus, Status
@shared_task
def test(param):
return 'The test task executed with argument "%s" ' % param
@shared_task
def update | _user(redditor):
update_user_status(redditor, 10)
get_submissions(redditor)
update_user_status(redditor, 20)
get_comments(redditor)
update_user_status(redditor, 30)
@shared_task
def write_user(user):
cr | eate_user(user)
|
sawmurai/spendrbackend | spendrbackend/wsgi.py | Python | apache-2.0 | 404 | 0 | """
WSGI config for spendrbackend project.
It exposes the WSGI callable as a mo | dule-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
""" |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spendrbackend.settings")
application = get_wsgi_application()
|
phha/taskwiki | tests/__init__.py | Python | mit | 115 | 0 | imp | ort os
import sys
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, path | )
|
stuckj/dupeguru | qt/base/details_dialog.py | Python | gpl-3.0 | 1,600 | 0.00875 | # Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | elf._setupUi()
# To avoid saving uninitialized geometry on appWillSavePrefs, we track whether our dialog
# has been shown. If it has, we know that our geometry should be saved.
self._shown_once = False
self.app.prefs.restoreGeometry('DetailsWindowRect', self)
self.tableModel = De... | el(self.tableModel)
self.model.view = self
self.app.willSavePrefs.connect(self.appWillSavePrefs)
def _setupUi(self): # Virtual
pass
def show(self):
self._shown_once = True
super().show()
#--- Events
def appWillSavePrefs(self):
if self._... |
uclouvain/OSIS-Louvain | base/management/commands/dump_waffle_flags.py | Python | agpl-3.0 | 436 | 0 | #!/usr/bin/env pyt | hon
from django.core.management imp | ort call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
call_command(
'dumpdata',
"waffle.flag",
indent=4,
use_natural_foreign_keys=True,
use_natural_primary_keys=True,
... |
warriorframework/warriorframework | warrior/WarriorCore/__init__.py | Python | apache-2.0 | 581 | 0.001721 | '''
Copyright 2017, Fujitsu Network Communications, | Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in 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
limitations under the License.
'''
|
martyni/amazon | my_env.py | Python | mit | 5,433 | 0.001104 | from pprint import pprint
from amazon_cf import Environment
from amazon_client import Cloudformation
from helper import (
Listener,
SecurityGroupRules,
UserPolicy,
get_my_ip,
get_local_variables,
convert_to_aws_list,
ContainerDefinition
)
if __name__ == "__main__":
# Manually created it... | "My Load Balancer",
[l_443.get_listener()],
HealthCheck=healthcheck)
my_env.add_autoscaling_group("My Autoscaling Group", DesiredCapacity="1", LoadBalancerNames=[
my_env.cf_ref("MyLoadBalancer")])
app_container = ContainerDefinition(**app_container)
nginx_... | container_definitions=[
app_container.return_container(),
nginx_container.return_container()
]
)
my_env.add_ecs_service('web service running')
resource_record = [my_env.cf_get_at("MyLo... |
rtnpro/opencabs | opencabs/signals.py | Python | gpl-3.0 | 635 | 0 | from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from finance.models import | Payment
from .models import BookingVehicle
@receiver([post_save, post_delete], sender=Payment)
def update_booking_payment_info(sender, instance, **kwargs):
if instance.item_content_type.app_label == 'opencabs' and \
| instance.item_content_type.model == 'booking':
if instance.item_object:
instance.item_object.save()
@receiver([post_save, post_delete], sender=BookingVehicle)
def update_booking_drivers(sender, instance, **kwargs):
instance.booking.update_drivers()
|
Zlash65/erpnext | erpnext/quality_management/doctype/quality_meeting/quality_meeting.py | Python | gpl-3.0 | 242 | 0.012397 | # | -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.document import Document
class Qualit | yMeeting(Document):
pass |
hguemar/cinder | cinder/tests/test_emc_vnxdirect.py | Python | apache-2.0 | 125,902 | 0.000246 | # Copyright (c) 2012 - 2014 EMC Corporation, Inc.
# 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
#
# ... |
test_volume_rw = {
'name': 'vol1',
'size': 1,
'volume_name': 'vol1',
'id': '1',
'provider_auth': None,
'project_id': 'project',
'display_name': 'vol1',
'display_description': 'test volume',
'volume_type_id': None,
'consistencygroup_id... | attached_mode', 'value': 'rw'},
{'key': 'readonly', 'value': 'False'}]
}
test_volume2 = {
'name': 'vol2',
'size': 1,
'volume_name': 'vol2',
'id': '1',
'provider_auth': None,
'project_id': 'project',
'display_name': 'vol2'... |
bitprophet/ssh | ssh/transport.py | Python | lgpl-2.1 | 88,838 | 0.002161 | # Copyright (C) 2011 Jeff Forcier <jeff@bitprophet.org>
#
# This file is part of ssh.
#
# 'ssh' 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 2.1 of the License, or (at your option)
# ... | , MD5
try:
from Crypto.Util import Counter
except I | mportError:
from ssh.util import Counter
# for thread cleanup
_active_threads = []
def _join_lingering_threads():
for thr in _active_threads:
thr.stop_thread()
import atexit
atexit.register(_join_lingering_threads)
class SecurityOptions (object):
"""
Simple object containing the security pre... |
johnbolia/plyer | plyer/facades/audio.py | Python | mit | 1,873 | 0 | '''
Audio
=====
The :class:`Audio` is used for recording audio.
Default path for recording is set in platform implementation.
.. note::
On Android the `RECORD_AUDIO`, `WAKE_LOCK` permissions are needed.
Simple Examples
---------------
To get the file path::
>>> audio.file_path
'/sdcard/testrecorde... | ath = file_path
def start(self):
'''
Start record.
'''
self._start()
self.state = 'record | ing'
def stop(self):
'''
Stop record.
'''
self._stop()
self.state = 'ready'
def play(self):
'''
Play current recording.
'''
self._play()
self.state = 'playing'
@property
def file_path(self):
return self._file_path... |
Felix5721/voc | tests/datatypes/test_str.py | Python | bsd-3-clause | 9,931 | 0.000101 | from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase
class StrTests(TranspileTestCase):
def test_setattr(self):
self.assertCodeExecution("""
x = "Hello, world"
x.attr = 42
print('Done.')
""")
... | # Simple negative index
self.assertCodeExecution("""
x = "12345"
print(x[-2])
""")
# Positive index out of range
self.assertCodeExecution("""
x = "12345"
print(x[10])
""")
| # Negative index out of range
self.assertCodeExecution("""
x = "12345"
print(x[-10])
""")
def test_slice(self):
# Full slice
self.assertCodeExecution("""
x = "12345"
print(x[:])
""")
# Left bound slice
... |
mpasternak/pyglet-fix-issue-552 | pyglet/input/__init__.py | Python | bsd-3-clause | 7,205 | 0.001249 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | rn: The remote device, or ``None`` if the computer does not support
it.
'''
return None
if _is_epydoc:
def get_devices(display=None):
' | ''Get a list of all attached input devices.
:Parameters:
`display` : `Display`
The display device to query for input devices. Ignored on Mac
OS X and Windows. On Linux, defaults to the default display
device.
:rtype: list of `Device`
... |
akhilerm/Castle | storage/app/public/drivers/driver.py | Python | mit | 1,024 | 0.019531 | #! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes th | e test cases from the answers/question_name file
and executes each test case. The output of each execu | tion
will be compared and the program outputs a binary string.
Eg : 1110111 means out of 7 test cases 4th failed and rest
all passed.
Resource/Time limit errors will be produced from docker container'''
#opening and parsing test cases
with open ("answer") as file: # change after development finishes
cases=fil... |
hwine/build-relengapi | relengapi/blueprints/tooltool/test_tooltool.py | Python | mpl-2.0 | 32,335 | 0.000526 | # 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 http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
import datetime
import hashlib
import json
import time
import urlparse
from cont... | 'instances': instances,
"has_instances": any(instances),
}
eq_(json.loads(resp.data)['result'], exp, resp.data)
def do_patch(client, algo, digest, ops):
return client.open(method='PATCH',
path='/tooltool/file/sha512/{}'.format(digest),
headers=[... | 'application/json')],
data=json.dumps(ops))
# tests
def test_is_valid_sha512():
"""is_valid_sha512 recgnizes valid digests and rejects others"""
assert tooltool.is_valid_sha512(ONE_DIGEST)
assert tooltool.is_valid_sha512(TWO_DIGEST)
assert not tooltool.is_valid_sha512(ONE_DIG... |
googleapis/python-shell | docs/conf.py | Python | apache-2.0 | 12,306 | 0.00065 | # -*- coding: utf-8 -*-
# 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 agr... | ---------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation... | "github_repo": "python-shell",
"github_banner": True,
"font_family": "'Roboto', Georgia, sans",
"head_font_family": "'Roboto', Georgia, serif",
"code_font_family": "'Roboto Mono', 'Consolas', monospace",
}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path ... |
WarrenWeckesser/scipy | benchmarks/benchmarks/cython_special.py | Python | bsd-3-clause | 1,956 | 0 | import re
import numpy as np
from scipy import special
from .common import with_attributes, safe_import
with safe_import():
from scipy.special import cython_special
FUNC_ARGS = {
'airy_d': (1,),
'airy_D': (1,),
'beta_dd': (0.25, 0.75),
'erf_d': (1,),
'erf_D': (1+1j,),
'exprel_d': (1e-6,)... | me,), (args,)] + params,
param_names=['name', 'argument'] + param_names)
def func(self, name, args, N, api):
if api == 'python':
self.py_func(N, *args)
elif api == 'numpy':
self.np_func(*self.obj)
| else:
self.cy_func(N, *args)
func.__name__ = 'time_' + name
return func
for name in FUNC_ARGS.keys():
func = get_time_func(name, FUNC_ARGS[name])
dct[func.__name__] = func
return type.__new__(cls, cls_name, bases, dct)
... |
Caesurus/CTF_Writeups | 2019-PicoCTF/exploits/exploit_overflow-1.py | Python | apache-2.0 | 624 | 0.00641 | # -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template ./vuln
from pwn import *
# Set up pwntools for the correct architecture
exe = context.binary = ELF('./vuln')
def start(argv | =[], *a, **kw):
'''Start the exploit against the target.'''
if args.GDB:
return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
else:
return process([exe.path] + argv, *a, **kw)
gdbscript = '''
break *0x{exe.symb | ols.main:x}
continue
'''.format(**locals())
io = start()
payload = cyclic(76)
#payload = 'A'*64
payload += p32(0x80485e6)
io.sendline(payload)
io.interactive()
|
kokimoribe/todo-api | todo/schemas.py | Python | mit | 1,124 | 0 | """Request/Response Schemas are defined here"""
# pylint: disable=invalid-name
from marshmallow import Schema, fields, validate
from todo.constants import TO_DO, IN_PROGRESS, DONE
class TaskSchema(Schema):
"""Schema for serializing an instance of Task"""
id = fields.Int(required=True)
title = fields.Str... | PROGRESS, DONE],
error="Status must be one of {choices} (given: {input})"))
number = fields.Int(required=True)
created_at = fields.DateTime(required=True)
updated_at = fields.DateTime(required=True)
class BoardSchema(Schema):
"""Schema for serializing an instance of Board"""
id = field... | ired=True)
updated_at = fields.DateTime(required=True)
class BoardDetailsSchema(BoardSchema):
"""Schema for serializing an instance of Board and its tasks"""
tasks = fields.Nested(TaskSchema, many=True)
|
Pandentia/Liara-Cogs | cogs/tempvoice.py | Python | mit | 3,721 | 0.00215 | import asyncio
import discord
from discord.ext import commands
from cogs.utils import checks
from cogs.utils.storage import RedisDict
class TemporaryVoice:
"""A cog to create TeamSpeak-like voice channels."""
def __init__(self, liara):
self.liara = liara
self.config = RedisDict('pandentia.te... | _channel(self, member: discord.Member):
guild = member.guild
overwrites = {
guild.default_role: discord.PermissionOverwrite(connect=False),
member: discord.PermissionOverwrite(connect=True, manage_channels=True, manage_roles=True)
}
channel = await guild.create_vo... | acked_channels.add(channel.id)
await member.move_to(channel)
async def on_voice_state_update(self, member, *_):
guild = member.guild
if guild is None:
return # /shrug
if self.config.get(guild.id) is None:
return
# lobby processing
channel = s... |
nextdude/robogator-controller | src/test-motor.py | Python | mit | 19 | 0 | im | port brickpi3
| ZZ
|
concerned3rdparty/jirafe-python | jirafe/models/Category.py | Python | mit | 944 | 0.007415 | #!/usr/bin/env python
"""
Copyright 2014 Jirafe, 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 applicab... | istributed 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
limitations under the License.
"""
class Category:
"""NOTE: This class is auto generated by the sw... | : 'str'
}
self.id = None # str
self.name = None # str
|
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/generators/tests/test_geometric.py | Python | bsd-2-clause | 1,036 | 0.029923 | #!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestGeneratorsGeometric():
def test_random_geometric_graph(self):
G=nx.random_geometric_graph(50,0.25)
assert_equal(len(G),50)
def test_geographical_threshold_graph(self):
G=nx.geographical_threshold_graph(50,10... | )
def test_naviable_small_world(self):
G = nx.navigable_small_world_graph(5,p=1,q=0)
gg = nx.grid_2d_graph(5,5).t | o_directed()
assert_true(nx.is_isomorphic(G,gg))
G = nx.navigable_small_world_graph(5,p=1,q=0,dim=3)
gg = nx.grid_graph([5,5,5]).to_directed()
assert_true(nx.is_isomorphic(G,gg))
G = nx.navigable_small_world_graph(5,p=1,q=0,dim=1)
gg = nx.grid_graph([5]).to_directed()
... |
openstack/nova | nova/compute/utils.py | Python | apache-2.0 | 63,683 | 0.000094 | # Copyright (c) 2011 OpenStack Foundation
#
# 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 ... | t user's server (migrations, reboot, etc) and
# service startup and periodic tasks could take actions on a server
# and those use an admin context.
message = fault.__class__.__name__
# NOTE(dripton) The message field in the database is limited to 255 c | hars.
# MySQL silently truncates overly long messages, but PostgreSQL throws an
# error if we don't truncate it.
u_message = utils.safe_truncate(message, 255)
fault_dict = dict(exception=fault)
fault_dict["message"] = u_message
fault_dict["code"] = code
return fault_dict
def _get_fault_det... |
xbmc/atv2 | xbmc/lib/libPython/Python/Lib/plat-irix6/GLWS.py | Python | gpl-2.0 | 181 | 0 | NOERROR = 0
NOCONTEXT = -1
NODISP | LAY = -2
NOWINDOW = -3
NOGRAPHICS = -4
NOTTOP = -5
NOVISUAL = -6
BUFSIZE = -7
BADWINDOW = -8
ALREADYBOUND = - | 100
BINDFAILED = -101
SETFAILED = -102
|
googlegenomics/pipelines-api-examples | bioconductor/run_bioconductor.py | Python | bsd-3-clause | 6,448 | 0.004498 | #!/usr/bin/python
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Python sample demonstrating use of the Google Genomics Pipelines API.
This sample demonstrates a pipe... | 'name': 'bamFile',
'description': 'Cloud Storage path to the BAM file.',
'localCopy': {
'path': 'input.bam',
'disk': 'data'
}
}, {
'name': 'indexFile',
'description': 'Cloud Storage path to the BAM index file.',
'localCopy | ': {
'path': 'input.bam.bai',
'disk': 'data'
}
} ],
'outputParameters' : [ {
'name': 'outputFile',
'description': 'Cloud Storage path for where to write the result.',
'localCopy': {
'path': 'overlapsCount.tsv',
'disk': 'data'
}
}, {
'nam... |
alsrgv/tensorflow | tensorflow/lite/testing/generate_examples_lib.py | Python | apache-2.0 | 176,619 | 0.005588 | # Copyright 2019 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 applica... | st_function(name=None):
| def decorate(function, name=name):
if name is None:
name = function.__name__
_MAKE_TEST_FUNCTIONS_MAP[name] = function
return decorate
class ExtraTocoOptions(object):
"""Additional toco options besides input, output, shape."""
def __init__(self):
# Whether to ignore control dependency nodes... |
zepto/biblesearch.web | sword_search.old/search.py | Python | gpl-3.0 | 146,124 | 0.000561 | #!/usr/bin/env python
# vim: sw=4:ts=4:sts=4:fdm=indent:fdl=0:
# -*- coding: UTF8 -*-
#
# A sword KJV indexed search module.
# Copyright (C) 2012 Josiah Gordon <josiahg@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published... | .
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute | and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
... |
openstack/sahara | sahara/tests/unit/service/api/test_v10.py | Python | apache-2.0 | 11,635 | 0 | # Copyright (c) 2015 Mirantis 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 writ... | self.assertEqual(c_u.CLUSTER_STATUS_ACTIVE, result_cluster2.status)
expected_count = {
'ng_1': 1,
'ng_2': 3,
'ng_3': 1,
}
ng_count = 0
| for ng in result_cluster1.node_groups:
self.assertEqual(expected_count[ng.name], ng.count)
ng_count += 1
self.assertEqual(3, ng_count)
api.terminate_cluster(result_cluster1.id)
api.terminate_cluster(result_cluster2.id)
self.assertEqual(
['get_ope... |
hybrid-storage-dev/cinder-fs-111t-hybrid-cherry | volume/drivers/ec2/exception_ex.py | Python | apache-2.0 | 1,031 | 0.012609 |
from cinder.exception import *
from cinder.i18n import _
class ProviderMultiVolumeError(CinderException):
msg_fmt = _("volume %(volume_id)s More than one provider_volume are found")
class ProviderMultiSnapshotError(CinderException):
msg_fmt = _("snapshot %(snapshot_id)s More than one provider_snapshot are fo... | (volume_id)s create request failed,network or provider internal error")
class ProviderCreateSnapshotError(CinderException):
msg_fmt = _("snapshot %(snapshot_id)s create request failed,network or provider internal error")
class ProviderLocationError(CinderExceptio | n):
msg_fmt = _("provider location error")
class ProviderExportVolumeError(CinderException):
msg_fmt = _("provider export volume error")
class ProviderVolumeNotFound(NotFound):
message = _("Volume %(volume_id)s could not be found.")
class VgwHostNotFound(NotFound):
message = _("node of %(Vgw_id)s... |
diplomacy/research | diplomacy_research/proto/tensorflow_serving/config/platform_config_pb2.py | Python | mit | 6,119 | 0.00621 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow_serving/config/platform_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.pr... | low.serving.PlatformConfigMap.PlatformConfigsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, defa | ult_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='tensorflow.serving.PlatformConfigMap.PlatformConfigsEntry.valu... |
MaxwellCoriell/DjangoTaskManager | DjangoTaskManager/task/urls.py | Python | mit | 544 | 0 | from django.conf.urls import url
from DjangoTaskManager.task import views
urlpatterns = [
url(r'^$', views.all_tasks, name='all_tasks'),
url(r'^add/$', views.add, name='task_add'),
url(r'^mark-done/(?P<task_id>[\w+:-]+)/$',
views.mark_done, name='task_mark_done'),
url(r'^edit/(?P<task_id>[\w+:... | views.delete, name='task_delete'),
url(r'^single/(?P<task_id>[\w+:-]+)/$',
views.single, name='single_task | '),
]
|
prk327/CoAca | Algo - DataStru/bst.py | Python | gpl-3.0 | 4,916 | 0.058381 |
class Node(object):
#a binary search tree has a left node (smaller values) and a right node (greater values)
def __init__(self, data):
self.data = data;
self.left_child = None;
self.right_child = None;
class BinarySearchTree(object):
def __init__(self):
self.root = None;
#inserting ite... | not node.left_child: # node !!!
print("Removing a node with single right child...");
temp_node = node.right_child;
|
del node;
return temp_node;
#the node we want to remove has a single left child
elif not node.right_child: # node instead of self
print("Removing a node with single left child...");
temp_node = node.left_child;
del node;
return temp_node;
#the node has both left and rig... |
thibault/libnexmo | libnexmo/response.py | Python | mit | 1,868 | 0.000535 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>>... | on_data['messages']]
self.message_count = len(self.messages)
self.total_price = sum(msg.message_price for msg in self.messages)
self.remaining_balance = min(msg.remaining_balance for msg in self.messages)
class NexmoM | essage(object):
"""A wrapper to manipulate a single `message` entry in a Nexmo response.
When a text messages is sent in several parts, Nexmo will return a status
for each and everyone of them.
The class does nothing more than simply wrapping the json data for easy
access.
"""
def __init_... |
ddenhartog/itmaybeahack-roulette | bin.py | Python | mit | 4,662 | 0.000858 | #PROJECT
from outcome import Outcome
from odds import Odds
class Bin:
def __init__(
self,
*outcomes
):
self.outcomes = set([outcome for outcome in outcomes])
def add_outcome(
self,
outcome
):
self.outcomes.add(outcome)
def __str__(self):
re... | )
for r in range(12):
self.wheel.add_outcome(3 * r + c + 1, outcome)
def even_money_bets(self):
for bin in range(1, 37):
if 1 <= bin < 19:
name = '1 to 18' #low
else:
name = '19 to 36' #high
self.wheel... | else:
name = 'even'
self.wheel.add_outcome(
bin,
Outcome(name, Odds.EVEN_MONEY_BET)
)
if bin in (
[1, 3, 5, 7, 9] +
[12, 14, 16, 18] +
[19, 21, 23, 25, 27] +
[30, 32, 3... |
spketoundi/CamODI | waespk/urls.py | Python | mit | 1,548 | 0.001292 | from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from djgeojson.views import GeoJSONLayerView
from wagtail.contrib.wagtailsitemaps.views | import sitemap
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from wagtail.wagtailcore import urls as wagtail_urls
from waespk.core import urls as ossuo_urls
urlpatterns = [
url(r'^django-admin/', include(admin.site.urls)),
url(r'^admin/'... | ,
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^sitemap\.xml$', sitemap),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView, RedirectView
# Serve static and... |
pkrebs/WIDPS | fw_modules/module_dumper.py | Python | gpl-2.0 | 3,313 | 0.00815 | #!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#
# module_dumper.py - WIDS/WIPS framework file dumper module
# Copyright (C) 2009 Peter Krebs, Herbert Haas
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by the
# Fr... | ary, module_logger)
return dumper_class
if | __name__ == "__main__":
print "Warning: This module is not intended to be executed directly. Only do this for test purposes." |
apache/incubator-airflow | tests/providers/apache/hive/operators/test_hive_stats.py | Python | apache-2.0 | 14,564 | 0.003158 | #
# 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... | urn_value = False
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
field_types = {
col.name: col.type for col in mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols
}
expr... | ld_types.items()):
exprs.update(hive_stats_collection_operator.assignment_func(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_opera... |
mitsuhiko/raven | raven/utils/__init__.py | Python | bsd-3-clause | 3,540 | 0.003107 | """
raven.utils
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import hashlib
import hmac
import logging
try:
import pkg_resources
except ImportError:
pkg_resources = None
import sys
import raven
def construct_check... | version = '.'.join(str(o) for o in version)
_VERSION_CACHE[module_name] = version
else:
version = _VERSION_CACHE[module_name]
if version is None: |
continue
versions[module_name] = version
return versions
def get_signature(key, message, timestamp):
return hmac.new(key, '%s %s' % (timestamp, message), hashlib.sha1).hexdigest()
def get_auth_header(signature, timestamp, client):
return 'Sentry sentry_signature=%s, sentry_timestamp=%... |
SteveDiamond/cvxpy | cvxpy/reductions/complex2real/atom_canonicalizers/__init__.py | Python | gpl-3.0 | 4,337 | 0.003459 | """
Copyright 2017 Robin Verschueren
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, softw... | Pos, SOC, PSD, Zero
from cvxpy.reductions.complex2real.atom_canonicalizers.abs_canon import abs_canon |
from cvxpy.reductions.complex2real.atom_canonicalizers.aff_canon import (separable_canon,
real_canon,
imag_canon,
... |
yippeecw/sfa | sfa/trust/credential_factory.py | Python | mit | 5,023 | 0.002588 | #----------------------------------------------------------------------
# Copyright (c) 2014 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including ... | try:
cred = ABACCredential(string=credString)
return cred
except Exception, e:
if credFile:
raise Exception("%s not a parsable ABAC credential: %s" % (credFile, e))
els | e:
raise Exception("ABAC Credential not parsable: %s. Cred start: %s..." % (e, credString[:50]))
else:
raise Exception("Unknown credential type '%s'" % cred_type)
if __name__ == "__main__":
c2 = open('/tmp/sfa.xml').read()
cred1 = CredentialFactory.createCred(cred... |
jocelynmass/nrf51 | toolchain/arm_cm0/arm-none-eabi/lib/thumb/v7-ar/libstdc++.a-gdb.py | Python | gpl-2.0 | 2,483 | 0.006444 | # -*- python -*-
# Copyright (C) 2009-2017 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the | GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PAR... | eived a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import os
import os.path
pythondir = '/Users/build/work/GCC-7-build/install-native/share/gcc-arm-none-eabi'
libdir = '/Users/build/work/GCC-7-build/install-native/arm-none-eabi/... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/matplotlib/tests/test_collections.py | Python | bsd-2-clause | 21,429 | 0 | """
Tests specific to the collections module.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import io
from nose.tools import assert_equal
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.... | ,
props['extra_positions'][1:]])
coll.extend_positions(props['extra_positions'][1:])
np.testing.assert_arr | ay_equal(new_positions, coll.get_positions())
check_segments(coll,
new_positions,
props['linelength'],
props['lineoffset'],
props['orientation'])
splt.set_title('EventCollection: extend_positions')
splt.set_xlim(-1, 90)
@image_com... |
bqbn/addons-server | src/olympia/scanners/migrations/0009_auto_20191023_0906.py | Python | bsd-3-clause | 1,450 | 0.004138 | # Generated by Django 2.2.6 on 2019-10-23 09:06
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import olympia.amo.models
class Migration(migrations.Migration):
dependencies = [
('scanners', '0008_auto_20191021_1718'),
]
operations = [
... | 'get_latest_by': 'created',
'abstract': False,
'base_manager_name': 'objects',
},
bases=(olympia.amo.models.SearchMixin, olympia.am | o.models.SaveUpdateMixin, models.Model),
),
migrations.AddField(
model_name='scannerresult',
name='matched_rules',
field=models.ManyToManyField(through='scanners.ScannerMatch', to='scanners.ScannerRule'),
),
]
|
rohitranjan1991/home-assistant | homeassistant/components/vacuum/__init__.py | Python | mit | 11,915 | 0.000587 | """Support for vacuum cleaner robots (botvacs)."""
from dataclasses import dataclass
from datetime import timedelta
from functools import partial
import logging
from typing import final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( # noqa: F401 # STAT... | """Set fan speed.
This method must be run in the event loop.
| """
await self.hass.async_add_executor_job(
partial(self.set_fan_speed, fan_speed, **kwargs)
)
def send_command(self, command, params=None, **kwargs):
"""Send a command to a vacuum cleaner."""
raise NotImplementedError()
async def async_send_command(self, command,... |
shakamunyi/neutron-vrrp | neutron/services/loadbalancer/drivers/radware/driver.py | Python | apache-2.0 | 45,498 | 0.000374 | # Copyright 2013 Radware LTD.
#
# 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 agree... | rad.l4_workflow_name
self.l2_l3_ctor_params = rad.l2_l3_ctor_params
self.l2_l3_setup_params = rad.l2_l3_setup_params
self.l4_action_name = rad.l4_action_name
self.actions_to_skip = rad.actions_to_skip
vdirect_address = rad.vdirect_address
sec_server = rad.ha_secondary_ad... | secondary_server=sec_server,
user=rad.vdirect_user,
password=rad.vdirect_password)
self.queue = Queue.Queue()
self.completion_handler = OperationCompletionHandler(self.queue,
... |
haldean/longtroll | longtroll/longtroll.py | Python | mit | 3,588 | 0.015886 | '''longtroll: Notify you when your long-running processes finish.'''
import argparse
import getpass
import os
import pickle
import re
import subprocess
import time
collapse_whitespace_re = re.compile('[ \t][ \t]*')
def spawn_notify(notifier, proc_ended):
cmd = notifier.replace('<cmd>', proc_ended[0])
cmd = cmd.r... | :
line = re.sub(collapse_whitespace_re, ' ', line).strip()
time, pid, ppid, command = line.split(' ', 3)
try:
return {
'age': etime_to_secs(time),
'pid': int(pid),
'ppid': int(ppid),
'command': command,
}
except Exception:
print('Caught excep... | n(' '.join([
'ps', '-U %s' % user, '-o etime,pid,ppid,command']),
shell=True, stdout=subprocess.PIPE).communicate()[0]
for line in ps_out.split('\n')[1:]:
if line: yield line_to_dict(line)
def etime_to_secs(etime):
'Parsing etimes is rougher than it should be.'
seconds = 0
etime = etime.split('-'... |
junzis/pyModeS | pyModeS/decoder/allcall.py | Python | gpl-3.0 | 1,888 | 0.003178 | """
Decode all-call reply messages, with downlink format 11
"""
from pyModeS import common
def _checkdf(func):
"""Ensure downlink format is 11."""
def wrapper(msg):
df = common.df(msg)
if df != 11:
raise RuntimeError(
"Incorrect downlink format, expect 11, got {}"... | ""
msgbin = common.hex2bin(msg)
ca = common.bin2int(msgbin[5:8])
if ca == 0:
text = "level 1 transponder"
elif ca == 4:
text = "level 2 | transponder, ability to set CA to 7, on ground"
elif ca == 5:
text = "level 2 transponder, ability to set CA to 7, airborne"
elif ca == 6:
text = "evel 2 transponder, ability to set CA to 7, either airborne or ground"
elif ca == 7:
text = "Downlink Request value is 0,or the Flight St... |
catapult-project/catapult | third_party/gsutil/third_party/argcomplete/argcomplete/my_argparse.py | Python | bsd-3-clause | 15,351 | 0.000912 | # Copyright 2012-2013, Andrey Kislyuk and argcomplete contributors.
# Licensed under the Apache License. See https://github.com/kislyuk/argcomplete for more info.
from argparse import ArgumentParser, ArgumentError, SUPPRESS, _SubParsersAction
from argparse import OPTIONAL, ZERO_OR_MORE, ONE_OR_MORE, REMAINDER, PARSER
... | Begin added by argcomplete
# When a subparser action is taken and fails due to incomplete arguments, it does not merge the
# contents of its parsed namespace into the parent namespace. Do that here to allow completers to
| # access the partially parsed arguments for the subparser.
if isinstance(action, _SubParsersAction):
subnamespace = action._name_parser_map[argument_values[0]]._argcomplete_namespace
for key, value in vars(subnamespace).items():
... |
jeff-alves/Tera | ui/custom_menu_bar.py | Python | mit | 2,593 | 0.00617 | import wx
from ui.custom_checkbox import CustomCheckBox
class CustomMenuBar(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.SetBackgroundColour(self.parent.GetBackground | Colour())
self.SetForegroundColour(self.parent.GetForegroundColour())
self.SetFont(self.parent.GetFont())
self.img_size = 12
self._dragPos = None
self.Bind(wx.EVT_MOTION, self.OnMouse)
gbSizer = wx.GridBagSizer()
self.txtTitle = wx.StaticText(self, wx.ID_ANY, u"T... | lf, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0)
gbSizer.Add(self.txtServer, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL | wx.ALIGN_CENTER_HORIZONTAL , 5)
self.btn_pin = CustomCheckBox(self, 'ui.pin', color_checked='#FF0000', color_hover='#1188FF')
self.btn_pin.Bind(wx.EVT_CHECKBOX,... |
Affirm/cabot | cabot/metricsapp/tests/test_views.py | Python | mit | 4,754 | 0.004417 | from urlparse import urlparse
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from cabot.cabotapp.models import Service
from cabot.metricsapp.models import MetricsSourceBase, ElasticsearchStatusCheck, GrafanaInstance, GrafanaPanel
class TestM... | self.assertEqual(self.metrics_check.name, 'test')
# now accept the changes by manually setting skip_review to True (which should be done in the response)
# (would ideally do this by using a | browser's normal submit routine on the response,
# but I don't think we can do that with just django's standard testing functions.
# we at least scan the HTML for the skip_review input to make sure it got set to True)
self.assertContains(response,
'<input id="skip_rev... |
kilbee/blender-script-watcher | script_watcher.py | Python | gpl-2.0 | 12,299 | 0.007887 | """
script_watcher.py: Reload watched script upon changes.
Copyright (C) 2015 Isaac Weaver
Author: Isaac Weaver <wisaac407@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; eith... | """
bl_info = {
"name": "Script Watcher",
"author": "Isaac Weaver",
"version": (0, 5),
"blender": (2, 75, 0),
"location": "Properties > Scene > Script Watcher",
"description": "Reloads an external script on edits.",
"warning": "Still in beta stage.",
"wiki_url": "http://wi | ki.blender.org/index.php/Extensions:2.6/Py/Scripts/Development/Script_Watcher",
"tracker_url": "https://github.com/wisaac407/blender-script-watcher/issues/new",
"category": "Development",
}
import os, sys
import io
import traceback
import types
import bpy
from bpy.app.handlers import persistent
@persistent
de... |
btovar/cctools | work_queue/src/bindings/python3/PythonTask_example.py | Python | gpl-2.0 | 2,499 | 0.002001 | #!/usr/bin/env python3
# copyright (C) 2021- The University of Notre Dame
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.
# Example on how to execute python code with a Work Queue task.
# The class PythonTask allows users to execute python functions as Work Que... | an output file and read when neccesary
# allowing the user to get the result as a python variable during runtime and
# manipulated later.
# A PythonTask object is created as `p_task = PyTask.PyTask(func, args)` where
# `func` is the name of the function and args are the arguments needed to
# execute the function. Pyth... | ueue as regular Work
# Queue functions, such as `q.submit(p_task)`.
#
# When a has completed, the resulting python value can be retrieved by calling
# the output method, such as: `x = t.output` where t is the task retuned by
# `t = q.wait()`.
#
# By default, the task will run assuming that the worker is executing insi... |
d33tah/bpgsql | tests/dbapi20.py | Python | lgpl-2.1 | 31,413 | 0.010251 | #!/usr/bin/env python
''' Python DB API 2.0 driver compliance unit test suite.
This software is Public Domain and may be used without restrictions.
"Now we have booze and barflies entering the discussion, plus rumours of
DBAs on drugs... and I won't tell you what flashes through my mind each
time I read... | equal 2.0
self.assertEqual(apilevel,'2.0')
except AttributeError:
self.fail("Driver doesn't define apilevel")
def test_threadsafety(self):
try:
# Must exist
threadsafety = self.driver.threadsafety
# Must be a valid value
self.f... | try:
# Must exist
paramstyle = self.driver.paramstyle
# Must be a valid value
self.failUnless(paramstyle in (
'qmark','numeric','named','format','pyformat'
))
except AttributeError:
self.fail("Driver doesn't defi... |
Vauxoo/e-commerce | website_sale_require_legal/tests/__init__.py | Python | agpl-3.0 | 88 | 0 | # License AGPL-3.0 | or later (https://www.gnu.org/licenses/agpl).
from . i | mport test_ui
|
antsmc2/mics | survey/management/commands/__init__.py | Python | bsd-3-clause | 77 | 0.012987 | from survey.management.commands.import_locatio | n import Command
__all__ = [ | ''] |
lssfau/walberla | python/mesa_pd/kernel/HCSITSRelaxationStep.py | Python | gpl-3.0 | 2,010 | 0.006468 | # -*- coding: utf-8 -*-
from mesa_pd.accessor import create_access
from mesa_pd.utility import generate_file
def create_property(name, type, defValue=""):
"""
Parameters
----------
name : str
name of the property
type : str
type of the property
defValue : str
default valu... | f):
self.context = {'properties': [], 'interface': []}
self.context['properties'].append(create_property("maxSubIterations", "size_t", defValue="20"))
self.context['pr | operties'].append(
create_property("relaxationModel", "RelaxationModel", defValue="InelasticFrictionlessContact"))
self.context['properties'].append(create_property("deltaMax", "real_t", defValue="0"))
self.context['properties'].append(create_property("cor", "real_t", defValue="real_t(0.2)")... |
atomman/nmrglue | tests/pipe_proc_tests/shuf.py | Python | bsd-3-clause | 963 | 0 | #! /usr/bin/env python
""" Create files for shuf unit test """
import nmrglue.fileio.pipe as pipe
import nmrglue.process.pipe_proc as p
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="ri2c")
pipe.write("shuf1.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.sh | uf(d, a, mode="c2ri")
pipe.write("shuf2.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="ri2rr")
pipe.write("shuf3.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="exlr")
pipe.write("shuf4.glue", d, a, | overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="rolr")
pipe.write("shuf5.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="swap")
pipe.write("shuf6.glue", d, a, overwrite=True)
d, a = pipe.read("time_complex.fid")
d, a = p.shuf(d, a, mode="inv"... |
xLemon/xExcelConvertor | excel_convertor/processors/processor_php.py | Python | mit | 7,054 | 0.026398 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from core.base_processor import xBaseProcessor
from utilities.export_helper import xExportHelper
from utilities.file_utility import xFileUtility
from definitions.constant_data impo... | > array('.format(strKey)
else :
strContent += '{0} => a | rray('.format(strKey)
strContent += self.__ConvertPHPContent(p_mapExportConfigs, p_mapDataSheetConfigs, p_mixPreloadDatas[mixKey], p_lstCategoryLevelColumnIndexIndexs, p_nCategoryLevel, p_mapGenerateControl)
if p_mapGenerateControl['level_index'] < len(p_lstCategoryLevelColumnIndexIndexs) :
strCo... |
htc-msm8960/android_kernel_htc_msm8930 | scripts/gcc-wrapper.py | Python | gpl-2.0 | 3,965 | 0.002774 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are | met:
# * Redistributions of source code must retain the above copyright
# notice, this list of cond | itions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of The Linux Foundation nor
# ... |
chotchki/servo | python/licenseck.py | Python | mpl-2.0 | 1,985 | 0.002519 | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# 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 http://opensource.org/licenses/MIT>, at your
#... | ccordi | ng to those terms.
""",
"""\
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# 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 http://opensourc... |
SCUEvals/scuevals-api | scuevals_api/models/professor.py | Python | agpl-3.0 | 905 | 0.00221 | from . import db
from .assoc import section_professor
class Professor(db.Model):
__tablename__ = 'professors'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), unique=True)
first_name = db.Column(db.Text, nullable=False)
last_name = db.Column... | ('universities.id'), nullable=False)
university = db.relationship('University', back_populates='professors')
sections = db.relationship('Section', second | ary=section_professor, back_populates='professors')
evaluations = db.relationship('Evaluation', back_populates='professor')
__mapper_args__ = {
'polymorphic_identity': 'p',
}
def to_dict(self):
return {
'id': self.id,
'first_name': self.first_name,
'... |
tersmitten/ansible-modules-core | cloud/openstack/os_router.py | Python | gpl-3.0 | 12,382 | 0.001373 | #!/usr/bin/python
#
# This module 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.
#
# This software is distributed in the hope that it ... | ip | : 172.24.4.2
interfaces:
- private-subnet
# Update existing router1 external gateway to include the IPv6 subnet.
# Note that since 'interfaces' is not provided, any existing internal
# interfaces on an existing router will be left intact.
- os_router:
cloud: mycloud
state: present
name: router1
... |
opstooling/python-cratonclient | cratonclient/tests/base.py | Python | apache-2.0 | 1,608 | 0.000622 | # -*- coding: utf-8 -*-
# Copyright 2010- | 2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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
#
... | 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 limitations
# under the License.
"""Base TestCase for all cratonclient tests."""
import mock
import six
import sys
from oslotest import base
from cratoncl... |
victorivanovspb/challenge-accepted | resp_simple/is_prime.py | Python | gpl-3.0 | 1,857 | 0.005675 | # -*- coding: utf-8 -*-
"""
Написать функцию is_prime, принимающую 1 аргумент: число от 0 до 1000.
Если число простое, то функция возвращает True, а в противном случае - False.
"""
prime_1000 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, ... | , 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
def is_prime... | or("argument value out of bounds")
if num % 2 == 0:
return False
mass = prime_1000
i1 = 0
i2 = len(mass) - 1
while i1 < i2:
if num == mass[i1] or num == mass[i2]:
return True
mid = i2 - int(round((i2 - i1) / 2))
if num < mass[mid]:
... |
soscpd/bee | root/tests/zguide/examples/Python/clonecli6.py | Python | mit | 638 | 0.007837 | """
Clo | ne server Model Six
"""
import random
import time
import zmq
from clone import Clone
SUBTREE = "/client/"
def main(): |
# Create and connect clone
clone = Clone()
clone.subtree = SUBTREE
clone.connect("tcp://localhost", 5556)
clone.connect("tcp://localhost", 5566)
try:
while True:
# Distribute as key-value message
key = "%d" % random.randint(1,10000)
value = "%d" % ra... |
jjbgf/eventbooking | zeltlager_registration/migrations/0002_auto_20150211_2011.py | Python | gpl-2.0 | 675 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(mig | rations.Migration):
dependencies = [
('zeltlager_registration', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='jugendgruppe',
name='address',
),
migrations.DeleteModel(
name='Jugendgruppe',
),
migrat... | model_name='zeltlagerdurchgang',
name='description',
),
]
|
spcui/virt-test | virttest/qemu_vm.py | Python | gpl-2.0 | 146,685 | 0.000389 | """
Utility classes and functions to handle Virtual Machine creation using qemu.
:copyright: 2008-2009 Red Hat Inc.
"""
import time
import os
import logging
import fcntl
import re
import commands
from autotest.client.shared import error
from autotest.client import utils
import utils_misc
import virt_vm
import test_se... | t db lookups depend on this
if state:
self.instance = state['instance']
self.qemu_command = ''
self.start_time = 0.0
def verify_alive(self):
"""
Make sure the VM is alive and that the main monitor is responsive.
:raise VMDeadError: If the VM is dead
... | self.verify_disk_image_bootable()
self.verify_userspace_crash()
self.verify_kernel_crash()
self.verify_illegal_instruction()
self.verify_kvm_internal_error()
try:
virt_vm.BaseVM.verify_alive(self)
if self.monitor:
self.monitor.verify_res... |
flgiordano/netcash | +/google-cloud-sdk/lib/googlecloudsdk/api_lib/compute/firewalls_utils.py | Python | bsd-3-clause | 6,885 | 0.003631 | # Copyright 2014 Google Inc. 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 applicable law or ag... | be either the name of a well-known protocol
(e.g., tcp or icmp) or the IP protocol number.
A list of IP protocols can be found at
link:http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml[].
A port o | r port range can be specified after PROTOCOL to
allow traffic through specific ports. If no port or port range
is specified, connections through all ranges are allowed. For
example, the following will create a rule that allows TCP traffic
through port 80 and allows ICMP traffic:
$ {comm... |
jbloom512/Linear_Algebra_Encryption | Generate_Encryption_Key.py | Python | mit | 3,446 | 0.006384 | #!/usr/bin/env python3
import random
import numpy as np
import sympy
mod_space = 29
'''
Generate Encryption Key
'''
# In --> size of matrix (n x n)
# Out --> List of lists [[1,2,3],[4,5,6],[7,8,9]]
def generate_encryption_key(size):
determinant = 0
# Need to make sure encryption key is invertible, IE det(k... | nd(row) # Add row to matrix
# Convert list of lists into numpy array, which acts as a matrix
encryption_key = np.array(matrix)
try:
determinant = sympy.Matrix(encryption_key.tolist()).inv_mod(29).det()
except:
pass
# If matrix is invertible, end function... | inant = int(np.linalg.det(encryption_key))
return encryption_key
'''
Find Modular Inverse
'''
# In --> number, modspace (default is 29 for our case)
# Out --> modular inverse of number
def modular_inverse(num):
for i in range(mod_space): # Loop through possibile inverses in modspace
if (num * i) ... |
DevangS/CoralNet | bug_reporting/forms.py | Python | bsd-2-clause | 661 | 0.006051 | from django.forms import ModelForm
from bug_reporting.models import Feedback
from CoralNet.forms import FormHelper
class FeedbackForm( | ModelForm):
class Meta:
model = Feedback
fields = ('type', 'comment') # Other fields are auto-set
#error_css_class = ...
#required_css_class = ...
def clean(self):
"""
1. Strip spaces from character fields.
2. Call the parent's clean() to finish up with the d... | ta, self.fields)
self.cleaned_data = data
return super(FeedbackForm, self).clean() |
jacol12345/TP-ankiety-web-app | mobilepolls/manage.py | Python | mit | 254 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__" | :
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mobilepolls.settings")
from django.core.management import execute_from_command_line
|
execute_from_command_line(sys.argv)
|
kayhayen/Nuitka | nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Tool/MSCommon/vc.py | Python | apache-2.0 | 33,537 | 0.006202 | #
# Copyright (c) 2001 - 2019 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge... | VC_VERSION documentation in Tool/msvc.xml.
_VCVER = ["14.2", "14.1", "14.0", "14.0Exp", "12.0", "12.0Exp", "11.0", "11.0Exp", "10.0", "10.0Exp", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
# if using vswhere, a further mapping is needed
_VCVER_TO_VSWHERE_VER = {
'14.2' : '[16.0, 17.0)',
'14.1' : '[15.... | _MACHINE, r'')], # VS 2017 doesn't set this key
'14.0' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir')],
'14.0Exp' : [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\14.0\Setup\VC\ProductDir')],
'12.0' : [
(SCons.Util.HKEY_LOCAL_MACHINE,... |
yanchen036/tensorflow | tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_test.py | Python | apache-2.0 | 57,239 | 0.006918 | # Copyright 2016 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 applica... | ining=False,
seed=None,
kernel_initializer=None,
bias_initializer=None):
if dtype not in (dtypes.float16, dtypes.float32, dtypes.float64):
raise ValueError("Invalid dtype: %s" % dtype)
self._dtype = dtype
self._inputs = array_ops.placeholder(
dtype... | ps.placeholder(
dtype=dtype, shape=[None, None, num_units], name="h")
c = array_ops.placeholder(
dtype=dtype, shape=[None, None, num_units], name="c")
if rnn_mode == CUDNN_LSTM:
model_fn = cudnn_rnn.CudnnLSTM
self._initial_state = (h, c)
elif rnn_mode == CUDNN_GRU:
model_fn... |
citrix-openstack-build/python-cinderclient | cinderclient/tests/v2/fakes.py | Python | apache-2.0 | 24,282 | 0.000124 | # Copyright (c) 2013 OpenStack Foundation
#
# 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 ... | f58b',
'container': 'volumebackups',
'object_count': 220,
'size': 10,
'availability_zone': 'az1',
'created_at': '2013-04-12T08:16:37.000000',
'status': 'available',
'links': [
{
'href': _self_href(base_uri, tenant_id, id),
... | ref': _bookmark_href(base_uri, tenant_id, id),
'rel': 'bookmark'
}
]
}
def _stub_backup(id, base_uri, tenant_id):
return {
'id': id,
'name': 'backup',
'links': [
{
'href': _self_href(base_uri, tenant_id, id),
... |
squarebracket/star | registrator/models/registration_proxy.py | Python | gpl-2.0 | 1,141 | 0.001753 | from registrator.models.registration_entry import RegistrationEntry
from uni_info.models import Section
class RegistrationProxy(RegistrationEntry):
"""
Proxy class which handles actually doing the registration in a system
of a :model:`registrator.RegistrationEntry`
"""
# I guess functions for reg... | ould go here?
def add_schedule_item(self, schedule_item):
section_list = schedule_item.sections
sections = {}
sections['MainSec'] = section_list[0]
for i in range(1, len(section_list)):
| sections['RelSec' + str(i)] = section_list[i]
sections['course_letters'] = section_list[0].course.course_letters
sections['course_numbers'] = section_list[0].course.course_numbers
sections['session'] = section_list[0].semester_year
sections['CatNum'] = '12345'
sections['St... |
clarete/docket | docket/command_line.py | Python | mit | 1,369 | 0.005844 | import argparse
import docker
import logging
import os
import docket
logger = logging.getLogger('docket')
logging.basicConfig()
parser = argparse.ArgumentParser(description='')
parser.add_argument('-t --tag', dest='tag', help='tag for final image')
parser.add_argument('--verbose', dest='verbose', action='store_true',... | iron.get('DOCKER_HOST', 'tcp://127.0.0.1:2375')
base_url = base_url.replace('tcp:', 'https:')
tls_config = None
if cert_path:
tls_config = docker.tls.TLSConfig(verify=tls_verify,
client_cert=(os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem')),
ca_cert=os.path.join(cert_path, '... | ne
buildpath = args.buildpath[0]
def main():
docket.build(client=client, tag=tag, buildpath=buildpath, no_cache=args.no_cache)
exit()
if __name__ == '__main__':
main()
|
bartosh/zipline | zipline/utils/preprocess.py | Python | apache-2.0 | 7,205 | 0 | """
Utilities for validating inputs to user-facing API functions.
"""
from textwrap import dedent
from types import CodeType
from functools import wraps
from inspect import getargspec
from uuid import uuid4
from toolz.curried.operator import getitem
from six import viewkeys, exec_, PY3
_code_argorder = (
('co_ar... | __name__,
signature=', '.join(signature),
assignments='\n '.join(assignments),
wrapped_funcname=mangled_funcname,
call_args=', '.join(call_args),
| )
compiled = compile(
exec_str,
func.__code__.co_filename,
mode='exec',
)
exec_locals = {}
exec_(compiled, exec_globals, exec_locals)
new_func = exec_locals[func.__name__]
code = new_func.__code__
args = {
attr: getattr(code, attr)
for attr in dir... |
163gal/Time-Line | libs64/wx/tools/XRCed/plugins/controls.py | Python | gpl-3.0 | 19,978 | 0.00866 | # Name: controls.py
# Purpose: Control components
# Author: Roman Rolinsky <rolinsky@femagsoft.com>
# Created: 31.05.2007
# RCS-ID: $Id: core.py 47823 2007-07-29 19:24:35Z ROL $
from wx.tools.XRCed import component, images, attribute, params
from wx.tools.XRCed.globals import TRACE
import... | ', 'wxSL_SELRANGE', 'wxSL_INVERSE')
component.Manager.register(c)
c.setParamClass('value', params.ParamInt)
c.setParamClass('tickfreq', params.ParamIntNN)
c.setParamClass('pagesize', params.ParamIntNN)
c.setParamClass('linesize', params.ParamIn | tNN)
c.setParamClass('thumb', params.ParamUnit)
c.setParamClass('tick', params.ParamInt)
c.setParamClass('selmin', params.ParamInt)
c.setParamClass('selmax', params.ParamInt)
c.addEvents('EVT_SCROLL', 'EVT_SCROLL_TOP', 'EVT_SCROLL_BOTTOM',
'EVT_SCROLL_LINEUP', 'EVT_SCROLL_LINEDOWN', 'EVT_SCROLL_PAGEUP',
... |
hcs/mailman | src/mailman/commands/cli_version.py | Python | gpl-3.0 | 1,359 | 0.000736 | # Copyright (C) 2009-2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it u | nder
# 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.
#
# GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY... | License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# GNU Mailman. If not, see <http://www.gnu.org/licenses/>.
"""The Mailman version."""
from __future__ import absolute_import, print_function, unicode_literals
__metaclass__ = type
__all__ = [
'Version',
... |
sanjayankur31/pyjigdo | pyJigdo/__init__.py | Python | gpl-2.0 | 827 | 0 | #
# Copyright 2007-2009 Fedora Unity Project (http://fedoraunity.org)
#
# This progr | am 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, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# ... |
ahmedaljazzar/edx-platform | openedx/core/lib/tests/test_courses.py | Python | agpl-3.0 | 3,146 | 0.001271 | """
Tests for functionality in openedx/core/lib/courses.py.
"""
import ddt
from django.test.utils import override_settings
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from ..course... | "Test image URL formatting."""
course = CourseFactory.create()
self.verify_url(
unicode(course.id.make_ass | et_key('asset', course.course_image)),
course_image_url(course)
)
def test_non_ascii_image_name(self):
""" Verify that non-ascii image names are cleaned """
course_image = u'before_\N{SNOWMAN}_after.jpg'
course = CourseFactory.create(course_image=course_image)
se... |
hipnusleo/laserjet | resource/pypi/cryptography-1.7.1/tests/hazmat/backends/test_openssl.py | Python | apache-2.0 | 28,781 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import datetime
import itertools
import os
import subprocess
im... | .NULL
)
cipher = Cipher(
Dumm | yCipherAlgorithm(), mode, backend=b,
)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
cipher.encryptor()
def test_openssl_assert(self):
backend.openssl_assert(True)
with pytest.raises(InternalError):
backend.openssl_assert(False)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.