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
tayebzaidi/PPLL_Spr_16
ejemplos_map_reduce/011-char_count.py
Python
gpl-3.0
317
0.006309
from mrjob.job import MRJob class MRCharCount(MRJob): def mapper(self, _, line): self.increment_counter('group', 'total_chars', len(line)) yield "chars", len(line) def r
educer(self, key, values):
yield key, sum(values) if __name__ == '__main__': MRCharCount.run()
pmeier82/BOTMpy
botmpy/test/test_mad_scaling.py
Python
mit
2,951
0.001355
# -*- coding: utf-8 -*- #_____________________________________________________________________________ # # Copyright (c) 2012 Berlin Institute of Technology # All rights reserved. # # Develop
ed by: Neural Information Processing Group (NI) # School for Electrical Engineering and Computer Science # Berlin Institute of Technology # MAR 5-6, Marchstr. 23, 10587 Berlin, Germany # http://www.ni.tu-berlin.de/ # # Permission is hereby granted, free of charge,...
this software and associated documentation files (the "Software"), to # deal with the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to ...
eeriks/velo.lv
config/settings/local_db.py
Python
gpl-3.0
133
0.007519
f
rom .local import * DATABASES = { 'default': env.db("DATABASE_URL", default="postgres://postgres:post
gres@postgres/velolv"), }
jellis18/libstempo
libstempo/emcee.py
Python
mit
2,045
0.000978
import math import numpy as N # note: we run emcee as if it was multinest, by remapping parameter ranges to [0,1] # if we didn't, the logPL function could just be # # prior = p0.prior(xs) # return -N.inf if not prior else math.log(prior) + ll.loglike(xs) # # and the initialization would be # #...
get coordinates out of range try: pars = p0.remap(xs) except ValueError:
return -N.inf prior = pprior * p0.prior(pars) return -N.inf if not prior else math.log(prior) + ll.loglike(pars) def save(basename, sample, p0, skip): # save last cloud to resume from it N.save(basename + "-resume.npy", sample.chain[:, -1, :]) # thin out the run chain, lnprob = sample.ch...
litedesk/litedesk-webserver-provision
src/tenants/management/commands/update_lastseen.py
Python
apache-2.0
12,643
0.000712
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs) # # 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...
'), private_key, scope=self.OAUTH_SCOPE, sub=google_tenant_asset.get('ADMINISTRATOR') ) # Create an httplib2.Http object and authorize it with our # credentials http = httplib2.Http() http = credentials.authoriz...
) directory_service = build('admin', 'directory_v1', http=http) # Get Google Account lastseen information all_users = [] page_token = None params = {'customer': 'my_customer'} self.stdout.write("") self.stdout.write("Get Google Accoun...
karrtikr/ete
ete3/test/test_api.py
Python
gpl-3.0
463
0.006479
from __future__ import absolute_import import unittest from .datasets
import * from .test_tree import * from .test_interop import * from .test_seqgroup import * from .test_phylotree import * from .test
_ncbiquery import * from .test_arraytable import * from .test_clustertree import * from .test_evol import * #from .test_xml_parsers import * from .test_treeview.test_all_treeview import * def run(): unittest.main() if __name__ == '__main__': run()
jcsp/manila
manila_tempest_tests/tests/api/test_rules.py
Python
apache-2.0
11,108
0
# Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
rotocol.") def test_create_delete_ro_access_rule(self): _create_delete_ro_access_rule(self) class ShareUserRulesForNFSTest(base.BaseSharesTest): protocol = "nfs" @classmethod def resource_setup(cls): super(ShareUserRulesForNFSTest, cls).resource_setup() if (cls.p
rotocol not in CONF.share.enable_protocols or cls.protocol not in CONF.share.enable_user_rules_for_protocols): msg = "USER rule tests for %s protocol are disabled" % cls.protocol raise cls.skipException(msg) cls.share = cls.create_share(cls.protocol) ...
espensirnes/paneltime
build/lib.win-amd64-3.7/paneltime/gui/gui_charts.py
Python
gpl-3.0
4,478
0.071684
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter as tk from tkinter import ttk from multiprocessing import pool import numpy as np import stat_functions as stat from
scipy import stats as scstats from gui import gui_functions as guif import os import functions as fu class process_charts(ttk.Frame): def __init__(self,window,master,main_tabs,tabs): style = ttk.Style() style.configure("TFrame", background='white') ttk.Frame.__init__(self,master,sty
le='new.TFrame') self.window=window self.ll=None self.initialized=False self.subplot=tabs.subplot self.print_subplot=tabs.print_subplot self.img_tmp=tabs.img_tmp def get_images_for_storage(self): charts=[] for i in self.charts: charts.append((i.path,i.name)) return charts def charts_from_s...
pyblish/pyblish-lite
tests/test_control.py
Python
lgpl-3.0
8,342
0
import pyblish.api import pyblish.lib from pyblish_lite import control # Vendor libraries from nose.tools import ( with_setup, assert_equals ) def clean(): pyblish.api.deregister_all_plugins() @with_setup(clean) def test_something(): """Anything runs""" count = {"#": 0} class MyCollector(p...
ctorOrder def process(self, context): context.create_instance("A", publish=False) context.create_instance("B", publish=True) count["#"] += 1
class MyValidator(pyblish.api.InstancePlugin): order = pyblish.api.ValidatorOrder def process(self, instance): count["#"] += 10 for plugin in [MyCollector, MyValidator]: pyblish.api.register_plugin(plugin) ctrl = control.Controller() ctrl.reset() assert count[...
benofben/implier
implierWorkspace/Implier/src/fix/fixFileReader.py
Python
mit
4,271
0.040037
class fixFileReader: def __init__(self, inputFilename, myFixParser): self.myFixParser = myFixParser self.inputFile = open(inputFilename) self.securities={} def __del__(self): self.inputFile.close() def updateOrderBookWithNextLine(self): # Mark the entire order book as not updated for secu...
bed on page 64 of http://www.cmegroup.com/globex/files/SDKFFCore.pdf # I'm just going to ignore these. I think they only have meaning for trade
busting rules, but not certain. pass else: mdPriceLevel = int(self.myFixParser.getField(1023, mdEntry)) index = mdPriceLevel-1 mdUpdateAction = self.myFixParser.getFieldandLookup(279, mdEntry) if mdUpdateAction=='NEW': self.securities[securityDesc][mdEntryType][...
etkirsch/legends-of-erukar
erukar/content/modifiers/material/base/MagicOre.py
Python
agpl-3.0
76
0.013158
from
.MaterialModifier import * class MagicOre(MaterialModifier):
pass
Storj/storjnode
examples/network/multinode.py
Python
mit
1,124
0
#!/usr/bin/env python import time import signal import storjnode from crochet import setup, TimeoutError # start twisted via crochet and remove twisted handler setup() signal.signal(signal.SIGINT, signal.default_int_handler) # create alice node (with bitcoin wif as node key) alice_key = "Kyh4a6zF1TkBZW6gyzwe7XRVtJ18Y...
y) bob_key = ("xprv9s21ZrQH143K3uzRG1qUPdYhVZG1TAxQ9bLTWZuFf1
FHR5hiWuRf" "o2L2ZNoUX9BW17guAbMXqHjMJXBFvuTBD2WWvRT3zNbtVJ1S7yxUvWd") bob_node = storjnode.network.Node(bob_key) try: print("Giving nodes some time to find peers.") time.sleep(storjnode.network.WALK_TIMEOUT) # use nodes alice_node["examplekey"] = "examplevalue" # alice inserts value s...
knipknap/SpiffWorkflow
doc/tutorial/deserialize.py
Python
lgpl-3.0
261
0
from SpiffWorkflow.specs import WorkflowSpec from SpiffWorkflow.serializer.json import JSONSerializer serializer = JSONSerializer() with open('workflow-spec.json') as fp: workflow_json = fp.read() spec = WorkflowSpe
c.deserialize(serializer, wo
rkflow_json)
libyal/winreg-kb
scripts/catalog.py
Python
apache-2.0
2,974
0.009079
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to extract a catalog of Windows Registry keys and values.""" import argparse import logging import sys from dfwinreg import creg as dfwinreg_creg from dfwinreg import regf as dfwinreg_regf from dfwinreg import registry as dfwinreg_registry from winregrc import ...
ile.Open(file_object) except IOError: registry_file = None if not registry_file: print('Unable to open Windows Registry file.') return False # Using dfWinReg to determine Windows native key paths if available. registry = dfwinreg_registry.WinRegistry() key_path_prefix = regi...
t_key = registry_file.GetRootKey() output_writer_object = StdoutWriter() if not output_writer_object.Open(): print('Unable to open output writer.') print('') return False try: has_results = False if root_key: collector_object = catalog.CatalogCollector() has_...
kangkot/elephantdb
elephantdb-thrift/src/py/genpy/keyval/ttypes.py
Python
bsd-3-clause
432
0.011574
# # Autogenerated by Thrift Compiler (0.9.1) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py:utf8strings # from thrift.Thrift import TTyp
e, TMessageType, TException, TApplicationException import elephantdb.ttypes from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol t
ry: from thrift.protocol import fastbinary except: fastbinary = None
moremorefor/Logpot
logpot/admin/setting.py
Python
mit
2,802
0.008922
#-*- coding: utf-8 -*- from flask import current_app, flash, url_for, request from flask_admin import expose, BaseView from logpot.admin.base import AuthenticateView, flash_errors from logpot.admin.forms import SettingForm from logpot.utils import ImageUtil, getDirectoryPath, loadSiteConfig, saveSiteConfig import os...
e class SettingView(AuthenticateView, BaseView): def savePr
ofileImage(self, filestorage): buffer = filestorage.stream buffer.seek(0) image = Image.open(buffer) image = ImageUtil.crop_image(image, 64) current_app.logger.info(image) dirpath = getDirectoryPath(current_app, '_settings') filepath = os.path.join(dirpath, "profi...
levanhien8/pelican
pelican/utils.py
Python
agpl-3.0
23,526
0.000765
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import six import codecs import errno import fnmatch import locale import logging import os import pytz import re import shutil import sys import traceback import pickle import datetime from collections import Hashable from contextlib imp...
second=0, microsecond=0) try: return dateutil.parser.parse(string, default=default) except (TypeError, ValueError): raise ValueError('{0!r} is not a valid date'.format(string)) @contextmanager def pelican_open(filename, mode='rb', strip_crs=(sys.platform == 'win32')): """Open a file an...
if content[0] == codecs.BOM_UTF8.decode('utf8'): content = content[1:] if strip_crs: content = content.replace('\r\n', '\n') yield content def slugify(value, substitutions=()): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphen...
pgodel/rdiff-backup
rdiff_backup/rpath.py
Python
gpl-2.0
50,335
0.032522
# Copyright 2002, 2003, 2004 Ben Escoto # # This file is part of rdiff-backup. # # rdiff-backup is free software; you can redistribute it and/or modify # 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 ver...
that all the rps exist, raise error if not""" for rp in rps: if not rp.lstat(): raise RPathException("File %s does not exist" % rp.get_indexpath()) def move(rpin, rpout): """Move rpin to rpout, renaming if possible""" try: rename(rpin, rpout) except os.error: copy(rpin, rpout) rpin.delete() def copy(rpin...
""" log.Log("Regular copying %s to %s" % (rpin.index, rpout.path), 6) if not rpin.lstat(): if rpout.lstat(): rpout.delete() return if rpout.lstat(): if rpin.isreg() or not cmp(rpin, rpout): rpout.delete() # easier to write than compare else: return if rpin.isreg(): return copy_reg_file(rpin, rpout, c...
HaraldWeber/client
src/featuredmods/__init__.py
Python
gpl-3.0
1,073
0.008388
#------------------------------------------------------------------------------- # Copyright (c) 2012 Gael Honorez. # All rights reserved. This program and the accompanying materials # are made available under the terms of the GNU Public License v3.0 # which accompanies this distribution, and is available at # http://w...
rogram 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 that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ...
pyhmsa/pyhmsa-gui
pyhmsa_gui/util/test_registry.py
Python
mit
1,342
0.002235
#!/usr/bin/env python """ """ # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pyhmsa_gui.util.testcase import TestCaseQApp
, QTest from pyhmsa_gui.util.registry import \ (iter_entry_points, iter_condition_widget_classes, iter_condition_widgets, iter_datum_widget_classes, iter_datum_widgets, iter_importer_classes, iter_importers, iter_exporter_classes, iter_exporters, iter_preferences_widget_classes) # Globals ...
lf) def testiter_entry_points(self): pass def testiter_condition_widget_classes(self): pass def testiter_condition_widgets(self): pass def testiter_datum_widget_classes(self): pass def testiter_datum_widgets(self): pass def testiter_importer_classes(...
Salmista-94/Ninja_3.0_PyQt5
ninja_ide/gui/main_panel/helpers/split_orientation.py
Python
gpl-3.0
1,346
0.002229
# -*- coding: utf-8 -*- from PyQt5.QtWidgets import QDialog from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtCore import Qt #from PyQt5.QtCore import pyqtSignal from PyQt5.QtQuickWidgets import QQuickWidget from ninja_ide.gui.ide import IDE from ninja_ide.tools import ui_tools class SplitOrientation(QDialog): ...
get.SizeRootObjectToView) view.setSource(ui_tools.get_qml_resource("SplitOrientation.qml")) self._root = view.rootObject() vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) vbox.addWidget(view) self._root.selected.connect(self._split...
main_container.show_split(self._operations[orientation]) self.hide()
RedXBeard/kivy-1010
main.py
Python
gpl-2.0
24,667
0.000486
from datetime import datetime, timedelta from random import choice from kivy.animation import Animation from kivy.app import App from kivy.clock import Clock from kivy.core.window import Window from kivy.lang import Builder from kivy.metrics import dp, sp from kivy.properties import NumericProperty from kivy.uix.gridl...
return_position=True) if occupied: raise IndexError place = True or place all_positio
ns.append(positions) except: pass return place, all_positions class Shape(GridLayout): """ Generate shapes from given already set list with random colour. """ def __init__( self, rows=None, cols=None, array=None, color=None, color_set=COLOR): su...
xyuanmu/you-get
setup.py
Python
mit
1,277
0.032106
#!/usr/bin/env python3 PROJ_NAME = 'you-get' PACKAGE_NAME = 'you_get' PROJ_METADATA = '%s.json' % PROJ_NAME import os, json, imp here = os.path.abspath(os.path.dirname(__file__)) proj_info = json.loads(open(os.path.join(here, PROJ_METADATA), encoding='utf-8').read()) try: README = open(os.path.join(here, 'README...
rsion', os.path.join(here, 'src/%s/version.py' % PACKAGE_NAME)).__version__ from setuptools import setup, find_packages setup( name = proj_info['name'], version = VERSION, author = proj_info['author'], author_email = proj_info['author_email'], url = proj_info['url'], license = proj_info['licen...
proj_info['description'], keywords = proj_info['keywords'], long_description = README, packages = find_packages('src'), package_dir = {'' : 'src'}, test_suite = 'tests', platforms = 'any', zip_safe = True, include_package_data = True, classifiers = proj_info['classifiers'], ...
delcypher/klee-runner
tools/result-info-native-replay-summary.py
Python
mit
3,311
0.007853
#!/usr/bin/env python # Copyright (c) 2016, Daniel Liew # This file is covered by the license in LICENSE-SVCB.txt # vim: set sw=4 ts=4 softtabstop=4 expandtab: """ Read a result info describing a set of KLEE test case replays. """ from load_klee_runner import add_KleeRunner_to_module_search_path from load_klee_analysis...
errorTypeToErrorListMap = dict() multipeOutcomeList = [] for result_index, r in enumerate(resultInfos): _logger.info('Processing {}/{}'.format(result_index + 1, len(resultInfos))) raw_result = r.GetInternalRepr() program_path = r.RawInvocationInfo['program'] outcome = nativeanal...
= errorTypeToErrorListMap[type(outcome)] except KeyError: error_list = [] errorTypeToErrorListMap[type(outcome)] = error_list error_list.append(outcome) # Print report print('#'*70) print("# of test cases with multiple outcomes: {}".format(len(multipeOutcomeList))) ...
fedspendingtransparency/data-act-broker-backend
tests/integration/sqs_work_dispatcher_tests.py
Python
cc0-1.0
78,313
0.005172
import inspect import boto3 import logging import multiprocessing as mp import os import signal import psutil as ps from random import randint from botocore.config import Config from botocore.exceptions import EndpointConnectionError, ClientError, NoCredentialsError, NoRegionError from dataactcore.aws.sqsHandler impo...
# The "work" we're doing is just putting something else on the queue queue_in_use = sqs_queue() queue_in_use.send_message(MessageBody=9999) dispatcher.dispatch(do_some_work, message_transformer=lambda x: (x.body, x.body * 2)) dispatcher._worker_process.join(5) # w
ait at most 5 sec for the work to complete # Make sure the "work" was done messages = queue.receive_messages(WaitTimeSeconds=1, MaxNumberOfMessages=10) self.assertEqual(1, len(messages)) self.assertEqual(9999, messages[0].body) # Worker process should have a successful (0) exit...
sunj1/my_pyforms
pyforms/gui/Controls/ControlEventsGraph/Track.py
Python
mit
2,110
0.000474
from PyQt4 import QtGui import bisect class Track(object): DEFAULT_COLOR = QtGui.QColor(100, 100, 255) def __init__(self, parent): self._title = '' self._color = self.DEFAULT_COLOR self._parent = parent self._periods = [] # Functions needed for the bisect insertion #####...
self): return self._periods @property def color(self): return self._color @color.setter def color(self, value): self._color = value @property def title(self): return self._titl
e @title.setter def title(self, value): self._title = value @property def properties(self): return ['T', self.title, self.color.name()] @properties.setter def properties(self, value): self.title = value[1] self.color = QtGui.QColor(value[2])
n6151h/pyconau2016
alembic/versions/3e7de5c31b2b_add_jsonic_proposal_event_targets.py
Python
gpl-2.0
1,366
0.016105
"""add JSONic proposal event targets Revision ID: 3e7de5c31b2b Revises: 4cb574d6501a Create Date: 2016-03-21 07:13:24.424092 """ # revision identifiers, used by Alembic. revision = '3e7de5c31b2b' down_revision = '4cb574d6501a' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects.postgresql impor...
unique=True, nullable=False)) # Populate it. op.bulk_insert(event_targets, data) # Add JSON column to proposal. op.add_column('proposal', sa.Column('event_targets', sa.dialects.postgr...
llable=True)) def downgrade(): op.drop_column('proposal', 'event_targets') op.drop_table('proposal_event_target')
pepsin92/cookbook
manage.py
Python
mit
155
0.006452
from flask
_script import Manager from app import app # migrate = Migrate(app, db) manager = Manager(app) if __name__ == '__main__': manager
.run()
solominh/python-stardict
stardict.py
Python
gpl-3.0
13,634
0.0011
#!/usr/bin/python # -*- coding: utf-8 -*- import struct import gzip import os from dictutils import find_dictionary_filepaths class IfoFileException(Exception): """Exception while parsing the .ifo file. Now version error in .ifo file is the only case raising this exception. """ def __init__(self, des...
May raise IndexError if number is out of range. Arguments: - `number`: the origin index of the entry in .idx file Return: A tuple in form of (word_str, word_data_offset, word_data_size) """ if number >= len(self._index_idx): raise IndexError("Index o...
number, len(self._index_idx))) return self._index_idx[number] def get_index_by_word(self, word_str): """Get index infomation of a specified word entry. Arguments: - `word_str`: name of word entry. Return: Index infomation corresponding to the specified wo...
adamrp/qiime
qiime/workflow/upstream.py
Python
gpl-2.0
19,937
0.000301
#!/usr/bin/env python # File created on 20 Feb 2013 from __future__ import division __author__ = "Greg Caporaso" __copyright__ = "Copyright 2011, The QIIME project" __credits__ = ["Greg Caporaso", "Kyle Bittinger", "Justin Kuczynski", "Jai Ram Rideout"] __license__ = "GPL" __version__ = "1.9.1-dev" __ma...
xcept KeyError: pass
if otu_picking_method == 'uclust_ref': try: suppress_new_clusters = d['suppress_new_clusters'] del d['suppress_new_clusters'] cluster_failures = False except KeyError: cluster_failures = True failure_otu_picking...
coco19/salud-api
app/mod_profiles/models/__init__.py
Python
gpl-2.0
232
0
from .Gender import Gender from .Profile import Profile from .Measurement import Measurement from .MeasurementSour
ce import MeasurementSource from .MeasurementTy
pe import MeasurementType from .MeasurementUnit import MeasurementUnit
lbc001/zhihu-oauth
zhihu_oauth/zhcls/search.py
Python
mit
6,167
0
# coding=utf-8 from copy import deepcopy from ..exception import UnimplementedException from .utils import ConstValue, build_zhihu_obj_from_dict, SimpleEnum __all__ = ['SearchResult', 'SearchResultSection', 'SearchType'] _search_type_t_map = { 'GENERAL': 'general', 'PEOPLE': 'people', 'TOPIC': 'topic',...
self.type == "people", self. has_more == True 那么表示::: client.search('something', SearchType.PEOPLE) 能获取到此 Section 的更多结果。 :rtype: bool """ return self._data[self._SECTION_HAS_MORE_KEY] def raw_data(self): """ 同 :any:`SearchResult.raw_data` ...
__iter__(self): self._index = 0 return self def __len__(self): return self._len def __next__(self): try: obj = self[self._index] except IndexError: self._index = 0 raise StopIteration self._index += 1 return obj ...
alikins/subscription-manager
src/subscription_manager/identitycertlib.py
Python
gpl-2.0
3,028
0
# # Copyright (c) 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License
, # version 2 (GPLv2). There is NO WARRANTY
for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2...
cfpb/django-widgeter
widgeter/__init__.py
Python
cc0-1.0
214
0.009346
from django.conf import settings def autodiscover
(): """Find all th
e widgets within the installed apps""" for app in settings.INSTALLED_APPS: __import__(app, {}, {}, ['widgets']) autodiscover()
facelessuser/TabsExtra
lib/file_strip/json.py
Python
mit
2,064
0.001938
""" File Strip. Licensed under MIT Copyright (c) 2012 - 2016 Isaac Muse <isaacmuse@gmail.com> """ import re from .comments import Comments JSON_PATTERN = re.compile( r'''(?x) ( (?P<square_comma> , # trailing comma (?P<square_ws>[\s\r\n]*) ...
preserve_lines=False): """Strip dangling commas.""" regex = JSON_PATTERN def remove_comma(g, preserve_lines): """Remove comma.""" if prese
rve_lines: # ,] -> ] else ,} -> } if g["square_comma"] is not None: return g["square_ws"] + g["square_bracket"] else: return g["curly_ws"] + g["curly_bracket"] else: # ,] -> ] else ,} -> } return g["square_bracket"] if g...
prevwong/PSP0201
modules/ui.py
Python
mit
38
0
import r
anking ranking.sho
w_ranking()
ahmedaljazzar/edx-platform
common/djangoapps/student/roles.py
Python
agpl-3.0
13,043
0.001993
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ import logging from abc import ABCMeta, abstractmethod from collections import defaultdict from django.contrib.auth.models import User from opaque_keys.ed...
" if check_user_activation and not (user.is_authenticated and user.is_active): return False # pylint: disable=protected-access if not hasattr(user, '_roles'): # Cache a list of tuples identifying the particular roles that a user has # Stored as tuples,
rather than django models, to make it cheaper to construct objects for comparison user._roles = RoleCache(user) return user._roles.has_role(self._role_name, self.course_key, self.org) def add_users(self, *users): """ Add the supplied django users to this role. """ ...
ruchikd/Algorithms
Python/FindAnagrams/anagrams.py
Python
gpl-3.0
521
0.040307
class Word: def __init__(self,
data, index): self.data = data self.index = index def printAnagrams(arr): dupArray = [] size = len(arr) for i in range(size): dupArray.append(Word(arr[i], i)) for i in range(size): dupArray[i].data = ''.join(sorted(dupArray[i].data)) dupArray = sorted(dupArray, key=lambda x: x.data) for i in range(s...
printAnagrams(arr) if __name__== '__main__': main()
agry/NGECore2
scripts/mobiles/talus/aakuan_guardian.py
Python
lgpl-3.0
1,655
0.022961
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate...
fficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(True) mobileTemplate.setScale(1) mobileTemplate.setSocialGroup("aakuans") mobileTemplate.setAssistRange(0) mobileTemplate.setStalker(True) mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Opti...
lnielsen/invenio
invenio/modules/pidstore/admin.py
Python
gpl-2.0
2,270
0.005727
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any ...
n_choices = { 'status': { 'N': 'NEW', 'R': 'REGISTERED', 'K': 'RESERVED', 'D': 'INACTIVE', } } page_size = 100 def __init__(self, model, session, **kwargs): super(PersistentIdentifierAdmin, self).__init__( model, session, *...
edit = False _can_delete = False column_list = ('id_pid', 'action', 'message') def __init__(self, model, session, **kwargs): super(PidLogAdmin, self).__init__(model, session, **kwargs) def register_admin(app, admin): """ Called on app initialization to register administration interface. ...
fr4c74l/glome
scripts/mesh_export.py
Python
gpl-3.0
8,298
0.013859
#!BPY # -*- coding: utf-8 -*- # """ Name: 'Glome Mesh Exporter' Blender: 259 Group: 'Export' Tooltip: 'Export meshes to Binary file format for Glome Game Renega Desruga' """ # Copyright (C) 2011 Fractal Corp. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
len = mat.col_size for i in range(0, row_len): for j in range(0, col_len): # t[col][row] because this is how OpenGL represents matrices bfile.write(struct.pack('<f', mat[j][i])) ########### # Objects # ########### class Sp
aceShip: def __init__(self, objs, listAllScenes): self.data = objs.get(ssname).to_mesh(listAllScenes.get('mesh'),True,'PREVIEW') self.ssMesh = Mesh(self.data) #TODO: work for n guns and engines self.lguns = listAllScenes.get('gun').objects.values() self.ssGuns = Guns(objs.get(ssname),self.lguns) ...
tejesh95/Zubio.in
zubio/allauth/socialaccount/providers/twitter/views.py
Python
mit
1,493
0
import json from allauth.socialaccount.providers.oauth.client import OAuth from allauth.socialaccount.providers.oauth.views import (OAuthAdapter, OAuthLoginView, OAuthCallbackView) from .provider import T...
erProvider.id request_token_url = 'https://api.twitter.com/oauth/request_token' access_token_url = 'https://api.twitter.com/oauth/access_token' # Issue #42 -- this one authenticates over and over again... # authorize_url = 'https://api.twitter.com/oauth/authorize' authorize_url = 'https://api.twitte...
gin(self, request, app, token, response): client = TwitterAPI(request, app.client_id, app.secret, self.request_token_url) extra_data = client.get_user_info() return self.get_provider().sociallogin_from_response(request, ...
kubeflow/pipelines
samples/core/resource_ops/resource_ops.py
Python
apache-2.0
1,733
0.000577
# Copyright 2019 The Kubeflow 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...
ense for the specific language governing pe
rmissions and # limitations under the License. """ This example demonstrates how to use ResourceOp to specify the value of env var. """ import json from kfp.deprecated import dsl, compiler _CONTAINER_MANIFEST = """ { "apiVersion": "batch/v1", "kind": "Job", "metadata": { "generateName": "resour...
aronsky/home-assistant
homeassistant/components/doorbird/const.py
Python
apache-2.0
647
0
"""The DoorBird integration constants.""" DOMAIN = "doorbird" PLATFORMS = ["switch", "camera"] DOOR_STATION = "door_station" DOOR_STATION_INFO = "door_station_info" DOOR_STATION_EVENT_ENTITY_IDS = "door_station_event_entity_ids" CONF_EVENTS = "events" MANUFACTURER = "Bird Home Automation Group" DOORBIRD_OUI = "1CCAE...
DOORBIRD_INFO_KEY_BUILD_NUMBER = "BUILD_NUMBER" DOORBIRD_INFO_KEY_DEVICE_TYPE = "DEVICE-TYPE" DOORBIRD_INFO_KEY_RELAYS = "RELAYS" DOORBIRD_INFO_KEY_PRIMARY_MAC_ADDR = "PRIMARY_MAC_ADDR" DOORBIRD_INFO_KEY_WIFI_MAC_ADDR = "WIFI_MAC_ADDR" UNDO_UPDATE_LISTENER = "undo_
update_listener"
mthomure/glimpse-project
glimpse/models/base/layer_test.py
Python
mit
741
0.014845
import unittest from .layer import * class L(Layer): L1 = LayerSpec("l1", "layer-1") L2 = LayerSpec("l2", "layer-2", [L1]) class TestLayer(unittest.TestCase): def testFromId(self): self.assertEqual(L.FromId(L.L1.id_
), L.L1) self.assertEqual(L.FromId(L.L2.id_), L.L2) def testFromName(self): self.assertEqual(L.FromName(L.L1.name), L.L1) self.assertEqual(L.FromName(L.L2.name), L.L2) def testAllLayer
s(self): self.assertEqual(set(L.AllLayers()), set((L.L2, L.L1))) def testIsSublayer(self): self.assertTrue(L.IsSublayer(L.L1, L.L2)) self.assertFalse(Layer.IsSublayer(L.L2, L.L1)) def testTopLayer(self): self.assertEqual(L.TopLayer(), L.L2) if __name__ == '__main__': unittest.main()
yunbademo/yunba-smartoffice
tests/get_status.py
Python
mit
1,501
0.00533
#!/usr/bin/env python import time import sys import logging import argparse from socketIO_client import SocketIO from messenger import Messenger logger = logging.getLogger('get_status') logging.basicConfig(level=logging.DEBUG) APPKEY = '5697113d4407a3cd028abead' #TOPIC = 'yunba_smart_plug' #ALIAS = 'plc_0' class St...
) self.socketIO.emit('set_alias', {'alias': 'status'}) def on_set_alias(self, args): self.__logger.debug('on_set_alias: %s', args) self.publish_to_alias(self.alias, '{"cmd": "'+ self.cmd + '", "devid": "' + self.alias + '"}') if __name__ == '__main__': parser = argparse.ArgumentParser...
parser.add_argument('cmd', type=str, help='cmd') args = parser.parse_args() s = Status(args.topic, args.alias, args.cmd) while True: s.loop() time.sleep(0.1)
ssorgatem/qiime
qiime/truncate_fasta_qual_files.py
Python
gpl-2.0
6,323
0.000158
#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "William....
qual_scores, base_pos)
# Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, se...
bluedynamics/yafowil.widget.autosuggest
src/yafowil/widget/autosuggest/example.py
Python
bsd-3-clause
501
0.002004
# -*- coding: utf-8 -*- from yafowil.base import factory def get_example(): part = factory(u'fieldset', name='yafowilwidgetautosuggest') part['text'] = factory('field:label:error:autosuggest', props={ 'label': 'Enter some text', 'source': sorted((u
'Weißburgunder', u'Welschriesling', u'Sauvingnon Blanc', u'Sämling', u'Scheurebe',
u'Traminer', u'Morrilon', u'Muskateller'))}) return [{'widget': part, 'doc': 'TODO'}]
yeming233/rally
rally/common/db/sqlalchemy/migrations/versions/a6f364988fc2_change_tag_type_enum.py
Python
apache-2.0
1,864
0.001609
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
missions and limitations # under the License. """Chan
ge tag type enum Revision ID: a6f364988fc2 Revises: 37fdbb373e8d Create Date: 2017-01-17 18:47:10.700459 """ # revision identifiers, used by Alembic. revision = "a6f364988fc2" down_revision = "37fdbb373e8d" branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from rally import exc...
davissandefur/Irish-Dictionary-with-GUI
Irish-Dictionary-GUI/qt_gui.py
Python
gpl-3.0
12,607
0.002064
# Irish Dictionary GUI app # saved as qt_gui.py # Last edit by Davis Sandefur 15.07.2015 import sys import os from PyQt5 import QtCore, QtWidgets, QtGui, QtMultimedia from PyQt5 import QtNetwork from irish_dictionary import irish_dictionary, gaeilge_gaeilge from audio_grabber import entry_search, related_matches cla...
_version irish_version = IrishVersion() irish_version.show() english_version.layout().removeWidget(english_version.text_entry) irish_version.layout().addWidget(irish_version.text_entry, 3, 0, 24, 8) irish_version.resize(200, 400) irish_version.center() class EnglishButt...
""" This class creates the English version buttons""" def __init__(self, parent=None): super().__init__(parent) # Define buttons self.english_button = QtWidgets.QPushButton("English") self.irish_button = QtWidgets.QPushButton("Irish") self.audio = False # Initial audio s...
lxwvictor/flask-ask
tests/test_integration.py
Python
apache-2.0
2,295
0
import unittest import json from flask_ask import Ask, audio from flask import Flask play_request = { "version": "1.0", "session": { "new": True, "sessionId": "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000", "application": { "applicationId": "fake-application-id" }, "attribut...
f.ass
ertEqual('AudioPlayer.Play', directive['type']) stream = directive['audioItem']['stream'] self.assertIsNotNone(stream['token']) self.assertEqual(self.stream_url, stream['url']) self.assertEqual(0, stream['offsetInMilliseconds']) if __name__ == '__main__': unittest.main()
ryanpepper/oommf-python
joommf/energies/exchange.py
Python
bsd-2-clause
413
0.002421
from joommf.energies.baseenergy import energy import textwrap class Exchange(energy): def __init__(self, A): energy.__init__(self, "Exchange") self.A = A def get_mif(self): exchange_mif = textwrap.dedent("""\
Specify Oxs_UniformExchange {{ A {:.2e}
}}\n\n""").format(self.A) return exchange_mif
mogproject/artifact-cli
tests/artifactcli/test_artifactcli.py
Python
apache-2.0
177
0
import
unittest import artifactcli.artifactcli class TestArtifactCli(unittest.TestCase): def test_usage(self):
self.assertEqual(artifactcli.artifactcli.main(), 1)
sadanandb/pmt
src/tactic/ui/chart/chart2_wdg.py
Python
epl-1.0
27,920
0.00394
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
d", -5) def add_style(my, name, value): my.top.add_style(name, value) def add_color(my, name, value): my.top.add_color(name, value) def add_gradient(my, name, value, offset=0, gradient=-10): my.top.add_gradient(name, value, o
ffset, gradient) def get_display(my): top = my.top top.add_style("position: relative") labels = my.kwargs.get("labels") if not labels: labels = [] label_values = my.kwargs.get("label_values") width = my.kwargs.get("width") height = my.kwargs.g...
Alignak-monitoring-contrib/alignak-checks-glances
setup.py
Python
agpl-3.0
10,827
0.003602
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import re del os.link from importlib import import_module import fileinput import getpass from string import Template try: import distutils.core from distutils.command.install_data import install_data as _install_data from setuptools impo...
g['ALIGNAKRUN'] = line.split('=')[1] elif line.startswith('LOG'): alignak_cfg['ALIGNAKLOG'] = line.split('=')[1] elif line.startswith('LIB'): alignak_cfg['ALIGNAKLIB'] = line.split('=')[1] elif line.startswith('ALIGNAKUSER'): alignak_cf...
t('=')[1] etc_file.close() # Check Alignak configuration directory if 'ALIGNAKETC' in alignak_cfg: if not os.path.exists(alignak_cfg['ALIGNAKETC']): print "Alignak configuration directory (%s) not found: does not seem to be installed on this host!" % alignak_cfg['ALIGNAKETC'] ...
tejasckulkarni/hydrology
checkdam/checkdam.py
Python
gpl-3.0
22,747
0.003473
__author__ = 'kiruba' import numpy as np # import matplotlib.pyplot as plt import pandas as pd import itertools from fractions import Fraction from bisect import bisect_left import math from datetime import datetime from datetime import timedelta import meteolib as met # import evaplib import scipy as sp date_format =...
file = elevation_data[
"Y_%s" % float(l1)] order = l1 dy = int(l2 - l1) for stage in dz: water_area = 0 for z1, z2 in pairwise(profile): delev = (z2 - z1) / 10 elev = z1 for b in range(1, 11, 1): elev += delev ...
stefano-maggiolo/boundary
test/test.py
Python
gpl-3.0
22,312
0.043654
#!/usr/bin/env python from sys import argv, exit import shelve from subprocess import Popen, PIPE import os, signal, time from test_graph import plot # Database of known cases correct = {} correct[(0,0)] = ((), ()) correct[(0,1)] = ((), ()) correct[(0,2)] = ((), ...
eturn "%5d.%01d" % (s, ds) def strMemRel(s, tot): if tot < 100 or abs((100.0*s) / tot) < 5: if s > 0: return strMem(s) else: return strMem(-s) if s > 0: return "\033[31m" + strMem(s) + "\033[39m" else: return "\033[32m" + strMem(-s) + "\033[39m" # Testing def getFlags(name): process =...
close_fds=True) e = process.stderr flags = e.readline()[:-1] os.kill(process.pid, signal.SIGTERM) return flags def compute(name, flags, gn, maxTime = 60*5000): print "Computing %d %d... " % gn, current = {} current["flags"] = flags current["name"] = name output ...
googleapis/python-dataplex
samples/generated_samples/dataplex_v1_generated_dataplex_service_update_lake_async.py
Python
apache-2.0
1,513
0.000661
# -*- coding: utf-8 -*- # Copyright 2022 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, software # distributed under the License ...
ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for UpdateLake # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to...
ufukdogan92/is-teklif-sistemi
odeme/migrations/0001_initial.py
Python
gpl-3.0
1,244
0.003223
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-22 16:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('teklif', '0003_auto_20170522_1559'), ...
_length=3)), ('tamamlanma_durumu', models.BooleanField(default=False)), ('teklif', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='odeme_teklifi', to='teklif.Teklif')), ], options={ 'ver
bose_name_plural': 'Ödemeler', 'verbose_name': 'Ödeme', }, ), ]
rhots/automation
heroes-sidebar-master/match.py
Python
isc
2,849
0.027729
import requests import sys import urllib import json from env import env from urlShort import urlShort from datetime import datetime, timedelta from email_me import email_me class match: def __init__(self): self.env = env() self.urlShort = urlShort() self.matches = {} self.r = '' self.matchLimit = 5 s...
if self.body == '': self.body = 'No Upcoming Matches' return self.body def enterDatabase(self): #make an entry in the database if match is live and not in database pass def formatTime(self, datetime): days = datetime.days hours = int(datetime.seconds / 60) / 60 minutes = int((datetime.second...
'' if days != 0: formatted = formatted + str(days) + 'd ' if hours != 0: formatted = formatted + str(hours) + 'h ' minutes = self.roundToFive(minutes) formatted = formatted + str(minutes) + 'm' return formatted def roundToFive(self, x, base=5): return int(base * round(float(x)/base))
ewanbarr/anansi
anansi/tcc/tcc_utils.py
Python
apache-2.0
4,234
0.017478
from lxml import etree from anansi.xml import XMLMessage,gen_element,XMLError class TCCError(Exception): def __init__(self,msg): super(TCCError,self).__init__(msg) class TCCMessage(XMLMessage): def __init__(self,user,comment=""): super(TCCMessage,self).__init__(gen_element('tcc_request')) ...
elf.passed = False self.message = self.root.find('error').text raise TCCError(self.message) class TCCControls(object): def __init__(self,user="anansi"): conf =
config.tcc_server self.ip = conf.ip self.port = conf.port self.user = user def _send(self,msg): client = TCPClient(self.ip,self.port,timeout=10.0) client.send(msg) return TCCResponseHandler(client.receive()) def track(self,x,y,system,units,**kwargs): m...
SeanEstey/Bravo
app/routing/sheet.py
Python
gpl-2.0
6,147
0.009273
'''app.routing.sheet''' import re, time from flask import g from .. import get_keys from app.lib import gdrive from app.lib.gsheets_cls import SS from app.main.parser import has_postal from logging import getLogger log = getLogger(__name__) #-----------------------------------------------------------------------------...
if notes['driver notes'].find('***') > -1: summary = summary.replace("***", "")
if notes.get('status') == 'Dropoff': blue.append([idx+1+1, 4]) summary += 'Name: ' + notes['name'] + '\n' if notes.get('neighborhood'): summary += 'Neighborhood: ' + notes['neighborhood'] + '\n' #summary += 'Block: ' + notes['block'] ...
bashrc/zeronet-debian
src/src/Test/TestCryptBitcoin.py
Python
gpl-2.0
2,344
0.000853
from Crypt import CryptBitcoin cl
ass TestCryptBitcoin: def testSignOld(self): privatekey = "23DKQpDz7bXM7w5KN5Wnmz7bwRNqNHcdQjb2WwrdB1QtTf5gM3pFdf" privatekey_bad = "23DKQpDz7bXM7w5KN5Wnmz6bwRNqNHcdQjb2WwrdB1QtTf5gM3pFdf" # Get address by privatekey address = CryptBitcoin.privatekeyToAddress(privatekey) ass...
sjscg4hYPewUL2onma5pgQmWPMs3ez" # Text signing sign = CryptBitcoin.signOld("hello", privatekey) assert CryptBitcoin.verify("hello", address, sign) # Original text assert not CryptBitcoin.verify("not hello", address, sign) # Different text # Signed by bad privatekey si...
SV-Seeker/pi-rov
rov/main.py
Python
mit
2,172
0.00046
import signal as signals import messages from config import config from curio import SignalQueue, TaskGroup, run, spawn, tcp_server # Queue, CancelledError from feeds import ClientStreamFeed from logs import setup_logging from tasks import ControlTask, HeartbeatTask, StatusTask logger = setup_logging(__name__) # T...
.append(task) add_task(HeartbeatTask) add_task(StatusTask) add_task(ControlTask) async def server(host, port): # Server task groups async with TaskGroup() as group: await group.sp
awn(feed.dispatcher) await group.spawn(out_feed.dispatcher) await group.spawn(tcp_server, host, port, connection_handler) for rov_task in rov_tasks: await group.spawn(rov_task, out_feed) async def main(host, port): async with SignalQueue(signals.SIGHUP, signals.SIGTERM) as clo...
onecloud/neutron
neutron/plugins/mlnx/rpc_callbacks.py
Python
apache-2.0
4,874
0.000205
# Copyright 2013 Mellanox Technologies, Ltd # # 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 t...
port['device'] = device else: port = db.get_port_from_device_mac(device) if port: port['device'] = device return port def get_device_details(self, rpc_cont
ext, **kwargs): """Agent requests device details.""" agent_id = kwargs.get('agent_id') device = kwargs.get('device') LOG.debug(_("Device %(device)s details requested from %(agent_id)s"), {'device': device, 'agent_id': agent_id}) port = self.get_port_from_device(...
goha2/labs_2016
past/sem 3/13.py
Python
gpl-3.0
1,074
0.009311
__author__ = 'student' import turtle import math turtle.shape('turtle') def duga(r): for i in range (20): turtle.forward(r) turtle.left(9) def krug(r): for i in range(72): turtle.forward(r) turtle.left(5) turtle.penup() turtle.forward(200) #Head turtle.left(90) t...
pencolor('black') turtle.fillcolor('blue') turtle.begin_fill() krug(2) turtle.end_fill() turtle.penup() turtle.goto(-10, 50) #Nose turtle.left(180) turtle.pendown() turtle.pencolor('black') turtle.width(20) turtle.forward(50) turtle.penup() turtle.goto(-65
, -35) #Mouth turtle.pendown() turtle.pencolor('red') turtle.width(10) duga(10)
sammyshj/nyx
test/panel/graph.py
Python
gpl-3.0
4,813
0.006025
""" Unit tests for nyx.panel.graph. """ import datetime import unittest import stem.control import nyx.curses import nyx.panel.graph import test from test import require_curses from mock import patch EXPECTED_BLANK_GRAPH = """ Download: 0 b 0 b 5s 10 15 """.rstrip() EXPECTE
D_ACCOUNTING = """ Accounting (awake) Time to reset: 01:02 37.7 Kb / 842.0 Kb 16.0 Kb / 74.1 Kb """.strip() EXPECTED_GRAPH = """ Download: 5 Kb * * 2 Kb ** * * **** 0 b ********* 5s 10
15 """.rstrip() class TestGraphPanel(unittest.TestCase): def test_x_axis_labels(self): test_inputs = { 0: {}, 7: {}, 10: {5: '25s'}, 15: {5: '25s', 10: '50'}, 20: {5: '25s', 10: '50', 15: '1m'}, 25: {5: '25s', 10: '50', 15: '1m', 20: '1.6'}, 45: {5: '25s', 10: '50', 1...
birkelbach/python-canbus
canbus/exceptions.py
Python
gpl-2.0
1,265
0.003953
# Copyright (c) 2012 Phil Birkelbach # # This program is fre
e 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 o
ption) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GN...
nigelsmall/httpstream
book/conf.py
Python
apache-2.0
8,191
0.006348
# -*- coding: utf-8 -*- # # HTTPStream documentation build configuration file, created by # sphinx-quickstart on Thu Jun 20 11:07:05 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # ...
directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx ve...
ngs. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # T...
mandeepdhami/stevedore
stevedore/sphinxext.py
Python
apache-2.0
3,790
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...
.name), ext.entry_point.module_name) yield ('\n', ext.entry_point.module_name) doc = _get_docstring(ext.plugin) if doc: yield (doc, ext.entry_point.module_name) else: yield ('.. warning:: No documentation found in %s' % e
xt.entry_point, ext.entry_point.module_name) yield ('\n', ext.entry_point.module_name) class ListPluginsDirective(rst.Directive): """Present a simple list of the plugins in a namespace.""" option_spec = { 'class': directives.class_option, 'detailed': directives.flag...
altur13/osu-Assistant
oppy/curves.py
Python
gpl-3.0
4,911
0.003665
from oppy.vector import * import numpy as np # ported from osu-web """ gets a point on a line p1, p2: the two points that define the line t: how far into the line we are (0.0 would be p1 and 1.0 would be p2) """ def pt_on_line(p1, p2, t): r = min(1.0, max(0.0, t)) l = (p2.subtract(p1)).length() n = l - l...
ts[2]): radians *= -1 return rotate(self.circle.center, self.points[0], radians) class Bezier(Curve): def at(self, t): res = Vector(0.0, 0.0) r = min(1.0, max(0.0, t)) n = len(self.points) - 1 for i in range(0, len(self.points), 1): multiplier = bi...
cale(multiplier)) return res class Catmull(Curve): def at(self, t): r = min(1.0, max(0.0, t)) r *= len(self.points) i = math.floor(r) # TODO: discover if this is true return self.compute_single_point(i, t - i) def compute(self): dst = [] for i in range...
everyevery/programming_study
tools/gen_prime.py
Python
mit
2,129
0.006106
import argparse import sys # Sieve o
f Eratosthenes # Code by David Eppstein, UC Irvine, 28 Feb 2002 # http://
code.activestate.com/recipes/117119/ def gen_primes(): """ Generate an infinite sequence of prime numbers. """ # Maps composites to primes witnessing their compositeness. # This is memory efficient, as the sieve is not "run forward" # indefinitely, but only as long as required by the current # ...
vhavlena/appreal
netbench/pattern_match/tests/test_sym_char_class.py
Python
gpl-2.0
12,368
0.002426
############################################################################### # test_sym_char_class.py: Test module for PATTERN MATCH - symbol char class # class # Copyright (C) 2011 Brno University of Technology, ANT @ FIT # Author(s): Jaroslav Suchodol <xsucho04@stud.fit.vutbr.cz> ######...
. # # $Id$ from netbench.pattern_match.b_symbol import io_mapper from netbench.pattern_match.sym_char import b_Sym_char from netbench.pattern_match.sym_kchar import b_Sym_kchar from netbench.pattern_match.sym_string import b_Sym_string from netbench.pattern_match.sym_char_class import b_Sym_char_class from netbench.p...
t_exception import unittest class test_b_Sym_char_class(unittest.TestCase): """A base test class to represent a char class symbol.""" def test_accept(self): """accept()""" # method accept(text): # Check if len(text) == 0, # then is call exception symbol_string_to_short ...
mlba-team/open-lighting
python/ola/rpc/StreamRpcChannel.py
Python
lgpl-2.1
11,310
0.007339
# This program is free software; you can redistribute it and/or modify # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later ...
lback(response) response = OutstandingResponse(message.id, controller, done, response_pb) self._outstanding_responses[message.id] = response def RequestComplete(self, request, response): """This is called on the server side when a request has completed. Args: request: the OutstandingRequest o...
ailed(): self._SendRequestFailed(request) return message.type = Rpc_pb2.RESPONSE message.id = request.id message.buffer = response.SerializeToString() self._SendMessage(message) del self._outstanding_requests[request.id] def _EncodeHeader(self, size): """Encode a version and size...
edx-solutions/edx-platform
common/djangoapps/util/testing.py
Python
agpl-3.0
5,905
0.000847
""" Utility Mixins for unit tests """ import json import sys import six from django.conf import settings from django.test import TestCase from django.urls import clear_url_caches, resolve from mock import patch from util.db import OuterAtomic if six.PY3: from importlib import reload class UrlResetMixin(objec...
""" Reset the mock tracker in order to forget about old events. """ self.mock_tracker.reset_mock() def
get_latest_call_args(self): """ Return the arguments of the latest call to emit. """ return self.mock_tracker.emit.call_args[0] class PatchMediaTypeMixin(object): """ Generic mixin for verifying unsupported media type in PATCH """ def test_patch_unsupported_media_type(s...
erikaklein/algoritmo---programas-em-Python
AlunosPesoAlturaImc.py
Python
mit
439
0.034404
#Faça um programa que o usuário informe a quantidade de alunos
de uma turma, o sistema deve ler o peso e altura de cada # aluno, ao final informa
r o imc. T= int(input("entre com a quantidade de alunos")) x=0 soma=0 somapesos=0 somaltura=0 while (x<T): P= float(input("entre com o peso do aluno")) A= float(input("entre com a altura do aluno")) IMC=P/(A*A) print("IMC é ", IMC) x=x+1
cetic/python-msp430-tools
msp430/memory/error.py
Python
bsd-3-clause
881
0.001135
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2002-2010 Chris Liechti <cliechti@gmx.net> # All Rights Reserved. # Simplified BSD License (see LICENSE.txt for full text) """\ Error messages for file handler modules. """ class Fi
leFormatError(Exception): """\ Exception for "file is not in the expected format" messages. """ def __init__(self, message, filename=None, lineno=None): Exception.__init__(self, message) self.filename = filename self.line
no = lineno def __repr__(self): return "%s(%s, %s, %s)" % ( self.__class__.__name__, Exception.__repr__(self), self.filename, self.lineno) def __str__(self): return "%s:%s: %s)" % ( self.filename, s...
npdoty/pywikibot
scripts/welcome.py
Python
mit
41,884
0.000024
#!/usr/bin/python # -*- coding: utf-8 -*- u""" Script to welcome new users. This script works out of the box for Wikis that have been defined in the script. It is currently used on the Dutch, Norwegian, Albanian, Italian Wikipedia, Wikimedia Commons and English Wikiquote. Ensure you have community support before runn...
(C) Kyle/Orgullomoore, 2006-2007 # (C) Siebrand Mazeland, 2006-2009 # (C) Filnik, 2007-2011 # (C) Daniel Herding, 2007 # (C) Alex Shih-Han Lin, 2009-2010 # (C) xqt, 2009-2017 # (C) Pywikibot team, 2008-2017 # # Distributed under the terms of the MIT license. # from __future__ imp
ort absolute_import, unicode_literals import codecs from datetime import timedelta import locale import re import sys import time from random import choice import pywikibot from pywikibot import config, i18n from pywikibot.tools.formatter import color_format from pywikibot.tools import issue_deprecation_warning, Un...
pytorch/fairseq
fairseq/modules/adaptive_input.py
Python
mit
2,565
0.00078
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import List import torch from torch import nn from fairseq.modules.quant_noise import quant_noise class AdaptiveInput
(nn.Module): def __init__( self, vocab_size: int, padding_idx: int, initial_dim: int, factor: float, output_dim: in
t, cutoff: List[int], q_noise: float = 0, qn_block_size: int = 8, ): super().__init__() if vocab_size > cutoff[-1]: cutoff = cutoff + [vocab_size] else: assert ( vocab_size == cutoff[-1] ), "cannot specify cutoff la...
hivelocity/imbox
imbox/__init__.py
Python
mit
1,824
0
from imbox.imap import ImapTransport from imbox.parser import parse_email from imbox.query import build_search_query class Imbox(object): def __init__(self, hostname, username=None, password=None, ssl=True): self.se
rver = ImapTransport(hostname, ssl=ssl) self.username = username
self.password = password self.connection = self.server.connect(username, password) def logout(self): self.connection.close() self.connection.logout() def query_uids(self, **kwargs): query = build_search_query(**kwargs) message, data = self.connection.uid('search', None...
arenadata/ambari
ambari-server/src/main/python/ambari_server/serverClassPath.py
Python
apache-2.0
5,779
0.00969
#!/usr/bin/env python ''' 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")...
arguments: classpath - java class path """ jars = self._find_all_jars(classpath) jar_names = {} for jar in jars: match = JAR_FILE_PATTERN.mat
ch(os.path.basename(jar)) if match: for group in match.groups(): if group in JAR_DUPLICATES_TO_IGNORE: break if group in jar_names: err = "Multiple versions of {0}.jar found in java class path " \ "({1} and {2}). \n Make sure that yo...
xuweiliang/Codelibrary
nova/conf/key_manager.py
Python
apache-2.0
3,561
0.000281
# Copyright 2016 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
, help=""" Fixed key returned by key manager, specified in hex. Possible values: * Empty string or a key in hex value """), ] barbican_group = cfg.OptGroup( "barbican", title="Barbican options") barbican_opts = [ cfg.StrOpt("catalog_info", default="key-manager:barbican:public"...
been moved to the " "Castellan library", help=""" Info to match when looking for barbican in the service catalog. Format is: separated values of the form: <service_type>:<service_name>:<endpoint_type> """), cfg.StrOpt("endpoint_template", deprecated_for...
cmptrgeekken/evething
thing/models/notification.py
Python
bsd-2-clause
2,097
0.005246
# ------------------------------------------------------------------------------ # Copyright (c) 2010-2013, EVEthing team # 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...
TERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY # OF SUCH DAMAGE. # -------------------------------------------------------------------...
m django.db import models from thing.models.character import Character class Notification(models.Model): id = models.BigIntegerField(primary_key=True) notification_id = models.BigIntegerField() character = models.ForeignKey(Character, on_delete=models.DO_NOTHING) type = models.CharField(max_length=250...
Fiware/dataModels
specs/Weather/WeatherForecast/harvesters/portugal/portugal_weather_forecast.py
Python
mit
21,328
0.001922
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This program collects Portugal weather forecasts from IPMA and uploads them to the Orion Context Broker. It uploads the list of stations on the fly from - http://api.ipma.pt/json/locations.json. Legal notes: - http://www.ipma.pt/en/siteinfo/in...
if value != -1, then work as a service http_ok = [200, 201, 204] log_levels = ['ERROR', 'INFO', 'DEBUG'] logger = None logger_req = None stations = dict() # preprocessed list of stations tz = timezone('UTC') tz_wet = 'Europe/Lisbon' tz_azot = 'Atlantic/Azores' tz_azot_codes = ['3490100', '34802...
json' url_stations = 'http://api.ipma.pt/json/locations.json' template = { 'id': 'urn:ngsi-ld:WeatherForecast:Portugal-WeatherForecast-', 'type': 'WeatherForecast', 'address': { 'type': 'PostalAddress', 'value': { 'addressCountry': 'PT', 'addressLocality': None, ...
pengkobe/leetcode
questions/Valid_Sudoku.py
Python
gpl-3.0
1,179
0.021422
# -*- coding: utf-8 -*- # Determine if a Sudoku is valid,
according to: Sudoku Puzzles - The Rules. # The Sudo
ku board could be partially filled, where empty cells are filled with the character '.'. # A partially filled sudoku which is valid. # Note: # A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. def isValidSudoku(self, board): """ :type board: Lis...
tanglei528/ceilometer
ceilometer/orchestration/notifications.py
Python
apache-2.0
2,499
0
# Author: Swann Croiset <swann.croiset@bull.net> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
CE = 'orchestra
tion' class StackCRUD(plugin.NotificationBase): resource_name = '%s.stack' % SERVICE @property def event_types(self): return [ '%s.create.end' % (self.resource_name), '%s.update.end' % (self.resource_name), '%s.delete.end' % (self.resource_name), '...
LuckDragon82/demo
config/localhost.py
Python
lgpl-3.0
4,151
0.027945
""" This is the boilerplate default configuration file. Changes and additions to settings should be done in the config module located in the application root rather than this config. """ config = { # webapp2 sessions 'webapp2_extras.sessions' : {'secret_key': 'Force_be_with'}, # webapp2 authentication 'webapp2_extras...
'en', # Locale code = <language>_<territory> (ie 'en_US') # to pick locale codes see http://cldr.unicode.org/index/cldr-spec/picking-the-right-language-code # also see http://www.sil.org/iso639-3/codes.asp # Language codes defined under iso 639-1 http://en.wikipedia.org/wiki/List_of_ISO
_639-1_codes # Territory codes defined under iso 3166-1 alpha-2 http://en.wikipedia.org/wiki/ISO_3166-1 # disable i18n if locales array is empty or None 'locales' : ['en_US', 'es_ES', 'it_IT', 'zh_CN', 'id_ID', 'fr_FR', 'de_DE', 'ru_RU', 'pt_BR', 'cs_CZ'], # contact page email settings 'contact_sender' : "PUT_SENDER_E...
tool-labs/static-browser
setup.py
Python
mit
489
0.002045
# coding=utf-8 import distutils.core with open('requirements.txt') as f: reqs = f.read().splitlines() distutils.core.setup( name='static-bro
wser', version='0.1dev', author='Robin Krahl', author_email='robin.krahl@wikipedia.de', packages=['static_browser'], package_dat
a={'righttovote': ['templates/*.html', 'static/js/*.js', 'static/css/*.css']}, license='LICENSE', long_description=open('README.md').read(), install_requires=reqs, )
dhylands/upy-examples
extint_toggle.py
Python
mit
401
0.012469
import pyb import micropython micropython.alloc_emergency_exception_buf(100) led1 = pyb.LED(4) # 4 = Blue led2 = pyb.LED(3) # 3 = Yellow pin = pyb.Pin(
'SW', pyb.Pin.IN, pull=pyb.Pin.PULL_UP) def callback(line): led1.toggle() if pin.value(): # 1 = not pressed led2.off() else: led2.on() ext =
pyb.ExtInt(pin, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, callback)
plotly/python-api
packages/python/plotly/plotly/graph_objs/layout/_polar.py
Python
mit
45,890
0.000392
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Polar(_BaseLayoutHierarchyType): # class properties # -------------------- _parent_path_str = "layout" _path_str = "layout.polar" _valid_props = { "angularaxis", "bargap...
h categories on this axis appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. categoryarraysrc Sets the source reference on Chart Studio Cloud for categoryarray . cate...
"trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the ...
sevanteri/micropython
util.py
Python
mit
1,664
0.009615
import pyb from pyb import Pin def translate(val, oMin=0, oMax=4096, nMin=0, nMax=255): """Tr
anslate val from range [oMin, oMax] to [nMin, nMax]""" return int(((val * (nMax - nMin)) / (oMax - oMin)) + nMin) def ledsOff(): """Turn all leds off""" [pyb.LED(i).off() for i in range(1,5)]
def binLeds(n, leds = [pyb.LED(i) for i in range(1,5)]): """Show an integer as binary with the onboard leds""" l = len(leds) n = n % 2 ** l ledsOff() for i in range(l): if n & (2**i): leds[i].on() def flashLeds(leds = [pyb.LED(i) for i in range(1,5)]): """Flash leds from 1...
iceout/python_koans_practice
python3/koans/about_strings.py
Python
mit
2,971
0.00101
#!/usr/bin/env python
# -*- coding: utf-8 -*- from runner.koan import * class AboutStrings(Koan): def test_double_quoted_strings_are_strings(self): string = "Hello, world." self.assertEqual(__, isinstance(string, str)) def test_single_quoted_strings_are_also_strings(self): string = 'Goodbye, world.' ...
str)) def test_triple_single_quotes_work_too(self): string = '''Bonjour tout le monde!''' self.assertEqual(__, isinstance(string, str)) def test_raw_strings_are_also_strings(self): string = r"Konnichi wa, world!" self.assertEqual(__, isinstance(string, str)) def test_use_...
tbarbette/clickwatcher
npf_run.py
Python
gpl-3.0
11,804
0.004829
#!/usr/bin/env python3 """ Main NPF testie runner program """ import argparse import errno import sys from npf import npf from npf.regression import * from npf.statistics import Statistics from npf.testie import Testie, ScriptInitException def main(): parser = argparse.ArgumentParser(description='NPF Testie run...
thod.get_last_ve
rsions(limit=args.history,branch=args.branch) else: versions = ['local'] # Builds of the regression versions builds = [] for version in versions: builds.append(Build(repo, version)) last_rebuilds = [] last_build = None if args.compare: if args.compare_version and ...
PHYC/Assign_Forcefield
XYZ-to-ForceField.py
Python
mit
14,964
0.051123
#!/opt/local/bin/python2.7 import os #import numpy import math from numpy import * from sys import * import sys import getopt ### --- Arguments --- ### program = "XYZ-to-ForceField.py" ifile = '' ofile = '' ### Read command line args try: myopts, args = getopt.getopt(sys.argv[1:],"i:o:h") except getopt.GetoptError:...
["na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","p
m","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","uut","fl","uup","lv","uus","uuo"] def getElementNum(at1): elem...
apache/incubator-systemml
src/main/python/systemds/operator/nodes/matrix.py
Python
apache-2.0
16,930
0.002067
# ------------------------------------------------------------- # # 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 unde...
is python local!' if self._is_numpy(): prepared_script.setMatrix(var_name, numpy_to_matrix_block( sds, self._np_array), True) # True for reuse def code_line(self, var_name: str, unnamed_input_vars: Sequence[str], named_input_vars: Dict[str, str]) -> str: ...
s, named_input_vars) if self._is_numpy(): code_line = code_line.format(file_name=var_name) return code_line def compute(self, verbose: bool = False, lineage: bool = False) -> np.array: if self._is_numpy(): if verbose: print('[Numpy Array - No Compilat...
skavulya/spark-tk
python/sparktk/models/regression/regression_test_metrics.py
Python
apache-2.0
2,055
0.002023
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # 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 require...
parktk.propobj import PropertiesObject class RegressionTestMetrics(PropertiesObject): """ RegressionMetrics class used to hold the data returned from regression tests """
def __init__(self, scala_result): self._explained_variance = scala_result.explainedVariance() self._mean_absolute_error = scala_result.meanAbsoluteError() self._mean_squared_error = scala_result.meanSquaredError() self._r2 = scala_result.r2() self._root_mean_squared_error = ...
loredanacirstea/ai-algos
hidden_markov_models/my_recognizer.py
Python
gpl-3.0
1,646
0.006075
import warnings from asl_data import SinglesData def recognize(models: dict, test_set: SinglesData): """ Recognize test word sequences from word models set :param models: dict of trained models {'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...} :param test_set: Si...
ist) as probabilities, guesses both lists are ordered by the test set word_id probabilities is a list of dictionaries where each key a word and value is Log Liklihood [{SOMEWORD': LogLvalue, 'SOMEOTHERWORD' LogLvalue, ... }, {SOMEWORD': LogLvalue, 'SOMEOTHERWORD' LogLvalue, ... }, ...
gs("ignore", category=DeprecationWarning) probabilities = [] guesses = [] # TODO implement the recognizer # return probabilities, guesses for word_id in range(0, len(test_set.get_all_Xlengths())): current_sequence, current_length = test_set.get_item_Xlengths(word_id) pr...
protonn/Electrum-Cash
plugins/cosigner_pool/qt.py
Python
mit
7,561
0.00119
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without...
sword to
decrypt it.') if not password: return else: password = None if not window.question(_("An encrypted transaction was retrieved from cosigning pool.\nDo you want to open it now?")): return xprv = wallet.keystore.get_master_private_key(pas...
meghabhoj/NEWBAZAAR
tests/listings/test_processor.py
Python
bsd-2-clause
631
0
from __future__ import absolute_import from __future__ import unicode_literals from django.te
st import TestCase import mock from bazaar.listings.processor import OrderProcessor from .. import factories as f class TestProcessorGetOrder(TestCase): def setUp(self): self.order = f.OrderFactory() def test_get_order_does_not_fail_if_order_not_linked_to_a_publishing(self):
processor = OrderProcessor() processor.order_lookup_id = 'external_id' incoming = mock.Mock() incoming.external_id = self.order.external_id self.assertEqual(processor.get_order(incoming), self.order)
lotaku/pytest-2.3.5
testing/conftest.py
Python
mit
3,773
0.005831
import pytest import sys pytest_plugins = "pytester", import os, py pid = os.getpid() def pytest_addoption(parser): parser.addoption('--lsof', action="store_true", dest="lsof", default=False, help=("run FD checks if lsof is available")) def pytest_configure(config): config.addinivalue_...
pass else: config._numfiles = len(getopenfiles(out)) #def pytest_report_header(): # return "pid: %s" % os.getpid() def getopenfiles(out): def isopen(line)
: return ("REG" in line or "CHR" in line) and ( "deleted" not in line and 'mem' not in line and "txt" not in line) return [x for x in out.split("\n") if isopen(x)] def check_open_files(config): out2 = py.process.cmdexec("lsof -p %d" % pid) lines2 = getopenfiles(out2) if len(lines2) ...