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
Venris/crazyflie-multilink
KM/kamera_testy/3d_position.py
Python
gpl-2.0
2,600
0.030385
import numpy as np def wzorProst3d(p1,p2): wsp = np.array([p1[0],(p2[0]-p1[0]),p1[1],(p2[1]-p1[1]),p1[2],(p2[2]-p1[2])]) return wsp def plaszczyznaRownolegla(p1,p2,p3): p12 = np.array([p2[0]-p1[0],p2[1]-p1[1],p2[2]-p1[2]]) p13 = np.array([p3[0]-p1[0],p3[1]-p1[1],p3[2]-p1[2]]) wek = np.cross(p12,p1...
+ C*wsp[5]) x =
wsp[1]*t + wsp[0] y = wsp[3]*t + wsp[2] z = wsp[5]*t + wsp[4] return x,y,z def plaszczyznaProsotopadla(wsp,x,y,z): A = wsp[1] B = wsp[3] C = wsp[5] D = -A*x - B*y - C*z return A,B,C,D def position_estimate(xp1,yp1,xp2,yp2): H = 2.0 # wysokosc kamery gornej h = 0.4 # wyokosc ...
intel-analytics/BigDL
python/orca/src/bigdl/orca/cpu_info.py
Python
apache-2.0
2,911
0.000687
# # Copyright 2016 The BigDL 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 ...
ptional[int] = None): # If we are in a docker container whose --cpuset-cpus are set, # we can get available cpus in /sys/fs/cgroup/cpuset/cpuset.cpus. # If we are not in a container, this just return all cpus. cpuset = get_cgroup_cpuset() cpuset = sorted(cpuset) l_core_to_p_core, l_core_to_sock...
physical_core = l_core_to_p_core[logical_core] p_cores.add(physical_core) if physical_core not in p2l: p2l[physical_core] = logical_core p_cores = sorted(p_cores) if cores_per_worker is None: cores_per_worker = len(p_cores) // num_workers msg = "total number of co...
allenlavoie/tensorflow
tensorflow/contrib/distributions/python/kernel_tests/bijectors/cholesky_outer_product_test.py
Python
apache-2.0
5,365
0.006151
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
l(x, x.T) with s
elf.test_session() as sess: x_pl = array_ops.placeholder(dtypes.float32) y_pl = array_ops.placeholder(dtypes.float32) y_actual = bijectors.CholeskyOuterProduct().forward(x=x_pl) x_actual = bijectors.CholeskyOuterProduct().inverse(y=y_pl) [y_actual_, x_actual_] = sess.run([y_actual, x_actual]...
palmtree5/Red-DiscordBot
tests/cogs/test_trivia.py
Python
gpl-3.0
799
0.001252
import textwrap import yaml from schema import SchemaError
def test_trivia_lists(): from redbot.cogs.trivia import InvalidListError, get_core_lists, get_list list_names = get_core_lists() assert list_names problem_lists = [] for l in list_names: try: get_list(l) except InvalidListError as exc: e = exc.__cause__ ...
problem_lists.append((l.stem, f"SCHEMA error:\n{e!s}")) else: problem_lists.append((l.stem, f"YAML error:\n{e!s}")) if problem_lists: msg = "" for name, error in problem_lists: msg += f"- {name}:\n{textwrap.indent(error, ' ')}" raise...
ImageIntelligence/mimiron
mimiron/__init__.py
Python
mit
334
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals __
all__ = [ '__version_info__',
'__version__', '__author__', '__author_email__', ] __version_info__ = (0, 4, 3) __version__ = '.'.join([unicode(i) for i in __version_info__]) __author__ = 'David Vuong' __author_email__ = '[email protected]'
khanhnnvn/poet
server.py
Python
mit
10,080
0.001091
#!/usr/bin/python2.7 import os import sys import zlib import base64 import socket import os.path import argparse from datetime import datetime import debug import module import config as CFG from poetsocket import * __version__ = '0.4.4' POSH_PROMPT = 'posh > ' FAKEOK = """HTTP/1.1 200 OK\r Date: Tue, 19 Mar 2013 2...
builtins = ['exit', 'help'] # exists so modules can stop server (used by selfdestruct) self.continue_ = True def start(self): """Poet server control shell.""" debug.info('Entering control shell') self.conn = PoetSocket(self.s.accept()[0]) print 'Welcome to posh, the...
le True: try: found = False argv = raw_input(POSH_PROMPT).split() # # builtins # if argv == []: continue if argv[0] == 'exit': break elif ...
yuanagain/seniorthesis
venv/lib/python2.7/site-packages/scipy/sparse/dok.py
Python
mit
17,654
0.000906
"""Dictionary Of Keys based matrix""" from __future__ import division, print_function, absolute_import __docformat__ = "restructuredtext en" __all__ = ['dok_matrix', 'isspmatrix_dok'] import functools import operator import numpy as np from scipy._lib.six import zip as izip, xrange, iteritems, itervalues from .b...
Duplicates are not allowed. Can be efficiently converted to a coo_matrix once constructed. Examples -------- >>> import numpy as np >>> from scipy.sparse import dok_matrix >>> S = dok_matrix((5, 5), dtype=np.float32) >>> for i in range(5): ... for j in range(5): ... ...
element """ format = 'dok' def __init__(self, arg1, shape=None, dtype=None, copy=False): dict.__init__(self) spmatrix.__init__(self) self.dtype = getdtype(dtype, default=float) if isinstance(arg1, tuple) and isshape(arg1): # (M,N) M, N = arg1 self...
mozaik-association/mozaik
mozaik_account/tests/__init__.py
Python
agpl-3.0
153
0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or l
ater
(http://www.gnu.org/licenses/agpl). from . import test_accounting from . import test_donation
youtube/cobalt
starboard/build/run_bash.py
Python
bsd-3-clause
1,290
0.003101
#!/usr/bin/env python3 # # Copyright 2021 The Cobalt Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
ross-platform way (that is, it should only be used for an action on a particular platform, not an platform-independent target). """ import logging import subprocess import sys if __name__ == '__main__': logging_format = '[%(levelname)s:%(filename)s:%(lineno)s] %(message)s' logging.basicConfig( level=logging...
ng('Calling a bash process during GN build. ' 'Avoid doing this whenever possible.') sys.exit(subprocess.call(sys.argv[1:]))
gigglearrows/anniesbot
alembic/versions/4db5dc4bc98_added_a_table_for_timed_commands.py
Python
mit
1,034
0.014507
"""Added a table for timed commands Revision ID: 4db5dc4bc98 Revises: 514f4
b9bc74 Create Date: 2015-12-23 00:00:59.156496 """ # revision identifiers, used by Alembic. revision = '4db5dc4bc98' down_revision = '514f4b9bc74' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): ### commands auto generate...
sa.Integer(), nullable=False), sa.Column('name', sa.String(length=256), nullable=False), sa.Column('action', mysql.TEXT(), nullable=False), sa.Column('interval_online', sa.Integer(), nullable=False), sa.Column('interval_offline', sa.Integer(), nullable=False), sa.Column('enabled', sa.Boolean(), nul...
changsimon/trove
trove/tests/api/mgmt/malformed_json.py
Python
apache-2.0
12,085
0
# Copyright 2013 OpenStack Foundation # Copyright 2013 Rackspace Hosting # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a co...
_bad_db_data) @test def test_bad_user_data(self): def format_path(values): values = list(values) msg = "%s%s" % (values[0], ''.join(['[%r]' % i for i in values[1:]])) return msg _user =
[] _user_name = "F343jasdf" _user.append({"name12": _user_name, "password12": "password"}) try: self.dbaas.users.create(self.instance.id, _user) except Exception as e: resp, body = self.dbaas.client.last_response httpCode = resp....
ity/pants
tests/python/pants_test/engine/test_fs.py
Python
apache-2.0
7,436
0.007934
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_
statement) import os import unittest from abc import abstractmethod from contextlib import contextmanager from pants.base.scm_project_tree import ScmProjectTree from pants.engine.fs import (Dir, DirectoryListing, Dirs, FileContent, Files, Link, Pat
h, PathGlobs, ReadLink, Stat, Stats) from pants.engine.nodes import FilesystemNode from pants.util.meta import AbstractClass from pants_test.engine.scheduler_test_base import SchedulerTestBase from pants_test.testutils.git_util import MIN_REQUIRED_GIT_VERSION, git_version, initialize_repo ...
schleichdi2/OPENNFR-6.3-CORE
bitbake/lib/bb/ui/uievent.py
Python
gpl-2.0
4,475
0.00514
# # Copyright (C) 2006 - 2007 Michael 'Mickey' Lauer # Copyright (C) 2006 - 2007 Richard Purdie # # SPDX-License-Identifier: GPL-2.0-only # """ Use this class to fork off a thread to recieve event callbacks from the bitbake server and queue them for the UI to process. This process must be used to avoid client/server...
if self.EventHandle != None: break errmsg = "Could not register UI event handler. Error: %s, host %s, "\ "port %d" % (err
or, self.host, self.port) bb.warn("%s, retry" % errmsg) import time time.sleep(1) else: raise Exception(errmsg) self.server = server self.t = threading.Thread() self.t.setDaemon(True) self.t.run = self.startCallbackHandler ...
dmlb2000/pacifica-archiveinterface
tests/posix_test.py
Python
lgpl-3.0
6,379
0.000314
#!/usr/bin/python # -*- coding: utf-8 -*- """File used to unit test the pacifica archive interface.""" import unittest import os from stat import ST_MODE from six import PY2 from pacifica.archiveinterface.archive_utils import bytes_type from pacifica.archiveinterface.backends.posix.archive import PosixBackendArchive im...
self.assertEqual(error,
None) else: self.assertEqual(error, 18) my_file.close() def test_posix_file_mod_time(self): """Test the correct setting of a file mod time.""" filepath = '1234' mode = 'w' backend = PosixBackendArchive('/tmp/') my_file = backend.open(filepath, mod...
artcz/euler
problems/02/2.py
Python
mit
1,241
0.001612
# coding: utf-8 """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8,
13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ import itertools import time def oneliner(): fib = lambda x: fib(x-1)+fib(x-2) if x > 2 else 1 return sum( fib(z) for z in itertool...
unt() ) if fib(z) % 2 == 0 ) def impl1(): oldfib = 1 fib = 1 even = [] while fib <= 4*10**6: if fib % 2 == 0: even.append(fib) fib, oldfib = fib + oldfib, fib return sum(even) def impl2(): prev, fib = 1, 1 _sum = 0 while fib <= 4*10*...
jorik041/dfvfs
dfvfs/file_io/qcow_file_io.py
Python
apache-2.0
1,285
0.003891
# -*- coding: utf-8 -*- """The QCOW image file-like object.""" import pyqcow from dfvfs import dependencies from dfvfs.file_io import file_object_io from dfvfs.lib import errors from dfvfs.resolver import resolver dependencies.CheckModuleVersion(u'pyqcow') class QcowFile(file_object_io.FileObjectIO): """Class t...
supported path specification without parent.') file_object = resolver.Resolver.OpenFileObject( path_spec.parent, resolver_context=self._resolver_context) qcow_file = pyqcow.file() qcow_file.open_file_object(file_
object) return qcow_file def get_size(self): """Returns the size of the file-like object. Raises: IOError: if the file-like object has not been opened. """ if not self._is_open: raise IOError(u'Not opened.') return self._file_object.get_media_size()
jtpaasch/armyguys
venv/bin/rst2xetex.py
Python
mit
811
0.001233
#!/home/jt/code/armyguys/venv/bin/python3.4 # $Id: rst2xetex.py 7038 2011-05-19 09:12:02Z milde $ # Author: Guenter Milde # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing XeLaTeX source code. """ try: import locale locale.setlocale(lo...
standalone reStructuredText ' 'sources. ' 'Reads from <source> (default is stdin) and writes to ' '<destination> (default is stdout). See '
'<http://docutils.sourceforge.net/docs/user/latex.html> for ' 'the full reference.') publish_cmdline(writer_name='xetex', description=description)
Akrog/cinder
cinder/api/v1/snapshots.py
Python
apache-2.0
8,045
0
# Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
"AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # u
nder the License. """The volumes snapshots api.""" from oslo_utils import strutils import webob from webob import exc from cinder.api import common from cinder.api.openstack import wsgi from cinder.api import xmlutil from cinder import exception from cinder.i18n import _, _LI from cinder.openstack.common import log ...
races1986/SafeLanguage
CEM/tests/test_xmlreader.py
Python
epl-1.0
1,809
0.00387
import xml.sax import unittest import test_utils import xmlreader import os path = os.path.dirname(os.path.abspath(__file__) ) class XmlReaderTestCase(unittest.TestCase): def test_XmlDumpAllRevs(self): pages = [r for r in xmlreader.XmlDump(path + "/data/article-pear.xml", allrevisions=True).parse()] ...
t) def test_MediaWikiXmlHandler(self): handler = xmlreader.MediaWikiXmlHandler() pages = [] def pageDone(page): pages.append(page) handler.setCallback(pageDone) xml.sax.parse(path + "/data/article-pear.xml", handler) self.assertEquals(u"Pear", pages[0].ti...
self.assertNotEquals("", pages[0].comment) if __name__ == '__main__': unittest.main()
HudsonWerks/OLED-SSD1306
ssd1306/fonts/stencil_24.py
Python
lgpl-3.0
98,068
0.156068
# coding=utf-8 # Module stencil_24 # generated from Stencil 18pt name = "Stencil 24" start_char = '!' end_char = chr(127) char_height = 24 space_width = 12 gap_width = 3 bitmaps = ( # @0 '!' (5 pixels wide) 0x00, # 0x00, # 0x00, # 0x00, # 0x70, # OOO ...
0x40, 0x00, # OO OO O 0x00, 0xC0, 0x00, # OO 0x00, 0x80, 0x00, # O 0x01, 0x9E, 0x00, # OO OOOO 0x01, 0x33, 0x00, #
O OO OO 0x03, 0x73, 0x80, # OO OOO OOO 0x02, 0x73, 0x80, # O OOO OOO 0x06, 0x73, 0x80, # OO OOO OOO 0x04, 0x33, 0x00, # O OO OO 0x0C, 0x1E, 0x00, # OO OOOO 0x00, 0x00, 0x00, # 0x00, 0x00, 0x00, # 0x00, ...
SivagnanamCiena/mock-s3
tests/push.py
Python
mit
652
0.003067
#!/usr/bin/env python import boto from boto.s3.key import Key OrdinaryCallingFormat = boto.config.get('s3', 'calling_format', 'bo
to.s3.connection.OrdinaryCallingFormat') s3 = boto.connect_s3(host='localhost', port=10001, calling_format=OrdinaryCallingFormat, is_secure=False) b = s3.get_bucket('mocking') k_cool = Key(b) k_cool.key = 'cool.html' k_cool.set_contents_from_string('this is some really cool html') k_green = Key(b) k_green.key = 'gre...
m_string('this is some really good music html') k_horse = Key(b) k_horse.key = 'seminoles.html' k_horse.set_contents_from_string('this is some really seminoles html')
ncliam/serverpos
openerp/addons/hr_gamification/wizard/grant_badge.py
Python
agpl-3.0
2,525
0.002376
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the ...
raise osv.except_osv(_('Warning!'), _('You can not send a badge to
yourself')) values = { 'user_id': wiz.user_id.id, 'sender_id': uid, 'badge_id': wiz.badge_id.id, 'employee_id': wiz.employee_id.id, 'comment': wiz.comment, } badge_user = badge_user_obj.create(cr, uid, ...
TheWardoctor/Wardoctors-repo
script.module.fantastic/lib/resources/lib/sources/en/rlsbb.py
Python
apache-2.0
5,587
0.013782
# -*- coding: utf-8 -*- ''' fantastic Add-on 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 later version. This pro...
/.|/,]', '', size))/div size = '%.2f GB' % size info.append(size) ex
cept: pass info = ' | '.join(info) url = item[1] if any(x in url for x in ['.rar', '.zip', '.iso']): raise Exception() url = client.replaceHTMLCodes(url) url = url.encode('utf-8') ...
ellisonbg/ipyleaflet
ipyleaflet/basemaps.py
Python
mit
14,548
0.02997
class Bunch(dict): """A dict with attribute-access""" def __getattr__(self, key): try: return self.__getitem__(key) except KeyError: raise AttributeError(key) def __setattr__(self, key, value): self.__setitem__(key, value) def __dir__(self): ret...
/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', name = 'CartoDB.Positron' ), DarkMatter = dict(
url = 'http://c.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', max_zoom = 20, attribution = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', name = 'CartoDB.DarkMatter' ) ...
bengjerstad/windowslogonofflogger
logserver/__init__.py
Python
mit
450
0.048889
import hug try: from . import runserver ##to run windowslogonofflo
gger ##https://github.com/bengjerstad/windowslogonofflogger hug.API(__name__).extend(runserver, '') print('Running windowslogonofflogger Server') except: pass try: from . import logserver ##to run MulitUse Log Server ##https://github.com/bengjerstad/multiuselogserver hug.API(__name__).extend(logserver, '/lo...
FocusLab/willie
vendor/lightningjs/lib/python/lightningjs/http/__init__.py
Python
bsd-3-clause
2,265
0.001766
import os import urlparse from SocketServer import ThreadingMixIn from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_server, WSGIServer from lightningjs.http.gzipper import GzipperMiddleware class ThreadedWsgiServer(ThreadingMixIn, WSGIServer): pass class RoutableApplication...
] status, content_type, content = getattr(self.__routable_object, path_method)(**single_value_args) else: # route doesn't exist content_type = 'text/html'
content = status = '404 NOT FOUND' # write out the HTTP response status = '200 OK' headers = [('Content-type', content_type)] start_response(status, headers) return [content] def serve_routable_object(routable_object, port): routable_server = RoutableApplication(rout...
spulec/moto
tests/test_core/test_nested.py
Python
apache-2.0
736
0
import sure # noqa # pylint: disable=unused-import import unittest import boto3 from moto import mock_sqs, mock_ec2 from tests import EXAMPLE_AMI_ID class TestNestedDecoratorsBoto3(unittest
.TestCase): @mock_sqs def setup_sqs_queue(self): conn = boto3.resource("sqs", region_name="us-east-1") queue = conn.create_queue(QueueName="some-queue") queue.send_message(MessageBody="test message 1") queue.reload() queue.attributes["ApproximateNumberOfMessages"].shoul...
@mock_ec2 def test_nested(self): self.setup_sqs_queue() conn = boto3.client("ec2", region_name="us-west-2") conn.run_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
anhstudios/swganh
data/scripts/templates/object/mobile/shared_kaja_orzee.py
Python
mit
437
0.048055
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create
(kernel): result = Cr
eature() result.template = "object/mobile/shared_kaja_orzee.iff" result.attribute_template_id = 9 result.stfName("theme_park_name","kaja_orzee") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
depop/django-oauth2-provider
provider/oauth2/admin.py
Python
mit
840
0
from django.apps import apps from d
jango.contrib import admin AccessToken = apps.get_model('oauth2', 'AccessToken') Client = apps.get_model('oauth2', 'Client') Grant = apps.get_model('oauth2', 'Grant') RefreshToken = apps.get_model('oauth2', 'RefreshToken') class AccessTokenAdmin(admin.ModelAdmin): list_display = ('user', 'client', 'token', 'expi...
'user',) class ClientAdmin(admin.ModelAdmin): list_display = ('url', 'user', 'redirect_uri', 'client_id', 'client_type') raw_id_fields = ('user',) admin.site.register(AccessToken, AccessTokenAdmin) admin.site.register(Grant, GrantAdmin) admin.site.register(Client, ClientAdmin) admin.site.register(RefreshTok...
akiokio/centralfitestoque
src/.pycharm_helpers/python_stubs/-1807332816/zipimport.py
Python
bsd-2-clause
4,893
0.008379
# encoding: utf-8 # module zipimport # from (built-in) # by generator 1.130 """ zipimport provides support for importing Python modules from Zip archives. This module exports three objects: - zipimporter: a class; its constructor takes a path to a Zip archive. - ZipImportError: exception raised by zipimporter objects....
unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" # variables with complex values _zip_directory_cache = {} # real value of type <type 'dic
t'> skipped
eltuxusb/eltuxusb
eltuxusb/el_input.py
Python
gpl-3.0
981
0.004077
# -*- coding: utf-8 -*- # This module contains classes to manage EL1USB device # This class reads the content of the EL-USB-1 thermometer import sys import datetime import time class el1_input: "Doc ..." def __init__(self): self.fake = 0 def request(self, text, base_value, min_value, max_value): ...
min_value: print "value too low, should be between", min_value, "and", max_value if base_value > max_value: print "value too high, should be between", min_value, "and", max_value return base_value
def convert_name(self, name): new_buffer = [] for char in name: new_buffer.append(ord(char)) count = len(name) while count != 16: new_buffer.append(0) count += 1 return new_buffer
ralphiee22/kolibri
kolibri/logger/api.py
Python
mit
2,079
0.002886
from kolibri.auth.api import KolibriAuthPermissions, KolibriAuthPermissionsFilter from kolibri.content.api import OptionalPageNumberPagination from rest_framework import filters, viewsets from .models import ContentRatingLog, ContentSessionLog, ContentSummaryLog, UserSessionLog from .serializers import ContentRatingLo...
missions,) filter_backends = (KolibriAuthPermissionsFilter,) queryset = ContentRatingLog.objects.all() serializer_class = ContentRatingLogSerializer pagination_class = OptionalPageNumberPagination class UserSessionLogViewSet(viewsets.ModelViewSet): permission_classes = (KolibriAut
hPermissions,) filter_backends = (KolibriAuthPermissionsFilter,) queryset = UserSessionLog.objects.all() serializer_class = UserSessionLogSerializer pagination_class = OptionalPageNumberPagination
youtube/cobalt
build/util/lib/common/PRESUBMIT.py
Python
bsd-3-clause
513
0.005848
# Copyright 2015 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. def _RunTests(input_api, output_api): return (input_api.canned_checks.RunUnitTestsInDir
ectory( input_api, output_api, '.', files_to_check=[r'.+_test.py$'])) def CheckChangeOnUpload(input_api,
output_api): return _RunTests(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _RunTests(input_api, output_api)
m-labs/llvmlite
llvmlite/tests/__init__.py
Python
bsd-2-clause
1,433
0.000698
import sys import unittest from unittest import TestCase try: import faulthandler except ImportError: pass else: try: # May fail in IPython Notebook with UnsupportedOperation faulthandler.enable() except BaseException as e: msg = "Failed to enable faulthandler due to:\n{err}" ...
# Try to inject Numba's unittest customizations. from . import customize def discover_tests(startdir): """Discover test under a directory """ # Avoid importing unittest loader = unittest.TestLoader() suite = loader.discover(startdir) return suite def run_tests(suite=None, xmloutput=None, ver...
---- - suite [TestSuite] A suite of all tests to run - xmloutput [str or None] Path of XML output directory (optional) - verbosity [int] Verbosity level of tests output Returns the TestResult object after running the test *suite*. """ if suite is None: suite =...
Smaed/pyDbManager
lib/Lang.py
Python
gpl-2.0
228
0.004386
#!/usr/bin/env
python # -*- coding: utf-8 -*- MENU_FILE = "File" FILE_NEW = "New"
FILE_OPEN = "Open" FILE_EXIT = "Exit" TAB_DATA = "Data" TAB_SQL = "SQL" BUTTON_EXIT = "Exit"
djangomini/djangomini
test_project/wsgi.py
Python
mit
373
0
""" WSGI config for project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangopr
oject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "settings") application = get_wsgi_application()
khchine5/lino
lino/utils/cycler.py
Python
bsd-2-clause
1,929
0.000518
# -*- coding: UTF-8 -*- # Copyright 2013-2014 by Luc Saffre. # License: BSD, see LICENSE for more details. """ Turns a list of items into an endless loop. Useful when generating demo fixtures. >>> from lino.utils import Cycler >>> def myfunc(): ... yield "a" ... yield "b" ... yield "c" >>> c = Cycler(myf...
If there is more than one positional argument, then these arguments themselves will be the list of items. """ if len(args) == 0: self.items = [] elif len(args) ==
1: if args[0] is None: self.items = [] else: self.items = list(args[0]) else: self.items = args self.current = 0 def pop(self): if len(self.items) == 0: return None item = self.items[self.current] ...
shelt/Fries
modules/user.py
Python
apache-2.0
3,458
0.006362
# Local imports from connect import m from crypto import * #NOTE: SQL '?' tuples must use '_t' as var name #NOTE: the tuples that fetch(one|all)() returns should be called 'res' ####################### # USER CLASS # ####################### # IDs and names are stored as fields because they # are used to quer...
return True def verify_user(username, password): _t = (username,) m.execute("SELECT * FROM Users WHERE name IS ?", _t) res = m.fetchone() assert res[1] == username
if get_hash(password, res[4]) == res[3]: return True else: return False def username_exists(username): _t = (username,) m.execute("SELECT COUNT(1) FROM Users WHERE name IS ?", _t) if m.fetchone()[0] == 1: return True ###################### # USER GETTERS # #############...
ulmusic/python-evolver
test/DS_sweep.py
Python
gpl-2.0
1,956
0.00818
import subprocess import multiprocessing import select import fcntl, os import re import matplotlib.pyplot as plt import numpy as np import time import evolver import logging evolver.logger.setLevel(logging.DEBUG) evolver.logger.addHandler(logging.StreamHandler()) def find_values(fileloc, phrase): wf = open(file...
bo + 0.05*i define_values(bo) E.open_file('dr
opSinusoidal.fe') for j in range(1): #E.refine(1) vals = E.evolve(1) E.run_command('car_app') E.run_command('car') E.run_command('') E.run_command('dump') E.run_command('') E.close...
MrTheodor/espressopp
src/interaction/TabulatedSubEnsAngular.py
Python
gpl-3.0
5,918
0.010645
# Copyright (C) 2018 # Max Planck Institute for Polymer Research # # This file is part of ESPResSo++. # # ESPResSo++ 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, o...
dSubEnsAngular(system, ftl, potential) :param system: The Espresso++ system object. :param ftl: The FixedTripleList. :param potential: The potential. :type system: espressopp.System :type ftl: espressopp.FixedTripleList :type potential: espr
essopp.interaction.Potential .. function:: espressopp.interaction.FixedTripleListTabulatedSubEnsAngular.setPotential(potential) :param potential: The potential object. :type potential: espressopp.interaction.Potential .. function:: espressopp.interaction.FixedTripleListTypesTabulatedSubEnsAngular(system, ftl) ...
yunity/foodsaving-backend
karrot/activities/migrations/0022_add_activity_types.py
Python
agpl-3.0
1,901
0.00263
# Generated by Django 3.0.9 on 2020-08-16 20:47 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('groups', '0042_auto_20200507_1258'), ('activities', '0021_remove_activity_feedback_as_su...
('has_feedback_weight', models.BooleanField(default=True)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='activity', name='activity_type', f
ield=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='activities', to='activities.ActivityType'), ), migrations.AddField( model_name='activityseries', name='activity_type', field=models.ForeignKey(null=True, on_delete=django.db.m...
BetterCollective/thumbor
thumbor/utils.py
Python
mit
2,733
0
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com [email protected] import os import logging from functools import wraps
CONTENT_TYPE = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.png': 'image/png', '.webp': 'image/webp', '.mp4': 'video/mp4', '.webm': 'video/webm', '.svg': 'image/svg+xml', } EXTENSION = { 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/png': '.png...
logger = logging.getLogger('thumbor') class on_exception(object): def __init__(self, callback, exception_class=Exception): self.callback = callback self.exception_class = exception_class def __call__(self, fn): def wrapper(*args, **kwargs): self_instance = args[0] if le...
robotics-at-maryland/qubo
src/teleop/src/keyboard_controller.py
Python
mit
2,473
0.024262
import pygame import rospy import time from std_msgs.msg import Float64 from std_msgs.msg import Float64MultiArray #pygame setup pygame.init() pygame.display.set_mode([100,100]) delay = 100 interval = 50 pygame.key.set_repeat(delay, interval) #really this should be passed in or something but for now if you want to ...
bot_namespace + "surge_cmd" , Float64, queue_size = 10 ) sway_pub = rospy.Publisher(robot_namespace + "sway_cmd" , Float64, queue_size = 10 ) thruster_pub = rospy.Publisher(robot_namespace + "thruster_cmds"
, Float64MultiArray, queue_size = 10) thruster_msg = Float64MultiArray() pygame.key.set_repeat(10,10) while(True): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: print event.key keys_pressed = pygame.key.get_pressed() sway = surge = yaw = depth = 0 thruster...
arth-co/shoop
shoop/simple_cms/__init__.py
Python
agpl-3.0
823
0
# This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop 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. from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ import sh
oop.apps class AppConfig(shoop.apps.AppConfig): name = __name__ verbose_name = _("Simple CMS") label = "shoop_simple_cms" provides = { "front_urls_post": [__name__ + ".urls:urlpatterns"], "admin_module": [ "shoop.simple_cms.admin_module:SimpleCMSAdminModule" ], ...
ericholscher/django-haystack
tests/whoosh_tests/tests/whoosh_backend.py
Python
bsd-3-clause
46,194
0.002165
from datetime import timedelta from decimal import Decimal import os import shutil from whoosh.fields import TEXT, KEYWORD, NUMERIC, DATETIME, BOOLEAN from whoosh.qparser import QueryParser from django.conf import settings from django.utils.datetime_safe import datetime, date from django.test import TestCase from hayst...
xt' ) author = indexes.CharField(model_attr='author', weight=2.0) editor = indexes.CharField(model_attr='editor') pub_date = indexes.DateField(model_attr='pub_date') def get_model(self): return AFourthMockModel def prepare(self, obj): data = super(WhooshBoostMockSearchIndex, se...
data['boost'] = 2.0 return data class WhooshAutocompleteMockModelSearchIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(model_attr='foo', document=True) name = indexes.CharField(model_attr='author') pub_date = indexes.DateField(model_attr='pub_date') text_auto = index...
LIMXTEC/BitCore
test/functional/combine_logs.py
Python
mit
4,611
0.004121
#!/usr/bin/env python3 """Combine logs from multiple bitcore nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile.""" import argparse from collections import defaultdict, namedtuple import heapq import itertools import os i...
opened. Continuing without it." % logfile, file=sys.stderr) def print_logs(log_events, color=False, html=False): """Renders the iterator of log events into text or html.""" if not html: colors = defaultdict(lambda: '') if color: colors["test"] = "\033[0;36m" # CYAN co...
EEN colors["node2"] = "\033[0;31m" # RED colors["node3"] = "\033[0;33m" # YELLOW colors["reset"] = "\033[0m" # Reset font color for event in log_events: print("{0} {1: <5} {2} {3}".format(colors[event.source.rstrip()], event.source, event.event, colors["res...
gres147679/IngSoftwareRectaFinal
Tarea5/ServiSoft/ServiSoft/WebAccess/signalActions.py
Python
gpl-2.0
948
0.033755
import models def borradoPlan(sender, **kwargs): borrada = kwargs['instance'] if borrada.tipo == "pr": aBorrar = models.PlanPrepago.objects.filter(codplan=borrada) else: aBorrar = models.PlanPostpago.objects.filter(codplan=borrada) aBorrar.delete() def insertadoServicio(sender, **kwargs): ...
odserv,nombrepaq=insertado.nombreserv + ' Paquete',precio=insertado.costo) nuevoPaq.save() nuevo
Contiene = models.Contiene(codpaq=nuevoPaq,codserv=insertado,cantidad=1) nuevoContiene.save() def borradoServicio(sender, **kwargs): borrado = kwargs['instance'] if borrado.id is not None: contieneBorrar = models.Contiene.objects.all().filter(codpaq=borrado.codserv) contieneBorrar.delete() paqBorrar = mod...
mzdaniel/oh-mainline
vendor/packages/amqplib/demo/amqp_clock.py
Python
agpl-3.0
2,344
0.005973
#!/usr/bin/env python """ AMQP Clock Fires off simple messages at one-minute intervals to a topic exchange named 'clock', with the topic of the message being the local time as 'year.month.date.dow.hour.minute', for example: '2007.11.26.1.12.33', where the dow (day of week) is 0 for Sunday, 1 for Monday, and so on (sim...
parser = OptionParser() parser.add_option('--host', dest='host', help='AMQP server to connect to (default: %default)', default='localhost') parser.add_option('-u', '--userid', dest='userid', help='AMQP userid to authenticate as (default: %d...
password to authenticate with (default: %default)', default='guest') parser.add_option('--ssl', dest='ssl', action='store_true', help='Enable SSL with AMQP server (default: not enabled)', default=False) options, args = parser.parse_args()...
arju88nair/projectCulminate
venv/lib/python3.5/site-packages/nltk/app/__init__.py
Python
apache-2.0
1,733
0.000577
# Natural Language Toolkit: Applications package # # Copyright (C) 2001-2017 NLTK Project # Author: Edward Loper <[email protected]> # Steven Bird <[email protected]> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Interactive NLTK Applications: chartparser: Chart Parser chunkpar...
nltk.app.rdparser_app import app as rdparser from nltk.app.srparser_app import app as srparser from nltk.app.wordnet_app import app as wordnet try: from matplotlib import pylab except ImportError: import warnings warnings.warn("nltk.app.wordfreq not loaded " ...
p.wordfreq_app import app as wordfreq # skip doctests from this package def setup_module(module): from nose import SkipTest raise SkipTest("nltk.app examples are not doctests")
jordanemedlock/psychtruths
temboo/core/Library/Amazon/S3/CopyObject.py
Python
apache-2.0
9,236
0.005414
# -*- coding: utf-8 -*- ############################################################################### # # CopyObject # Makes a copy of an existing object in S3 Storage. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not ...
ef set_ServerSideEncryption(self, value): """ Set the value of the ServerSideEncryption input for this Choreo. ((optional, string) Specifies the server-side encryption algorithm to use when Amazon S3 creates the target object. Valid value: AES256.) """ super(CopyObjectInputSet, self)._se...
eEncryption', value) def set_StorageClass(self, value): """ Set the value of the StorageClass input for this Choreo. ((optional, string) Enables RRS customers to store their noncritical, reproducible data at lower levels of redundancy than Amazon S3's standard storage. Valid Values: STANDARD (defaul...
r0mai/metashell
3rd/templight/llvm/projects/compiler-rt/test/ubsan_minimal/lit.common.cfg.py
Python
gpl-3.0
1,525
0.013115
# -*- Python -*- import os def get_required_attr(config, attr_name): attr_value = getattr(config, attr_name, None) if attr_value == None: lit_config.fatal(
"No attribute %r in test configuration! You may need to run " "tests from your build directory or add this attribute " "to lit.site.cfg.py " % attr_name) return attr_value # Setup source root. config.test_source_root = os.path.di
rname(__file__) config.name = 'UBSan-Minimal-' + config.target_arch def build_invocation(compile_flags): return " " + " ".join([config.clang] + compile_flags) + " " target_cflags = [get_required_attr(config, "target_cflags")] clang_ubsan_cflags = ["-fsanitize-minimal-runtime"] + target_cflags clang_ubsan_cxxflags =...
gulopine/steel
steel/fields/__init__.py
Python
bsd-3-clause
214
0
from steel.fields.base import * from steel.fields.numbers import * from steel.fields.strings import * from steel.fields.compression import * from
steel.fields.co
mpound import * from steel.fields.integrity import *
jrha/artemis
tools/artemis-plot.py
Python
gpl-3.0
5,014
0.008975
#!/usr/bin/env python # # Copyright Science and Technology Facilities Council, 2009-2012. # # This file is part of ARTEMIS. # # ARTEMIS 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 ...
.0, 0.0), (1.0, 1.0, 1.0))
, } my_cmap = colors.LinearSegmentedColormap('my_colormap',cdict,256) #pcolor(rand(10,10),cmap=plt.cm.jet) def process(d, f, mode): x = [] y = [] z = [] for i in d: if "TEMPERATURE" in i[0]: r = float(i[3]) c = float(i[4]) v = float(i[1]) x.appe...
facepalm/bliss-station-game
src/modular_module.py
Python
gpl-3.0
7,899
0.033675
from generic_module import BasicModule from equipment.general import SolarPanel, DOCK_EQUIPMENT, WaterTank, CBM, Window, Battery, Comms from equipment.lifesupport import UniversalToilet, WaterPurifier, OxygenElectrolyzer, RegenerableCO2Filter from equipment.computer import DockingComputer, MissionComputer from equipme...
ModuleComponent.__init__(self,pos) _sampdict = {'port' : [ -0.5, 0, math.pi, 0 ], 'starboard' : [ 0.5 , 0, -math.pi, 0 ], 'nadir' : [0, -0.5, 0, -math.pi]} for _d in _sampdict.keys(): self.equipment.append([ ''.join( [ _d , str( pos ) ] ), np.array([ 0 , _sampdict[_d][0] , _sampdict...
os ) ] ) ] ) def refresh_image(self, x_off = 0): super(RackRing, self).refresh_image('images/rack_comp.png',x_off) def spawn_component(letter,pos=0): if letter in '{': return DockingCap(pos) elif letter in '}': return DockingCapClosed(pos) elif l...
botswana-harvard/edc-sms
edc_sms/settings.py
Python
gpl-2.0
4,211
0.00095
""" Django settings for edc_sms project. Generated by 'django-admin startproject' using Django 3.0.6. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os i...
django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_crypto_fields.apps.AppConfig', 'django_extensions', 'simple_history', 'django_apscheduler', 'edc_model_admin.apps.AppConfig', 'edc_base.apps.AppConfig', 'edc_devic
e.apps.AppConfig', 'edc_identifier.apps.AppConfig', 'edc_sms.apps.AppConfig', 'django_q' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMid...
synappio/swagger-pyramid
swagger/models.py
Python
apache-2.0
42
0.02381
def gene
rate_ming_models(models): pass
albertosalmeronunefa/tuconsejocomunal
addons/l10n_ve_dpt/models/l10n_ve_dpt.py
Python
gpl-3.0
2,432
0.004934
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
se for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## # Generated by
the Odoo plugin for Dia ! from odoo import api, fields, models class CountryState(models.Model): """ Add Municipalities reference in State """ _name = 'res.country.state' _inherit = 'res.country.state' _description="Country states" municipality_id = fields.One2many('res.country.state.municipality...
raviolli77/machineLearning_breastCancer_Python
src/python/produce_model_metrics.py
Python
mit
2,206
0.006346
import sys from sklearn.metrics impo
rt roc_curve from
sklearn.metrics import auc # Function for All Models to produce Metrics --------------------- def produce_model_metrics(fit, test_set, test_class_set, estimator): """ Purpose ---------- Function that will return predictions and probability metrics for said predictions. Parameters --------...
Punzo/SlicerAstro
AstroMomentMaps/Testing/Python/AstroMomentMapsSelfTest.py
Python
bsd-3-clause
6,817
0.008655
import os import unittest import vtk, qt, ctk, slicer import math import sys # # AstroMomentMapsSelfTest # class AstroMomentMapsSelfTest: def __init__(self, parent): parent.title = "Astro MomentMaps SelfTest" parent.categories = ["Testing.TestCases"] parent.dependencies = ["AstroVolume"] parent.cont...
self.parent = slicer.qMRMLWidget
() self.parent.setLayout(qt.QVBoxLayout()) self.parent.setMRMLScene(slicer.mrmlScene) else: self.parent = parent self.layout = self.parent.layout() if not parent: self.setup() self.parent.show() def setup(self): # Instantiate and connect widgets ... # reload button ...
rdolgushin/pgdumper
setup.py
Python
mit
642
0.034268
from setuptools import setup setup( name = 'pgdumper', description = 'Simple PostgreSQL dumper', author = 'Roman Dolgushin', author_em
ail = '[email protected]', url = 'https://github.com/rdolgushin/pgdumper', license = 'MIT', version = '0.1', packages = ['pgdumper'], install_requires = ['mydumper'], entry_points = { 'console_scripts': ['pgdumper = pgdumper.pgdumper:main'] }, classifiers = [ 'Topic :: Utilities', 'Topic...
], )
kyuupichan/electrum
gui/kivy/uix/dialogs/fee_dialog.py
Python
mit
4,529
0.001987
from kivy.app import App from kivy.factory import Factory from kivy.properties import ObjectProperty from kivy.lang import Builder from electrum_gui.kivy.i18n import _ Builder.load_string(''' <FeeDialog@Popup> id: popup title: _('Transaction Fees') size_hint: 0.8, 0.8 pos_hint: {'top':0.9} method:...
orientation: 'horizontal' size_hint: 1, 0.5 Button: text: 'Cancel' size_hint: 0.5, None height: '48dp'
on_release: popup.dismiss() Button: text: 'OK' size_hint: 0.5, None height: '48dp' on_release: root.on_ok() root.dismiss() ''') class FeeDialog(Factory.Popup): def __init__(self, app, config, c...
jpardobl/monscale
monscale/pypelib/Rule.py
Python
bsd-3-clause
3,386
0.056113
import os import sys import time import exceptions import uuid import logging ''' @author: msune,lbergesio,omoya,CarolinaFernandez @organization: i2CAT, OFELIA FP7 PolicyEngine Rule class Encapsulates logic of a simple Rule ''' from monscale.pypelib.Condition import Condition from monscale.pypelib.persi...
E_NONTERMINAL={'value':False,'terminal':False} _types = [POSITIVE_TERMINAL,POSITIVE_NONTERMINAL,NEGATIVE_TERMINAL, NEGATIVE_NONTERMINAL] #Rule type _type = None #Rule match Action _matchAction=None #Getters def getCondition(self): return self._condition def getDescription(self): return self._descrip...
return self._matchAction def getUUID(self): return self._uuid #setters def setUUID(self,UUID): self._uuid = UUID #Constructor def __init__(self,condition,description,errorMsg,ruleType=POSITIVE_TERMINAL,action=None,uuid=None): if not isinstance(condition,Condition): raise Exception("Object must be an i...
magicgoose/simple_dr_meter
audio_io/cue/cue_parser.py
Python
gpl-3.0
2,049
0.000488
import re from enum import Enum, auto from fractions import Fraction from io import BufferedIOBase from numbers import Number from typing import Iterable import chardet class CueCmd(Enum): PERF
ORMER = auto() TITLE = auto() FILE = auto() TRACK = auto() INDEX = auto() REM = auto() EOF = auto() def _unquote(s: str): return s[1 + s.index('"'):s.rindex('"')] _whitespace_pattern = re.compile(r'\s+') _rem_tag_pattern = re.compile(r'([A-Z_]+) (.+)')
def parse_cd_time(offset: str) -> Number: """parse time in CD-DA (75fps) format to seconds, exactly MM:SS:FF""" m, s, f = map(int, offset.split(':')) return m * 60 + s + Fraction(f, 75) def _parse_cue_cmd(line: str, offset_in_seconds: bool = True): line = line.strip() cmd, args = _whitespace_p...
hackaugusto/raiden
raiden/tests/unit/test_operators.py
Python
mit
2,554
0.000392
from raiden.messages import Processed from raiden.tests.utils import factories from raiden.transfer.events import ( EventPaymentReceivedSuccess, EventPaymentSentFailed, EventPaymentSentSuccess, ) from raiden.transfer.state_change import ActionCancelPayment, Block from raiden.utils import sha3 ADDRESS = sha...
assert a == b assert not a != b assert a != c assert not a == c assert c != d assert not c == d def test_message_operators(): message_identifier = 10 message_identifier2 = 11 a = Processed(message_identifier=message_i
dentifier) b = Processed(message_identifier=message_identifier) c = Processed(message_identifier=message_identifier2) # pylint: disable=unneeded-not assert a == b assert not a != b assert a != c assert not a == c
ResearchComputing/RCAMP
rcamp/tests/test_projects_receivers.py
Python
mit
4,732
0.00317
from mock import MagicMock import mock from django.test import override_settings from tests.utilities.utils import SafeTestCase from tests.utilities.ldap import get_ldap_user_defaults from accounts.models import ( User, AccountRequest, Intent ) from projects.models import Project from projects.receivers im...
eck_general_eligibility
organization_info = { 'ucb': { 'long_name': 'University of Colorado Boulder', 'suffix': None, 'general_project_id': 'ucb-general' }, 'csu': { 'long_name': 'Colorado State University', 'suffix': 'colostate.edu', 'general_project_id': 'csu-general' } } @ov...
Syralist/yet-another-hexapod
hexapy/Arm.py
Python
mit
6,538
0.008259
''' Copyright (C) 2013 Travis DeWolf 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 later version. This program is distributed in the hope t...
"""Objective function to minimize Calculates the euclidean distance through joint space to the
default arm configuration. The weight list allows the penalty of each joint being away from the resting position to be scaled differently, such that the arm tries to stay closer to resting state more for higher weighted joints than those with a lower weight. ...
jcollie/ceph_exporter
ceph_exporter/ceph/metrics/ceph_objects_recovered.py
Python
gpl-3.0
908
0
# -*- mode: python; coding: utf-8 -*- # Copyright © 2016 by Jeffrey C. Ollie # # This file is part of ceph_exporter. # # ceph_exporter is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by t
he Free Software Foundation, either version 3 of the # License, or (at you
r option) any later version. # # ceph_exporter is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU...
yshalenyk/reports
reports/tests/bids_tests.py
Python
apache-2.0
9,230
0.000108
import unittest import mock from reports.tests.base import BaseBidsUtilityTest from copy import copy test_bids_invalid = [ [{ "owner": "test", "date": "2016-03-17T13:32:25.774673+02:00", "id": "44931d9653034837baff087cfc2fb5ac", }], [{ "status": "invalid", "owner": ...
data) def test_bids_view_invalid_mode(self): data = { 'mode': 'test', "awardPeriod": { "startDate": test_award_period, }, 'owner': 'teser', "bids": test_bids_valid[0],
} self.assertLen(0, data) def test_bids_view_invalid_status(self): data = { "procurementMethod": "open", "awardPeriod": { "startDate": test_award_period, }, 'owner': 'teser', 'bids': test_bids_invalid[1], } ...
kirsle/rophako
rophako/jsondb.py
Python
gpl-2.0
7,743
0.002583
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function, absolute_import """JSON flat file database system.""" import codecs import os import os.path import re from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN import redis import json import time from rophako.settings import Config from roph...
# Unlock and close. flock(fh, LOCK_UN) fh.close() ############################################################################ # Redis Caching Functions # ############################################################################ disable_redis = False def ge...
isable_redis if not redis_client and not disable_redis: try: redis_client = redis.StrictRedis( host = Config.db.redis_host, port = Config.db.redis_port, db = Config.db.redis_db, ) redis_client.ping() except Except...
lesteve/joblib
joblib/test/test_memory.py
Python
bsd-3-clause
39,966
0.0002
""" Test the memory module. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import shutil import os import os.path import pickle import sys import time import datetime import pytest from joblib.memory import Memory from job...
from joblib.testing import parametrize, raises, warns from joblib._compat import PY3_OR_LATER from joblib.hashing import hash if sys.version_info[:2] >= (3, 4): import pathlib ############################################################################### # Module-level variables for the tests def f(x, y=1): ...
################# # Helper function for the tests def check_identity_lazy(func, accumulator, location): """ Given a function and an accumulator (a list that grows every time the function is called), check that the function can be decorated by memory to be a lazy identity. """ # Call each fun...
OxPython/Python_set_pop
src/set_pop.py
Python
epl-1.0
574
0.017483
''' Created on Jul 9, 2014 @author: viejoemer HowTo remove an arbitrary element and retrieve that item at t
he same time? ¿Cómo eliminar un elemento de forma arbitraria y recuperar ese elemento al mismo tiempo? pop() Remove and return an arbitrary element from the set. Raises KeyError if the set is empty. ''' #Create a set with values. s_1 = set([1,2,3]) print("set one", s_1) s_2 = set() print("set one", s_2) #Removing...
value = s_1.pop() print("Element removed",s_1) print("Value removed",value) #If the set is empty return an error value = s_2.pop()
suttond/MODOI
ase/ga/convergence.py
Python
lgpl-3.0
3,442
0.000581
"""Classes that determine convergence of an algorithm run based on population stagnation or max raw score reached""" class Convergence(object): """ Base class for all convergence object to be based on. It is necessary to supply the population instance, to be able to obtain current and former populatio...
max([i.info['key_value_pairs']['generation'] for i in cur_pop[:self.numindis]]) if newest + self.numgens > cur_gen_num: return False self.populate_pops(cur_gen_num) duplicate_gens = 1
latest_pop = self.pops[cur_gen_num - 1] for i in range(cur_gen_num - 2, -1, -1): test_pop = self.pops[i] if test_pop[:self.numindis] == latest_pop[:self.numindis]: duplicate_gens += 1 if duplicate_gens >= self.numgens: return True ret...
gerritjvv/cryptoplayground
kerberos/kdc/src/krb5-1.16/src/tests/t_keytab.py
Python
apache-2.0
5,482
0.00073
#!/usr/bin/python from k5test import * for realm in multipass_realms(create_user=False): # Test kinit with a keytab. realm.kinit(realm.host_princ, flags=['-k']) realm = K5Realm(get_creds=False, start_kadmind=True) # Test kinit with a partial keytab. pkeytab = realm.keytab + '.partial' realm.run([ktutil], inp...
nit(realm.host_princ, flags=['-t', realm.keytab],
expected_msg='keytab specified, forcing -k') realm.klist(realm.host_princ) realm.run([kdestroy]) realm.kinit(realm.user_princ, flags=['-i'], expected_msg='keytab specified, forcing -k') realm.klist(realm.user_princ) # Test extracting keys with multiple key versions present. os.remove(realm.keytab) realm...
openstack/neutron-lib
neutron_lib/tests/unit/api/definitions/test_port.py
Python
apache-2.0
793
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from neutron_lib.api.definitions import port from neutron_lib.tests.unit.api.defini
tions import base class PortDefinitionTestCase(base.DefinitionBaseTestCase): extension_module = port extension_attributes = ()
DinoTools/ArduRPC-python
ardurpc/handler/lcd/__init__.py
Python
lgpl-3.0
1,384
0.001445
import ardurpc from ardurpc.handler import Handler class Base(Handler): """Handler for the Base Text-LCD type""" def __init__(self, **kwargs): Handler.__init__(self, **kwargs) def getWidth(self): """ Get the display width as number of characters. :return: Width :...
0x12) def setCursor(self, col, row): """ Position the cursor. """ return self._call(0x13, '>BB', col, row) def write(self, c): """ Print a single character to the LCD. """ c = c.encode('ASCII') return self._call(0x21, '>B', c[0]) d...
LCD. """ s = s.encode('ASCII') return self._call(0x22, '>B%ds' % len(s), len(s), s) ardurpc.register(0x0300, Base, mask=8)
Akrog/cinder
cinder/volume/drivers/netapp/dataontap/nfs_cmode.py
Python
apache-2.0
24,731
0
# Copyright (c) 2012 NetApp, Inc. All rights reserved. # Copyright (c) 2014 Ben Swartzlander. All rights reserved. # Copyright (c) 2014 Navneet Singh. All rights reserved. # Copyright (c) 2014 Clinton Knight. All rights reserved. # Copyright (c) 2014 Alex Meade. All rights reserved. # Copyright (c) 2014 Bob Callaw...
eated on shares.") raise exception.VolumeBackendAPIException(data=msg % (volume['name'])
) def _set_qos_policy_group_on_volume(self, volume, share, qos_policy_group): target_path = '%s' % (volume['name']) export_path = share.split(':')[1] flex_vol_name = self.zapi_client.get_vol_by_junc_vserver(self.vserver, expor...
magenta/ddsp
ddsp/training/train_util.py
Python
apache-2.0
12,295
0.008459
# Copyright 2022 The DDSP 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 wri...
fy an address to the `tpu` argument. For multi-machine GPU jobs, specify a `cluster_config` argument of the cluster configuration. Args: tpu: Address of the TPU. No TPU if left blank. cluster_config: Shoul
d be specified only for multi-worker jobs. Task specific dictionary for cluster config dict in the TF_CONFIG format. https://www.tensorflow.org/guide/distributed_training#setting_up_tf_config_environment_variable If passed as a string, will be parsed to a dictionary. Two components should be spe...
abhattad4/Digi-Menu
tests/template_tests/test_loaders.py
Python
bsd-3-clause
8,433
0.00107
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os.path import sys import types import unittest from contextlib import contextmanager from django.template import Context, TemplateDoesNotExist from django.template.engine import Engine from django.test import SimpleTestCase, override_settings fro...
urces('Ångström', ['/dir1/Ångström', '/dir2/Ångström']) def test_utf8_bytestring(self): """ Invalid UTF-8 encoding in bytestrings should raise a useful error """ engine = Engine() loader = engine.template_loaders[0] with self.assertRaises(UnicodeDecodeError): ...
e']) as check_sources: check_sources('Ångström', ['/Straße/Ångström']) check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/Straße/Ångström']) @unittest.skipUnless( os.path.normcase('/TEST') == os.path.normpath('/test'), "This test only runs on case-sensitive file systems.", ) ...
jbedorf/tensorflow
tensorflow/python/ops/distributions/transformed_distribution.py
Python
apache-2.0
27,637
0.005826
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.p...
ops.distributions import util as distribution_util from tensorflow.python.util import deprecation __all__ = [ "TransformedDistribution", ] # The following helper functions attempt to statically perform a TF operation. # These functions make debugging easier since we can do more validation during # graph construc...
apache/arrow
dev/archery/archery/integration/tester_go.py
Python
apache-2.0
3,999
0
# 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"); yo
u may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR C...
skycucumber/Messaging-Gateway
webapp/venv/lib/python2.7/site-packages/MySQLdb/connections.py
Python
gpl-2.0
11,777
0.001359
""" This module implements connections for MySQLdb. Presently there is only one class: Connection. Others are unlikely. However, you might want to make your own subclasses. In most cases, you will probably override Connection.default_cursor with a non-standard Cursor class. """ from MySQLdb import cursors fr...
unicode = False use_unicode = kwargs2.pop('use_unicode', use_unicode)
sql_mode = kwargs2.pop('sql_mode', '') client_flag = kwargs.get('client_flag', 0) client_version = tuple([ numeric_part(n) for n in _mysql.get_client_info().split('.')[:2] ]) if client_version >= (4, 1): client_flag |= CLIENT.MULTI_STATEMENTS if client_version ...
gdsfactory/gdsfactory
gdsfactory/geometry/outline.py
Python
mit
2,655
0.002637
import phidl.geometry as pg import gdsfactory as gf from gdsfactory.component import Component @gf.cell def outline(elements, **kwargs) -> Component: """ Returns Component containing the outlined polygon(s). wraps phidl.geometry.outline Creates an outline around all the polygons passed in the `elem...
isions:
array-like[2] of int The number of divisions with which the geometry is divided into multiple rectangular regions. This allows for each region to be processed sequentially, which is more computationally efficient. join: {'miter', 'bevel', 'round'} Type of join us...
shabab12/edx-platform
lms/djangoapps/courseware/tests/test_grades.py
Python
agpl-3.0
18,523
0.000702
""" Test grade calculation. """ from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from mock import patch, MagicMock from nose.plugins.attrib import attr from opaque_keys.edx.locations import SlashSeparatedCourseKey from opaque_keys.edx.locator import CourseL...
import MultipleChoiceResponseXMLFactory from student.tests.factories import UserFactory from student.models import CourseEnrollment from xmodule.modulestore.tests.factories impor
t CourseFactory, ItemFactory from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase def _grade_with_errors(student, course, keep_raw_scores=False): """This fake grade method will throw exceptions for student3 and student4, but allow any other students to go through normal grading. I...
mapillary/OpenSfM
opensfm/commands/create_submodels.py
Python
bsd-2-clause
454
0
from opensfm.actions import create_submodels from . import command import argparse from opensfm.dataset import DataSet class Command(command.CommandBase): name = "create_submodels" help = "Split the dataset into smaller submodels" def run_impl(self, dataset: DataSet, args: argparse.Namespace) -> None: ...
ars
er: argparse.ArgumentParser) -> None: pass
ValRose/Rose_Bone
PythonLibraries/lcd_demo.py
Python
mit
1,617
0.006184
''' Created on Dec 13, 2015 @author: Shannon Litwin ''' import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.PWM as PWM import Lib_LCD as LCD import Lib_Main as BBB import sys import signal import time leftForward = "P8_46" leftBackward = "P8_45" rightForward = "P9_14" rightBackward = "P9_16" def Control_C_Exit(si...
m1 = "It works 1" m2 = "It works 2" m3 = "It works 3" m4 = "It works 4" time.sleep(1) LCD.goto_line(4) LCD.write_line(m4) time.sleep(1) LCD.goto_line(3) LCD.write_line(m3) time.sleep(1) LCD.goto_line(2) LCD.write_line(m2) time.sleep(1) LCD.goto_line(1) LCD.write_line(m1) LCD.clear() #pause with while loop exam...
eanup_all()
cdd1969/pygwa
lib/flowchart/nodes/n000_testnode/myNode.py
Python
gpl-2.0
578
0.00519
from lib.flowchart.nodes.generalNode import NodeWithCtrlWidget class myNode(NodeWithCtrl
Widget): '''This is test d
ocstring''' nodeName = 'myTestNode' uiTemplate = [{'name': 'HNO3', 'type': 'list', 'value': 'Closest Time'}, {'name': 'C2H5OH', 'type': 'bool', 'value': 0}, {'name': 'H20', 'type': 'str', 'value': '?/?'}] def __init__(self, name, **kwargs): super(myNode, self...
sarielsaz/sarielsaz
test/functional/sendheaders.py
Python
mit
24,054
0.003492
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Sarielsaz Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of headers messages to announce blocks. Setup: - Two nodes, two p2p connections to n...
# return the list of block hashes newly mined def mine_reorg(self, length): self.nodes[0].generate(length) # make sure all invalidated blocks are node0's sync_blocks(self.nodes, wait=0.1) for x in self.p2p_connections: x.wait_for_block_announcement(int(self.nodes[0].getbestbl...
= self.nodes[1].getblockhash(tip_height-(
Esri/ops-server-config
Utilities/ListServiceWorkspaces.py
Python
apache-2.0
6,504
0.009533
#!/usr/bin/env python #------------------------------------------------------------------------------ # Copyright 2014 Esri # 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.apac...
------------------------------------------------------ # Check arguments # --------------------------------------------------------------------- if len(sys.argv) <> 6: print '\n' + scriptName + ' <Server_FullyQualifiedDomainName> <Server_Port> <User_Name> <Password> <Use_SSL: Yes|No>' ...
e fully qualified domain name of the ArcGIS Server machine.' print '\n\t<Server_Port> (required): the port number of the ArcGIS Server (specify # if no port).' print '\n\t<User_Name> (required): ArcGIS Server for ArcGIS site administrator.' print '\n\t<Password> (required): Password for ArcGIS S...
ksmit799/Toontown-Source
toontown/minigame/RingTrackGroups.py
Python
mit
8,136
0.004671
import math import RingGameGlobals import RingAction import RingTracks import RingTrack import RingTrackGroup from direct.showbase import PythonUtil STATIC = 0 SIMPLE = 1 COMPLEX = 2 def getRandomRingTrackGroup(type, numRings, rng): global trackListGenFuncs funcTable = trackListGenFuncs[type][numRings - 1] ...
/ 3.0] inc = 14.0 / 23.0 for numRings in range(4, 5): o = [0] * numRings accum = 0.0 for i in range(0, numRings): o[i] = accum % 1.0 accum += inc offsets[numRings - 1] = o infinityTOffsets = offsets __in
itInfinityTOffsets() def get_vertInfinity(numRings, rng): tracks = [] for i in range(0, numRings): actions, durations = RingTracks.getVerticalInfinityRingActions() track = RingTrack.RingTrack(actions, durations) tracks.append(track) return (tracks, infinityTOffsets[numRings - 1], i...
ppizarror/korektor
test/_template.py
Python
gpl-2.0
1,642
0.00061
#!/usr/bin/env python # -*- coding: utf-8 -*- """ package/module TEST Descripción del test. Autor: PABLO PIZARRO @ github.com/ppizarror Fecha: AGOSTO 2016 Licencia: GPLv2 """ __author__ = "ppizarror" # Importación de librerías # noinspection PyUnresolvedReferences from _testpath import * # @UnusedWildI...
d :rtype: None """ pass # noinspection PyMethodMayBeStatic def testA(self): """ Ejemplo de test. :return: void :rtype:
None """ pass @unittest.skipIf(DISABLE_HEAVY_TESTS, DISABLE_HEAVY_TESTS_MSG) def testSkipped(self): """ Ejemplo de test saltado. :return: void :rtype: None """ pass # Main test if __name__ == '__main__': runner = unittest.T...
cstipkovic/spidermonkey-research
testing/marionette/harness/setup.py
Python
mpl-2.0
1,214
0.002471
import os import re from setuptools import setup, find_packages THIS_DIR = os.path.dirname(os.path.realpath(__name__)) def read(*parts): with open(os.path.join(THIS_DIR, *parts)) as f: return f.read() def get_version(): return re.findall("__version__ = '([\d\.]+)'", read('mar...
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), package_data={'marionette': ['touch/*.js']}, include_package_data=True, zip_safe=False, entry_points=""" # -*- Entry points: -*- [console_scripts] marionette = marionette.runtests:cl
i """, install_requires=read('requirements.txt').splitlines(), )
viswimmer1/PythonGenerator
data/python_files/28964260/services.py
Python
gpl-2.0
5,901
0.002542
import oauth2 as oauth import sher.settings as settings import cgi import urlparse import urllib import gdata.youtube import gdata.youtube.service import twitter class TwitterService(object): def __init__(self, consumer_key, consumer_secret): self.consumer_key = consumer_key self.consumer_secret =...
f.api_key = api_key self.secret = secret self.auth_url = "http://flickr.com/services/auth/?" self.rest_url = "http
://flickr.com/services/rest/?" def gen_sig(self, base_url, **kwargs): from md5 import md5 params = {} for kwarg in kwargs: params.update({kwarg: kwargs[kwarg]}) pkeys = params.keys() pkeys.sort() sigstring = self.secret + "" for k in pkeys: ...
svohara/pyvision
src/pyvision/point/DetectorROI.py
Python
bsd-3-clause
4,461
0.011432
# PyVision License # # Copyright (c) 2006-2008 David S. Bolme # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, thi...
e[1]/self.bin_size npts = self.n / nbins + 1 corners = [] for xmin in range(0,A.shape[0],self.bin_size): xmax = xmin + self.bin_size for ymin in range(0,A.shape[1],self.bin_size): bin_data = [] ymax = ymin +...
for each in L: #print each if xmin <= each[1] and each[1] < xmax and ymin <= each[2] and each[2] < ymax: bin_data.append(each) if len(bin_data) >= npts: break ...
tkolhar/robottelo
tests/foreman/ui/test_architecture.py
Python
gpl-3.0
5,128
0
# -*- encoding: utf-8 -*- """Test class for Architecture UI""" from fauxfactory import gen_string from nailgun import entities from robottelo.datafactory import generate_strings_list, invalid_values_list from robottelo.decorators import run_only_on, tier1 from robottelo.test import UITestCase from robottelo.ui.factory ...
e) self.assertIsNotNone(self.architecture.search(old_name)) for new_name in generate_strings_list(): with self.subTest(new_name): os_name = gen_string('alpha') entities.OperatingSystem(name=os_name).create() self.archite...
ame, new_name, new_os_names=[os_name]) self.assertIsNotNone(self.architecture.search(new_name)) old_name = new_name # for next iteration
isslayne/enigma2
skin.py
Python
gpl-2.0
35,736
0.035678
from Tools.Profile import profile profile("LOAD:ElementTree") import xml.etree.cElementTree import os profile("LOAD:enigma_skin") from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, addFont, gRGB, eWindowStyleSkinned, getDesktop from Components.config import ConfigSubsection,...
fig from Components.Converter.Converter import Converter from Components.Sources.Source import Source, ObsoleteSource from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_FONTS, SCOPE_CURRENT_SKIN, SCOPE_CONFIG, fileExists, SCOPE_SKIN_IMAGE from Tools.Import import my_import from Tools.LoadPixmap import Loa...
t SystemInfo colorNames = {} # Predefined fonts, typically used in built-in screens and for components like # the movie list and so. fonts = { "Body": ("Regular", 18, 22, 16), "ChoiceList": ("Regular", 20, 24, 18), } parameters = {} def dump(x, i=0): print " " * i + str(x) try: for n in x.childNodes: dump(n...
AustereCuriosity/astropy
astropy/analytic_functions/blackbody.py
Python
bsd-3-clause
2,225
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Functions related to blackbody radiation.""" from __future__ import (absolute_import, division, print_function, unicode_literals) # LOCAL from ..modeling import blackbody as _bb from ..utils.decorators import deprecated __all_...
Parameters ---------- in_x : number, array-like, or `~astropy.units.Quantity` Frequency, wavelength, or wave number. If not a Quantity, it is assumed to be in Angstrom. temperature : number, array-like, or `~astropy.units.Quantity` Blackbody temperature. If not a Quanti...
:math:`erg \\; cm^{-2} s^{-1} \\mathring{A}^{-1} sr^{-1}`. """ return _bb.blackbody_lambda(in_x, temperature)
Learning-from-our-past/Kaira
interface/valuewrapper.py
Python
gpl-2.0
1,114
0.002693
class ValueWrapper(object): xmlEntry = None # Processdata sets this every time before extracting a new Entry. idcounter = 1000 # class variable to generate @staticmethod def reset_id_counter(): ValueWrapper.idcounter = 1000 def __init__(self, val): self._value = val ...
manual entered value for this field in xml, use it instead self._value = ValueWrapper.xmlEntry.attrib[self.id] self.manuallyEdited = True ValueWrapper.idcounter += 1 def manualEdit(self, val): """ :param val: Meant to manually edit the
value from GUI. :return: """ self._value = val self.manuallyEdited = True @property def value(self): return self._value @value.setter def value(self, value): if not self.manuallyEdited: self._value = value
Passw/gn_GFW
build/win/merge_pgc_files.py
Python
gpl-3.0
5,397
0.008894
#!/usr/bin/env python # Copyright 2017 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. """Merge the PGC files generated during the profiling step to the PGD database. This is required to workaround a flakyness in pgomgr.e...
ow.com/a/312464 """ for i in xrange(0, len(items), chunk_size): yield items[i:i + chunk_size] for chunk in _split_in_chunks(pgc_files, options.files_per_iter): files_to_merge = [] for p
gc_file in chunk: files_to_merge.append( os.path.join(options.build_dir, os.path.basename(pgc_file))) ret = merge_pgc_files(pgomgr_path, files_to_merge, pgd_file) # pgomgr.exe sometimes fails to merge too many files at the same time (it # usually complains that a stream is missing, but if yo...
Jannes123/inasafe
safe/common/minimum_needs.py
Python
gpl-3.0
8,353
0
# coding=utf-8 """This module contains the abstract class of the MinimumNeeds. The storage logic is omitted here.""" __author__ = 'Christian Christelis <[email protected]>' __date__ = '05/10/2014' __copyright__ = ('Copyright 2014, Australia Indonesia Facility for ' 'Disaster Reduction') from coll...
0",
"Maximum allowed": "100", "Frequency": "weekly", "Resource name": drinking_water, "Resource description": "For drinking", "Unit": "litre", "Units": "litres", "Unit abbreviation": "l", ...
walchko/pygecko
dev/cpp-simple/subpub.py
Python
mit
1,370
0.00219
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################## # The MIT License (MIT) # Copyright (c) 2018 Kevin Walchko # see LICENSE for full details ############################################## from pygecko.multiprocessing import geckopy from pygecko.multiprocessing import GeckoSim...
s, pi def pub(**kwargs): geckopy.init_node(**kwargs) rate = geckopy.Rate(2) p = geckopy.pubBinderTCP("local", "bob") if (p == None): print("ERROR setting up publisher") return cnt = 0 while not geckopy.is_shutdown(): # msg = "hi" + str(cnt) msg = [pi, cos(pi)...
(pi/2,)] p.publish(msg) print("sent") rate.sleep() cnt += 1 def sub(**kwargs): geckopy.init_node(**kwargs) rate = geckopy.Rate(2) s = geckopy.subConnectTCP("local", "bob") if (s == None): print("ERROR setting up subscriber") return cnt = 0 while...