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 |
|---|---|---|---|---|---|---|---|---|
garyjohnson/ci_screen_2 | ci_screen/service/ci_server_poller.py | Python | mit | 2,307 | 0.002167 | import logging
import time
import threading
try:
import ConfigParser as config
except:
import configparser as config
from pydispatch import dispatcher
import requests
import ci_screen.service.ci_server_loader as ci_ | loader
logger = logging.getLogger(__name__)
class CIServerPoller(object):
def __init__(self):
self._stop = threading.Event()
self._update = threading.Event()
self._poll_rate = self.get_poll_rate()
se | lf.polling_thread = None
self.ci_servers = ci_loader.get_ci_servers()
def __del__(self):
self.stop_polling()
def start_polling_async(self):
self._stop.clear()
self._update.clear()
self.polling_thread = threading.Thread(target=self.poll_for_changes)
self.polling_... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_peer_express_route_circuit_connections_operations.py | Python | mit | 9,496 | 0.004844 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | -----------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.p... | ls as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class PeerExpressRouteCir... |
google-research/football | gfootball/scenarios/tests/11_vs_11_hard_deterministic.py | Python | apache-2.0 | 2,272 | 0.013204 | # coding=utf-8
# Copyright 2019 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | am.e_Right
else:
first_team = Team.e_Right
sec | ond_team = Team.e_Left
builder.SetTeam(first_team)
builder.AddPlayer(-1.000000, 0.000000, e_PlayerRole_GK)
builder.AddPlayer(0.000000, 0.020000, e_PlayerRole_RM)
builder.AddPlayer(0.000000, -0.020000, e_PlayerRole_CF)
builder.AddPlayer(-0.422000, -0.19576, e_PlayerRole_LB)
builder.AddPlayer(-0.500000, -0.0... |
gion86/awlsim | awlsimhw_dummy/main.py | Python | gpl-2.0 | 1,933 | 0.021728 | # -*- coding: utf-8 -*-
#
# AWL simulator - Dummy hardware interface
#
# Copyright 2013-2014 Michael Buesch <m@bues.ch>
#
# 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 ... | Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
from __future__ import division, | absolute_import, print_function, unicode_literals
from awlsim.common.compat import *
from awlsim.core.hardware import *
from awlsim.core.operators import AwlOperator
from awlsim.core.datatypes import AwlOffset
class HardwareInterface(AbstractHardwareInterface):
name = "dummy"
def __init__(self, sim, parameters={}... |
prometheanfire/cloud-init | cloudinit/config/cc_keys_to_console.py | Python | gpl-3.0 | 2,179 | 0 | # vi: ts=4 expandtab
#
# Copyright (C) 2011 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistr | ibute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# | 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public Licens... |
m4ll0k/Infoga | setup.py | Python | gpl-3.0 | 494 | 0.022267 | #! | /usr/bin/env python
# -*- coding:utf-8 -*-
#
# @name : Infoga - Email OSINT
# @url : http://github.com/m4ll0k
# @author : Momo Outaadi (m4ll0k)
from setuptools import setup
setup(
name='infoga',
version='0.1.5',
description='Email OSINT',
url= | 'https://github.com/m4ll0k',
author = 'Momo (m4ll0k) Outaadi',
author_email='m4ll0k@protonmail.com',
license='GPLv3',
install_requires = ['colorama','requests','urllib3'],
console =['infoga.py'],
) |
collective/ECSpooler | lib/util/errorcodes.py | Python | gpl-2.0 | 154 | 0.006494 | # -*- co | ding: utf-8 -*-
# $Id: $
ERROR_AUTH_FAILED = "Authorization failed"
NO_SUCH_BACKEND = "No such backend"
REDIRECTION_FAILED = "R | edirection failed" |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyQt4/QtCore/QSequentialAnimationGroup.py | Python | gpl-2.0 | 2,169 | 0.011065 | # encoding: utf-8
# module PyQt4.QtCore
# from /usr/lib/python3/dist-packages/PyQt4/QtCore.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import sip as __sip
from .QAnimationGroup import QAnimationGroup
class QSequentialAnimationGroup(QAnimationGroup):
""" QSequentialAnimationGroup(QObj... | on
def currentAnimationChanged(self, *args, **kwargs): # real signature unknown
""" QSequentialAnimationGroup.cu | rrentAnimationChanged[QAbstractAnimation] [signal] """
pass
def duration(self): # real signature unknown; restored from __doc__
""" QSequentialAnimationGroup.duration() -> int """
return 0
def event(self, QEvent): # real signature unknown; restored from __doc__
""" QSequentialA... |
kaihuang201/opinion | appopinion/CommentGenerator.py | Python | gpl-2.0 | 1,938 | 0.013416 |
"""
CommentGenerator.py
Author: Zefu Lu (zefulu2)
Description: This Module generates comments and add it to the database
Creation: 2014-11-4
"""
#===============================================================================
# import references
#=======================================================================... | ppopinion.models import *
users = User.objects.all()
django.setup()
class CommentGenerator(object):
'''Constructor'''
def __init__(self, topic_id):
self.topic_id = topic_id;
#initialize database wrapper
#self.db = DatabaseWrapper(db_config_file)
def generate(self):
cou... | etime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
item_dict['date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
item_dict['parent_id'] = self.topic_id
# self.db.insertToTable('newapp_comment', item_dict)
topic = Topic.objects.get(pk=item_dict['parent_id'])
... |
jpoullet2000/cgs-apps | installForTest.py | Python | apache-2.0 | 4,453 | 0.005614 | #!/usr/bin/python
__author__ = 'CGS'
import os, shutil, sys, distutils.core, subprocess
# Some configuration needed for this file
apps_directory = ""
apps = {"variants": "apps/variants"}
PRODUCTION = False
# TODO: better management of errors
# Some basic checks
if os.getuid() != 0:
sys.exit("This program require... | ]).split(" ")[2].strip()
except:
hue_directory = "/usr/lib/hue"
if not os.path.exists(hue_directory) and "HUE_DIRECTORY" in os.environ:
hue_directory = os.environ["HUE_DIRECTORY"]
if os.path.exists(hue_directory) and not os.path.exists(hue_directory+"/myapps"):
try:
os.makedirs(hue_directory+"/mya... | t os.path.exists(hue_directory):
sys.exit("This installation file did not find the hue directory, please create a HUE_DIRECTORY environment"
"variable.")
# We install each application
aborted = 0
for i in xrange(1, len(sys.argv)):
app_name = sys.argv[i]
if not app_name in apps:
sys.exi... |
odoousers2014/LibrERP | account_due_list/reports/parser.py | Python | agpl-3.0 | 1,214 | 0.007414 | # -*- coding: utf-8 -*-
############################################################ | ##################
#
# Modulo realizzato da Andrea Cometa (info@andreacometa.it)
# Compatible with OpenERP release 6.1.X
# Copyright (C) 2012 Andrea Cometa. All Rights Reserved.
# Email: info@andreacometa.it
# Web site: http://www.andreacometa.it
#
####################################################... | _parse):
def __init__(self, cr, uid, name, context):
super(account_due_list_webkit, self).__init__(cr, uid, name, context=context)
file_path = os.path.dirname(inspect.getfile(inspect.currentframe()))
self.localcontext.update({
'datetime': datetime,
'time': time,
... |
MartinHjelmare/home-assistant | homeassistant/components/toon/binary_sensor.py | Python | apache-2.0 | 4,548 | 0 | """Support for Toon binary sensors."""
from datetime import timedelta
import logging
from typing import Any
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from . import (ToonEntity, ... | ])
async_add_entities(sensors)
class ToonBinarySensor(ToonEntity, BinarySensorDevice):
"""Defines an Toon binary sensor."""
def __init__(self, toon, section: str, measurement: str, on_value: Any,
| name: str, icon: str, device_class: str,
inverted: bool = False) -> None:
"""Initialize the Toon sensor."""
self._state = inverted
self._device_class = device_class
self.section = section
self.measurement = measurement
self.on_value = on_value
... |
eduNEXT/edx-platform | lms/djangoapps/commerce/tests/test_views.py | Python | agpl-3.0 | 370 | 0 | """ Tests for commerce views. """
from common.djangoapps.student.tests.factories import UserFactory
class UserMixin:
""" Mixin for tests involving users. """
def s | etUp(self):
super().setUp()
self.user = UserFactory()
def _login(self):
""" Log into LMS. """
self.client.logi | n(username=self.user.username, password='test')
|
satyrius/cmsplugin-feedback | cmsplugin_feedback/signals.py | Python | mit | 1,157 | 0.000864 | import django.dispatch
from django.contrib.sites.models import get_current_site
from django.core.mail import mail_managers
from django.core.urlresolvers import reverse
from django.template import loader, Context
from . import settings
form_submited = django.dispatch.Signal()
def notify | _managers(sender, message, request, *args, **kwargs):
if settings.NOTIFY_MANAGERS:
mail_managers(
subject=settings.NOTIFY_SUBJECT,
message=render_email(message, request),
fail_silently=True)
form_submited.connect(notify_managers)
def get_admin_url(instance, request):
... | =meta.app_label, model=model)
s = get_current_site(request)
return 'http://' + s.domain + reverse(url_pattern, args=[instance.pk])
def render_email(message, request):
t = loader.get_template('cms/plugins/feedback-email.html')
c = Context({
'message': message,
'url': get_admin_url(messa... |
nightlights/py_vn | src/cable.py | Python | gpl-3.0 | 415 | 0 | __author__ = "Liam R | igby"
__license__ = "GPLv3"
__version__ = "0.1 alpha"
__maintainer__ = "Liam Rigby"
__email__ = "lrig521@aucklanduni.ac.nz"
__status__ = "Development"
class FastEthernetCable:
def __init__(self):
self.max_length = 300
class GigabitEthernetCable:
def __init__(self):
self.max_length = 300
... | self.max_length = 300
|
podcastquotes/podcastquotes | django_project/quotes_app/management/commands/rank_quotes.py | Python | agpl-3.0 | 387 | 0.007752 | from django.core.management.base import BaseCommand, CommandError
from quotes_app.tasks import | rank_all
import logging
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Runs reranking algorithms on the Quotes.'
def handle(self, *args, **options):
logger.info('Running {0} management task.'.format(__name__ | ))
rank_all()
|
tomashaber/raiden | raiden/tests/unit/test_channel.py | Python | mit | 32,853 | 0.000213 | # -*- coding: utf-8 -*-
# pylint: disable=too-many-locals,too-many-statements
from __future__ import division
import pytest
from ethereum import slogging
from raiden.channel import (
BalanceProof,
Channel,
ChannelEndState,
ChannelExternalState,
)
from raiden.exceptions import (
InsufficientBalance... | dress2, balance2, BalanceProof(None))
external_state = make_external_state()
test_channel = Channel(
our_state,
partner_state,
external_state,
token_address,
reveal_timeout,
| settle_timeout,
)
amount = balance1
expiration = block_number + settle_timeout
sent_mediated_transfer0 = test_channel.create_mediatedtransfer(
address1,
address2,
fee=0,
amount=amount,
identifier=1,
expiration=expiration,
hashlock=sha3('test_l... |
X-DataInitiative/tick | tick/hawkes/inference/hawkes_sumgaussians.py | Python | bsd-3-clause | 15,015 | 0.001399 | # License: BSD 3 clause
import math
import numpy as np
from scipy.stats import norm
from tick.hawkes.inference.base import LearnerHawkesNoParam
from tick.hawkes.inference.build.hawkes_inference import (HawkesSumGaussians as
_HawkesSumGaussians)
from tick.solve... | ``
record_every : `int`, default=10
Record history information when ``n_iter`` (iteration number) is
a multiple of ``record_every``
Other Parameters
----------------
approx : `int`, default=0 (read-only)
Level of approximation used for computing exponential functions
*... | ed
em_max_iter : `int`, default=30
Maximum number of loop for inner em algorithm.
em_tol : `float`, default=None
Tolerance of loop for inner em algorithm. If relative difference of
baseline and adjacency goes bellow this tolerance, em inner loop
will stop.
If None, it w... |
robjwells/adventofcode-solutions | 2017/python/2017-01.py | Python | mit | 3,488 | 0 | #!/usr/bin/env python3
import pytest
def circ_pairs(sequence, distance=1):
"""Zip elements some distance apart in sequence and wrap around
For example:
[4, 5, 1] -> [(4, 5), (5, 1), (1, 4)]
"""
return zip(sequence, sequence[distance:] + sequence[:distance])
def int_to_sequence(integer):
"... | cular_number):
"""Sums all digits that match the next digit in the sequence"""
return total_nearby_digits_in_sequence(circular_number, digit_distance=1)
def total_half_distant(circular_number):
"""Sums all digits that match the digit halfway distant in the sequence"""
return total_nearby_digits_in_seq... | , 1), (1, 4)]),
(1122, 1, [(1, 1), (1, 2), (2, 2), (2, 1)]),
(1122, 2, [(1, 2), (1, 2), (2, 1), (2, 1)]),
(1212, 1, [(1, 2), (2, 1), (1, 2), (2, 1)]),
(1212, 2, [(1, 1), (2, 2), (1, 1), (2, 2)]),
(123123, 1, [(1, 2), (2, 3), (3, 1), (1, 2), (2, 3), (3, 1)]),
(123123, 3, [(1, 1), (2, 2), (3, 3), ... |
wkschwartz/django | tests/auth_tests/settings.py | Python | bsd-3-clause | 587 | 0 | import os
AUTH_MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', |
]
AUTH_TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(__file__), 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.... | ages',
],
},
}]
|
noba3/KoTos | addons/plugin.video.vox-now.de/resources/lib/kodion/utils/function_cache.py | Python | gpl-2.0 | 3,125 | 0.00096 | from functools import partial
import hashlib
import datetime
from storage import Storage
class FunctionCache(Storage):
ONE_MINUTE = 60
ONE_HOUR = 60 * ONE_MINUTE
ONE_DAY = 24 * ONE_HOUR
ONE_WEEK = 7 * ONE_DAY
ONE_MONTH = 4 * ONE_WEEK
def __init__(self, filename, max_file_size_kb=-1):
... | cached_time = data[1]
pass
now = datetime.datetime.now()
if cached_time is not None:
# this is so stupid, but we have the function 'total_seconds' only st | arting with python 2.7
diff_seconds = _seconds_difference(cached_time, now)
pass
if cached_data is None or diff_seconds > seconds:
cached_data = partial_func()
self._set(cache_id, cached_data)
pass
return cached_data
pass
|
wolverineav/horizon-bsn | horizon_bsn/bsndashboard/networktemplate/panel.py | Python | apache-2.0 | 817 | 0.001224 | # 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.a | pache.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 limi... | bsn.bsndashboard import dashboard
class Networktemplate(horizon.Panel):
name = _("Network Templates")
slug = "networktemplate"
dashboard.Bsndashboard.register(Networktemplate)
|
wiad/librenms | discovery-wrapper.py | Python | gpl-3.0 | 13,314 | 0.004431 | #! /usr/bin/env python2
"""
discovery-wrapper A small tool which wraps around discovery and tries to
guide the discovery process with a more modern approach with a
Queue and workers.
Based on the original version of poller-wrapper.py by Job Snijders
Author: Neil Lathwood <nei... | sefu | l, but
WITHOUT ANY WARRANTY; without even the implied warranty of
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
... |
GoogleCloudPlatform/datacatalog-connectors-hive | google-datacatalog-hive-connector/src/google/datacatalog_connectors/hive/scrape/metadata_sync_event_scraper.py | Python | apache-2.0 | 5,015 | 0 | #!/usr/bin/python
#
# Copyright 2020 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 ag... | urn cls.__build_metadata_entities_for_drop_database_event(
message)
@classmethod
def __buil | d_metadata_entities_for_create_table_event(cls, message):
database, table = cls.__build_common_metadata_fields(message['table'])
table.table_params = []
tables = [table]
database.tables = tables
return {'databases': [database]}
@classmethod
def __build_metadata_entities... |
Cat5TV/nems-scripts | temper.py | Python | gpl-3.0 | 14,754 | 0.007794 | #!/usr/bin/env python3
# temper.py -*-python-*-
# Copyright 2018 by Pham Urwen (urwen@mail.ru)
#
# 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 limitat... | # Get firmware identifier
os.write(fd, struct.pack('8B', 0x01, 0x86, 0xff, 0x01, 0, 0, 0, 0))
firmware = b''
while True:
r, _, _ = select.select([fd], [], [], 0.1)
if fd not in r:
break
data = os.read(fd, 8)
firmware += data
if firmware == b'':
os.close(fd)
r... | rmware value: %s' % binascii.b2a_hex(firmware))
# Get temperature/humidity
os.write(fd, struct.pack('8B', 0x01, 0x80, 0x33, 0x01, 0, 0, 0, 0))
bytes = b''
while True:
r, _, _ = select.select([fd], [], [], 0.1)
if fd not in r:
break
data = os.read(fd, 8)
bytes += data
... |
cblop/tropic | instal-linux/instal/firstprinciples/fluentchange/TestInitiateNormsPerms.py | Python | epl-1.0 | 1,549 | 0.005165 | from instal.firstprinciples.TestEngine import InstalSingleShotTestRunner, InstalTestCase
from instal.instalexceptions import InstalParserError
class InitiateNormsPerms(InstalTestCase):
def test_initiate_perms_institutional(self):
runner = InstalSingleShotTestRunner(input_files=["fluentchange/perminitiate... | domain_files=[
"fluentchange/fluentchange.idc"],
fact_files=["fluentchange/fluentinitiates_permissions.iaf"])
in_a_true_condition = [
{"holdsat": ["holdsat(perm(ex_a(foo... | bose=self.verbose,
conditions=in_a_true_condition), 0,
"A permission initiated by an institutional event")
def test_initiate_perms_exogenous(self):
runner = InstalSingleShotTestRunner(input_files=["fluentchange/perminitiates_exogenous.ial"],... |
lbjworld/article-search | article-manager/site/employee/views.py | Python | mit | 526 | 0.003802 | # codin | g: utf-8
from rest_framework import generics
from rest_framework import filters
from employee.models import Operator
from employee.serializers import EmployeeDetailSerializer
class IsOwnerFilterBackend(filters.BaseFilterBackend | ):
def filter_queryset(self, request, queryset, view):
return queryset.filter(user=request.user)
class EmployeeDetail(generics.RetrieveAPIView):
queryset = Operator.objects.all()
serializer_class = EmployeeDetailSerializer
filter_backends = (IsOwnerFilterBackend,)
|
Frikanalen/frikanalen | packages/utils/prom-check-video-stream/snapshot.py | Python | lgpl-3.0 | 674 | 0.004451 | import asyncio
import aiohttp
class Snapshot:
filename = 'fk_test.ts'
async def update(self):
async with aiohttp.ClientSession() as session:
async with session.get('http://192.168.3.1:9094/frikanalen.ts') as resp:
with open(self.filename, 'wb') as fd:
wh... | ait resp.content.read(1024)
if not chunk:
break
fd.write(chunk)
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(Snap | shot.update())
|
burnpanck/traits | traits/tests/test_class_traits.py | Python | bsd-3-clause | 1,363 | 0 | """
Unit tests for the `HasTraits.class_traits` class function.
"""
from __future__ import absolute_import
from traits import _py2to3
from traits.testing.unittest_tools import unittest
from ..api import HasTraits, Int, List, Str
class A(HasTraits):
x = Int
name = Str(marked=True)
class B(A):
pas... | eve all traits that have the `marked` metadata
# attrib | ute set to True.
traits = C.class_traits(marked=True)
_py2to3.assertCountEqual(self, traits.keys(), ('y', 'name'))
# Retrieve all traits that have a `marked` metadata attribute,
# regardless of its value.
marked_traits = C.class_traits(marked=lambda attr: attr is not None)
... |
stackforge/blazar | blazar/tests/plugins/oshosts/test_physical_host_plugin.py | Python | apache-2.0 | 103,122 | 0 | # Copyright (c) 2013 Bull.
#
# 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, sof... | _api, 'host_extra_capability_get_all_per_host')
self.db_host_extra_capability_get_all_per_name = self.patch(
self.db_api, 'host_extra_capability_get_all_per_name')
self.db_host_extra_capability_create = self.patch(
| self.db_api, 'host_extra_capability_create')
self.db_host_extra_capability_update = self.patch(
self.db_api, 'host_extra_capability_update')
self.nova = nova
self.rp_create = self.patch(self.nova.ReservationPool, 'create')
self.patch(self.nova.ReservationPool, 'get_aggregat... |
onto/sonata | sonata/library.py | Python | gpl-3.0 | 66,200 | 0.000785 | import os
import re
import gettext
import locale
import threading # libsearchfilter_toggle starts thread libsearchfilter_loop
import operator
import gtk
import gobject
import pango
import ui
import misc
import formatting
import mpdhelper as mpdh
from consts import consts
import breadcrumbs
def library_set_data(albu... | CK_CANCEL),
h=self.searchcombo.size_request()[1])
self.searchbutton.set_no_show_all(True)
self.searchbutton.hide()
self.searchbutton.set_tooltip_text(_("End Search"))
self.libraryview = ui.button(relief=gtk.RELIEF_NONE)
sel | f.libraryview.set_tooltip_text(_("Library browsing view"))
# disabled as breadcrumbs replace this:
# self.searchbox.pack_start(self.libraryview, False, False, 1)
# self.searchbox.pack_start(gtk.VSeparator(), False, False, 2)
self.searchbox.pack_start(ui.label(_("Search:")), False, False, 3)
se... |
MonoCloud/pyoanda | setup.py | Python | mit | 2,560 | 0 | from setuptools import setup, find_packages
from codecs import open
from os import path
import pyoanda
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='P... | _packages(exclude=['contrib', 'docs', 'tests*' | ]),
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['requests'],
tests_require=['nose', 'cov... |
DadanielZ/incubator-eagle | eagle-external/hadoop_jmx_collector/lib/kafka-python/kafka/common.py | Python | apache-2.0 | 4,849 | 0.002269 | import inspect
import sys
from collections import namedtuple
###############
# Structs #
###############
# Request payloads
ProduceRequest = namedtuple("ProduceRequest",
["topic", "partition", "messages"])
FetchRequest = namedtuple("FetchRequest",
["topic", "... | ProtocolError(KafkaError):
pass
class UnsupportedCodecError(KafkaError):
pass
class KafkaConfigurationError(KafkaError):
pass
def _iter_broker_errors():
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj) and issubclass(obj, BrokerResponseError) and obj != ... | nseError:
yield obj
kafka_errors = dict([(x.errno, x) for x in _iter_broker_errors()])
def check_error(response):
if response.error:
error_class = kafka_errors.get(response.error, UnknownError)
raise error_class(response)
|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/PIL/ImageChops.py | Python | gpl-3.0 | 44 | 0.022727 | ../../../../share | /pyshared/PIL/ImageChops.p | y |
nacc/autotest | client/tools/tapfd_helper.py | Python | gpl-2.0 | 1,866 | 0.001608 | #!/usr/bin/python
import sys, os, re, logging
import common
from autotest.client.shared import logging_manager
from autotest.client.virt import virt_utils
def destroy_tap(tapfd_list):
f | or tapfd in tapfd_list:
try:
os.close(tapfd)
# File descriptor is already closed
except OSError:
pass
if __name__ | == "__main__":
logging_manager.configure_logging(virt_utils.VirtLoggingConfig(),
verbose=True)
if len(sys.argv) <= 2:
logging.info("Usage: %s bridge_name qemu_command_line", sys.argv[0])
sys.exit(255)
brname = sys.argv[1]
cmd_line = ' '.join(sys.arg... |
garbas/mozilla-releng-services | src/shipit_taskcluster/tests/test_tc_utils.py | Python | mpl-2.0 | 912 | 0.002193 | # -*- coding: utf-8 -*-
import pytest
from unittest.mock import patch
import os
import json
from shipit_taskcluster.taskcluster_utils import get_queue_group_state
def mocked_listtaskgroup(task_group_id):
filename = os.path.join(os.path.dirname(__file__), 'testdata', task_group_id)
with open(filename, 'r') as... | ,
'running',
),
(
'somefailedid',
'failed',
),
(
'someexceptionid',
'failed',
),
(
'badformatid',
'exception'
),
))
def test_get_queue_group_state(task_group_id, result):
assert get_queue_group_state(task_ | group_id) == result
|
heryandi/mnp | mnp/test/test_command.py | Python | mit | 6,569 | 0.00548 | import StringIO
import sys
import unittest
from mock import patch
from mnp.command import *
# For tests needing subprocess
class SubprocessTest(unittest.TestCase):
def setUp(self):
patcher1 = patch("subprocess.check_call")
self.addCleanup(patcher1.stop)
self.mockSubprocess_check_call = pa... | uery1"}, "or")
newest_packages = [
{"name": "package1", "version": "1.1.0", "summary": "summary1"},
{"name": "package2", "version": "1.0.0", "summary": "summary2"},
]
expected_string = "\n".join("- ".join([p["name"].ljust(20), p["summary"]]) for p in newest_packages)
... | lass DocsTest(XmlRpcTest):
def setUp(self):
super(DocsTest, self).setUp()
self.docs_return_value = "Some String"
self.mockServerProxy.return_value.docs.return_value = self.docs_return_value
def test_docs(self):
docs("indexUrl1", "package1")
self.mockServerProxy.assert_c... |
Apostol3/race_env_editor | map.py | Python | mit | 1,833 | 0.001091 | import json
import math
__author__ = 'apostol3'
class Map:
def __init__(self, w, h):
self.max_time = 120
self.size = (w, h)
self.walls = []
self.headline = []
self.cars = []
self.finish = []
self.objects = []
self.car_size = (1.8/2, 4.6/2)
def ... |
def create_car(self, x, y):
self.cars.append((x, y, 3 * math.pi / 2))
def append_finish_ | point(self, x, y):
if x > self.size[0] or y > self.size[1]:
self.finish.clear()
if len(self.finish) < 2:
self.finish.append((x, y))
else:
self.finish = [(x, y)]
@staticmethod
def open_from_file(file):
f = open(file, 'r')
doc = json.loa... |
jacobbieker/Insights | insights/google/GCalendar2SQLite.py | Python | gpl-2.0 | 4,019 | 0.001244 | '''
Copyright (C) 2015 Jacob Bieker, jacob@bieker.us, www.jacobbieker.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; either version 2 of the License, or
(at your option) any later version.
Thi... | tants"])
constants = configuration_files[0]
def process_calendar(calendar) | :
with open(calendar, "r", encoding="latin-1") as source:
# Dictionary of values to insert later
event_data = []
which_calendar = os.path.basename(calendar)
which_calendar = which_calendar.replace(".ics", "")
print(which_calendar)
for line in source:
compo... |
martbhell/wasthereannhlgamelastnight | src/lib/pyasn1/codec/cer/encoder.py | Python | mit | 9,409 | 0.001275 | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pyasn1/license.html
#
from pyasn1 import error
from pyasn1.codec.ber import encoder
from pyasn1.compat.octets import str2octs, null
from pyasn1.type import univ
from pyasn1.type import ... | value | = asn1Spec.clone(value)
numbers = value.asNumbers()
if self.PLUS_CHAR in numbers or self.MINUS_CHAR in numbers:
raise error.PyAsn1Error('Must be UTC time: %r' % value)
if numbers[-1] != self.Z_CHAR:
raise error.PyAsn1Error('Missing "Z" time zone specifier: %r' % value)... |
kyle8998/Practice-Coding-Questions | CTCI/Chapter3/3.3-Stack_Of_Plates.py | Python | unlicense | 1,838 | 0.005985 | # CTCI 3.1
# Three in One
import unittest
class MultiStack():
def __init__(self, capacity):
self.capacity = capacity
self.stacks = []
def push(self, item):
if len(self.stacks) and (len(self.stacks[-1]) < self.capacity):
self.stacks[-1].append(item)
else:
... | 22)
stack.push(33)
stack.push(44)
stack.push(55)
stack.push(66)
stack.push(77)
stack.push(88)
self.assertEqual(stack.pop(), 88)
self.assertEqual(stack.pop_at(1), 66)
self.assertEqual(stack.pop_at(0), 33)
self.assertEqual(stack.pop_at(1), 55)
se | lf.assertEqual(stack.pop_at(1), 44)
self.assertEqual(stack.pop_at(1), None)
stack.push(99)
self.assertEqual(stack.pop(), 99)
self.assertEqual(stack.pop(), 77)
self.assertEqual(stack.pop(), 22)
self.assertEqual(stack.pop(), 11)
self.assertEqual(stack.pop(), None)
if __name__ == "__main__":
... |
Symmetry-Innovations-Pty-Ltd/Python-2.7-for-QNX6.5.0-x86 | usr/pkg/lib/python2.7/distutils/unixccompiler.py | Python | mit | 14,430 | 0.00194 | """distutils.unixccompiler
Contains the UnixCCompiler class, a subclass of CCompiler that handles
the "typical" Unix-style command-line C compiler:
* macros defined with -Dname[=value]
* macros undefined with -Uname
* include search directories specified with -Idir
* libraries specified with -lllib
* library... | atic_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s"
if sys.platform == "cygwin":
exe_extension = ".exe"
def preprocess(self, source,
output_file=None, macros=None, include_dirs=None,
extra_preargs=None, extra_postargs=None):
ignore, macros, i... | + pp_opts
if output_file:
pp_args.extend(['-o', output_file])
if extra_preargs:
pp_args[:0] = extra_preargs
if extra_postargs:
pp_args.extend(extra_postargs)
pp_args.append(source)
# We need to preprocess: either we're being forced to, or we'r... |
mountainstorm/MobileDevice | crashmover.py | Python | mit | 4,328 | 0.028195 | #!/usr/bin/python
# coding: utf-8
# Copyright (c) 2013 Mountainstorm
#
# 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,... | rt afccrashlogdirectory
import posixpath
import stat
def cmd_crashmove(args, dev):
cm = CrashMover(dev)
cm.move_crashlogs()
cm.disconnect()
def get_logs(afc, path, dest):
dirlist = []
for name in afc.listdir(path):
info = afc.lstat(posixpath.join(path, name))
if info.st_ifmt == stat.S_I | FDIR:
dirlist.append((
posixpath.join(path, name),
os.path.join(dest, name)
))
try:
os.mkdir(os.path.join(dest, name))
except OSError:
pass # it already exists
elif info.st_ifmt == stat.S_IFLNK:
pass # XXX handle symlinks e.g. LatestCrash*
else:
s = afc.open(posixpath.j... |
phe-bioinformatics/emm-typing-tool | modules/phe_exceptions.py | Python | gpl-3.0 | 2,133 | 0.007501 | '''
Base module for all of the exceptions classes used internally.
Created on 10 Dec 2013
@author: alex
'''
class PheException(Exception):
'''
This is the top level class that EVERYTHING must be derived from. In particular,
this class contains an abstract property called 'phe_return_code'. This property... | f
the exception. In this case, the cause should generally be subprocess.CallerProcessError.
The particu | lars of the failed command can be found inside the cause.
If the catcher of this exception choses to exit the code, 'phe_return_code'
should be used to indicate the cause of it all.
'''
def __init__(self, msg, cause):
'''
Constructor for the PheExternalError
... |
workflo/dxf2gcode | python_examples/NURBS_fitting_by_Biarc_curves.py | Python | gpl-3.0 | 69,179 | 0.021943 | #!/usr/bin/python
# -*- coding: cp1252 -*-
#
#NURBS_fittin_by_Biarc_curves
#Programmer: Christian Kohlöffel
#E-mail: n/A
#
#Copyright 2008 Christian Kohlöffel
#
#Distributed under the terms of the GPL (GNU Public License)
#
#dxf2gcode is free software; you can redistribute it and/or modify
#it under the terms of th... | r Homogenen Punkte bis zur n ten Ableitung
HPt=self.BSpline.bspline_ders | _evaluate(n=n,u=u)
#Punkt wieder in Normal Koordinaten zurück transformieren
Point=self.HPt_2_Pt(HPt[0])
#Errechnen der ersten Ableitung wenn n>0 als Richtungsvektor
dPt=[]
tangent=None
if n>0:
# w(u)*A'(u)-w'(u)*A(u)
#dPt=----... |
joebos/django-allauth | allauth/socialaccount/providers/oauth/views.py | Python | mit | 3,898 | 0.001539 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from allauth.socialaccount.helpers import render_authentication_error, send_social_connection_error_email
from allauth.socialaccount.providers.oauth.client import (OAuthClient,
... | uth.socialaccount.helpers import complete_social_login
from allauth.socialaccount import providers
from allauth.socialaccount.models import SocialToken, SocialLogin
from ..base import AuthAction
class OAuthAdapter(object):
def complete_login(self, request, app):
"""
Returns a SocialLogin instanc... | rs.registry.by_id(self.provider_id)
class OAuthView(object):
@classmethod
def adapter_view(cls, adapter):
def view(request, *args, **kwargs):
self = cls()
self.request = request
self.adapter = adapter()
return self.dispatch(request, *args, **kwargs)
... |
CaymanUnterborn/burnman | burnman/minerals/HP_2011_fluids.py | Python | gpl-2.0 | 5,104 | 0.001763 | # This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for the Earth and Planetary Sciences
# Copyright (C) 2012 - 2017 by the BurnMan team, released under the GNU
# GPL v2 or later.
"""
HP_2011_fluids
^^^^^^^^
| Fluids from Holland and Powell 2011 and references therein.
CORK parameters:
CHO gases from Holland and Powell, 1991. ["CO2",304.2,0.0738],["CH4",190.6,0.0460],["H2",41.2,0.0211],["CO",132.9,0.0350]
H2O and S2 from Wikipedia, 2012/10/23. ["H2O",647.096,0.22060],["S2",1314.00,0.21000]
H2S from ancyclopedia.airliquide.co... | in Holland and Powell datasets are
a = kJ^2/kbar*K^(1/2)/mol^2 -> multiply by 1e-2
b = kJ/kbar/mol -> multiply by 1e-5
c = kJ/kbar^1.5/mol -> multiply by 1e-9
d = kJ/kbar^2/mol -> multiply by 1e-13
Individual terms are divided through by P, P, P^1.5, P^2, so
[0][j] -> multiply by 1e6
[1][j] -> multiply by 1e3
[2][j] ... |
awacha/cct | attic/gui/toolframes/accounting.py | Python | bsd-3-clause | 3,520 | 0.003409 | import logging
from ..core.functions import update_comboboxtext_choices
from ..core.toolframe import ToolFrame
from ...core.services.accounting import Accounting, PrivilegeLevel
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class AccountingFrame(ToolFrame):
def __init__(self, *args, **kwarg... | .instrument.services['accounting'].get_user())
self.on_accounting_privlevel_changed(self.instrument.services['accounting'],
self.instrument.services['accounting'].get_privilegelevel())
self._acctconn = [self.instrument.services['accounting'].connect('project-... | g'].connect('privlevel-changed',
self.on_accounting_privlevel_changed),
self.instrument.services['accounting'].connect('user-changed', self.on_user_changed)]
self.on_project_changed(self.instrument.services['accou... |
softinus/IMDB_DataMiner | imdb.com/Parse_err.py | Python | apache-2.0 | 3,935 | 0.012706 | # written by python 2.*
import urllib2
import string
import os
import re
import sys
from datetime import datetime
from bs4 import BeautifulSoup
import logging
import ssl
import Config
from AllMovies_imdb import upload_data, add_empty_data, get_connections, get_business_of_movie, get_companycredits_of_movie, get_f... | todo) # 4. if it has things to do, do work.
if fileuri == "":
print "There's no file."
| todo.status = "done"
todo.save()
else:
upload_data(session, todo, fileuri)
|
hellsgate1001/thatforum_django | thatforum/models.py | Python | mit | 3,446 | 0 | from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import slugify
from mptt.models import MPTTModel, TreeForeignKey
class ForumCategory(MPTTModel):
parent = TreeForeignKey(
'self', blank=True, null=True, related_n... | self.slug == '':
self.slug = slugify(self.title)
return super(ForumThread, se | lf).save(*args, **kwargs)
class ForumPost(models.Model):
thread = models.ForeignKey(ForumThread)
post = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
reply_to = models.Fore... |
ppizarror/Hero-of-Antair | data/images/pil/FitsStubImagePlugin.py | Python | gpl-2.0 | 1,644 | 0.002433 | #
# T | he Python Imaging Library
# $Id$
#
# FITS stub adapter
#
# Copyright (c) 1998-2003 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
import Image, ImageFile
_handler = None
##
# Install application-specific FITS image handler.
#
# @param handler Handler object.
def register_ha... | global _handler
_handler = handler
# --------------------------------------------------------------------
# Image adapter
def _accept(prefix):
return prefix[:6] == "SIMPLE"
class FITSStubImageFile(ImageFile.StubImageFile):
format = "FITS"
format_description = "FITS"
def _open(self):
... |
Pantkowsky/electricitymap | feeder/parsers/ENTSOE.py | Python | gpl-3.0 | 15,636 | 0.004605 | from bs4 import BeautifulSoup
from collections import defaultdict
import arrow, os, re, requests
ENTSOE_ENDPOINT = 'https://transparency.entsoe.eu/api'
ENTSOE_PARAMETER_DESC = {
'B01': 'Biomass',
'B02': 'Fossil Brown coal/Lignite',
'B03': 'Fossil Coal-derived gas',
'B04': 'Fossil Gas',
'B05': 'Foss... | NTSOE_TOKEN']
return session.get(ENTSOE_ENDPOINT, params=params)
def query_consumption(domain, session):
params = {
'documentType': 'A65',
'processType': 'A16',
'outBiddingZone_Domain': domain,
}
response = query_ENTSOE(session, params)
if response.ok: return | response.text
else:
# Grab the error if possible
soup = BeautifulSoup(response.text, 'html.parser')
error_text = soup.find_all('text')[0].contents[0]
if 'No matching data found' in error_text: return
raise Exception('Failed to get consumption. Reason: %s' % error_text)
def q... |
JuliaSprenger/elephant | elephant/statistics.py | Python | bsd-3-clause | 44,328 | 0 | # -*- coding: utf-8 -*-
"""
Statistical measures of spike trains (e.g., Fano factor) and functions to
estimate firing rates.
Tutorial
--------
:doc:`View tutorial <../tutorials/statistics>`
Run tutorial interactively:
.. image:: https://mybinder.org/badge.svg
:target: https://mybinder.org/v2/gh/NeuralEnsemble/el... |
The firing rate of the `spiketrain`
Raises
---- | --
TypeError
If the input spiketrain is a `np.ndarray` but `t_start` or `t_stop` is
`pq.Quantity`.
If the input spiketrain is a `neo.SpikeTrain` or `pq.Quantity` but
`t_start` or `t_stop` is not `pq.Quantity`.
ValueError
If the input spiketrain is empty.
"""
if ... |
mongodb/mongo-python-driver | test/test_transactions.py | Python | apache-2.0 | 20,801 | 0.00149 | # Copyright 2018-present MongoDB, 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 wri... | # Session is pinned to Mongos.
with s.start_transaction():
coll.insert_one({}, session=s)
addresses = set()
for _ in range(UNPIN_TEST_MAX_ATTEMPTS):
with s.start_transaction():
cursor = coll.find({}, session=s)
... | addresses.add(cursor.address)
# Break early if we can.
if len(addresses) > 1:
break
self.assertGreater(len(addresses), 1)
@client_context.require_transactions
@client_context.require_multiple_mongoses
def test_unpin_for_non_tra... |
chubbymaggie/simuvex | simuvex/procedures/libc___so___6/__isoc99_sscanf.py | Python | bsd-2-clause | 684 | 0.00731 | import simuvex
from simuvex.s_format import FormatParser
from simuvex.s_type import SimTypeInt, SimTypeString
import logging
l = logging.getLogger("simuvex.procedures.libc.system")
class __isoc99_sscanf | (FormatParser):
#pylint:disable=arguments-differ
def run(self, scan, fmt):
#pylint:disable=attribute-defined-outside-init
self.argument_types = {0: self.ty_ptr(SimTypeString()),
| 1: self.ty_ptr(SimTypeString())}
self.return_type = SimTypeInt(self.state.arch.bits, True)
fmt_str = self._parse(1)
_, items = fmt_str.interpret(self.arg(0), 2, self.arg, region=self.state.memory)
return items
|
gepd/uPiotMicroPythonTool | tools/sampy_manager.py | Python | mit | 9,119 | 0 | # This file is part of the uPiot project, https://github.com/gepd/upiot/
#
# MIT License
#
# Copyright (c) 2017 GEPD
#
# 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, inc... | the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCL | UDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WIT... |
acrsilva/animated-zZz-machine | bundle_final_app/source/panelScatter.py | Python | lgpl-3.0 | 11,134 | 0.009263 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from PyQt4.uic import loadUiType
from pyqtgraph.Qt import QtCore, QtGui
#from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as Fig... | <b>Episodio:</b> " + ep.nombre))
vbox.addWidget(QtGui.QLabel("<b>Inicio:</b> " + str(ep.tiempo[0])))
vbox.addWidget(QtGui.QLabel("<b>Final:</b> " + str(ep.tiempo[-1])))
vbox.addWidget(QtGui.QLabel("<b>Duración:</b> %s min" % (ep.tiempo[-1] - ep.tiempo[0])))
vbox.addWidget(QtGui.QL | abel("<b>Coeficiente de correlación:</b> " + str(ep.correlacion)[:5]))
vbox.addWidget(QtGui.QLabel("<b>Calorías consumidas:</b> " + str(ep.numCalorias)[:6] + " (" + str(ep.numCalorias/self.selep.totalCal*100)[:4] + "%)"))
vbox.addWidget(canvas1)
vbox.addWidget(canvas2)
canvas2.mpl_connec... |
Matt-Deacalion/django | tests/schema/fields.py | Python | bsd-3-clause | 2,822 | 0.002835 | from django.db import models
from django.db.models.fields.related import (
RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor,
ManyToManyField, ManyToManyRel, RelatedField,
create_many_to_many_intermediary_model,
)
from django.utils.functional import curry
class CustomManyToManyField(RelatedField):
... | emote_field.through = create_many_to_many_intermediary_model(self, cls)
setattr(cls, self.name, ManyToManyDescriptor(self.remote_field))
self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)
def get_internal_type(self):
return 'ManyToManyField'
# Copy those methods from ManyToMa... | ontribute_to_related_class = ManyToManyField.__dict__['contribute_to_related_class']
_get_m2m_attr = ManyToManyField.__dict__['_get_m2m_attr']
_get_m2m_reverse_attr = ManyToManyField.__dict__['_get_m2m_reverse_attr']
_get_m2m_db_table = ManyToManyField.__dict__['_get_m2m_db_table']
class InheritedManyToMa... |
toway/towaymeetups | mba/views/admin/meetup_types.py | Python | gpl-3.0 | 3,010 | 0.008174 | #!/usr/bin/python
# coding: utf-8
from datetime import datetime
import deform
import colander
import jinja2
from deform import ValidationFailure
from deform.widget import CheckedPasswordWidget
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPForbidden
from pyramid.httpexceptions import HTTP... | od == 'del-mt':
DBSession.delete(to_op_mt)
request.session.flash(_(u"成功删除'%s'" % mt_title), 'succe | ss')
elif method == 'mdf-mt':
to_op_mt.title = mt_title
request.session.flash(_(u"修改成功!"), 'success')
else:
err_msg = u"错误的方法"
request.session.flash(_(u"错误的参数"))
except Exception,ex:
er... |
sapfo/ancientselection | ancientselection/ancientselection.py | Python | gpl-3.0 | 12,851 | 0.028947 | #!/usr/bin/env python
import sys,os,random,errno
import numpy as np
import argparse
from argparse import RawTextHelpFormatter
# ---------------- Arguments
parser = argparse.ArgumentParser(description='''Take as input time se | rial data (one locus). The output can be either mles or | likelihood surface over a grid or the mles'
An example of a run: ./ancientselection.py -i TestData_sel0_Jeff.py --dirout Out --codedir ../ancientselection/ --run run1 --exhaust''',formatter_class=RawTextHelpFormatter)
#./ancientselection.py -i TestData_sel0_Jeff.py --dirout Out --codedir ../ancientselection/ --run run1... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/social/backends/shopify.py | Python | agpl-3.0 | 3,362 | 0 | """
Shopify OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/shopify.html
"""
import imp
import six
from social.utils import handle_http_errors
from social.backends.oauth import BaseOAuth2
from social.exceptions import AuthFailed, AuthCanceled
class ShopifyOAuth2(BaseOAuth2):
"""Shopify OA... | t_uri(state)
session = self.shopifyAPI.Session(self.data.get('shop').strip())
return session.create_permission_url(
scope=scope,
redirect_uri=redirect_uri
)
@handle_http_errors
| def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance"""
self.process_error(self.data)
access_token = None
key, secret = self.get_key_and_secret()
try:
shop_url = self.data.get('shop')
self.shopifyAPI.Session.setup... |
adamfast/isthatanearthquake | isthatanearthquake/settings.py | Python | bsd-3-clause | 7,204 | 0.002082 | import os
import socket
# Django settings for isthatanearthquake project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
if socket.gethostname() == 'adam-air' or socket.gethostname() == 'TWC101037.local':
DATABASES = {
'default': {
... | postgres']['host'],
}
else:
DATABASE_ENGINE = "postgresql_psycopg2"
DATABASE_NAME = config['postgres']['data | base']
DATABASE_USER = config['postgres']['username']
DATABASE_PASSWORD = config['postgres']['password']
DATABASE_HOST = config['postgres']['host']
if "redis" in config:
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
... |
sanacl/GrimoireELK | grimoire/elk/gmane.py | Python | gpl-3.0 | 995 | 0.001005 | #!/usr/bin/python3
# | -*- coding: utf-8 -*-
#
#
# Copyright (C) 2015 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# i | t 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
# MERCHANTABI... |
millen1m/flask-restplus-server-example | tests/conftest.py | Python | mit | 2,625 | 0.002286 | # encoding: utf-8
# pylint: disable=redefined-outer-name,missing-docstring
import pytest
from tests import utils
from app import create_app
@pytest.yield_fixture(scope='session')
def flask_app():
app = create_app(flask_config_name='testing')
from app.extensions import db
with app.app_context():
... |
flask_app.test_client_class = utils.AutoAuthFlaskClient
flask_app.response_class = utils.JSONResponse
return flask_app.test_client()
@pytest.yield_fixture(scope='session')
def regular_user(flask_app):
# pylint: disable | =invalid-name,unused-argument
from app.extensions import db
regular_user_instance = utils.generate_user_instance(
username='regular_user'
)
db.session.add(regular_user_instance)
db.session.commit()
yield regular_user_instance
db.session.delete(regular_user_instance)
db.session.... |
numericube/twistranet | twistranet/notifier/models.py | Python | agpl-3.0 | 2,203 | 0.005901 | """
This is the content used as a notification.
"""
import pickle
from django.db import models
from django.utils.translation import ugettext as _
from twistranet.twistapp.models import Twistable, Content
from twistranet.twistapp.lib import permissions
class Notification(Content):
"""
ACCOUNT did WHAT [on ACC... | hor is usually SystemAccount.
Publisher is usually the community (or account) this content belongs to.
"""
# Parameters as a dict
_encoded_parameters = models.TextField()
# Other type configuration stuff
type_text_template_creation = None
type_html_template_creation = None
# Vi... | view = "content/summary.notification.part.html"
type_detail_view = None
def get_parameters(self,):
"""
Unpickle parameters
"""
if self._encoded_parameters:
p = self._encoded_parameters
if isinstance(p, unicode):
p = p.encode('ascii')
... |
bsipocz/astropy | astropy/table/__init__.py | Python | bsd-3-clause | 2,572 | 0.004277 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.table`.
"""
auto_colname = _config.ConfigItem(
'col{0}',
'The template that determines the name of a co... | leColumns, Row, TableFormatter,
NdarrayMixin, TableReplaceWarning)
from .operations import join, setdiff, hstack, cstack, vstack, unique, TableMergeError
from .bst import BST, FastBST, FastRBT
from .sorted_array import SortedArray
from .soco import SCEngine
from .serialize import SerializedColumn, r... | import the formats for the read and write method but delay building
# the documentation until all are loaded. (#5275)
from astropy.io import registry
with registry.delay_doc_updates(Table):
# Import routines that connect readers/writers to astropy.table
from .jsviewer import JSViewer
from astropy.io.ascii ... |
ric2b/Vivaldi-browser | chromium/third_party/blink/tools/blinkpy/web_tests/port/base.py | Python | bsd-3-clause | 99,778 | 0.001032 | # Copyright (C) 2010 Google Inc. 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 conditions and the ... | ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Abstract base class for Port classes.
The Port classes encapsulate Port-specific (platform-specific) behavior
in the web test infrastructure.
" | ""
import time
import collections
import json
import logging
import optparse
import os
import re
import sys
import tempfile
from collections import defaultdict
import six
from six.moves import zip_longest
from blinkpy.common import exit_codes
from blinkpy.common import find_files
from blinkpy.common import read_chec... |
kodi-addons/plugin.video.espn_3 | resources/lib/adobe_activate_api.py | Python | gpl-3.0 | 11,244 | 0.002046 | import urlparse
import urllib
import uuid
import hashlib
import hmac
import base64
import urllib2
import time
import json
import gzip
import os
import cookielib
from StringIO import StringIO
import requests
import xbmc
from globals import ADDON_PATH_PROFILE
SETTINGS_FILE = 'adobe.json'
UA_ATV = 'AppleCoreMedia/1.0.0.... | nonce=' + nonce + ', signature_method=HMAC-SHA1, request_time=' + today + ', request_uri=' + path
signature = hmac.new(key, message, hashlib.sha1)
signature = base64.b64encode(signature.digest())
message = message + ', public_key=yKpsHYd8TOITdTMJHmkJOVmgbb2DykNK, signature=' + signature
return message
... | :
settings = load_settings()
if 'generateRegCode' not in settings:
xbmc.log(TAG + 'Unable to find reg code', xbmc.LOGDEBUG)
return False
# Check code isn't expired
expiration = settings['generateRegCode']['expires']
if is_expired(expiration):
xbmc.log(TAG + 'Reg code is expir... |
angelinawawrzyniak/bomberman | game.py | Python | mit | 2,898 | 0.00207 | from artifacts.life import Life
from artifacts.points import Point
from artifacts.super_bomb_artifact import SuperBombArtifact
from bomb import Bomb
from brick import Brick
from context import Context
from game_over_error import GameOverError
from monster import Monster
def draw_scene(context, graphic_buffer):
co... | ffer, context)
for artifact in context.artifacts:
artifact.draw(graphic_buffer, context)
if context.game_over:
letters = list('GAME OVER')
offset = int((len(graphic_buffer[0]) - len(letters)) / 2)
for x in range(0, len(letters)):
| graphic_buffer[int(len(graphic_buffer) / 2)][x + offset] = letters[x]
for row in graphic_buffer:
print(' '.join(row))
print('Level: {}, Lives: {}, Points: {}'.format(context.game_level, context.user.life,
context.user.points))
for bomb in con... |
jwbernin/dns-sanity-checker | bindripper.py | Python | gpl-2.0 | 8,378 | 0.015039 | #!/usr/bin/python
import sys
import os
import pprint
import copy
class BINDRipper:
def __init__(self):
self.cfgTokens = []
self.cfgStr = ""
self.curToken = 0
self.saveToken = 0
self.config = {}
return None
def consume(self):
_item = self.cfgTokens[self.curToken]
self.curToken+=1
... | fail - enter logging")
token = self.consume()
while token != '}':
if token == 'channe | l':
channelName = self.consume()
logging['channels'][channelName] = self.ripLogChannel()
elif token == 'category':
catName = self.consume()
logging['categories'][catName] = self.ripList()
else:
raise Exception("Parser fail - something not channel or category in loggin... |
Snergster/virl-salt | openstack/nova/files/kilo/vif.py | Python | gpl-2.0 | 31,926 | 0.000282 | # Copyright (C) 2011 Midokura KK
# Copyright (C) 2011 Nicira, Inc
# Copyright 2011 OpenStack Foundation
# 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
#
# ... | _ovs_interfaceid(vif),
self.get_vif_devname(vif))
designer.set_vif_bandwidth_config(conf, inst_type)
return conf
def get_config_ovs_hybrid(self, instance, vif, image_meta,
| inst_type, virt_type):
newvif = copy.deepcopy(vif)
newvif['network']['bridge'] = self.get_br_name(vif['id'])
return self.get_config_bridge(instance, newvif, image_meta,
inst_type, virt_type)
def get_config_ovs(self, instance, vi... |
alex-bauer/kelvin-power-challenge | src/viz/power_analysis.py | Python | mit | 708 | 0.012712 | """Visualizes top 5 power lines by variance"""
import sys
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
sys.path.append("../")
from utils.utils | import *
interval = '1D'
def d_resample(df):
if interval:
return df.resample(interval).mean()
else:
return df
scale=lambda x: MinMaxScaler().fit_transform(x)
target = d_resample(pd.read_pickle(config.data_folder + '/target.pkl'))
cols=config.target_cols
cols=sorted(cols, key=lambda col:t... | , label=col)
axs[ix].legend()
plt.show()
|
bacaldwell/ironic | ironic/tests/unit/drivers/modules/msftocs/test_power.py | Python | apache-2.0 | 7,843 | 0 | # Copyright 2015 Cloudbase Solutions Srl
# 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 r... | =self.info)
def test_get_properties(self):
expected = msftocs_common.REQUIRED_PROPERTIES
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
self.assertEqual(expected, task.driver.get_properties())
@mock.patch.object(msft | ocs_common, 'parse_driver_info', autospec=True)
def test_validate(self, mock_drvinfo):
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
task.driver.power.validate(task)
mock_drvinfo.assert_called_once_with(task.node)
... |
akruis/pyheapdump | pyheapdump/__main__.py | Python | apache-2.0 | 3,105 | 0.004509 | #
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 by Anselm Kruis
#
# 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 a... | the specific language governing permissions and
# limitations under the License.
#
"""
=====================
Pyheap | dump.__main__
=====================
Debug heap dumps.
.. warning::
This is alpha quality code.
.. autofunction:: main
"""
from __future__ import absolute_import, print_function, unicode_literals, division
import argparse
import sys
import os
from pyheapdump import debug_dump
def main(argv=None):
"""Debu... |
openstack/python-ironicclient | ironicclient/tests/unit/common/apiclient/test_exceptions.py | Python | apache-2.0 | 5,355 | 0 | # Copyright 2012 OpenStack Foundation
# 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 requ... | tion=False)
def test_from_response_with_different_response_format(self):
method = "GET"
url = "/fake-wsme"
status_code = http_client.BAD_REQUEST
json_data1 = {"error_message": {"debuginfo": None,
"faultcode": "Client",
... | faultstring": "fake message"}}
message = str(
json_data1["error_message"]["faultstring"])
details = str(json_data1)
self.assert_exception(
exceptions.BadRequest, method, url, status_code, json_data1,
message, details)
json_data2 = {"badRequest": {"mes... |
google-research/google-research | symbolic_functionals/syfes/xc/gga_test.py | Python | apache-2.0 | 6,540 | 0.003058 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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... | )
@parameterized.parameters(
('gga_x_pbe', gga.e_x_pbe_polarized),
('gga_x_rpbe', gga.e_x_rpbe_polarized),
('gga_x_b88', gga.e_x_b88_polarized),
('gga_c_pbe', gga.e_c_pbe_polarized),
('hyb_gga_xc_b97',
utils.function_sum(gga.e_x_b9 | 7_polarized, gga.e_c_b97_polarized)),
)
def test_gga_xc_polarized_against_libxc(self, xc_name, xc_fun):
eps_xc_ref, (vrho_ref, vsigma_ref, _, _), _, _ = libxc.eval_xc(
xc_name,
(self.rho_and_derivs_a, self.rho_and_derivs_b),
spin=1,
relativity=0,
deriv=1)
e_xc_ref... |
shiquanwang/numba | deps/pyextensibletype/setup.py | Python | bsd-2-clause | 975 | 0.005128 | import os
from fnmatch import fnmatchcase
from distutils.util import conve | rt_path
from distutils.core import setup
from Cython.Distutils import build_ext
from setupconfig import get_extensions
def find_packages(where='.', exclude=()):
out = []
stack=[(convert_path(where), '')]
while stack:
where, prefix = stack.pop(0)
| for name in os.listdir(where):
fn = os.path.join(where,name)
if ('.' not in name and os.path.isdir(fn) and
os.path.isfile(os.path.join(fn, '__init__.py'))
):
out.append(prefix+name)
stack.append((fn, prefix+name+'.'))
for pat in li... |
stvstnfrd/edx-platform | common/lib/xmodule/xmodule/modulestore/tests/test_mixed_modulestore.py | Python | agpl-3.0 | 178,445 | 0.003301 | """
Unit tests for the Mixed Modulestore, with DDT for the various stores (Split, Draft, XML)
"""
import datetime
import itertools
import logging
import mimetypes
from collections import namedtuple
from contextlib import contextmanager
from shutil import rmtree
from tempfile import mkdtemp
from uuid import uuid4
imp... | are_ignore_version(self, loc1, loc2, msg=None):
"""
AssertEqual replacement for CourseLocator
"""
if loc1.for_branch(None) != loc2.for_branch(None):
self.fail(self._formatMessage(msg, u"{} != {}".format(six.text_type(loc1), six.text_type(loc2))))
def setUp(self):
... | _field(None, 'wiki_slug')
self.exclude_field(None, 'xml_attributes')
self.exclude_field(None, 'parent')
self.ignore_asset_key('_id')
self.ignore_asset_key('uploadDate')
self.ignore_asset_key('content_son')
self.ignore_asset_key('thumbnail_location')
self.options ... |
nicholasmhughes/random-scripts | zeromq_examples/router_to_req.py | Python | gpl-3.0 | 1,519 | 0.002633 |
# encoding: utf-8
#
# Custom routing Router to Mama (ROUTER to REQ)
#
# Author: Jeremy Avnet (brainsik) <spork(dash)zmq(at)theo | ry(dot)org>
#
import time
import random
from threading import Thread
import zmq
import zhelpers
NBR_WORKERS = 10
def worker_thread(context=None):
context = context or zmq.Cont | ext.instance()
worker = context.socket(zmq.REQ)
# We use a string identity for ease here
zhelpers.set_id(worker)
worker.connect("tcp://localhost:5671")
total = 0
while True:
# Tell the router we're ready for work
worker.send(b"ready")
# Get workload from router, until ... |
akaraspt/deepsleepnet | tensorlayer/nlp.py | Python | apache-2.0 | 32,754 | 0.004396 | #! /usr/bin/python
# -*- coding: utf8 -*-
import tensorflow as tf
import os
from sys import platform as _platform
import collections
import random
import numpy as np
import warnings
from six.moves import xrange
from tensorflow.python.platform import gfile
import re
## Iteration functions
def generate_skip_gram_bat... | .int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(ba... | window ]
for j in range(num_skips):
while target in targets_to_avoid:
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.a... |
zhouhoo/conceptNet_55_client | tools/debug.py | Python | apache-2.0 | 213 | 0 | import inspect
def caller():
return inspect.stack | ()[2][3]
def print_debug(msg, tag=None):
if tag:
print('[%s]%s %s' % (caller(), tag, msg))
else:
print('[%s] %s' % ( | caller(), msg))
|
endlessm/chromium-browser | third_party/llvm/lldb/test/API/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py | Python | bsd-3-clause | 1,265 | 0 | # encoding: utf-8
"""
Test lldb data formatter subsystem.
"""
import lldb
from lldbsuite.test.dec | orators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
class ObjCDataFormatterNSURL(ObjCDataFormatterTestCase):
@skipUnlessDarwin
def test_nsurl_with_run_command(self):
"""Test formatters for NSURL.""... | ldurl_ref cfgchildurl_ref',
substrs=[
'(CFURLRef) cfurl_ref = ', '@"http://www.foo.bar',
'cfchildurl_ref = ', '@"page.html -- http://www.foo.bar',
'(CFURLRef) cfgchildurl_ref = ',
'@"?whatever -- http://www.foo.bar/page.html"'
])
... |
macedir/Software-Development | Python/OOP/Decorators.py | Python | gpl-3.0 | 398 | 0.012563 | # DECORATORS
import time
def funcA( | function):
def wrappingPaper():
t1 = time.time()
function()
t2 = time.time()
return 'Runtime was {} seconds.'.format(str(t2 - t1))
return wrappingPaper()
@funcA
def funcB():
workList = []
for x in range(0, 1001):
workList.append(x)
print('Sum is {}.'.form... | t(funcB)
|
andreamartire/gmpy | test2/test_large.py | Python | lgpl-3.0 | 884 | 0.003394 | from gmpy2 import *
from math import log
from time import time
# This test is designed to detect issues when allocating memory for large
# numbers. If it crashes and you need to work with very large numbers,
# you will need to compile GMP from scratch and tr | y a different memory
# allocation option.
def pi(N):
print "Computing pi to %s decimal places." % N
start = time()
N = int(round(log(10,2)*N))
sq2 = fs | qrt(mpf(2, N))
a = mpz(6) - 4*sq2
y = sq2-1
for k in range(0, 10000):
xx = fsqrt(fsqrt(1-y**4))
y = (1-xx)/(1+xx)
anew = a*(1+y)**4 - 2**(2*k+3)*y*(1+y+y**2)
if anew == a:
break
a = anew
print "Computation took %5.2f seconds." % (time() - sta... |
Qwlouse/Findeco | node_storage/tests/__init__.py | Python | gpl-3.0 | 1,410 | 0.004255 | #!/usr/bin/python
# coding=utf-8
# region License
# Findeco is dually licensed under GPLv3 or later and MPLv2.
#
################################################################################
# Copyright (c) 2012 Klaus Greff <klaus.greff@gmx.net>
# This file is part of Findeco.
#
# Findeco is free software; you can r... | , see <http://www.gnu.org/licenses/>.
################################################################################
#
################################################################################
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL w | as not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#endregion #####################################################################
from __future__ import division, print_function, unicode_literals
|
pgromano/Markov_Models | Markov_Models/coarse_grain/pcca.py | Python | gpl-3.0 | 1,708 | 0 | import numpy as np
from sklearn.preprocessing import normalize
from copy import deepcopy
class PCCA(object):
def __init__(self, n_states=2, psi=None, ncv=None):
self.n_states = n_states
if n_states < 2:
raise ValueError('''Coarse-graining with PCCA+ requires at least
... | ectors('right',
k | =self.n_states + 1, ncv=self.ncv)
self.psi = self.psi[:, 1:]
self.chi = np.zeros(self.psi.shape[0], dtype=int)
for ma in range(self.n_states - 1):
v = self.psi[:, ma]
index = np.argmax([spread(v[self.chi == mi])
for mi in range(ma + 1)])
... |
excelly/xpy-ml | ex/ml/rpca.py | Python | apache-2.0 | 2,134 | 0.007966 | from ex import *
from ex.alg.common import svdex
def RPCA(D, lam = None, tol = 1e-7, maxIter = 500):
'''Yi Ma's robust pca
return (L, SingularValues(L))
'''
m, n = D.shape
maxmn, minmn = (max(m, n), min(m, n))
lam = float(lam) if lam is not None else 1.0
log.info('RPCA for %dx%d matri... | )*Y;
E_hat[:] = 0;
filt = temp_T > lam/mu;
E_hat[filt] = temp_T[filt] - lam/mu
filt = temp_T < -lam/mu;
E_hat[filt] = temp_T[filt] + lam/mu
U, diagS, Vh = svdex(D - E_hat + (1/mu)*Y, sv)
svp = | sum(diagS > 1/mu);
if svp < sv:
sv = min(svp + 1, minmn)
else:
sv = min(svp + round(0.05*minmn), minmn)
A_hat = mul(U[:,:svp]*(diagS[:svp] - 1/mu), Vh[:svp])
Z = D - A_hat - E_hat
Y = Y + mu*Z
mu = min(mu*rho, mu_bar)
# stop criterion
... |
deonwu/Goku | scripts/GokuCtrl/ipa4django/views/pyExcelerator/BIFFRecords.py | Python | mit | 88,384 | 0.002478 | #!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 Roman V. Kiseliov
# 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. Redistributions of source code must reta... | chunks = []
pos = 0
while pos < len(data):
chunk_pos = pos + 0x2020
chunk = data[pos:chunk_pos]
chunks.append(chunk)
pos = chunk_pos
continues = pack('<2H', self._REC_ID, len(chunks[0])) + chunks[0]
... | continues += pack('<2H%ds'%len(chunk), 0x003C, len(chunk), chunk)
# 0x003C -- CONTINUE record id
return continues
else:
return self.get_rec_header() + data
class Biff8BOFRecord(BiffRecord):
"""
Offset Size Contents
0 2 Version, contains 0600H for BIF... |
BU-PyCon/Meeting-3 | Programs/interpolate.py | Python | mit | 3,010 | 0.015615 | import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from scipy.interpolate import interp1d,splev,splrep
def extractSpectrum(filename):
"""
NAME:
extractSpectrum
PURPOSE:
To open an input fits file from SDSS and extract the relevant
components, ... | ned for convienience.
INPUTS:
points Set of new points to get interpolated values for.
lam The wavelengths of the data points
flux The fluxes of the data points
method The method of interpolation to use. Valide values include
'interp1d... | 1d:quadratic', and 'splrep'.
OUTPUTS:
Interpolated set of values for each corresponding input point.
EXAMPLE:
interpFlux = interpolate(interpLam, lam, flux)
"""
if method == 'interp1d:linear':
f = interp1d(lam, flux, assume_sorted = True)
return f(points)
... |
blhughes/forge | forge/commands/group/add.py | Python | gpl-2.0 | 734 | 0.021798 | import forge
from forge.models.groups import Group
class Add(object):
def __init__(self,json_args,session):
if type(json_args) != type({}):
raise TypeError("JSON Arg must be dict type")
if 'name' and 'distribution' not in json_args.keys():
... | ribution = json_args['distribution']
| self.session = session
def call(self):
group = Group(self.name,self.distribution)
self.session.add(group)
self.session.commit()
return {'name':self.name, 'distribution':self.distribution}
|
kishs1991/mythoughts | mythoughts/mythoughts/settings.py | Python | gpl-3.0 | 3,202 | 0.001249 | """
Django settings for mythoughts project.
Generated by 'django-admin startproject' using Django 1.9.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os... | sn$y&twnk&b_9dpmegvvrks!v*sinbbi)!9'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'me.apps.MeConfig',
'django.contrib.admin',
'django.contrib.auth',
' | django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'd... |
anryko/ansible | lib/ansible/modules/network/onyx/onyx_snmp_hosts.py | Python | gpl-3.0 | 20,657 | 0.003824 | #!/usr/bin/python
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | notification_type: trap
port: 66
version: 2c
- name: configures snmp host with version 3 and configures it with user as sara
onyx_snmp_hosts:
hosts:
- name: 2.3.2.4
enabled: true
notification_type: trap
port: 66
version: 3
... | fh
- name: deletes the snmp host
onyx_snmp_hosts:
hosts:
- name: 2.3.2.4
state: absent
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device.
returned: always
type: list
sample:
- snmp-server host <host_name> disable
- no ... |
cedadev/ndg_xacml | ndg/xacml/core/context/action.py | Python | bsd-3-clause | 495 | 0.00202 | """NDG XACML Context Action type
NERC DataGrid
"""
__author__ = "P J Kershaw"
__date__ = "24/03/10"
__copyright__ = "(C) 2010 Science and Technology Facilities Council"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__license__ = "BSD - see | LICENSE file in top-level directory"
__contact | __ = "Philip.Kershaw@stfc.ac.uk"
__revision__ = "$Id$"
from ndg.xacml.core.context import RequestChildBase
class Action(RequestChildBase):
"""XACML Context Action type"""
ELEMENT_LOCAL_NAME = 'Action'
|
gusDuarte/sugar-toolkit-gtk3 | tests/graphics/customdestroy.py | Python | lgpl-2.1 | 918 | 0.002179 | from gi.repository import Gtk
"""
Since GTK+3 Gtk.CellRenderer doesn't have a destroy signal anymore.
We can do the cleanup in the python destructor | method instead.
"""
class MyCellRenderer(Gtk.CellRenderer):
def __init__(self):
Gtk.CellRenderer.__init__(self)
| def __del__(self):
print "cellrenderer destroy"
def do_render(self, cairo_t, widget, background_area, cell_area, flags):
pass
def window_destroy_cb(*kwargs):
print "window destroy"
Gtk.main_quit()
window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
window.connect("destroy", window_destroy_cb)... |
palmtree5/Red-DiscordBot | redbot/cogs/streams/streams.py | Python | gpl-3.0 | 39,323 | 0.00267 | import discord
from redbot.core.bot import Red
from redbot.core import checks, commands, Config
from redbot.core.i18n import cog_i18n, Translator, set_contextual_locales_from_guild
from redbot.core.utils._internal_utils import send_to_owners_with_prefix_replaced
from redbot.core.utils.chat_formatting import escape, pag... | params={
"client_id": tokens. | get("client_id", ""),
"client_secret": tokens.get("client_secret", ""),
"grant_type": "client_credentials",
},
) as req:
try:
data = await req.json()
except aiohttp.ContentTypeError:
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_data_structures/enum_aliases.py | Python | apache-2.0 | 470 | 0.002128 | import enum
class BugStatus(enum.Enum) | :
new = 7
incomplete = 6
invalid = 5
wont_fix = 4
in_progress = 3
fix_committed = 2
fix_released = 1
by_design = 4
closed = 1
for status in BugStatus:
print('{:15} = {}'.format(status.name, status.value))
print('\nSame: by_design is wont_fix: ',
BugStatus.by_design is B... | BugStatus.closed is BugStatus.fix_released)
|
sbnoemi/notorhot | notorhot/contrib/write_in/_tests/views.py | Python | bsd-3-clause | 4,631 | 0.011445 | import datetime
from mock import Mock, patch, MagicMock, PropertyMock
from django.test import TestCase
from django import forms
from django.http import Http40 | 4
from not | orhot._tests.factories import mixer
from notorhot._tests._utils import setup_view, ViewTestMixin
from notorhot.contrib.write_in._tests.models import SimpleWriteIn
from notorhot.contrib.write_in.models import DefaultWriteIn
from notorhot.contrib.write_in.views import WriteInBaseView, WriteInDefaultView, \
WriteInTha... |
evanw/flatbuffers | tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py | Python | apache-2.0 | 128 | 0.007813 | # automatically generated, do not mod | ify
# namespace: NamespaceB
class EnumInNestedNS(object | ):
A = 0
B = 1
C = 2
|
kidmaple/CoolWall | user/python/Tools/idle/keydefs.py | Python | gpl-2.0 | 2,235 | 0.000895 | windows_keydefs = \
{'<<Copy>>': ['<Control-c>'],
'<<Cut>>': [ | '<Control-x>'],
'<<Paste>>': ['<Co | ntrol-v>'],
'<<beginning-of-line>>': ['<Control-a>', '<Home>'],
'<<center-insert>>': ['<Control-l>'],
'<<close-all-windows>>': ['<Control-q>'],
'<<close-window>>': ['<Alt-F4>'],
'<<dump-undo-state>>': ['<Control-backslash>'],
'<<end-of-file>>': ['<Control-d>'],
'<<help>>': ['<F1>'],
'<<history-next>>': ['<Alt-n... |
docker/docker-py | tests/integration/api_image_test.py | Python | apache-2.0 | 12,869 | 0 | import contextlib
import json
import shutil
import socket
import tarfile
import tempfile
import threading
import pytest
from http.server import SimpleHTTPRequestHandler
import socketserver
import docker
from ..helpers import requires_api_version, requires_experimental
from .base import BaseAPIIntegrationTest, TEST_... | def dummy_tar_stream(self, n_bytes):
'''Yields a stream that is valid tar data of size n_bytes.'''
with tempfile.NamedTemporaryFile() as tar_file:
self.write_dummy_tar_content(n_bytes, tar_file)
tar_file.seek(0)
yield tar_file
@contextlib.contextmanager
d... | amedTemporaryFile(delete=False) as tar_file:
self.write_dummy_tar_content(n_bytes, tar_file)
tar_file.seek(0)
yield tar_file.name
def test_import_from_bytes(self):
with self.dummy_tar_stream(n_bytes=500) as f:
content = f.read()
# The generic import_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.