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 |
|---|---|---|---|---|---|---|---|---|
Tayamarn/socorro | socorro/unittest/external/postgresql/test_bugs.py | Python | mpl-2.0 | 4,325 | 0.001156 | # 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 pytest
from socorro.external.postgresql.bugs import Bugs
from socorro.lib import MissingArgumentError
from socor... | signature without bugs
params = {
"signatures": "unknown"
}
res = bugs.get(**params)
res_expected = {
"hits": [],
"total": 0
}
assert res == res_expected
# Test 4: missing argument
with pyt | est.raises(MissingArgumentError):
bugs.get()
# Test 5: search by bug_ids argument
params = {
"bug_ids": ["1", "2"]
}
res = bugs.get(**params)
# This is what we expect but because the results aren't sorted,
# we can't expect them to come in in thi... |
Arno-Nymous/pyload | module/plugins/accounts/EuroshareEu.py | Python | gpl-3.0 | 1,755 | 0.00114 | # -*- coding: utf-8 -*-
import re
import time
from ..internal.Account import Account
from ..internal.misc import json
class EuroshareEu(Account):
__name__ = "EuroshareEu"
__type__ = "account"
__version__ = "0.12"
__status__ = "testing"
__description__ = """Euroshare.eu account plugin"""
__l... | hare.eu/",
get={'lang': "en"})
m = re.search(
r'<span class="btn btn--nav green darken-3">Premium account until: (\d+/\d+/\d+ \d+:\d+:\d+)<',
html)
if m is None:
premium = False
validuntil = -1
else:
premium = ... | til = time.mktime(
time.strptime(
m.group(1),
"%d/%m/%Y %H:%M:%S"))
return {'validuntil': validuntil,
'trafficleft': -1, 'premium': premium}
def signin(self, user, password, data):
html = self.load("http://euroshare.eu/login.h... |
rarbg/ZeroNet | src/util/Event.py | Python | gpl-2.0 | 1,306 | 0.037519 | # Based on http://stackoverflow.com/a/2022629
class Event(list):
def __call__(self, *args, **kwargs):
for f in self[:]:
if "once" in dir(f) and f in self:
self.remove(f)
f(*args, **kwargs)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
def once(self, func, name=None):
func.once = ... | ppend(func)
return self
def testBenchmark():
def say(pre, text):
print "%s Say: %s" % (pre, text)
import time
s = time.time()
onChanged = Event()
for i in | range(1000):
onChanged.once(lambda pre: say(pre, "once"), "once")
print "Created 1000 once in %.3fs" % (time.time()-s)
onChanged("#1")
def testUsage():
def say(pre, text):
print "%s Say: %s" % (pre, text)
onChanged = Event()
onChanged.once(lambda pre: say(pre, "once"))
onChanged.once(lambda pre: say(pre,... |
jdanbrown/pydatalab | google/datalab/bigquery/commands/__init__.py | Python | apache-2.0 | 679 | 0.005891 | # Copyright 2015 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 agreed ... | either express
# or implied. See the License for the specific l | anguage governing permissions and limitations under
# the License.
from __future__ import absolute_import
from . import _bigquery
__all__ = ['_bigquery']
|
odrolliv13/Hex-Photos | shop/views/store_details.py | Python | apache-2.0 | 2,324 | 0.032702 | from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from shop import models as pmod
from . import templater
from django.conf import settings
import decimal, datetime
def process_request(request):
if not request.user.is_authenticate... | ned_data['street']
store.city = form.cleaned_data['city']
store.state = form.cleaned_data['state']
store.zipcode = form.cleaned_data['zipcode']
store.phone = form.cleaned_data['phone']
store.active = True
store.save()
return HttpResponseRedirect('/manager/stores') |
tvars = {
'form': form,
}
return templater.render_to_response(request, 'store_details.html', tvars)
class StoreForm(forms.Form):
locationName = forms.CharField(required=False, label='Location Name', widget=forms.TextInput(attrs={'class':'form-control'}))
street = forms.CharField(required=False, labe... |
filipenf/ansible | lib/ansible/plugins/connection/ssh.py | Python | gpl-3.0 | 29,029 | 0.002859 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | llows us to correctly catch failed transfers, but can
# be disabled if the client side doesn't support the option. However,
# sftp batch mode does no | t prompt for passwords so it must be disabled
# if not using controlpersist and using sshpass
if binary == 'sftp' and C.DEFAULT_SFTP_BATCH_MODE:
if self._play_context.password:
self._add_args('disable batch mode for sshpass', ['-o', 'BatchMode=no'])
self._command ... |
oleg-toporkov/python-bdd-selenium | core/decorators.py | Python | mit | 790 | 0.001266 | """
Created on September 18, 2015
@author: oleg-toporkov
"""
from functools import wraps
import logging
def log_exception(mess | age, logger=None):
"""
Decorator for function execution in try/except with first logging what tried to do and then raising an exception
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if logger is None:
_self = args[0] | # self
log = getattr(_self, 'logger')
else:
log = logger
assert isinstance(log, logging.Logger)
try:
return func(*args, **kwargs)
except Exception:
log.error(message.format(args[1]))
raise
... |
rleigh-dundee/openmicroscopy | components/tools/OmeroPy/test/gatewaytest/user.py | Python | gpl-2.0 | 6,878 | 0.002472 | #!/usr/bin/env python
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
... | .AUTHOR.name)
finally:
self.gateway.getUpdateService().deleteObject(ann._obj)
anns = self.gateway.getQueryService().findAllByQuery('from CommentAnnotation as a where a.ns=:ns', param)
self.assertEqual(len(anns), 0)
def testCrossGroupSave | (self):
self.loginAsUser()
uid = self.gateway.getUserId()
self.loginAsAdmin()
self.gateway.SERVICE_OPTS.setOmeroGroup('-1')
d = self.getTestDataset()
did = d.getId()
g = d.getDetails().getGroup()
admin = self.gateway.getAdminService()
admin.addGrou... |
ajpina/uffema | uffema/machines/synchronous.py | Python | apache-2.0 | 2,520 | 0.000397 | #!/usr/bin/python
# -*- coding: iso-8859-15 -*-
# ==========================================================================
# Copyright (C) 2016 Dr. Alejandro Pina Ortega
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ob... | ================================================
# Program: synchronous.py
# Author: ajpina
# Date: 12/23/16
# Version: 0.1.1
#
# Revision History:
# Date Version Author Description
# - 12/23/16: 0.1.1 ajpina Defines mandatory methods a | nd properties
#
# ==========================================================================
__author__ = 'ajpina'
from abc import abstractmethod
from uffema.machines import RotatingMachine
class Synchronous(RotatingMachine):
@property
@abstractmethod
def stator(self):
return 'Should never see... |
bsmr-eve/Pyfa | scripts/conversion.py | Python | gpl-3.0 | 23,244 | 0.007013 | # Developed for module tiericide, this script will quickly print out a market
# conversion map based on patch notes, as well as database conversion mapping.
import argparse
import os.path
import sqlite3
import sys
# Add eos root path to sys.path so we can import ourselves
path = os.path.dirname(str(__file__, sys.getf... | ontrol
'Gonzo' Damage Control I is bein | g converted to 'Radical' Damage Control
'Gonzo' Damage Control I Blueprint is being converted to 'Radical' Damage Control Blueprint
Emergency Damage Control I is being converted to IFFA Compact Damage Control
F85 Peripheral Damage System I is being converted to IFFA Compact Damage Control
Pseudoelectron Containment Fie... |
inveniosoftware/invenio-previewer | setup.py | Python | mit | 3,916 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio module for previewing files."""
import os
from setuptools import find_pa... | Language :: Python :: 3.6',
'Programming Language :: Python : | : 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Development Status :: 5 - Production/Stable',
],
)
|
eagleamon/home-assistant | homeassistant/components/notify/ios.py | Python | apache-2.0 | 3,679 | 0 | """
iOS push notification platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/ecosystem/ios/notifications/
"""
import logging
from datetime import datetime, timezone
import requests
from homeassistant.components import ios
import homeass... | targets = kwargs.get(ATTR_TARGET)
if not targets:
targets = ios.enabled_push_ids()
if kwargs.get(ATTR_DATA) is not None:
data[ATTR_DATA] = kwargs.get(ATTR_DATA)
for target in targets:
data[ATTR_TARGET] = target
req = requests.post(PUSH_URL, j... | fallback_error = req.json().get("errorMessage",
"Unknown error")
fallback_message = ("Internal server error, "
"please try again later: "
"{}").format(fallback_error)
... |
kayhayen/Nuitka | tests/syntax/GlobalForParameter.py | Python | apache-2.0 | 793 | 0 | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache Lice | nse, 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 | aw or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def f(a):
glob... |
explosion/spaCy | spacy/tests/doc/test_retokenize_merge.py | Python | mit | 18,955 | 0.001266 | import pytest
from spacy.attrs import LEMMA
from spacy.vocab import Vocab
from spacy.tokens import Doc, Token
def test_doc_retokenize_merge(en_tokenizer):
text = "WKRO played songs by the beach boys all night"
attrs = {
"tag": "NAMED",
"lemma": "LEMMA",
"ent_type": "TYPE",
"mor... | beach boys songs")
assert not any(token.is_stop for token in doc)
with doc.retokenize() as retokenizer:
retokenizer.merge(doc[2:4], attrs={"LEMMA": "boys", "IS_STOP": True})
assert doc[2].text == "beach boys"
assert doc[2].lemma_ == "boys"
assert doc[2].is_stop
new_doc = Doc(doc.vocab, w... | ["dep"] * len(heads)
tokens = en_tokenizer(text)
doc = Doc(tokens.vocab, words=[t.text for t in tokens], heads=heads, deps=deps)
assert len(doc) == 4
assert doc[0].head.text == "Angeles"
assert doc[1].head.text == "start"
with doc.retokenize() as retokenizer:
attrs = {"tag": "NNP", "lemm... |
quantumlib/Cirq | cirq-google/cirq_google/transformers/analytical_decompositions/two_qubit_to_sycamore.py | Python | apache-2.0 | 18,563 | 0.004902 | # Copyright 2022 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | an arbitrary 2 qubit operation to a Sycamore operation using the given Tabulation.
Args:
op: Operation to decompose.
tabulation: A `cirq.TwoQubitGateTabulation` for the Sycamore gate.
Yields:
A `cirq.OP_TREE` that performs the given operation using Sycamore operations.
"""
qub... | bits
result = tabulation.compile_two_qubit_gate(cirq.unitary(op))
local_gates = result.local_unitaries
for i, (gate_a, gate_b) in enumerate(local_gates):
yield from _phased_x_z_ops(gate_a, qubit_a)
yield from _phased_x_z_ops(gate_b, qubit_b)
if i != len(local_gates) - 1:
... |
gratipay/gratipay.com | tests/py/test_username_json.py | Python | mit | 3,211 | 0.003116 | # coding: utf8
from __future__ import print_function, unicode_literals
import json
from gratipay.testing import Harness
class Tests(Harness):
def change_username(self, new_username, auth_as='alice'):
if auth_as:
self.make_participant(auth_as, claimed_time='now')
r = self.client.POS... | gent: *\nDisallow: /*.json\nDisallow: /on/*\n'
def test_unavailable(self):
self.make_participant("bob")
code, body = self.change_username("bob")
assert code == 400
assert body['error_message_long'] == "The username 'bob' is already taken."
def test_too_l | ong(self):
username = "I am way too long, and you know it, and the American people know it."
code, body = self.change_username(username)
assert code == 400
assert body['error_message_long'] == "The username '%s' is too long." % username
|
icedtrees/unsw-lecture-times | scraper/scraper.py | Python | mit | 2,622 | 0.00267 | """ Original python command-line scraper for UNSW lecture times. Unused in the webapp. """
import re
import sys
from collections import Counter
import requests
SEMESTER = "15s2"
BASE_URL = "http://www.cse.unsw.edu.au/~teachadmin/lecture_times/" + SEMESTER
DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday... | rses):
courses = []
for arg in user_courses:
if len(arg) == 4:
courses += get_courses(arg)
elif len(arg) == 8:
courses.append('{}/{}.html'.format(arg[:4], arg[4:]))
else:
print("Invalid argument: {}".format(arg))
table_texts = {}
for course in... | ormat(BASE_URL, course))
if response.status_code == 200:
table_match = re.search(r'<table border=1.*?>(.*?)</table>', response.text, re.DOTALL)
table_texts[course] = table_match.group(1)
else:
print("Could not find course {}".format(course))
tables = {}
for c... |
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_sn_status_registered.py | Python | mit | 3,849 | 0.003378 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.sn/status_registered
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse ... | tetime')
eq_(self.record.created_on, time_parse('2008-05-08 17:59:38.43'))
def test_registrar(self):
eq_(self.record.registrar.__class__.__name__, 'Registrar')
eq_(self.record.registrar.id, "registry")
eq_(self.record.registrar.name, | "registry")
def test_registrant_contacts(self):
eq_(self.record.registrant_contacts.__class__.__name__, 'list')
eq_(len(self.record.registrant_contacts), 1)
eq_(self.record.registrant_contacts[0].__class__.__name__, 'Contact')
eq_(self.record.registrant_contacts[0].type, yawhois.rec... |
DedMemez/ODS-August-2017 | coghq/CashbotMintGearRoom_Action00.py | Python | apache-2.0 | 7,793 | 0.001412 | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.coghq.CashbotMintGearRoom_Action00
from panda3d.core import Point3, Vec3
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'... | 'goon',
'value': '10'},
10002: {'type': 'goon',
'name': '<unnamed>',
'comment': '',
'parentEntId': 10001,
'pos': Point3(0.0, 0.0, 0.0),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': 1.5,
'attackR | adius': 15,
'crushCellId': None,
'goonType': 'pg',
'gridId': None,
'hFov': 70,
'strength': 10,
'velocity': 4.0},
10004: {'type': 'goon',
'name': '<unnamed>',
'comment': '',
'parentEntId': 10003,
'pos': Point3(0.0, 0.0,... |
threefoldfoundation/app_backend | plugins/tff_backend/handlers/cron.py | Python | bsd-3-clause | 4,468 | 0.001119 | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... | payload=json.dumps(request),
method=urlfetch.POST,
| deadline=60,
headers=headers) # type: urlfetch._URLFetchResult
if result.status_code == httplib.OK:
logging.info(result.content)
else:
logging.error(result.content)
self.response.sta... |
Telestream/telestream-cloud-python-sdk | telestream_cloud_qc_sdk/telestream_cloud_qc/models/black_frame_test.py | Python | mit | 24,026 | 0.000375 | # coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class... | max_time_allowed is not None:
self.max_time_allowed = max_time_allowed
if max_time_allowed_secs_or_frames is not None:
self.max_time_allowed_secs_or_frames = max_time_allowed_secs_or_frames
if max_time_at_start is not None:
self.max_time_at_start = max_time_at_start |
if max_time_allowed_at_start is not None:
self.max_time_allowed_at_start = max_time_allowed_at_start
if max_time_allowed_at_start_secs_or_frames is not None:
self.max_time_allowed_at_start_secs_or_frames = max_time_allowed_at_start_secs_or_frames
if max_time_at_end is no... |
kosgroup/odoo | odoo/fields.py | Python | gpl-3.0 | 100,758 | 0.001965 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
""" High-level objects for fields. """
from collections import OrderedDict, defaultdict
from datetime import date, datetime
from functools import partial
from operator import attrgetter
from types import NoneType
import... | me(DATE_FORMAT))
DATETIME_LENGTH = len(datetime.now().strftime(DATETIME_FORMAT))
EMPTY_DICT = frozendict()
RENAMED_ATTRS = [ | ('select', 'index'), ('digits_compute', 'digits')]
_logger = logging.getLogger(__name__)
_schema = logging.getLogger(__name__[:-7] + '.schema')
Default = object() # default value for __init__() methods
class SpecialValue(object):
""" Encapsulates a value in the cache in place of a normal val... |
jhoenicke/python-trezor | trezorlib/tests/device_tests/test_msg_verifymessage.py | Python | lgpl-3.0 | 8,390 | 0.002145 | # This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | le of a signed message!",
)
assert res is False
def test_message_verify_bcash(self):
self.setup_mnemonic_nopin_nopassphrase()
res = btc.verify_message(
self.client,
"Bcash",
"bitcoincash:qqj22md58nm09vpwsw82fyletkxkq36zxyxh322pru",
byt... | "209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80"
),
"This is an example of a signed message.",
)
assert res is True
def test_verify_bitcoind(self):
self.setup_mnemonic_nopin... |
florian-f/sklearn | examples/ensemble/plot_adaboost_multiclass.py | Python | bsd-3-clause | 3,612 | 0.002215 | """
=====================================
Multi-class AdaBoosted Decision Trees
=====================================
This example reproduces Figure 1 of Zhu et al [1] and shows how boosting can
improve prediction accuracy on a multi-class problem. The classification
dataset is constructed by taking a ten-dimensional ... | (132)
pl.plot(n_trees, bdt_discrete.estimator_errors_, "b", label='SAMME', alpha=.5)
pl.plot(n_trees, bdt_real.estimator_errors_, "r", label='SAMME.R', alpha=.5)
pl.legend()
pl.ylabe | l('Error')
pl.xlabel('Number of Trees')
pl.ylim((.2,
max(bdt_real.estimator_errors_.max(),
bdt_discrete.estimator_errors_.max()) * 1.2))
pl.xlim((-20, len(bdt_discrete) + 20))
pl.subplot(133)
pl.plot(n_trees, bdt_discrete.estimator_weights_, "b", label='SAMME')
pl.legend()
pl.ylabel('Weight')
pl.xl... |
apagac/robottelo | tests/foreman/ui/test_sso.py | Python | gpl-3.0 | 10,139 | 0.000197 | # -*- encoding: utf-8 -*-
"""Test class for installer (UI)"""
from robottelo.common.decorators import stubbed
from robottelo.test import UITestCase
class TestSSOUI(UITestCase):
# Notes for SSO testing:
# Of interest... In some test cases I've placed a few comments prefaced
# with "devnote:" These are -- ... | (basic) that has rights assigned
@ | feature: SSO
@setup: assure SSO with kerberos is set up.
@steps:
1. attempt to login using a kerberos ID
@assert: Log in to foreman UI successfully and can access functional
areas in UI
@status: Manual
"""
@stubbed()
def test_sso_kerberos_user_disab... |
amith01994/intellij-community | python/testData/intentions/afterReturnTypeInNewGoogleDocString.py | Python | apache-2.0 | 68 | 0.029412 | d | ef f(x):
"""
Returns:
object:
"" | "
return 42 |
BeTeK/EliteMerchant | src/ui/GuideTab.py | Python | bsd-3-clause | 615 | 0.003252 |
import ui.GuideTabUI
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QVariant
import ui.TabAbstract
class GuideTab(ui.GuideTabUI.Ui_Dialog, QtWidgets.QWidget, ui.TabAbstract.TabAbstract):
def __init__(self, db, analyzer, tabName, | mainWindow):
super(QtWidgets.QWidget, self).__init__()
self.setupUi(self)
self.mainWindow = mainWindow
self.tabName = tabName
def setTabName(self, name):
self.tabName = name
def getType(self):
return "guide"
def getTabName(self):
r | eturn "User Guide"
def dispose(self):
pass
|
Basic-Components/auth-center | auth-center/App/auth/login_agents.py | Python | mit | 533 | 0 | from App.model import UserAgents
async def agent_save(reques | t, user):
ua = request.headers['User-Agent']
now = datetime.datetime.now()
uas = [await i for i in user.ips]
if ua in [i.content for i in contents]:
ua_in = [i for i in uas if i.content == content][0]
ua_in.utime = now
ua_in.count += 1
await ip_in.save()
else:
... | {
"content": ua,
'ctime': now,
'utime': now,
'user': user
}])
|
pymagic-org/pymagic_driver | bmp180.py | Python | mit | 5,278 | 0.010421 | import pyb
from struct import unpack as unp
# BMP180 default address
BMP180_I2CADDR = 0x77
# Operating Modes
BMP180_ULTRALOWPOWER = 0
BMP180_STANDARD = 1
BMP180_HIGHRES = 2
BMP180_ULTRAHIGHRES = 3
# BMP180 Registers
BMP180_CAL_AC1 = 0xAA
BMP180_CAL_AC2 = 0xAC
BMP180_... | titude(self, sealevel_pa = 101325.0):
"""Calculates the altitude in meters."""
#Calculation taken straight from section 3 | .6 of the datasheet
pressure = float(self.read_pressure())
altitude = 44330.0 * (1.0 - pow(pressure / sealevel_pa, (1.0 /5.255)))
return altitude
def read_sealevel_pressure(self, altitude_m=0.0):
"""Calculates the pressure at sealevel when given a know
altitude in meters. ... |
ajillion-by-crossrider/ajillion-rpc-client | rpcclient/test/test_with_httpretty.py | Python | apache-2.0 | 17,368 | 0.001036 | import concurrent
from concurrent.futures._base import Future
import json
from threading import Barrier
import time
import unittest
import requests_mock
from rpcclient.client import RpcClient
from rpcclient.deserialize import DictDeserializer
from rpcclient.exceptions import RemoteFailedError
from rpcclient.handlers im... | sts_mock.mock()
def test_get_second_level_method(self, mock):
mock.register_uri('POST', "http://server/api/", status_code=200, json=insert_id(
{"error": None, "jsonrpc": "2.0", "id": {},
"result": {"report": "success"}}),
)
self.client.test.level2(a... | request_history[-1].json()
self.assertRegex(request['jsonrpc'], '2.0')
self.assertRegex(request['method'], 'test.level2')
self.assertIn('token', request['params'])
self.assertRegex(request['params']['token'], 'yea')
self.assertIn('arg1', request['params'])
self.assertRege... |
miurahr/translate | translate/convert/test_po2prop.py | Python | gpl-2.0 | 17,884 | 0.001626 | from io import BytesIO
from translate.convert import po2prop, test_convert
from translate.storage import po
class TestPO2Prop:
def po2prop(self, posource):
"""helper that converts po source to .properties source without requiring files"""
inputfile = BytesIO(posource.encode())
inputpo = p... | propexpected
def test_mozilla_all_whitespace(self):
"""
Check for all white-space Mozilla hack, | remove when the corresponding code
is removed.
"""
posource = """#: accesskey-accept
msgctxt "accesskey-accept"
msgid ""
msgstr " "
#: accesskey-help
msgid "H"
msgstr "م"
"""
proptemplate = """accesskey-accept=
accesskey-help=H
"""
propexpected = """accesskey-accept=
accesskey-... |
mfranczy/prototype | src/leappto/actor_cli.py | Python | lgpl-2.1 | 10,539 | 0.004175 | import logging
import os
import subprocess
import sys
import tempfile
from argparse import ArgumentParser
from contextlib import contextmanager
import argcomplete
import signal
from snactor import loader
from snactor import registry
ACTOR_DIRECTORY = '/usr/share/leapp/actors'
SCHEMA_DIRECTORY = '/usr/share/leapp/sch... | action="store_true")
migrate_cmd.add_argument('machine', help='source machine to migrate')
migrate_cmd.add_argument('-t', '--target', default='localhost', help='target VM name')
migrate_cmd.add_argument(
'--tcp-port',
default=None,
dest="forwarded_tcp_ports",
... | dd_argument(
'--no-tcp-port',
default=None,
dest="excluded_tcp_ports",
nargs='*',
type=_port_spec,
help='define tcp ports which will be excluded from the mapped ports [[target_port]:source_port>]'
)
migrate_cmd.add_argument(
'--exclude-path',
defa... |
openearth/delft3d-gt-server | delft3dworker/migrations/0051_auto_20160825_0935.py | Python | gpl-3.0 | 438 | 0 | # -*- coding: utf-8 -*-
| from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("delft3dworker", "0050_auto_20160825_0934"),
]
operations = [
migrations.AlterField(
model_name="container",
name="docker_id"... |
),
]
|
JMSkelton/Transformer | Transformer/Framework/Utilities.py | Python | gpl-3.0 | 9,340 | 0.013383 | # Transfomer/Framework/Utilities.py
# ----------------
# Module Docstring
# ----------------
""" Utilities for (re)processing sets of structures in parallel. """
# -------
# Imports
# -------
import multiprocessing;
from Transformer import StructureSet;
from Transformer.Utilities import MultiprocessingHelper;
... | y routine.
return MergeStructureSets(
structureSets, useMP = True, mpNumProcesses = mpNumProcesses, pr | intProgressUpdate = printProgressUpdate, inPlace = True
);
else:
# Serial code path.
return StructureSet.StructureSet(
structures = structures, degeneracies = degeneracies, **kwargs
);
# Helper class for grouping a list of structures into sets.
class _Structur... |
sultan99/online | ONode/Tools/test.py | Python | apache-2.0 | 42,584 | 0.015687 | #!/usr/bin/env python
#
# Copyright 2008 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# noti... | self | .lock.release()
def EscapeCommand(command):
parts = []
for part in command:
if ' ' in part:
# Escape spaces. We may need to escape more characters for this
# to work properly.
parts.append('"%s"' % part)
else:
parts.append(part)
return " ".join(parts)
class SimpleProgressIndic... |
numa-engineering/python-daemon | daemon/runner.py | Python | gpl-2.0 | 7,204 | 0 | # -*- coding: utf-8 -*-
# daemon/runner.py
# Part of python-daemon, an implementation of PEP 3143.
#
# Copyright © 2009–2010 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2007–2008 Robert Niederreiter, Jens Klein
# Copyright © 2003 Clark Evans
# Copyright © 2002 Noah Spurrier
# Copyright © 2001 Jürgen Hermann
... | uffering=0)
self.daemon_context.stderr = open(
app.stderr | _path, 'wb+', buffering=0)
self.pidfile = None
if app.pidfile_path is not None:
self.pidfile = make_pidlockfile(
app.pidfile_path, app.pidfile_timeout)
self.daemon_context.pidfile = self.pidfile
def _usage_exit(self, argv):
""" Emit a usage message, then... |
NotAGameDev/website | website/migrations/0008_auto_20170422_1629.py | Python | agpl-3.0 | 448 | 0 | # -*- coding: utf-8 -*-
# Generated b | y Django 1.10.6 on 2017-04-22 16:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0007_auto_20170422_1622'),
]
operations = [
migrations.AlterField(
model_name='user',
... | 256),
),
]
|
rtucker-mozilla/mozpackager | vendor-local/lib/python/kombu/utils/compat.py | Python | bsd-3-clause | 4,371 | 0.002745 | """
kombu.utils.compat
==================
Helps compatibility with older Python versions.
"""
############## py3k #########################################################
import sys
is_py3k = sys.version_info[0] == 3
if is_py3k: # pragma: no cover
from io import StringIO, BytesIO... | stat[ST_INO]
def emit(self, record):
"""
Emit a record.
| First check if the underlying file has changed, and if it
has, close the old stream and reopen the file to get the
current stream.
"""
if not os.path.exists(self.baseFilename):
stat = None
changed = 1
... |
aronsky/home-assistant | homeassistant/components/forked_daapd/media_player.py | Python | apache-2.0 | 30,898 | 0.000874 | """This library brings support for forked_daapd to Home Assistant."""
import asyncio
from collections import defaultdict
import logging
from pyforked_daapd import ForkedDaapdAPI
from pylibrespot_java import LibrespotJavaAPI
from homeassistant.components.media_player import MediaPlayerEntity
from homeassistant.compone... | == 0:
return
self._last_volume = self.volume_level # store volume level to restore later
target_volume = 0
else:
target_volume = self._last_volume # restore volume level
await self.async_set_volume_level(volume=target_volume)
async def async_se... | utput_id=self._output_id)
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORTED_FEATURES_ZONE
class ForkedDaapdMaster(MediaPlayerEntity):
"""Representation of the main forked-daapd device."""
def __init__(
self, clientse... |
yamaguchiyuto/icwsm15 | tag_follow_disagreement.py | Python | mit | 857 | 0.005834 | import sys
tagging_filepath = sys.argv[1]
following_filepath = sys.argv[2]
delim = '\t'
if len(sys.argv) > 3:
delim = sys.argv[3]
graph = {}
for line in open(tagging_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if not src in graph: graph[src] = {}
graph[src][dst]... | ph[src]:
graph[src][dst] += 1
if dst in graph and src in graph[dst]:
graph[dst][src] += 2
w_dir = 0
wo_dir = 0
count = 0.0
for src in graph:
for dst in graph[src]:
val = graph[src][dst]
count += 1
if val in [1,3]:
w_dir += 1
if val in [1,2,3]:
... | "%s\t%s" % (w_dir/count, wo_dir/count)
|
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/synthesizer/gui/default_census_cat_transforms.py | Python | gpl-2.0 | 42,838 | 0.00845 | # PopGen 1.1 is A Synthetic Population Generator for Advanced
# Microsimulation Models of Travel Demand
# Copyright (C) 2009, Arizona State University
# See PopGen/License
DEFAULT_PERSON_PUMS2000_QUERIES = [ "alter table person_pums add column agep bigint",
"alter table person_pu... | loyment = 3 where esr = 3",
"update person_pums set employment = 4 wher | e esr = 6",
"drop table person_sample",
"create table person_sample select state, pumano, hhid, serialno, pnum, agep, gender, race, employment, relate from person_pums",
"alter table person_sample add index(serialno, pnum... |
GNOME/pygtkimageview | tests/demo03.py | Python | lgpl-2.1 | 645 | 0.003101 | '''
Shows how to load SVG files in gtkimageview. It is really easy.
'''
imp | ort gtk
from gtk import gdk
import gtkimageview
import sys
try:
import rsvg
except ImportError:
print 'Sorry! rsvg is needed to run this demo.'
sys.exit(1)
try:
handle = rsvg.Handle(sys.argv[1])
except IndexError:
print 'Usage: %s SVG-image' % sys.argv[0]
sys.exit(1)
pixbuf = handle.get_p... | uit)
win.add(gtkimageview.ImageScrollWin(view))
win.set_default_size(400, 300)
win.show_all()
gtk.main()
|
jdfekete/progressivis | tests/__init__.py | Python | bsd-2-clause | 2,610 | 0.000383 | from __future__ import annotations
from os import getenv
import gc
import sys
from unittest import TestCase, main
from unittest import skip as skip
from unittest import skipIf as skipIf
import logging
from progressivis import Scheduler, log_level
from progressivis.storage import init_temp_dir_if, cleanup_temp_dir
imp... | l:
print(f"Logger level {level} for {self}", file=sys.stderr)
self.log(int(level))
@staticmethod
def terse(x: Any) -> None:
_ = x
print(".", end="", file=sys.std | err)
@staticmethod
async def _stop(scheduler: Scheduler, run_number: int) -> None:
await scheduler.stop()
def setUp(self) -> None:
np.random.seed(42)
def tearDown(self) -> None:
# print('Logger level for %s back to ERROR' % self, file=sys.stderr)
# self.log()
g... |
pypa/virtualenv | src/virtualenv/seed/embed/via_app_data/via_app_data.py | Python | mit | 6,032 | 0.002155 | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import sys
import traceback
from contextlib import contextmanager
from subprocess import CalledProcessError
from threading import Lock, Thread
from virtualenv.in | fo import fs_supports_symlink
from virtualenv.seed.embed.base_embed import BaseEmbed
from virtualenv.seed.wheels import get_wheel
from virtualenv.util.path import Path
from .pip_install.copy import CopyPipInstall
from .pip_install.symlink import SymlinkPipInstall
class FromAppData(BaseEmbed):
def __init__(self, ... | :
super(FromAppData, self).__init__(options)
self.symlinks = options.symlink_app_data
@classmethod
def add_parser_arguments(cls, parser, interpreter, app_data):
super(FromAppData, cls).add_parser_arguments(parser, interpreter, app_data)
can_symlink = app_data.transient is False ... |
ijzer/cwbot-ndy | kol/request/BountyHunterRequest.py | Python | bsd-3-clause | 3,005 | 0.007987 | from kol.database import ItemDatabase
from kol.manager import PatternManager
from kol.request.GenericRequest import GenericRequest
class BountyHunterRequest(GenericRequest):
"""Interacts with the Bounty Hunter Hunter in the Forest Village."""
VISIT = None
ACCEPT_BOUNTY = 'takebounty'
ABANDON_BOUNT... | bountyAvaila | ble = False
bountyChosenPattern = PatternManager.getOrCompilePattern('bountyChosen')
bountyActivePattern1 = PatternManager.getOrCompilePattern('bountyActive1')
bountyActivePattern2 = PatternManager.getOrCompilePattern('bountyActive2')
if bountyChosenPattern.search(self.response... |
benjiyamin/nimbus | nimbus/network/links/weir.py | Python | gpl-2.0 | 4,270 | 0.004215 | import math
from .link import Link
from nimbus.reports import report as rp
from nimbus.reports import input as inp
from nimbus.network.links.sections import circle as cir
from nimbus.network.links.sections import rectangle as rct
class Weir(Link):
def __init__(self, name=None, section=None, orif_coef... | if stage1 > self.invert: # submerged flow
flow *= 1.0 - pow(pow(stage1 / stage2, 1.5), | 0.385)
else:
flow = 0.0
return flow
def get_input_strings(self):
if self.section:
shape_type = rp.property_to_string(self.section.__class__, '__name__')
shape_span = rp.float_to_string(self.section.span, 3)
shape_rise = rp.fl... |
google-research/meta-dataset | meta_dataset/data/tfds/api.py | Python | apache-2.0 | 9,094 | 0.004728 | # coding=utf-8
# Copyright 2022 The Meta-Dataset Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | interleave_cycle_length=builder.info.splits[
f'all_classes[{st | art}:{stop}]'].num_shards,
interleave_block_length=4,
enable_ordering_guard=False
)
return builder.as_full_ways_dataset(
md_version=md_version,
meta_split=meta_split,
shuffle_files=shuffle_files,
read_config=read_config,
**as_dataset_kwargs
)
def meta_dataset(
md_so... |
Th3l5D/lsbot | default.py | Python | mit | 5,164 | 0.004841 | import socket
import plugin
import ssl
import user
import os
class bot(object):
def __init__(self, server):
self.server = server
self.port = 6667
self.ssl = None
self.channels = []
self.connectedChannels = []
self.nick = 'default_nick'
self.realName = 'defau... | mmand'] = datas[0]
if datas_dict['command'].isdigit():
# numeric commands are server response and don't follow any logic. annoying :/
# so we just put the whole line into content. Parsing is done in functions
datas_dict['content'] = datas[1]
else:
splited = datas[... | t'] = splited[1]
else:
datas_dict['to'], datas_dict['content'] = splited[0].split(' ', 1)
return datas_dict
def parseLine(self, line):
self.debug(line)
datas = self.splitLine(line)
self.debug(datas)
if datas['command'].lower() in self.allowedCom... |
ack8006/hapipy | hapi/nurturing.py | Python | apache-2.0 | 890 | 0.01236 | from base import BaseClient
NURTURING_API_VERSION = '1'
class NurturingClient(BaseClient):
def _get_path(self, subpath):
return 'nurture/v%s/%s' % (NURTURING_API_VERSION, subpath)
def get_campaigns(self, **options):
return self._call('campaigns', **options)
def get_leads(self,... | re | turn self._call('campaign/%s/remove' % campaign_guid, data=lead_guid, method='POST', **options)
|
untergeek/es_stats_zabbix | es_stats_zabbix/backend/stat.py | Python | apache-2.0 | 1,693 | 0.002363 | """
Stat module for flask_restful
"""
import json
import logging
from dotmap import DotMap
from flask import request
from flask_restful import Resource
from es_stats_zabbix.exceptions import EmptyResult
from es_stats_zabbix.helpers.utils import status_map
class Stat(Resource):
"""Stat Resource class for flask_res... | st decode to 'utf-8' for older versions of Python
json_data = json.loads(request.data.decode('utf-8'))
node = json_data['node'] if 'node' in json_data else None
self.lo | gger.debug('Node = {0} -- key = {1}'.format(node, key))
result = self.statobj.get(key, name=node)
# Remap for `status`
if key == 'status':
result = status_map(result)
if result == DotMap():
return {'message':'ZBX_NOTFOUND'}, 404
if str(result).strip().lowe... |
piratf/Game_Boxes | lib/div.py | Python | gpl-3.0 | 404 | 0.014851 | # -*- coding: utf-8 -*
# Filename: div.py
|
__author__ = 'Piratf'
from pygame.locals import *
import pygame
class Div(object):
"""small panel in the frame"""
def __init__(self, (width, height), (x, y) = (0, 0)):
# super(Div, self).__init__()
self.width = width
self.height = height
self.x = x;
self.y = y;
... | h, height)) |
JulyKikuAkita/PythonPrac | cs15211/SearchinRotatedSortedArray.py | Python | apache-2.0 | 6,100 | 0.003443 | __source__ = 'https://leetcode.com/problems/search-in-rotated-sorted-array/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/search-in-rotated-sorted-array.py
# Time: O(logn)
# Space: O(1)
# Binary Search
#
# Description: Leetcode # 33. Search in Rotated Sorted Array
#
# Suppose a sorted array is rotated at ... | t's say 7, then we adjust nums to this:
[-inf, -inf, -inf, -inf, | -inf, -inf, -inf, -inf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
And then we can simply do ordinary binary search.
# 10ms 24.16%
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right... |
mrambausek/PPFem | ppfem/elements/lagrange_elements.py | Python | gpl-3.0 | 3,551 | 0.002816 | # PPFem: An educational finite element code
# Copyright (C) 2015 Matthias Rambausek
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | nction!
if self._dimension == 1:
return np.dot(self.basis_function_gradients | (point, jacobian_inv=jacobian_inv).reshape(dof_values.shape).T,
dof_values)
elif self.space_dim() > 1:
return np.einsum('ijk,ijkl->jkl',
dof_values,
self.basis_function_gradients(point, jacobian_inv=jacobian_inv))
... |
lankier/brigantina | runserver.py | Python | gpl-3.0 | 400 | 0.006135 | #!/usr/bin/env | python
# -*- mode: python; coding: utf-8; -*-
import sys, os
# для доступа к файлам данных меняем каталог на тот,
# в котором лежит скрипт запуска
dir = os.path.dirname(os.path.abspath(__file__))
os.chdi | r(dir)
from brigantina import code
# поехали!
code.webapp.run() # stand alone server
|
OssecTN/codejam-2014 | python/magic_trick/__init__.py | Python | gpl-2.0 | 251 | 0.007968 | #!/usr/bin/env python
__version__ = "0.1.0"
__date__ = "2014- | 04-11 1:42:05"
__author__ = "Dhia Abbassi"
__email__ = "dhiaabbassi90@gmail.com"
__license__ = "GPL"
__maintainer__ = ""
__doc__=""" Snip | pet of code that solves <Problem A. Magic Trick> """ |
Hybrid-Cloud/cinder | cinder/volume/drivers/netapp/eseries/library.py | Python | apache-2.0 | 92,586 | 0.000032 | # Copyright (c) 2015 Alex Meade
# Copyright (c) 2015 Rushil Chugh
# Copyright (c) 2015 Navneet Singh
# Copyright (c) 2015 Yogesh Kshirsagar
# Copyright (c) 2015 Jose Porrua
# Copyright (c) 2015 Michael Price
# Copyright (c) 2015 Tom Barron
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (t... | napshots per snapshot group
MAX_SNAPSHOT_COUNT = 32
# | Maximum number of snapshot groups
MAX_SNAPSHOT_GROUP_COUNT = 4
RESERVED_SNAPSHOT_GROUP_COUNT = 1
SNAPSHOT_PERSISTENT_STORE_KEY = 'cinder-snapshots'
SNAPSHOT_PERSISTENT_STORE_LOCK = str(uuid.uuid4())
def __init__(self, driver_name, driver_protocol="iSCSI",
configuration=None, **kwar... |
bwinton/svg-magic | magic.py | Python | mpl-2.0 | 14,704 | 0.000272 | #! /usr/bin/env python
# coding=utf-8
import argparse
from clint.textui.colored import red, green, blue
from clint.textui import progress
import copy
import csv
import io
from lxml import etree
import os
import subprocess
import sys
from time import sleep
SPRITESHEET_SVG = io.BytesIO('''<?xml version="1.0" encoding=... | def __str__(self):
| rv = 'Spritesheet<' + self.name
if self.isTheme:
rv += ':theme'
rv += '>'
return rv
def __repr__(self):
return self.__str__()
def addImage(self, image):
self.images.append(image)
def loadStyle(self, style):
data = open(style).read()
ret... |
denz/geophys | gnss/data/satellite.py | Python | gpl-3.0 | 1,759 | 0.000569 | from gnss.base import Blocks, BlocksRegistry
__all__ = []
# | class RinexD(Blocks, metaclass=BlocksRegistry):
# '''Hatanaka compressed GNSS observation'''
# @classmethod
# def valid_filetype(self, src):
# return src.endswith('.rinex-d')
# class RinexN(Blocks, metaclass=BlocksRegistry):
# '''GPS navigation file'''
# @classmethod
# def valid_filetyp... | ''GLONASS navigation file'''
# @classmethod
# def valid_filetype(self, src):
# return src.endswith('.rinex-g')
# class RinexL(Blocks, metaclass=BlocksRegistry):
# '''Galileo navigation file'''
# @classmethod
# def valid_filetype(self, src):
# return src.endswith('.rinex-l')
# class... |
androidx/androidx | leanback/leanback/generatef.py | Python | apache-2.0 | 6,367 | 0.007068 | #!/usr/bin/env python
# Copyright (C) 2017 The Android Open Source Project
#
# 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... | ite(content)
outfil | e.close()
|
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/scipy/odr/odrpack.py | Python | gpl-3.0 | 41,283 | 0.000654 | """
Python wrappers for Orthogonal Distance Regression (ODRPACK).
Notes
=====
* Array formats -- FORTRAN stores its arrays in memory column first, i.e. an
array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,
NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For
ef... | problems.appe | nd('N < 1')
if I[2] != 0:
problems.append('M < 1')
if I[3] != 0:
problems.append('NP < 1 or NP > N')
if I[4] != 0:
problems.append('NQ < 1')
elif I[0] == 2:
if I[1] != 0:
problems.append('LDY and/or L... |
joaduo/mepinta | core/python_core/mepinta/testing/plugins_testing/ModuleAutoTesterUtil.py | Python | gpl-3.0 | 990 | 0.00101 | # -*- coding: utf-8 -*-
'''
Mepinta
Copyright (c) 2011-2012, Joaquin G. Duo
This file is part o | f Mepinta.
Mepinta 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.
Mepinta is distributed in the hope that it will be useful,
but WITHOUT A... | rranty 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 Mepinta. If not, see <http://www.gnu.org/licenses/>.
'''
from mepinta.testing.plugins_testing.base import ModuleAutoTesterBas... |
redhat-openstack/ironic | ironic/common/keystone.py | Python | apache-2.0 | 5,538 | 0 | # coding=utf-8
#
# 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
# di... | pi_version = 'v3' if api_v3 else 'v2.0'
# NOTE(lucasagomes): Get rid of the trailing '/' otherwise urljoin()
# fails to override the version in the URL
return parse.urljoin(auth_url.rstrip('/'), api_version)
def get_service_url(service_type='baremetal', endpoint | _type='internal'):
"""Wrapper for get service url from keystone service catalog.
Given a service_type and an endpoint_type, this method queries keystone
service catalog and provides the url for the desired endpoint.
:param service_type: the keystone service for which url is required.
:param endpoi... |
destijl/grr | grr/client/stdlib.py | Python | apache-2.0 | 8,367 | 0.045417 | #!/usr/bin/env python
"""This file imports the Python std lib so it can be used by components."""
# pylint: disable=g-import-not-at-top, unused-import, using-constant-test
if False:
import BaseHTTPServer
import CGIHTTPServer
import ConfigParser
import Cookie
import DocXMLRPCServer
import HTMLParser
impo... | db
import binhex
import bisect
import bsddb.db
import bsddb.dbobj
import bsddb.dbrecio
import bsddb.dbshelve
import bsddb.dbtables
import bsddb.dbutils
import cProfile
import calendar
import cgi
import cgitb
import chunk
import | cmd
import code
import codecs
import codeop
import collections
import colorsys
import commands
import compileall
import compiler.ast
import compiler.consts
import compiler.future
import compiler.misc
import compiler.pyassem
import compiler.pycodegen
import compiler.symbols
import compiler.... |
foursquare/commons-old | src/python/twitter/common/process/__init__.py | Python | apache-2.0 | 1,910 | 0.004712 | __author__ = 'Brian Wickman'
from process_provider_ps import ProcessProvider_PS
from process_provider_procfs import ProcessProvider_Procfs
class ProcessProviderFactory(object):
"""
A factory for producing platform-appropriate ProcessProviders.
Typical use-cases:
Import
>>> from twitter.common.... | te
>>> sum(map(lambda pid: ps.get_handle(pid).cpu_time(), ps.children_of(init.pid())))
228642.19999999998
| """
PROVIDERS = [
ProcessProvider_Procfs,
ProcessProvider_PS
]
@staticmethod
def get():
"""
Return a platform-specific ProcessProvider.
"""
for provider in ProcessProviderFactory.PROVIDERS:
if provider._platform_compatible():
return provider()
|
tpltnt/SimpleCV | SimpleCV/ImageClass.py | Python | bsd-3-clause | 517,130 | 0.0112 | from __future__ import print_function
from __future__ import absolute_import
# Load required libraries
from SimpleCV.base import *
from SimpleCV.Color import *
from SimpleCV.LineScan import *
from numpy import int32
from numpy import uint8
import cv2
from .EXIF import *
if not init_options_handler.headless:
impor... | >>> imgs.filelist
>>> logo = imgs.find('simplecv.png')
**TO DO**
Eventually this should allow us to pull image urls / pat | hs from csv files.
The method also allow us to associate an arbitraty bunch of data with each
image, and on load/save pickle that data or write it to a CSV file.
"""
filelist = None
def __init__(self, directory=None):
if not directory:
return
if isinstance(directory, l... |
popazerty/dvbapp2-gui | lib/python/Plugins/Extensions/EGAMIPermanentClock/plugin.py | Python | gpl-2.0 | 5,326 | 0.024972 | ##
## Permanent Clock
## by AliAbdul
##
from Components.ActionMap import ActionMap
from Components.config import config, ConfigInteger, ConfigSubsection, ConfigYesNo
from Components.MenuList import MenuList
from enigma import ePoint, eTimer, getDesktop
from os import environ
from Plugins.Plugin import PluginDescriptor
... | .desktopHeight = desktop.size().height()
self.moveTimer = eTimer()
self.moveTimer.callback.append(self.movePosition)
self.moveTimer.start(100, 1)
def movePosition(self):
self.instance.move(ePoint(config.plugins.PermanentClock.position_x.value, config.plugins.PermanentClo | ck.position_y.value))
self.moveTimer.start(100, 1)
def left(self):
value = config.plugins.PermanentClock.position_x.value
value -= 10
if value < 0:
value = 0
config.plugins.PermanentClock.position_x.value = value
def up(self):
value = config.plugins.PermanentClock.position_y.value
value -= 10
if ... |
DigitalPublishingToolkit/Society-of-the-Query-Reader | scripts/gather_essays.py | Python | gpl-3.0 | 470 | 0.002128 | import os, re, shutil
for (base, _, files) in os.walk("essays",):
for f in files:
if f.e | ndswith(".markdown"):
fp = os.path.join(base, f)
_, np = os.path.split(base)
np = re.sub(r"_def$", "", np)
np = os.path.join("essays", np+".markdown")
# print fp, "=>", np
# shutil.copy(fp, np)
cmd = 'git mv "{0}" "{1}"'.format(fp, np)
... | s.system(cmd)
|
glennyonemitsu/funkybomb | website/handlers/docs/integrations.py | Python | apache-2.0 | 634 | 0 | from funkybomb import Template, Text
from application.util import route
from templates import documentation
from templ | ates.util import template
@route('/docs/integrations')
@template(documentation.tmpl)
async def docs_integrations_home(req):
tmpl = Template()
tmpl.p + | 'Coming soon.'
return {
'content': tmpl,
'headline': Text('Integrations')
}
@route('/docs/integrations/flask')
@template(documentation.tmpl)
async def docs_integrations_flask(req):
tmpl = Template()
tmpl.p + 'Coming soon.'
return {
'content': tmpl,
'headline': Te... |
mutability/kafka-python | kafka/client.py | Python | apache-2.0 | 21,917 | 0.001414 | import collections
import copy
import functools
import logging
import time
import kafka.common
from kafka.common import (TopicAndPartition, BrokerMetadata,
ConnectionError, FailedPayloadsError,
KafkaTimeoutError, KafkaUnavailableError,
Leade... | : a method to encode the list of payloads to a request body,
must accept client_id, correlation_id, and payloads as
keyword arguments
decode_fn: a method to decode a response body into response objects.
The response objects must be object-like and have topic
and ... | es
Returns:
List of response objects in the same order as the supplied payloads
"""
# encoders / decoders do not maintain ordering currently
# so we need to keep this so we can rebuild order before returning
original_ordering = [(p.topic, p.partition) for p in payloads]... |
inventree/InvenTree | InvenTree/part/test_migrations.py | Python | mit | 1,487 | 0 | """
Unit tests for the part model database migrations
"""
from django_test_migrations.contrib.unittest_case import MigratorTestCase
from InvenTree import helpers
class TestForwardMigrations(MigratorTestCase):
"""
Test entire schema migration sequence for the part app
"""
migrate_from = ('part', hel... | ('part'))
migrate_to = ('part', helpers.getNewestMigrationFile('part'))
def prepare(self):
"""
Create initial data
"""
Part = self.old_state.apps.get_model('part', 'part')
Part.objects.create(name='A', description='My part A')
Part.objects.create(name='B', desc... | C')
Part.objects.create(name='D', description='My part D')
Part.objects.create(name='E', description='My part E')
# Extract one part object to investigate
p = Part.objects.all().last()
# Initially some fields are not present
with self.assertRaises(AttributeError):
... |
the-blue-alliance/the-blue-alliance | src/backend/common/queries/tests/district_history_query_test.py | Python | mit | 1,069 | 0 | from backend.common.models.district import District
from backend.common.models.keys import DistrictAbbreviation, Year
from backend.common.queries.district_query import DistrictHistoryQuery
def preseed_district(year: Year, abbrev: DistrictAbbreviation) -> None:
d = District(
id=f"{year}{abbrev}",
y... | eseed_district(2018, "mar")
districts_fma = DistrictHistoryQuery(abbreviation="fma").fetch()
districts_mar = DistrictHistoryQuery(abbreviation="mar").fetch()
assert len(districts_fma) == 2
assert len(distric | ts_mar) == 2
|
erigones/esdc-ce | gui/dc/dns/forms.py | Python | apache-2.0 | 10,134 | 0.004638 | from operator import and_
from functools import reduce
from django import forms
from django.db.models import Q
from django.utils.six import PY3
from django.utils.translation import ugettext_lazy as _
from api.dc.domain.views import | dc_domain
from api.dns.domain.views import dns_domain
from api.dns.record.views import dns_record_list, dns_record
from api.vm.utils import get_owners
from gui.forms import SerializerForm
from gui.fields import ArrayField
from gui.widgets import NumberInput
from pdns.models import Domain, Record
TEXT_INPUT_ATTRS = {'... | lass DcDomainForm(SerializerForm):
"""
Create or remove DC<->DNS Domain link by calling dc_domain.
"""
_api_call = dc_domain
name = forms.ChoiceField(label=_('Domain'), required=True,
widget=forms.Select(attrs={'class': 'input-select2 narrow disable_created2'}))
de... |
bryantdo/PiPID | pypid/backend/__init__.py | Python | gpl-3.0 | 6,272 | 0.000478 | # Copyright (C) 2011-2012 W. Trevor King <wking@tremily.us>
#
# This file is part of pypid.
#
# pypid 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 la... | ""
raise NotImplementedError()
def set_up_gains(self, proportional=None, integral=None, derivative=None):
"""
...
"""
raise NotImplementedError()
def get_feedback_terms(self):
"""Experimental
"""
raise | NotImplementedError()
def clear_integral_term(self):
"""Reset the integral feedback turn (removing integrator windup)
Because the proportional term provides no control signal when
the system exactly matches the setpoint, a P-only algorithm
will tend to "droop" off the setpoint. T... |
OsirisSPS/osiris-sps | client/data/extensions/148B613D055759C619D5F4EFD9FDB978387E97CB/scripts/portals/peers.py | Python | gpl-3.0 | 3,117 | 0.048444 | import osiris
import os
import osiris.events
class Page(osiris.IPortalPage):
def __init__(self, session):
osiris.IPortalPage.__init__(self, session)
self.ajax = (session.request.getUrlParam("act") != "")
def getPageName(self):
return "portal.pages.peers"
def isMcpModeRequired(self):
return True
... | full"
template.addChildParam(self.addPeerIP)
self.addPeerPort = osiris.HtmlTextBox()
self.addPeerPort.id = "addPeerPort"
self.addPeerPort.css = "os_input_full" |
template.addChildParam(self.addPeerPort)
self.addPeerCommand = osiris.IdeButton(self.getText("common.actions.add"))
self.addPeerCommand.id = "addPeerCommand"
osiris.events.connect(self.addPeerCommand.eventClick, self.onAddPeer)
template.addChildParam(self.addPeerCommand)
#if(self.act == "your"... |
lucasoldaini/dict2csv | dict2csv.py | Python | mit | 3,606 | 0 | import csv
from StringIO import StringIO
from math import ceil
from collections import Mapping, Sequence
def __expand_container(cont, i, j, empty_sym=''):
""" Expand, if possible, the list of list cont of size (h, k) to a list
of lists of size (i, j). If the expansion is successful, newly
created ... | col_index
new_col_index = col_index
# assign progressive index names starting from 0 if di
# is a list-li | ke object
di_iter = (di.iteritems() if isinstance(di, Mapping) else enumerate(di))
for k, v in di_iter:
# recursively insert data for the sublist of di
new_col_index = __recursive_insert_data(v, data_cont, new_col_index)
if new_col_index == col_index:
# previous iteration has reach... |
idf-archive/OneLinerPython | Fibonacci.py | Python | apache-2.0 | 101 | 0.029703 | __autho | r__ = 'Danyang'
fib = lambda n : redu | ce(lambda x, n: [x[1], x[0]+x[1]], xrange(n), [0, 1])[0] |
WQuanfeng/wagtail | wagtail/wagtailadmin/apps.py | Python | bsd-3-clause | 172 | 0 | from django | .apps import AppConfig
class WagtailAdminAppConfig(AppConfig):
name = 'wagtail.wagtailadmin'
label = 'wagtailadmin | '
verbose_name = "Wagtail admin"
|
raphaottoni/arglex | arglex/macros.py | Python | gpl-3.0 | 1,719 | 0.006399 | #Macros commonly used
_be = "(be|is|am|are|were|was|been|being)"
_intensadj1 = "( absolutely| absurdly| resoundingly | amazingly | awfully | extremely | completely | highly | incredibly | perfectly | quite | really | strikingly | surprisingly | terribly | totally | unbelievably | hugely | unnaturally | unusually | utte... | | very | tremendously | spectacularly)"
_intensadv1= "{ absolutely| absurdly| resoundingly| ama | zingly| awfully| extremely| completely| highly| incredibly| perfectly| quite| really| strikingly| surprisingly| terribly| totally| unbelievably| hugely| unnaturally| unusually| utterly| very| tremendously| spectacularly}"
_intensadj1 = "( absolute| extreme| incredible| perfect| phenomenal| spectacular| huge| maj... |
conwetlab/ckanext-datarequests | ckanext/datarequests/tests/test_helpers.py | Python | agpl-3.0 | 4,934 | 0.003446 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of CKAN Data Requests Extension.
# CKAN Data Requests Extension 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 F... | quest_id = 'example_uuidv4'
result = helpers.get_comments_number(datarequest_id)
| # Assertions
helpers.db.init_db.assert_called_once_with(helpers.model)
helpers.db.Comment.get_comment_datarequests_number.assert_called_once_with(datarequest_id=datarequest_id)
self.assertEquals(result, n_comments)
def test_get_comments_badge(self):
# Mocking
n_comment... |
asdf1011/bdec | bdec/choice.py | Python | lgpl-3.0 | 3,099 | 0.00355 | # Copyright (C) 2008-2011 Henry Ludemann
#
# This file is part of the bdec decoder library.
#
# The bdec decoder library is free software; you can redistribute it
# and/or modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 ... | ry that can be one of many entries.
The first entry to decode correctly will be used.
"""
def __init__(self, name, children, length=None):
bdec.entry.Entry.__init_ | _(self, name, length, children)
def _range(self, ignore_entries):
minimum = min(child.entry.range(ignore_entries).min for child in self.children)
maximum = max(child.entry.range(ignore_entries).max for child in self.children)
return bdec.entry.Range(minimum, maximum)
|
glimix/limix-genetics | limix_genetics/_colors.py | Python | mit | 259 | 0.003861 | from bokeh.palettes import brewer
def get_colors( | colors, labels):
if colors is None:
colors = dict()
colors_iter = iter(brewer['Spectral'][11])
for label in labels:
colors[label] | = next(colors_iter)
return colors
|
dabo02/Upwork_Tom_VideoShowroom | Back-End.py | Python | gpl-3.0 | 4,500 | 0.001556 | from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, Response
from celery import Celery
from werkzeug.utils import secure_filename
from VideoPlayer import VideoPlayer
from subprocess import Popen
import os
app = Flask(__name__)
local = False
if local:
UPLOAD_FOLDER = '/home/dabo02/... |
vp = VideoPlayer()
while True:
mag_switch = GPIO.input(23)
if mag_switch:
if not vp.video_is_playing:
GPIO.output(24, 0)
check_for_current()
global current_video
vp.set_video(UPLOAD_FOLDER + current_video)
... | ideo()
@app.route('/')
def dashboard():
video_list = os.listdir(UPLOAD_FOLDER)
video_info = {}
videos = []
global current_video
global preview_video
global light_state
preview = ''
for v in video_list:
if current_video:
if current_video in v:
current... |
callowayproject/django-concepts | example/settings.py | Python | apache-2.0 | 4,239 | 0.001887 | # Django settings for example project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
import os, sys
APP = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PROJ_ROOT = os.path.abspath(os.path.dirname(__file__))
sys.path.append(APP)
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABAS... | ot relative paths.
os.path.join(PROJ_ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contr | ib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'concepts',
'simpleapp',
)
|
CristhGunners/Photon | manage.py | Python | mit | 249 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.env | iron.setdefault("DJANGO_SETTINGS_MODULE", "photon.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys. | argv)
|
vanabo/mattress | src/products/migrations/0021_auto_20170228_1211.py | Python | mit | 395 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migratio | ns.Migration):
dependencies = [
('products', '0020_auto_20170227_1345'),
]
operations = [
migrations.RenameField(
model_name='product',
o | ld_name='categories',
new_name='category',
),
]
|
mcfletch/django-assets | django_assets/management/commands/assets.py | Python | bsd-2-clause | 4,988 | 0.001804 | """Manage assets.
Usage:
./manage.py assets build
Build all known assets; this requires tracking to be enabled: Only
assets that have previously been built and tracked are
considered "known".
./manage.py assets build --parse-templates
Try to find as many of the project's tem... | irectly define your bundles in tem | plates.')
# this collects the unrecognized arguments to pass through to webassets
parser.add_argument('args', nargs=argparse.REMAINDER)
def handle(self, *args, **options):
# Due to the use of LaxOptionParser ``args`` now contains all
# unparsed options, and ``options`` those that t... |
mrniranjan/python-scripts | reboot/system/system4.py | Python | gpl-2.0 | 288 | 0.003472 | import os
import select
fds = os.open("data", os.O_RDONLY)
while True:
r | eads, _, _ = select.select(fds, [], [], 2.0)
if 0 < len(reads):
d = os.read(reads[0], 10)
if d:
print "-> ", d
else:
break
else:
print | "timeout"
|
damianbaran/inz | popup/publikacja.py | Python | gpl-3.0 | 16,876 | 0.03421 | # -*- coding: utf-8 -*-
################################################
## Aplikacja wspomagajaca tworzenie bazy publikacji naukowych wpsółpracujaca z Google Scholar
## Copyright (C) 2013 Damian Baran
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the... | x.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText3.Wrap( -1 )
bSizer4.Add( self.m_staticText3, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 )
self.m_textCtrl3 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.Defa | ultPosition, wx.Size( 145,-1 ), 0 )
bSizer4.Add( self.m_textCtrl3, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 )
bSizer15.Add( bSizer4, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, 5 )
bSizer6 = wx.BoxSizer( wx.HORIZONTAL )
self.m_staticText5 = wx.StaticText( self, w... |
tmtowtdi/MontyLacuna | gui/ORIGships/lib/gui/ui_about.py | Python | mit | 2,866 | 0.003838 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/about.ui'
#
# Created: Thu Jun 4 15:32:51 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_About(object):
def setupUi(self,... | About.resize(400, 300)
self.verticalLayout_2 = QtGui.QVBoxLayout(About)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
| self.lbl_appname = QtGui.QLabel(About)
self.lbl_appname.setObjectName("lbl_appname")
self.verticalLayout.addWidget(self.lbl_appname)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self... |
todaychi/hue | apps/impala/src/impala/dashboard_api.py | Python | apache-2.0 | 22,801 | 0.01 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | 'min': min_value,
'max': max_value,
}
}
}
}
def get(self, dashboard, doc_id):
database, table = | self._get_database_table_names(dashboard['name'])
field = self._get_field(dashboard, dashboard['idField'])
quotes = '' if self._is_number(field['type']) else "'"
sql = "SELECT * FROM `%(database)s`.`%(table)s` WHERE `%(idField)s` = %(quotes)s%(doc_id)s%(quotes)s" % {
'database': database,
'tabl... |
visionegg/visionegg | demo/color_grating.py | Python | lgpl-2.1 | 2,726 | 0.023844 | #!/usr/bin/env python
"""Colored sine wave grating in circular mask"""
############################
# Import various modules #
############################
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation, F... | pedestal = 0.1,
mask = mask, # optional
position = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
anchor = 'center',
size = ( 300.0 , 300.0 ),
... | 1.0,
orientation = 270.0 )
def pedestal_func(t):
# Calculate pedestal over time. (Pedestal range [0.1,0.9] and
# contrast = 0.2 limits total range to [0.0,1.0])
temporal_freq_hz = 0.2
return 0.4 * sin(t*2*pi * temporal_freq_hz) + 0.5
######################################... |
mscuthbert/abjad | abjad/tools/pitchtools/test/test_pitchtools_Octave_from_pitch_name.py | Python | gpl-3.0 | 267 | 0.003745 | # -*- encoding: utf-8 -*-
from abjad import *
|
def test_pitchtools_Octave_from_pitch_name_01():
assert pitchtools.Octave.from_pitch_name("cs'") == 4
assert pitchtools.Octave.from_pitch_name('cs') == 3
| assert pitchtools.Octave.from_pitch_name('cs,') == 2 |
Elico-Corp/odoo_OCB | addons/l10n_fr_certification/__init__.py | Python | agpl-3.0 | 1,524 | 0.004593 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import models
from openerp import api, SUPERUSER_ID
def _setup_inalterability(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
# enable ping for this module
env['publisher_warranty.contract'].updat... | for cancel_view in ir_views:
cancel_view.write({'active': False})
fr_c | ompanies = env['res.company'].search([('partner_id.country_id.code', '=', 'FR')])
if fr_companies:
# create the securisation sequence per company
fr_companies._create_secure_sequence()
#reset the update_posted field on journals
journals = env['account.journal'].search([('company_id'... |
pombredanne/voc | tests/builtins/test_abs.py | Python | bsd-3-clause | 566 | 0 | from .. utils import TranspileTestCase, BuiltinFuncti | onTestCase
class AbsTests(TranspileTestCase):
def test_abs_not_implemented(self):
self.assertCodeExecution("""
class NotAbsLike:
pass
x = NotAbsLike()
try:
print(abs(x))
except TypeError as err:
print(err)
... | 'test_frozenset',
]
|
davidyezsetz/kuma | vendor/packages/Werkzeug/docs/conf.py | Python | mpl-2.0 | 6,395 | 0.005786 | # -*- coding: utf-8 -*-
#
# Werkzeug documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 16 23:10:43 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickle... | ontain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the p | roject.
project = u'Werkzeug'
copyright = u'2009, The Werkzeug Team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
import re
from werkzeug import __version__ as release
if 'dev' in release:
... |
savoirfairelinux/account-financial-tools | account_cancel_invoice_check_voucher/account_invoice.py | Python | agpl-3.0 | 2,758 | 0.001813 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2012 Camptocamp (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Vincent Renaville (Camptocamp)
#
# This program is free software: you can redistribute it and/or modify
# it under ... | sion.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GN | U Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.tools.translate impo... |
espenak/enkel | testsuite/unittest_tpl.py | Python | gpl-2.0 | 1,046 | 0.005736 | # This file is part of the Enkel web programming library.
#
# Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net)
#
# 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... | E. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc. | , 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from unittest import TestCase
from enkel.wansgli.testhelpers import unit_case_suite, run_suite
class Test(TestCase):
def suite():
return unit_case_suite(Test)
if __name__ == '__main__':
run_suite(suite())
|
stackforge/blazar | blazar/opts.py | Python | apache-2.0 | 1,861 | 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
# distributed under the... | ort itertools
import blazar.api.v2.app
import blazar.api.v2.controllers
import blazar.cmd.api
import blazar.config
import blazar.db.base
import blazar.db.migration.cli
import blazar.manager
import blazar.manager.service
import blazar.notification.notifier
import blazar.plugins.oshosts.host_plugin
import blazar.utils.o... | return [
('DEFAULT',
itertools.chain(
blazar.api.v2.app.auth_opts,
blazar.cmd.api.opts,
blazar.config.api_opts,
blazar.config.cli_opts,
blazar.config.lease_opts,
blazar.config.os_opts,
blazar.db.base.db_driver_... |
jss-emr/openerp-7-src | openerp/addons/account/wizard/account_unreconcile.py | Python | agpl-3.0 | 2,140 | 0.002336 | # -*- coding: utf-8 -*-
################################################################ | ##############
#
# OpenERP, Open Source Manag | ement Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# 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 opti... |
lekshmideepu/nest-simulator | pynest/nest/lib/hl_api_simulation.py | Python | gpl-2.0 | 15,584 | 0.001091 | # -*- coding: utf-8 -*-
#
# hl_api_simulation.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the Licen... | nges may cause
undefined behavior and check these thoroughly.
See Also
| --------
Prepare, Run, Cleanup, Simulate
"""
Prepare()
try:
yield
finally:
Cleanup()
@check_stack
def ResetKernel():
"""Reset the simulation kernel.
This will destroy the network as well as all custom models created with
:py:func:`.CopyModel`. Calling this functi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.