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 |
|---|---|---|---|---|---|---|---|---|
tracim/tracim-webdav | wsgidav/addons/tracim/sql_resources.py | Python | mit | 16,929 | 0.000945 | # coding: utf8
from wsgidav.dav_provider import DAVCollection, DAVNonCollection
from wsgidav.dav_error import DAVError, HTTP_FORBIDDEN
from wsgidav import util
from wsgidav.addons.tracim import role, MyFileStream
from time import mktime
from datetime import datetime
from os.path import normpath, dirname, basename
try... | se:
self.provi | der.add_workspace(basename(normpath(destpath)))
def supportRecursiveMove(self, destpath):
return True
def moveRecursive(self, destpath):
if not self.provider.has_right(
self.environ["http_authenticator.username"],
self.workspace.workspace_id,
rol... |
shahankhatch/aurora | src/main/python/apache/aurora/executor/common/announcer.py | Python | apache-2.0 | 8,388 | 0.008345 | #
# 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 ... | ()
self._joiner()
def stop(self):
self._stopped.set()
class Announcer(Observable):
class Error(Exception): pass
EXCEPTION_WAIT = Amount(15, Time.SECONDS)
def __init__(self,
serverset,
endpoint,
additional=None,
shard=None,
... | oint
self._additional = additional or {}
self._shard = shard
self._serverset = serverset
self._rejoin_event = threading.Event()
self._clock = clock
self._thread = None
self._exception_wait = exception_wait or self.EXCEPTION_WAIT
def disconnected_time(self):
# Lockless membership lengt... |
larose/utt | utt/plugins/0_hello.py | Python | gpl-3.0 | 593 | 0.003373 | import argparse
from ..api import _v1
class HelloHandler:
def __init__(
self, args: argparse.Namespace, now: _v1.Now, add_entry: _v1._private.AddEntry,
):
self._args = args
self._now = now
self._add_entry = add_entry
def __call__(self):
self._add_e | ntry(_v1.Entry(self._now, _v1.HELLO_ENTRY_NAME, False))
hello_command = _v1.Command(
| "hello",
"Say '{hello_entry_name}' when you arrive in the morning...".format(hello_entry_name=_v1.HELLO_ENTRY_NAME),
HelloHandler,
lambda p: None,
)
_v1.register_command(hello_command)
|
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/edx_proctoring/migrations/0001_initial.py | Python | agpl-3.0 | 13,525 | 0.00414 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.conf import settings
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODE... | ose_name': 'proctored exam review policy history',
},
),
migrations.CreateModel(
name='ProctoredExamSoftwareSecureComment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
| ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),
('start_time', models.Integ... |
dogukantufekci/supersalon | supersalon/users/admin.py | Python | bsd-3-clause | 1,106 | 0.000904 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.a | uth.forms import UserChangeForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _
from .models import User
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta | ):
model = User
class MyUserCreationForm(UserCreationForm):
error_message = UserCreationForm.error_messages.update({
'duplicate_username': _("This username has already been taken.")
})
class Meta(UserCreationForm.Meta):
model = User
def clean_username(self):
username... |
Rctue/DialogStateMachine | DialogTest_2_AskDeviceOnFinger.py | Python | gpl-2.0 | 1,079 | 0.013902 | #!/usr/bin/env python
from sre_parse import isdigit
import sys
__author__ = 'jpijper'
import roslib; roslib.load_manifest('smach_tutorials')
import rospy
import smach_ros
from DialogStateMachine import SMDialog
def main():
# To restrict the amount of feedback to the screen, a feedback leve | l can be given on the command line.
# Level 0 means show only the most urgent feedback and the higher the level, the more is shown.
feedback_level = int(sys.argv[1]) if len(sys.argv) > 1 and isdigit(sys.argv[1]) else 10
rospy.init_node('sm_dialog_ask_device_on_finger')
sm_top = SMDialog('ask_device_on_... | s = smach_ros.IntrospectionServer('server_name', sm_top, '/SM_ROOT')
#sis.start()
## end insert
# Execute SMACH plan
outcome = sm_top.execute()
## inserted for smach_viewer
# Wait for ctrl-c to stop the application
#rospy.spin()
#sis.stop()
## end insert
if __name__ == '__main... |
JoelEager/pyTanks.Server | dataModels/command.py | Python | mit | 2,194 | 0.002735 | import json
import numbers
import html
import config
class command:
"""
Used to store an incoming player command
"""
def __init__(self, message):
"""
Called with a raw message string from a client
:raise: ValueError if the message isn't a valid command
"""
# Try... | self.action = message["action"]
# Check for a valid arg if it's required
if self.action == config.server.commands.turn or self.action == config.server.commands.fire:
if not isinstance(message.get("arg"), numbers.Number):
raise ValueError("Missing or invalid arg")
... | if len(self.arg) > config.server.commands.infoMaxLen:
raise ValueError("Info string is longer than " + str(config.server.commands.infoMaxLen) + " characters")
self.arg = html.escape(self.arg)
self.arg = self.arg.replace("\n", " <br /> ")
# Parse urls
... |
moniker-dns/debian-beaver | beaver/transports/sqs_transport.py | Python | mit | 3,043 | 0.003615 | # -*- coding: utf-8 -*-
import boto.sqs
import uuid
from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException
class SqsTransport(BaseTransport):
def __init__(self, beaver_config, logger=None):
super(SqsTransport, self).__init__(beaver_config, l... | t_access_key=self._secret_key)
if self._connection is None:
self._logger.warn('Unable to connect to AWS - check your AWS credentials')
raise TransportException('Unable to connect to AWS - check your AWS credentials')
self._queue = self._connection.get_queue(self... | raise TransportException(e.message)
def callback(self, filename, lines, **kwargs):
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
message_batch = []
for line in lines:
message_batch.append((uuid.uui... |
vongochung/ngudan | permission_backend_nonrel/admin.py | Python | bsd-3-clause | 5,050 | 0.002178 | from django import forms
from django.contrib import admin
from django.utils.translation import ugettext
from django.contrib.auth.admin import UserAdmin
from django.contrib.admin.sites import NotRegistered
from django.contrib.auth.models import User, Group, Permission
from django.contrib.admin.widgets import FilteredSel... | init__(*args, **kwargs)
self.fields['user_permissions'] = forms.MultipleChoiceField(required=False)
self.fields['groups'] = forms.MultipleChoiceField(required=False)
permissions_objs = Permission.objects.all().order_by('name')
choices = []
for perm_obj in permissions_objs:
... | es = choices
group_objs = Group.objects.all()
choices = []
for group_obj in group_objs:
choices.append([group_obj.id, group_obj.name])
self.fields['groups'].choices = choices
try:
user_perm_list = UserPermissionList.objects.get(
user=kwar... |
project-rig/network_tester | examples/getting_started_example.py | Python | gpl-2.0 | 1,458 | 0.000686 | """This is (more-or-less) the example experiment described in the getting
started section of the manual.
In this experiment we simply measure the number of | packets received as we ramp
up the amount of traffic generated.
"""
import sys
import random
from network_tester import Experiment, to_csv
# Take the SpiNNaker board IP/hostname from the command-line
e = Experiment(sys.argv[1])
# Define a random network
cores = [e.new_core() for _ in range(64)]
flows = [e.new_flow(... | 1e-5 # 10 us
# Sweep over a range of packet-generation probabilities
num_steps = 10
for step in range(num_steps):
with e.new_group() as group:
e.probability = step / float(num_steps - 1)
group.add_label("probability", e.probability)
# Run each group for 1/10th of a second (with some time for war... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_runtime_features/sys_current_frames.py | Python | apache-2.0 | 1,093 | 0 | import sys
import threading
import time
io_lock = threading.Lock()
blocker = threading.Lock()
def block(i):
t = threading.current_thread()
with io_lock:
print('{} with ident {} going to sleep'.format(
t.name, t.ident))
if i:
blocker.acquire() # acquired but never released
... | # Main thread
continue
print('{} stopped in {} at line {} of {}'.format(
t.name, frame.f_code.co_name,
frame.f_lineno, frame.f_code.co_filename))
| |
hughperkins/kgsgo-dataset-preprocessor | thirdparty/future/tests/test_future/test_requests.py | Python | mpl-2.0 | 3,385 | 0.001182 | """
Tests for whether the standard library hooks in ``future`` are compatible with
the ``requests`` package.
"""
from __future__ import absolute_import, unicode_literals, print_function
from future import standard_library
from future.tests.base import unittest, CodeHandler
import textwrap
import sys
import os
import i... | elf, code, tempdir):
self.code = code
self.tempdir = tempdir
def __enter__(self):
print('Creating {0}test_imports_future_stdlib.py ...'.format(se | lf.tempdir))
with io.open(self.tempdir + 'test_imports_future_stdlib.py', 'wt',
encoding='utf-8') as f:
f.write(textwrap.dedent(self.code))
sys.path.insert(0, self.tempdir)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
If an ... |
JonSteinn/Kattis-Solutions | src/Red Rover/Python 3/rr.py | Python | gpl-3.0 | 479 | 0.004175 | def all_substr(string):
s = set()
length = len(strin | g)
for i in range(length):
for j in range(i, length + 1):
s.add(string[i:j])
return s
def compr(string, substring):
l = len(substring)
c = string.count(substring)
return len(string) - c * (l-1) + l |
def min_enc(string):
x = len(string)
for s in all_substr(string):
y = compr(string, s)
if y < x:
x = y
return x
print(min_enc(input())) |
KaiSzuttor/espresso | samples/immersed_boundary/sampleImmersedBoundary.py | Python | gpl-3.0 | 3,388 | 0.001771 | # Copyright (C) 2010-2019 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 version 3 of the License, or
# (at your option) any later v... | f a spherical red blood cell-like particle advected
in a planar Poiseuille flow, with or without volume conservation. For more
details, see :ref:`Immersed Boundary Method for soft elastic objects`.
"""
import espressomd
required_features = ["LB_BOUNDARIES", "VIRTUAL_SITES_INERTIALESS_TRACERS",
| "EXPERIMENTAL_FEATURES"]
espressomd.assert_features(required_features)
from espressomd import lb, shapes, lbboundaries
from espressomd.virtual_sites import VirtualSitesInertialessTracers
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--no-volcons", action="store_const", dest="v... |
seftler/GPSstorage | manage.py | Python | mit | 808 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GPSstorage.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 is missing to avoid masking other
# exceptions on Python 2.
try:
import djang... |
dsajkl/123 | lms/envs/common.py | Python | agpl-3.0 | 62,841 | 0.002803 | # -*- coding: utf-8 -*-
"""
This is the common settings file, intended to set sane defaults. If you have a
piece of configuration that's dependent on a set of feature flags being set,
then create a function that returns the calculated value based on the value of
FEATURES[...]. Modules that extend this one can change th... | # Enable instructor to assign individual due dates
'INDIVIDUAL_DUE_DATES': False,
# Enable legacy instructor dashboard
'ENABLE_INSTRUCTOR_LEGACY_DASHBOARD': True,
# Is this an edX-owned domain? (used on instructor dashboard)
'IS_EDX_DOMAIN': False,
# Toggle to enable certificates of courses on... | AUTOMATIC_AUTH_FOR_TESTING': False,
# Toggle to enable chat availability (configured on a per-course
# basis in Studio)
'ENABLE_CHAT': |
pynamodb/PynamoDB | pynamodb/settings.py | Python | mit | 2,509 | 0.004384 | import importlib.util
import logging
import os
import warnings
from os import getenv
from typing import Any, Optional, Mapping, ClassVar
log = logging.getLogger(__name__)
default_settings_dict = {
'connect_timeout_seconds': 15,
'read_timeout_seconds': 30,
'max_retry_attempts': 3,
'base_backoff_ms': 2... | 'extra_headers': None,
}
OVERRIDE_SETTINGS_ | PATH = getenv('PYNAMODB_CONFIG', '/etc/pynamodb/global_default_settings.py')
def _load_module(name, path):
# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec) # type: i... |
pmghalvorsen/gramps_branch | gramps/gen/plug/report/_reportbase.py | Python | gpl-2.0 | 2,801 | 0.002499 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001 David R. Hampton
# Copyright (C) 2001-2006 Donald N. Allingham
# Copyright (C) 2007 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | pass
def set_locale(self, language):
"""
Set the translator to one selected with
stdoptions.add_localization_option().
"""
if language == GrampsLocale.DEFAULT_TRANSLATION_STR:
language = None
locale = GrampsLocale(lang=language)
self._ = loc | ale.translation.gettext
self._get_date = locale.get_date
self._get_type = locale.get_type
self._dd = locale.date_displayer
self._name_display = NameDisplay(locale) # a legacy/historical name
return locale
def write_report(self):
pass
def end_report(self):
... |
pombreda/fMBT | pythonshare/pythonshare/__init__.py | Python | lgpl-2.1 | 2,903 | 0.004478 | # fMBT, free Model Based Testing tool
# Copyright (c) 2013, Intel Corporation.
#
# Author: antti.kervinen@intel.com
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foun... | Error):
pass
class RemoteExecError(PythonShareError):
pass
class RemoteEvalError(PythonShareError):
pass
class AsyncStatu | s(object):
pass
class InProgress(AsyncStatus):
pass
# Misc helpers for client and server
def _close(*args):
for a in args:
if a:
try:
a.close()
except (socket.error, IOError):
pass
def connection(hostspec, password=None):
if not "://" in... |
AdrianRibao/notifintime | notifintime/admin.py | Python | bsd-3-clause | 58 | 0.017241 | # - | *- coding: utf-8 -*-
#from django.contrib import admin
| |
hclivess/Stallion | nuitka/Cryptodome/Hash/MD2.py | Python | gpl-3.0 | 6,130 | 0.001305 | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... | bfr)
if result:
raise ValueError("Error %d while instantiating MD2"
% result)
return get_raw_buffer(bfr)
def hexdigest(self):
"""Return the **printable** digest of the message that has been hashed so far.
:return: The hash di | gest, computed over the data processed so far.
Hexadecimal encoded.
:rtype: string
"""
return "".join(["%02x" % bord(x) for x in self.digest()])
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as th... |
eduNEXT/edunext-platform | import_shims/lms/grades/exceptions.py | Python | agpl-3.0 | 374 | 0.008021 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from i | mport_shims.warn import warn_deprecated_import
warn_deprecated_import('grades.exceptions', 'lms.djangoapps.grades.exceptions')
from lms.djangoapps.grades. | exceptions import *
|
Weatherlyzer/weatherlyzer | base/cron.py | Python | mit | 264 | 0.003788 | import kronos
import random
@kronos.register('0 0 * * *')
def complain():
complaints = | [
"I forgot to migrate our applications's cron jobs to our new server! Darn!",
| "I'm out of complaints! Damnit!"
]
print random.choice(complaints)
|
salvacarrion/orange3-recommendation | orangecontrib/recommendation/widgets/__init__.py | Python | bsd-2-clause | 2,082 | 0.001921 | import sysconfig
# Category metadata.
# Category icon show in the menu
ICON = "icons/star2.svg"
# Background color | for category background in menu
# and widget icon background in workflow.
BACKGROUND = "light-blue"
# Location of widget help files.
WIDGET_HELP_PATH = (
# No local documentation (There are problems with it, so Orange3 widgets
# usually don't use it)
# Local documentation. This fake line is needed to acce... | tation is not available.
# Url should point to a page with a section Widgets. This section should
# includes links to documentation pages of each widget. Matching is
# performed by comparing link caption to widget name.
# IMPORTANT TO PUT THE LAST SLASH '/'
("http://orange3-recommendation.readthedoc... |
shakcho/Indic-language-ngram-viewer | demo.py | Python | mit | 120 | 0.033333 | a = "nabb jasj | jjs, jjsajdhh kjkda jj"
a1 = a.split(",")
for i in range(0,len(a1)):
print (len(a1[i].s | plit())) |
obulpathi/poppy | poppy/transport/pecan/controllers/v1/services.py | Python | apache-2.0 | 9,877 | 0 | # Copyright (c) 2014 Rackspace, 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 wr... | port.pecan.models.response import service as resp_service_model
from poppy.transport.validators import helpers
from poppy.transport.validators.schemas import service
from poppy.transport.validators.stoplight import decorators
from poppy.transport.validators.stoplight import exceptions
from popp | y.transport.validators.stoplight import helpers as stoplight_helpers
from poppy.transport.validators.stoplight import rule
LIMITS_OPTIONS = [
cfg.IntOpt('max_services_per_page', default=20,
help='Max number of services per page for list services'),
]
LIMITS_GROUP = 'drivers:transport:limits'
clas... |
ksmit799/Toontown-Source | toontown/trolley/Trolley.py | Python | mit | 7,361 | 0.005434 | from pandac.PandaModules import *
from toontown.toonbase.ToonBaseGlobal import *
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.fsm import StateData
from toontown.toontown... | ck')
self.noTrolleyBox.cleanup()
del self.noTrolleyBox
def __handleNoTrolleyAck(self):
ntbDoneStatus = self.noTrolleyBox.doneStatus
if ntbDoneStatus == 'ok':
doneStatus = {}
doneStatus['mode'] = 'reject'
messenger.send(self.doneEvent, [doneStatus]... | tify.error('Unrecognized doneStatus: ' + str(ntbDoneStatus))
def enterRequestBoard(self):
return None
def handleRejectBoard(self):
doneStatus = {}
doneStatus['mode'] = 'reject'
messenger.send(self.doneEvent, [doneStatus])
def exitRequestBoard(self):
return None
... |
t3dev/odoo | addons/website_sale/models/product.py | Python | gpl-3.0 | 20,625 | 0.003782 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError
from odoo.addons import decimal_precision as dp
from odoo.addons.website.models import ir_http
from odoo.tools.translate import h... | t create recursive categories.'))
| @api.multi
def name_get(self):
res = []
for category in self:
names = [category.name]
parent_category = category.parent_id
while parent_category:
names.append(parent_category.name)
|
mnahm5/django-estore | Lib/site-packages/awscli/customizations/emr/ssh.py | Python | mit | 7,731 | 0 | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | rminated
if parsed_args.dest:
command[-1] = command[-1] + ":" + parsed_args.dest
else:
command[-1] = comm | and[-1] + ":" + parsed_args.src.split('/')[-1]
print(' '.join(command))
rc = subprocess.call(command)
return rc
class Get(Command):
NAME = 'get'
DESCRIPTION = ('Get file from master node.\n%s' % KEY_PAIR_FILE_HELP_TEXT)
ARG_TABLE = [
{'name': 'cluster-id', 'required': True,... |
baby5/Django-httpbin | httpbin/bin/helpers.py | Python | mit | 1,339 | 0.004481 | from functools import wraps
import json
from django.http import JsonResponse, HttpResponseNotAllowed
from django.utils.decorators import available_attrs
def methods(method_list):
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kw):
if requ... | se iterator
if key.startswith('HTTP_'):
headers['-'.join(key.split('_')[1:]).title()] = value
elif key.startswith('CONTENT'):
headers['-'.join(key.split('_')).title()] = value
return headers
def no_get(request):
rep_dict = {
'args': request.GET,
... | quest),
'json': None,
'origin': request.META['REMOTE_ADDR'],
'url': request.build_absolute_uri(),
}
if 'json' in request.content_type:
try:
rep_dict['json'] = json.loads(request.body)
except:
pass
return rep_dict
|
komuW/sewer | sewer/dns_providers/tests/test_rackspace.py | Python | mit | 8,481 | 0.003184 | from unittest import mock
from unittest import TestCase
from sewer.dns_providers.rackspace import RackspaceDns
from . import test_utils
class TestRackspace(TestCase):
"""
"""
def setUp(self):
self.domain_name = "example.com"
self.domain_dns_value = "mock-domain_dns_value"
self.R... | zone_id, mock_dns_zone_id)
self.assertTrue(mock_requests_get.called)
def test_find_dns_record_id(self):
with mock.patch("requests.get") as mock_requests_get, mock.patch(
"sewer.dns_providers.rackspace.RackspaceDns.find_dns_zone_id"
) as mock_find_dns_zone_id:
# s... | 4"
mock_requests_content = {
"totalEntries": 1,
"records": [
{
"name": self.domain_name,
"id": mock_dns_record_id,
"type": "A",
"data": self.domain_dns_value,
... |
tchellomello/home-assistant | homeassistant/components/isy994/__init__.py | Python | apache-2.0 | 8,442 | 0.000711 | """Support the ISY-994 controllers."""
import asyncio
from functools import partial
from typing import Optional
from urllib.parse import urlparse
from pyisy import ISY
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeass... | ries.ConfigEntry, isy
) -> None:
device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
connections={(dr.CONNECTION_N | ETWORK_MAC, isy.configuration["uuid"])},
identifiers={(DOMAIN, isy.configuration["uuid"])},
manufacturer=MANUFACTURER,
name=isy.configuration["name"],
model=isy.configuration["model"],
sw_version=isy.configuration["firmware"],
)
async def async_unload_entry(
hass: HomeA... |
carlsonp/kaggle-TrulyNative | processURLS_count.py | Python | gpl-3.0 | 2,502 | 0.031575 | from __future__ import print_function
import re, os, sys, multiprocessing, zipfile, Queue
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from urlparse import urlparse
#https://pypi.python.org/pypi/etaprogress/
from etaprogress.progress import ProgressBar
#337304 total HTML files, some are actuall... | ))
#print("Normal pages: ", G.out_degree("NOTSPONSORED"))
#if G.out_degree("TESTING") != 235917:
#print("Error, invalid number of testing nodes.")
#if G.out_degree("SPONSORED") + G.out_deg | ree("NOTSPONSORED") != 101107:
#print("Error, invalid number of training nodes.")
|
pmarks-net/dtella | dtella/common/core.py | Python | gpl-2.0 | 131,965 | 0.001523 | """
Dtella - Core P2P Module
Copyright (C) 2008 Dtella Labs (http://www.dtella.org)
Copyright (C) 2008 Paul Marks
$Id$
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 2
of the Licen... | JOIN_BIT = 0x1
# Bridge general flags
MODERATED_BIT = 0x1
# Init response codes
CODE_IP_OK = 0
CODE_IP_FOREIGN = 1
CODE_IP_BANNED = 2
##############################################################################
class NickManager(object):
def __init__(self, main):
self.main = main
self.nickm... | getNickList(self):
return [n.nick for n in self.nickmap.itervalues()]
def lookupNick(self, nick):
# Might raise KeyError
return self.nickmap[nick.lower()]
def removeNode(self, n, reason):
try:
if self.nickmap[n.nick.lower()] is not n:
raise KeyErr... |
edx/edx-ora2 | openassessment/xblock/studio_mixin.py | Python | agpl-3.0 | 20,504 | 0.003414 | """
Studio editing view for OpenAssessment XBlock.
"""
import copy
import logging
from uuid import uuid4
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy
from voluptuous import MultipleInvalid
from xblock.fields import List, Scope
from xblock.core import XBlock
from... | 'white_listed_file_types': white_listed_file_types_string,
'allow_latex': self.allow_latex,
'leaderboard_show': self.leaderboard_show,
'editor_assessments | _order': [
make_django_template_key(asmnt)
for asmnt in self.editor_assessments_order
],
'teams_feature_enabled': self.team_submissions_enabled,
'teams_enabled': self.teams_enabled,
'base_asset_url': self._get_base_url_path_for_course_asset... |
boos/cppcheck | addons/findcasts.py | Python | gpl-3.0 | 1,197 | 0.001671 | #!/usr/bin/env python3
#
# Locate casts in the code
#
import cppcheckdata
import sys
for arg in sys.argv[1:]:
if arg.startswith('-'):
continue
print('Checking %s...' % arg)
data = cppcheckdata.CppcheckData(arg)
for cfg in data.iterconfigurations():
print('Checking %s, config %s...' %... | g, cfg.name))
for token in cfg.tokenlist:
if token.str != '(' or not token.astOperand1 or token.astOp | erand2:
continue
# Is it a lambda?
if token.astOperand1.str == '{':
continue
# we probably have a cast.. if there is something inside the parentheses
# there is a cast. Otherwise this is a function call.
typetok = token.next
... |
lucashtnguyen/pybmpdb | pybmpdb/tests/summary_tests.py | Python | bsd-3-clause | 29,742 | 0.001143 | import sys
import os
from pkg_resources import resource_filename
pythonversion = sys.version_info.major
from six import StringIO
import mock
import nose.tools as nt
import numpy as np
import numpy.testing as nptest
import matplotlib.pyplot as plt
import pandas
import pandas.util.testing as pdtest
import... | df}
\caption{Influent vs. Effluent Plots of Carbon Dioxide at testbmp BMPs}
\end{figure} \clearpage""" + '\n'
self.known_latex_input_ff = ''
self.known_latex_input_ft = r"""\subsection{testbmp}
\begin{table}[h!]
\caption{test table title}
\cen... | oprule
Count & NA & 25 \\
\midrule
Number of NDs & NA & 5 \\
\midrule
Min; Max & NA & 0.123; 123 \\
\midrule
Mean & NA & 12.3 \\
%%
(95\% confidence interval) & NA & (... |
zeckalpha/mindfeed | mindfeed/__init__.py | Python | mit | 75 | 0 | from mi | ndfeed.mindfeed import main
if __name__ == "__main | __":
main()
|
qsheeeeen/Self-Driving-Car | rl_toolbox/agent/__init__.py | Python | mit | 26 | 0 | from .ppo | import PPOAgent
| |
uaprom-summer-2015/Meowth | commands/static.py | Python | bsd-3-clause | 3,080 | 0 | from subprocess import call
import os
from flask.ext.script import Manager
from commands.utils import perform
def alt_exec(cmd, alt=None):
"""
Tries to execute command.
If command not found, it tries to execute the alternative comand
"""
try:
call(cmd)
except OSError as e:
if... | if silent:
cmd_args.append("--silent")
alt_exec(
cmd=["bower", "install"] + cmd_args,
alt=["./node_modules/bower/bin/bower", "install"] + cmd_args,
)
@StaticCommand.option(
'--deploy-type',
dest='deploy_type',
default="production",
help='Set de... | perform(
name='static gulp',
before='run gulp',
):
cmd_args = list()
if deploy_type is not None:
cmd_args.append("--type")
cmd_args.append(deploy_type)
alt_exec(
cmd=["gulp"] + cmd_args,
alt=["./node_modules/gulp/bin/gu... |
izapolsk/integration_tests | cfme/tests/configure/test_version.py | Python | gpl-2.0 | 824 | 0.002427 | import pytest
from cfme import test_requirements
from cfme.configure import about
@test_requirements.appliance
@pytest. | mark.tier(3)
@pytest.mark.sauce
def test_appliance_version(appliance):
"""Check version presented in UI against version retrieved directly from the machine.
Version retrieved from appliance is in this format: 1.2.3.4
Version in the UI is always: 1.2.3.4.20140505xyzblabla
So we check whether the UI ver... | with SSH version
Polarion:
assignee: jhenner
casecomponent: Appliance
caseimportance: high
initialEstimate: 1/4h
"""
ssh_version = str(appliance.version)
ui_version = about.get_detail(about.VERSION, server=appliance.server)
assert ui_version.startswith(ssh_version), ... |
bskinn/run_jensen | run_jensen.py | Python | mit | 65,917 | 0.008829 | #-------------------------------------------------------------------------------
# Name: run_jensen
# Purpose: Automated execution of diatomic M-L computations in the form
# of Jensen et al. J Chem Phys 126, 014103 (2007)
#
# Author: Brian
#
# Created: 8 May 2015
# Copyright: ... | ate_str)
# Log the template file contents
logger.info("Template file '" + template_file + "' contents:\n\n" + \
template_str)
# Store the starting time
start_time = time.t | ime()
# Retrieve the data repository
repo = h5.File(repofname, 'a')
# Log the restart
logger.info("Restarting '" + build_base(m, nm, chg) + \
"' at multiplicity " + str(mult) + ", reference " + \
"multiplicity " + str(ref))
# Run the diatomic optimization... |
lqez/django-summernote | django_summernote/admin.py | Python | mit | 974 | 0.001027 | from django.contrib import admin
from django.db import models
fr | om django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget
from django_summernote.settings import summernote_config, get_attachment_model
__widget__ = SummernoteWidget if summernote_config['iframe'] \
else SummernoteInplaceWidget
class SummernoteInlineModelAdmin(admin.options.InlineM | odelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class SummernoteModelAdmin(admin.ModelAdmin):
formfield_overrides = {models.TextField: {'widget': __widget__}}
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file', 'uploaded']
search_fields = ['name']
... |
withtwoemms/pygame-explorations | render_particle.py | Python | mit | 926 | 0.009719 | import pygame
pygame.init()
#-- SCREEN CHARACTERISTICS ------------------------->>>
background_color = (255,255,255)
(width, height) = (300, 200)
class Particle:
def __init__(self, (x, y), radius):
self.x = x
self.y = y
self | .radius = radius
self.color = (255, 0, 0)
self.thickness = 1
def display(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius, self.thickness)
#-- RENDER SCREEN ---------------------------------->>>
screen = pygame.display.set_mode((width, height))
screen.fill(backgr... | RUN LOOP --------------------------------------->>>
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
|
mpvismer/gltk | offscreenrender.py | Python | mit | 3,321 | 0.013851 | """
For using OpenGL to render to an off screen buffer
Ref:
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from OpenGL.GL import *
from OpenGL.raw.GL.VERSION import GL_1_1,GL_1_2, GL_3_0
class OffScreenRender(... | L_DRAW_FRAMEBUFFER, fbo)
render_buf = glGenRenderbuffers(1)
self._render_buf = render_buf
glBindRenderbuffer(GL_RENDERBUFFER, render_buf)
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, self._width, self._height)
glFramebufferRenderbuffer(GL | _DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, render_buf)
if depth:
depth = glGenRenderbuffers(1)
self._depth = depth
glBindRenderbuffer(GL_RENDERBUFFER, depth)
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, self._width, se... |
d4l3k/compute-archlinux-image-builder | arch-staging.py | Python | apache-2.0 | 5,271 | 0.011762 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 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... | 'fakeroot').split()
IMAGE_PACKAGES = ('base tar wget '
'curl sudo mkinitcpio syslinux dhcp ethtool irqbalance '
'ntp psmisc openssh udev less bash-completion zip unzip '
'python2 python3').split()
def main():
args = utils.DecodeArgs(sys.argv[1])
... | )
image_path = os.path.join(os.getcwd(), IMAGE_FILE)
CreateImage(image_path, size_gb=int(args['size_gb']))
mount_path = utils.CreateTempDirectory(base_dir='/')
image_mapping = utils.ImageMapper(image_path, mount_path)
try:
image_mapping.Map()
primary_mapping = image_mapping.GetFirstMapping()
image... |
mancoast/CPythonPyc_test | fail/331_test_re.py | Python | gpl-3.0 | 54,426 | 0.002536 | from test.support import verbose, run_unittest, gc_collect, bigmemtest, _2G, \
cpython_only
import io
import re
from re import Scanner
import sys
import string
import traceback
from weakref import proxy
# Misc tests from Tim Peters' re.doc
# WARNING: Don't change details in these tests if you don't know
# wha... | .match('a*', 'xxx').span(0), (0, 0))
self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
self.assertEqual(re.match('a+', 'xxx'), None)
def bump_num(self, matchobj):
... | (re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
'9.3 -3 24x100y')
self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
'9.3 -3 23x99y')
self.assertEqual(re.sub('.', la... |
ffakhraei/pProj | python/codility/ch15/countDistinctSlices.py | Python | gpl-3.0 | 350 | 0.04 | #/bin/env/python
A=[3,4,5,5,2]
M=6
def solution(M, A) :
n=len(A)
| total = 0
for back in xrange(n) :
front = back
while front < n and A[front] not in A[back:front] :
total += 1
front += 1
if total >= 1000000000 :
return 1000000000
retu | rn total
print solution(M, A)
|
gregoil/rotest | src/rotest/common/django_utils/fields.py | Python | mit | 2,999 | 0 | """Contain common module fields."""
# pylint: disable=too-many-public-methods
from __future__ import absolute_import
import re
from django.db import models
from django.core.exceptions import ValidationError
class NameField(models.CharField):
"""Item name string field.
This field is limited to 64 characters ... | N = 17 # enables writing exactly 16 characters
MAC_ADDRESS_REGEX = '(([0-9a-fA-F]{2}): | ){5}[0-9a-fA-F]{2}'
def __init__(self, max_length=MAX_LEN, *args, **kwargs):
super(MACAddressField, self).__init__(*args,
max_length=max_length,
**kwargs)
def validate(self, value, model_instance):
"""V... |
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/connectivity/disjoint_paths.py | Python | gpl-3.0 | 14,544 | 0.000619 | """Flow based node and edge disjoint paths."""
import networkx as nx
from networkx.exception import NetworkXNoPath
# Define the default maximum flow function to use for the undelying
# maximum flow computations
from networkx.algorithms.flow import edmonds_karp
from networkx.algorithms.flow import preflow_push
from net... | low"] and d["flow"] > 0
]
# This is equivalent of what flow.utils.build_flow_dict returns, but
# only for the nodes with saturated edges and without reporting 0 flows.
flow_dict = {n: {} for edge in cutset for n in edge}
for u, v in cutset:
flow_dict[u][v] = 1
# Rebuild the edge disjoin... | ound >= cutoff:
# preflow_push does not support cutoff: we have to
# keep track of the paths founds and stop at cutoff.
break
path = [s]
if v == t:
path.append(v)
yield path
continue
u = v
while u != t:
p... |
tmenjo/cinder-2015.1.1 | cinder/tests/objects/test_objects.py | Python | apache-2.0 | 36,876 | 0 | # Copyright 2015 IBM Corp.
#
# 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... | Integer())}
class MyObj(base.CinderPersistentObject, base.CinderObject,
base.CinderObjectDictCompat):
VERSION = '1.6'
fields = {'foo': fields.Field(fields.Integer(), default=1),
'bar': fields.Field(fields.String()),
'missing': fields.Field(fields.String()),
... | =True),
'rel_objects': fields.ListOfObjectsField('MyOwnedObject',
nullable=True),
}
@staticmethod
def _from_db_object(context, obj, db_obj):
self = MyObj()
self.foo = db_obj['foo']
self.bar = db_obj['bar'... |
siosio/intellij-community | python/testData/override/qualified.py | Python | apache-2.0 | 57 | 0.035088 | imp | ort turtle
class C(turtle.TurtleScreenBase):
pa | ss |
gditzler/BigLS2014-Code | src/bmu.py | Python | gpl-3.0 | 2,945 | 0.021053 | #!/usr/bin/env python
import json
import numpy
import scipy.sparse as sp
from optparse import OptionParser
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2014, EESI Laboratory (Drexel University)"
__credits__ = ["Gregory Ditzler"]
__license__ = "GPL"
__version__ = "0.1.0"
__maintainer__ = "Gregory Ditzler... | (open(fname,"U").read())
if o["matrix_type"] == "sparse":
data = load_sparse(o)
else:
data = load_dense(o)
samples = []
for sid in o["columns"]:
samples.append(sid["id"])
features = []
for sid in o["rows"]:
# check to see if the taxonomy is listed, this will generally lead to more
# de... | nd(str( \
# sid["metadata"]["taxonomy"]).strip( \
# "[]").replace(",",";").replace("u'","").replace("'",""))
features.append(json.dumps(sid["metadata"]["taxonomy"]))
else:
features.append(sid["id"])
else:
features.append(sid["id"])
return data, samples, features
... |
hmmlearn/hmmlearn | scripts/benchmark.py | Python | bsd-3-clause | 8,715 | 0.000115 | """
A script for testing / benchmarking HMM Implementations
"""
import argparse
import collections
import logging
import time
import hmmlearn.hmm
import numpy as np
import sklearn.base
LOG = logging.getLogger(__file__)
class Benchmark:
def __init__(self, repeat, n_iter, verbose):
self.repeat = repeat... | rue")
parser.add_argument("--repeat", type=int, default=10)
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--n-iter", type=int, default=100)
args = parser.parse_args()
if args.all:
args.categorical = True
args.gaussian = True
args.multivariate_gau... |
n_iter=args.n_iter,
verbose=args.verbose,
)
bench.run("categorical.benchmark.csv")
if args.gaussian:
bench = GaussianBenchmark(
repeat=args.repeat,
n_iter=args.n_iter,
verbose=args.verbose,
)
bench.run("gaussian.ben... |
Elfhir/apero-imac | apero_imac/views.py | Python | mpl-2.0 | 255 | 0.023529 | from apero_imac.models import *
from django.shortcuts import render_to_response
from datetime import datetime
def home(request):
return render_to_response('home.html', locals())
def about(request):
return render_to_response('about.html', locals() | )
| |
FCP-INDI/C-PAC | CPAC/surface/surf_preproc.py | Python | bsd-3-clause | 6,597 | 0.00864 | import os
import nipype.interfaces.utility as util
from CPAC.utils.interfac | es.function import Function
from CPAC.pipeline import nipype_pipeline_engine as pe
def run_surface(post_freesurfer_folder,
freesurfer_folder,
subject,
t1w_restore_image,
atlas_space_t1w_image,
atlas_transform,
inverse_atl... | surf_atlas_dir,
gray_ordinates_dir,
gray_ordinates_res,
high_res_mesh,
low_res_mesh,
subcortical_gray_labels,
freesurfer_labels,
fmri_res,
smooth_fwhm):
import os
import subprocess... |
bergolho1337/URI-Online-Judge | Basicos/Python/1060/main.py | Python | gpl-2.0 | 173 | 0 | # -*- coding: utf-8 - | *-
cont = 0
v = []
for i in range( | 6):
v.append(float(raw_input()))
if (v[i] > 0):
cont = cont + 1
print("%d valores positivos" % cont)
|
sgraham/nope | tools/grit/grit/tool/build_unittest.py | Python | bsd-3-clause | 11,256 | 0.00613 | #!/usr/bin/env python
# Copyright (c) 2012 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.
'''Unit tests for the 'grit build' tool.
'''
import codecs
import os
import sys
import tempfile
if __name__ == '__main__':
sys.p... | _h = os.path.join(output_dir, 'whitelist_test_resources_map.h')
pak = os.path.join(output_dir, 'whitelist_test_resources.pak')
# Ensure the resource map head | er and .pak files exist, but don't verify
# their content.
self.failUnless(os.path.exists(map_h))
self.failUnless(os.path.exists(pak))
whitelisted_ids = [
'IDR_STRUCTURE_WHITELISTED',
'IDR_STRUCTURE_IN_TRUE_IF_WHITELISTED',
'IDR_INCLUDE_WHITELISTED',
]
non_whitelisted_id... |
ganeshrn/ansible | test/units/parsing/yaml/test_loader.py | Python | gpl-3.0 | 17,230 | 0.002266 | # coding: utf-8
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.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 o... | yfile.yml')
self.assertRaises(ParserError, loader.get_single_data)
def test_tab_error(self):
stream = StringIO(u"""---\nhosts: localhost\nvars:\n foo: bar\n\tblip: baz""")
loader = AnsibleLoader(stream, 'myfile.yml')
self.assertRaises(ScannerError, loader.get_single_data)
def ... | stream = StringIO(u"""---\nfoo: bar""")
loader = AnsibleLoader(stream, 'myfile.yml')
data = loader.get_single_data()
self.assertEqual(data, dict(foo=u'bar'))
self.assertEqual(data.ansible_pos, ('myfile.yml', 2, 1))
self.assertEqual(data[u'foo'].ansible_pos, ('myfile.yml', 2, 6... |
Nitrate/Nitrate | src/tcms/logs/managers.py | Python | gpl-2.0 | 527 | 0 | # -*- coding: utf-8 -*-
from django.contrib.contenttypes.models import ContentType
from django.db import models
class TCMSLogManager(models.Manager):
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class). |
"""
| ct = ContentType.objects.get_for_model(model)
qs = self.get_queryset().filter(content_type=ct)
if isinstance(model, models.Model):
qs = qs.filter(object_pk=model.pk)
return qs
|
astroclark/numrel_bursts | nrburst_utils/nrburst_pickle_preserve.py | Python | gpl-2.0 | 2,870 | 0.007666 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 James Clark <james.clark@ligo.org>
#
# 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 2 of the License, or
#... | file = pickle_files[f]
current_matches, current_masses, current_inclinations, config, \
current_simulations = pickle.load(open(file,'r'))
matches[f,startidx:endidx] = current_matches[0]
masses[f,startidx:endidx] = current_masses[0]
inclinations[f,startidx:endi... | ons.append(current_simulations.simulations[0])
filename=user_tag+'_'+config.algorithm+'.pickle'
pickle.dump([matches, masses, inclinations, config, simulations],
open(filename, "wb"))
|
redpawfx/massiveImporter | python/ns/tests/TestGenotype.py | Python | mit | 2,335 | 0.02227 | # The MIT License
#
# Copyright (c) 2008 James Piechota
#
# 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,... | input = "R:/massive/testdata/cdl/man/CDL/embedded_simple.cdl"
agentSpec = CDLReader.read(input, CDLReader.kEvolveTokens)
geno = Genotype.Genotype(agentSpec)
expectedChannels = [ "ty", "rx", "ry", "rz",
"height", "leg_length", "shirt_ma | p",
"walk", "walk_45L", "walk_sad",
"walk->walk_45L", "walk->walk_sad",
"walk_45L->walk", "walk_45L->walk_sad",
"walk_sad->walk", "walk_sad->walk_45L",
"walk:rate", "walk_45L:rate", "walk_sad:rate" ]
self.assertEqual(sorted(expectedChannels), sorted(... |
bozzmob/dxr | dxr/plugins/python/menus.py | Python | mit | 674 | 0 | from dxr.lines import Ref
from dxr.utils import search_url
class _PythonPluginAttr(object):
plugin = 'python'
class ClassRef(Ref, _PythonPluginAttr):
"""A refe | rence attached to a class definition"""
def menu_items(self):
qualname = self.menu_data
yield {'html': 'Find subclasses',
'title': 'Find subclasses of this class',
'href': search_url(self.tree, '+derived:' + qualname),
'icon': 'type'}
yield {'htm... | 'icon': 'type'}
|
zengchunyun/s12 | day9/temp/ext/twisted_client.py | Python | gpl-2.0 | 935 | 0.00107 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
from twisted.internet import reactor
from twisted.internet import protocol
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write(bytes("hello zengchunyun", "utf8"))
def dataReceived(self, data):
... | ef connectionLost(self, reason):
print("Connection lost")
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print("Connection failed - goodbye")
reactor.stop()
def clientConnectionLost(self, connector, reason):
... | or.stop()
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 1234, f)
reactor.run()
if __name__ == "__main__":
main() |
tobiashelfenstein/wuchshuellenrechner | wuchshuellenrechner/lib/xml.py | Python | gpl-3.0 | 6,767 | 0.005619 | """
xml.py -
Copyright (C) 2016 Tobias Helfenstein <tobias.helfenstein@mailbox.org>
Copyright (C) 2016 Anton Hammer <hammer.anton@gmail.com>
Copyright (C) 2016 Sebastian Hein <hein@hs-rottenburg.de>
Copyright (C) 2016 Hochschule für Forstwirtschaft Rottenburg <hfr@hs-rottenburg.de>
This file is part of Wuchshüllenre... |
return True
def readItemTree(self, element):
items = []
for variantEntry in elem | ent:
kind = int(variantEntry.findtext("type", "-1"))
child = VariantItem(protection=kind)
item, plant, protection = child.prepareSerialization()
# first read item's general data
item = self.readTags(item, variantEntry)
... |
glomex/gcdt-bundler | tests/test_bundler_utils.py | Python | mit | 2,286 | 0.000875 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import fnmatch
import logging
from gcdt_bundler.bundler_utils import glob_files, get_path_info
from . import here
ROOT_DIR = here('./resources/static_files')
log = logging.getLogger(__name__)
def test_find_two_files():
re... | 'a/ab.txt')
]
def test_exclude_file_with_gcdtignore():
result = glob_files(ROOT_DIR, ['a/**'],
gcdtignore=['aa.txt'])
assert list(result) == [
(ROOT_DIR + '/a/ab.txt', 'a/ab.txt')
]
def test_how_crazy_is_it():
f = '/a/b/c/d.txt'
p = '/a/**/d.txt'
assert f... | t_path_info_relative():
path = {'source': 'codedeploy', 'target': ''}
base, ptz, target = get_path_info(path)
assert base == os.getcwd()
assert ptz == 'codedeploy'
assert target == '/'
def test_get_path_info_abs():
path = {'source': os.getcwd() + '/codedeploy', 'target': ''}
base, ptz, tar... |
Arno-Nymous/pyload | module/plugins/accounts/OverLoadMe.py | Python | gpl-3.0 | 1,824 | 0.001096 | # -*- coding: utf-8 -*-
from ..internal.misc import json
from ..internal.MultiAccount import MultiAccount
class OverLoadMe(MultiAccount):
__name__ = "OverLoadMe"
__type__ = "account"
__version__ = "0.13"
__status__ = "testing"
__config__ = [("mh_mode", "all;listed;unlisted", "Filter hosters to u... | return {'premium': False, 'validuntil': None, 'trafficleft': None}
else:
return {'premium': True,
'validuntil': data['expirationunix'],
'trafficleft': -1}
def signin(self, user, password, data):
html = self.load("https://api.over-load.me... | 'auth': password}).strip()
data = json.loads(html)
if data['err'] == 1:
self.fail_login()
|
bigswitch/snac-nox-zaku | src/nox/lib/packet/dhcp.py | Python | gpl-3.0 | 8,935 | 0.005708 | # Copyright 2008 (C) Nicira, Inc.
#
# This file is part of NOX.
#
# NOX 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.
#
# NOX is d... | |
# +------------------------------------ | ---------------------------+
#
#======================================================================
import struct
from packet_utils import *
from packet_exceptions import *
from array import *
from packet_base import packet_base
class dhcp(packet_base):
"DHCP Packet struct"
STRUCT_BOUNDARY = 28
... |
supermari0/config | utils/pwgen.py | Python | gpl-2.0 | 183 | 0.005464 | #!/usr/local/bin/python3
import secrets, str | ing
length = 16
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
print(''.join(secrets.choice(chars) for i in ran | ge(length)))
|
yourcelf/btb | printing/print_mail.py | Python | agpl-3.0 | 4,703 | 0.002126 | import os
import sys
import glob
import json
import subprocess
from collections import defaultdict
from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser
import addresscleaner
from click2mail import Click2MailBatch
parser.add_argument("directory", help="Path to downloaded mail batch")
parser.add_... | print "Building job with", filename
batch = Click2MailBatch(
username=args.username,
password=args.password,
filename=filename,
jobs=jobs,
staging=args.staging)
if batch.run(args.dry_run):
os.remove(filename)
def main():
args = parser.pa... | rectory):
subprocess.check_call([
"unzip", args.directory, "-d", os.path.dirname(args.directory)
])
else:
directory = args.directory
with open(os.path.join(directory, "manifest.json")) as fh:
manifest = json.load(fh)
if manifest["letters"] and not ar... |
ChristianKniep/QNIB | serverfiles/usr/local/lib/networkx-1.6/networkx/tests/test_relabel.py | Python | gpl-2.0 | 5,962 | 0.032372 | #!/usr/bin/env python
from nose.tools import *
from networkx import *
from networkx.convert import *
from networkx.algorithms.operators import *
from networkx.generators.classic import barbell_graph,cycle_graph
class TestRelabel():
def test_convert_node_labels_to_integers(self):
# test that empty graph co... | 'D')])
mapping={'A':'aard | vark','B':'bear','C':'cat','D':'dog'}
H=relabel_nodes(G,mapping,copy=False)
assert_equal(sorted(H.nodes()), ['aardvark', 'bear', 'cat', 'dog'])
def test_relabel_nodes_multigraph(self):
G=MultiGraph([('a','b'),('a','b')])
mapping={'a':'aardvark','b':'bear'}
G=relabel_nodes(G,... |
zniper/django-quickadmin | setup.py | Python | mit | 1,119 | 0.000894 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='django-quickadmin',
version='0.1.2',
description='Django appli... | or_email='me.zniper@gmail.com',
license='MIT', |
classifiers=[
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
... |
timdiels/0publish | validator.py | Python | lgpl-2.1 | 2,847 | 0.038286 | import os
from zeroinstall.injector import namespaces
from zeroinstall.injector.reader import InvalidInterface, load_feed
from xml.dom import minidom, Node, XMLNS_NAMESPACE
import tempfile
from logging import warn, info
group_impl_attribs = ['version', 'version-modifier', 'released', 'main', 'stability', 'arch', 'lice... | , elem.localName)
for child in elem.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
checkEl | ement(child)
def check(data, warnings = True, implementation_id_alg=None, generate_sizes=False):
fd, tmp_name = tempfile.mkstemp(prefix = '0publish-validate-')
os.close(fd)
try:
tmp_file = file(tmp_name, 'w')
tmp_file.write(data)
tmp_file.close()
try:
feed = load_feed(tmp_name, local=True, implementation... |
artolaluis/restblog | docs/source/conf.py | Python | bsd-3-clause | 7,320 | 0.007104 | # -*- coding: utf-8 -*-
#
# restblog documentation build configuration file, created by
# sphinx-quickstart on Mon Jul 12 17:19:21 2010.
#
# 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.
#
# Al... | pend(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx exten | sion module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']
# Add any paths that co... |
fakdora/flaksy-upto-login | app/__init__.py | Python | mit | 1,012 | 0 | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config
bootstrap = Bootstrap()
mail = Mai... | ect(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
pagedown.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .... | auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
|
tridvaodin/Assignments-Valya-Maskaliova | LPTHW/ex43.py | Python | gpl-2.0 | 5,149 | 0.004273 | from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enrer()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
curr... | your head. In the middle of your artful dodge your foor slips and you bang your head on the metal wall and pass out. You wake up shortly after only to die as the Gothon stomps on your head and eats you."
return 'death'
elif action == "tell a joke":
print "Lucky for you they made you le... | n stops, tries not to laugh, then busts out laughing and can't stop. While he's laughing you run up and shoot him square in the head putting him down, then jump through the Weapon Armory door."
return 'laser_weapon_armory'
else:
print "DOES NOT COMPUTE!"
return 'central_corr... |
VisTrails/VisTrails | vistrails/packages/spreadsheet/cell_rc.py | Python | bsd-3-clause | 211,544 | 0.000151 | # -*- coding: utf-8 -*-
###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is p... | \xcd\xe7\x93\x99\x24\x84\x21\x0c\
\x49\xde\x37\x13\x66\x86\x84\x64\x42\xc0\x01\x4c\x20\x4c\x06\x08\
\x13\x36\x93\x78\x03\x1b\x6f\xb2\x8c\x65\xc9\x96\xd5\x52\x4b\xea\
\x56\xb7\x7a\xbb\x5b\xd5\x39\xcf\xf3\xfe\x71\xea\xde\xbe\x6a\xc9\
\x2b\x96\x5a\xc6\xfa\x7d\x54\xaa\x7b\xeb\x56\xdd\x3e\x75\x9f\xdf\
\x79\xb6\xf3\x9c\x53\x... | x88\x99\x2d\x76\x1b\x4e\x61\x11\
\xe1\x16\xbb\x01\xa7\xb0\xb8\x38\x45\x80\x17\x39\x4e\x11\xe0\x45\
\x8e\x74\xb1\x1b\xb0\x98\xb8\xe2\x8a\x2b\x3a\x0e\xd0\xdd\x77\xdf\
\x2d\x8b\xd9\x96\xc5\xc2\x29\x0d\xf0\x22\xc7\x8b\x5a\x03\x74\x43\
\x44\x56\x03\x55\xa0\x09\x4c\x99\x59\x73\x91\x9b\x74\x42\x70\x8a\
\x00\xf3\xb8\x04\x58\x0... |
ajn123/Python_Tutorial | Python Version 2/Advanced/exceptions.py | Python | mit | 1,154 | 0.034662 | """
An exception is what occurs when you have a run time error in your
program.
what you can do is "try" a statement wether it is invalid or not
if an error does occur withan that statement you can catch that error
in the except clause and print out a corresponding message
(or you can print out the error message).
... |
def main():
while True:
#Similar to Try and catch, tries an error and catches it.
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
#A lookup error in whon an a incorrect lookup happens in a dictionary,
dict =... | print LookupError
"""
You can catch an exception and then use a finally clause
to take care of your program
A finally statement is executed no matter if an exception is
thrown.
"""
try:
a = 4 / 2
except Exception, e:
raise e
finally:
print "finally clause raised"
if __name__ == '__main__':
main(... |
MarekSuchanek/repocribro | repocribro/github.py | Python | mit | 9,565 | 0 | import hashlib
import hmac
import json
import requests
class GitHubResponse:
"""Wrapper for GET request response from GitHub"""
def __init__(self, response):
self.response = response
@property
def is_ok(self):
"""Check if request has been successful
:return: if it was OK
... | return 1
params = url.split('?')[1].split('=')
params = {k: v for k, v in zip(params[0::2], params[1::2])}
if 'page' not in params:
return 1
return int(pa | rams['page'])
class GitHubAPI:
"""Simple GitHub API communication wrapper
It provides simple way for getting the basic GitHub API
resources and special methods for working with webhooks.
.. todo:: handle if GitHub is out of service, custom errors,
better abstraction, work with extension... |
beernarrd/gramps | gramps/gen/filters/rules/person/_hascitation.py | Python | gpl-2.0 | 1,883 | 0.006373 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 2 of the License, or
# (at you... |
# MERCHANTABILITY or FITNESS FOR 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 U... | ------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps ... |
gundalow/ansible-modules-extras | windows/win_webpicmd.py | Python | gpl-3.0 | 1,852 | 0.00162 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Peter Mounce <public@neverrunwithscissors.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... | eb Platform Installer command-line (http://www.iis.net/ | learn/install/web-platform-installer/web-platform-installer-v4-command-line-webpicmdexe-rtw-release).
- Must be installed and present in PATH (see win_chocolatey module; 'webpicmd' is the package name, and you must install 'lessmsi' first too)
- Install IIS first (see win_feature module)
notes:
- accepts EU... |
rolando-contrib/scrapy | tests/__init__.py | Python | bsd-3-clause | 1,205 | 0 | """
tests: this package contains all Scrapy unittests
see http://doc.scrapy.org/en/latest/contributing.html#running-tests
"""
import os
# ignore system-wide proxies for tests
# which would send requests to a totally unsuspecting server
# (e.g. because urllib does not fully understand the proxy spec)
os.environ['http... | path.abspath(__file__)))
if 'COV_CORE_CONFIG' in os. | environ:
os.environ['COVERAGE_FILE'] = os.path.join(_sourceroot, '.coverage')
os.environ['COV_CORE_CONFIG'] = os.path.join(_sourceroot,
os.environ['COV_CORE_CONFIG'])
try:
import unittest.mock as mock
except ImportError:
import mock
tests_datadir = os.p... |
Forage/Gramps | gramps/gui/widgets/linkbox.py | Python | gpl-2.0 | 1,754 | 0.005701 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# | 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but... | neral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
__all__ = ["LinkBox"]
#--------------------------------------... |
ResearchSoftwareInstitute/MyHPOM | hs_tracking/tests.py | Python | bsd-3-clause | 15,515 | 0.001482 | from datetime import datetime, timedelta
import csv
from cStringIO import StringIO
from django.test import TestCase
from django.contrib.auth.models import User
from django.test import Client
from django.http import HttpRequest, QueryDict, response
from mock import patch, Mock
from .models import Variable, Session, Vi... | ch_cnt = Variable.objects.filter(name='app_launch').count()
self.assertEqual(app_ | lauch_cnt, 1)
data = list(Variable.objects.filter(name='app_launch'))
values = dict(tuple(pair.split('=')) for pair in data[0].value.split('|'))
self.assertTrue('res_type' in values.keys())
self.assertTrue('name' in values.keys())
self.assertTrue('user_email_domain' in values.ke... |
SpeedProg/eve-inc-waitlist | waitlist/blueprints/xup/__init__.py | Python | mit | 52 | 0 | from . | blueprint | import bp
from .submission import *
|
jfillmore/Omega-API-Engine | clients/python/omega/__init__.py | Python | mit | 402 | 0.002488 | #!/usr/bin/python
# omega - python client
# https://github.com/jfillmore/Omega-API-Engine
#
# Copyright 2011, J | onathon Fillmore
# Licensed under the MIT license. See LICENSE file.
# http://www.opensource.org/licenses/mit-license.php
"""Omega core library."""
__all__ = ['client', 'dbg', 'browser', 'box_factory', 'error', 'util', 'shell']
import dbg
from util import *
from error import Exc | eption
|
jkandasa/integration_tests | cfme/fixtures/cli.py | Python | gpl-2.0 | 4,212 | 0.002374 | from cfme.utils.version import get_stream
from collections import namedtuple
from contextlib import contextmanager
from cfme.test_framework.sprout.client import SproutClient
from cfme.utils.conf import cfme_data, credentials
from cfme.utils.log import logger
import pytest
from wait_for import wait_for
from cfme.test_fr... | raise SproutException('No provision available')
yield apps[0]
apps[0].ssh_client.close()
sp.destroy_pool(pool_id)
@pyt | est.yield_fixture()
def unconfigured_appliance(appliance):
with fqdn_appliance(appliance, preconfigured=False) as app:
yield app
@pytest.yield_fixture()
def configured_appliance(appliance):
with fqdn_appliance(appliance, preconfigured=True) as app:
yield app
@pytest.yield_fixture()
def ipa_c... |
Repythory/Libraries | amolf/plotting/__init__.py | Python | bsd-2-clause | 236 | 0.008475 | import os
import glob
| SOURCE_FILES = glob.glob(os.path.dirname(__file__) + "/*.py")
__all__ = [os.path.basename( | f)[: -3] for f in SOURCE_FILES]
__doc__ = """\
Module for advanced plotting based on matplotlib
"""
from .popups import * |
RingCentralVuk/ringcentral-python | ringcentral/subscription/__init__test.py | Python | mit | 2,725 | 0.001835 | #!/usr/bin/env python
# encoding: utf-8
import unittest
from ..test import TestCase, Spy
from ..http.mocks.presence_subscription_mock import PresenceSubscriptionMock
from ..http.mocks.subscription_mock import SubscriptionMock
from . import *
class TestSubscription(TestCase):
def test_presence_decryption(self):
... | '/qE0It3DqQ6vdUWISoTfjb+vT5h9kfZxWYUP4ykN2UtUW1biqCjj1Rb6GWGnTx6jP | qF77ud0XgV1rk/Q6heSFZWV/GP2' + \
'3/iytDPK1HGJoJqXPx7ErQU='
s = sdk.get_subscription()
spy = Spy()
s.add_events(['/restapi/v1.0/account/~/extension/1/presence'])
s.on(EVENTS['notification'], spy)
s.register()
s._get_pubnub().receive_message(aes_mes... |
remontees/EliteHebergPanel | home/forms.py | Python | lgpl-3.0 | 442 | 0.020362 | #-*- coding: utf-8 -*-
from django import forms
from models import User
from captcha.fields import CaptchaField
class UserFo | rm(forms.ModelForm):
captcha = CaptchaField()
cgu = forms.BooleanField()
class Meta:
model = User
widgets = { 'pseudo': forms.TextInput(attrs={'class':'form-control'}), 'nom': forms.TextInput(attrs={'class':'form-control'}), 'email': forms.TextInput(attrs={'class' | :'form-control'}) }
|
SINGROUP/pycp2k | pycp2k/classes/_nmr1.py | Python | lgpl-3.0 | 844 | 0.00237 | from pycp2k.inputsection import InputSection
from ._print55 import _print55
from ._interpolator10 import _interpolator10
class _nmr1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_par | ameters = None
self.Interpolate_shift = None
self.Nics = None
self.Nics_file_name = None
self.Restart_nmr = None
self.Shift_gapw_radius = None
self.PRINT = _print55()
self.INTERPOLATOR = _interpolator10()
self._name = "NMR"
self._keywords = {'Resta... | pw_radius': 'SHIFT_GAPW_RADIUS'}
self._subsections = {'INTERPOLATOR': 'INTERPOLATOR', 'PRINT': 'PRINT'}
self._attributes = ['Section_parameters']
|
sniemi/SamPy | plot/interactive_correlation_plot.py | Python | bsd-2-clause | 11,714 | 0.015025 | ### Interactively plot points
### to show the correlation between the x and y directions.
### By Rajeev Raizada, Jan.2011.
### Requires Python, with the Matplotlib and SciPy modules.
### You can download Python and those modules for free from
### http://www.python.org/download
### http://scipy.org
### http://matplotlib... | ts the statistics
def plot_the_correlation():
# First, delete any existing regression line plots fr | om the figure
global handle_of_regression_line_plot
pylab.setp(handle_of_regression_line_plot,visible=False)
#### Next, calculate and plot the stats
number_of_points = scipy.shape(coords_array)[0]
x_coords = coords_array[:,0] # Python starts counting from zero
y_coords = coords_array[:,1]
... |
maoterodapena/pysouliss | souliss/Typicals.py | Python | mit | 9,295 | 0.00979 | import logging
import struct
_LOGGER = logging.getLogger(__name__)
typical_types = {
0x11: {
"desc": "T11: ON/OFF Digital Output with Timer Option", "size": 1,
"name": "Switch Timer",
"state_desc": { 0x00: "off",
0x01: "on"}
},
... | , "state_topic": "souliss/% | s/%s/state"}' \
% (self.device_class, self.name, self.device_class, self.name))
#'{"name" : "once,", "payload_on": "0", "payload_off": "1", "optimistic": false, "retain": true, "state_topic": "souliss/switch/%s", "command_topic": "souliss/switch/%s/set"}' % (self.name,... |
PriviPK/privipk-sync-engine | kgc/kgc-service.py | Python | agpl-3.0 | 1,469 | 0.001361 | #!/usr/bin/env python2.7
import click
from common import KGC_PORT
from server import KgcRpcServer
import privipk
from privipk.keys import LongTermSecretKey
@click.group()
def cli():
"""
Use this tool to spawn a KGC server and/or to generate
a private key for a KGC server.
"""
pass
@cli.command(... | roup parameters is not yet implemented
"""
params = privipk.parameters.default
lts = LongTermSecretKey.unserialize(params, open(secret_key_path).read())
server = KgcRpcServer(lts, port)
server.start()
@cli.command()
@click.argument('secret_key_path', required=True)
def genkey(secret_key_path):
... |
stores the public key in the another file named by appending .pub
to the first file.
"""
params = privipk.parameters.default
lts = LongTermSecretKey(params)
open(secret_key_path, 'w').write(lts.serialize())
ltp = lts.getPublicKey()
open(secret_key_path + '.pub', 'w').write(ltp.serialize... |
vishnu-kumar/PeformanceFramework | tests/unit/plugins/openstack/scenarios/nova/test_keypairs.py | Python | apache-2.0 | 2,878 | 0 | # Copyright 2015: Hewlett-Packard Development Company, L.P.
# 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-... | rt_called_once_with(fakearg="fakearg")
scenario._list_keypairs.assert_called_once_with()
def test_create_and_delete_keypair(self):
scenario = keypairs.NovaKeypair(self.context)
scenario.generate_random_name = mock.MagicMock(return_value="name")
scenario._create_keypair = mock.MagicM... | mock.MagicMock()
scenario.create_and_delete_keypair(fakearg="fakearg")
scenario._create_keypair.assert_called_once_with(fakearg="fakearg")
scenario._delete_keypair.assert_called_once_with("foo_keypair")
def test_boot_and_delete_server_with_keypair(self):
scenario = keypairs.NovaKe... |
CajetanP/code-learning | Python/Learning/Tips/args_and_kwargs.py | Python | mit | 319 | 0 |
def test_var_args(f_arg, *argv):
print("normal:" | , f_arg)
for arg in argv:
print("another one:", arg)
def greet_me(**kwargs):
for key, value in kwargs.items():
print("{0} = {1}".format(key, value))
test_var_args('hello', 'there', 'general', 'Kenob | i')
greet_me(name="test", surname="me")
|
akpeker/sayi-tahmin-cozucu | py/sayitahminCozucu.py | Python | mit | 5,341 | 0.02385 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 11 14:10:30 2017
@author: WİN7
"""
# 4 basamaklı, basamakları tekrarsız sayıların (4lü karakter dizisi)
# tümünü bir liste olarak (5040 tane) üretip döndürür.
def sayilariUret():
S = []
for n in range(10000):
ss = "%04d"%n
if ss[0]==ss[1] or s... | entr -= p*math.log(p,2)
E[n] = entr |
if entr > 3.5: print("%04d : %f"%(n,entr))
return E
def getEntropiesDict(S,UNI,yaz=True,tr=1.9):
EN = OrderedDict()
# try all possible guesses (n) and find entropy of results for each guess
for n in range(len(UNI)):
#tahmin = "%04d"%n
tahmin = UNI[n]
hist = getHist(... |
tomka/CATMAID | django/applications/catmaid/control/graph2.py | Python | gpl-3.0 | 24,814 | 0.004796 | # -*- coding: utf-8 -*-
from collections import defaultdict
from functools import partial
from itertools import count
import json
import networkx as nx
from networkx.algorithms import weakly_connected_component_subgraphs
from numpy import subtract
from numpy.linalg import norm
from typing import Any, DefaultDict, Dict... | connector_id = ANY(%(allowed_c_ids)s::bigint[])' if allowed_connector_ids else ''}
''', {
'project_id': | int(project_id),
'skids': list(skeleton_ids),
'source_rel_id': source_rel_id,
'target_rel_id': target_rel_id,
'allowed_c_ids': allowed_connector_ids,
})
stc:DefaultDict[Any, List] = defaultdict(list)
for row in cursor.fetchall():
stc[row[0]].append(row[1:]) # skeleto... |
ATNF/askapsdp | Tools/Dev/rbuild/askapdev/rbuild/utils/create_init_file.py | Python | gpl-2.0 | 2,053 | 0.002923 | ## Package for various utility functions to execute build and shell commands
#
# @copyright (c) 2007 CSIRO
# Australia Telescope National Facility (ATNF)
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# PO Box 76, Epping NSW 1710, Australia
# atnf-enquiries@csiro.au
#
# This file is part of the ... | ibution.
#
# The ASKAP software distribution 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 the License
# or (at your option) any later version.
#
# This program is distributed in the hope... | PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
#
# @author Malte Marquarding <Malte.Marquardin... |
runekaagaard/django-contrib-locking | django/forms/models.py | Python | bsd-3-clause | 54,740 | 0.00148 | """
Helper functions for creating Form classes from Django models
and database field objects.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from itertools import chain
import warnings
from django.core.exceptions import (
ImproperlyConfigured, ValidationError, NON_FIELD_ERRORS, F... | if labels and f.name in labels:
kwargs['label'] = labels[f.name]
if help_texts and f.name in help_texts:
kwargs['help_text'] = help_texts[f.name]
if error_messages and f.name in error_messages:
kwargs['error_messages'] = error_messages[f.name]
if formfie... | tion or cal |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.