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 |
|---|---|---|---|---|---|---|---|---|
chepazzo/ansible-modules-extras | cloud/amazon/ec2_eni.py | Python | gpl-3.0 | 13,881 | 0.004322 | #!/usr/bin/python
#
# This is a free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This Ansible library is distributed in the hope that i... | 'instance_id': interface.attachment.instance_id,
| 'device_index': interface.attachment.device_index,
'status': interface.attachment.status,
'attach_time': interface.attachment.attach_time,
'delete_on_termination': interface.attachment.delete... |
liminspace/dju-privateurl | tests/urls.py | Python | mit | 188 | 0 | from django.conf.urls import include, url
from django.contrib import admin
url | patterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('dju_privateurl.urls')) | ,
]
|
ianjuma/usiu-app-dir | benchcare/patients/forms.py | Python | gpl-2.0 | 775 | 0.00129 | from patients.m | odels import Patient, Next_of_Kin, Vitals, Visits, Diagnosis, Medication, History, Documents
from django import forms
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
class Next_of_KinForm(forms.ModelForm):
class Meta:
model = Next_of_Kin
class | VitalsForm(forms.ModelForm):
class Meta:
model = Vitals
class VisitsForm(forms.ModelForm):
class Meta:
model = Visits
class DiagnosisForm(forms.ModelForm):
class Meta:
model = Diagnosis
class MedicationForm(forms.ModelForm):
class Meta:
model = Medication
class H... |
AntoineAugusti/katas | rosalind/long.py | Python | mit | 1,108 | 0.001805 | # http://rosalind.in | fo/problems/long/
def superstring(arr, accumulator=''):
# We now have all strings
| if len(arr) == 0:
return accumulator
# Initial call
elif len(accumulator) == 0:
accumulator = arr.pop(0)
return superstring(arr, accumulator)
# Recursive call
else:
for i in range(len(arr)):
sample = arr[i]
l = len(sample)
for p ... |
JohanComparat/pySU | spm/bin/combine_model_spectra_write_scripts.py | Python | cc0-1.0 | 1,246 | 0.028892 | import glob
import os
from os.path import join
import numpy as n
def writeScript(rootName, plate, env):
f=open(rootName+".sh",'w')
f.write("#!/bin/bash \n")
f.write("#PBS -l walltime=40:00:00 \n")
f.write("#PBS -o "+plate+".o.$PBS_JOBID \n")
f.write("#PBS -e "+plate+".e$PBS_JOBID \n")
f.write("#PBS -M comparat@m... | specList])
for el in data :
f.write("python combine_model_spectra.py "+el[1]+" "+el[2]+" "+el[3]+" "+env+" \n")
f.write(" \n")
f | .close()
env="SDSSDR12_DIR"
plates = n.loadtxt( join(os.environ[env], "catalogs", "plateNumberList"), unpack=True, dtype='str')
for plate in plates:
rootName = join(os.environ['HOME'], "batch_combine_sdss", plate)
writeScript(rootName, plate, env)
|
ibarria0/Cactus | cactus/plugin/manager.py | Python | bsd-3-clause | 2,122 | 0.001885 | #coding:utf-8
import functools
from cactus.utils.internal import getargspec
from cactus.plugin import defaults
class PluginManager(object):
def __init__(self, site, loaders):
self.site = site
self.loaders = loaders
self.reload()
for plugin_method in defaults.DEFAULTS:
... | _meth(*args, **kwargs)
def preBuildPage(self, site, page, context, data):
"""
Special call as we have changed the API for this.
We have two calling conventions:
- The new one, which passes page, context, data
- The deprecated one, which also passes the site (Now accessib... | ind the correct calling convention
new = [page, context, data]
deprecated = [site, page, context, data]
arg_lists = dict((len(l), l) for l in [deprecated, new])
try:
# Try to find the best calling convention
n_args = len(getargspec(plugin.... |
predakanga/plugin.video.catchuptv.au.ninemsn | resources/lib/ninemsnvideo/objects.py | Python | mit | 3,248 | 0.011084 | #
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), ... | channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', ... | 'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item... |
USStateDept/FPA_Core | openspending/model/dataorg.py | Python | agpl-3.0 | 5,452 | 0.004585 | from datetime import datetime
from sqlalchemy.orm import reconstructor, relationship, backref
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, Unicode, Boolean, DateTime
from sqlalchemy import BigInteger
from sqlalchemy.sql.expression import false, or_
from sqlalchemy.ext.associati... | on','ORTemplate','mappingTemplate','prefuncs']
for field in fields:
json['fields'][field] = getattr(self, field)
return json
@classmethod
def import_json_dump(cls, theobj):
fields = ['label','description','ORTemplate','mappingTemplate','prefuncs']
cl... | sobj, field, theobj['fields'][field])
#classobj.set(field, theobj['fields'][field])
db.session.add(classobj)
db.session.commit()
return classobj.id
def __repr__(self):
return "<DataOrg(%r,%r)>" % (self.id, self.label)
def update(self, dataorg):
self.labe... |
wolverineav/neutron | neutron/tests/unit/agent/l3/test_router_info.py | Python | apache-2.0 | 16,514 | 0 | # 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
# d... | router['routes'] = fake_new_routes
ri.routes_updated(fake_old_routes, fake_new_routes)
expected = [['ip', 'route', 'replace', 'to', '110.100.30.0/24',
'via', '10.100.10.30'],
['ip', 'route', 'replace', 'to', '110.100.31.0/24',
'via', '10.100.... | 'nexthop': "10.100.10.30"}]
ri.router['routes'] = fake_new_routes
ri.routes_updated(ri.routes, fake_new_routes)
expected = [['ip', 'route', 'delete', 'to', '110.100.31.0/24',
'via', '10.100.10.30']]
self._check_agent_method_called(expected)... |
devyn/unholy | decompyle/decompyle/dis_files.py | Python | mit | 1,163 | 0.006019 | import magics
__all__ = ['by_version', 'by_magic']
_fallback = {
'EXTENDED_ARG': None,
'hasfree': [],
}
class dis(object):
def __init__(self, version, module):
self._version = version
from __builtin__ import __import__
self._module = __import__('decompyle.%s' % module, globals... | eyError, e:
if _fallback.has_key(attr):
val = _fallback[attr]
else:
raise e
return val
by_version = {
'1.5': dis('1.5', 'dis_15'),
'1.6': dis('1.6', 'dis_16'),
'2.0': dis('2.0', 'dis_20'),
'2.1': dis('2.1', 'dis_21'),
| '2.2': dis('2.2', 'dis_22'),
'2.3': dis('2.3', 'dis_23'),
'2.4': dis('2.4', 'dis_24'),
'2.5': dis('2.5', 'dis_25'),
}
by_magic = dict( [ (mag, by_version[ver])
for mag, ver in magics.versions.iteritems() ] )
if __name__ == '__main__':
for m, ver in by_magic.items():
magics... |
plotly/plotly.py | packages/python/plotly/plotly/validators/layout/xaxis/tickfont/_color.py | Python | mit | 418 | 0.002392 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
| self, plotly_name="color", parent_name="layout.xaxis.tickfont", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "ticks"),
**kwargs
| )
|
insiderr/insiderr-app | app/modules/requests/packages/chardet/big5prober.py | Python | gpl-3.0 | 1,685 | 0.000593 | # ####################### BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights ... | e along with this library; if | not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import Big5D... |
StrellaGroup/frappe | frappe/website/doctype/website_settings/website_settings.py | Python | mit | 4,709 | 0.026545 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import get_request_site_address, encode
from frappe.model.document import Document
from six.moves.urllib.parse import quote
fr... |
via_hooks = frappe.get_hooks("website_context")
for key in via_hooks:
context[key] = via_hooks[key]
if key not in ("top_bar_items", "footer_items", "post_login") \
and isinstance(context[key], (list | , tuple)):
context[key] = context[key][-1]
add_website_theme(context)
if not context.get("favicon"):
context["favicon"] = "/assets/frappe/images/favicon.png"
if settings.favicon and settings.favicon != "attach_files:":
context["favicon"] = settings.favicon
return context
def get_items(parentfield):
all... |
bsmr-eve/Pyfa | gui/builtinStatsViews/resourcesViewFull.py | Python | gpl-3.0 | 15,284 | 0.002748 | # =============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of pyfa.
#
# pyfa 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 ... | Used%s%s" % (panel.capitalize(), type_.capitalize(), suffix[type_].capitalize()), lbl)
box.Add(lbl, 0, wx.ALIGN_CENTER | wx.LEFT, 5)
box.Ad | d(wx.StaticText(parent, wx.ID_ANY, "/"), 0, wx.ALIGN_CENTER)
lbl = wx.StaticText(parent, wx.ID_ANY, "0")
setattr(self, "label%sTotal%s%s" % (panel.capitalize(), type_.capitalize(), suffix[type_].capitalize()),
lbl)
box.Add(lbl, 0, wx.ALIGN_CENTER)
set... |
raprasad/worldcup | worldcup/worldcup/predictions/views.py | Python | mit | 6,415 | 0.018083 | from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.forms.models import modelformset_factory
from worldcup.common.msg_util import *
from worldcup.common.user_util import *
from worldcup.matches.models ... | h_type is None:
return None
if match_type.name == MATCH_TYPE_KNOCKOUT_STAGE:
p = PredictionStage2(user=user
, match=match
, team1=get_team_not_determined() |
, team2=get_team_not_determined()
)
else:
p = Prediction(user=user, match=m)
p.save()
return p
def get_users_predictions(request, user, match_type):
"""For a given user and match type, return Prediction objects.
If they don't exist, ... |
recurly/recurly-client-python | recurly/base_errors.py | Python | mit | 353 | 0 | import recurly
class RecurlyError(Exception):
@classmethod
def | error_from_status(cls, status):
return recurly.errors.ERROR_MAP.get(status, "")
class ApiError(RecurlyError):
def __init__(self, message, error):
super(ApiError, self).__init__(message)
self.error = error
class NetworkError(RecurlyError):
pass
| |
kmunve/pysenorge | pysenorge/constants.py | Python | gpl-3.0 | 1,844 | 0.005965 | '''
Contains physical constants used in snow modeling.
@var a_gravity: Gravitational acceleration [m s-2]
@var eta0: Viscosity of snow at T=0C and density=0 [N s m- 2 = kg m-1 s-1]
@var rho_air: Density of air [kg m-3], dry air at 0 C and 100 kPa
@var rho_water: Density of water [kg m-3]
@var rho_ice: Density o... |
@var k_ice10: Thermal conductivity of ice [W m-1 K-1] at -10 C
@var secperday: Seconds per day [s]
@var boltzmann: Boltzmann constant [J K-1].
The Boltzmann constant (k or kB) is the physical constant relating energy
at the particle level with temperature observed at the bulk level.
It is the gas c... |
@since: 25. mai 2010
'''
# gravitational acceleration [m s-2]
a_gravity = 9.81
# viscosity of snow at T=0C and density=0 [N s m- 2= kg m-1 s-1]
eta0 = 3.6e6
# Density of air [kg m-3], dry air at 0 C and 100 kPa
rho_air = 1.2754
# Density of water [kg m-3]
rho_water = 1000.0
# Density of ice [kg... |
imron/scalyr-agent-2 | benchmarks/micro/test_json_serialization.py | Python | apache-2.0 | 5,318 | 0.00188 | # Copyright 2014-2020 Scalyr 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 writin... | ) == json_lib
assert scalyr_agent.util.SORT_KEYS == sort_keys
assert isinstance(result, six.text_type)
assert json_decode(result) == data
# fmt: off
@pytest.mark.parametrize("log_tuple",
[
("agent_debug_5_mb.log", 3 * 1024),
("agent_debug_5_mb.log", 500 * 1024),
],
ids=[
... | son_lib", ["json", "ujson", "orjson"])
@pytest.mark.benchmark(group="json_encode")
def test_json_encode(benchmark, json_lib, log_tuple):
if not six.PY3 and json_lib == "orjson":
pytest.skip("Skipping under Python 2, orjson is only available for Python 3")
return
_test_json_encode(benchmark, jso... |
genialis/resolwe | resolwe/storage/management/__init__.py | Python | apache-2.0 | 180 | 0 | """.. Ignore pydocsty | le D400.
==================
Storage Management
==================
.. autom | odule:: resolwe.storage.management.commands.run_storage_manager
:members:
"""
|
krafczyk/spack | var/spack/repos/builtin/packages/py-lrudict/package.py | Python | lgpl-2.1 | 1,591 | 0.001257 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along w... |
tanghaibao/goatools | goatools/test_data/sections/gjoneska_pfenning.py | Python | bsd-2-clause | 9,848 | 0.017465 | """Sections variable used for grouping Gjoneska 2015 GO IDs."""
__copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
SECTIONS = [ # 18 sections
("immune", [ # 15 GO-headers
"GO:0002376", # BP 564 L01 D01 M immune system process
... | osynthetic process
]),
("adhesion", [ # 3 GO-headers
"GO:0022610", # BP 194 L01 D01 P biological adhesion
"GO:0030155", # BP 246 L02 D02 AB regulation of cell adhesion
"GO:0007155", # BP 165 L02 D02 P cell adhesion
]),
("cell cycle", [ # 9 GO-headers
"... | "GO:0051726", # BP 411 L03 D03 AB regulation of cell cycle
"GO:0051301", # BP 54 L03 D03 CD cell division
"GO:0007049", # BP 12 L03 D03 CD cell cycle
"GO:0070192", # BP 17 L03 D05 CIL chromosome organization in meiotic cell cycle
"GO:0007051", # BP 19 L0... |
huyphan/pyyawhois | test/record/parser/test_response_whois_biz_status_available.py | Python | mit | 1,928 | 0.002593 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.biz/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse as t... | status_available.txt"
host = "whois.biz"
part = yawhois.record.Part(open(fixture_path, "r").read(), host)
self.record = yawhois.record.Record(None, [part])
def test_status(self):
eq_(self.record.s | tatus, None)
def test_available(self):
eq_(self.record.available, True)
def test_domain(self):
eq_(self.record.domain, "u34jedzcq.biz")
def test_nameservers(self):
eq_(self.record.nameservers.__class__.__name__, 'list')
eq_(self.record.nameservers, [])
def test_admin_... |
eljost/pysisyphus | deprecated/optimizers/RSRFOptimizer.py | Python | gpl-3.0 | 5,961 | 0.001342 | #!/usr/bin/env python3
# See [1] https://pubs.acs.org/doi/pdf/10.1021/j100247a015
# Banerjee, 1985
# [2] https://aip.scitation.org/doi/abs/10.1063/1.2104507
# Heyden, 2005
# [3] https://onlinelibrary.wiley.com/doi/abs/10.1002/jcc.540070402
# Baker, 1985
# [4] 10.1007/s002140050387
#... | est eigenvalue) or the last (largest eigenvalue) index.
step_nu = eigenvectors.T[ind]
nu = step_nu[-1]
self.log(f"nu_{verbose}={nu:.4e}")
# Scale eigenvector so that its last element equals 1. The
# final is step is the scaled eigenvector without | the last element.
step = step_nu[:-1] / nu
eigval = eigenvalues[ind]
self.log(f"eigenvalue_{verbose}={eigval:.4e}")
return step, eigval, nu
def optimize(self):
forces = self.geometry.forces
self.forces.append(forces)
self.energies.append(self.geometry.energy)... |
paplorinc/intellij-community | python/testData/testRunner/env/pytest/test1.py | Python | apache-2.0 | 209 | 0.014354 | from time import slee | p
class TestPyTest:
def testOne(self):
sleep(1.5) # To check duration
assert 4 == 2*2
def testTwo(self): |
assert True
def testThree():
assert 4 == 2*2
|
fbradyirl/home-assistant | homeassistant/components/facebook/notify.py | Python | apache-2.0 | 3,953 | 0.000253 | """Facebook platform for notify component."""
import json
import logging
from aiohttp.hdrs import CONTENT_TYPE
import requests
import voluptuous as vol
from homeassistant.const import CONTENT_TYPE_JSON
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import (
ATTR_DATA,
... | ate_body = {"messages": [body_message]}
_LOGGER.debug("Broadcast body %s : ", broadcast_create_body)
resp = requests.post(
CREATE_BROADCAST_URL,
data=json.dumps(broadcast_create_body),
params=payload,
headers={CONTENT_TYPE: CONTENT... | oadcast_body = {
"message_creative_id": resp.json().get("message_creative_id"),
"notification_type": "REGULAR",
}
resp = requests.post(
SEND_BROADCAST_URL,
data=json.dumps(broadcast_body),
params=payload,
... |
custode/reviewboard | reviewboard/webapi/errors.py | Python | mit | 4,753 | 0 | from __future__ import unicode_literals
from djblets.webapi.errors import WebAPIError
class WebAPITokenGenerationError(Exception):
"""An error generating a Web API token."""
pass
#
# Standard error messages
#
UNSPECIFIED_DIFF_REVISION = WebAPIError(
200,
'Diff revision not specified.',
http_sta... | mmit ID specified has already been used.',
http_status=409) # 409 Conflict
MISSING_REPOSITORY = WebAPIError(
205,
'There was no repository found at the specified path.',
http_status=400) # 400 Bad Request
INVALID_REPOSITORY = WebAPIError(
206,
'The repository path specified is not in the lis... | Bad Request
INVALID_USER = WebAPIError(
208,
'User does not exist.',
http_status=400) # 400 Bad Request
REPO_NOT_IMPLEMENTED = WebAPIError(
209,
'The specified repository is not able to perform this action.',
http_status=501) # 501 Not Implemented
REPO_INFO_ERROR = WebAPIError(
210,
... |
levilucio/SyVOLT | t_core/tc_python/arule.py | Python | mit | 2,673 | 0.001871 |
from t_core.composer import Co | mposer
from t_core.matcher import Matcher
from t_core.iterator import Iterator
from t_core.rewriter import Rewriter
|
from t_core.resolver import Resolver
class ARule(Composer):
'''
Applies the transformation on one match.
'''
def __init__(self, LHS, RHS):
'''
Applies the transformation on one match.
@param LHS: The pre-condition pattern (LHS + NACs).
@param... |
MSEMJEJME/Get-Dumped | renpy/display/imagelike.py | Python | gpl-2.0 | 10,715 | 0.004666 | # Copyright 2004-2012 Tom Rothamel <[email protected]>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, m... | t(cr, (x, y))
cr = newcr
else:
newcr = Render(cdw, cdh)
newcr.forward = Matrix2D(1.0 * csw / cdw, 0, 0, 1.0 * csh / cdh)
newcr.reverse = Matrix2D(1.0 * cdw / csw, 0, 0, 1.0 * cdh / ... | 0))
return
rv = Render(dw, dh)
self.draw_pattern(draw, left, top, right, bottom)
return rv
def draw_pattern(self, draw, left, top, right, bottom):
# Top row.
if top:
if left:
draw(0, left, 0, top)
draw(... |
jaap-karssenberg/zim-desktop-wiki | zim/main/__init__.py | Python | gpl-2.0 | 28,210 | 0.026728 |
# Copyright 2013-2016 Jaap Karssenberg <[email protected]>
'''This module defines the L{main()} function for executing the zim
application. It also defines a number of command classes that implement
specific commandline commands and an singleton application object that
takes core of the process life cycle.
'... | okinfo is None:
return None, None # Cancelled prompt
try:
notebook, uripage = build_notebook(notebookinfo) # can raise FileNotFound
except FileNotFoundError:
if used_default:
# Default notebook went missing? Fallback to dialog to allow changi | ng it
notebookinfo = prompt_notebook_list()
if notebookinfo is None:
return None, None # Cancelled prompt
notebook, uripage = build_notebook(notebookinfo) # can raise FileNotFound
else:
raise
if ensure_uptodate and not notebook.index.is_uptodate:
for info in notebook.index.update_iter():
... |
dbk138/ImageRegionRecognition-FrontEnd | PythonScripts/LocationLookup.py | Python | mit | 2,163 | 0.017568 | __author__ = 'jhala'
import Helpers
import json
import os
''' creates a location lookup, and an associated image lookup '''
''' main '''
if __name__ == "__main__":
fil = r"c:\capstone\featureInfo.csv"
outLoc = r"c:\capstone\locationLookup.json"
imageBaseDir="C:\\Users\\jhala\\angular-seed\\app\\images\\"... | ons.index(locationName)
imagesForThisLocationTmp = locationsFinal[locIndex]['images']
imagesForThisLocationTmp.append( { 'name' : imgName})
locationsFinal[locIndex] = { 'name' : locationsFinal[locIndex]['name'] , 'id' : locationsFinal[locIndex]['id'] , 'numIm... | ndex]['numImages']+1 , 'images' : imagesForThisLocationTmp }
except ValueError:
locationId += 1
locations.append(locationName)
thisImageCount += 1
imagesForThisLocation = { 'name': imgName}
locationsFin... |
GbalsaC/bitnamiP | venv/src/oauth2-provider/oauth2_provider/tests/base.py | Python | agpl-3.0 | 5,353 | 0.000374 | # pylint: disable=missing-docstring
import json
from urlparse import urlparse
from django.core.urlresolvers import reverse
from django.http import QueryDict
from django.test import TestCase
import jwt
import provider.scope
from oauth2_provider.models import TrustedClient
from oauth2_provider.tests.util import normp... | =None, claims=None, trusted=False):
""" Login into client using OAuth2 authorization flow. """
self.set_trusted(self.auth_client, trusted)
self.client.login(username=self.user.username, password=self.password)
payload = {
'client_id': self.auth_client.client_id,
... | ,
'response_type': 'code',
'state': 'some_state',
}
_add_values(payload, 'id_token', scope, claims)
response = self.client.get(reverse('oauth2:capture'), payload)
self.assertEqual(302, response.status_code)
response = self.client.get(reverse('oauth2:auth... |
jimklo/LearningRegistry | LR/lr/lib/oauth.py | Python | apache-2.0 | 6,907 | 0.007963 | import logging, couchdb, oauth2, json, sys
from decorator import decorator
from pylons import config, request as r, response as res, session
from pylons.controllers.util import abort
from functools import wraps
log = logging.getLogger(__name__)
appConfig = config['app_conf']
class Error(RuntimeError):
"""Generic... | (type(o), repr(o)))
raise e
class CouchDBOAuthUtil():
def __init__(self, couchdb_dba_url=appConfig['couchdb.url.dbadmin'], users_d | b=appConfig['couchdb.db.users'], oauth_view=appConfig['couchdb.db.users.oauthview']):
self.server = couchdb.Server(couchdb_dba_url)
self.users = self.server[users_db]
self.oauth_view = oauth_view
def find_possible(self, consumer, token, mapper=None):
def wrap_row... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyKDE4/kio/KIconDialog.py | Python | gpl-2.0 | 1,319 | 0.010614 | # encoding: utf-8
# module PyKDE4.kio
# from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class KIconDialog(__PyKDE4_kdeui.KDialog):
... | unknown
pass
def newIconName(self, *args, **kwarg | s): # real signature unknown
pass
def openDialog(self, *args, **kwargs): # real signature unknown
pass
def setCustomLocation(self, *args, **kwargs): # real signature unknown
pass
def setIconSize(self, *args, **kwargs): # real signature unknown
pass
def setStrictIconSi... |
steve-ord/daliuge | daliuge-engine/dlg/runtime/tool_commands.py | Python | lgpl-2.1 | 1,948 | 0.00462 | #
# ICRAR - International Centre for Radio Astronomy Research
# (c) UWA - The University of Western Australia, 2020
# Copyright by UWA (in the framework of the ICRAR)
# All rights reserved
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser G... |
# MA 02111-1307 USA
#
from ..common import tool
def include_dir(_parser, _args):
from . import get_include_dir
print(get_include_dir())
def register_command | s():
tool.cmdwrap('nm', 'Starts a Node Manager', 'dlg.manager.cmdline:dlgNM')
tool.cmdwrap('dim', 'Starts a Drop Island Manager', 'dlg.manager.cmdline:dlgDIM')
tool.cmdwrap('mm', 'Starts a Master Manager', 'dlg.manager.cmdline:dlgMM')
tool.cmdwrap('replay', 'Starts a Replay Manager', 'dlg.manager.cmdlin... |
sqlalchemy/sqlalchemy | test/ext/mypy/plugin_files/issue_7321.py | Python | mit | 427 | 0 | from typing import Any
from typing import Dict
from | sqlalchemy.orm import declarative_base
from s | qlalchemy.orm import declared_attr
Base = declarative_base()
class Foo(Base):
@declared_attr
def __tablename__(cls) -> str:
return "name"
@declared_attr
def __mapper_args__(cls) -> Dict[Any, Any]:
return {}
@declared_attr
def __table_args__(cls) -> Dict[Any, Any]:
r... |
yongwen/makahiki | makahiki/apps/widgets/smartgrid_play_tester/migrations/__init__.py | Python | mit | 25 | 0 | "" | "Schema migrations."""
| |
wooyek/django-tasker | django_tasker/apps.py | Python | mit | 197 | 0 | from django.apps import AppConfig
from django.utils.translation | import ugettext as __, ugettext_lazy as _
class TaskerConfig(AppConfig):
name = 'django_tasker'
| verbose_name = _('tasker')
|
shagunsodhani/powerlaw | powerlaw/regression.py | Python | mit | 7,543 | 0.012727 | import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
from scipy.special import zeta
from .distribution import frequency_distribution, powerlaw_series, random_series
from .utils import unique
from math import pow, e, log, sqrt
import sys
import random
def least_square_regression(x, y, ... | = "x", ylabel = "y", prefix="", suffix=""):
"""
Perform least square regression to find the best fit line and returns the slope of the line.
**Parameters**
x : List of values along x axis.
y : List of values along y axis.
"""
X = np.asarray(x).reshape((len(x), 1))
Y = np.... | .fit(X, Y)
label_string = "Best fit line, y = "+str(regr.coef_[0][0])+" * x + "+str(regr.intercept_[0])
print(label_string)
print("Residual sum of squares: %.2f" % np.mean((regr.predict(X) - Y) ** 2))
print("Variance score: %.2f" % regr.score(X, Y))
# Plot outputs
original_data, = plt.plot(X, ... |
chickenzord/dotenvy | setup.py | Python | mit | 1,627 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
REPO_NAME = 'chickenzord/dotenvy'
VERSION = '0.2.0'
ARCHIVE_URL = 'https://github.com/%s/archive/v%s.tar.gz' % (REPO_NAME, VERSION)
setup(
# packaging
packages=find_packages('src'),
| package_dir={'': 'src'},
package_data={},
install_requires=[
'future',
],
setup_requires=[
'pytest-runner',
'flake8',
],
tests_require=[
'pytest',
'pytest-cov',
'pytest-travis-fold',
'moc | k',
'backports.tempfile',
],
entry_points={
"console_scripts": ['dotenvy = dotenvy.cli:main']
},
zip_safe=False,
# metadata
name='dotenvy',
version=VERSION,
author='Akhyar Amarullah',
author_email='[email protected]',
description='Dotenv handler for Python',
... |
aeroaks/httpProfiler | methods/webencodings/tests.py | Python | mit | 6,184 | 0 | # coding: utf8
"""
webencodings.tests
~~~~~~~~~~~~~~~~~~
A basic test suite for Encoding.
:copyright: Copyright 2012 by Simon Sapin
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
from . import (lookup, LABELS, decode, encode, iter_decode, iter_encode,
... | '\ue900'
assert decode(b'\x00\xe9', 'UTF-16BE') == 'é'
assert decode(b'\xe9\x00', 'UTF-16LE') == 'é'
assert decode(b'\xe9\x00', 'UTF-16') == 'é'
assert decode(b'\xe9\x00', 'UTF-16BE') == '\ue900'
assert decode(b'\x00\xe | 9', 'UTF-16LE') == '\ue900'
assert decode(b'\x00\xe9', 'UTF-16') == '\ue900'
def test_encode():
assert encode('é', 'latin1') == b'\xe9'
assert encode('é', 'utf8') == b'\xc3\xa9'
assert encode('é', 'utf8') == b'\xc3\xa9'
assert encode('é', 'utf-16') == b'\xe9\x00'
assert encode('é', 'utf-16le')... |
imajes/Sick-Beard | sickbeard/notifiers/boxcar2.py | Python | gpl-3.0 | 5,011 | 0.002993 | # Author: Marvin Pinto <[email protected]>
# Author: Dennis Lutter <[email protected]>
# Author: Shawn Conroyd <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | msg: The message to send (unicode)
title: The title of the message
accessToken: The access token to send notification to
returns: True if the message succeeded, False otherwise
"""
# build up the URL and parameters
| msg = msg.strip().encode('utf-8')
data = urllib.urlencode({
'user_credentials': accessToken,
'notification[title]': title + " - " + msg,
'notification[long_message]': msg,
'notification[sound]': sound,
'notification[source_name]': "SickBeard"
... |
garrettcap/Bulletproof-Backup | wx/tools/Editra/src/syntax/_smalltalk.py | Python | gpl-2.0 | 3,406 | 0.00411 | ###############################################################################
# Name: smalltalk.py #
# Purpose: Define Smalltalk syntax for highlighting and other features #
# Author: Cody Precord <[email protected]> #
... | WORDS]
def GetSyntaxSpec(self):
"""Syntax Specifications """
return SYNTAX_ITEMS
def GetCommentP | attern(self):
"""Returns a list of characters used to comment a block of code """
return [u'\"', u'\"']
#---- Syntax Modules Internal Functions ----#
def KeywordString():
"""Returns the specified Keyword String
@note: not used by most modules
"""
return ST_KEYWORDS[1]
#---- End Syntax... |
maniteja123/numdifftools | conda_recipe/run_test.py | Python | bsd-3-clause | 40 | 0.025 | import numdifftools
n | umdifftools.tes | t() |
Hattivat/hypergolic-django | hypergolic/catalog/urls/power_cycle_urls.py | Python | agpl-3.0 | 826 | 0.001211 | from django.conf.urls import url
from ..views import (PowerCycleListView, PowerCycleCreateView, PowerCycleDetailView,
PowerCycleUpdateView, PowerCycleDeleteView)
from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^create/$', # NOQA
login_required(PowerCyc... | ew()),
name="power_cycle_delete"),
url(r'^(?P<pk>.+)/$',
PowerCycleDetailView.as_view(),
name="pow | er_cycle_detail"),
url(r'^$',
PowerCycleListView.as_view(),
name="power_cycle_list"),
]
|
AdrianGaudebert/configman | configman/converters.py | Python | bsd-3-clause | 15,400 | 0.002013 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | ---------------------
def classes_in_namespaces_converter(template_for_namespace="cls%d",
name_of_class_option='cls',
instantiate_classes=False):
"""take a comma delimited list of class names, convert each class name
into an actual class a... | es a class derived from RequiredConfig. The inner function,
'class_list_converter', populates the InnerClassList with a Namespace for
each of the classes in the class list. In addition, it puts the each class
itself into the subordinate Namespace. The requirement discovery mechanism
of configman then... |
emijrp/pywikibot-core | pywikibot/i18n.py | Python | mit | 21,745 | 0.000368 | # -*- coding: utf-8 -*-
"""
Various i18n functions.
Helper functions for both the internal translation system
and for TranslateWiki-based translations.
By default messages are assumed to reside in a package called
'scripts.i18n'. In pywikibot 2.0, that package is not packaged
with pywikibot, and pywikibot 2.0 does ... | 'ksh', 'pdc', 'pfl']:
return ['de']
if code == 'lb':
return ['de', 'fr']
if code in ['als', 'gsw']:
return ['als', 'gsw', 'de']
if code == 'nds':
return ['nds-nl', 'de']
if code in ['dsb', 'hsb']:
return ['hsb', 'dsb', 'de']
if code == 'sli':
return [... | = 'rm':
return ['de', 'it']
if code == 'stq':
return ['nds', 'de']
# Greek
if code in ['grc', 'pnt']:
return ['el']
# Esperanto
if code in ['io', 'nov']:
return ['eo']
# Spanish
if code in ['an', 'arn', 'ast', 'ay', 'ca', 'ext', 'lad', 'nah', 'nv', 'qu',
... |
gchinellato/Self-Balance-Robot | nfs-server/modules/Motion/Motor/motor.py | Python | gpl-3.0 | 3,971 | 0.007555 | #!/usr/bin/python
"""
*************************************************
* @Project: Self Balance
* @Platform: Raspberry PI 2 B+
* @Description: Motor module
* DC Motor with gearbox/encoder
* Motor driver VNH2SP30
* @Owner: Guilherme Chinellato
* @Email: guilhermechi... | self.pinCCW = pinCCW
#Set up BCM GPIO numbe | ring
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#Set GPIO as output
GPIO.setup(pinPWM, GPIO.OUT)
GPIO.setup(pinCW, GPIO.OUT)
GPIO.setup(pinCCW, GPIO.OUT)
GPIO.output(pinCW, False)
GPIO.output(pinCCW, False)
#Set GPIO as PWM output
... |
DIRACGrid/RESTDIRAC | RESTSystem/private/RESTApp.py | Python | gpl-3.0 | 2,840 | 0.044366 |
import ssl
import sys
from tornado import web, httpserver, ioloop, process, autoreload
from DIRAC import gLogger, S_OK, S_ERROR
from DIRAC.Core.Utilities.ObjectLoader import ObjectLoader
from RESTDIRAC.RESTSystem.Base.RESTHandler import RESTHandler
from RESTDIRAC.ConfigurationSystem.Client.Helpers import RESTConf
cl... | ocess.fork_processes( RESTConf.numProcesses(), max_restarts = 0 )
kw[ 'debug' ] = False
if kw[ 'debug' ]:
gLogger.always( "Starting in debug mode" )
self.__app = web.Appl | ication( self.__routes, **kw )
port = RESTConf.port()
if balancer:
gLogger.notice( "Configuring REST HTTP service for balancer %s on port %s" % ( balancer, port ) )
self.__sslops = False
else:
gLogger.notice( "Configuring REST HTTPS service on port %s" % port )
self.__sslops = dict( ... |
alipsgh/tornado | drift_detection/page_hinkley.py | Python | mit | 2,052 | 0.001462 | """
The Tornado Framework
By Ali Pesaranghader
University of Ottawa, Ontario, Canada
E-mail: apesaran -at- uottawa -dot- ca / alipsgh -at- gmail -dot- com
---
*** The Page Hinkley (PH) Method Implementation ***
Paper: Page, Ewan S. "Continuous inspection schemes."
Published in: Biometrika 41.1/2 (1954): 100-115... | f.sum = 0.0
self.delta = delta
self.lambda_ = lambda_
self.alpha = alpha
def run(self, pr):
pr = 1 if pr is False else 0
warning_status = False
| drift_status = False
# 1. UPDATING STATS
self.x_mean = self.x_mean + (pr - self.x_mean) / self.m_n
self.sum = self.alpha * self.sum + (pr - self.x_mean - self.delta)
self.m_n += 1
# 2. UPDATING WARNING AND DRIFT STATUSES
if self.m_n >= self.MINIMUM_NUM_INSTAN... |
andela/troupon | troupon/troupon/settings/development.py | Python | mit | 420 | 0.002381 | """
Development specific settings for trou | pon project.
"""
from .base import *
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'troupon',
'USER': os.getenv('DB_USE | R'),
'PASSWORD': os.getenv('DB_PASSWORD'),
'HOST': '127.0.0.1',
'PORT': '5432',
}
} |
mitya57/debian-buildbot | buildbot/db/connector.py | Python | gpl-2.0 | 5,291 | 0.000756 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | CLEANUP_PERIOD,
| self._doCleanup)
self.cleanup_timer.setServiceParent(self)
def setup(self, check_version=True, verbose=True):
db_url = self.configured_url = self.master.config.db['db_url']
log.msg("Setting up database with URL %r" % (db_url,))
# set up the engine and pool
self._engin... |
yuhangwang/ninjag-python | test/frontend/build_dep/test_5.py | Python | mit | 304 | 0 | import ninjag
from ninjag.tk.ioTK import read_all
def test():
f_input = "input/in5.yaml"
| f_answer = "output/out5.ninja"
f_solution = "solution/sol5.ninja"
ninjag.main(f_answer, [f_input])
answer = read_all(f_answer)
solution = read_all(f_solution)
assert answe | r == solution
|
gunan/tensorflow | tensorflow/python/keras/saving/saved_model/load.py | Python | apache-2.0 | 40,001 | 0.006875 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | .saved_model import constants
from tensorflow.python.keras.saving.saved_model import json_utils
fro | m tensorflow.python.keras.saving.saved_model import utils
from tensorflow.python.keras.saving.saved_model.serialized_attributes import CommonEndpoints
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils import metrics_utils
from tensorflow.python.platform import tf_logging as logg... |
gnu-user/mcsc-6030-project | codes/benchmarks/baseline.py | Python | gpl-3.0 | 1,605 | 0 | #!/usr/bin/env python2
###############################################################################
#
# Set a baseline for all benchmarks using numpy's serial matrix multiplication
#
# Copyright (C) 2015, Jonathan Gillett
# All rights reserved.
#
#
# This program is free software: you can redistribute it and/or modi... | x, usage, schema
from schema import SchemaError
if __name__ == '__main__':
args = docopt(usage)
try:
args = | schema.validate(args)
except SchemaError as e:
exit(e)
# Generate the dynamic matrices for the test
dim, dtype, mtype = args['DIM'], args['--dtype'], args['--mtype']
A = gen_matrix(dim, dim, dtype, mtype)
B = gen_matrix(dim, dim, dtype, mtype)
# Calculate the execution time for the ba... |
bluszcz/basketpinfo | python/process_to_rrdtool.py | Python | bsd-3-clause | 812 | 0.011084 | #!/usr/bin/env python
"""
basketPInfo data procesors (rrdtool output)
Rafal Zawadzki <[email protected]>
BSD License (license.txt)
"""
import sys
def exit_failure():
" Nice info on failur | e "
print "usage: %s int\n" % sys.argv[0]
print "int should be 2 (humidity) or 3 (temperature)"
sys. | exit(-1)
if len(sys.argv)!=2:
exit_failure()
ARG = int(sys.argv[1])
if ARG not in (2, 3):
exit_failure()
FILENAME = "/home/pi/logs/temphum.txt"
HANDLER = open(FILENAME)
def transpose_data(data):
" Parses data "
return [ll.lstrip('\t') for ll in data.strip().split(',')]
for line in (transpose_data... |
vicnet/weboob | modules/ing/api/login.py | Python | lgpl-3.0 | 5,888 | 0.002887 | # -*- coding: utf-8 -*-
# Copyright(C) 2019 Sylvie Ye
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | mage = Image.eval(tile.image, lambda px: 0 if px <= self.alter_img_params['limit_pixel'] else 255)
def cut_tiles(self, tile_margin=None):
assert self.tiles, 'There are no tiles to process'
super(INGVirtKeyboard, self).cut_tiles(tile_margin)
# alter tile
self.process_tiles()
de... | les = []
for digit in password:
for tile in self.tiles:
if tile.md5 in self.symbols[digit]:
password_tiles.append(tile)
break
else:
# Dump file only when the symbol is not found
self.dump_tiles(self.... |
jeremiahyan/odoo | addons/product_matrix/__manifest__.py | Python | gpl-3.0 | 888 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': "Product Matrix",
'summary': """
Technical module: Matrix Implementation
""",
'description': """
Please refer to Sale Matrix or Purchase Matrix for the use of this module.
""",
'ca... |
'assets': {
'web.assets_backend': [
'product_matrix/static/src/js/section_and_note_widget.js',
'product_matrix/static/src/scs | s/product_matrix.scss',
],
'web.assets_qweb': [
'product_matrix/static/src/xml/**/*',
],
},
'license': 'LGPL-3',
}
|
thast/EOSC513 | DC/SimultaneousSources/Update_W_each_3it_5s_rademacher/Update_W_each_3it_5s_rademacher.py | Python | mit | 8,698 | 0.022189 | from SimPEG import Mesh, Regularization, Maps, Utils, EM
from SimPEG.EM.Static import DC
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import copy
#import pandas as pd
#from scipy.sparse import csr_matrix, spdiags, dia_matrix,diags
#from scipy.sparse.linalg import spsolve
from scipy.stats imp... | rx.getP(mesh,'CC')
#Update W Inversion
nsubSrc = 5
m0 = (-5.)*np.ones(mapping.nP);
miter = m0
n_its = 50
InnerIt = | 3
dmisfitsub = []
dmisfitall = []
#beta schedule
beta = 1.
betalist = [beta]
coolingFactor = 2.
coolingRate = 3
W = np.random.randint(0, high=2, size=[survey.nSrc,nsubSrc])*2-1
print W
dmisAll = DataMisfit.l2_DataMisfit(survey)
dmisfitall.append(dmisAll.eval(m0)/survey.nD)
print "Starting Model Dmisfit compared to full... |
ContinuumBridge/hot_drinks_app | hot_drinks.py | Python | mit | 13,490 | 0.005263 | #!/usr/bin/env python
# hot_drinks.py
# Copyright (C) ContinuumBridge Limited, 2014-2015 - All Rights Reserved
# Written by Peter Claydon
#
# Default values:
config = {
"hot_drinks": True,
"name": "A Human Being",
"alert": True,
"ignore_time": 120,
"window": 360,
"threshold": 10,
"daily_rep... | self.cbLog("debug", "msg send to client: " + str(json.dumps(msg, indent=4)))
values = {
"name": self.bridge_id + "/hot_drinks",
"points": [[int(now*1000), 1]]
}
| self.storeValues(values)
except Exception as ex:
self.cbLog("warning", "HotDrinks onChange encountered problems. Exception: " + str(type(ex)) + str(ex.args))
def sendValues(self):
msg = {"m": "data",
"d": self.s
}
self.cbLog("debug", "sendVa... |
SMAC/corelib | smac/amqp/protocol.py | Python | gpl-3.0 | 13,170 | 0.008276 | # Copyright (C) 2005-2010 MISG/ICTI/EIA-FR
# See LICENSE for details.
"""
Factories for AMQ clients, Thrift clients and SMAC Clients and servers.
@author: Jonathan Stoppani <[email protected]>
"""
import weakref
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.internet impo... |
response_exchange = Exchange(channel, **topology.exchanges['responses'])
response_queue = Queue(cha | nnel, exclusive=True, auto_delete=True)
yield response_queue.declare()
yield response_queue.bind(response_exchange)
consumer_tag = yield response_queue.consume()
service_exchange = Exchange(channel, **topology.exchanges[di... |
CWVanderReyden/originalMyHomeNet | recipeBox/migrations/0001_initial.py | Python | gpl-3.0 | 353 | 0.005666 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from sou | th.db import db
from south.v2 impor | t SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
}
complete_apps = ['recipeBox'] |
trondeau/gnuradio-old | gr-blocks/python/blocks/qa_stream_mux.py | Python | gpl-3.0 | 6,241 | 0.005929 | #!/usr/bin/env python
#
# Copyright 2004,2005,2007,2010,2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 ... | self.help_stream_2ff(N, strea | m_sizes)
result_data = self.help_stream_2ff(N, stream_sizes)
exp_data = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0)... |
Akrog/gcs-client | gcs_client/common.py | Python | apache-2.0 | 7,705 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Red Hat, 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... | void synchronized waves.
:type randomize: bool
"""
self.max_retries = max_retries
self.initial_delay = initial_delay
self.max_backoff = max_backoff
self.backoff_factor = backoff_factor
self.randomize = randomize
@classmethod
def get_default(cls):
... | if not hasattr(cls, 'default'):
cls.default = cls()
return cls.default
@classmethod
def set_default(cls, *args, **kwargs):
"""Set default retry configuration.
Methods acepts a RetryParams instance or the same arguments as the
__init__ method.
"""
... |
Wireless-Innovation-Forum/Spectrum-Access-System | src/harness/reference_models/pre_iap_filtering/inter_sas_duplicate_grant.py | Python | apache-2.0 | 2,583 | 0.00813 | # Copyright 2018 SAS Project Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | s is a subset of the pre-IAP reference model which implements inter-SAS
duplicate CBSD removal. If a CBSD has registered with multiple SASs then the
CBSD is removed from the FAD objects of the respective SASs.
"""
from __future__ import absolute_imp | ort
from __future__ import division
from __future__ import print_function
import logging
from collections import defaultdict
def interSasDuplicateGrantPurgeReferenceModel(sas_uut_fad, sas_test_harness_fads):
""" Removes CBSDs with grants from more than one SAS from FAD objects.
Checks if a CBSD is registered wi... |
lixxu/sanic | sanic/request.py | Python | mit | 11,420 | 0.000088 | import asyncio
import email.utils
import json
import sys
from cgi import parse_header
from collections import namedtuple
from http.cookies import SimpleCookie
from urllib.parse import parse_qs, unquote, urlunparse
from httptools import parse_url
from sanic.exceptions import InvalidUsage
from sanic.log import error_l... | if not | self.body:
return None
raise InvalidUsage("Failed when parsing body as json")
return self.parsed_json
@property
def token(self):
"""Attempt to return the auth header token.
:return: token related to request
"""
prefixes = ("Bearer", "Token"... |
srijannnd/Login-and-Register-App-in-Django | simplesocial/accounts/tokens.py | Python | mit | 375 | 0.008 | from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class AccountActivationTokenGenerator | (PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (six.text_type(user.pk) + six.text_type(timestamp)) + six.text_type(user.is_active)
account | _activation_token = AccountActivationTokenGenerator() |
mozilla/pto | pto/apps/dates/views.py | Python | mpl-2.0 | 37,380 | 0.00099 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
import traceback
from StringIO import StringIO
import re
import datetime
from urllib import urlencode
from co... | or hour in Hours.objects.filter(entry=entry):
if hour.hours == 8:
days += 1
elif hour.hours == 4:
days += 0.5
if days > 1:
if int(days) == days:
title += '%d days' % days
else:
title += '%s days' % days
if Hours.objects.filter(... | Hours.objects.filter(entry=entry, birthday=True)):
title += 'Birthday!'
elif days == 1 and entry.total_hours == 8:
title += '1 day'
else:
title += '%s hours' % entry.total_hours
if entry.details:
if days == 1:
max_length = 20
else:
max_l... |
fopina/django-holidays | holidays/tests.py | Python | mit | 1,476 | 0 | from django.test import TestCase
from .utils import is_holiday
from datetime import date, timedelta
class HolidaysTests(TestCase):
longMessage = True
fixtures = ['demo']
def fullYearTest(self, group, year, holidays):
it = date(year, 1, 1)
end = date(year, 12, 31)
delta = timedelta... | 5, 5, 1),
date(2015, 6, 10),
date(2015, 8, 15),
date(2015, 12, 8),
date(2015, 12, 25),
],
)
def testPortugalPorto2015(self):
self.fullYearTest(
'PT-PRT',
2015,
| [
date(2015, 1, 1),
date(2015, 4, 3),
date(2015, 4, 5),
date(2015, 4, 25),
date(2015, 5, 1),
date(2015, 6, 10),
date(2015, 6, 24),
date(2015, 8, 15),
date(2015, 12, 8... |
sfcta/synthpop | synthpop/synthesizer.py | Python | bsd-3-clause | 6,015 | 0.001829 | import logging
import sys
import traceback
from collections import namedtuple
import numpy as np
import pandas as pd
from scipy.stats import chisquare
from . import categorizer as cat
from . import draw
from .ipf.ipf import calculate_constraints
from .ipu.ipu import household_weights
logger = logging.getLogger("synt... | print traceback.format_exc()
# continue
return (pd.concat(hh_list) if len(hh_list) > 0 else None,
| pd.concat(people_list, ignore_index=True) if len(people_list) > 0 else None,
fit_quality)
|
sdeleeuw/contagement | videos/api/viewsets/video.py | Python | gpl-3.0 | 1,272 | 0 | from __future__ import unicode_literals
from rest_framework import viewsets
from rest_framework import permissions
from videos.api.serializers import video as video_serializers
from videos.models import Video
class VideoViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.DjangoModelPermissionsOrA... | video_serializers.RetrieveSerializer
return video_serializers.DefaultSerializ | er
def get_serializer_context(self):
context = super(VideoViewSet, self).get_serializer_context()
if self.request.method not in permissions.SAFE_METHODS \
and not self.request.user.is_superuser:
context['exclude'] = ('sites', )
return context
def perform_... |
pybursa/homeworks | s_shybkoy/hw1/hw1_task8_ShybkoiSergei.py | Python | gpl-2.0 | 162 | 0.018519 | #hw 1/ task8/ S | ergei Shybkoi
t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c')
print "Set:",t
print "Each third element:"
print t[2::3]
print | t[-1*len(t)+2:-1:3] |
yaroslavprogrammer/django-modeltranslation | modeltranslation/fields.py | Python | bsd-3-clause | 15,602 | 0.002628 | # -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.db.models import fields
from modeltranslation import settings as mt_settings
from modeltranslation.utils import (
get_language, build_localized_fieldname, build_localized_verbose_name, resolution_or... | There are 3 different formfields:
- CharField that stores all empty values as empty strings;
- NullCharField | that stores all empty values as None (Null);
- NullableField that can store both None and empty string.
By default, if no empty_values was specified in model's translation options,
NullCharField would be used if the original field is nullable, CharField otherwise.
This can be overridd... |
com4/py-editdist | test.py | Python | isc | 1,856 | 0.033405 | #!/usr/bin/env python
# Copyright (c) 2006 Damien Miller <[email protected]>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... | bc', 'ab', 1 ),
( 'abc', 'abcd', 1 ),
( 'abc', 'bc', 1 ),
( 'abc', 'a', 2 ),
( 'abc', '', 3 ),
( '', '', 0 ),
( 'abc', 'acx', 2 ),
( 'abc', 'acxx', 3 ),
( 'abc', 'bcd', 2 ),
( 'a' * 1000, 'a' * 1000, 0 ),
( 'a' * 1000, 'b' * 1000, 1000),
)
def randstring(l):
a = "abcdefghijklmnopqrstuvwxyz"
r =... | n test_vectors:
self.assertEqual(editdist.distance(a, b), score)
def test_01__reversed_test_vectors(self):
for b, a, score in test_vectors:
self.assertEqual(editdist.distance(a, b), score)
def test_02__fuzz(self):
for i in range(0, 32) + range(128, 1024, 128):
for j in range(0, 32):
a = randstring(... |
nuclear-wizard/moose | python/chigger/tests/wireframe/points.py | Python | lgpl-2.1 | 936 | 0.019231 | #!/usr/bin/env python3
#pylint: disable=missing-docstring
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
... | tFocalPoint(0.0000, 0.0000, 0.1250)
reader = chigger.exodus.ExodusReader('../input/mug_blocks_out.e')
mug = chigger.exodus.ExodusResult(reader, block=[76], representation='points', camera=camera, color=[0,1,0])
window = chigger.RenderWindow(mug, size=[300,300], test=True)
window.update();window.resetCamera() #TODO: Th... | ly, not sure why
window.write('points.png')
window.start()
|
google/syzygy | syzygy/build/gyp_main.py | Python | apache-2.0 | 3,560 | 0.009551 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | return item[len(needle):]
return 'out'
def apply_syzygy_gyp_env(syzygy_src_path):
if 'SKIP_SYZYGY_GYP_ENV' not in os.environ:
# Update the environment based on syzygy.gyp_env
path = os.path.join(syzygy_src_path, 'syzygy.gyp_env')
applied_env_from_file = apply_gyp_environment_from_file(path)
if (n... | fault to ninja if no generator has explicitly been set.
os.environ['GYP_GENERATORS'] = 'ninja'
if (not applied_env_from_file or not os.environ.get('GYP_MSVS_VERSION')):
os.environ['GYP_MSVS_VERSION'] = '2015'
if __name__ == '__main__':
# Get the path of the root 'src' directory.
self_dir = os.path... |
spiceqa/virt-test | qemu/tests/watchdog.py | Python | gpl-2.0 | 12,256 | 0.000408 | import logging
import re
import time
import os
from autotest.client.shared import error, utils
from virttest import utils_misc, env_process
@error.context_aware
def run_watchdog(test, params, env):
"""
Configure watchdog, crash the guest and check if watchdog_action occurs.
Test Step:
1. see every... | r or not the watchdog action occurred. if the action was
not occurred will raise error.
"""
# when watchdog action is pause, shutdown, re | set, poweroff
# the vm session will lost responsive
response_timeout = int(params.get("response_timeout", '240'))
error.context("Check whether or not watchdog action '%s' take effect"
% watchdog_action, logging.info)
if not utils_misc.wait_for(lambda: not session.is... |
iharsh234/MIT6.00x | pset6-P2-FindBestShift.py | Python | mit | 475 | 0 | def findBestShift(wordList, text):
text = "".join((char if char.isalpha() else " ") for char in text).split()
max_valid = 0
best_shift = 0
for shift in rang | e(26):
num_valid = 0
for word in text:
plaintext = applyShif | t(word, shift)
if isWord(wordList, plaintext):
num_valid += 1
if num_valid > max_valid:
max_valid = num_valid
best_shift = shift
return best_shift
|
StefanBruens/libsigrokdecode | decoders/rc_encode/pd.py | Python | gpl-3.0 | 6,428 | 0.007156 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2018 Steve R <[email protected]>
##
## 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... | : 'none',
'values': ('none', 'maplin_l95ar')},
)
def __init__(self):
self.reset()
def reset(self):
self.samplenumber_last = None
self.pulses = []
self.bits = []
self.labels = []
self.bit_count = 0
self.ss = None
self.es = None
... | self.put(self.ss, self.es, self.out_ann, data)
def decode(self):
while True:
pin = self.wait({0: 'e'})
self.state = 'DECODING'
if not self.samplenumber_last: # Set counters to start of signal.
self.samplenumber_last = self.samplenum
... |
franciscod/python-telegram-bot | telegram/parsemode.py | Python | gpl-2.0 | 1,054 | 0 | #!/usr/bin/env python
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public L... | .gnu.org/licenses/].
"""This module contains a object that represents a Telegram
Message Parse Modes."""
class ParseMode(object):
"""This object represents a Telegram Message Parse Modes."""
M | ARKDOWN = 'Markdown'
HTML = 'HTML'
|
sofianehaddad/ot-svn | python/test/t_BarPlot_std.py | Python | mit | 1,975 | 0.000506 | #! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
dim = 1
meanPoint = NumericalPoint(dim, 1.0)
meanPoint[0] = 0.5
sigma = NumericalPoint(dim, 1.0)
sigma[0] = 2.0
R = CorrelationMatrix(dim)... | , min1, "blue", "shaded", "dashed", "histogram1")
# Then, draw it
myGraph.add(myBarPlot1)
myGraph.draw("Graph_BarPlot_a_OT", 640, 480)
# Check that the correct files have been generated by computing their
# checksum
# Create the second barplot
myBarPlot2 = BarPlot(data2, min2, "red", "sol... | import sys
print "t_BarPlot_std.py", sys.exc_type, sys.exc_value
|
igor-rodrigues01/casv | casv/core/migrations/0010_auto_20150804_1030.py | Python | agpl-3.0 | 443 | 0.002257 | # -*- coding: utf-8 | -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0009_auto_20150729_1745'),
]
operations = [
migrations.AlterField(
model_name='areasoltura',
name='cpf',
... | )
]
|
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_PolyTrend/cycle_7/ar_/test_artificial_32_Anscombe_PolyTrend_7__0.py | Python | bsd-3-clause | 261 | 0.088123 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_data | set(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, | transform = "Anscombe", sigma = 0.0, exog_count = 0, ar_order = 0); |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/cr/crvserver_crpolicy_binding.py | Python | apache-2.0 | 7,634 | 0.037595 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | rn self._policyname
except Exception as e:
raise e
@policyname.setter
def policyname(self, policyname) :
ur""" | Policies bound to this vserver.
"""
try :
self._policyname = policyname
except Exception as e:
raise e
@property
def name(self) :
ur"""Name of the cache redirection virtual server to which to bind the cache redirection policy.<br/>Minimum length = 1.
"""
try :
return self._name
except Excepti... |
OSAlt/secret-santa | santa_lib/__init__.py | Python | mit | 559 | 0.003578 | __author__ = 'sfaci'
"""
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 distribut | ed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
""" |
Vagab0nd/SiCKRAGE | tests/notifier_tests.py | Python | gpl-3.0 | 9,061 | 0.002097 | """
Test notifiers
"""
import unittest
from sickchill.oldbeard import db
from sickchill.oldbeard.notifiers.emailnotify import Notifier as EmailNotifier
from sickchill.oldbeard.notifiers.prowl import Notifier as ProwlNotifier
from sickchill.tv import TVEpisode, TVShow
from sickchill.views.home import Home
from tests ... | show.saveToDB()
cls.shows.append(show)
def setUp(self):
"""
Set up tests
"""
self._debug_spew("\n\r")
@unittest.skip('Not yet im | plemented')
def test_boxcar(self):
"""
Test boxcar notifications
"""
pass
@unittest.skip('Cannot call directly without a request')
def test_email(self):
"""
Test email notifications
"""
email_notifier = EmailNotifier()
# Per-show-emai... |
OmnesRes/onco_lnc | lncrna/cox/COAD/patient_info.py | Python | mit | 6,839 | 0.021787 | ## A script for extracting info about the patients used in the analysis
## Load necessary modules
from rpy2 import robjects as ro
import numpy as np
import os
ro.r('library(survival)')
import re
##This call will only work if you are running python from the command line.
##If you are not running from the command line... | [i for i in new_clinical if i[1]>0]
final_clinical=[]
## A new list containing both follow up times and sex and age is constructed.
## Only patients with sex and age information are included.
## Data is [[Patient ID, time (days), vital status, 0, sex, age at diagnosis],...]
for i in clinic | al:
if i[0] in more_clinical:
final_clinical.append(i+more_clinical[i[0]])
##In a separate script I parsed the mitranscriptome.expr.counts.tsv file and extracted the COAD patient and expression values.
##From this file I will load the expression data.
##There are duplicated transcripts and the possibilit... |
Ultimaker/Uranium | UM/PluginObject.py | Python | lgpl-3.0 | 1,812 | 0.002208 | # Copyright (c) 2018 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Optional, Dict, Any
class PluginObject:
"""Base class for objects that can be provided by a plugin.
This class should be inherited by any class that can be provided
by a plugin. Its only ... | ) -> str:
result = self.getPluginId()
if self._name:
result += "_%s" % self._name
return result
def setPluginId(self, plugin_id: str) -> None:
self._plugin_id = plugin_id
# The metadata of the plugin is set at the moment it is loaded.
def setMetaData(self, m | etadata: Dict[str, Any]) -> None:
self._metadata = metadata
def getMetaData(self) -> Dict[str, Any]:
return self._metadata
def getPluginId(self) -> str:
if not self._plugin_id:
raise ValueError("The plugin ID needs to be set before the plugin can be used")
return se... |
maarons/pressui | cherrypy/server.py | Python | mit | 1,340 | 0.009701 | from cherrypy.process.plugins import PIDFile
import argparse
impo | rt cherrypy
from PressUI.cherrypy.PressConfig import PressConfig
import PressUI.cherrypy.PressProduction as PressProduction
parser = argparse.ArgumentParser()
parser.add_argument(
'--production',
help = 'Run app in production mode',
action = 'store_true',
)
parser.add_argument(
'--port',
help = 'R... | kstart(app, app_name, fun_callback = None):
args = parser.parse_args()
PressConfig.init(args.config)
if fun_callback is not None:
fun_callback()
cherrypy.config.update({
'server.socket_port': args.port,
'server.socket_host': '127.0.0.1',
'tools.gzip.on': True,
})
... |
aychedee/kubrick | kubrick/secrets.py | Python | isc | 333 | 0 | # copyright: (c) 2012 by Hansel Dunlop.
# license: ISC, see LICENSE for more details.
#
| # secret keys for virtual server providers
# Users of this package will need to add their
# keys to this file for it to work
#
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY | = ''
RACKSPACE_USERNAME = ''
RACKSPACE_API_KEY = ''
KEY_FILENAME = ''
|
digitalocean/netbox | netbox/extras/templatetags/plugins.py | Python | apache-2.0 | 2,412 | 0.001658 | from django import template as template_
from django.conf import settings
from django.utils.safestring import mark_safe
from extras.plugins import PluginTemplateExtension
from extras.registry import registry
register = template_.Library()
def _get_registered_content(obj, method, template_context):
"""
Given... | @register.simple_tag(takes_context=True)
def plugin_left_page(context, obj):
"""
Render all left page content registered by plugins
"""
| return _get_registered_content(obj, 'left_page', context)
@register.simple_tag(takes_context=True)
def plugin_right_page(context, obj):
"""
Render all right page content registered by plugins
"""
return _get_registered_content(obj, 'right_page', context)
@register.simple_tag(takes_context=True)
def ... |
Hemisphere-Project/Telemir-DatabitMe | Telemir-EEG/TeleMir_171013/Fake_TeleMir_CB.py | Python | gpl-2.0 | 6,881 | 0.034443 | # -*- coding: utf-8 -*-
"""
TeleMir developpement version with fake acquisition device
lancer dans un terminal :
python examples/test_osc_receive.py
"""
from pyacq import StreamHandler, FakeMultiSignals
from pyacq.gui import Oscilloscope, Oscilloscope_f, TimeFreq, TimeFreq2
from TeleMir.gui import Topoplot, Kurtosis... | ([])
# Impedances
w_imp=Topoplot_imp(stream = dev.streams[0], type_Topo= 'imp' | )
w_imp.show()
# freqbands
w_sp_bd=freqBandsGraphics(stream = dev.streams[0], interval_length = 3., channels = [12])
w_sp_bd.run()
# signal
w_oscilo=Oscilloscope(stream = dev.streams[0])
w_oscilo.show()
w_oscilo.set_params(xsize = 10, mode = 'scroll')
w_oscilo.auto_gain_... |
thomaslaurenson/Vestigium | dfxml/Objects.py | Python | gpl-2.0 | 127,176 | 0.005198 |
"""
This file re-creates the major DFXML classes with an emphasis on type safety, serializability, and de-serializability.
With this module, reading disk images or DFXML files is done with the parse or iterparse functions. Writing DFXML files can be done with the DFXMLObject.print_dfxml function.
"""
__version__ = ... | mes") or []
input_files = kwargs.get("files") or []
for v in input_volumes:
self.append(v)
for f in input_files:
self.append(f)
#Add default namespaces
self.add_namespace("", dfxml.XMLNS_DFXML)
self.add_namespace("dc", dfxml.XMLNS_DC)
def __i... | jects directly attached to this DFXMLObject, in that order."""
for v in self._volumes:
yield v
for f in v:
yield f
for f in self._files:
yield f
def add_namespace(self, prefix, url):
self._namespaces[prefix] = url
ET.register_names... |
rubendura/django-rest-framework | tests/test_response.py | Python | bsd-2-clause | 10,811 | 0.002312 | from __future__ import unicode_literals
from django.conf.urls import include, url
from django.test import TestCase
from django.utils import six
from rest_framework import generics, routers, serializers, status, viewsets
from rest_framework.renderers import (
BaseRenderer, BrowsableAPIRenderer, JSONRenderer
)
from... | uters.DefaultRouter()
new_model_viewset_router.register(r'', HTMLNewModelViewSet)
urlpatterns = [
url(r' | ^setbyview$', MockViewSettingContentType.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
url(r'^html$', HTMLView... |
adamtheturtle/flocker | flocker/dockerplugin/test/test_api.py | Python | apache-2.0 | 6,785 | 0.000147 | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Tests for the Volumes Plugin API provided by the plugin.
"""
from uuid import uuid4, UUID
from twisted.web.http import OK
from twisted.internet import reactor
from .._api import VolumePlugin, DEFAULT_SIZE
from ...apiclient import FakeFlockerClient, Datas... | self.assertResult(
b"PO | ST", b"/VolumeDriver.Mount",
{u"Name": name}, OK,
{u"Err": None,
u"Mountpoint": u"/flocker/{}".format(dataset_id)}))
d.addCallback(lambda _: self.flocker_client.list_datasets_state())
d.addCallback(lambda ds: self.assertEqual... |
kdyq007/cmdb-api | core/__init__.py | Python | gpl-2.0 | 299 | 0.003344 | # -*- coding:utf-8 -*-
from attribute i | mport attribute
from | ci_type import citype
from ci_type_relation import cityperelation
from ci_relation import cirelation
from ci import ci
from history import history
from account import account
from special import special
from dns_record import dnsrecord
|
Fokko/incubator-airflow | airflow/contrib/sensors/bigquery_sensor.py | Python | apache-2.0 | 1,138 | 0 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under | one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# t | o you 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 Lice... |
JohnGriffiths/ConWhAt | setup.py | Python | bsd-3-clause | 1,353 | 0.005913 | #!/usr/bin/env python
from setuptools import setup, find_packages
import versioneer
setup(name='conwhat', #version=versioneer.get_version(),
description='python library for connectome-based white matter atlas analyses in neuroimaging',
long_description='python library for connectome-based white matter at... | keywords='white ma | tter, tractography, MRI, DTI, diffusion, python',
author='John David Griffiths',
author_email='[email protected]',
url='https://github.com/JohnGriffiths/conwhat',
packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
install_requires=['numpy', 'setuptools... |
stweil/letsencrypt | certbot-compatibility-test/certbot_compatibility_test/util.py | Python | apache-2.0 | 1,520 | 0 | """Utility functions for Certbot plugin tests."""
import argparse
import copy
import os
import re
import shutil
import tarfile
import josepy as jose
from certbot._internal import constants
from certbot.tests import util as test_util
from certbot_compatibility_test import errors
_KEY_BASE = "rsa2048_key.pem"
KEY_PATH... | onfig_dir = os.path.join(parent_dir, "configs")
if os.path.isdir(configs): |
shutil.copytree(configs, config_dir, symlinks=True)
elif tarfile.is_tarfile(configs):
with tarfile.open(configs, "r") as tar:
tar.extractall(config_dir)
else:
raise errors.Error("Unknown configurations file type")
return config_dir
|
zjuchenyuan/BioWeb | Lib/Bio/NMR/NOEtools.py | Python | mit | 3,420 | 0.000877 | # Copyright 2004 by Bob Bussell. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""NOEtools: For predicting NOE coordinates from assignment data.
The input and output are model... | Nuc + ".P"] + 1
# Make a list of the data lines involving the detected
if str(toResNum) in peaklist.residue_dict(detectedNuc) \
and str(originResNum) in peaklist.residue_dict(detectedNuc):
detectedList = peaklist.residue_dict(detectedNuc)[str(toResNum)]
originList = peaklist.residue_dict(de... | (detectedList, detectedPPMCol)
aveOriginPPM = _col_ave(originList, originPPMCol)
originAss = originList[0].split()[originAssCol]
returnLine = xpktools.replace_entry(returnLine, originAssCol + 1, originAss)
returnLine = xpktools.replace_entry(returnLine, originPPMCol + 1, aveOrig... |
etherkit/OpenBeacon2 | macos/venv/lib/python3.8/site-packages/macholib/framework.py | Python | gpl-3.0 | 1,125 | 0 | """
Generic framework path manipulation
"""
import re
__all__ = ["framework_info"]
_STRICT_FRAMEWORK_RE = re.compile(
r"""(?x)
(?P<location>^.*)(?:^|/)
(?P<name>
(?P<shortname>[-_A-Za-z0-9]+).framework/
(?:Versions/(?P<version>[^/]+)/)?
(?P=shortname)
(?:_(?P<suffix>[^_]+))?
)$
"""
)
def framew... | work:
| return None
return is_framework.groupdict()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.