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 |
|---|---|---|---|---|---|---|---|---|
rochapps/django-google-oauth | google_oauth/models.py | Python | bsd-3-clause | 545 | 0 | from django.contrib.auth.models import User
from django.db import models
from oauth2client.django_orm import Flo | wField
from oauth2client.django_orm import CredentialsField
class Flow(models.Model):
"""
class to save flow objects in a multitreaded environment
"""
id = models.ForeignKey(User, primary_key=True)
flow = FlowField()
class Credentials(models.Model):
"""
saves user oauth credentia... | credential = CredentialsField()
|
dobladov/NickCage-TelegramBot | main.py | Python | mit | 1,853 | 0.001079 | #!/usr/bin/env python
# encoding: utf-8
import logging
import telegram
import random
import json
from giphypop import translate
with open('quotes.json') as data_file:
quotes = json.load(data_file)
quotes = quotes["quotes"]
def main():
logging.basicConfig(
format='%(asctime)s - %(name)s - %(level... | dMessage(chat_id=chat_id,
text="Nick is searching for an awesome gif.")
img = translate('nicolas cage')
bot.sendDocument(chat_id=chat_id,
document=img.fixed_height.url)
print "Enviar Gif " + img.fixed_height... | turn random.choice(quotes)
if __name__ == '__main__':
main()
|
skoslowski/gnuradio | gnuradio-runtime/examples/volk_benchmark/volk_plot.py | Python | gpl-3.0 | 6,303 | 0.003332 | #!/usr/bin/env python
from __future__ import division
from __future__ import unicode_literals
import sys, math
import argparse
from volk_test_funcs import (create_connection, list_tables, get_results,
helper, timeit, format_results)
try:
import matplotlib
import matplotlib.pyplot ... | lib.sourceforge.net/)\n")
sys.exit(1)
def main():
desc='Plot Volk performance results from a SQLite database. ' + \
'Run one of the volk tests first (e.g, volk_math.py)'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-D', '--database', ty | pe=str,
default='volk_results.db',
help='Database file to read data from [default: %(default)s]')
parser.add_argument('-E', '--errorbars',
action='store_true', default=False,
help='Show error bars (1 standard dev.)')
... |
prats226/python-amazon-product-api-0.2.8 | tests/conftest.py | Python | bsd-3-clause | 5,765 | 0.004163 | from ConfigParser import SafeConfigParser
import os.path
import pytest
import re
import textwrap
from amazonproduct import utils
def pytest_addoption(parser):
group = parser.getgroup('amazonproduct',
'custom options for testing python-amazon-product-api')
group._addoption('--locale', action='append', ... | f teardown(server):
server.stop()
return request.cached_setup(setup, teardown, 'module')
class DummyConfig (object):
"""
Dummy config to which to which you can add config files which in turn | will
be created on the file system as temporary files.
"""
_file_counter = 0
def __init__(self, tmpdir):
self.tmpdir = tmpdir
self.files = []
def add_file(self, content, path):
"""
Writes one temporary file.
"""
if not path:
path = 'con... |
SukkoPera/Arduino-Sensoria | python/server3.py | Python | gpl-3.0 | 1,544 | 0.036269 | #!/usr/bin/env python
import server
import time
from Sensoria.stereotypes.TimeControlData import TimeControlData
from Sensoria.stereotypes.InstantMessageData import InstantMessageData
class TemperatureSensor (server.TemperatureSensor):
def __init__ (self):
super (TemperatureSensor, self).__init__ ("HD", "Heater T... | initData.unmarshal ("PMO:000000001000000003222110 PTU:000000001000000003222110 PWE:000000001000000003222110 PTH:000000001000000003222110 PFR:000000001000000003222111 PSA:00 | 0000000322222222222211 PSU:000000000322222222222210")
ok, msg = self.write (initData)
print msg
assert ok
class HeaterSettings (server.ValueSetActuator):
def __init__ (self):
super (HeaterSettings, self).__init__ ("HS", "Heater Settings")
self.levels = [10, 18, 21]
@property
def values (self):
return s... |
openelections/openelections-core | openelex/us/md/datasource.py | Python | mit | 12,263 | 0.001957 | """
Standardize names of data files on Maryland State Board of Elections.
File-name convention on MD site (2004-2012):
general election
precinct: countyname_by_precinct_year_general.csv
state leg. district: state_leg_districts_year_general.csv
county: countyname_par... | tion):
if election['special']:
return 'special'
return election['race_type'].lower()
def _build_metadata(self, year, | elections):
year_int = int(year)
if year_int == 2002:
general, primary, special = self._races_by_type(elections)
meta = [
{
"generated_filename": "__".join((general['start_date'].replace('-',''), self.state, "general.txt")),
... |
littleghosty/forum | mysite/usercenter/views.py | Python | gpl-3.0 | 3,333 | 0.000627 | from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... | er.objects.create_user(username=username,
email=email, password=password)
user.is_active = False
user.save()
new_code = str(uuid.uuid4()).replace("-", "")
expire_time = datetime.datetime.now() + datetime.timedelta(days=2)
| code_record = ActivateCode(owner=user, code=new_code,
expire_timestamp=expire_time)
code_record.save()
activate_link = "http://%s%s" % (request.get_host(), reverse(
"user_activate", args=[new_code]))
sen... |
mozman/ezdxf | src/ezdxf/proxygraphic.py | Python | mit | 30,574 | 0.000229 | # Copyright (c) 2020-2021, Manfred Moitzi
# License: MIT License
from typing import (
TYPE_CHECKING,
Optional,
Iterable,
Tuple,
List,
Set,
Dict,
cast,
Sequence,
Any,
)
import sys
import struct
import math
from enum import IntEnum
from itertools import repeat
from ezdxf.lldxf impo... | unpack_from("<2L", self._buffer, offset=index)
try:
| name = ProxyGraphicTypes(type_).name
except ValueError:
name = f"UNKNOWN_TYPE_{type_}"
yield index, size, name
index += size
def virtual_entities(self) -> Iterable["DXFGraphic"]:
return self.__virtual_entities__()
def __virtual_entities__(self) -> ... |
pmclanahan/django-mozilla-product-details | product_details/settings_defaults.py | Python | bsd-3-clause | 335 | 0 | import logging
im | port os
# URL to clone product_details JSON files from.
# Include trailing slash.
PROD_DETAILS_URL = 'http://svn.mozilla.org/libs/product-details/json/'
# Target dir to drop JSON files into (must be writable)
PROD_DETAILS_DIR = os.path.join(os.path.dir | name(__file__), 'json')
# log level.
LOG_LEVEL = logging.INFO
|
Orange9000/Codewars | Solutions/beta/beta_answer_the_students_questions.py | Python | mit | 293 | 0.040956 | from collect | ions import Counter
def answer(q,inf):
s = Counter(q.split(' ')); r = [-1,-1]
for i,j in enumerate(inf):
check = sum(s.get(w,0) for w in j.split(' '))
if check != 0 and check > r[ | 1]: r = [i,check]
return None if r == [-1,-1] else inf[r[0]]
|
kvangent/PokeAlarm | PokeAlarm/Events/QuestEvent.py | Python | agpl-3.0 | 6,377 | 0 | # Standard Library Imports
from datetime import datetime
# 3rd Party Imports
# Local Imports
from PokeAlarm import Unknown
from . import BaseEvent
from PokeAlarm.Utils import get_gmaps_link, get_applemaps_link, \
get_waze_link, get_dist_as_str, get_base_types, get_type_emoji
from PokeAlarm.Utilities.QuestUtils impo... | ,
'type2_or_empty': Unknown.or_empty(type2),
'type2_emoji' | : Unknown.or_empty(get_type_emoji(
self.monster_types[1])),
'types': (
"{}/{}".format(type1, type2)
if Unknown.is_not(type2) else type1),
'types_emoji': (
"{}{}".format(
get_type_emoji(self.monster_types[0]),
... |
cpcloud/numba | numba/cuda/codegen.py | Python | bsd-2-clause | 12,947 | 0 | from llvmlite import binding as ll
from llvmlite import ir
from warnings import warn
from numba.core import config, serialize
from numba.core.codegen import Codegen, CodeLibrary
from numba.core.errors import NumbaInvalidConfigWarning
from .cudadrv import devices, driver, nvvm
import ctypes
import numpy as np
import o... | alize.ReduceMixin, CodeLibrary):
"""
The CUDACodeLibrary generates PTX, SASS, cubins for multiple different
compute capabilities. It also loads cubins to multiple | devices (via
get_cufunc), which may be of different compute capabilities.
"""
def __init__(self, codegen, name, entry_name=None, max_registers=None,
nvvm_options=None):
"""
codegen:
Codegen object.
name:
Name of the function in the source.
... |
dgjnpr/py-junos-eznc | lib/jnpr/junos/cfg/srx/shared_ab.py | Python | apache-2.0 | 2,925 | 0 | # debuggin
from lxml import etree
# 3rd-party modules
from lxml.builder import E
# module packages
from jnpr.junos.cfg | import Resource
from jnpr.junos import jxml as JXML
from jnpr.junos.cfg.srx.shared_ab_addr import SharedAddrBookAddr
from jnpr.junos.cfg.srx.shared_ab_set import SharedAddrBookSet
class SharedAddrBook(Resource):
"""
| [edit security address-book <name>]
Resource <name>
The address book name, string
Manages:
addr - SharedAddrBookAddr resources
set - SharedAddrBookAddrSet resources
"""
PROPERTIES = [
'description',
'$addrs', # read-only addresss
'$sets', # r... |
rackerlabs/django-DefectDojo | dojo/components/sql_group_concat.py | Python | bsd-3-clause | 1,326 | 0.004525 | from django.db.models import Aggregate, CharField
class Sql_GroupConcat(Aggregate):
function = 'GROUP_CONCAT'
allow_distinct = True
def __init__(self, expression, separator, distinct=False, ordering=None, **extra):
self.separator = separator
super(Sql_GroupConcat, self).__init__(e | xpression,
distinct='DISTINCT ' if distinct else '',
ordering=' ORDER BY %s' % ordering if ordering is not None else '',
separator=' SEPARATOR "%s"' % separator,
... | nnection):
return super().as_sql(compiler,
connection,
template='%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)',
separator=' SEPARATOR \'%s\'' % self.separator)
def as_sql(self, compiler, connecti... |
catkin/catkin_tools | tests/utils.py | Python | apache-2.0 | 4,974 | 0.000402 | import functools
import os
import re
import shutil
import subprocess
import sys
import tempfile
from io import StringIO
from subprocess import TimeoutExpired
from catkin_tools.commands.catkin import main as catkin_main
TESTS_DIR = os.path.dirname(__file__)
MOCK_DIR = os.path.join(TESTS_DIR, 'mock_resources')
def c... | gex is None:
return True
expected_regex = self.expected_regex
expected_regex = re.compile(expected_regex)
if not expected_regex.search(str(exc_value)):
raise AssertionError("'{0}' does | not match '{1}'".format(expected_regex.pattern, str(exc_value)))
return True
class redirected_stdio(object):
def __enter__(self):
self.original_stdout = sys.stdout
self.original_stderr = sys.stderr
self.out = StringIO()
self.err = StringIO()
sys.stdout = self.out
... |
Xavierwei/porsche_lemans | web/api/performance/util/pylot_win_recorder.py | Python | mit | 1,833 | 0.00491 | #!/usr/bin/env python
#
# Copyright (c) 2007-2009 Corey Goldberg (corey@goldb.org)
# License: GNU GPLv3
#
#
# This file is part of Pylot.
#
# 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
# ... | on installed
# http://sourceforge.net/projects/pywin32/
import sys
import threading
import pythoncom
from win32com.client import Dispatch, WithEvents
stop_event = threading.Event()
finished = False
class EventSink(object):
def OnBeforeNavigate2(self, *args):
print ' <case>'... | <method>POST</method>'
print ' <body><![CDATA[%s]]></body>' % post_data
if headers:
print ' <add_header>%s</add_header>' % headers
print " </case>"
stop_event.set()
def OnQuit(self):
global finished
finished = True
... |
jinankjain/zamboni | apps/zadmin/urls.py | Python | bsd-3-clause | 2,133 | 0.001406 | from django.conf.urls import include, patterns, url
from django.contrib import admin
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from addons.urls import ADDON_ID
| from amo.urlresolvers import reverse
from . import view | s
urlpatterns = patterns('',
# AMO stuff.
url('^$', views.index, name='zadmin.index'),
url('^models$', lambda r: redirect('admin:index'), name='zadmin.home'),
url('^addon/manage/%s/$' % ADDON_ID,
views.addon_manage, name='zadmin.addon_manage'),
url('^addon/recalc-hash/(?P<file_id>\d+)/', v... |
ecreall/lagendacommun | lac/views/lac_view_manager/questionnaire/improve.py | Python | agpl-3.0 | 3,097 | 0.000969 | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import deform
import colander
from pyramid.view import view_config
from dace.objectofcollaboration.principal.util import get_current
from dace.processinstance.core im... | 'Alert improve'
name = 'alertimprove'
template = 'lac:views/l | ac_view_manager/questionnaire/templates/improve_info.pt'
def update(self):
result = {}
values = {'context': self.context}
body = self.content(args=values, template=self.template)['body']
item = self.adapt_item(body, self.viewid)
result['coordinates'] = {self.coordinates: [it... |
MakarenaLabs/Orator-Google-App-Engine | orator/orm/relations/has_many_through.py | Python | mit | 5,076 | 0.000985 | # -*- coding: utf-8 -*-
from ...query.expression import QueryExpression
from .relation import Relation
class HasManyThrough(Relation):
_first_key = None
_second_key = None
_far_parent = None
def __init__(self, query, far_parent, parent, first_key, second_key):
"""
:param query: A Bu... | t.get_table()
self._query.where_in('%s.%s' % (t | able, self._first_key), self.get_keys(models))
def init_relation(self, models, relation):
"""
Initialize the relation on a set of models.
:type models: list
:type relation: str
"""
for model in models:
model.set_relation(relation, self._related.new_coll... |
IlyaSergeev/taxi_service | first_app/wsgi.py | Python | mit | 393 | 0.002545 | """
WSGI config for first_app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJ | ANGO_SETTINGS_MODULE", "first_app.settings")
fr | om django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
chen0031/rekall | rekall-core/rekall/plugins/collectors/darwin/sessions.py | Python | gpl-2.0 | 7,561 | 0.000132 | # Rekall Memory Forensics
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 v... | from the memory objects."""
_name = "sessions"
outputs = ["Session",
"User",
| "Struct/type=tty",
"Struct/type=proc"]
collect_args = dict(sessions="Struct/type is 'session'")
def collect(self, hint, sessions):
for entity in sessions:
session = entity["Struct/base"]
# Have to sanitize the usernames to prevent issues when comparing
... |
NeCTAR-RC/designate | designate/api/v2/controllers/limits.py | Python | apache-2.0 | 1,347 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# 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/L... | er the License.
import pecan
from designate.central import rpcapi as central_rpcapi
from designate.openstack.common import log as logging
from designate.api.v2.controllers import rest
from designate.api.v2.views import limits as limits_view
LOG = logging.getLogger(__name__)
central_api = central_rpcapi.CentralAPI()
... | imits_view.LimitsView()
@pecan.expose(template='json:', content_type='application/json')
def get_all(self):
request = pecan.request
context = pecan.request.environ['context']
absolute_limits = central_api.get_absolute_limits(context)
return self._view.show(context, request, ab... |
akuks/pretix | src/pretix/plugins/banktransfer/payment.py | Python | apache-2.0 | 2,341 | 0.002136 | import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment | import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
identifier = 'banktransfer'
verbose_name = _('Bank transfer')
@property
def settings_form_fields(self):
return OrderedDict(
list(super().settings_form_fields.items()) + [
('bank_details',
... | rms.CharField(
widget=forms.Textarea,
label=_('Bank account details'),
))
]
)
def payment_form_render(self, request) -> str:
template = get_template('pretixplugins/banktransfer/checkout_payment_form.html')
ctx = {'reques... |
timbotron/ICLS | framework.py | Python | gpl-3.0 | 2,817 | 0.048988 | # This file is part of ICLS.
#
# ICLS 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.
#
# ICLS is distributed in the hope that it will ... | for more details.
#
# You should have received a copy of the GNU General Public License
# along with ICLS. If not, see <http://www.gnu.org/licenses/>.
import xml.dom.minidom
from time import strftime, strptime
from sys import exit
from textwrap import wrap
from os import path
def colorize(the_color='blue',entry='',... | \n'
else:
new_line=''
return_me='\033[1;'+str(color[the_color])+'m'+entry+'\033[1;m'+new_line
return return_me
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
# Only if error is one that halts things,... |
lukasklein/pruefungsplan | pruefungsplan/notifier/views.py | Python | bsd-3-clause | 3,148 | 0 | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.generic.edit import FormView
from .forms import SignUpForm, ExamSignUpForm
from .models import Notification
from .utils import send_email, send_sms
class ExamSignUpView(FormView):
kind =... | s_code = request.GET.get('sms_code')
if sms_code:
if sms_code == notification.sms_code:
notification.sms_verified = T | rue
notification.save()
else:
sms_error = True
mail_error = False
mail_code = request.GET.get('mail_code')
if mail_code:
if mail_code == notification.email_token:
notification.email_verified = True
notification.save()
else:
... |
djedproject/djed.static | djed/static/__init__.py | Python | isc | 5,214 | 0 | import logging
import os
from collections import namedtuple
from zope.interface import Interface
from bowerstatic import (
Bower,
InjectorTween,
PublisherTween,
)
from pyramid.interfaces import IApplicationCreated
from pyramid.path import AssetResolver
from pyramid.exceptions import ConfigurationError
lo... | tory)
registry.registerUtility(info, IBowerComponents, name=name)
config.action(discr, register)
def add_bower_component(config, path, components_name=None):
"""
"""
registry = config.registry
resolver = AssetResolver()
directory = resolver.resolve(path).abspath()
if not os.path.... | )
bower = get_bower(registry)
if components_name is None:
components_name = bower.components_name
discr = ('djed:static', directory, components_name)
def register():
info = BowerComponentInfo(directory, components_name)
registry.registerUtility(info, IBowerComponent, name... |
zaqwes8811/matlab_ext | measurement/mc-assistant/projects/py_hw_models/trash/testModelADDAC.py | Python | apache-2.0 | 5,245 | 0.061971 | #-*- coding: utf-8 -*-
import unittest
import ModelADDAC as adda
import api_convertors.type_conv as tc
''' Просто заглушка '''
def printRpt( value, valueDisplacemented, valueScaled, valueCode, Kda ):
#print '\nvalueDisplacemented : '+str(valueDisplacemented)
pass
''' Класс тестов '''
class TestCaseModelADDAC(unitt... | ._valueDict['Vmax'] = Vmax
code, Kda = adda.modelADC( self._valueDict, printRpt, adda.calcZeroDisplacmentY )
# Проверка кода числ
self.assertEqual( tc.byte4strhex( code ), '0x00FE' )
# Проверка множителя
''' Проверка ЦАП '''
def testDAC( self ):
# Constants and coeff.
R1 = 5.11 # Om
R2 = 10.0 ... | 8.0 # mV/A
Udig = 322 # V ue
# проверяем
self._valueDict[ 'value' ] = 0
self._valueDict['displacement'] = 500
self._valueDict['converter' ] = Kiu
self._valueDict['scale'] = Splitter
self._valueDict['capacity'] = capacity
self._valueDict['Vmax'] = Vmax
# сперва получаем поправочный код
code,... |
shinpeimuraoka/ryu | ryu/__init__.py | Python | apache-2.0 | 680 | 0 | # Copyright (C) 2012 Nippon Telegraph | and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
version_info = (4, 12)
version = '.'.join(map(str, version_info))
|
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/urbansim/gridcell/is_near_arterial.py | Python | gpl-2.0 | 2,343 | 0.012804 |
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants
from numpy imp... | 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]),
},
'urbansim_constant':{
'cell_ | size': array([150]),
'near_arterial_threshold': array([100]),
'units': array(['meters']),
}
}
)
should_be = array( [True, True, True, False, False, False] )
tester.test_is_equal_for_variable_defined_by_this_modu... |
stefanv/selective-inference | selection/algorithms/tests/test_forward_step.py | Python | bsd-3-clause | 8,482 | 0.00896 | import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from selection.algorithms.lasso import instance
from selection.algorithms.forward_step import forward_stepwise, info_crit_stop, sequential, data_carving_IC
def test_FS(k=10):
n, p = 100, 200
X = np.random.standard_normal((n,p)) + ... | _pivots(3, saturated=False, which_var=[FS.variables[2]], burnin=5000, ndraw=5000)
print FS.model_quadratic(3)
def test_FS_unknown(k=10):
n, p = 100, 200
| X = np.random.standard_normal((n,p)) + 0.4 * np.random.standard_normal(n)[:,None]
X /= (X.std(0)[None,:] * np.sqrt(n))
Y = np.random.standard_normal(100) * 0.5
FS = forward_stepwise(X, Y)
for i in range(k):
FS.next()
print 'first %s variables selected' % k, FS.variables
pri... |
danielvdao/facebookMacBot | venv/lib/python2.7/site-packages/sleekxmpp/plugins/xep_0196/stanza.py | Python | mit | 536 | 0.003731 | """
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. S | tout
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.xmlstream import ElementBase, ET
class UserGaming(ElementBase | ):
name = 'gaming'
namespace = 'urn:xmpp:gaming:0'
plugin_attrib = 'gaming'
interfaces = set(['character_name', 'character_profile', 'name',
'level', 'server_address', 'server_name', 'uri'])
sub_interfaces = interfaces
|
LauritzThaulow/fakelargefile | fakelargefile/segment/literal.py | Python | agpl-3.0 | 2,718 | 0.001104 | '''
A segment which is a literal string
A FakeLargeFile composed entirely of LiteralSegments is not fake, but may
still be more useful than a plain old file.
'''
COPYING = """\
Copyright 2014 Lauritz Vesteraas Thaulow
This file is part of the FakeLargeFile python package.
FakeLargeFile is free software:... | gment
class LiteralSegment(AbstractSegment):
"""
A segment containing exactly a given string.
"""
def __init__(self, s | tart, string):
"""
Initialize a LiteralSegment instance.
:param int start: The start pos of the segment.
:param str string: The string this segment should contain.
"""
start = parse_unit(start)
super(LiteralSegment, self).__init__(start, start + len(string))
... |
aroraenterprise/projecteos | backend/api/v1/fundamentals/sage_methods.py | Python | mit | 212 | 0.009434 | """
Project: flask-rest
Author: Saj Arora
Descri | ption: All of the rest | methods...
"""
class SageMethod:
GET = 'get'
POST = 'post'
DELETE = 'delete'
PUT = 'put'
ALL = [GET, POST, DELETE, PUT] |
cflq3/getcms | plugins/mongodb_dbs.py | Python | mit | 138 | 0.007246 | #!/usr/bin/env py | thon
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "Replica set | status")
|
zapcoop/vertex | vertex_api/service/filters/note.py | Python | agpl-3.0 | 147 | 0 | from vertex.filt | ers import IdListFilterSet
from ..m | odels import Note
class NoteFilterSet(IdListFilterSet):
class Meta:
model = Note
|
canvasnetworks/canvas | website/canvas/search.py | Python | bsd-3-clause | 1,105 | 0.01086 | import threading
import solr
from django.conf import settings
class SolrConnection(threading.local):
_connection = None
def __init__(self, core):
threading.local.__init__(core)
self.core = core
|
@property
def connection(self):
if self._connection:
return self._connection
else:
return solr.Solr(settings.SOLR_HOST + '/' + self.core)
valid_core_names = ['comment', 'group']
local = {}
def get_local(core):
assert core in valid_core_names
if not core in l... | (char if char not in escapes else '\\' + char)
for char
in input
)
def query(core, *args, **kwargs):
return get_local(core).connection.select(*args, **kwargs)
def add(core, *args, **kwargs):
return get_local(core).connection.add(*args, **kwargs)
def update(core, doc, *args, **kw... |
open-power/op-test-framework | testcases/OpTestPCI.py | Python | apache-2.0 | 36,744 | 0.001116 | #!/usr/bin/env python3
# IBM_PROLOG_BEGIN_TAG
# This is an automatically generated prolog.
#
# $Source: op-test-framework/testcases/OpTestPCI.py $
#
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2015,2017
# [+] International Business Machines Corp.
#
#
# Licensed under the Apache License,... | Host.get_lspci
Case E --run testcases.OpTestPCI.PCIHostSoftboot.get_lspci
Case F --run testcases.OpTestPCI.PCIHostHardboot.get_lspci
'''
lspci_data = self.c.run_command("lspci -mm -n")
return lspci_data
def check_commands(self):
'''
Checks for general capabil... | ases.OpTestPCI.PCISkirootHardboot.check_commands
Case D --run testcases.OpTestPCI.PCIHost.check_commands
Case E --run testcases.OpTestPCI.PCIHostSoftboot.check_commands
Case F --run testcases.OpTestPCI.PCIHostHardboot.check_commands
'''
list_pci_devices_commands = ["lspci -mm -n... |
jordanemedlock/psychtruths | temboo/core/Library/KhanAcademy/Users/GetExerciseFollowUp.py | Python | apache-2.0 | 4,590 | 0.0061 | # -*- coding: utf-8 -*-
###############################################################################
#
# | GetExerciseFollowUp
# Retrieves user data about all excercises which have the specified excercise as a prerequisite.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except | in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either e... |
danbarrese/pwdgen | pwdgen.py | Python | gpl-3.0 | 4,586 | 0.002617 | # RANDOM PASSWORD GENERATOR
# Author: Dan Barrese (danbarrese.com)
# Version: 1.01
# Description: Yep. This is my first Python script.
# Skills exemplified in this script:
# * Random number generation
# * Command line interface
# * List comprehension
# * Loops
#
# Update History:
# 2013.12.25 [DRB][1.0] Initial imp... | parser.add_argument('--no-alpha-lower', dest='do_alpha_lower', ac | tion='store_false',
help='do NOT include alphas [a-z]')
parser.set_defaults(do_alpha_lower=True)
parser.add_argument('--alpha-upper', dest='do_alpha_upper', action='store_true',
help='include numbers [A-Z]')
parser.add_argument('--no-alpha-upper', dest='do_alpha_upper', action='s... |
eiginn/passpie | setup.py | Python | mit | 2,730 | 0 | #!/usr/bin/env python
import io
import os
import sys
try:
from setuptools import setup, Command, find_packages
except ImportError:
from distutils.core import setup, Command, find_packages
__version__ = "1.4.3"
with io.open('README.rst', encoding='utf-8') as readme_file:
long_description = readme_file.r... | gs")
os.system("git push")
sys.exit()
requirements = [
'click==6.2',
'PyYAML==3.11',
'tabulate==0.7.5',
'tinydb==3.1.2',
'rstr==2.2.3',
]
class PyTest(Command):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
self.pyte... | ass
def run(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
class PyTestCoverage(PyTest):
def initialize_options(self):
self.pytest_args = [
"-v", "tests",
"--cov", 'passpie',
"--cov-config", ".coveragerc",
... |
matk86/pymatgen | pymatgen/io/abinit/launcher.py | Python | mit | 47,862 | 0.003134 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""Tools for the submission of Tasks."""
from __future__ import unicode_literals, division, print_function
import os
import time
import ruamel.yaml as yaml
import pickle
from collections import deque
from date... | tinue
for task in tasks:
fired = task.start()
if fired:
launched.append(task)
num_launched += 1
if num_launched >= max_nlaunch > 0:
logger.info('num_launched >= max_nlaunch, going | back to sleep')
do_exit = True
break
# Update the database.
self.flow.pickle_dump()
return num_launched
def fetch_tasks_to_run(self):
"""
Return the list of tasks that can be submitted.
Empty list if no task has been found.
... |
youtube/cobalt | third_party/llvm-project/clang-tools-extra/test/clang-tidy/check_clang_tidy.py | Python | bsd-3-clause | 5,589 | 0.013777 | #!/usr/bin/env python
#
#===- check_clang_tidy.py - ClangTidy Test Helper ------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===--------------------------------------... | ort re
import subprocess
import sys
def write_file(file_name, text):
with open(file_name, 'w') as f:
f.write(text)
f.truncate()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-expect-clang-tidy-error', action='store_true')
parser.add_argument('-resource-dir')
parser.add_argumen... | dd_argument('temp_file_name')
args, extra_args = parser.parse_known_args()
resource_dir = args.resource_dir
assume_file_name = args.assume_filename
input_file_name = args.input_file_name
check_name = args.check_name
temp_file_name = args.temp_file_name
expect_clang_tidy_error = args.expect_clang_tidy_er... |
Kankroc/pdf2image | pdf2image/pdf2image.py | Python | mit | 8,412 | 0.004042 | """
pdf2image is a light wrapper for the poppler-utils tools that can convert your
PDFs into Pillow images.
"""
import os
import platform
import re
import uuid
import tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buff... | = _page_count(pdf_path, userpw, poppler_path=poppler_path)
# We start by getting the output format, the buffer processing function and if we need pdftocairo
parsed_fmt, parse_buffer_func, use_pdfcairo_format = _pa | rse_format(fmt)
# We use pdftocairo is the format requires it OR we need a transparent output
use_pdfcairo = use_pdfcairo_format or (transparent and parsed_fmt in TRANSPARENT_FILE_TYPES)
if thread_count < 1:
thread_count = 1
if first_page is None:
first_page = 1
if last_page is N... |
samdsmx/omegaup | bin/karel_mdo_convert.py | Python | bsd-3-clause | 4,150 | 0.024096 | #!/usr/bin/python3
import struct
import sys
if len(sys.argv) == 1:
print("python karel_mdo_convert.py mundo.mdo")
sys.exit(1)
f = open(sys.argv[1], "rb")
data = f.read()
f.close()
worldname = sys.argv[1]
if '/' in worldname:
worldname = worldname[worldname.rfind('/')+1:]
if '.' in worldname:
worldname = worldn... | ruct.unpack("HHH", kec[i:i+6]) for i in range(0, len(kec), 6)]
maxlines = kec[0][1] if kec[0][0] else 10000000
maxmove = kec[1][1] if kec[1][0] else False
maxturnleft = kec[2][1] if kec[2][0] else False
maxpickbeeper = kec[3][1] if kec[3][0] else False
maxputbeeper = kec[4][1] if kec[4][0] else False
maxkarelbeepers =... | if kec[5][0] else False
maxbeepers = kec[6][1] if kec[6][0] else False
endposition = kec[7][1:] if kec[7][0] else False
endorientation = ["NORTE", "ESTE", "SUR", "OESTE"][kec[8][1]] if kec[8][0] else False
dumpcount = kec[9][1] if kec[9][0] else 0
def formatbuzzers(b):
if b == 65535:
return "INFINITO"
else:
ret... |
Kjir/papyon | papyon/gnet/io/tcp.py | Python | gpl-2.0 | 1,708 | 0.001172 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Ole André Vadla Ravnås <oleavr@gmail.com>
# Copyright (C) 2006-2007 Ali Sabil <ali.sabil@gmail.com>
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Gene... | ndation, Inc., 51 Franklin St, Fifth Floor, Boston, | MA 02110-1301 USA
#
from papyon.gnet.constants import *
from papyon.gnet.proxy.proxyfiable import ProxyfiableClient
from sock import SocketClient
import gobject
__all__ = ['TCPClient']
class TCPClient(SocketClient, ProxyfiableClient):
"""Asynchronous TCP client class.
@sort: __init__, open, send, clo... |
pkerpedjiev/forna | test/restserver_test.py | Python | apache-2.0 | 1,136 | 0.014085 | import sys
import unittest
import restserver
import json
from flask import jsonify
class RestServerTest(unittest.TestCase):
def setUp(self):
self.app = restserver.create_app(static=True).test_client()
def tearDown(self):
pass
def test_struct_graph(self):
rv = self.app.post('/stru... | assertEqual(rv.data, "Missing a json in the request")
self.assertEqual(rv.status_code, 400)
data_in = json.dumps({'seq':'ACCCGG', 'struct':'((..))'})
rv = self.app.post('/struct_graph',
data=data_in,
content_type='application... | ost('/struct_graph',
data=data_in,
content_type='application/json')
self.assertEqual(rv.status_code, 400)
|
bbirand/python-driver | benchmarks/base.py | Python | apache-2.0 | 8,795 | 0.001478 | # Copyright 2013-2015 DataStax, 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 writi... | e=TABLE))
values = ('key', 'a', 'b')
per_thread = options.num_ops // options.threads
threads = []
log.debug("Beginning inserts...")
start = time.time()
try:
for i in range(options.threads):
thread = thread_class(
| i, session, query, values, per_thread,
cluster.protocol_version, options.profile)
thread.daemon = True
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
while thread.is_al... |
eLRuLL/scrapy | scrapy/extensions/closespider.py | Python | bsd-3-clause | 2,631 | 0.0019 | """CloseSpider is an extension that forces spiders to be closed after certain
conditions are met.
See documentation in docs/topics/extensions.rst
"""
from collections import defaultdict
from twisted.internet import reactor
from scrapy import signals
from scrapy.exceptions import NotConfigured
class CloseSpider(ob... |
self.crawler.engine.close_spider(spider, 'closespider_pagecount')
def spider_opened(self, spider):
self.task = reactor.callLater(self.close_on['timeout'],
self.crawler.engine.close_spider, spider,
reason='closespider_t... | aped(self, item, spider):
self.counter['itemcount'] += 1
if self.counter['itemcount'] == self.close_on['itemcount']:
self.crawler.engine.close_spider(spider, 'closespider_itemcount')
def spider_closed(self, spider):
task = getattr(self, 'task', False)
if task and task.ac... |
FlorianLudwig/rueckenwind | test/test_scope.py | Python | apache-2.0 | 7,840 | 0.000128 | from __future__ import absolute_import, division, print_function, with_statement
import pytest
import sys
from tornado import concurrent
import tornado.gen
import tornado.testing
import rw.scope
# def test_low_level_api():
# scope = rw.scope.Scope()
# current_user = object()
#
# def get_current_user():... | bscope('my_sub_scope')
sub2 = scope2.subscope('my_sub_scope')
sub1['value_1'] = 1
sub1['shared'] = 1
sub2['value_2'] = 2
sub2['shared'] = 2
@rw.scope.inject
def ge | t_sub_scope(my_sub_scope):
return my_sub_scope
@rw.scope.inject
def get_sub_scope_var(var, my_sub_scope):
return my_sub_scope[var]
def checks_inside_scope1():
assert rw.scope.get('my_sub_scope') == get_sub_scope()
assert rw.scope.get('my_sub_scope')['value_1'] == 1
... |
soerendip42/rdkit | Contrib/M_Kossner/Frames.py | Python | bsd-3-clause | 6,124 | 0.033801 | #!/usr/bin/python
# encoding: utf-8
# Jan 2011 (markus kossner) Cleaned up the code, added some documentation
# somwhere around Aug 2008 (markus kossner) created
#
# This script extracts the molecular framework for a database of molecules.
# You can use two modes (hard coded):
# - Scaff: The molecular fr... | m = GetFrame(mol)
cansmiles = Chem.MolToSmiles(m, isomericSmiles=True)
if FrameDict.has_key(cansmiles):
FrameDict[cansmiles].append(mol)
else:
FrameDict[cansmiles]=[mol,]
counter=0
w=open('frames.smi','w')
for key,item in FrameDict.items():
counter+=1
d=Chem.SDWriter(str(c | ounter)+'.sdf')
for i in item:
i.SetProp('Scaffold',key)
i.SetProp('Cluster',str(counter))
d.write(i)
print(key,len(item))
w.write(key+'\t'+str(len(item))+'\n')
w.close
print('number of Clusters: %d' %(counter))
|
haggi/OpenMaya | src/common/python/Renderer/textureCreator.py | Python | mit | 17,166 | 0.005942 |
import path
import logging
import shutil
import os
log = logging
START_ID = "automatically created attributes start"
END_ID = "automatically created attributes end"
START_STATIC_ID = "automatically created static attributes start"
END_STATIC_ID = "automatically created static attributes end"
START_NODE_ID = 0x0011E... | ult
self.data = data
print "Attribute", self.name, self.type, self.displayName, self.default, self.data
print "make func", "make{0}".format(self.type.capitalize())
def getDefForDefFile(self):
return "inAtt:{0}:{1}".format(self.name, self.type)
def getDefinition(self):
... | self.addControl("{0}", label="{1}")'.format(self.name, self.displayName)
def getStaticDefinition(self):
return "MObject\tTextureBase::{0};".format(self.name)
def getImplementation(self):
methodName = "make" + self.type.capitalize()
print "Calling", methodName, "for", self.name
... |
RDCEP/psims | pysims/models/apsim75.py | Python | agpl-3.0 | 2,004 | 0.003992 | import glob
import os
import shutil
import sys
import tarfile
import traceback
from model import Model
from subprocess import Popen, PIPE
class Apsim75(Model):
def run(self, latidx, lonidx):
try:
| apsim_bin = self.config.get('executable')
# The apsim 'execu | table' is a gzipped tarball that needs to be extracted into the current working directory
tar = tarfile.open(apsim_bin)
tar.extractall()
tar.close()
model_dir = 'Model'
for xml_file in glob.glob('*.xml'):
if os.path.basename(xml_file) == 'Aps... |
mishbahr/djangocms-fbcomments | aldryn_config.py | Python | bsd-3-clause | 819 | 0.003663 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from aldryn_client import forms
class Form(forms.BaseForm):
plugin_module = forms.CharField('Plugin module name', initial='Generic')
plugin_name = forms.CharField('Plugin name', initial='Facebook Comments')
plugin_template = forms.CharField(... | lf, data, settings):
setti | ngs['DJANGOCMS_FBCOMMENTS_PLUGIN_MODULE'] = data['plugin_module']
settings['DJANGOCMS_FBCOMMENTS_PLUGIN_NAME'] = data['plugin_name']
settings['DJANGOCMS_FBCOMMENTS_PLUGIN_TEMPLATE'] = data['plugin_template']
settings['DJANGOCMS_FBCOMMENTS_APP_ID'] = data['app_id']
return settings
|
jamespcole/home-assistant | homeassistant/components/knx/climate.py | Python | apache-2.0 | 11,048 | 0 | """Support for KNX/IP climate devices."""
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice
from homeassistant.components.climate.const import (
STATE_DRY, STATE_ECO, STATE_FAN_ONLY, STATE_HEAT, STATE_IDLE, STATE_MANUAL,
SUPPORT_ON_OFF, SUPPORT_OPERATION_MODE,... | et(
CONF_CONTROLLER_STATUS_STATE_ADDRESS),
group_address_cont | roller_mode=config.get(
CONF_CONTROLLER_MODE_ADDRESS),
group_address_controller_mode_state=config.get(
CONF_CONTROLLER_MODE_STATE_ADDRESS),
group_address_operation_mode_protection=config.get(
CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS),
group_address_operati... |
akshayaurora/kivy | kivy/uix/splitter.py | Python | mit | 13,228 | 0.000076 | '''Splitter
======
.. versionadded:: 1.5.0
.. image:: images/splitter.jpg
:align: right
The :class:`Splitter` is a widget that helps you re-size its child
widget/layout by letting you re-size it via dragging the boundary or
double tapping the boundary. This widget is similar to the
:class:`~kivy.uix.scrollview.S... | e information about how
to use it.
:attr:`border` is a :class:`~kivy.properties.ListProperty` and
defaults to (4, 4, 4, 4).
'''
strip_cls = ObjectProperty(SplitterStrip)
'''Specifies the class of the resize Strip.
:attr:`strip_cls` is an :class:`kivy.properties.ObjectProperty` and
| defaults to :class:`~kivy.uix.splitter.SplitterStrip`, which is of type
:class:`~kivy.uix.button.Button`.
.. versionchanged:: 1.8.0
If you set a string, the :class:`~kivy.factory.Factory` will be used to
resolve the class.
'''
sizable_from = OptionProperty('left', options=(
... |
hovo1990/deviser | generator/legacy/createCMakeFiles.py | Python | lgpl-2.1 | 16,329 | 0.020454 | #!/usr/bin/env python
#
# @file createCMakeFiles.py
# @brief create the CMake files
# @author Frank Bergmann
# @author Sarah Keating
#
# <!--------------------------------------------------------------------------
#
# Copyright (c) 2013-2014 by the California Institute of Technology
# (California, USA), the Euro... | "bindings/perl/local-downcast-packages-{0}.cpp"\n'. | format(name))
fileOut.write(' "bindings/perl/local-downcast-namespaces-{0}.cpp"\n'.format(name))
fileOut.write(' "bindings/perl/local-downcast-plugins-{0}.cpp"\n\n'.format(name))
fileOut.write(' # python bindings\n')
fileOut.write(' "bindings/python/local-downcast-extension-{0}.cpp"\n'.format(name))
fileOut.wr... |
mic4ael/indico | indico/testing/fixtures/util.py | Python | mit | 2,040 | 0.00049 | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import inspect
from datetime import datetime
import freezegun
import pytest
from sqlalchemy import DateTi... | rator.__call__
def FunctionGenerator_call(self, *args, **kwargs):
if self._FunctionGenerator__names == ['now']:
return cast(datetime.now().isoformat(), DateTime)
return orig_call(self, *args, **kwargs)
monkeypatch.setattr(_FunctionGenerator, '__call__', FunctionGenerator_call)
... |
freezer.start()
freezers.append(freezer)
yield _freeze_time
for freezer in reversed(freezers):
freezer.stop()
|
nevtum/Echopoint | tests/testrunner.py | Python | apache-2.0 | 569 | 0.005272 | from tests.subscriptions import Subscription_tests
from tests.messaging import Event_publisher_tests
from tests.callbacks import Callback | _tests
from tests.shortcut_subscriptions import Decorator_tests
import unittest
import logging
def configure_logger():
handler = logging.FileHandler('log.txt')
formatter = logging.Formatter("%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s")
handler.setFormatter(formatter)
logger = logging.ge... | configure_logger()
unittest.main()
|
BiRG/Omics-Dashboard | modules/sbin/batch_parse_txtxy.py | Python | mit | 457 | 0 | #!/usr/bin/env python3
import sys
import text_parsers as tp
import os
infilenames = sys.argv[1:len(sys.argv)-1]
nameprefix = sys.argv[len(sys.argv)-1]
for infilename in infilenames:
outfilename = f'{os.environ[" | HOME"]}/{os.path.basename(infilename)}.h5'
data = tp.parse_txt_xy(infilename)
data['metadata']['name'] = f'{nameprefix}: {os.path.basename(infilename)}'
tp.save_sample_file(outfilenam | e, data['data'], data['metadata'])
sys.exit(0)
|
utiasASRL/batch-informed-trees | tests/control/test_control.py | Python | bsd-3-clause | 11,947 | 0.002595 | #!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... | 2
def project(self, state, projection):
projection[0] = state[0]
| projection[1] = state[1]
class MyStatePropagator(oc.StatePropagator):
def propagate(self, state, control, duration, result):
result[0] = state[0] + duration*control[0]
result[1] = state[1] + duration*control[1]
result[2] = control[0]
result[3] = control[1]
class TestPlanner(object)... |
eayunstack/fuel-ostf | fuel_health/tests/ha/test_mysql_replication.py | Python | apache-2.0 | 6,751 | 0 | # Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Target Service: HA mysql
Scenario:
1. Check that mysql is running on all controller or database no | des.
2. Create database on one node.
3. Create table in created database
4. Insert data to the created table
5. Get replicated data from each database node.
6. Verify that replicated data in the same from each database
7. Drop created database
... |
deonwu/robotframework-debuger | src/rdb/interface/base.py | Python | gpl-2.0 | 3,484 | 0.01062 | import logging
class BaseDebugInterface(object):
def __init__(self, debuger):
self.robotDebuger = debuger
self.debugCtx = debuger.debugCtx
self.logger = logging.getLogger("rbt.int")
self.bp_id = 0
def start(self, settings):
"""start debug interface."""
... |
self.robotDebuger.add_telnet_monitor(monitor)
def add_debug_listener(self, l):
self.debugCtx.add_listener(l)
def remove_debug_listener(self, l):
self.debugCtx.remove_listener(l)
class Listener:
def __init__(self):
pass
def pause(self, breakpoint):... | pass
def end_keyword(self, keyword):
pass |
aakashrana1995/svnit-tnp | tnp/consent/migrations/0014_auto_20170325_1723.py | Python | mit | 523 | 0 | # -*- coding: utf-8 -*-
# Generated | by Django 1.10.5 on 2017-03-25 11:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consent', '0013_auto_20170217_1606'),
]
operations = [
migrations.AlterField(
model_name='education... | ),
]
|
mcs07/ChemDataExtractor | chemdataextractor/doc/table.py | Python | mit | 13,370 | 0.003141 | # -*- coding: utf-8 -*-
"""
chemdataextractor.doc.table
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Table document elements.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unico | de_liter | als
import logging
from collections import defaultdict
from ..model import Compound, ModelList
from ..parse.table import CompoundHeadingParser, CompoundCellParser, UvvisAbsHeadingParser, UvvisAbsCellParser, \
QuantumYieldHeadingParser, QuantumYieldCellParser, UvvisEmiHeadingParser, UvvisEmiCellParser, ExtinctionCe... |
BowdoinOrient/bongo | bongo/apps/api/serializers/event.py | Python | mit | 200 | 0 | from | bongo.apps.bongo import models
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = models.Event
fields = ('i | d', )
|
nhlx5haze/Kaggle_WestNileVirus | src/predict.py | Python | bsd-3-clause | 5,983 | 0.01755 | from __future__ import print_function
import numpy as np
import datetime
import csv
import pickle
import sys
species_map = {'CULEX RESTUANS' : "100000",
'CULEX TERRITANS' : "010000",
'CULEX PIPIENS' : "001000",
'CULEX PIPIENS/RESTUANS' : "101000",
'CULEX ER... | , axis=0)
for i in range(count):
X[np.isnan(X[:,i]), i] = mean[i]
if std is None:
std = np.std(X, axis=0)
for i in range( | count):
X[:,i] = (X[:,i] - mean[i]) / std[i]
return mean, std
def scaled_count(record):
SCALE = 9.0
if "NumMosquitos" not in record:
# This is test data
return 1
return int(np.ceil(record["NumMosquitos"] / SCALE))
def assemble_X(base, weather):
X = []
for b... |
stxnext-kindergarten/presence-analyzer-kjagodzinski | src/presence_analyzer/script.py | Python | mit | 3,487 | 0 | # -*- coding: utf-8 -*-
"""Startup utilities"""
# pylint:skip-file
import os
import sys
from functools import partial
import paste.script.command
import werkzeug.script
etc = partial(os.path.join, 'parts', 'etc')
DEPLOY_INI = etc('deploy.ini')
DEPLOY_CFG = etc('deploy.cfg')
DEBUG_INI = etc('debug.ini')
DEBUG_CFG =... | edApplication(app, evalex=True)
# bin/flask | -ctl shell
def make_shell():
"""
Interactive Flask Shell.
"""
from flask import request
app = make_app()
http = app.test_client()
reqctx = app.test_request_context
return locals()
def _serve(action, debug=False, dry_run=False):
"""
Build paster command from 'action' and 'debug'... |
CMSS-BCRDB/RDS | trove/guestagent/strategies/restore/mysql_impl.py | Python | apache-2.0 | 13,702 | 0.000146 | # Copyright 2013 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-2... | -skip-grant-tables"
" --skip-networking"
" --init-file='%s'"
" --log-error='%s'" %
(init_file.name, err_log_file.name)
)
try:
i = child.expect(['Start... | meout launching mysqld_safe"))
finally:
# There is a race condition here where we kill mysqld before
# the init file been executed. We need to ensure mysqld is up.
#
# mysqld_safe will start even if init-file statement(s) fail.
# We therefore also chec... |
ecorreig/automatic_pattern | tests/main_tests.py | Python | gpl-2.0 | 32,788 | 0.001921 | __author__ = 'dracks'
import unittest
import models
from Api.Manager import DataManager
import main
import dateutil.parser
import datetime
import models_tests
import mocks
class DayWeekTests(unittest.TestCase):
def test_sunday(self):
day = dateutil.parser.parse("2015-09-27")
self.assertEqual(main... | for i in range(0, 10):
list_percentiles.append(models_tests.generate_percentile(
pk=i, seed=5, type=i * 2, | course=i * 3, trimester=trimester
))
self.percentiles = list_percentiles
activity1 = models.Activity()
activity1.sort = 10
activity1.words_minute = 10
activity2 = models.Activity()
activity2.sort = 20
activity2.words_minute = 19
session.list_a... |
elego/tkobr-addons | unported/tko_purchase_show_only_supplier_products/__init__.py | Python | agpl-3.0 | 1,094 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004- | 2010 Tiny SPRL (<http://tiny.be>).
#
# ThinkOpen Solutions Brasil
# Copyright (C) Thinkopen Solutions <http://www.tkobr.com>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero | General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE... |
fergalmoran/dss | spa/migrations/0021_auto__add_activitylike.py | Python | bsd-2-clause | 16,207 | 0.007836 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ActivityLike'
#db.delete_table(u'spa_activitylike')
db.create_table(u'spa_activityli... | "'chat_messages'", 'null': 'True', 'to': "orm['spa.UserProfile']"})
},
'spa.comment': {
'Meta': {'object_name': 'Comment'},
'comment': ('django.db.models.fields.CharField', [], {'max_length': '1024'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'a... | d.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': "orm['spa.Mix']"}),
'time_index': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
'spa.event': {
... |
scorphus/authomatic | tests/functional_tests/expected_values/yammer.py | Python | mit | 4,202 | 0.000714 | from datetime import datetime
import fixtures
import constants
from authomatic.providers import oauth2
conf = fixtures.get_configuration('yammer')
LINK = 'https://www.yammer.com/peterhudec.com/users/{0}'\
.format(conf.user_username)
# Yammer allows users to only set month and day of their birth day.
# The year ... | name', 'phone_numbers', 'number',
'email_addresses', 'address', 'has_fake_email', 'stats', 'following',
'followers', 'updates', 'settings', 'xdr_proxy', 'web_preferences',
'absolute_timestamps', 'threaded_mode', 'network_settings',
'message_prompt', 'allow_attachments', 'show_c | ommunities_directory',
'enable_groups', 'allow_yammer_apps', 'admin_can_delete_messages',
'allow_inline_document_view', 'allow_inline_video',
'enable_private_messages', 'allow_external_sharing', 'enable_chat',
'home_tabs', 'select_name', 'feed_description', 'ordering_index',
'ent... |
vlukes/sfepy | tests/test_dg_input_advection.py | Python | bsd-3-clause | 187 | 0.026738 | from __future__ i | mport absolute_import
input_name = '../examples/dg/advection_2D.py'
output_name = 'advection_sol.msh'
from tests_basic i | mport TestInput
class Test( TestInput ):
pass |
mrcl/HakketyYaks | run.py | Python | mit | 94 | 0 | #!/usr/bin/python2.7
from app import app |
if __name__ == '__main__':
app.run(debug=Tr | ue)
|
pjdufour/slackbot-osm | slackbotosm/settings.py | Python | bsd-3-clause | 101 | 0 | import os
DE | BUG = False
try:
from l | ocal_settings import * # noqa
except ImportError:
pass
|
IntelLabs/hpat | sdc/tests/test_hiframes.py | Python | bsd-2-clause | 29,355 | 0.000477 | # *****************************************************************************
# Copyright (c) 2020, Intel Corporation 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 sou... | t_func(df1)
self.assertTrue(hasattr(df1, 'B'))
test_impl(df2)
np.testing.assert_equal(df1.B.values, df2.B.values)
@skip_numba_jit
@skip_sdc_jit('Not implemented in sequ | ential transport layer')
def test_cumsum(self):
def test_impl(n):
df = pd.DataFrame({'A': np.ones(n), 'B': np.random.ranf(n)})
Ac = df.A.cumsum()
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
... |
favll/pogom | pogom/pgoapi/protos/POGOProtos/Settings/Master/EquippedBadgeSettings_pb2.py | Python | mit | 3,197 | 0.006569 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Settings/Master/EquippedBadgeSettings.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from go... | ings.Master\"y\n\x15\x45quippedBadgeSettings\x12\x1f\n\x17\x65quip_badge_cooldo | wn_ms\x18\x01 \x01(\x03\x12\x1f\n\x17\x63\x61tch_probability_bonus\x18\x02 \x03(\x02\x12\x1e\n\x16\x66lee_probability_bonus\x18\x03 \x03(\x02\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_EQUIPPEDBADGESETTINGS = _descriptor.Descriptor(
name='EquippedBadgeSettings',
full_name='POGOProtos.Settings... |
astropy/astropy-helpers | astropy_helpers/commands/test.py | Python | bsd-3-clause | 1,466 | 0.000682 | """
Different implementations of the ``./setup.py test`` command depending on
what's locally available.
If Astropy v1.1 or later is available it should be possible to import
AstropyTest from ``astropy.tests.command``. Otherwise there is a skeleton
implementation that allows users to at least discover the ``./setup.py ... | nly ImportErrors, but there are
# some other obscure exceptional conditions that can occur when importing
# astropy.tests (at least on older versions) that can cause these imports to
# fail
try:
# If we are testing astropy itself, we need to use import_file to avoid
# actually importing astropy (just the file... | :
AstropyTest = import_file(command_file, 'astropy_tests_command').AstropyTest
else:
import astropy # noqa
from astropy.tests.command import AstropyTest
except Exception:
# No astropy at all--provide the dummy implementation
from ._dummy import _DummyCommand
class AstropyTest... |
quantifiedcode/checkmate | checkmate/contrib/plugins/python/pep8/setup.py | Python | mit | 266 | 0.018797 | from .analyzer import Pep8Analyzer
from .issues_ | data import issues_data
analyzers = {
'pep8' :
{
'title' : 'Pep-8',
'class' : Pep8Analyzer,
'language' : 'python',
'issues_data' : issues_data,
| },
}
|
dianvaltodorov/happy-commas | db_migrate.py | Python | mit | 963 | 0 | #!env/bin/python
"""Migrate the database"""
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%03d_... | SQLALCHEMY_MIGRATE_REPO,
| tmp_module.meta, db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('New migration saved as ' + migration)
print('Current database version: ' + str(v))
|
lowRISC/fusesoc | tests/test_edalizer.py | Python | gpl-3.0 | 1,641 | 0.001219 | # Copyright FuseSoC contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause
def test_generators():
import os
import tempfile
from fusesoc.config import Config
from fusesoc.coremanager import CoreManager
from fusesoc.edalizer import ... | oin(
cache_root, "generated", "generat | e-testgenerate_without_params_0"
)
assert os.path.isfile(os.path.join(gendir, "generated.core"))
assert os.path.isfile(os.path.join(gendir, "testgenerate_without_params_input.yml"))
gendir = os.path.join(
cache_root, "generated", "generate-testgenerate_with_params_0"
)
assert os.path.isf... |
yaohongkok/py-one-chat | onechat/client.py | Python | mit | 747 | 0.034806 | from ConfigParser import SafeConfigParser
import requests
class Client(object):
def __init__(self, configFileName):
self.config = SafeConfigParser()
self.config.read(configFileName)
def send(self, recepient, message):
i | f message.platform == "facebook":
return self.sendFacebookMessage(recepient, message)
else:
raise Exception('Unknown Message\' Platform')
def sendFacebookMessage(self,recepient, message):
token = self.config.get('onechat','FACEBOOK_MESSENGER_TOKEN')
sendUrl = "https://graph.facebook.com/v2.6/me/messages?... | d"
return "Failed sending request"
|
dagoaty/eve-wspace | evewspace/account/views.py | Python | gpl-3.0 | 3,492 | 0.002864 | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your ... | 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 License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from account.models import RegistrationForm
from account.utils import *
from account.forms import EditProfileForm
from django.contrib.auth.models import User
from dja... |
tschmorleiz/amcat | amcat/scripts/actions/deduplicate.py | Python | agpl-3.0 | 6,399 | 0.003907 | #!/usr/bin/python
###########################################################################
# (C) Vrije Universiteit, Amsterdam (the Netherlands) #
# #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit ... | "date")
for i, article in enumerate(articles.iterator(), start=1):
if not i % 100 or i == n_articles:
log.info("Checking article {i} of {n_articles}".format(**locals()))
compare_with = self.get_articles(articleset_2, article, text_ratio)
if not skip_simple:... | h, article, text_ratio)
compare_with = self.get_matching(compare_with, article, headline_ratio, "headline")
compare_with = set(self.get_matching(compare_with, article, text_ratio, "text"))
if not delete_same:
discard = None
for a in compare_with:
... |
zstackio/zstack-woodpecker | integrationtest/vm/virtualrouter/test_update_vm_cpu_memory.py | Python | apache-2.0 | 2,076 | 0.003372 | '''
Test change cpu and memory configuration when VM is running
@author: quarkonics
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
#import zstackwoodpecker.operations | .host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.vm_operations as vm_ops
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()
def test():
test_util.test_dsc('Test update instance offering')
... | instance_offering = test_lib.lib_get_instance_offering_by_uuid(vm.get_vm().instanceOfferingUuid)
test_obj_dict.add_vm(vm)
vm_ops.update_vm(vm.get_vm().uuid, instance_offering.cpuNum * 2, None)
vm_ops.update_vm(vm.get_vm().uuid, None, instance_offering.memorySize * 2)
vm.update()
if (vm.get_... |
plotly/plotly.py | packages/python/plotly/plotly/validators/streamtube/starts/_x.py | Python | mit | 391 | 0.002558 | import _plotly_utils.ba | sevalidators
class XValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="x", parent_name="streamtube.starts", **kwargs):
super(XValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit... | kwargs
)
|
jody-frankowski/ansible | test/units/TestModuleUtilsBasic.py | Python | gpl-3.0 | 13,044 | 0.003527 | import os
import tempfile
import unittest
from nose.tools import raises
from nose.tools import timed
from ansible import errors
from ansible.module_common import ModuleReplacer
from ansible.utils import checksum as utils_checksum
TEST_MODULE_DATA = """
from ansible.module_utils.basic import *
def get_module():
... |
friendlier to unittests so that we can test at the level that the public
is interacting with the APIs.
'''
MANY_RECORDS = 7000
URL_SECRET = 'http://username:pas:word@foo.com/data'
SSH_SECRET = 'username:pas:word@foo.com/data'
def cleanup_temp_file(self, fd, path):
try:
... | )
os.remove(path)
except:
pass
def cleanup_temp_dir(self, path):
try:
os.rmdir(path)
except:
pass
def _gen_data(self, records, per_rec, top_level, secret_text):
hostvars = {'hostvars': {}}
for i in range(1, records, 1):
... |
andrewgodwin/django-channels | channels/staticfiles.py | Python | bsd-3-clause | 2,778 | 0.00108 | from urllib.parse import urlparse
from urllib.request import url2pathname
from django.conf import settings
from django.contrib.staticfiles import utils
from django.contrib.staticfiles.views import serve
from django.http import Http404
from .http import AsgiHandler
class StaticFilesWrapper:
"""
ASGI applicat... | scope, static_base_url=self.base_url), receive, send
)
# Hand off to the main app
return await self.application(scope, receive, send)
class StaticFilesHandler(AsgiHandler):
"""
Subclass of AsgiHandler that serves directly from its get_response.
"""
# TODO: Review hierarchy... | = scope["static_base_url"][2]
return await super().__call__(scope, receive, send)
def file_path(self, url):
"""
Returns the relative path to the media file on disk for the given URL.
"""
relative_url = url[len(self.static_base_url) :]
return url2pathname(relative_ur... |
astrobin/astrobin | astrobin/forms/solar_system_acquisition_form.py | Python | agpl-3.0 | 1,528 | 0.003272 | from django import forms
from django.utils.translation import ugettext_lazy as _
from astrobin.models import SolarSystem_Acquisition
class SolarSystem_AcquisitionForm(forms.ModelForm):
error_css_class = 'error'
date = forms.DateField(
required=False,
input_formats=['%Y-%m-%d'],
widge... | (self):
data = self.cleaned_data['transparency']
if dat | a and data not in list(range(1, 11)):
raise forms.ValidationError(_("Please enter a value between 1 and 10."))
return data
class Meta:
model = SolarSystem_Acquisition
fields = (
'date',
'time',
'frames',
'fps',
'exposu... |
asterix135/infonex_crm | marketing/migrations/0006_auto_20181221_1059.py | Python | mit | 594 | 0 | # Generated by Django 2.0.3 on 2018-12-21 15:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('marketing', '0005_auto_20180123_1157'),
]
operati | ons = [
migrations.AlterField(
model_name='uploadedcell',
name='content',
field=models.TextField | (blank=True, default=''),
),
migrations.AlterField(
model_name='uploadedrow',
name='error_message',
field=models.CharField(blank=True, default='', max_length=255),
),
]
|
b-jesch/service.fritzbox.callmonitor | resources/lib/PhoneBooks/pyicloud/vendorlibs/keyring/util/escape.py | Python | gpl-2.0 | 1,497 | 0.004008 | """
escape/unescape routines available for backends which need
alphanumeric usernames, services, or other values
"""
import re
import string
import sys
# True if we are running on Python 3.
# taken from six.py
PY3 = sys.version_info[0] == 3
# allow use of unicode literals
if PY3:
def u(s):
return s
d... | else:
def u(s):
return unicode(s, "unicode_escape")
def _unichr(c):
return unichr(c)
LEGAL_CHARS = (
getattr(string, 'letters', None) # Py | thon 2
or getattr(string, 'ascii_letters') # Python 3
) + string.digits
ESCAPE_FMT = "_%02X"
def _escape_char(c):
"Single char escape. Return the char, escaped if not already legal"
if isinstance(c, int):
c = _unichr(c)
return c if c in LEGAL_CHARS else ESCAPE_FMT % ord(c)
def escape(value):... |
abhishekkr/nix-bootstrapper | commands/command_plugins/password/__init__.py | Python | apache-2.0 | 5,851 | 0.000855 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2011 Openstack, LLC.
# 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... | stderrdata.strip('\n')
else:
st | derrdata = '<None>'
logging.error("pwd_mkdb failed: %s" % stderrdata)
try:
os.unlink(tmpfile)
except Exception:
pass
raise PasswordError(
(500, "Rebuilding the passwd database failed"))
... |
sgonzalez/wsn-parking-project | sensor-pi/testimages.py | Python | gpl-2.0 | 764 | 0.027487 | #!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
|
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def takepic(imageName):
print("picture")
command = "sudo raspistill -o " + imageName + " -q 100 -t " + camera_pa | use
print(command)
os.system(command)
while(True):
if(up==True):
if(GPIO.input(24)==False):
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d_%H%M%S")
filename = "photo-"+timeString+".jpg"
takepic(filename)
subprocess.call(['./processImage.sh', filename, '&'])
... |
dleicht/planx | manage.py | Python | mit | 559 | 0.003578 | # This file starts the WSGI web application.
# - Heroku starts gunicorn, which loads Procfile, whi | ch starts manage.py
# - Developers can run it from the command line: python runserver.py
import logging
from logging.handlers import RotatingFileHandler
from app import create_app
app = create_app()
# Start a development web server if executed from the command line
if __name__ == "__main__":
# Manage the command ... | n manage.py db
from app import manager
manager.run()
|
caneruguz/osf.io | addons/osfstorage/decorators.py | Python | apache-2.0 | 2,839 | 0.000704 | import httplib
import functools
from modularodm.exceptions import NoResultsFound
from modularodm.storage.base import KeyExistsException
from framework.auth.decorators import must_be_signed
from framework.exceptions import HTTPError
from addons.osfstorage.models import OsfStorageFileNode, OsfStorageFolder
from osf.mo... | ser, AbstractNode
from website.files import exceptions
from website.project.decorators import (
must_not_be_registration, must_have_addon,
)
def handle_odm_errors(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except NoResultsFound... | xcept KeyExistsException:
raise HTTPError(httplib.CONFLICT)
except exceptions.VersionNotFoundError:
raise HTTPError(httplib.NOT_FOUND)
return wrapped
def autoload_filenode(must_be=None, default_root=False):
"""Implies both must_have_addon osfstorage node and
handle_odm_erro... |
baylee-d/osf.io | website/archiver/utils.py | Python | apache-2.0 | 11,737 | 0.003238 | import functools
from framework.auth import Auth
from website.archiver import (
StatResult, AggregateStatResult,
ARCHIVER_NETWORK_ERROR,
ARCHIVER_SIZE_EXCEEDED,
ARCHIVER_FILE_NOT_FOUND,
ARCHIVER_FORCED_FAILURE,
)
from website import (
mails,
settings
)
from osf.utils.sanitize import unesc... | mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIV | E_UNCAUGHT_ERROR_DESK,
user=user,
src=src,
results=results,
can_change_preferences=False,
url=url,
)
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_UNCAUGHT_ERROR_USER,
user=user,
src=src,
results=results,
can_ch... |
MikeLing/shogun | examples/undocumented/python/graphical/em_1d_gmm.py | Python | gpl-3.0 | 1,911 | 0.018315 | from pylab import figure,show,connect,hist,plot,legend
from numpy import array, append, arange, empty, exp
from shogun import Gaussian, GMM
from shogun import RealFeatures
import util
util.set_title('EM for 1d GMM example')
#set the parameters
min_cov=1e-9
max_iter=1000
min_change=1e-9
#setup the real GMM
real_gmm=G... | ariances
est_mean1=est_gmm.get_nth_mean(0)
est_mean2=est_gmm.get_nth_mean(1)
est_mean3=est_gmm.get_nth_mean(2)
est_cov1=est_gmm.get_nth_cov(0)
est_cov2=est_gmm.get_nth_cov(1)
est_cov3=est_gmm.get_nth_cov(2)
est_coef=est_gmm.get_coef()
print e | st_mean1
print est_cov1
print est_mean2
print est_cov2
print est_mean3
print est_cov3
print est_coef
#plot real GMM, data and estimated GMM
min_gen=min(min(generated))
max_gen=max(max(generated))
plot_real=empty(0)
plot_est=empty(0)
for i in arange(min_gen, max_gen, 0.001):
plot_real=append(plot_real, array([exp(r... |
BioMedIA/irtk-legacy | wrapping/cython/irtk/ext/chanvese.py | Python | bsd-3-clause | 9,929 | 0.022258 |
# http://www.creatis.insa-lyon.fr/~bernard/creaseg/
# http://ascratchpad.blogspot.com/2011/03/image-segmentation-using-active.html
#------------------------------------------------------------------------
# Region Based Active Contour Segmentation
#
# seg = region_seg(I,init_mask,max_its,alpha,display)
#
# Inputs: I ... | formation
curvature = get_curvature(phi,idx) # force from curvature penalty
| dphidt = F /np.max(np.abs(F)) + alpha*curvature # gradient descent to minimize energy
#-- maintain the CFL condition
dt = 0.45/(np.max(np.abs(dphidt))+eps)
#-- evolve the curve
phi.flat[idx] += dt*dphidt
#-- Keep SDF smooth
phi = sussman(phi, ... |
mulkieran/storage_alerts | tests/sources/generic/by_line/recognizers_test.py | Python | gpl-2.0 | 7,550 | 0.000662 | # Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be u... | et, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Anne Mulhern <amulhern@redhat.co... | . """
import unittest
from storage_alerts.sources.generic.by_line.recognizers import LazyRecognizer
from storage_alerts.sources.generic.by_line.recognizers import ManyRecognizer
from storage_alerts.sources.generic.by_line.recognizers import NoRecognizer
from storage_alerts.sources.generic.by_line.recognizers import Ye... |
riyas-org/sdr | bc_rx_recorded.py | Python | gpl-2.0 | 3,006 | 0.012641 | #!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Bc Rx Recorded
# Generated: Sun Jun 8 13:46:34 2014
##################################################
from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import ... | #################
self.connect((self.blocks_file_source_0, 0), (self.wxgui_ff | tsink2_0, 0))
self.connect((self.blocks_file_source_0, 0), (self.analog_wfm_rcv_0, 0))
self.connect((self.analog_wfm_rcv_0, 0), (self.audio_sink_0, 0))
# QT sink close method reimplementation
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.