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
rvs/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/basebackup/test_filespace.py
Python
apache-2.0
3,304
0.003632
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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 ...
Override """ # Removing standby as these tests will fail if there is a standby enabled # Ignore any failures run_shell_command(cmdstr='gpinitstandby -ra',
cmdname='remove standby') self.createdb(self.db_name) self.standby = Standby(self.standby_datadir, self.standby_port) def tearDown(self): """ Override """ try: dburl = dbconn.DbURL() self.standby.remove_catalog_standby(dburl) ex...
mzdaniel/oh-mainline
vendor/packages/Django/tests/regressiontests/generic_inline_admin/tests.py
Python
agpl-3.0
13,477
0.003487
# coding: utf-8 from django.conf import settings from django.contrib.contenttypes.generic import generic_inlineformset_factory from django.test import TestCase # local test models from models import Episode, EpisodeExtra, EpisodeMaxNum, EpisodeExclude, \ Media, EpisodePermanent, MediaPermanentInlin...
or="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-...
t(instance=e, queryset=Media.objects.filter(url__endswith=".png")) self.assertEqual(len(formset.forms), 4) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-...
albertaparicio/tfglib
tfglib/pretrain_data_params.py
Python
lgpl-3.0
12,490
0.00008
# Created by Albert Aparicio on 03/02/2017 # coding: utf-8 # This import makes Python use 'print' as in Python 3.x from __future__ import print_function import os from random import shuffle from sys import version_info from time import time import numpy as np from h5py import special_dtype, File from tfglib.constru...
um and minimum values spk_max[spk_index, :] = np.maximum( spk_max[spk_index, :], np.ma.max(seq_params, axis=0) ) spk_min[spk_index, :] = np.minimum( spk_min[spk_index, :], np.ma.min(seq_params, axis=0) ) print('...
values as attributes f.attrs.create('longest_sequence', longest_sequence, dtype=int) f.attrs.create('speakers_max', spk_max) f.attrs.create('speakers_min', spk_min) # TODO Support Python 2 # sys.version_info -> Get running Python version dt = special_dtype(vlen=str) ...
rjschwei/azure-sdk-for-python
azure-mgmt-logic/azure/mgmt/logic/models/x12_processing_settings.py
Python
mit
2,753
0.002543
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
ey': 'createEmptyXmlTagsForTrailingSeparators', 'type': 'bool'}, 'use_dot_as_decimal_separator': {'key': 'useDotAsDecimalSeparator', 'type': 'bool'}, } def __init__(self, mask_security_info=None, convert_implied_decimal=None, preserve_interchange=None, suspend_interchange_on_error=Non
e, create_empty_xml_tags_for_trailing_separators=None, use_dot_as_decimal_separator=None): self.mask_security_info = mask_security_info self.convert_implied_decimal = convert_implied_decimal self.preserve_interchange = preserve_interchange self.suspend_interchange_on_error = suspend_inte...
simoninireland/epydemic
test/test_monitor.py
Python
gpl-3.0
3,479
0.002587
# Test process monitoring # # Copyright (C) 2020 Simon Dobson # # This file is part of epydemic, epidemic network simulations in Python. # # epydemic 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 vers...
try: nb = epyc.HDF5LabNotebook(fn, create=True) lab = epyc.Lab(nb) # run the experiment m = MonitoredSIR() m.setMaximumTime(100) e = Stocha
sticDynamics(m, networkx.erdos_renyi_graph(1000, 5.0 / 1000)) lab[SIR.P_INFECTED] = 0.01 lab[SIR.P_INFECT] = 0.002 lab[SIR.P_REMOVE] = 0.002 lab[Monitor.DELTA] = 1.0 rc = lab.runExperiment(e) df = lab.dataframe() # check we read back i...
aaronr/shapely
shapely/geometry/multipolygon.py
Python
bsd-3-clause
4,465
0.002688
"""Collections of polygons and related utilities """ from ctypes import c_void_p, cast from shapely.geos import lgeos from shapely.geometry.base import BaseMultipartGeometry from shapely.geometry.polygon import Polygon, geos_polygon_from_py from shapely.geometry.proxy import CachingGeometryProxy __all__ = ['MultiPol...
erty def __geo_interface__(self): allcoords =
[] for geom in self.geoms: coords = [] coords.append(tuple(geom.exterior.coords)) for hole in geom.interiors: coords.append(tuple(hole.coords)) allcoords.append(coords) return { 'type': 'MultiPolygon', 'coordinates'...
open-telemetry/opentelemetry-python
exporter/opentelemetry-exporter-otlp-proto-grpc/setup.py
Python
apache-2.0
961
0
# Copyright The OpenTelemetry 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 law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES ...
for the specific language governing permissions and # limitations under the License. import os import setuptools BASE_DIR = os.path.dirname(__file__) VERSION_FILENAME = os.path.join( BASE_DIR, "src", "opentelemetry", "exporter", "otlp", "proto", "grpc", "version.py", ) PACKAGE_INFO = ...
Kilves/finnchan
chan/migrations/0012_auto_20161226_2331.py
Python
bsd-3-clause
1,792
0.003348
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-26 23:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('chan', '0011_auto_20161225_1559'), ] operations = ...
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ip', models.CharField(max_length=46)), ('expires', models.DateTimeField(null=True)), ], ), migrations.AlterField( mode...
-4823-9344-0bc0f7d42019', max_length=256), ), migrations.AlterField( model_name='attachment', name='post', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='chan.Post'), ), migrations.AlterF...
iandees/pyosm
pyosm/api.py
Python
mit
2,668
0.001124
import urllib2 from pyosm.parsing import iter_osm_file, iter_osm_change_file class Api(object): def __init__(self, base_url='https://api.openstreetmap.org/api'): self._base = base_url self.USER_AGENT = 'pyosm/1.0 (http://github.com/iandees/pyosm)' def _get(self, path, params={}): head...
rsion=None): path = '/0.6/{}/{}'.format(kind, thing_id)
if version: path += '/' + str(version) everything = self._get_as_osm(path) single = None if everything: single = next(iter(everything)) return single def get_node(self, node_id, version=None): return self._get_object_revision_as_osm('node', node_id...
designed27/firebase-backup-s3-python
backup-firebase.py
Python
mit
1,486
0.010767
from firebase import firebase import os import datetime import json import logging from boto.s3.connection import S3Connection from boto.s3.key import Key ## FIREBASE ACCESS INFO ## firebase_url = 'https://your-app.firebaseio.com/' #Or get from environment variable firebase_secret = os.environ['FIREBASE_SECRET'] fireb...
ation = firebase.FirebaseAuthentication(firebase_secret, firebase_username, admin=True) return f logger.info('Starting firebase data backup now...') #Use UTC time in key name now = datetime.datetime.utcnow() name = 'firebase_' + now.strftime('%Y-%m-%d--%H-%M-%S.%f') + '.json' f = connect_firebase() data = f.get...
#Save key with json data to S3 k.set_contents_from_string(unicode(json.dumps(data, ensure_ascii=False))) logger.info('Done.')
coherence-project/Coherence
misc/Nautilus/coherence_upnp_upload_extension.py
Python
mit
3,481
0.00316
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2008 Frank Scholz <coherence@beebits.net> """ Coherence and Nautilus bridge to upload files into a DLNA/UPnP MediaServer usable as Nautilus Extension or a Script for u...
item.connect('activate', self.import_resources, files) return item, def import_resources(self, menu, files): if len(files) == 0: return show_upload_widget([unquote(file.get_uri()[7:]) for file in files], standalone=False) except ImportError: ...
r(x)] show_upload_widget(files) gtk.gdk.threads_init() gtk.main()
fluentpython/isis2json
isis2json.py
Python
gpl-2.0
10,305
0.000679
#!/usr/bin/env python # -*- encoding: utf-8 -*- # isis2json.py: convert ISIS and ISO-2709 files to JSON # # Copyright (C) 2010 BIREME/PAHO/WHO # # This program 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 Found...
d_occurrences.append(''.join(conte
nt)) else: raise NotImplementedError('ISIS-JSON type %s conversion ' 'not yet implemented for .mst input' % isis_json_type) yield fields mst.close() def iter_iso_records(iso_file_name, isis_json_type): from iso2709 import IsoFile from subfield import...
glennyonemitsu/MarkupHiveServer
alembic/versions/20130510011014-add_canonical_domain.py
Python
mit
482
0.004149
"""add canonical domain column to account Revision ID: 1efbbd8d6721 Revises: 1e0b325c185e Create Date: 2013-05-10 01:1
0:14.676068 """ # revision identifiers, used by Alembic. revision = '1efbbd8d6721' down_revision = '1e0b325c185e' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'account', sa.Column('canonical_domain', sa.String(250), nullable=True) ) def downgrade(): op....
nt', 'canonical_domain')
dimagi/commcare-hq
corehq/apps/smsbillables/migrations/0018_index__date_sent.py
Python
bsd-3-clause
429
0
# Generated by Django 1.11.11 on 2018-04-01 00:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('smsbillables', '0017
_deactivate_grapevine_instance_fee_criteria
'), ] operations = [ migrations.AlterField( model_name='smsbillable', name='date_sent', field=models.DateTimeField(db_index=True), ), ]
yeleman/rtfw
rtfw/__init__.py
Python
gpl-2.0
1,181
0.000847
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) from rtfw.PropertySets import (AttributedList, Colours, Fonts, Papers, MarginsPS, ShadingPS,...
S, ARIAL_BULLET) from rtfw.Styles import (TextStyle, ParagraphStyle) from rtfw.Renderer import (Setti
ngs, Renderer)
grissiom/rt-thread
bsp/nuclei/hbird_eval/rtconfig.py
Python
gpl-2.0
1,968
0.012703
import os # toolchains options ARCH='risc-v' CPU='nuclei' CROSS_TOOL='gcc' if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' EXEC_PATH = 'D:/Software/Nuclei/gcc/bin' else: print("CROSS_TOOL = {} not yet supported" % CROSS_TOOL) # if os.getenv('RTT_EX...
'g++' AS = PREFIX + 'gcc' AR = PREFIX + 'ar' LINK = PREFIX + 'gcc' GDB = PREFIX + 'gdb' TARGET_EXT = 'elf' SIZE = PREFIX + 'size' OBJDUMP = PREFIX + 'objdump' OBJCPY = PREFIX + 'objcopy' CFLAGS = ' -ffunction-sections -fdata-sections -fno-common ' AFLAGS ...
ef,-Map=rtthread.map' LFLAGS += ' -u _isatty -u _write -u _sbrk -u _read -u _close -u _fstat -u _lseek ' CPATH = '' LPATH = '' LIBS = ['stdc++'] if BUILD == 'debug': CFLAGS += ' -O2 -ggdb' AFLAGS += ' -ggdb' else: CFLAGS += ' -O2 -Os' CXXFLAGS = CFLAGS DUMP_AC...
mtils/ems
ems/qt4/location/plugins/nokia/geomapreply_nokia.py
Python
mit
2,504
0.006789
''' Created on 16.11.2011 @author: michi ''' from PyQt4.QtCore import pyqtSlot, QDateTime from PyQt4.QtNetwork import QNetworkReply, QNetworkRequest from ems.qt4.location.maps.tiled.geotiledmapreply import GeoTiledMapReply class GeoMapReplyNokia(GeoTiledMapReply): _m_reply = QNetworkReply def __ini...
''' GeoTiledMapReply.__init__(self, request, parent=parent) self._m_reply = reply self._m_reply.setParent(self) self._m_reply.finished.connect(self._networkFi
nished) self._m_reply.error.connect(self._networkError) self._m_reply.destroyed.connect(self._replyDestroyed) def networkReply(self): ''' @rtype: QNetworkReply ''' return self._m_reply def abort(self): if not self._m_reply: return ...
lukecwik/incubator-beam
sdks/python/apache_beam/examples/cookbook/bigquery_tornadoes.py
Python
apache-2.0
3,690
0.002981
# # 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 us...
) # Write the output using a "Write" transform that has side effects. # pylint: disa
ble=expression-not-assigned counts | 'Write' >> beam.io.WriteToBigQuery( known_args.output, schema='month:INTEGER, tornado_count:INTEGER', create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE) # Run the pip...
tgquintela/pyDataProcesser
pyDataProcesser/aux_functions.py
Python
mit
13,382
0.002092
""" Auxiliar functions ------------------ Collection of main auxiliar functions. """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import unicodedata ########################### Administrative functions ########################## #############################################...
ethod could create a column with some numbers as integers #and anothers as floats #TOTEST: is this possible in pd df try: dataframe = dataframe.apply(int) except:
#add another try for the error if it is not possible dataframe = dataframe.apply(float) return dataframe def codification_precoded_functions(methodname, dataframe, dict4columns={}): """This is a function of functions. The conditions of these functions are: * The input of ...
shtalinberg/django-actions-logger
actionslog/settings.py
Python
mit
910
0
# """Django Actions Log settings file.""" # from __future__ import unicode_literals from django.conf import settings from django.utils.translation import ugettext_lazy as _ CREATE = 100 SUCCESS = 110 ACTIVATE = 130 AUTH = 150 VIEW = 180
UPDATE = 200 SUSPEND = 250 UNSUSPEND = 260 DELETE = 300 TERMINATE = 500 FAILED = 999 ERROR = 1000 LOG_ACTION_CHOICES_DEFAULT = [ (CREATE, _("create")), (SUCCESS, _("success")), (ACTIVATE, _("activate")), (AUTH, _("authorize")), (VIEW, _("view")), (UPDATE, _("update")), (SUSPEND, _("suspend...
(DELETE, _("delete")), (TERMINATE, _("terminate")), (FAILED, _("failed")), (ERROR, _("error")), ] AL_LOG_ACTION_SETTINGS = getattr( settings, 'AL_LOG_ACTION_CHOICES', LOG_ACTION_CHOICES_DEFAULT ) LOG_ACTION_CHOICES = [ (value[0], value[1]) for value in AL_LOG_ACTION_SETTINGS ]
PySimulator/PySimulator
PySimulator/Plugins/Simulator/SimulationX/SimXEnums.py
Python
lgpl-3.0
6,337
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Copyright (C) 2014 ITI GmbH All rights reserved. This file is part of PySimulator. PySimulator 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,...
ionStudio = 14 simCodeExportProjectFMIModelExchange20 = 15 simCodeExportProjectFMICoSimulation20 = 16 # SimCodeExportSaveOutputsApproach simCodeExportSaveOutputsEqidistant = 0 simCodeExportSaveOutputsAll = 1 simCodeExpor
tSaveOutputsAtleastwithdtProt = 2 # SimCurveMonotony simDescendMon = -1 simNonMonoton = 0 simAscendMon = 1 # SimCurveInterpolation simDefaultInterpol = 0 simLinearInterpol = 1 simStairsInterpol = 2 simSplineInterpol = 3 simHyperbolicApprox = 4 simArcApproc = 5 # SimFailureDataModes simFailurePropagat...
Honzin/ccs
dev/bitmarket/public/__init__.py
Python
agpl-3.0
4,152
0.006021
import urllib.parse import sys from ccs import core from ccs import constants from . import response def ticker(cur1, cur2): s = __name__.split(".")[1] r = sys._getframe().f_code.co_name symbol = cur1.upper().strip() + cur2.upper().strip() # complete request cr = core.request(s, r).replace(const...
) return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s)) # graphs90m def graph90m(cur1, cur2): s = __name__.split(".")[1] r = sys._getframe().f_code.co_name symbol = cur1.upper().strip() + cur2.upper().strip() # complete request cr = core.request(s, r).re...
lace(constants.SYMBOL_PATTERN, symbol) return core.get(core.hostname(s), cr, core.header(s), core.compression(s), core.timeout(s)) # graphs6h def graph6h(cur1, cur2): s = __name__.split(".")[1] r = sys._getframe().f_code.co_name symbol = cur1.upper().strip() + cur2.upper().strip() # complete req...
guardicore/monkey
monkey/tests/unit_tests/infection_monkey/utils/test_bit_manipulators.py
Python
gpl-3.0
1,072
0.005597
from infection_monkey.utils import bit_manipulators def test_flip_bits_in_single_byte(): for i in range(0, 256): assert bit_manipulators.flip_bits_in_single_byte(i) == (255 - i) def test_flip_bits(): test_input = bytes(b"ABCDEFGHIJNLMNOPQRSTUVWXYZabcdefghijnlmnopqrstuvwxyz1234567890!@#$%^&*()") ...
( b"ABCDEFGHIJNLM\xffNOPQRSTUVWXYZabcde\xf5fghijnlmnopqr\xC3stuvwxyz1\x87234567890
!@#$%^&*()" ) test_output = bit_manipulators.flip_bits(test_input) test_output = bit_manipulators.flip_bits(test_output) assert test_input == test_output
ttrifonov/horizon
horizon/horizon/dashboards/nova/instances_and_volumes/panel.py
Python
apache-2.0
870
0
# vim: tabstop=4 sh
iftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
TIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import horizon from horizon.dashboards.nova import dashboard class InstancesAndVolumes(horizon.Panel): name = "Instances & Volumes" slug = 'i...
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/test/crashers/borrowed_ref_2.py
Python
epl-1.0
644
0.006211
""" _PyType_Lookup() returns a borrowed reference. This attack
s PyObject_GenericSetAttr(). NB. on my machine this crashes in 2.5 debug but not release. """ class A(object): pass class B(object): def __del__(self): print "hi" del C.d class D(object): def __set__(self, obj, value): self.hello = 42 class C(object): d = D() def g(): ...
, im_self=d) lst[i] = c.g # consume the free list of instancemethod objects i += 1
anders-larsson/random-scripts
pysh_to_talk/pysh_to_talk.py
Python
gpl-3.0
1,059
0
#!/usr/bin/env python3 import subprocess from pynput import
keyboard KEY = keyboard.Key.scroll_lock SOURCE = '@DEFAULT_SOURCE@' class PushToTalk():
def __init__(self, source, key): # Mute microphone as default state self.muted = True self.pactl_command = 'pactl set-source-mute {} '.format(source) self.execute_command(self.pactl_command + '1') with keyboard.Listener( on_press=self.on_press, ...
GabrielBrascher/cloudstack
test/integration/component/test_cpu_max_limits.py
Python
apache-2.0
13,217
0.002572
# 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 u...
ise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.c
leanup = [] return def tearDown(self): try: # Clean up, terminate the created instance, volumes and snapshots cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) retu...
apporc/neutron
neutron/extensions/qos.py
Python
apache-2.0
8,465
0.000118
# Copyright (c) 2015 Red Hat 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...
m neutron.services import service_base QOS_PREFIX = "/qos" # Attribute Map QOS_RULE_COMMON_FIELDS = { 'id': {'allow_post': False, 'allow_put': False, 'validate': {'type:uuid': None}, 'is_visible': True, 'primary_key': True}, 'tenant_id': {'allow_post': True, 'allow_put': False...
= { 'policies': { 'id': {'allow_post': False, 'allow_put': False, 'validate': {'type:uuid': None}, 'is_visible': True, 'primary_key': True}, 'name': {'allow_post': True, 'allow_put': True, 'is_visible': True, 'default': '', 'validate':...
joaduo/python-simplerpc
simplerpc/common/abstract/FrameworkBase.py
Python
bsd-3-clause
1,399
0.002859
# -*- coding: utf-8 -*- ''' Copyright (c) 2013, LastSeal S.A. Copyright (c) 2011-2012, Joaquin G. Duo All rights reserved. This
code is distributed under BSD 3-clause License. For details check the LICENSE file in the root of the project. ''' from simplerpc.common.abstract.SelfConfigBase import SelfConfigBase from simplerpc.common.abstract.PostInitStrategyBase import PostInitStrategyBase class FrameworkBase(PostInitStrategyBase, SelfConfigBa...
context=context) PostInitStrategyBase._initChildren(self, a, ad) def smokeTestModule(): class ExtendedBase(FrameworkBase): def __post_init__(self, value): self.log('Post init abstract') self.post_init_var = value class Foo(object): pass #class ConcreteClas...
dtrip/weevely3
tests/test_terminal.py
Python
gpl-3.0
8,149
0.005522
from tests.base_test import BaseTest from core.weexceptions import FatalException from testfixtures import log_capture from core.terminal import Terminal from core.sessions import SessionURL, SessionFile from core import modules from core import messages import subprocess def setUpModule(): subprocess.check_output...
tured) self._assert_exec(':set shell_php "', err_msg, log_captured) @log_capture() def test_set(self, log_captured): self._assert_exec(':set', messages.terminal.set_usage, log_captured) self._assert_exec(':set ASD', messages.terminal.set_usage, log_captured) self._assert_exec(...
asd', messages.sessions.error_session_s_not_modified % 'asd', log_captured) self._assert_exec(':set asd asd asd', messages.sessions.error_session_s_not_modified % 'asd', log_captured) self._assert_exec(':set channel asd', messages.sessions.set_s_s % ('channel', 'asd'), log_captured) self._asser...
stefan-caraiman/cloudbase-init-ci
argus/unit_tests/backends/tempest/test_cloud.py
Python
apache-2.0
13,589
0
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
ip, mock_rand_name, mock_config): mock_tenant_id = mock.Mock() mock_tenant_id.tenant_id = "fake tenant id" mock_primary_credentials = mock.Mock() mock_primary_credentials.return_value = mock_tenant_id mock_isolated_creds = mock.Mock() ...
return_value) = ("fake net resource", ) * 4 mock_isolated_creds._creds = {} mock_fake_net_creds = mock.Mock() mock_fake_net_creds.subnet = {"id": "fake subnet id"} mock_fake_net_creds.network = {"id": "fake network id"} mock_get_namedtuple.return_value = mock_fake_net_creds...
SUSE/DeepSea
srv/modules/runners/populate.py
Python
gpl-3.0
25,670
0.001169
# -*- coding: utf-8 -*- # vim: ts=8 et sw=4 sts=4 # pylint: skip-file # pylint: disable=too-few-public-methods,modernize-parse-error """ WHY THIS RUNNER EXISTS: For a set of servers, multiple Ceph configurations are possible. Enumerating all of them would generate so many that the useful would be lost in the noise. R...
gger(__name__) def _cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) -...
es sls extensions and stack.py uses yml. """ def __init__(self, **kwargs): """ Keep yaml human readable/editable. Disable yaml references. """ self.dumper = yaml.SafeDumper self.dumper.ignore_aliases = lambda self, data: True if 'overwrite' in kwargs: ...
pbougue/navitia
source/sql/alembic/versions/2d86200bcb93_co2_emission_column_added.py
Python
agpl-3.0
558
0.007168
"""co2_emission column added
Revision ID: 2d86200bcb93 Revises: 82749d34a18 Create Date: 2014-12-30 17:23:39.654559 """ # revision identifiers, used by Alembic. revision = '2d86200bcb93' down_revision = '82749d34a18' from alembic import op import sqlalchemy as sa import geoalchemy2 as ga def upgrade(): op.add_column( 'physical_mod...
ia', ) def downgrade(): op.drop_column('physical_mode', 'co2_emission', schema='navitia')
xlqian/navitia
source/jormungandr/jormungandr/scenarios/ridesharing/instant_system.py
Python
agpl-3.0
11,739
0.002556
# Copyright (c) 2001-2018, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public tr...
, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU 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/...
g # https://groups.google.com/d/forum/navitia # www.navitia.io from __future__ import absolute_import, print_function, unicode_literals, division import datetime import logging import pybreaker import pytz import requests as requests from jormungandr import utils from jormungandr import app import jormungandr.scenar...
AZed/duplicity
testing/tests/tempdirtest.py
Python
gpl-2.0
1,458
0.003429
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
n, MA 02111-1307 USA import helper import sys, os, unittest from duplicity import tempdir helper.setup() class TempDirTest(unittest.TestCase): def test_all(self): td = tempdir.default() self.assert_(td.mktemp() != td.mktemp()) dir = td.mktemp() os.mkdir(dir) os.rmdir(di...
emp() os.close(fd) os.unlink(fname) td.forget(fname) fo, fname = td.mkstemp_file() fo.close() # don't forget, leave to cleanup() td.cleanup() if __name__ == "__main__": unittest.main()
jeremiahyan/odoo
addons/test_website/tests/__init__.py
Python
gpl-3.0
466
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import test_controller_args from . import test_custom
_snippet from . import test_error from . import test_image_upload_progress from . import test_is_multilang from . import test_multi_company from . import test_performance from . import test_redirect from . import test_reset_views from . imp
ort test_session from . import test_views_during_module_operation
paulsbrookes/subcipher
index_based/ciphertext.py
Python
apache-2.0
3,930
0.003053
import numpy as np import random def_alpha = ' etaoinshrdlcumwfgypbvkjxqz' from filter import filter class Ciphertext(object): def __init__(self, text_indices=np.zeros(0), map_record=0, alpha=def_alpha): if np.all(map_record == 0): map_record = np.arange(len(alpha)) self.map_record = ma...
self.text_indices[i] = new_map[x] for i, x in enumerate(self.map_record): self.map_record[i] = new_map[x] def randomise(self): random_map = np.arange(len(self.alpha)) random.shuffle(random_map) self.substitute(random_map) def pair_shuffle(self): n...
n(self.alpha)) [i, j] = random.sample(new_map) self.pair_swap(i, j) def pair_swap(self, i, j): new_map = np.arange(len(self.alpha)) i = random.randint(0, new_map.size - 1) if i == new_map.size - 1: new_map[i], new_map[0] = new_map[0], new_map[i] else: ...
craigcook/bedrock
bedrock/sitemaps/tests/test_models.py
Python
mpl-2.0
1,606
0.000623
# 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 https://mozilla.org/MPL/2.0/. from bedrock.
mozorg.tests import TestCase from bedrock.sitemaps.models import NO_LOCALE, SitemapURL class TestSitemapsModel(TestCase): def test_absolute_url(self): obj = SitemapURL(path="/firefox/", locale="de") assert obj.get_absolute_url() == "https://www.mozilla.org/de/firefox/" # none locale ...
"https://www.mozilla.org/firefox/" def test_all_for_locale(self): SitemapURL.objects.create(path="/firefox/", locale="de") SitemapURL.objects.create(path="/firefox/", locale="fr") SitemapURL.objects.create(path="/", locale="de") SitemapURL.objects.create(path="/about/", locale="de")...
debugger22/sympy_gamma
app/logic/resultsets.py
Python
bsd-3-clause
34,531
0.002548
import sys import json import itertools import sympy from sympy.core.function import FunctionClass import docutils.core import diffsteps import intsteps class ResultCard(object): """ Operations to generate a result card. title -- Title of the card result_statement -- Statement evaluated to get resul...
def __init__(self, title, *cards): super(MultiResultCard, self).__init__(title, '', lambda *args: '') self.cards = cards self.cards_used = [] def eval(self, evaluator, components, parameters): self.cards_used = [] results = [] # TODO Implici
t state is bad, come up with better API # in particular a way to store variable, cards used for card in self.cards: try: result = card.eval(evaluator, components, parameters) except ValueError: continue if result != None: ...
miing/mci_migo
fabfile/__init__.py
Python
agpl-3.0
899
0.005562
################################################################### # # Copyright (c) 2011 Canonical Ltd. # Copyright (c) 2013 Miing.org <samuel.miing@gmail.com> # # This software is licensed under the GNU Affero General Public # License version 3 (AGPLv3), as published by the Free Software # Foundation, and may be ...
############ from .environment import * from .django import * from .postgresql import * from .dbengine import * from .development import * from .docs import * # make sure the virtualenv is automatically activated setu
p_virtualenv()
rowinggolfer/openmolar2
src/lib_openmolar/common/db_orm/insertable_record.py
Python
gpl-3.0
2,413
0.008703
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### ## ## ## Copyright 2010-2012, Neil Wallace <neil@openmolar.com> ## ## ...
## ############################################################################### from PyQt4 import QtSql class InsertableRecord(QtSql.QSqlRecord): ''' Inherits from QtSql.QSqlRecord and adds a property insert query ''' #: include_ix = Fa...
atabase.record(tablename) QtSql.QSqlRecord.__init__(self, record) @property def insert_query(self): cols, vals = u"", u"" values = [] for i in range(self.count()): field = self.field(i) if not self.include_ix and field.name() == "ix": cont...
firebase/firebase-ios-sdk
scripts/lib/checker.py
Python
apache-2.0
3,057
0.007851
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
routine. """ self._pending.put
((task, args)) def join(self): """Waits for the completion of all submitted tasks. Returns: The number of errors encountered. """ self._pending.join() num_errors = 0 while not self._results.empty(): result = self._results.get() num_errors += result.errors sys.stdout....
DLR-SC/DataFinder
src/datafinder/persistence/adapters/ldap_/configuration.py
Python
bsd-3-clause
2,613
0.014543
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # All rights reserved. # # #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are #met: # ...
iguration: L{BaseConfiguration<datafinder.persistence.common.configuration.BaseConfiguration>} """
self.serverUri = baseConfiguration.baseUri self.username = baseConfiguration.username self.password = baseConfiguration.password self.encoding = baseConfiguration.encoding or _LDAP_SERVER_DEFAULT_ENCODING self.baseDn = baseConfiguration.baseDn or "" self.domain ...
pletisan/python-data-viz-cookbook
3367OS_Code/3367OS_04_Code/ch04/ch04_rec05_custom_grids.py
Python
mit
1,158
0.002591
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid from matplotlib.cbook import get_sample_data def get_demo_image(): f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) # z is a numpy array of 15x15 Z = np.load(f) return Z, (-3, 4, -4, ...
_ncols=None): assert fig is not None assert layout is not None assert nrows_ncols is not None grid = ImageGrid(fig, layout, nrows_ncols=nrows_ncols, axes_pad=0.05, add_all=True, label_mode="L") return grid def load_images_to_grid(grid, Z, *images): min, max = Z.min(), Z.ma...
erpolation="nearest") if __name__ == "__main__": fig = plt.figure(1, (8, 6)) grid = get_grid(fig, 111, (1, 3)) Z, extent = get_demo_image() # Slice image image1 = Z image2 = Z[:, :10] image3 = Z[:, 10:] load_images_to_grid(grid, Z, image1, image2, image3) plt.draw() plt.show(...
Karspexet/Karspexet
karspexet/show/migrations/0005_show_short_description.py
Python
mit
395
0
# Gener
ated by Django 1.10.1 on 2018-03-22 20:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('show', '0004_show_slug'), ] operations = [ migrations.AddField( model_name='show', name='short_description', f...
Field(default='', max_length=255), ), ]
xuyuhan/depot_tools
git_cl.py
Python
bsd-3-clause
106,464
0.01114
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Copyright (C) 2008 Evan Martin <martine@danga.com> """A git-command for integrating reviews on Rietveld.""" from distutils.vers...
burl, as_ref = glob_spec.split(':') if allow_wildcar
ds: glob_match = re.match('(.+/)?(\*|{[^/]*})(/.+)?', fetch_suburl) if glob_match: # Parse specs like "branches/*/src:refs/remotes/svn/*" or # "branches/{472,597,648}/src:refs/remotes/svn/*". branch_re = re.escape(base_url) if glob_match.group(1): branch_re += '/' + re.escape(glo...
jiahaoliang/group-based-policy
gbpservice/nfp/configurator/drivers/loadbalancer/v2/haproxy/octavia_lib/network/data_models.py
Python
apache-2.0
4,043
0
# Copyright 2014 Rackspace # # 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 agree...
elf.provider_segmentation_id = provider_segmentation_id self.router_external = router_external self.mtu = mtu class Subnet(data_models.BaseDataModel): def __init__(self, id=None, name=None, network_id=None, project_id=None,
gateway_ip=None, cidr=None, ip_version=None): self.id = id self.name = name self.network_id = network_id self.project_id = project_id self.gateway_ip = gateway_ip self.cidr = cidr self.ip_version = ip_version class Port(data_models.BaseDataModel): def __ini...
jtpereyda/boofuzz
boofuzz/monitors/process_monitor.py
Python
gpl-2.0
5,053
0.001781
import warnings from . import pedrpc from .base_monitor import BaseMonitor # Important: BaseMonitor needs to come *before* pedrpc.Client in the # Inheritance list for the method resolution order to produce # correct results. class ProcessMonitor(BaseMonitor, pedrpc.Client): """ Proxy class for the process ...
the RPC daemon.""" return self.__method_missing("get_crash_synopsis") def start_target(self): """This method is forwarded to the RPC daemon.""" return self.__method_missin
g("start_target") def stop_target(self): """This method is forwarded to the RPC daemon.""" return self.__method_missing("stop_target") def restart_target(self, target=None, fuzz_data_logger=None, session=None): """This method is forwarded to the RPC daemon.""" return self.__met...
trovdimi/wikilinks
normalized_entropy.py
Python
mit
12,536
0.012205
import scipy.stats as stats import matplotlib.pyplot as plt import MySQLdb from wsd.database import MySQLDatabase import matplotlib.cm as cm from matplotlib.colors import LogNorm, Normalize, BoundaryNorm, PowerNorm from conf import * from collections import defaultdict import cPickle as pickle import numpy as np import...
ckle.dump(obj, outfile, -1) def normalized_entropy(): transition_matrix = pickle.load( open( SSD_HOME+"pickle/transition_matrix", "rb" ) ) print "loaded transitions" graph = pickle.load( open( SSD_HOME+"pickle/graph", "rb" ) ) print "loaded graph" values = pickle.load( open( SSD_HO
ME+"pickle/values", "rb" ) ) vocab = pickle.load( open( SSD_HOME+"pickle/vocab", "rb" ) ) print "loaded vocab" state_count = len(vocab) states = vocab.keys() shape = (state_count, state_count) # structural hypothesises hyp_structural = csr_matrix((values, (graph[0], graph[1])), ...
jcchoiling/learningPython
s13/Day05/modules/core/atm_log.py
Python
gpl-3.0
639
0.00939
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Janice Cheng import logging from s13.Day5.conf import setting logger = logging.ge
tLogger('ATM-TRANSACTION-LOG') logger.setLevel(logging.INFO) #configure a global logging level console_handler = logging.StreamHandler() #print the log on the console file_handler = logging.FileHandler("{}/log/access.log".format(setting.APP_DIR)) formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s ...
matter(formatter) logger.addHandler(console_handler) logger.addHandler(file_handler)
cosmir/dev-set-builder
audioset/__init__.py
Python
mit
235
0
import pkg_resources from .vggish_params import * MODEL_PARAMS = pkg_resources.resource_filename( __name__, '.model/vggish_model.cpkt') PCA_PARAMS = pkg_resources.resource_fi
lename( __name__, '.m
odel/vggish_pca_params.npz')
FireWRT/OpenWrt-Firefly-Libraries
staging_dir/host/lib/scons-2.3.1/SCons/Scanner/IDL.py
Python
gpl-2.0
1,878
0.001597
"""SCons.Scanner.IDL This module implements the depenency scanner for IDL (Interface Definition Language) files. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a ...
ILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION #
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/IDL.py 2014/03/02 14:18:15 garyo" import SCons.Node.FS import SCons.Scanner def IDLScan(): """Return a prototype Scanner instance for scanning IDL source files""" cs = SCons.Scanner.ClassicCPP("IDLSca...
maxwallasaurus/arboretum
authentication/migrations 08-40-23-458/0001_initial 08-45-26-265.py
Python
mit
1,345
0.00223
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-25 01:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Accoun...
_length=254, unique=True)), ('username', models.CharField(max_length=40, unique=True)), ('first_name', models.CharField(blank=True, max_length=40)), ('last_name', models.CharField(blank=True, max_length=40)), ('tag_line', models.CharField(blank=True, max_l...
('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'abstract': False, }, ), ]
ReconCell/smacha
smacha/test/smacha_test_examples/random_outcomes.py
Python
bsd-3-clause
6,029
0.010615
#!/usr/bin/env python import smach import random class RandomOutcomeState(smach.State): def __init__(self, input_keys = ['outcome'], output_keys = ['outcome'], callbacks = {}, outcomes=['succeeded']): smach.State.__init__(self, input_keys=input_keys, output_keys=output_keys, outcomes=outcomes) ...
transitions={'succeeded':'RANDOMIZE'}) smach.StateMachine.add('FOO_2', CallbacksState(callbacks = ['outcome_foo_2_lambda_cb']), transitions={'succeeded':'final_outcome'})
outcome = sm.execute() if __name__ == '__main__': main()
whtsky/Catsup
tests/conftest.py
Python
mit
419
0
import os import pytest BASE_DI
R = os.path.abspath(os.path.dirname(__file__)) SITE_DIR = os.path.join(BASE_DIR, "site") @pytest.fixture def site_dir(): return SITE_DIR @pytest.fixture def output_exist(): return lambda path: os.path.exists(os.path.join(SITE_DIR, "deploy", path)) @pytest.fixture(autouse=True) def chdir(): from catsup...
wdpath = SITE_DIR
Simularia/arinfopy
arinfopy/__init__.py
Python
gpl-2.0
85
0
from
.adsobinapi import adsobin, adsowritebin __all__ = ["adsobin", "adsowritebin"]
suutari/shoop
shuup_tests/core/test_addresses.py
Python
agpl-3.0
5,067
0.00296
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree. import pytest import six from django.core.exceptions import ValidationError from django.test import override_settings from django.utils.translation import override from shuup.core.models import ( get_person_contact, ImmutableAddress, MutableAddress, SavedA...
a_dict def test_partial_address_fails(): address = MutableAddress( name=u"Dog Hello" ) with pytest.raises(ValidationError): address.full_clean() @pytest.mark.django_db def test_basic_address(): address = get_address() address.full_clean() string_repr = str(address) for fi...
pavanmishra/lesswebpy
examples/hello.py
Python
unlicense
279
0.02509
import lessweb def index(ctx): return 'Hello' def hello(ctx, name): if not name: name = 'World' return 'Hello, ' + name + '!' urls = ( 'GET', '/?', index, 'GET', '/(.*)', hello ) a
pp = lessweb.application(urls, loc
als()) if __name__ == '__main__': app.run()
vaidhy/python-linkedin-fork
linkedin/tests/linkedin_request_test.py
Python
mit
592
0.008446
''' Created on Aug 31, 2011 @author: Iftach ''' from linkedin.tests import * from linkedin import linkedin class LinkedInRequestTest(LinkedInTestBase): def test_request_token(self): self._test_request_token(False)
def test_request_token_gae(self): self._init_gae() self._test_request_token(True) def _test_request_token(self, gae): api = linkedin.LinkedIn(API_KEY, SECRET_
KEY, RETURN_URL, gae) self.assertTrue(api.request_token(), api.get_error()) if __name__ == "__main__": unittest.main()
warenlg/shell-complete
shcomplete/repospider.py
Python
apache-2.0
428
0
import just from scrapy.spiders import Spider class MySpider(Spider): name = "github_spider" allowed_domai
ns = ["github.com"] with open("../repos.txt") as f: start_urls = [url.strip() for url in f.readlines()] def parse(self, response): base = "https://raw.githubu
sercontent.com" content = response.text.encode("utf-8") just.write(content, "data" + response.url[len(base):])
MKLab-ITI/prophet
modules/messagebox_resources_rc.py
Python
apache-2.0
55,780
0.014987
# -*- coding: utf-8 -*- """ This file is part of the PROPheT tool. Copyright (C) 2016: MKLab <pmitzias@iti.gr; mriga@iti.gr; skontopo@iti.gr> http://mklab.iti.gr/project/prophet-ontology-populator https://github.com/MKLab-ITI/prophet Licensed under the Apache License, Version 2.0 (the "License"). You may use t...
\x02\x02\xc0\x84\x45\xd7\x65\x02\x
04\x08\x10\x20\x20\ \x00\x18\x03\x04\x08\x10\x20\x40\x60\x42\x01\x01\x60\xc2\xa2\xeb\ \x32\x01\x02\x04\x08\x10\x10\x00\x8c\x01\x02\x04\x08\x10\x20\x30\ \xa1\x80\x00\x30\x61\xd1\x75\x99\x00\x01\x02\x04\x08\x9c\x11\x00\ \xde\x2f\xa5\x3c\x2f\xa5\xfc\xfd\xc2\xff\xa1\x32\x10\x20\x40\x80\ \x00\x81\x49\x04\xde\x5c\xfa\x7...
reviewboard/rbpkg
rbpkg/package_manager/tests/test_dep_graph.py
Python
mit
1,217
0
from __future__ import unicode_literals from rbpkg.package_manager.dep_graph import DependencyGraph from rbpkg.testing.testcases import TestCase class DependencyGraphTests(TestCase): """Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph.""" def test_iter_sorted_simple(self): """Testing D...
5, 2, 6, 15, 12]) def test_iter_sorted_circular_ref(self): """Testing DependencyGraph.iter_sorted with circular reference""" graph = DependencyGraph() graph.add(1, [2])
graph.add(2, [1]) self.assertEqual(list(graph.iter_sorted()), [2, 1])
houssine78/addons
account_bank_statement_line_memo/models/models.py
Python
agpl-3.0
251
0
# -*- coding: utf-8 -*- from openerp impor
t models, fields class AccountBankStatementLine(models.Model): _inherit = "account.bank.statement.line" name = fields.Char( string
='Memo', required=False, default="", )
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/duplicity/asyncscheduler.py
Python
gpl-3.0
54
0.018519
..
/../../../share/pyshared/duplicity/asyncscheduler.
py
Debian/openjfx
modules/web/src/main/native/Tools/Scripts/webkitpy/layout_tests/models/test_failures_unittest.py
Python
gpl-2.0
3,135
0.000319
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
umps() new_failure_obj = TestFailure.loads(s) self.assertIsInstance(new_failure_obj, cls) self.assertEqual(failure_obj, new_failure_obj) # Also test that != is implemented. self.assertFalse(failure_obj != new_failure_obj) def test_unknown_failure_type(self): class ...
re_obj = UnknownFailure() self.assertRaises(ValueError, determine_result_type, [failure_obj]) def test_message_is_virtual(self): failure_obj = TestFailure() self.assertRaises(NotImplementedError, failure_obj.message) def test_loads(self): for c in ALL_FAILURE_CLASSES: ...
a113n/bcbio-nextgen
scripts/bcbio_setup_genome.py
Python
mit
15,182
0.002964
#!/usr/bin/env python -Es """ Script to set up a custom genome for bcbio-nextgen """ from __future__ import print_function from argparse import ArgumentParser import collections import gzip import os from Bio import SeqIO import toolz as tz from bcbio.utils import safe_makedir, file_exists, chdir, is_gzipped from bcb...
ile, 'wb') as out_handle: shutil.copyfileobj(in_handle, out_handle) else: shutil.copyfile(gtf, out_file) return out_file def install_srna(species, gtf): out_file = os.path.join(SRNASEQ_DIR, "srna-transcripts.gtf") safe_makedir(SRNASEQ_DIR) if gtf:
if not file_exists(out_file): shutil.copyfile(gtf, out_file) try: from seqcluster import install except ImportError: raise ImportError("install seqcluster first, please.") with chdir(SRNASEQ_DIR): hairpin, miRNA = install._install_mirbase() cmd = ("cat %s...
RomainBrault/scikit-learn
sklearn/cluster/spectral.py
Python
bsd-3-clause
19,196
0.000052
# -*- coding: utf-8 -*- """Algorithms for spectral clustering""" # Author: Gael Varoquaux gael.varoquaux@normalesup.org # Brian Cheung # Wei LI <kuantkid@gmail.com> # License: BSD 3 clause import warnings import numpy as np from ..base import BaseEstimator, ClusterMixin from ..utils import check_rand...
tarts += 1 except LinAlgError: print("SVD did not converge, randomizing and trying again") break ncut_value = 2.0 * (n_samples - S.sum()) if ((abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max)):
has_converged = True else: # otherwise calculate rotation and continue last_objective_value = ncut_value rotation = np.dot(Vh.T, U.T) if not has_converged: raise LinAlgError('SVD did not converge') return labels def spectral_clus...
SickGear/SickGear
lib/chardet/version.py
Python
gpl-3.0
251
0
""" This
module exists only to simplify retrieving the version number of chardet from within setup.py and from chardet subpackages. :author: Dan Blanchard (dan.blanchard@gmail.com) """ __version__ = "4.0.0" VERSION = __version__.split('.'
)
lmregus/Portfolio
python/design_patterns/env/lib/python3.7/site-packages/sphinx/testing/__init__.py
Python
mit
341
0.002933
""" sphinx.testing
~~~~~~~~~~~~~~ Sphinx test utilities You can require sphinx.testing pytest fixtures in a test module or a conftest file like this: pytest_plugins = 'sphinx.testing.fixtures' :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details.
"""
jacquev6/LowVoltage
LowVoltage/actions/describe_table.py
Python
mit
2,802
0.002141
# coding: utf8 # Copyright 2014-2015 Vincent Jacques <vincent@vincent-jacques.net> """ When given a :class:`DescribeTable`, the connection will return a :class:`DescribeTableResponse`: >>> r = connection(DescribeTable(table)) >>> r <LowVoltage.actions.describe_table.DescribeTableResponse ...> >>> r.table.table_statu...
def __init__( self, Table=None, **dummy ): self.__table = Table @property def table(self): """
The description of the table. :type: ``None`` or :class:`.TableDescription` """ if _is_dict(self.__table): return TableDescription(**self.__table) class DescribeTable(Action): """ The `DescribeTable request <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API...
itsallvoodoo/csci-school
CSCI220/Week 15 - FINAL/Scrabble/Tile.py
Python
apache-2.0
5,575
0.018834
from graphics import* import random from Player import * from Button import * class Tile(): def __init__(self,l): self.letter = l self.setValue() self.rect = Rectangle(Point(0,0),Point(10,10)) self.text_letter = Text(Point(5,5),self.letter) self.text_value = Text(...
f.value = 4 elif l == "W": self.value = 4 elif l == "X": self.value = 8 elif l == "Y": self.value = 4 elif l == "Z": self.value = 10 def main(): win = GraphWin("Test",400,400) win.setCoords(-30,-30,180,180) ...
t(50,50)) t.undraw() import pickle t2 = pickle.loads(pickle.dumps(t)) t2.move(Point(75,75)) t2.draw(win) win.getMouse() win.close() if __name__=="__main__": main()
ygrass/handsome
orders/migrations/0019_auto__add_field_order_redesign_reason.py
Python
unlicense
15,018
0.00799
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Order.redesign_reason' db.add_column(u'orders_order', 're...
enttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField'...
], {'max_length': '100'}) }, u'designs.design': { 'Meta': {'object_name': 'Design'}, 'client': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'designs_for_me'", 'to': u"orm['auth.User']"}), 'clothings': ('django.db.models.fields.related.ManyToMan...
helixyte/TheLMA
thelma/tools/iso/base.py
Python
mit
19,027
0.000788
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Base classes, functions and constants for ISO processing (type-independent). AAB """ from thelma.tools.semiconstants import get_rack_position_from_label fro...
highest_number = 0
for iso_job in iso_request.iso_jobs: number = cls.__get_job_number(iso_job) highest_number = max(highest_number, number) return highest_number + 1 @classmethod def __get_job_number(cls, iso_job): value_parts = cls._get_value_parts(iso_job.label) return cls._...
google/makani
avionics/bootloader/fake_bootloader_client.py
Python
apache-2.0
2,531
0.008692
#!/usr/bin/python # Copyright 2020 Makani Technologies LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
to # Python is not available due to the bash stubs instituted by Bazel. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) parsed_args = bootloader_client.ParseArguments() binary_path = parsed_args['file'] binary_size = os.stat(binary_path).st_size address_string = p
arsed_args['new_ip'] RandomSleep(0.5, 0.5) logging.info('Binary size: %d bytes; target IP: %s.', binary_size, address_string) RandomSleep(1.0, 0.1) logging.info('Target hardware type: kHardwareTypeSomething.') RandomSleep(2.0, 0.5) logging.info('Got an acknowledgement from target; starting ...
fgrunewald/Martini_PolyPly
polyply/structure_tool/analysis_funtions.py
Python
gpl-3.0
529
0.015123
import argparse import numpy as np import scipy.optimize as opt from numpy import sqrt
, pi, cos,
sin, dot, cross, arccos, degrees from numpy import float as nfl from numpy.linalg import norm def radius_of_gyr(traj): N = len(traj) diff=np.zeros((N**2)) count=0 for i in traj: for j in traj: diff[count]=dot((i - j),(i-j)) count = count + 1 Rg= 1/np.float(N)**2 * su...
schinckel/django-boardinghouse
boardinghouse/schema.py
Python
bsd-3-clause
10,412
0.001153
import inspect import logging import threading from django.apps import apps from django.conf import settings from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured from django.db import connection from django.db.migrations.operations.base import Operation from django.utils.translat...
= connection.cursor() schema_pre_activate.send(sender=None, schema_name=None) cursor.execute('SET search_path TO "$user",{0}'.format(settings.PUBLIC_SCHEMA)) schema_post_activate.send(sender=None, schema_name=None) _thread_locals.schema = None cursor.close() #: These models are required to be sha...
'sessions.session', 'contenttypes.contenttype', 'admin.logentry', 'migrations.migration', # In the case these are not the default values. lazy(lambda: settings.BOARDINGHOUSE_SCHEMA_MODEL.lower())(), lazy(lambda: settings.AUTH_USER_MODEL.lower())(), ] REQUIRED_SHARED_TABLES = [ 'django_mig...
jawilson/home-assistant
homeassistant/components/bmw_connected_drive/lock.py
Python
apache-2.0
3,416
0.000585
"""Support for BMW car locks with BMW ConnectedDrive.""" import logging from typing import Any from bimmer_connected.vehicle import ConnectedDriveVehicle from bimmer_connected.vehicle_status import LockState from homeassistant
.components.lock import LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import ( DOMAIN as BMW_DOMAIN, BMWConnectedDriveAccount, BMWConnectedDriveBaseEntity, ) from .con...
lock_state" _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the BMW ConnectedDrive binary sensors from config entry.""" account: BMWConnectedDriveAccount = hass.data[BMW...
rakeshvar/chamanti_ocr
lab/show_features.py
Python
apache-2.0
1,882
0.005313
from itertools import repeat import numpy as np from tensorflow import keras import sys sys.path.append("../../Lekhaka") import telugu as lang from Lekhaka import Scribe, Deformer, Noiser from Lekhaka import DataGenerator as Gen from lab.model_by_function import build_model from banti2chamanti import banti2chamanti ...
pecs, convpool_wts = banti2chamanti(sys.argv[1]) num_lstm_out = 66 # Model model = build_model(alphabet_size, scribe_args["height"], scriber.width, batch_size, gen.labelswidth, num_lstm_out, convpool_specs, convpool_wts) feature_model = keras.models.Model(model.get_layer(name="image").input, ...
rom PIL import Image def as255(v): return (255*(v-v.min())/(v.max()-v.min())).T.astype('uint8') def repea8(a, times): h, w = a.shape b = np.vstack(repeat(a, times)) return b.T.reshape((w*times, h)).T image, labels, image_lengths, label_lengths = gen.get() cpfs, features = feature_model.predict(ima...
tommiseppanen/visualizations
tyre-model/old-plots/combined-slip-basic.py
Python
mit
1,320
0.006061
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np def coefficient(slipValue, extremumValue, extremumSlip, asymptoteValue, asymptoteSlip): coefficient = asymptoteValue; absoluteSlip...
xtremumSlip and absoluteSlip < asymptoteSlip): coefficient = ((asymptoteValue - extremumValue) / (asymptoteSlip - extremumSlip)) \ * (absoluteSlip - extremumSlip) + extremumValue; return coefficient fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(0, 0.4, 0.01) ...
ge(0, 40, 1) X, Y = np.meshgrid(X, Y) longfunc = np.vectorize(lambda t: coefficient(t, 1, 0.2, 0.75, 0.4)) lateralfunc = np.vectorize(lambda t: coefficient(t, 1.0, 20.0, 0.75, 40)) Z = np.sqrt(longfunc(X)**2 + lateralfunc(Y)**2) surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, anti...
antiboredom/videogrep
videogrep/videogrep.py
Python
mit
18,643
0.002575
from __future__ import print_function import os import re import random import gc import subprocess from glob import glob from collections import OrderedDict from moviepy.editor import VideoFileClip, concatenate import audiogrep from .vtt import parse_auto_sub from .timecode import Timecode from . import searcher u...
output[key] += line + ' ' return output def cleanup_log_files(outputfile): """Search for and remove temp log files found in the output directory.""" d = os.path.dirname(os.path.abspath(outputfile)) logfiles = [f for f in os.listdir(d) if f.endswith('ogg.log')] for f in logfiles: ...
dding): """Print out timespans to be cut followed by the line number in the srt.""" for i, c in enumerate(composition): line = c['line'] start = c['start'] end = c['end'] if i > 0 and composition[i - 1]['file'] == c['file'] and start < composition[i - 1]['end']: start...
jythontools/clamp
tests/integ/clamp_samples/const_.py
Python
apache-2.0
191
0.005236
from java.lang import
Long, Object from clamp import clamp_base, Constant TestBase = clamp_base("org") class ConstSample(TestBase, Object): myConstant = Constant(Long(1234), Long.TYP
E)
UTSA-ICS/keystone-kerberos
keystone/tests/unit/test_cache_backend_mongo.py
Python
apache-2.0
27,559
0.000036
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 applicabl...
return copy.copy(obj) def insert(self, data, manipulate=True, **kwargs): if isinstance(data, list): return [self._insert(element) for element in data] return self._insert(data) def save(self, data, manipulate=True, **kwargs): return self._insert(data) def _insert...
ata['_id'] = uuid.uuid4().hex object_id = data['_id'] self._documents[object_id] = self._internalize_dict(data) return object_id def find_and_modify(self, spec, document, upsert=False, **kwargs): self.update(spec, document, upsert, **kwargs) def update(self, spec, document, ups...
phw/weblate
weblate/machinery/googlev3.py
Python
gpl-3.0
2,729
0.001101
# # Copyright © 2012 - 2021 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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 Lice...
" super().__init__() credentials = settings.MT_GOOGLE_CREDENTIALS project =
settings.MT_GOOGLE_PROJECT location = settings.MT_GOOGLE_LOCATION if credentials is None or project is None: raise MissingConfiguration("Google Translate requires API key and project") credentials = service_account.Credentials.from_service_account_file(credentials) self.cl...
esemin83/python_training_mantis
fixture/james.py
Python
apache-2.0
1,687
0.001186
from telnetlib import Telnet class James: def __init__(self, app): self.app = app def ensure_user_exists(self, username, password): james_config = self.app.config['james'] session = James.Session(james_config['host'], james_config['port'], james_config['username'], james_config['pass...
ists", b"does not exist"]) return res[0] == 0 def create_user(self, u
sername, password): self.write("adduser %s %s\n" % (username, password)) self.read_until("User %s added" % username) def reset_password(self, username, password): self.write("setpassword %s %s\n" % (username, password)) self.read_until("Password for %s reset" % u...
h4wkmoon/shinken
shinken/commandcall.py
Python
agpl-3.0
6,277
0.001115
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2009-2014: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can r...
get such :) """ pass class CommandCall(DummyCommandCall): """This class is use when a service, contact or host define a command with args. """ # AutoSlots create the __slots__ with properties and # running_properties names __metaclass__ = AutoSlots #__slots__ =
('id', 'call', 'command', 'valid', 'args', 'poller_tag', # 'reactionner_tag', 'module_type', '__dict__') id = 0 my_type = 'CommandCall' properties = { 'call': StringProp(), 'command': StringProp(), 'poller_tag': StringProp(default='None'), ...
frivoal/presto-testo
wpt/websockets/autobahn/oberstet-Autobahn-643d2ee/demo/pubsub/simple/server.py
Python
bsd-3-clause
1,625
0.017846
############################################################################### ## ## Copyright 2011 Tavendo GmbH ## ## Licensed under the Apac
he License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the Lice...
UT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### import sys from twisted.python import log from twiste...
rolandshoemaker/ghpn
log_parse.py
Python
mit
1,392
0.028017
def read_log(filename): with open(filename, "r") as f: lines = f.readlines() return [l.strip() for l in lines] def only_success(log_lines): return [l for l in log_lines if "processed user" in l] def only_errors(log_lines): return [l for l in log_lines if "processing error" in l] def get_stats(line): unparse...
s": int(unparsed_variables["requests"]), "took": float(unparsed_variables["
took"]), "rps": float(unparsed_variables["rps"]) } def print_stats(log_lines): stats = {"entries": []} for entry in log_lines: stats["entries"].append(get_stats(entry)) total_requests = sum([e["requests"] for e in stats["entries"]]) avg_requests = sum([e["requests"] for e in stats["entries"]]) / len(stats["en...
neilLasrado/erpnext
erpnext/bloombrackets/coupon_commands/utils.py
Python
gpl-3.0
457
0.041575
import frappe def flat_item_group_tree_list(item_group, result=None): if not result: result = [item_group] child_groups = frappe.get_list( "It
em Group",
filters={"parent_item_group": item_group}, fields=["name"] ) child_groups = [child.name for child in child_groups if child not in result] if len(child_groups) > 0: result = result + child_groups for child in child_groups: flat_item_group_tree_list(child, result) return result
creasyw/IMTAphy
modules/dll/glue/PyConfig/glue/support/CSMACA.py
Python
gpl-2.0
4,953
0.015344
############################################################################### # This file is part of openWNS (open Wireless Network Simulator) # _____________________________________________________________________________ # # Copyright (C) 2004-2009 # Chair of Communication Networks (ComNets) # Kopernikusstr. 5, D-5...
self.arq.connect(self.dispatcher) # connect broadcast path self.broadcastUpperConvergence.connect(broadcastBuffer) broadcastBuffer.connect
(self.dispatcher) # connect common path self.dispatcher.connect(crc) crc.connect(csmaCAMAC) csmaCAMAC.connect(overhead) overhead.connect(self.lowerConvergence)
tiagormk/gem5-hmp
configs/common/CacheConfigLittleBig.py
Python
bsd-3-clause
6,694
0.008814
# Copyright (c) 2012-2013 ARM Limited # All rights reserved # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functiona...
block_size=options.cacheline_size) for i in xrange(options.little_cpu_num_l2caches)]
system.little_tol2bus = [CoherentBus(clk_domain = system.little_cpu_clk_domain, width = 32) for i in xrange(options.little_cpu_num_l2caches)] for i in xrange(options.little_cpu_num_l2caches): system.little_l2_cache[i].mem_side = system.membus.slave sy...
lmarent/network_agents_ver2_python
agents/foundation/AgentClient.py
Python
mit
12,761
0.006269
from foundation.Bid import Bid from foundation.ChannelClockServer import Channel_ClockServer from foundation.ChannelMarketplace import Channel_Marketplace from foundation.FoundationException import FoundationException from foundation.Message import Message from foundation.Service import Service from AgentType imp...
D, sellingAddress, buyingAddress) if (agent_type.getType() == AgentType.PROVIDER_ISP): logger.debug('Agent Provider ISP %s', strID)
port = agent_properties.mkt_place_listening_port address = sellingAddress # This will be the channel to put bids. self._channelMarketPlace = Channel_Marketplace(address, port) address = buyingAddress # This will be the channel to buy resources. ...
macchina-io/macchina.io
platform/JS/V8/v8/tools/callstats.py
Python
apache-2.0
26,617
0.012661
#!/usr/bin/env python # Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ''' Usage: callstats.py [-h] <command> ... Optional arguments: -h, --help show this help message and exit Commands: run ...
w.location.reload(); } }, timeout); return; } console.log("Ignoring: " + url); }; var sites = """, json.dumps(sites), """; onLoad(window.location.href); })();""" def get_chrome_flags(js_flags, user_data_dir, arg_delimiter=""): return [ "--no-default-browser-check", "...
translate", "--enable-benchmarking", "--enable-stats-table", "--js-flags={}{}{}".format(arg_delimiter, js_flags, arg_delimiter), "--no-first-run", "--user-data-dir={}{}{}".format(arg_delimiter, user_data_dir, arg_delimiter), ] def get_chrome_repla...
lkrotowski/passwdk
src/passwdk/hooks.py
Python
gpl-3.0
431
0.025522
import os def post_add(conf, name): if "POST_ADD_HOOK" in conf: if "NEW_PASSWORD_NAME" in os.environ: del os.en
viron["NEW_PASSWORD_NAME"] passwd_dir = os.path.expanduser(os.path.expandvars(conf["PASSWD_DIR"])) hook_exec = os.path.expandvars(conf["POST_ADD_HOOK"]) os.chdir(passwd_dir) os.putenv("NEW_PASSWORD_NAME", name) os.putenv("PASSWD_FILE", os.path.expa
ndvars(conf["PASSWD_FILE"])) os.system(hook_exec)
CCLab/RS_ref
rawsalad/databrowser/urls.py
Python
bsd-3-clause
609
0.039409
from django.conf.urls.defaults import * urlpatterns = patterns( 'databr
owser.views', ( r'^$', 'app_page' ), ( r'^get_collections/$', 'get_collectio
ns' ), ( r'^get_init_data/$', 'get_init_data' ), ( r'^get_children/$', 'get_children' ), ( r'^store_state/$', 'store_state' ), ( r'^(?P<id>\d+)/$', 'init_restore' ), ( r'^restore_state/$', 'restore_state' ), ( r'^download/$', 'download_data' ), ( r'^feedback/$', ...
Harwood/pre-commit-hooks
tests/mixed_line_ending_test.py
Python
mit
3,733
0
from __future__ import absolute_import from __future__ import unicode_literals import pytest from pre_commit_hooks.mixed_line_ending import main @pytest.mark.parametrize( ('input_s', 'output'), ( # mixed with majority of 'LF' (b'foo\r\nbar\nbaz\n', b'foo\nbar\nbaz\n'), # mixed with m...
ry(b'foo\nbar\nbaz') assert not main((path.strpath,)) # the hook *could* fix the end of the file, but leaves it alone # this is mostly to document the current behaviour assert path.read_binary() == b'foo\nbar\nbaz' def test_mixed_no_newline_end_of_file(tmpdir): path = tmpdir.join('f.txt') path...
case but I think this is the better behaviour # this is mostly to document the current behaviour assert path.read_binary() == b'foo\nbar\nbaz\n' @pytest.mark.parametrize( ('fix_option', 'input_s'), ( # All --fix=auto with uniform line endings should be ok ('--fix=auto', b'foo\r\nbar\r\...
nickerso/libcellml
tests/resources/generator/hodgkin_huxley_squid_axon_model_1952/model.computed.constant.py
Python
apache-2.0
5,432
0.005155
# The content of this file was generated using the Python profile of libCellML 0.2.0. from enum import Enum from math import * __version__ = "0.3.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 4 VARIABLE_COUNT = 18 class VariableType(Enum): VARIABLE_OF_INTEGRATION = 1 STATE = 2 CONSTANT = 3 COMPUTED...
ium_channel", "type": VariableType.ALGEBRAIC}, {"name": "alpha_n", "units": "per_millisecond", "component": "potassium_channel_n_gate", "type": VariableType.ALGEBRAIC}, {"name": "beta_n", "units": "per_millisecond", "component": "potassium_channel_n_gate", "type": VariableType.ALGEBRAIC} ] def leq_func(x, y):...
lse 0.0 def and_func(x, y): return 1.0 if bool(x) & bool(y) else 0.0 def create_states_array(): return [nan]*STATE_COUNT def create_variables_array(): return [nan]*VARIABLE_COUNT def initialise_states_and_constants(states, variables): variables[0] = 0.3 variables[1] = 1.0 variables[2] = ...
quodlibet/quodlibet
tests/test_browsers_audiofeeds.py
Python
gpl-2.0
1,973
0
# 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. from gi.repository import Gtk import quodlibet.config from quodlibet.b...
et_data_path('valid_feed.xml') feed = Feed(fsn2uri(fn)) result = feed.parse() # Assume en_US / en_GB locale here in tests self.failIfEqual(feed.name, "Unknown", msg="Didn't find feed name") # Do this after the above, as many exceptions can be swallowed self.failUnless(res...
'Full Episode: Tuesday, November 28, 2017') def tearDown(self): quodlibet.config.quit()
BayesWatch/tf-variational-dropout
models/init.py
Python
gpl-3.0
392
0.007653
# c
ustom init
ializer in the style of pytorch's import math # call it by the original class name from tensorflow.contrib.layers import variance_scaling_initializer from tensorflow.python.framework import dtypes def pytorch_initializer(uniform=True, seed=None, dtype=dtypes.float32): return variance_scaling_initializer(factor=1./...
UnbDroid/robomagellan
Codigos/Raspberry/desenvolvimentoRos/devel/lib/python2.7/dist-packages/diagnostic_msgs/msg/_DiagnosticStatus.py
Python
gpl-3.0
10,760
0.019703
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from diagnostic_msgs/DiagnosticStatus.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import diagnostic_msgs.msg class DiagnosticStatus(genpy.Message): _md5sum = "d0ce0...
ng','string','diagnostic_msgs/KeyValue[]'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix
in-order arguments and keyword arguments. The available fields are: level,name,message,hardware_id,values :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: s...
Amr-MKamal/Multi-Application-Solar-Powered-Autonomous-Quadcopter
readings.py
Python
gpl-2.0
2,483
0.05437
import time import sys from sense_hat import
SenseHat sense = SenseHat() # msleep or time.sleep sense.set_imu_config(True, True, True) while(True) { #open file readings.txt.."w+"Overwrites the existing file if the file exists. #If the file does not exist, creates a new file for reading and
writing. f=open("readings.txt","w+") orientation = sense.get_orientation() yaw=orientation['yaw'] roll=orientation['roll'] pitch=orientation['pitch'] #all in degrees myfile.write("%s\n" % yaw) #Add (yaw,roll,pitch) to readings.txt f.writelines("%s\t" %yaw) f.writelines("%s\t" %roll) f.writelines("%s\n" %pitch) #myfile...