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
vorburger/mcedit2
src/mceditlib/bench/time_relight_natural.py
Python
bsd-3-clause
1,455
0.003436
import numpy import sys import time from mceditlib.test import templevel from mceditlib import relight # run me with the source checkout as the working dir so I can find the test_files folder. def natural_relight(): world = templevel.
TempLevel("AnvilWorld") dim = world.getDimension() positions = [] for cx, cz in dim.chunkPositions(): chunk = dim.getChunk(cx, cz) for cy in chunk.sectionPositions(): positions.append((cx, cy, cz)) poses = iter(positions) def do_relight(): cx, cy, cz = poses.nex...
= numpy.indices((16, 16, 16), numpy.int32) indices.shape = 3, 16*16*16 indices += ([cx << 4], [cy << 4], [cz << 4]) x, y, z = indices relight.updateLightsByCoord(dim, x, y, z) # Find out how many sections we can do in `maxtime` seconds. start = time.time() count = 0 ma...
technologiescollege/Blockly-rduino-communication
scripts_XP/Lib/site-packages/jedi/evaluate/docstrings.py
Python
gpl-3.0
10,503
0.000952
""" Docstrings are another source of information for functions and classes. :mod:`jedi.evaluate.dynamic` tries to find all executions of functions, while the docstring parsing is much easier. There are three different types of docstrings that |jedi| understands: - `Sphinx <http://sphinx-doc.org/markup/desc.html#info-f...
net/manual-fields.html>`_ - `Numpydoc <https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_ For example, the sphinx annotation ``:type foo: str`` clearly states that the type of ``foo`` is ``str``. As an addition to parameter searching, this module a
lso provides return annotations. """ import re from textwrap import dedent from parso import parse, ParserSyntaxError from jedi._compatibility import u from jedi.evaluate.utils import indent_block from jedi.evaluate.cache import evaluator_method_cache from jedi.evaluate.base_context import iterator_to_context_set, C...
Valka7a/python-playground
python-the-hard-way/mystuff.py
Python
mit
106
0.018868
de
f apple(): prin
t "I AM APPLES!" # this is just a variable tangerine = "Living reflection of a dream."
clemensv/qpid-proton
tests/python/proton_tests/engine.py
Python
apache-2.0
75,989
0.007054
# # 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 # to you under the Apache License, Version 2.0 (the # "License"); you may not...
mask2 = 0 for cat in ("TRACE_FRM", "TRACE_RAW"): trc = os.environ.get("PN_%s" % cat) if trc and trc.lower() in ("1", "2", "yes", "true"): mask1 = mask1 | getattr(Transport, cat) if trc == "2": mask2 = mask2 | getattr(Transport, cat) t1.trace(mask1) t2.trace(mask2) ...
self.connection() if max_frame: c1.transport.max_frame_size = max_frame[0] c2.transport.max_frame_size = max_frame[1] if idle_timeout: # idle_timeout in seconds expressed as float c1.transport.idle_timeout = idle_timeout[0] c2.transport.idle_timeout = idle_timeout[1] c1.open()...
guzzijones/parseDI
parseDI.py
Python
gpl-2.0
1,926
0.065421
from slpp import SLPP import re class diObj(object): def __init__(self,type,name,luaData): self.objectType=type self.objectName=name self.objectKey=type+name self.DictLuaData=luaData self.DictTotal={} self.setDict() def setDict(self): self.DictTotal["Name"]=self.objectName self.DictTotal["Type"]=sel...
): SLPP.__init__(self) self.filename=filename; self.diObjects={} self.version="" self.setString(); self.readVersion(); self.decode(); def setString(self): f = open(self.filename,'r') try: text=f.read()
##todo remove all comments correctly #for each character #if =" then ignore until next " without a preceding backslash #if / with preceding / then blank out everything until \n #currently only removes comments that start at the beginning of a line reg = re.compile('^//.*$', re.M) text = reg.sub...
Pulgama/supriya
supriya/ugens/LFTri.py
Python
mit
542
0.001845
import collections from supriya import CalculationRate from supriya.ugens.PureUGen import PureUGen class LFTr
i(PureUGen): """ A non-band-limited triangle oscillator unit generator. ::
>>> supriya.ugens.LFTri.ar() LFTri.ar() """ ### CLASS VARIABLES ### __documentation_section__ = "Oscillator UGens" _ordered_input_names = collections.OrderedDict( [("frequency", 440.0), ("initial_phase", 0.0)] ) _valid_calculation_rates = (CalculationRate.AUDIO, Calculation...
diNard/Saw
saw/saw.py
Python
mit
274
0.00365
from parsers.paragraphs import Parag
raphs, Sentences from parsers.blocks import Blocks, Words class Saw: paragraphs = Paragraphs sentences = Sentences blocks = Blocks words = Words @staticmethod def load(text):
return Paragraphs.load(text)
elianerpereira/gtg
GTG/core/__init__.py
Python
gpl-3.0
10,171
0.000098
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
"/org/gnome/GTG" # TAGS AL
LTASKS_TAG = "gtg-tags-all" NOTAG_TAG = "gtg-tags-none" SEP_TAG = "gtg-tags-sep" SEARCH_TAG = "search" def check_config_file(self, path): """ This function bypasses the errors of config file and allows GTG to open smoothly""" config = ConfigParser.ConfigParser() try: ...
Sinar/popit_ng
popit/serializers/misc.py
Python
agpl-3.0
13,241
0.00287
__author__ = 'sweemeng' from popit.models import Person from popit.models import Contact from popit.models import ContactDetail from popit.models import Link from popit.models import Identifier from popit.models import OtherName from hvad.contrib.restframework import TranslatableModelSerializer from rest_framework.seri...
ce.given_name = data.g
et('given_name', instance.given_name) instance.additional_name = data.get('additional_name', instance.additional_name) instance.honorific_suffix = data.get('honorific_suffix', instance.honorific_suffix) instance.honorific_prefix = data.get('honorific_prefix', instance.honorific_prefix) i...
ami/lob-python
tests/test_object.py
Python
mit
2,744
0.00984
from StringIO import StringIO import unittest import lob # Setting the API key lob.api_key = 'test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc' class ObjectFunctions(unittest.TestCase): def setUp(self): lob.api_key = 'test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc' self.obj = lob.Object.list(count=1).data[0] ...
self.assertTru
e(isinstance(objects.data[0], lob.Object)) self.assertEqual(len(objects.data), 2) def test_list_objects_fail(self): self.assertRaises(lob.error.InvalidRequestError, lob.Object.list, count=1000) def test_create_object_remote(self): object = lob.Object.create( name = 'Test Ob...
nmdp-bioinformatics/service-hml-fhir-converter
CodeGen/hmlFhirConverterCodeGenerator/codegen/service/ServiceGenerator.py
Python
apache-2.0
776
0.002577
import os from os import walk templatePath = r'templates/serviceTemplate.txt' writePath = r'/Source/Api/service-hmlFhirConverter/src/main/java/org/nmdp/hmlfhirconverter/service' class ServiceGenerator: def get_template(self): with open(templatePath, 'r') as fileReader: return fileReader.read(...
(fileName)) with open(path, 'w') as fileWriter: fileWriter.write(fileContents) def get_file_name(self, className): return className + 'Service.java' def file_exists(self, className):
for (dirpath, dirnames, filenames) in walk(writePath): return self.get_file_name(className) in filenames
ryokbys/nap
nappy/fitpot/reduce_high_energy_samples.py
Python
mit
2,920
0.009589
#!/usr/bin/env python """ Reduce samples that have too high energies by comparing between the same group of samples. The group is defined according to the name of directory before the last 5 digits. For example, the directory `smpl_XX_YYYYYY_#####` where `#####` is the last 5 digits and the group name would be `smpl_XX...
ghsmpls if __name__ == "__main__": args = docopt(__doc__) smpldirs = args['DIRS'] outfname = args['-o'] threshold = float(args['--threshold']) print('grouping samples...') groups = get_groups(smpldirs) print('looking for high-energy samples...'
) highsmpls = [] for g,smpls in groups.items(): print('.',end='') highsmpls.extend(get_list_high_energy(smpls,threshold)) print('') with open(outfname,'w') as f: for s in highsmpls: f.write(s+'\n') print('number of samples to be reduced = ',len(highsmpls)) pr...
MosheBerman/brisket-mashup
source/libraries/python-twitter-1.1/setup.py
Python
mit
2,426
0.010717
#!/usr/bin/env python # # Copyright 2007-2013 The Python-Twitter 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
ls is installed SETUPTOOLS_METADATA = dict( install_requires = ['setuptools', 'simplejson', 'oauth2', 'requests', 'requests_oauthlib'], include_package_data = True, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Soft...
se', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet', ], test_suite = 'twitter_test.suite', ) def Read(file): return open(file).read() def BuildLongDescription(): return '\n'.join([Read('README.md'), Read('CHANGES')]) def Mai...
mylvari/namubufferi
namubufferiapp/admin.py
Python
mit
1,669
0.002996
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Category, Product, Transaction, UserTag, ProductTag, Account class AccountInline(admin.StackedInline): model = Account
can_delete = False verbose_name_plural = 'Account' fk_name = 'user' class BalanceListFilter(admin.SimpleListFilter): title = 'balance' parameter_name = 'balance' default_value = None def lookups(self, request, model_admin): return [ ("negative", "negative balances only") ...
= [] for user in queryset: if user.account.balance < 0: negative_users.append(user.id) return User.objects.filter(id__in=negative_users) return queryset class CustomUserAdmin(UserAdmin): inlines = (AccountInline, ) list_display = ('email', '...
dob71/x2swn
skeinforge/fabmetheus_utilities/geometry/geometry_utilities/evaluate_fundamentals/print.py
Python
gpl-3.0
984
0.018293
""" Boolean geometry utilities. """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' ...
lueString)) return val
ueString def line(valueString): 'Print line.' print(valueString) return valueString globalAccessibleAttributeDictionary = {'continuous' : continuous, 'line' : line}
jicksy/oneanddone_test
oneanddone/tasks/management/commands/updatemetrics.py
Python
mpl-2.0
954
0.001048
# 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/. from datetime import datetime from optparse import make_option from django.core.management.base import BaseCommand from oneanddone.tasks.models import TaskMetrics class Command(BaseCommand): help = 'Updates stored metrics' option_list = Ba...
e_update', default=False, help='Force updating of all tasks'),) def handle(self, *args, **options): updated = TaskMetrics.update_task_metrics(force_update=options['force_update']) self.stdout.write('%s: %s tasks had their metrics updated\n' % ...
ibm-cds-labs/pixiedust
pixiedust/apps/cfBrowser.py
Python
apache-2.0
9,821
0.004175
# ------------------------------------------------------------------------------- # Copyright IBM Corp. 2017 # # 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/licens...
authHeader, 'Accept': 'application/json' }) json = r.json() i
f 'entity' in json.keys(): service_id = json['entity']['service_guid'] else: return "NO PLAN FOUND" # Load the service url = 'https://{}/v2/services/{}'.format(api_base_url, service_id) path = '/v2/services/{}'.format(service_id) r = requests.get(url, head...
sacsant/avocado-misc-tests
security/evmctl-tests.py
Python
gpl-2.0
2,182
0.001833
#!/usr/bin/env python # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that...
l = "https://sourceforge.net/projects/linux-ima/files/la
test/download" tarball = self.fetch_asset(name="download.tar.gz", locations=url, expire='7d') archive.extract(tarball, self.workdir) self.sourcedir = os.path.join(self.workdir, os.listdir(self.workdir)[0]) self.log.info("sourcedir - %s" % self.sourcedir) os.chdir(self.sourcedir) ...
OCA/l10n-italy
l10n_it_central_journal/models/central_journal.py
Python
agpl-3.0
2,270
0.000881
# Copyright 2018 Gianmarco Conte (gconte@dinamicheaziendali.it) import logging from odoo import api, models from odoo.tools.misc import formatLang _logger = logging.getLogger(__name__) class ReportGiornale(models.AbstractModel): _name = "report.l10n_it_central_journal.report_giornale" _description = "Journ...
ta, "docs": self.env["account.move.line"].browse(data["ids"]), "get_move": self._get_move, "save_print_info": self._save_print_info, "env": self.env, "formatLang": formatLang, "l10n_it_count_fi
scal_page_base": data["form"]["fiscal_page_base"], "start_row": data["form"]["start_row"], "date_move_line_to": data["form"]["date_move_line_to"], "daterange": data["form"]["daterange"], "print_state": data["form"]["print_state"], "year_footer": data["form"]["...
bsipocz/astropy
astropy/_erfa/erfa_generator.py
Python
bsd-3-clause
27,369
0.000548
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module's main purpose is to act as a script to create new versions of ufunc.c when ERFA is updated (or this generator is enhanced). `Jinja2 <http://jinja.pocoo.org/>`_ must be installed for this module/script to function. Note that this does *no...
'(').replace(r'\>', ')')) class FunctionDoc: d
ef __init__(self, doc): self.doc = doc.replace("**", " ").replace("/*\n", "").replace("*/", "") self.__input = None self.__output = None self.__ret_info = None def _get_arg_doc_list(self, doc_lines): """Parse input/output doc section lines, getting arguments from them. ...
s3rvac/talks
2017-03-07-Introduction-to-Python/examples/23-inheritance.py
Python
bsd-3-clause
303
0.016502
class A: def foo(self): print('
A.foo()') class B(A): def foo(self): print('B.foo()') class C(A): def foo(self): print('C.foo()') class D(B, C): def foo(self): print('D.foo()') x = D() print(D.__mro__) # (D, B, C, A, object) x.foo()
# D.foo()
wangtaoking1/hummer
hummer/wsgi.py
Python
apache-2.0
389
0
""" WSGI config for hummer project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTIN...
ODULE", "hummer.settings") applicat
ion = get_wsgi_application()
Frikeer/LearnPython
exc8/exc8.py
Python
unlicense
38
0.026316
impo
rt cubed print(cub
ed.cub(2,106))
Tesora-Release/tesora-python-troveclient
troveclient/v1/clusters.py
Python
apache-2.0
3,850
0
# Copyright (c) 2014 eBay Software Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
rl) common.check_for_exceptions(resp, body, url) def _action(se
lf, cluster, body): """Perform a cluster "action" -- grow/shrink/etc.""" url = "/clusters/%s" % base.getid(cluster) resp, body = self.api.client.post(url, body=body) common.check_for_exceptions(resp, body, url) if body: return self.resource_class(self, body['cluster']...
yevheniyc/Projects
1h_NGL_3D_Viewer/pyscripts/pdbmapper/PdbParser.py
Python
mit
2,840
0.002817
''' pdbparser.py - Yevheniy Chuba - 6/1/2017 Parse local or external (PDB Database) 3D structure files (.pdb, .cif) Usage: parser = PdbParser("2128-1.pdb").pdb_processing() output: [['L', 'DIQ...'], ['
H', 'EVQL...']] ''' import os from Bio.PDB import * from Bio.Seq import Seq class PdbParser: ''' PdbParser extracts amino acid sequence from PDB structure, either downloaded from PDB database or uploaded localy .pdb file Args: pdb_struct_name (string): name of the file or PDB d...
Extracted amino acid sequence from the PDB file, including chain information ''' def __init__(self, struct_name, struct_dir='PDB_Struct', external=False): self.struct_name = struct_name self.struct_dir = struct_dir self.external = external def pdb_processing(self): ...
cmcdowell/CLI-email
emailer.py
Python
mit
2,010
0.000498
#!/usr/bin/env python from ConfigParser import SafeConfigParser, NoSectionError, Error import argparse import os import smtplib import re import sys def main(): argument_parser = argparse.ArgumentParser(prog='mail') argument_parser.add_argument('subject', help='The subject of the email') argument_parser...
: config_parser.read(os.path.join(path, 'settings.ini')) except Error as e: print 'Error, settings.ini.', e sys.exit() try: settings = dict(config_parser.items('email')) except NoSectionError as e: print 'Error settings.ini.', e sys.exit() try: s...
sword'] except KeyError as e: print e sys.exit() if sys.stdin.isatty(): msg = raw_input('Please enter your message >') else: msg = '<br>'.join(line for line in sys.stdin) headers = ['From: ' + user, 'Subject: ' + args.subject, 'To: ' + args...
jeacaveo/planning_70
tests/test_planning.py
Python
agpl-3.0
19,305
0.002176
# -*- coding: utf-8 -*- from openerp.tests import common from openerp.osv.orm import except_orm from datetime import datetime from . import test_util class TestPlanning(common.TransactionCase): def setUp(self): super(TestPlanning, self).setUp() # Cursor and user initialization cr, uid =...
r') self.pos_order_line_obj = self.registry('pos.order.line') # Utility module methods self.create_sched = test_util.create_sched self.create_sched_line = test_util.create_sched_line self.create_appt = test_util.create_appt # Create amount of spaces in range spa...
#' + str(space_num)} self.space_id = self.space_obj.create(cr, uid, values) space_ids.append(self.space_id) # Create amount of services (in range) to be provided service_ids = [] for service_num in range(2): values = {'name': 'Service #' + str(service_num), ...
paleocore/paleocore
login/views.py
Python
gpl-2.0
1,470
0.005442
from django.contrib.auth import authenticate,login from django.contrib import messages from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render_to_response from django.template import RequestContext def user_logi...
reverse("login:user_login") + "?next=" + nextURL) else: messages.add_message(request, messag
es.INFO, 'Incorrect username and/or password.') return HttpResponseRedirect(reverse("user_login:user_login") + "?next=" + nextURL) else: nextURL = request.GET.get("next") return render_to_response('login.html', {"next...
edugrasa/demonstrator
gen.py
Python
gpl-2.0
37,281
0.005526
#!/usr/bin/env python # # Copyright (C) 2014-2017 Nextworks # Author: Vincenzo Maffione <v.maffione@nextworks.it> # # This 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 of...
gument('--ring', help = "Use ring topology with variable number of nodes", type = int) argparser.add_argument('--kernel',
help = "custom kernel buildroot image", type = str, default = 'buildroot/bzImage') argparser.add_argument('--initramfs', help = "custom initramfs buildroot image", type = str, default = 'buildroot/rootfs.cpio') argparser.add_argument('-f', '--f...
leppa/home-assistant
tests/components/hassio/test_discovery.py
Python
apache-2.0
5,530
0.000723
"""Test config flow.""" from unittest.mock import Mock, patch from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.setup import async_setup_component from tests.common import mock_coro async def test_hassio_discovery_startup(...
"port": 1883, "username": "mock-user", "password": "moc
k-pass", "protocol": "3.1.1", }, } ] }, }, ) aioclient_mock.get( "http://127.0.0.1/addons/mosquitto/info", json={"result": "ok", "data": {"name": "Mosquitto Test"}}, ) with patch(...
cloew/tidypip
tidypip/packages/url_package.py
Python
mit
604
0.008278
import posixpath class UrlPackage: """ Represents a package specified as a Url """ def __init__(self, url): """ Initialize
with the url """ if ':' in url: self.url = url else: self.url = posixpath.join('git+git://github.com', url) @property def installAs(self): """ Return the string to use to Install the package via pip """ return self.url def...
turn self.url
YiqunPeng/Leetcode-pyq
solutions/944DeleteColumnsToMakeSorted.py
Python
gpl-3.0
467
0.010707
class Solution: def minDel
etionSize(self, A): """ :type A: List[str] :rtype: int """ rows, cols = len(A), len(A[0]) if rows == 1: return 0 ans = 0 for j in range(cols):
sort = True for i in range(1, rows): if A[i][j] < A[i-1][j]: sort = False break if not sort: ans += 1 return ans
lukewink/buildops
manage.py
Python
gpl-3.0
806
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "buildops.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the...
except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environme
nt?" ) raise execute_from_command_line(sys.argv)
ABM-project/power-grid
test/test_network.py
Python
mit
814
0.001229
''' Module containing tests for the network data structure ''' import unittest from power_grid import network class TestNetwork(unittest.TestCase): ''' Class containing all unit tests related to the network data structure. ''' def test_randomly_generated_network(self): ''' Tests if the averag...
n my_net.nodes)/number_of_nodes self.assertAlmostEqual( average_connectivity, average_co
nnectivity_computed, delta=10e-6)
Yarrick13/hwasp
tests/wasp1/AllAnswerSets/choice_30.test.py
Python
apache-2.0
66
0
input = """ :- not b. b :- a, not a. a v c. """ output = "
"" """
viaict/viaduct
migrations/versions/2016_01_23_391b3fa1471_add_archived_field_to_custom_form.py
Python
mit
1,019
0.01472
"""Add archived field to custom form Revision ID: 391b3fa1471 Revises: 473f91b5874 Create Date: 2016-01-23 15:51:40.304025 """ # revision identifiers, used by Alembic. revision = '391b3fa1471' down_revision = '473f91b5874' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upg...
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.alter_column('custom_form', 'price', existing_type=mysql.FLOAT(), nullable=Fa
lse, existing_server_default=sa.text("'0'")) op.drop_column('custom_form', 'archived') ### end Alembic commands ###
LanceVan/SciCycle
HermiteInterpolation.py
Python
mit
1,740
0.011494
import numpy as np from Interpolation import * class HermiteInterpolation(Interpolation): def __init__(self, x, y, yDrv): Interpolation.__init__(self, x, y) sizeyDrv = yDrv.shape if not (len(sizeyDrv) == 1 or (len(sizeyDrv) == 2 and sizeyDrv[0] == 1)): raise ValueError("Size o...
l = np.empty(self.size) alpha = np.empty(self.size) alpha = alpha.reshape(self.size, 1) beta = np.empty(self.size) beta = beta.reshape(self.size, 1) li = np.empty(self.size - 1) for xi in x: lNume = np.linspace(xi, xi, self.size) - self.x[0] ...
i[ : i] = lNume[ : i] / lDeno[ : i] li[i : ] = lNume[i + 1 : ] / lDeno[i + 1 : ] l[i] = li.cumprod()[-1] alpha[i][0] = (1 - 2 * (xi - self.x[0][i]) * ((1 / lDeno[ : i]).sum() + (1 / lDeno[i + 1 : ]).sum())) * l[i] * l[i] beta[i][0] = (xi - self.x[0][i]) * ...
livni/old-OK
src/knesset/hashnav/base.py
Python
bsd-3-clause
6,270
0.008931
import copy from django import http from django.core import serializers from django.core.exceptions import ImproperlyConfigured from django.template import RequestContext from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ class View(object): """ Parent ...
they appear as views for decorators return callback(*args, **kwargs) allowed_methods = [m for m in view.allowed_methods if hasattr(view, m)] return http.HttpResponseNotAllowed(allowed_methods) def parse_params(self, *args, **kwargs): """ this method is used to parse...
Based on the request's HTTP method, get the callback on this class that returns a response. If the method isn't allowed, None is returned. """ method = self.request.method.upper() if method not in self.allowed_methods: if self.strict_allowed_methods: return ...
coin-or/oBB
obb/lboundme_loc_rr.py
Python
lgpl-3.0
2,004
0.021956
from __future__ import division def bound(c,(bndH,method),d1,f,g,d2,D,A=None,b=None,E=None,d=None,U=None,optimality=None,initialRadius=None): # Norm function from numpy import ones, sqrt from numpy.linalg import norm # Our own functions from trsq import trsq from mest import mest from doma...
ones(D) check = 1 for i in range(0,D): if l2[i]<l1[i] or u2[i]>u1[i]: check = 0 break #if the box reduce
d is not completely contained in the orginal box if check == 0: # Revert to the orginal ball depending o the level of depth (= initialRadius/const) #if c.r >= initialRadius/8: # l=l1 # u=u1 # xc = c.xc # r = c.r #e...
esben/brother-scan
brscan/snmp.py
Python
gpl-3.0
1,777
0.003376
from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 import time def add_menu_entry(button, func, user, host, appnum, duration=360, brid=''): global cmdGen, authData, transportTarget cmd = 'TYPE=BR;BUTTON=%s;USER="%s";FUNC=%s;HOST=%s;APPNUM=%s;DURATION=%s;BRID=%...
ring(cmd)) ) # See http://www.oidview.com/mibs/2435/BROTHER-MIB.html # Check for errors and print out results if errorIndicati
on: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?')) def launch(args, config): global cmdGen, authData, transportTarget cmdGen = cmdgen.CommandGenerato...
textmagic/textmagic-rest-python
textmagic/rest/models/contacts.py
Python
mit
8,232
0.001944
from . import Model, CollectionModel class Contact(Model): """ A Contact object model .. attribute:: id .. attribute:: phone .. attribute:: email .. attribute:: firstName .. attribute:: lastName .. attribute:: companyName .. attribute:: country Dictionary like this:...
unique id of the Contact to delete. """ return self.delete_instance(uid) def lists(self, uid=0, **kwargs): """ Returns a list of :cl
ass:`List` objects (lists which Contact belongs to) and a pager dict. :Example: lists, pager = client.contacts.lists(uid=1901010) :param int uid: The unique id of the Contact to update. Required. :param int page: Fetch specified results page. Default=1 :param int limit: How...
alexpark07/ARMSCGen
shellcodes/arm/sh.py
Python
gpl-2.0
355
0.005634
# /bin/sh def generate(cmd='/bin/sh'):
"""Executes cmd Args: cmd(str): executes cmd (default: ``/bin/sh``) """ sc = """ adr r0, bin_sh_1 mov r2, #0 push {r0, r2} mov r1, sp movw r7, #11 svc 1 bin_sh_1: .asciz "%s" """ % (cmd) # sometimes we have to change to specif
ic things like id return sc
pschillinger/lamor15
lamor_flexbe_states/src/lamor_flexbe_states/take_picture_state.py
Python
mit
877
0.028506
#!/usr/bin/env python import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import cv2 from flexbe_core import EventState, Logger from flexbe_core.proxy import ProxySubscriberCached from sensor_msgs.msg import PointCloud2 class TakePictureSta
te(EventState): ''' Stores the picture of the given topic. #> Image Image The received pointcloud. <= done The picture has been received and stored. ''' def __init__(self): super(TakePictureState, self).__init__(outcomes = ['done'], output_keys = ['Image']) self._topic = '/head_...
/rgb/image_rect_color' self._sub = ProxySubscriberCached({self._topic:Image}) def execute(self, userdata): if self._sub.has_msg(self._topic): userdata.Image = self._sub.get_last_msg(self._topic) print 'take_picture_state: took a picture' return 'done'
JohnGriffiths/nipype
nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py
Python
bsd-3-clause
3,121
0.030119
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.camino.convert import ProcStreamlines def test_ProcStreamlines_inputs(): input_map = dict(allowmultitargets=dict(argstr='-allowmultitargets', ),
args=dict(argstr='%s', ), datadims=dict(argstr='-datadims %s', units='voxels', ), directional=dict(argstr='-directional %s', units='NA', ), discardloops=dict(argstr='-discardloops', ), endpointfile=dict(argstr='-endpointfile %s', ), environ=dict(nohash=True, usede...
t(argstr='-gzip', ), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='-inputfile %s', mandatory=True, position=1, ), inputmodel=dict(argstr='-inputmodel %s', usedefault=True, ), iterations=dict(argstr='-iterations %d', units='NA', ), ...
Zearin/git-bup
wvtest.py
Python
lgpl-2.1
5,331
0.003189
#!/usr/bin/env python import traceback import os import re import sys if __name__ != "__main__": # we're imported as a module _registered = [] _tests = 0 _fails = 0 def wvtest(func): """ Use this decorator (@wvtest) in front of any function you want to run as part of the unit tes...
int 'Importing: %s' % modname wvtest
._registered = [] oldwd = os.getcwd() oldpath = sys.path try: path, mod = os.path.split(os.path.abspath(modname)) os.chdir(path) sys.path += [path, os.path.split(path)[0]] mod = __import__(modname.replace(os.path.sep, '.'), None, None, []) ...
Northshoot/AndroidContentProvider
acp/model/table.py
Python
apache-2.0
4,807
0.000208
# -*- coding: utf-8 -*- # _______ _______ _______ _______ _ # |\ /|( ___ )( ____ )( )( ___ )( ( /||\ /| # | ) ( || ( ) || ( )|| () () || ( ) || \ ( |( \ / ) # | (___) || (___) || (____)|| || || || | | || \ | | \ (_) / # | ___ || ___ || __)| |(_)| || | | || (...
eld in model.fields: foreign_key = field.foreign_key if foreign_key: continue ret += SqlBuilder.NEW_LINE ret += SqlBuilder.INDENT1 ret += SqlBuilder.IF ret += SqlBuilder.column_clauses(foreign_key.model) ret += SqlBuild...
ret += SqlBuilder.INDENT2 ret += SqlBuilder.CONCAT ret += SqlBuilder.LEFT_OUTER_JOIN ret += SqlBuilder.PLUS ret += field.foreign_key.model.name_camel_case ret += SqlBuilder.COLUMNS ret += SqlBuilder.TABLE_NAME ret += SqlBuilder.PLU...
ksopyla/tensorflow-mnist-convnets
mnist_2.0_5_layer_nn.py
Python
mit
6,492
0.00909
# encoding: UTF-8 # Copyright Krzysztof Sopyła (krzysztofsopyla@gmail.com) # # # Licensed under the MIT # Network architecture: # Five layer neural network, input layer 28*28= 784, output 10 (10 digits) # Output labels uses one-hot encoding # input layer - X[batch, 784] # 1 layer - W1[784,...
(Y, 1), tf.argmax(Y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # training, learning rate = 0.005 train_step = tf.train.GradientDescentOptimizer(0.005).minimize(cross_entropy) # m
atplotlib visualisation allweights = tf.concat([tf.reshape(W1, [-1]), tf.reshape(W2, [-1]), tf.reshape(W3, [-1]), tf.reshape(W4, [-1]), tf.reshape(W5, [-1])], 0) allbiases = tf.concat([tf.reshape(b1, [-1]), tf.reshape(b2, [-1]), tf.reshape(b3, [-1]), tf.reshape(b4, [-1]), tf.reshape(b5, [-1])], 0) # Initializing t...
CommonsCloud/CommonsRestless
tests/test_manager.py
Python
agpl-3.0
27,696
0.000217
""" tests.test_manager ~~~~~~~~~~~~~~~~~~ Provides unit tests for the :mod:`flask_restless.manager` module. :copyright: 2012 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com> :license: GNU AGPLv3+ or BSD """ import datetime from flask import json try: from flask.ext.sqlalchemy import SQLAl...
api(self.Person, allow_functions=True) response = self.app.get('/api/eval/person?q={}') assert response.status_code != 400 assert response.status_code == 204 def test_disallow_functions(self): """Tests that if the ``allow_functions`` keyword argument if ``False``, no endpoin...
be made available at :http:get:`/api/eval/...`. """ self.manager.create_api(self.Person, allow_functions=False) response = self.app.get('/api/eval/person') assert response.status_code != 200 assert response.status_code == 404 def test_include_related(self): """Test...
jbornschein/y2k
learning/tests/testing.py
Python
agpl-3.0
974
0.013347
import numpy as np import theano import thea
no.tensor as T theano.config.exception_verbosity = 'high' theano.config.compute_t
est_value = 'warn' floatX = theano.config.floatX def iscalar(name=None): Av = 1 A = T.iscalar(name=name) A.tag.test_value = Av return A, Av def fscalar(name=None): Av = 1.23 A = T.fscalar(name=name) A.tag.test_value = Av return A, Av def ivector(size, name=None): Av = np.zeros...
python-packages/vanity_app
src/vanity_app/vanity_app/config.py
Python
mit
11,226
0.001161
# encoding: utf-8 import os HERE = os.path.dirname(__file__) # Hosted config files BUILDOUT_USER = 'pythonpackages' BUILDOUT_INDEX = open(os.path.join(HERE, 'templates', 'buildout.html')).read() BUILDOUT_REPOS = ( ('buildout-apache-modwsgi', 'apache-modwsgi'), ('buildout-bluebream', 'bluebream'), ('buildo...
lobs/%s?%s') GITHUB_URL_REPOS_BLOB_ANON = (GITHUB_URL_API + '/repos/%s/%s/git/blobs/%s') # No qs needed GITHUB_URL_REPOS_COMMITS = GITHUB_URL_API +
'/repos/%s/%s/commits?%s' GITHUB_URL_REPOS_DELETE = GITHUB_URL_API + '/repos/%s/%s?%s' GITHUB_URL_REPOS_REFS = (GITHUB_URL_API + '/repos/%s/%s/git/refs?%s') GITHUB_URL_REPOS_TAGS = (GITHUB_URL_API + '/repos/%s/%s/git/tags?%s') GITHUB_URL_REPOS_TREE = (GITHUB_URL_API + '/repos/%s/%s/git/trees/%s?recursive=1?...
qzxx-syzz/study
python/Net/connect.py
Python
gpl-3.0
446
0.006726
#! /usr/bin/env python import socket print "creating socket..." s =
socket.socket(socket.AF_INET, socket.SOCK_STREAM) #ipv4, tcp print "done." print "looking up port number..." port = socket.getservbyname('http', 'tcp') print "done." print "connecting to remote host on port %d..." % port s.connect(("www.google.com", port)) print "done." print "connected f
rom", s.getsockname() #port randomly set print "connected to", s.getpeername()
mvaled/sentry
src/sentry/mediators/external_requests/util.py
Python
bsd-3-clause
953
0.003148
from __future__ import absolute_import from jsonschema import Draft4Validator SELECT_OPTIONS_SCHEMA = { "type": "array", "definitions": { "select-option": { "type": "object", "properties": {"label": {"type": "string"}, "value": {"type": "string"}}, "required": ["lab...
CHEMA, "issue_link": ISSUE_LINKER_SCHEMA
} def validate(instance, schema_type): schema = SCHEMA_LIST[schema_type] v = Draft4Validator(schema) if not v.is_valid(instance): return False return True
OmkarPathak/Python-Programs
CompetitiveProgramming/HackerEarth/Bit_Manipulation/P05_HihiAndCrazyBits.py
Python
gpl-3.0
1,216
0.011513
# Hihi is the grandfather of all geeks in IIITA. He and his crazy ideas.....Huh..... Currently, hihi is working on his most famous project # named 21 Lane, but he is stuck at a tricky segment of his code. # Hihi wants to assign some random IP addresses to users, but he won't use rand(). He wants to change the current...
nd differs by only 1 bit from the hash of original IP. # Smart Hihi already hashed the IP to some integer using his personal hash function. What he wants from you is to convert the given hashed # IP to the required IP X as mentioned above. # OK, just find the find the smallest number greater than n with exactly 1 bi...
tains hashed IP N ( 1 <= N <= 10^18) # Output : # Print T lines, each containing an integer X, the required IP.(don't worry Hihi will decode X to obtain final IP address) # SAMPLE INPUT # 5 # 6 # 4 # 10 # 12 # 14 # SAMPLE OUTPUT # 7 # 5 # 11 # 13 # 15 for _ in range(int(input())): a=int(input()) print(a|...
listyque/TACTIC-Handler
thlib/side/bs42/tests/test_html5lib.py
Python
epl-1.0
6,494
0.001386
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, ...
d> </head> <body> <p>foo</p> </body> </html>''' soup = self.soup(markup) # Verify that we can reach the <p> tag; this means the tree is connected. self.assertEqual(b"<p>foo</p>", soup.p.encode()) def test_reparented_markup(self): markup = '<p><em>foo</p>\n<p>bar<a></a></em>...
assertEqual(2, len(soup.find_all('p'))) def test_reparented_markup_ends_with_whitespace(self): markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>\n' soup = self.soup(markup) self.assertEqual(u"<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p>\n</body>", soup.body.decode()) ...
codl/forget
migrations/versions/04da9abf37e2_add_post_media.py
Python
isc
683
0.002928
"""add post media Revision ID: 04da9abf37e2 Revises: 2e3
a2882e5a4 Create Date: 2017-08-08 15:15:50.911420 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '04da9abf37e2' down_revision = '2e3a2882e5a4' branch_labels = None depends_on = None def upgrade(): op.add_column('accounts', sa.Colu
mn('policy_keep_media', sa.Boolean(), server_default='FALSE', nullable=False)) op.add_column('posts', sa.Column('has_media', sa.Boolean(), server_default='FALSE', nullable=False)) # ### end Alembic commands ### def downgrade(): op.drop_column('posts', 'has_media') op.drop_column('accounts', 'policy_ke...
afaerber/qemu-cpu
scripts/qapi-event.py
Python
gpl-2.0
5,197
0
# # QAPI event generator # # Copyright (c) 2014 Wenchao Xia # Copyright (c) 2015-2016 Red Hat Inc. # # Authors: # Wenchao Xia <wenchaoqemu@gmail.com> # Markus Armbruster <armbru@redhat.com> # # This work is licensed under the terms of the GNU GPL, version 2. # See the COPYING file in the top-level directory. from qa...
mp-event.h" ''', prefix=prefix)) fdecl.write(mcgen(''' #include "qapi/error.h" #include "qapi/qmp/qdict.h" #include "%(prefix)sqapi-types.h" ''',
prefix=prefix)) event_enum_name = c_name(prefix + "QAPIEvent", protect=False) schema = QAPISchema(input_file) gen = QAPISchemaGenEventVisitor() schema.visit(gen) fdef.write(gen.defn) fdecl.write(gen.decl) close_output(fdef, fdecl)
mpi4py/mpi4py
conf/cyautodoc.py
Python
bsd-2-clause
9,170
0.000545
from Cython.Compiler import Options from Cython.Compiler import PyrexTypes from Cython.Compiler.Visitor import CythonTransform from Cython.Compiler.StringEncoding import EncodedString from Cython.Compiler.AutoDocTransforms import ( ExpressionWriter as BaseExpressionWriter, AnnotationWriter as BaseAnnotationWrit...
ture, self).__call__(node) def visit_ClassDefNode(self, node): oldname = self.class_name oldclass = self.class_node self.class_node = node try: # PyClassDefNode self.class_name = node.name except AttributeError: # CClassDefNode ...
ode): # lambda expressions so not have signature or inner functions return node def visit_DefNode(self, node): if not self.current_directives['embedsignature']: return node is_constructor = False hide_self = False if node.entry.is_special: is...
drsmith48/fdp
fdp/methods/nstxu/bes/fft.py
Python
mit
3,236
0
# -*- coding: utf-8 -*- from warnings import warn import numpy as np import matplotlib.pyplot as plt from ....lib.utilities import isSignal, isContainer from ....lib.globals import FdpWarning from ...fft import Fft def fft(obj, *args, **kwargs): """ Calculate FFT(s) for signal or container. Return Fft ...
fig = plt.figure() ax = fig.add_subplot(1, 1, 1) pcm = ax.pcolormesh(sigfft.time, sigfft.freq, sigfft
.logpsd.transpose(), cmap=plt.cm.YlGnBu) pcm.set_clim([sigfft.logpsd.max() - 100, sigfft.logpsd.max() - 20]) cb = plt.colorbar(pcm, ax=ax) cb.set_label(r'$10\,\log_{10}(|FFT|^2)$ $(V^2/Hz)$') ax.set_xlabel('Time (s)') ax.set_ylabel('Frequency (kHz)') tmin = kwargs.get('tm...
toobaz/pandas
pandas/io/msgpack/__init__.py
Python
bsd-3-clause
1,223
0
# coding: utf-8 from collections import namedtuple from pandas.io.msgpack.exceptions import * # noqa from pandas.io.msgpack._version import version # noqa class ExtType(namedtuple("ExtType", "code data")): """ExtType represents ext type in msgpack.""" def __new__(cls, code, data): if not isinstan...
See :class:`Packer` for options. """ packer = Packer(**kwargs) stream
.write(packer.pack(o)) def packb(o, **kwargs): """ Pack object `o` and return packed bytes See :class:`Packer` for options. """ return Packer(**kwargs).pack(o) # alias for compatibility to simplejson/marshal/pickle. load = unpack loads = unpackb dump = pack dumps = packb
rldhont/Quantum-GIS
python/core/auto_additions/qgsmaplayer.py
Python
gpl-2.0
1,706
0.002345
# The following has been generated automatically from src/core/qgsmaplayer.h QgsMapLayer.LayerType = QgsMapLayerType # monkey patching scoped based enum QgsMapLayer.VectorLayer = QgsMapLayerType.VectorLayer QgsMapLayer.VectorLayer.__doc__ = "" QgsMapLayer.RasterLayer = QgsMapLayerType.RasterLayer QgsMapLayer.RasterLaye...
r``: ' + QgsMapLayerType.VectorTileLayer.__doc__ + '\n' + '* ``AnnotationLayer``: ' + QgsMapLayerType.AnnotationLayer.__doc__ # -- QgsMapLayer.LayerFlag.baseClass = QgsMapLayer QgsMapLayer.LayerFlags.baseClass = QgsMapLayer LayerFlags = QgsMapLayer # dirty hac
k since SIP seems to introduce the flags in module QgsMapLayer.StyleCategory.baseClass = QgsMapLayer QgsMapLayer.StyleCategories.baseClass = QgsMapLayer StyleCategories = QgsMapLayer # dirty hack since SIP seems to introduce the flags in module
varnivey/hakoton_images
image_preparation/cells_search.py
Python
gpl-2.0
1,484
0.020889
import matplotlib.pyplot as plt import numpy as np from image_funcs import * from scipy.misc import imread, imsave def grid(image, threshold): ############################################################################### import scipy.misc nuclei = imread('3.jpg') nuclei = scipy.misc.imresize(nuclei, 0.05) nuclei =...
fill_holes(nuclei) #imsave('nuclei.jpg', binary) from skimage.exposure import rescale_inten
sity rescaled_nuclei = rescale_intensity(nuclei, in_range=(np.min(nuclei),np.max(nuclei))) new_range = tuple(np.percentile(nuclei,(2,98))) rescaled_nuclei = rescale_intensity(nuclei, in_range=new_range) from skimage.filter import gaussian_filter blured = gaussian_filter(nuclei,8) plt.imshow(blured) highpass = nuclei...
futurice/fabric-deployment-helper
soppa/celery/__init__.py
Python
bsd-3-clause
311
0.016077
from soppa.contrib import *
class Celery(Soppa): def setup(self): self.action('up', 'celery_supervisor.conf', '{supervisor_conf_dir}celery_supervisor_{project}.conf',
handler=['supervisor.restart'], when=lambda x: x.soppa_proc_daemon=='supervisor',)
micromagnetics/magnum.fe
site-packages/magnumfe/common/wrapped_mesh.py
Python
lgpl-3.0
4,232
0.007798
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe 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) any later ...
on the super mesh. *Returns* :class:`dolfin.Function` The function on the sub mesh. """ mapping = self._get_mapping(f.function_space()) result = Function(mapping['Vsub']) result.vector()[:] = f.vector().array()[mapping['map']] result.rename(f.name(), f.label()) return result...
get = None): """ Takes a function defined on the sub mesh and returns a function defined on the super mesh with unknown values set to zero. *Arguments* f (:class:`dolfin.Function`) The function on the sub mesh. *Returns* The function on the super mesh. """ mapping = se...
the-zebulan/CodeWars
tests/kyu_7_tests/test_bug_fixing_unfinished_loop.py
Python
mit
541
0
import unittest from katas.kyu_7.bug_fixing_unfinished_loop import create_array class CreateArrayTestCase(unittest.TestCase): def test_equals(self):
self.assertEqual(create_array(1), [1]) def test_equals_2(self): self.assertEqual(create_array(2), [1, 2]) def test_equals_3(self): self.assertEqual(create_array(3), [1, 2, 3])
def test_equals_4(self): self.assertEqual(create_array(4), [1, 2, 3, 4]) def test_equals_5(self): self.assertEqual(create_array(5), [1, 2, 3, 4, 5])
humanist1965/hm65Vault
test.py
Python
gpl-3.0
212
0.04717
import os import sys def
getRootDir(): cwd = os.getcwd() print(cwd) pos = cwd.find("hm65Vault") print(pos) pos += len("hm65Vault") cwd = cwd[0:p
os] print(cwd) getRootDir() sys.exit(0)
sgtsquiggs/PlexThrottle
TransmissionCleanUp.py
Python
unlicense
3,486
0.003155
from datetime import datetime as dt from functools import reduce import transmissionrpc from config import config TRANSMISSION_ENABLED = config['TRANSMISSION_ENABLED'] TRANS_HOST = config['TRANS_HOST'] TRANS_PORT = config['TRANS_PORT'] TRANS_USER = config['TRANS_USER'] TRANS_PASS = config['TRANS_PASS'] TRANS_PUBLIC_...
len(delete_completed
_public_stopped_torrents(TRANS_HOST, TRANS_PORT, TRANS_USER, TRANS_PASS)) print("[%s] Torrents changed: %d; stopped: %d; deleted: %d" % (dt.now().strftime('%Y-%m-%d %H:%M:%S'), num_changed, num_stopped, num_deleted))
CognizantOneDevOps/Insights
PlatformAgents/com/cognizant/devops/platformagents/agents/deployment/rundeck/RundeckAgent.py
Python
apache-2.0
2,690
0.005204
#------------------------------------------------------------------------------- # Copyright 2017 Cognizant Technology Solutions # # 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:...
if not self.tracking.get(ProjName, ''): getProjectDetailsUrl = ExecutionsBaseEndPoint+"/"+ProjName+"/executions?authtoken="
+authtoken+"&begin="+startFrom else: TimeStamp = self.tracking.get(ProjName, '') TimeStamp = str(TimeStamp) getProjectDetailsUrl = ExecutionsBaseEndPoint+"/"+ProjName+"/executions?authtoken="+authtoken+"&begin="+TimeStamp rundeckProjectDetails = se...
IndiciumSRL/wirecurly
tests/test_serialization/utils.py
Python
mpl-2.0
2,146
0.007922
from itertools import groupby from lxml import etree def xml2d(e): """Convert an etree into a dict structure @type e: etree.Element @param e: the root of the tree @return: The dictionary representation of the XML tree """ def _xml2d(e): kids = dict(e.attrib) # if e.text: ...
alue is a simple string, then the key is an attribute 4. if a value is dict then, then key is a subelement 5. if a value is list, then key is a set of sublements a = { 'module' : {'tag' : [ { 'name': 'a', 'value': 'b'}, { 'name': 'c', 'value': 'd'}, ...
} } >>> d2xml(a) <module uri="test"> <gobject type="xx" name="g"/> <tag name="a" value="b"/> <tag name="c" value="d"/> </module> @type d: dict @param d: A dictionary formatted as an XML document @return: A etree Root element """ def _d2xm...
adbetin/organico-cooperativas
cooperativa/migrations/0003_auto_20171008_1549.py
Python
gpl-3.0
464
0
# -*- coding: utf-8 -*- # Generated by Dja
ngo 1.11.4 on 2017-10-08 20:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cooperativa', '0002_auto_20171005_1404'), ] operations = [ migrations.AlterField( model_name='cooperativa...
n', field=models.CharField(max_length=255), ), ]
remybaranx/qtaste
demo/TestSuites/PlayBack/VisibilityCheck/TestScript.py
Python
gpl-3.0
1,239
0.008071
# encoding= utf-8 ## # VisibilityCheck. # <p> # Description of the test. # # @data INSTANCE_ID [String] instance id ## from qtaste import * import time # update in order to cope with the javaGUI extension declared in your testbed configuration. javaguiMI = testAPI.getJavaGUI(INSTANCE_ID=testData.getValue("JAVAGUI_I...
""" @step Description of the actions done for this step @expected Description of the expected result """ doSubSteps(TabbedPaneSelection.changeTabByTitle) subtitler.setSubtitle("Click on the button to make the component invisible") time.sleep(1) javaguiMI.clickOnButton("VISIBILITY_...
component should not be visible") try: subtitler.setSubtitle("Try to insert a value in the invible text field", 10) javaguiMI.setText("VISIBILITY_TEXT", "pas bien") testAPI.stop(Status.FAIL, "The component should not be visible and the setText() should failed") except : javagui...
radiateboy/Demo126mail
testcase/public/__init__.py
Python
gpl-2.0
98
0.020408
#-*- coding: utf-8 -*- __author__ = 'tsbc
' import sys r
eload(sys) sys.setdefaultencoding('utf-8')
kamawanu/pydbgr
trepan/bwprocessor/command/base_cmd.py
Python
gpl-3.0
3,660
0.001366
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, 2012-2013 Rocky Bernstein # # 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 lat...
le is the one module in this directory that isn't a real command and commands.py needs to take care to avoid instantiating this class and storing it as a list of known debugger commands. """ NotImplementedMessage = "This method must be overriden in a
subclass" from import_relative import import_relative __all__ = ['DebuggerCommand'] class DebuggerCommand: """Base Class for Debugger commands. We pull in some helper functions for command from module cmdfns.""" category = 'misc' def __init__(self, proc): """proc contains the command proce...
SOM-st/PySOM
src/som/primitives/bc/integer_primitives.py
Python
mit
4,603
0.000652
from rlib import jit from som.primitives.integer_primitives import IntegerPrimitivesBase as _Base from som.vmobjects.double import Double from som.vmobjects.integer import Integer from som.vmobjects.primitive import Primitive, TernaryPrimitive def get_printable_location_up(block_method): from som.vmobjects.metho...
hod) return "downToto:do: " + block_method.merge_point_string() jitdriver_int_down = jit.JitDriver(
name="downTo:do: with int", greens=["block_method"], reds="auto", # virtualizables=['frame'], is_recursive=True, get_printable_location=get_printable_location_down, ) jitdriver_double_down = jit.JitDriver( name="downTo:do: with double", greens=["block_method"], reds="auto", # virtu...
Stargrazer82301/CAAPR
CAAPR/CAAPR_AstroMagic/PTS/pts/core/plot/memory.py
Python
mit
7,242
0.002762
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
er): """ This class ... """ def __init__(self): """ The constructor ... :return: """ # Call the constructor of the base class super(MemoryPlotter, self).__init__() # -- Attributes -- # A data structure to store the memory (de)allocati...
nformation self.allocation = None # ----------------------------------------------------------------- @staticmethod def default_input(): """ This function ... :return: """ return "memory.dat" # ---------------------------------------------------------...
sunshine027/iris-panel
iris/etl/scm.py
Python
gpl-2.0
8,948
0.000112
# -*- encoding: utf-8 -*- # This file is part of IRIS: Infrastructure and Release Information System # # Copyright (C) 2013-2015 Intel Corporation # # IRIS is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # version 2.0 as published by the Free Software Found...
""" if not email: return # get the user which is from LDAP users = User.objects.filte
r(email=email).exclude(username=email) def updata_role(role, old, new): role.user_set.remove(old) role.u
nailgun/seedbox
src/seedbox/manage.py
Python
apache-2.0
478
0
import logging from flask_script import Manager from flask_migrate import MigrateCommand from seedbox.app import app manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def watch_updates(): """Starts component updates watche
r in foreground (CoreOS, k8s, etcd)""" from seedbox import update_watcher update_watcher.watc
h() def run(): logging.basicConfig(level='NOTSET') manager.run() if __name__ == '__main__': run()
jor-/scipy
scipy/linalg/decomp_lu.py
Python
bsd-3-clause
6,757
0.000444
"""LU decomposition functions.""" from __future__ import division, print_function, absolute_import from warnings import warn from numpy import asarray, asarray_chkfinite # Local imports from .misc import _datacopied, LinAlgWarning from .lapack import get_lapack_funcs from .flinalg import get_flinalg_funcs __all__ ...
to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but
may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- **(If permute_l == False)** p : (M, M) ndarray Permutation matrix l : (M, K) ndarray Lower triangular or trapezoidal matrix with unit diagonal. K = min(M,...
Spoken-tutorial/spoken-website
cron/upload-subtitle.py
Python
gpl-3.0
7,439
0.010082
from builtins import str from builtins import object import httplib2 import MySQLdb import json import os import sys import time import config from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import OAuth2WebServerFlow from oauth2client.tools import run class Erro...
when uploading captions \ to %s." % (response_headers["status"], url), False return '
%s - %s %s - caption updated' % (video_id, \ self.CAPTIONS_LANGUAGE_CODE, self.CAPTIONS_TITLE), True def set_caption_language_title(self, language='', title=''): self.CAPTIONS_LANGUAGE_CODE = language self.CAPTIONS_TITLE = title if __name__ == "__main__": caption = YoutubeCaption...
CodeAtCode/CSVEmailVerifier
mergecsv.py
Python
gpl-2.0
340
0
#!/usr/bin/python # First parameter: the pattern for the files in "" # Second parameter: output file import glob import sys read_files = sorted(glob.glob(sys.argv[1])) with open(sys.argv[2], "wb")
as outfile:
for f in read_files: with open(f, "rb") as infile: outfile.write(infile.read()) print("File generated")
MSusik/invenio
invenio/modules/deposit/restful.py
Python
gpl-2.0
18,728
0.000694
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013, 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your opt...
else: schema = self.input_schema # Either conform to dictionary schema or dictionary is empty if not v.validate(request.json, schema) and \ request.json: abort(
400, message="Bad request", status=400, errors=filter_validation_errors(v.errors), ) def process_input(self, deposition, draft_id=None): """ Process input data """ # If data provided, process it if request.json: if dr...
onebsv1/floodlight
example/mininet/dhcp_linear_sw.py
Python
apache-2.0
6,108
0.009987
#!/usr/bin/python import json import httplib import os import subprocess import time from mininet.cli import CLI from mininet.log import setLogLevel, info from mininet.net import Mininet from mininet.node import RemoteController from mininet.topo import Topo from mininet.util import irange HOME_FOLDER = os.getenv('HO...
# Start DHCP ret = enableDHCPServer() print(ret) addDHCPInstance1('mininet-dhcp-1') ret = addSwitchToDHCPInstance1('mininet-dhcp-1') print(ret) addDHCPInstance2('mininet-dhcp-2') ret = addSwitchToDHCPInstance2('mininet-dhcp
-2') print(ret) hosts = net.hosts for host in hosts: mountPrivateResolvconf(host) startDHCPclient(host) waitForIP(host) def stopNetwork(): if net is not None: info('** Tearing down network\n') hosts = net.hosts for host in hosts: unmountPriv...
Ajapaik/ajapaik-web
ajapaik/ajapaik/management/commands/tartunlp_on_all_albums.py
Python
gpl-3.0
963
0.001038
from django.core.management.base import BaseCommand from django.db.models import Q from ajapaik.ajapaik.models import Album class Command(BaseCommand): help = 'Connects to TartuNLP API and retrieves neuro machine translations for empty name fields' def handle(self, *args, **options): albums = Album....
(name_original_language__isnull=False) | Q(atype=Album.PERSON) | Q(atype=Album.COLLECTION) ).filter( Q(name_et__isnul
l=False) | Q(name_lv__isnull=False) | Q(name_lt__isnull=False) | Q(name_fi__isnull=False) | Q(name_ru__isnull=False) | Q(name_de__isnull=False) | Q(name_en__isnull=False) ) for each in albums: print(f'Processing Album {e...
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/dependencies/tests/test_functions.py
Python
mit
4,537
0
from nose.tools import eq_, raises from ...errors import DependencyError, DependencyLoop from ..dependent import Dependent from ..functions import dig, draw, expand, normalize_context, solve def test_solve(): # Simple functions eq_(solve(lambda: "foo"), "foo") eq_(list(solve([lambda: "foo", lambda: "bar"...
bar = Dependent("bar", lambda: "bar") foobar = Dependent("foobar", lambda foo, bar: foo + bar, depends_on=[foo, bar]) derp = Dependent("derp", lambda: "derp") fooderp = Dependent("fooder
p", lambda foo, derp: foo + derp, depends_on=[foo, derp]) dependents = list(expand(foobar)) eq_(len(dependents), 3) eq_(set(dependents), {foo, bar, foobar}) dependents = list(expand([fooderp, foobar])) eq_(len(dependents), 5) eq_(set(dependents), {derp, fooderp, foo, ba...
admesh/python-admesh
test/test_io.py
Python
gpl-2.0
1,085
0.00093
# -*- coding: utf-8 -*- from admesh import Stl from utils import asset import filecmp
class TestIO(object): '''Tests for the basic IO operations''' def test_saved_equals_original_ascii(self): '''Tests if saved ASCII file is identical to the loaded one'''
stl = Stl(asset('block.stl')) stl.write_ascii(asset('block_ascii.stl')) assert filecmp.cmp(asset('block.stl'), asset('block_ascii.stl')) def test_saved_equals_original_binary(self): '''Tests if saved binary file is identical to the loaded one''' stl1 = Stl(asset('block.stl')) ...
bkuczenski/lca-tools
antelope_catalog/providers/v1_client/tests/test_antelope_v1_client.py
Python
gpl-2.0
1,973
0.005068
import unittest from antelope_catalog.data_sources.local import TEST_ROOT from antelope_catalog import LcCatalog from lcatools.interfaces import IndexRequired cat = LcCatalog(TEST_ROOT) ref = 'calrecycle.antelope' cat.new_resource(ref, 'http://www.antelope-lca.net/uo-lca/api/', 'AntelopeV1Client', ...
self.assertEqual(inv.get_stage_name('42'), 'Na
tural Gas') self.assertEqual(inv.get_stage_name('47'), 'Natural Gas Supply') self.assertEqual(inv.get_stage_name('81'), 'WWTP') def test_impactcategory(self): self.assertEqual(ar._get_impact_category(6), 'Cancer human health effects') with self.assertRaises(ValueError): ...
ewandor/home-assistant
homeassistant/components/homematic/__init__.py
Python
apache-2.0
29,766
0
""" Support for HomeMatic devices. For more details about this component, please refer to the documentation at
https://home-assistant.io/components/homematic/ """ import asyncio from datetime import timedelta from functools import partial import logging import os import socket import voluptuous as vol from homeassistant.config import load_yaml_config_file from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, CONF_US...
from homeassistant.helpers import discovery from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv from homeassistant.loader import bind_hass REQUIREMENTS = ['pyhomematic==0.1.36'] DOMAIN = 'homematic' _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL_HUB = timedelta(se...
MarionTheBull/watchmaker
docs/conf.py
Python
apache-2.0
9,706
0.000206
# -*- coding: utf-8 -*- # # MothBall documentation build configuration file, created by # sphinx-quickstart on Thu Jun 30 20:11:36 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # ...
_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # from recommonmark.parser import CommonMarkParser source_suffix = ['.rst', '.md'] parsers = { '.md': CommonMarkParser, } # source_suffix = '.rst' # The encoding of source files. # # source_encodin...
# 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. # # The short X.Y version. version = u'0.1' # The full version, including alpha/beta/rc tags. release = u'0.1' # The language for content autogen...
HPI-SWA-Lab/RSqueak
rsqueakvm/plugins/vmdebugging/hooks.py
Python
bsd-3-clause
3,381
0.002958
from rsqueakvm.util.cells import QuasiConstant from rsqueakvm.plugins.vmdebugging.model import wrap_oplist, wrap_greenkey, wrap_debug_info from rpython.rlib.jit import JitHookInterface, Counters jit_iface_recursion = QuasiConstant(False) def make_hook(args, func): import inspect, re src = "\n".join([ ...
hook(self, debug_info, is_bridge=False): jitdriver = debug_info.get_jitdriver() self.wrapped_compiled_hook(jitdriver, debug_info, is_bridge) def after_compile(self, debug_info): self._compile_hook(debug_in
fo, is_bridge=False) def after_compile_bridge(self, debug_info): self._compile_hook(debug_info, is_bridge=True) def before_compile(self, debug_info): pass def before_compile_bridge(self, debug_info): pass jitiface = JitIface()
gluke77/rally
rally/plugins/common/sla/outliers.py
Python
apache-2.0
4,530
0
# Copyright 2014: Mirantis 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 b...
pdate the threshold value self.mean_comp.add(duration) self.std_comp.add(dura
tion) if self.iterations >= 2: mean = self.mean_comp.result() std = self.std_comp.result() self.threshold = mean + self.sigmas * std self.success = self.outliers <= self.max_outliers return self.success def merge(self, other): # N...
pablotcarreira/django-arangodb
sample_project/settings.py
Python
apache-2.0
4,023
0.001491
""" Django settings for sample project. Generated by 'django-admin startproject' using Django 1.10.1. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os ...
'HOST': 'localhost', 'PORT': '8529', 'NAME': 'teste_python', 'USER': 'root', 'PASSWORD': 'omoomo',
} } # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'defaultbd', # }, # 'arangodb': { # 'ENGINE': 'arangodb_driver', # 'HOST': 'localhost', # 'PORT': '8529', # 'NAME': 'teste_python', # 'USER': 'root', # ...
yerejm/ttt
noxfile.py
Python
isc
1,940
0.000515
import tempfile import nox nox.options.sessions = "lint", "tests" locations = "src", "tests", "noxfile.py" def install_with_constraints(session, *args, **kwargs): with tempfile.NamedTemporaryFile() as requirements: session.run( "poetry", "export", "--dev", ...
rgs) @nox.session(python="3.9") def safety(session): with tempfile.NamedTemporaryFile() as requirements: session.run( "poetry", "export", "--dev", "--format=requirements.txt", "--without-hashes", f"--output={requirements.name}", ...
"safety", ) session.run("safety", "check", f"--file={requirements.name}", "--full-report") @nox.session(python=["3.9", "3.8"]) def tests(session): args = session.posargs or ["--cov", "-m", "not e2e"] session.run("poetry", "install", "--no-dev", external=True) install_with_const...
GedRap/xs-vm
xsvm/vm.py
Python
mit
4,947
0.001819
from xsvm import instructions from tabulate import tabulate class Memory: def __init__(self): self.memory_storage = {} self.labels_map = {} def set(self, address, value): self.memory_storage[address] = value def set_label(self, label, address): self.labels_map[label] = add...
def get(self, register): register = RegisterBank._resolve_alias(register) RegisterBank._validate_register_name(register) return self.registers[register] def set(self, register, value): register =RegisterBank._resolve_alias(register) RegisterBank._validate_register_name(reg...
reg_right = "r{r}".format(r=i+1) table_content.append([reg_left, self.get(reg_left), reg_right, self.get(reg_right)]) return tabulate(table_content, tablefmt="fancy_grid") @staticmethod def _resolve_alias(register): if register in RegisterBank.aliases: regi...
Ebag333/Pyfa
eos/db/gamedata/item.py
Python
gpl-3.0
3,101
0.002902
# =============================================================================== # Copyright (C) 2010 Diego Duclos # # This file is part of eos. # # eos 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, ...
Integer), Column("volume", Float), Column("mass", Float), Column("capacity", Float), Column("published", Boolean), Column("marketGroupID", Integer, ForeignKey("invmarketgroups.marketGroupID")),
Column("iconID", Integer, ForeignKey("icons.iconID")), Column("groupID", Integer, ForeignKey("invgroups.groupID"), index=True)) from .metaGroup import metatypes_table # noqa from .traits import traits_table # noqa mapper(Item, items_table, properties={"group": relation(Group, backr...
jtaylor/pysfm
sfm/util.py
Python
bsd-3-clause
3,379
0.025155
"""Utility functions.""" import numpy as np def vec(X, order='F'): """Returns the vectorization of X. Columns of X are stacked. (The opposite of X.flatten()).""" assert X.ndim == 2, 'vec operator requires a matrix.' return X.flatten(order=order) def from_vec(x, m, n, order='F'): return x.resh...
re(x), axis=axis)) def normed(x, axis = -1): if axis <
-x.ndim or axis >= x.ndim: raise ValueError("axis(=%d) out of bounds" % axis) if axis < 0: axis += x.ndim shape = list(x.shape) shape[axis] = 1 shape = tuple(shape) return x / norm(x,axis=axis).reshape(shape)
llvm-mirror/lldb
packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsString.py
Python
apache-2.0
2,009
0.00896
""" Test more expression command sequences with objective-c. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil @skipUnlessDarwin class FoundationTestCaseString(TestBase): mydir = TestBase.comp...
\$.* = 0x"]) self.expect("expression str.length") self.expect('expression str = @"new"') self
.runCmd("image lookup -t NSString") self.expect('expression str = (id)[NSString stringWithCString: "new"]') self.runCmd("process continue") @expectedFailureAll(archs=["i[3-6]86"], bugnumber="<rdar://problem/28814052>") def test_MyString_dump_with_runtime(self): """Test dump of a known O...
agiledata/python-gpiozero
gpiozero/input_devices.py
Python
bsd-3-clause
5,990
0.001503
from __future__ import division from time import sleep, time from threading import Event from collections import deque from RPi import GPIO from w1thermsensor import W1ThermSensor from .devices import GPIODeviceError, GPIODevice, GPIOThread class InputDeviceError(GPIODeviceError): pass class InputDevice(GPIO...
eue_len=5, darkness_time=0.01, threshold=0.1, partial=False): super(LightSensor, self).__init__(pin, pull_up=False) if queue_len < 1: raise InputDeviceError('queue_len must be at least one')
self.darkness_time = darkness_time self.threshold = threshold self.partial = partial self._charged = Event() GPIO.add_event_detect(self.pin, GPIO.RISING, lambda channel: self._charged.set()) self._queue = deque(maxlen=queue_len) self._queue_full = Event() ...
ericholscher/django
tests/custom_managers/tests.py
Python
bsd-3-clause
6,629
0.000905
from __future__ import unicode_literals from django.test import TestCase from django.utils import six from .models import Person, Book, Car, PersonManager, PublishedBookManager class CustomManagerTests(TestCase): def setUp(self): self.b1 = Book.published_objects.create( title="How to program...
rtQuerysetEqual( self.b1.favorite_things(manager='fun_people').all(), [ "Bugs", ], lambda c: c.first_name ) def test_related_manager_m2m(self): self.b1.authors.add(self.p1) self.b1.authors.add(self.p2) self.assertQuerysetEqual( ...
"Droopy", ], lambda c: c.first_name ) self.assertQuerysetEqual( self.b1.authors(manager='boring_people').all(), [ "Droopy", ], lambda c: c.first_name ) self.assertQuerysetEqual( self.b1.authors(m...
birkenfeld/conduct
conduct/loggers.py
Python
gpl-2.0
10,769
0.000464
# ***************************************************************************** # conduct - CONvenient Construction Tool # # 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...
""" A lightweight formatter for the interactive console, with optional colored output. """ def __init__(self, fmt=None, datefmt=None, colorize=None): Formatter.__init__(s
elf, fmt, datefmt) if colorize: self.colorize = colorize else: self.colorize = lambda c, s: s def formatException(self, exc_info): return traceback.format_exception_only(*exc_info[0:2])[-1] def formatTime(self, record, datefmt=None): return time.strftime...
CroceRossaItaliana/jorvik
anagrafica/migrations/0025_auto_20160129_0056.py
Python
gpl-3.0
670
0.001493
# -*- coding: utf-8 -*- from __fut
ure__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('anagrafica', '0024_auto_20160129_0053'), ] operations = [ migrations.AlterIndexTogether( name='delega', index_together=set([('persona'...
e'), ('oggetto_tipo', 'oggetto_id'), ('tipo', 'oggetto_tipo', 'oggetto_id'), ('persona', 'inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('persona', 'inizio', 'fine', 'tipo')]), ), ]
amorphic/braubuddy
braubuddy/tests/output/test_libratoapi.py
Python
bsd-3-clause
1,721
0
""" Braubuddy LibratoAPI unit tests. """ from mock import call, patch, MagicMock from braubuddy.tests import BraubuddyTestCase from braubuddy.output import libratoapi @patch('braubuddy.output.libratoapi.librato.connect') class LibratoAPIOutput(BraubuddyTestCase): def test_librato_api_connect(self, mk_libratoapi...
self.assertEqual( mk_queue.add.mock_calls, [ call('target_temperature', 26, source='braubuddy'), call('actual_temperature',
20, source='braubuddy'), call('heater_percent', 0, source='braubuddy'), call('cooler_percent', 100, source='braubuddy') ]) self.assertTrue(mk_queue.submit.called)