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
akrherz/pyWWA
parsers/taf_parser.py
Python
mit
120
0
""" NESDIS TAF Ingestor """ # Local from
pywwa.workflows.taf_parser import main if __name__ ==
"__main__": main()
nawawi/wkhtmltopdf
webkit/Source/ThirdParty/gyp/test/make/gyptest-dependencies.py
Python
lgpl-3.0
812
0
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of t
his source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that .d files and all.deps are properly generated. """ import os import TestGyp # .d files are only used by the make build. test = TestGyp.TestGyp(formats=['make']) test.run_gyp('dependencies.gyp')
test.build('dependencies.gyp', test.ALL) deps_file = test.built_file_path(".deps/out/Default/obj.target/main/main.o.d") test.must_contain(deps_file, "main.h") # Build a second time to make sure we generate all.deps. test.build('dependencies.gyp', test.ALL) all_deps_file = test.built_file_path(".deps/all.deps") test....
ymind/docker-mongo-es
conf/appconfig.py
Python
mit
1,677
0
import os import yaml MONGO_USERNAME = os.getenv('MONGO_USERNAME', None) MONGO_PASSWORD = os.getenv('MONGO_PASSWORD', None) MONGODB_HOST = os.getenv('MONGODB_HOST', '127.0.0.1') MONGODB_PORT = int(os.getenv('MONGODB_PORT', '27017')) MONGODB_SERVERS = os.getenv('MONGODB_SERVERS') \ or '{}:{}'.format(...
os.getenv('MONGO_URL') or MONGODB_DE
FAULT_URL MONGO_INCLUDES = os.getenv('MONGO_INCLUDES', '') ES_URL = os.getenv('ES_URL', 'http://localhost:9200') ES_INDEXES = yaml.load(os.getenv('ES_INDEXES') or '{}') ES_TIMEOUT_SECONDS = int(os.getenv('ES_TIMEOUT_SECONDS', '100')) LOG_VERBOSITY = int(os.getenv('LOG_VERBOSITY', 2)) MONGO_CONNECTOR_CONFIG = 'mongo...
david-hoffman/scripts
imreg_dph.py
Python
apache-2.0
14,711
0.000748
#!/usr/bin/env python # -*- coding: utf-8 -*- # imreg_dph.py """ Functions for 2D image registration Copyright (c) 2018, David Hoffman """ import itertools import numpy as np from dphutils import slice_maker # three different registration packages # not dft based import cv2 # dft based from skimage.feature import re...
.__init__.__doc__ = AffineTransformBase.__init__.__doc__ AffineTransform.__doc__ = AffineTransformBase.__doc__ def _calc_pad(oldnum, newnum): """ Calculate the proper padding for fft_pad We have three cases: old number even new number even >>> _calc_pad(10, 16) (3, 3) old number odd new numb...
ld number odd new number odd >>> _calc_pad(11, 17) (3, 3) old number even new number odd >>> _calc_pad(10, 17) (4, 3) same numbers >>> _calc_pad(17, 17) (0, 0) from larger to smaller. >>> _calc_pad(17, 10) (-4, -3) """ # how much do we need to add? width = newn...
OpenPathView/batchPanoMaker
opv_import/helpers/bit_utils.py
Python
gpl-3.0
1,156
0
# coding: utf-8 # Copyright (C) 2017 Open Path View, Maison Du Libre # 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. # ...
ou should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # Contributors: Benjamin BERNARD <benjamin.bernard@openpathview.fr> # Email: team@openpathview.fr # De
scription: Utils for makelot. def bit_len(int_type: int) -> int: """ Returns int_type length, position of last non 0 bit. :param int_type: An int value. :type int_type: int :return: position of last non 0 bit. :rtype: int """ length = 0 while (int_type): int_type >>= 1 ...
glen3b/CyberPatriotScoreboardParser
scoreovertime.py
Python
gpl-3.0
756
0.003968
#!/usr/bin/python3 import sys from lxml import html import urllib3 import re http = urllib3.PoolManager() baseUrl = 'http://scoreboard.uscyberpatriot.org/' scoresPage = html.fromstring(http.request('GET', baseUrl + 'team.php?team=' + sys.argv[1]).data) # XPath for chart script: /html/body/div[2]/div/script[1] char...
all(chart.text) for res in reSearch: # Tuple result # Capture 0 is time # Capture 1 is screwyformat scores print(res[0], end='') for score in filter(None, res[1].split(',')): print('\t' +
score, end='') print()
TaliesinSkye/evennia
wintersoasis-master/web/character/backend.py
Python
bsd-3-clause
2,518
0.006354
""" Backend functions for the character application. """ import string from src.utils.create import create_player from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth import login from django.contrib.auth.models import User from django.core.mail import send_mail from Cr...
tivate it. You can activate the account by visiting the following URL: https://%s%s/%s/%s/ If you didn't register with Winter's Oasis, you can ignore
this email. The account will be deleted within a few days if it is not activated. """ % (context.META['HTTP_HOST'], reverse('roster.views.activate', args=(character.player.user.id, key))), settings.SERVER_EMAIL, [character.player.user.email] ) def new_player(name, email, password, context): """ E...
tensorflow/model-analysis
tensorflow_model_analysis/evaluators/legacy_aggregate_test.py
Python
apache-2.0
10,171
0.004523
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
beam.Create(test_input) | 'ComputePerSliceMetrics' >> aggregate.ComputePerSliceMetrics( eval_shared_model=eval_shared_model, desired_batch_size=3)) def check_result(got): self.assertEqual(3, len(got), 'got: %s' % got) slices = {} for slice_key, metrics in got: ...
slices[slice_key] = metrics overall_slice = () english_slice = (('language', 'english')) chinese_slice = (('language', 'chinese')) self.assertCountEqual( list(slices.keys()), [overall_slice, english_slice, chinese_slice]) self.assertDictElementsAlmostEqual( ...
beni55/django
tests/auth_tests/test_views.py
Python
bsd-3-clause
43,969
0.001638
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import itertools import re from importlib import import_module from django.apps import apps from django.conf import settings from django.contrib.admin.models import LogEntry from django.contrib.auth import REDIRECT_FIELD_NAME, SESSION_KEY...
(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) self.assertIn("http://", mail.outbox[0].body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) # optio
nal multipart text/html email has been added. Make sure original, # default functionality is 100% the same self.assertFalse(mail.outbox[0].message().is_multipart()) def test_html_mail_template(self): """ A multipart email with text/plain and text/html is sent if the html_em...
irmen/Pyro5
examples/stockquotes/phase2/stockmarket.py
Python
mit
1,133
0
import random import time from Pyro5.api import expose, Daemon, locate_ns @expose class StockMarket(object): def __init__(self, marketname, symbols): self._name = marketname self._symbols = symbols def quotes(self): w
hile True: symbol = random.choice(self.symbols) yield symbol, round(random.uniform(5, 150)
, 2) time.sleep(random.random()/2.0) @property def name(self): return self._name @property def symbols(self): return self._symbols if __name__ == "__main__": nasdaq = StockMarket("NASDAQ", ["AAPL", "CSCO", "MSFT", "GOOG"]) newyork = StockMarket("NYSE", ["IBM", "HP...
Onetaway/YouCompleteMe
python/ycm/completers/all/tests/identifier_completer_test.py
Python
gpl-3.0
3,220
0.014907
#!/usr/bin/env python # # Copyright (C) 2013 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe 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 you...
def GetCursorIdentifier_StartOfLine_StopsAtNonIdentifierChar_test(): eq_( 'foo', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': 'foo(goo)' } ) ) def GetCursorIdentifier_AtNonIdentifier_test(): eq_( 'goo', identifier_completer._G...
er_WalksForwardForIdentifier_test(): eq_( 'foo', identifier_completer._GetCursorIdentifier( { 'column_num': 0, 'line_value': ' foo' } ) ) def GetCursorIdentifier_FindsNothingForward_test(): eq_( '', identifier_completer._GetCursorIdentifier( { ...
dracos/QGIS
python/plugins/GdalTools/tools/inOutSelector.py
Python
gpl-2.0
7,841
0.0264
# -*- coding: utf-8 -*- """ *************************************************************************** inOutSelector.py --------------------- Date : April 2011 Copyright : (C) 2011 by Giuseppe Sucameli Email : brush dot tyler at gmail dot com *************...
()", "filenameChanged(), layerChanged()") def __init__(self, parent=None, type=None): QWidget.__init__(self, parent) self.setupUi(self) self.setFocusPolicy(Qt.StrongFocus) self.combo.setInsertPolicy(Q
ComboBox.NoInsert) self.clear() self.typ = None if type is None: self.resetType() else: self.setType(type) self.connect(self.selectBtn, SIGNAL("clicked()"), self.selectButtonClicked) self.connect(self.fileEdit, SIGNAL("textChanged(const QString &)"), self.textChang...
chris-ch/us-equities
create-stats-perfs-db.py
Python
mit
1,963
0.00866
from collections import defaultdict from zipfile import ZipFile from datetime import datetime from itertools import izip import logging import sys import shelve from backtest import constants def main(): PRICES_DATA = constants.PRICES_DATA performances = shelve.open(constants.CACHE_PERFS, ...
px_last = float(items[4]) dates.append(px_date) prices.append(px_last) for date, price, price_prev in izip(dates[1:], prices[1:], prices[:-1]): perf = (price / price_prev) - 1.0 se...
')] = perf performances[security_code] = security_performances performances.close() if __name__ == '__main__': logging.basicConfig( level=logging.DEBUG, format='%(levelname)s %(asctime)s %(module)s - %(message)s' )...
acil-bwh/SlicerCIP
Scripted/CIP_/CIP/ui/CollapsibleMultilineText.py
Python
bsd-3-clause
595
0.005042
import qt class Collapsibl
eMultilineText(qt.QTextEdit): """Text field that expands when it gets the focus and remain collapsed otherwise""" def __init__(self): super(CollapsibleMultilineText, self).__init__() self.minHeight = 20 self.maxHeight = 50 self.setFixedHeight(self.minHeight) def focusInEvent...
focusOutEvent(self, event): # super(MyLineEdit, self).focusOutEvent(event) self.setFixedHeight(self.minHeight)
zach-king/Python-Miscellaneous
Cryptography/transpositionCipher.py
Python
gpl-2.0
1,466
0.004775
import sys import pyperclip import math def encrypt(key, message): ciphertext = [''] * key for col in range(key): pointer = col while pointer < len(message): ciphertext[col] += message[pointer] pointer += key return ''.join(ciph
ertext) def decrypt(key, ciphertext): numColumns = math.ceil(len(ciphertext) / key) numRows = key numEmptyCells = (numColumns * numRows) - len(ciphertext) plaintext = [''] * numColumns col = 0 row = 0 for symbol in ciphertext: plaintext[col] += symbol col += 1 if...
sage=None, mode=None): if key == None: key = int(input("Enter a Key: ")) if message == None: message = input("Enter a Message: ") if mode == None: mode = int(input("Encrypt(1) or Decrypt(0): ")) if mode: encrypted = encrypt(key, message) print(encrypted) ...
firekillice/python-mysql-flushdata
gamemysql.py
Python
gpl-2.0
2,372
0.067454
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb import MySQLdb.cursors class GameMysql(): def __init__(self,host,port,user,pwd): try: print host,port,user,pwd self.__conn = MySQLdb.connect(host = host,port = port,user = user,passwd = pwd) self.__cursor = self.__conn.cursor() except Exception,e...
lf.__befo
re_excute__(dbname) self.__cursor.execute(mysql) self.__conn.commit() except Exception,e: print Exception,e #close this mysql conn def close(self): self.__cursor.close() self.__conn.close()
rcgee/oq-hazardlib
openquake/hazardlib/gsim/akkar_2013.py
Python
agpl-3.0
1,189
0.000841
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2013-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
ffer
o General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. """ Module exports :class:`AkkarEtAl2013`. """ from __future__ import division import warnings from openquake.hazardlib.gsim.akkar...
amanharitsh123/zulip
zerver/migrations/0069_realmauditlog_extra_data.py
Python
apache-2.0
416
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-27 20:00 from django.db import migrations, models class Migration(migrations.Migration)
: dependencies
= [ ('zerver', '0068_remove_realm_domain'), ] operations = [ migrations.AddField( model_name='realmauditlog', name='extra_data', field=models.TextField(null=True), ), ]
mrcaps/rainmon
code/ui/rain/tasks.py
Python
bsd-3-clause
5,117
0.012116
#Copyright (c) 2012, Carnegie Mellon University. #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, this list of condition...
cdir = os.path.join(cfg["tmpdir"][3:],"cache") return os.path.join(cdi
r,savename) @task() def add(x, y): return str(x + y) + "was a test." #@param outname the output directory name for the save cache #@param machines the list of nodes to run the analysis over #@param attributes the list of metrics to run the analysis over #@param startt starting time for analysis #@param endt endin...
koxudaxi/BacklogPy
tests/backlog/test_base.py
Python
mit
3,123
0.00064
from __future__ import absolute_import import six if six.PY3: from unittest import TestCase, mock else: import sys if sys.version_info < (2, 7, 0): from unittest2 import TestCase else: from unittest import TestCase import mock from BacklogPy.base import BacklogBase class TestBa...
ters={'name': 'abc'}) args, kwargs = m.call_args_list[0] self.assertTupleEqual(args, ('POST', 'https://space-id.backlog.jp/api/v2/path')) self.
assertDictEqual(kwargs, {'params': {'apiKey': 'api-key', 'id': 123}, 'data': {'name': 'abc'}, 'headers': { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}})
takeflight/wagtailvideos
wagtailvideos/views/videos.py
Python
bsd-3-clause
6,698
0.001941
from django.http import HttpResponseNotAllowed from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from django.utils.translation import ugettext as _ from django.views.decorators.vary import vary_on_headers from wagtail.admin import messages from wagtail.admin.forms import S...
return render(request, "wagtailvideos/videos/edit.html", { 'video': video, 'form': form, 'filesize': video.get_file_size(), 'can_transcode': ffmpeg.installed(), 'transcodes': video.transcodes.all(), 'transcode_form': VideoTranscodeAdminForm(video=video), 'us...
n_policy.user_has_permission_for_instance(request.user, 'delete', video) }) def create_transcode(request, video_id): if request.method != 'POST': return HttpResponseNotAllowed(['POST']) video = get_object_or_404(Video, id=video_id) transcode_form = VideoTranscodeAdminForm(data=request.POST, vi...
ei-grad/django-environ
environ/environ.py
Python
mit
22,397
0.001339
""" Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application. """ import json import logging import os import re import sys import warnings from django.core.exceptions import ImproperlyConfigured from six.moves import urllib_parse as urlparse from six import st...
ult # Resolve any proxied values if hasattr(value, 'startswith') and value.startswith('$'): value = value.lstr
ip('$') value = self.get_value(value, cast=cast, default=default) if value != default or parse_default: value = self.pa
jcfr/girder
plugins/jobs/server/__init__.py
Python
apache-2.0
871
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Vers
ion 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS I...
# limitations under the License. ############################################################################### from . import job_rest def load(info): info['apiRoot'].job = job_rest.Job()
redhat-cip/hardware
hardware/tests/test_benchmark_mem.py
Python
apache-2.0
5,424
0
# -*- coding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0...
, sorted(self.hw_data)) def test_check_mem_size(self, mock_popen, moc
k_cpu_socket, mock_get_memory): block_size_list = ('1K', '4K', '1M', '16M', '128M', '1G', '2G') mock_get_memory.return_value = 123456789012 for block_size in block_size_list: self.assertTrue(mem.check_mem_size(block_size, 2)) # Low memory ...
Azure/azure-sdk-for-python
sdk/textanalytics/azure-ai-textanalytics/tests/test_recognize_linked_entities_async.py
Python
mit
28,006
0.002287
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import os import pytest import platform import functools from azure.core.exceptions import HttpResponseError, ClientAuthenticationError from azure.core.credentials impo...
ent): docs = [ TextDocumentInput(id="1", text="one"),
TextDocumentInput(id="2", text="two"), TextDocumentInput(id="3", text="three"), TextDocumentInput(id="4", text="four"), TextDocumentInput(id="5", text="five") ] response = await client.recognize_linked_entities(docs) for idx, doc in enumerate(response...
wevoice/wesub
apps/openid_consumer/admin.py
Python
agpl-3.0
1,189
0.004205
# Amara, universalsubtitles.org # # Copyright (C) 2016 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Softwar
e 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. See the # GNU Affero General Public Licens...
f not, see # http://www.gnu.org/licenses/agpl-3.0.html. # Based on: http://www.djangosnippets.org/snippets/73/ # # Modified by Sean Reifschneider to be smarter about surrounding page # link context. For usage documentation see: # # http://www.tummy.com/Community/Articles/django-pagination/ from django.contri...
soumyanishan/azure-linux-extensions
OSPatching/patch/centosPatching.py
Python
apache-2.0
770
0.001299
#!/usr/bin/python # # Copyright 2014 Microsoft 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 required by applicable...
THOUT 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 redhatPatching import red
hatPatching class centosPatching(redhatPatching): def __init__(self, hutil): super(centosPatching,self).__init__(hutil)
amboycharlie/Child-Friendly-LCMS
leonardo/__init__.py
Python
apache-2.0
520
0
default_app_config = 'leonardo.apps.LeonardoConfig' __import__('pkg_resources').decla
re_namespace(__name__) try: from leonardo.base import leonardo # noqa except ImportError: import warnings def simple_warn(m
essage, category, filename, lineno, file=None, line=None): return '%s: %s' % (category.__name__, message) msg = ("Could not import Leonardo dependencies. " "This is normal during installation.\n") warnings.formatwarning = simple_warn warnings.warn(msg, Warning)
rvianello/rdkit
rdkit/ML/BuildComposite.py
Python
bsd-3-clause
35,920
0.0098
# $Id$ # # Copyright (C) 2000-2008 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ command line util...
** - msg
: the string to be d
evidation-health/ContinuousTimeMarkovModel
src/ContinuousTimeMarkovModel/profilingUtil.py
Python
mit
2,046
0.002444
import time, inspect try: from line_profiler import LineProfiler def do_profile(follow=[]): def inner(func): def profiled_func(*args, **kwargs): try: profiler = LineProfiler() profiler.add_function(func) for f in fo...
@property def delta(self): cur = time.time() diff = cur - self.prev self.prev = cur return diff def checkpoint(self, name=''): print '{timer} {checkpoint} at {elapsed} took {delta} seconds'.format( timer=self.name, checkpoint=name, ela...
def __exit__(self, type, value, traceback): self.checkpoint('finished') pass
soerendip42/rdkit
rdkit/ML/InfoTheory/entropy.py
Python
bsd-3-clause
2,823
0.01842
# # Copyright (C) 2000-2008 greg Landrum and Rational Discovery LLC # """ Informational Entropy functions The definitions used are the same as those in Tom Mitchell's book "Machine Learning" """ import numpy import math from rdkit.six.moves import xrange # try to get the C versions of these routines try: ...
1 # it's pretty obvious what this is for ;-) _log2 = math.log(2) def PyInfoEntropy(results): """ Calculates the informational entropy of a set of results. **Arguments** results is a 1D Numeric array containing the number of times a given set hits each possible result. For example, if a function has ...
loat(sum(results)) if nInstances == 0: # to return zero or one... that is the question return 0 probs = results/nInstances #------- # NOTE: this is a little hack to allow the use of Numeric # functionality to calculate the informational entropy. # The problem is that the system log function p...
ityaptin/ceilometer
ceilometer/tests/unit/hardware/pollsters/test_generic.py
Python
apache-2.0
7,408
0
# # Copyright 2015 Intel Corp. # # 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 writin...
lid', unit='B', snmp_inspector={}) try: generic.MeterDefinition(cfg) except declarative.MeterDefinitionException as e: self.assertEqual("Unrecognized type value invalid", e.brief_message) @mock.patch('c
eilometer.hardware.pollsters.generic.LOG') def test_bad_metric_skip(self, LOG): cfg = {'metric': [dict(name='test1', type='gauge', unit='B', snmp_inspector={}), dict(name='test_bad', ...
20tab/twentytab-sortable
sortable/__init__.py
Python
mit
80
0
VERSION = (0, 11) __versio
n__ = '.'.join(map(
str, VERSION)) DATE = "2015-02-06"
aileron-split/aileron-web
server/team/views.py
Python
gpl-3.0
4,519
0.003541
from rest_framework import viewsets, mixins from .models import Member from .serializers import MemberSerializer, MemberDetailSerializer # Team app views. # All team members class MembersViewSet (viewsets.ReadOnlyModelViewSet): serializer_class = MemberSerializer queryset = Member.objects def list(self...
(__class__, self).list(request, **kwargs) response['Access-Control-Allow-Origin'] = 'http://192.168.18.107:4200' # TODO: RE
MOVE, TESTING ONLY return response class PublishedEmployeesDetailViewSet (mixins.RetrieveModelMixin, viewsets.GenericViewSet): serializer_class = MemberDetailSerializer queryset = Member.objects.filter(published=True, status__in=(Member.FULLTIME, Member.PARTTIME)...
ddd332/presto
presto-docs/target/sphinx/rst2pdf/extensions/vectorpdf/pdfrw/pdfcompress.py
Python
apache-2.0
1,656
0.001812
# A part of pdfrw (pdfrw.googlecode.com) # Copyright (C) 2006-2009 Patrick Maupin, Austin, Texas # MIT license -- See LICENSE.txt for details ''' Currently, this sad little file only knows how to decompress using the flate (zlib) algorithm. Maybe more later, but it's not a priority for me... ''' from __future__ impo...
e if isinstance(ftype, list) and len(ftype) == 1: # todo: multiple filters ftype = ftype[0] parms = obj.DecodeParms if ftype != flate or parms is not None: msg = 'Not decompressing: cannot use filter %s with parameters
%s' % (repr(ftype), repr(parms)) if msg not in warnings: warnings.add(msg) print msg else: obj.stream = zlib.decompress(obj.stream) obj.Filter = None def compress(mylist): flate = PdfName.FlateDecode for obj in streamobjects(mylist): ...
jamesblunt/sympy
sympy/interactive/tests/test_ipythonprinting.py
Python
bsd-3-clause
5,908
0.0022
"""Tests that the IPython printing module is properly loaded. """ import warnings from sympy.core.compatibility import u fr
om sympy.interactive.session import init_ipython_session from sympy.external import import_module from sympy.utilities.pytest import raises # run_cell was added in IPython 0.11 ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not pr
esent if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy impo...
alexcoplan/p2proj
src/script/dist_comb.py
Python
mit
4,527
0.02342
# tpye hints from typing import Dict,Any # libs import numpy as np # type: ignore import matplotlib.pyplot as plt # type: ignore import argparse import json """ returns (arithmetic, geometric) combinations of input distribution list """ def combine_dists(dist_list, entropy_bias): dists = np.array(dist_list) sums ...
g2(dist_size) dist_entropies = -np.sum(dists * np.log2(dists), axis=1) weights = np.expand_dims(dist_entropies ** (-entropy_bias), axis=0) arith = np.squeeze(np.dot(np.transpose(dists), np.transpose(weights)) / np.sum(weights)) geo_weighted = np.power(dists, np.transpose(weights)) product = np.product...
np.sum(rooted) return list(arith), list(geom) parser = argparse.ArgumentParser() parser.add_argument("--gen-tests", default=False, action="store_true", help="if this option is set, then the script will generate test cases for\ both arithmetic and geometric distribution combination. otherwise, we\ wil...
purushothamc/myibitsolutions
two_pointers/remove_duplicates_sorted_array.py
Python
gpl-3.0
336
0.011905
def removeDuplicates(A): if not A: return A lenA = len(A) k = 0 A[k] = A[0] for idx in xrange(lenA):
if idx+1 < lenA and A[k] == A[idx+1]: continue else: k += 1 if idx + 1 < lenA: A[k] = A[idx+1] print k A
= [1,2,3] removeDuplicates(A)
ledatelescope/bifrost
testbench/your_first_block.py
Python
bsd-3-clause
3,507
0.003137
#!/usr/bin/env python # Copyright (c) 2017-2020, The Bifrost Authors. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice...
print(iseq.name) pprint(iseq.header) self.n_iter = 0 def on_data(self, ispan): now = datetime.now() if self.n_iter % 100 == 0: print("[%s] %s" % (now, ispan.data)) self.n_iter += 1 i
f __name__ == "__main__": # Setup pipeline filenames = sorted(glob.glob('testdata/sin_data*.bin')) b_read = BinaryFileReadBlock(filenames, 32768, 1, 'f32') b_add = UselessAddBlock(b_read, n_to_add=100) b_print = PrintStuffBlock(b_read) b_print2 = PrintStuffBlock(b_add) ...
tdyas/pants
contrib/go/src/python/pants/contrib/go/subsystems/go_import_meta_tag_reader.py
Python
apache-2.0
2,841
0.002112
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import re import requests from pants.subsystem.subsystem import Subsystem from pants.util.memo import memoized_method from pants.contrib.go.subsystems.imported_repo import ImportedRepo ...
""" <meta \s+ name=['"]go-import['"] \s+ content=['"](?P<ro
ot>[^\s]+)\s+(?P<vcs>[^\s]+)\s+(?P<url>[^\s]+)['"] \s* /?>""", flags=re.VERBOSE, ) @classmethod def find_meta_tags(cls, page_html): """Returns the content of the meta tag if found inside of the provided HTML.""" return cls._META_IMPORT_REGEX.findall(page_html) ...
TheTimmy/spack
var/spack/repos/builtin/packages/font-isas-misc/package.py
Python
lgpl-2.1
2,105
0.00095
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
r FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston,...
tIsasMisc(Package): """X.org isas-misc font.""" homepage = "http://cgit.freedesktop.org/xorg/font/isas-misc" url = "https://www.x.org/archive/individual/font/font-isas-misc-1.0.3.tar.gz" version('1.0.3', 'ecc3b6fbe8f5721ddf5c7fc66f73e76f') depends_on('font-util') depends_on('fontconfig'...
zyzyis/monetdb
sql/test/Users/Tests/table.SQL.py
Python
mpl-2.0
488
0.02459
### # SET a GRANTed ROLE for a USER (possible). # CREATE TABLE and INSERT (possible). ### import os, sys try: from MonetDBtesting import process except ImportError: import process clt = process.client('sql', user = 'my_user', passwd = 'p1',
stdin = open(os.path.join(os.getenv('RELSRCDIR'), os.pardir, 'table.sql')), stdout = process.PIPE, stderr = process.PIPE) out, err = clt.communicate()
sys.stdout.write(out) sys.stderr.write(err)
marianinn/mingus
mingus/containers/track.py
Python
gpl-3.0
7,328
0.001365
#!/usr/bin/python # -*- coding: utf-8 -*- # mingus - Music theory Python package, track module. # Copyright (C) 2008-2009, Bart Spaans # # 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 Found...
teContainer to the last Bar. If the Bar is full, a new one will automatically be created. If the Bar is not full but the note can't fit
in, this method will return False. True otherwise. An InstrumentRangeError exception will be raised if an Instrument is attached to the Track, but the note turns out not to be within the range of the Instrument. """ if self.instrument != None: if not self.ins...
dtattersall/BookSocialGraph
amazon_db.py
Python
mit
5,605
0.023194
''' this script is used to create a sqlite databse for all the book pages we collected. It reads from book_info.txt and writes the data to the book_attribute table in amazon.db. It also creates an edgelist table in the database. c1 to c10 are copurchases with the book. ''' import sqlite3 as lite import re rPrice=re.co...
') if count%18==3 and count<test_lim: isbn = line.lstrip('isbn:--').rstrip('\n') if count%18==4 and count<test_lim: nrevs = line.lstrip('nrevs:--').rstrip('\n') if count%18==5 and count<test_lim: format = line.lstrip('format:--').rstrip('\n') if count%...
m: url = line.lstrip('url:--').rstrip('\n') if count%18==7 and count<test_lim: price = line.lstrip('price:--').rstrip('\n').replace(',','') if count%18==8 and count<test_lim: title = line.lstrip('title:--').rstrip('\n') if count%18==9 and count<test_lim: ...
LikeMyBread/Saylua
saylua/modules/forums/forms/main.py
Python
agpl-3.0
632
0
from flask_wtf import FlaskForm from saylua.utils.form import sl_validators from saylua.utils.form.fields import SlField, SlTextAreaField class ForumThreadForm(FlaskForm): title = SlField('Thread Title', [ sl_validators.Required(), sl_validators.NotBlank(), sl_validators.Min(3)]) body ...
alidators.Required(), sl_validators.NotBlank(), sl_validators.Min(2)]) class ForumPostForm(FlaskForm): body = SlTextAreaField('Post Content', [ sl_validators.Req
uired(), sl_validators.NotBlank(), sl_validators.Min(2)])
onshape-public/onshape-clients
python/onshape_client/oas/models/bt_feature_filter127.py
Python
mit
7,271
0.000275
# coding: utf-8 """ Onshape REST API The Onshape REST API consumed by all clients. # noqa: E501 The version of the OpenAPI document: 1.113 Contact: api-support@onshape.zendesk.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 im...
tType", # noqa: E501 "exclusion": "exclusion", # noqa: E501 "feature_id": "featureId", # noqa: E501 } required_properties = set( [ "_data_store",
"_check_type", "_from_server", "_path_to_item", "_configuration", "_composed_instances", "_var_name_to_model_instances", "_additional_properties_model_instances", ] ) def __init__( self, _check_type=Tru...
andyeff/skybot
plugins/countdown.py
Python
unlicense
1,465
0.026621
from util import http, hook import time import datetime @hook.command(autohelp=False) def countdown(inp, say=None): ".countdown -- countdown timer for game releases" curtime = time.time() items=( ('test1','Te
st Event One','25 dec 14 00 00'), ('test2','Test Event Two','22 nov 16 00 00'), ) dict_date={} for i in items: dict_date[i[0]] = i[2] dict_desc={} for i in items: dict_desc[i[0]] = i[1] tracked = [] for i in items: tracked.append(i[0]) if len(inp) == 0: return 'Things I\'m track...
rptime(dict_date[inp], "%d %b %y %H %M")) if curtime > rlstime: return "it is released!!" difftime = datetime.timedelta(seconds=(rlstime - curtime)) def countdowner(td): return td.days, td.seconds//3600, (td.seconds//60)%60 res = countdowner(difftime) if res[0] == 1: s_days = "day" else: ...
bieschke/nuffle
lib/python/sqlobject/index.py
Python
gpl-2.0
5,230
0.002486
from types import * import col from converters import sqlrepr class SODatabaseIndex(object): def __init__(self, soClass, name, columns, unique=False): self.soClass = soClass self.name = name self.descriptions = self.conver...
(columns) self.unique = unique def convertColumns(self, columns): """ Converts all the columns to dictionary descriptors; dereferences string column names. """ new = [] for desc in columns: if not isinstance(desc, dict): desc = {'c...
oth an expression and a column ' '(for %s in index %s in %s)' % (desc, self.name, self.soClass)) assert not desc.has_key('length'), ( 'length does not apply to expressions (for %s in ' 'index %s in %s)' % ...
Taifxx/xxtrep
context.addtolib/lfm_service.py
Python
gpl-3.0
2,631
0.016356
# -*- coding: utf-8 -*- # # Copyright (C) 2016 Taifxx # # 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....
ext.xbmc.log('[%s] >> %s' % (context.addon.id, event)) def starter(): isRaise = False try: context.plgMain (importLI=ITD_FILE) except Exception as exc: context.DOS.delf(context.DOS.join(context.addon.profile, context.TAG_PAR_STRARTF)) context.GUI.msgf(adnname, msgProcessE...
= True finally: ## If user try double run ... if context.xbmcvfs.exists(context.DOS.join(context.addon.profile, ITD_FILE)): context.DOS.delf(context.DOS.join(context.addon.profile, ITD_FILE)) if isRaise : raise ### Main ... def service(externalAbort, report): ...
TwigWorld/Impostor
impostor/forms.py
Python
mit
252
0.007937
from django.contrib.auth.forms import AuthenticationForm fr
om django import forms from django.utils.translation import ugettext_lazy as _ class BigAuthenticationForm(AuthenticationForm):
username = forms.CharField(label=_("Username"), max_length=70)
CiscoSystems/os-sqe
lab/scenarios/server_resume.py
Python
apache-2.0
506
0
from lab.test_case_worker import TestCaseWorker class ServerResume(TestCaseWorker): def check_arguments(self,
**kwargs): pass # noinspection PyAttributeOutsideInit def setup_worker(self): self.name = self._kwargs.get('name', '') def
loop_worker(self): servers = self._cloud.os_server_list() for server in servers: server_name = server['Name'] if self.name in server_name: self._cloud.os_server_resume(server_name)
GoogleCloudPlatform/python-docs-samples
workflows/cloud-client/main.py
Python
apache-2.0
2,637
0.001138
# Copyright 2021 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, ...
ation path. parent = workflows_client.workflow_path(project, location, workflow) # Execute the workflow. response = execution_client.create_execution(request={"parent": parent}) print(f"Created execution: {response.name}")
# Wait for execution to finish, then print results. execution_finished = False backoff_delay = 1 # Start wait with delay of 1 second print('Poll every second for result...') while (not execution_finished): execution = execution_client.get_execution(request={"name": response.name}) ex...
kitizz/edge3d-paper
src/SandBox.py
Python
gpl-3.0
23,475
0.004047
''' SandBox.py ---------- Code that I was using to experiment with and understand how edges behaved. Very raw, a bit of a mess. Read at your own peril. I've included it in the name of being open, and would be a good place to start if anyone wanted to understand the algorithms with the help of Nutmeg for visualization. ...
@jit(no
python=True) def find_close_rays(Cs, Qs, frames, ind, eps=1e-3, min_angle=np.pi/6, min_depth=0.1, max_depth=np.inf, cone=False): c = Cs[ind] q = Qs[ind] frame = frames[ind] N = Cs.shape[0] sel = empty(N, np.int64) j = 0 for i in range(N): if frames[i] == frame: continu...
umitproject/network-admin
netadmin/plugins/utils.py
Python
agpl-3.0
1,010
0.009901
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Adriano Monteiro Marques # # Author: Amit Pal <amix.pal@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, ei...
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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along wit...
ser def get_user_objects(user_object,widget): if user_object==None: user_name = widget.user else: user_name = User.objects.get(username = user_object) return user_name
C4ptainCrunch/libulb
libulb/catalog/course.py
Python
bsd-3-clause
3,809
0.002371
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import requests from bs4 import BeautifulSoup import re import six from libulb.tools import Slug class Course: def __init__(self, slug, year, infos): self.slug = slug self.year = year self._fill(infos) ...
f __repr__(self): return self.__unicode__().encode('utf-8') if six.PY2 else self.__unicode__() d
ef __unicode__(self): if self.credits: return "<Course {}: {} ({} crédits)>".format(self.slug, self.name, self.credits) else: return "<Course {}: {}>".format(self.slug, self.name) @classmethod def get_from_slug(cls, slug, year): slug = Slug.match_all(slug) ...
RedHatQE/cfme_tests
cfme/tests/ansible/test_embedded_ansible_actions.py
Python
gpl-2.0
9,360
0.003205
import fauxfactory import pytest from cfme import test_requirements from cfme.control.explorer.policies import VMControlPolicy from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.services.myservice import MyService from cfme.utils.a...
f_exists() @pytest.fixture(scope="module") def policy_for_testing(appliance, full_template_vm_modscope, provider, ansible_action): vm = full_template_vm_modscope policy = appliance.collections.policies.create( VMControlPolicy, fauxfactory.gen_alpha(
), scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name) ) policy.assign_actions_to_event("Tag Complete", [ansible_action.description]) policy_profile = appliance.collections.policy_profiles.create( fauxfactory.gen_alpha(), policies=[policy]) provider.assign_policy_pro...
Stanford-Online/edx-ora2
openassessment/fileupload/backends/swift.py
Python
agpl-3.0
3,388
0.001476
''' Add in /edx/app/edxapp/edx-platform/lms/envs/aws.py: ORA2_SWIFT_URL = AUTH_TOKENS["ORA2_SWIFT_URL"] ORA2_SWIFT_KEY = AUTH_TOKENS["ORA2_SWIFT_KEY"] Add in /edx/app/edxapp/lms.auth.json "ORA2_SWIFT_URL": "https://EXAMPLE", "ORA2_SWIFT_KEY": "EXAMPLE", ORA2_SWIFT_KEY should correspond to Meta Temp-Url-Key configure ...
ettings() try: temp_url = swiftclient.utils.generate_temp_url( path='/v%s%s/%s/%s' % (SWIFT_BACKEND_VERSION, url.path, bucket_name, key_name), ke
y=key, method='PUT', seconds=self.UPLOAD_URL_TIMEOUT ) return '%s://%s%s' % (url.scheme, url.netloc, temp_url) except Exception as ex: logger.exception( u"An internal exception occurred while generating an upload URL." ...
zhaomr13/fruit
tests/test_this_module.py
Python
gpl-2.0
247
0
import fruit print locals() print fruit.utils.pathformat.prefix("hello/good") print fruit.utils.pathformat.prefix("good") print fruit.utils.pat
hforma
t.suffix("hello/good") print fruit.utils.pathformat.suffix("good") a = 'hello my name is zhaomr'
xkcd1253/Mimi
flask/lib/python2.7/site-packages/flask_wtf/i18n.py
Python
gpl-2.0
1,803
0
# coding: utf-8 """ flask_wtf.i18n ~~~~~~~~~~~~~~ Internationalization support for Flask WTF. :copyright: (c) 2013 by Hsiaoming Yang. """ from flask import _request_ctx_stack from wtforms.ext.i18n.utils import messages_path from flask.ext.babel import get_locale from speaklater import make_lazy_strin...
nslations(): """Returns the correct gettext translations. Copy from flask-babel with some modifications. """ ctx = _request_ctx_stack.top if ctx is None: return None # babel should be in extensions for get_l
ocale if 'babel' not in ctx.app.extensions: return None translations = getattr(ctx, 'wtforms_translations', None) if translations is None: dirname = messages_path() translations = support.Translations.load( dirname, [get_locale()], domain='wtforms' ) ctx.w...
SeaFalcon/Musicool_Pr
apps/music_database.py
Python
apache-2.0
622
0.037162
# -*- coding: utf-8 -*- # [{time: value(button)}{}] #time 함수 해서time 저장 class Database(object): def __init__(self): self.music_database = [] #button은 키코드, timing은 현재시간. def start_music(self,button, timing): self.music_database.append({timing: button}) def put(self, storage): self....
] start_music(85,"10:
00:01",music_database) start_music(90,"10:00:04",music_database) print music_database
cdubz/timestrap
core/migrations/0004_auto_20180204_1439.py
Python
bsd-2-clause
553
0
# Generated by Django 2.0.1 on 2018-02-04 19:39 from django.db import migr
ations, models class Migration(migrations.Migration): dependencies = [("core", "0003_auto_20171001_1018")] operations = [ migrations.AddField( model_name="entry", name="datetime_end", field=models.DateTimeField(blank=True, null=True), ), migrations...
nk=True, null=True), ), ]
tchellomello/home-assistant
tests/components/bond/test_fan.py
Python
apache-2.0
9,312
0.001933
"""Tests for the Bond fan device.""" from datetime import timedelta from typing import Optional from bond_api import Action, DeviceType, Direction from homeassistant import core from homeassistant.components import fan from homeassistant.components.fan import ( ATTR_DIRECTION, ATTR_SPEED, ATTR_SPEED_LIST,...
ests that the device is registered with custom speed list if number of supported speeds differs form 3.""" await setup_platform( hass, FAN_DOMAIN, ceiling_fan("name-1"), bond_device_id="test-device-id", props={"max_speed": 6}, ) actual_speeds = hass.states.get("fan.n...
, ] with patch_bond_device_state(): with patch_bond_action() as mock_set_speed_low: await turn_fan_on(hass, "fan.name_1", fan.SPEED_LOW) mock_set_speed_low.assert_called_once_with( "test-device-id", Action.set_speed(1) ) with patch_bond_action() as mock_...
qqalexqq/monkeys
app.py
Python
mit
737
0
"""Monkeys app exercise.""" import os import logging from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.menu import Menu import views def create_app(name_handler, config_object): """Application factory.""
" app = Flask(name_handler) app.config.from_object(config_object) # Imports db and all models-related things from models import db db.init_app(app) Bootstrap(app) Menu(app) app.register_blueprint(views.bp_monkey) if os.environ.get('HEROKU') is not None: stream_handler = ...
euphorie/Euphorie
src/euphorie/client/tests/test_model.py
Python
gpl-2.0
20,931
0.001386
# coding=utf-8 from AccessControl.PermissionRole import _what_not_even_god_should_do from datetime import timedelta from euphorie.client import config from euphorie.client import model from euphorie.client.tests.database import DatabaseTests from euphorie.testing import EuphorieIntegrationTestCase from plone import api...
e=u"Session", zodb_path="survey", account=account) session.add(survey) session.flush() return (session, survey) class SurveySessionTests(EuphorieIntegrationTestCase): def test_iface(self): """SurveySessions are marked by the ISurveySession interface""" survey = createSurvey()[-1] ...
l.ISurveySession.providedBy(survey)) def test_is_archived(self): """Verify that a session is archived when the archived attribute is set and it is in the past """ session = model.SurveySession() self.assertIsNone(session.archived) self.assertFalse(session.is_archived...
saltstack/salt
salt/modules/ebuildpkg.py
Python
apache-2.0
39,670
0.001235
""" Support for Portage .. important:: If you feel that Salt should be using this module to manage packages on a minion, and it is using a different module (or gives an error similar to *'pkg.install' is not available*), see :ref:`here <module-provider-override>`. :optdepends: - portage Python adap...
dded to make this behaviour optional, defaulting to off. .. seealso:: ``ebuild.ex_mod_init`` is called automatically when a state invokes a pkg state on a Gentoo system. :py:func:`salt.states.pkg.mod_init` ``ebuild.ex_mod_init`` uses ``portage_config.enforce_nice_config`` to do ...
CLI Example: .. code-block:: bash salt '*' pkg.ex_mod_init """ if __salt__["config.get"]("ebuild.enforce_nice_config", False): __salt__["portage_config.enforce_nice_config"]() return True def latest_version(*names, **kwargs): """ Return the latest version of the named pack...
odoo-arg/odoo_l10n_ar
l10n_ar_account_check_sale/__manifest__.py
Python
agpl-3.0
1,674
0
# -*- coding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # b
y 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 F
ITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################...
mbuhot/mbuhot-euler-solutions
python/problem-001.py
Python
mit
857
0.01867
#! /usr/bin/env python #if we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. def BruteForceSolution(): multiplesOf3 = range(3, 1000, 3) multiplesOf5 = range(5, 1000, 5) multiples...
*5) result = sum(multiplesOf3) + sum(multiplesOf5) - sum(multiplesOfBoth) print("Brute force result: %d" % result) def
MathSolution(): def SumOfArithmeticSequence(a, n): return a * (n + 1) * n // 2 multiplesOf3 = SumOfArithmeticSequence(3, 999 // 3) multiplesOf5 = SumOfArithmeticSequence(5, 999 // 5) multiplesOfBoth = SumOfArithmeticSequence(15, 999 // 15) result = multiplesOf3 + multiplesOf5 - multiplesOfBoth print...
N3evin/AmiiboAPI
routes/amiibo.py
Python
mit
5,303
0.001131
from flask import Blueprint, request, jsonify, abort from amiibo.amiibo import AmiiboHex, GameSeriesHex, CharacterHex, VariantHex, AmiiboTypeHex, AmiiboModelHex, AmiiboSeriesHex, Hex from amiibo.manager import AmiiboManager from amiibo.filterable import AmiiboCollection amiiboApp = Blueprint("amiibo", __name__) amii...
miibosfull elif 'showgames' in args: if filters != {}: result = amiibo_manager.amiibosfullwithoutusage.filter(**fil
ters) else: result = amiibo_manager.amiibosfullwithoutusage else: if filters != {}: for amiibo in amiibo_manager.amiibosfull.filter(**filters): result.add(amiibo_manager.amiibos[amiibo.id]) else: result = ami...
pprett/statsmodels
statsmodels/tools/eval_measures.py
Python
bsd-3-clause
8,338
0.003118
# -*- coding: utf-8 -*- """some measures for evaluation of prediction, tests and model selection Created on Tue Nov 08 15:23:20 2011 Author: Josef Perktold License: BSD-3 """ import numpy as np def mse(x1, x2, axis=0): '''mean squared error ''' return np.mean((x1-x2)**2, axis=axis) def rmse(x1, x2, a...
number of observations df_modelwc : int number of parameters including constant Returns ------- aicc : float information criterion Notes ----- A constant has been dropped in comparison to the loglikelihood base information criteria. These should be used to compare f...
np.log(sigma2) return sigma2 + aicc(0, nobs, df_modelwc) / nobs #float division def bic_sigma(sigma2, nobs, df_modelwc, islog=False): '''Bayesian information criterion (BIC) or Schwarz criterion Parameters ---------- sigma2 : float estimate of the residual variance or determinant of S...
Josowsky/Simple-Site-Monitor
scanner_engine/apps.py
Python
mit
143
0
from __future__ import unicode_literals from django.apps import AppConfig
class ScannerEngineConfig(AppConfig): na
me = 'scanner_engine'
Azure/azure-sdk-for-python
sdk/servicebus/azure-servicebus/azure/servicebus/aio/__init__.py
Python
mit
725
0
# ------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------
----------------- from ._servicebus_sender_async import ServiceBusSender from ._servicebus_receiver_async import ServiceBusReceiver from ._servicebus_session_async import ServiceBusSession from ._servicebus_client_async import ServiceBusClient from ._async_auto_lock_renewer import AutoLockRenewer __all__ = [ "Serv...
Session", "AutoLockRenewer", ]
zhangxq5012/sky_engine
mojo/devtools/common/android_gdb/install_remote_file_reader.py
Python
bsd-3-clause
903
0.006645
# 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. import android_gdb.config as config import subprocess import tempfile def install(gsutil, adb='adb'): verification_call_output = subprocess.check_output(...
TE_FILE_READER_DEVICE
_PATH]) if config.REMOTE_FILE_READER_DEVICE_PATH != verification_call_output.strip(): with tempfile.NamedTemporaryFile() as temp_file: subprocess.check_call([gsutil, 'cp', config.REMOTE_FILE_READER_CLOUD_PATH, temp_file.name]) subprocess.check_call([adb, 'push', temp_file....
arokem/scipy
scipy/io/harwell_boeing/tests/test_hb.py
Python
bsd-3-clause
2,366
0.000845
from __future__ import division, print_function, absolute_import from io import StringIO import tempfile import numpy as np from numpy.testing import assert_equal, \ assert_array_almost_equal_nulp from scipy.sparse import coo_matrix, csc_matrix, rand from scipy.io import hb_read, hb_write SIMPLE = """\ No Ti...
x(r) l = csc_matrix(l) assert_equal(r.indptr, l.indptr) assert_equal(r.indices, l.indices) assert_array_almost_equal_nulp(r.data, l.data, 10000) class TestHBReader(object): def test_simple(self): m = hb_read(StringIO
(SIMPLE)) assert_csc_almost_equal(m, SIMPLE_MATRIX) class TestHBReadWrite(object): def check_save_load(self, value): with tempfile.NamedTemporaryFile(mode='w+t') as file: hb_write(file, value) file.file.seek(0) value_loaded = hb_read(file) assert_csc_al...
fadushin/esp8266
micropython/neolamp/neolamp/scheduler.py
Python
bsd-2-clause
5,621
0.009251
# # Copyright (c) dushin.net All Rights Reserved # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the foll...
dules, color_specs, sleep_ms=1342, verbose=False) : core.task.TaskBase.__init__(self, sleep_ms) self.lamp = lamp self.tzd = tzd self.schedules = schedules self.color_specs = color_specs self.verbose = verbose self.current_schedule_name = None self.current_...
es(self, schedules) : self.schedules = schedules def perform(self) : localtime = self.get_localtime() secs = Scheduler.secs_since_midnight(localtime) (_year, _month, _mday, _hour, _minute, _second, wday, _yday) = localtime seq = self.get_current_seq(secs, wday + 1) i...
dataxu/ansible-modules-core
network/eos/eos_command.py
Python
gpl-3.0
5,314
0.002635
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distribut...
default: null retries: description: - Specifies the number of retries a command should be tried
before it is considered failed. The command is run on the target device every retry and evaluated against the waitfor conditionals required: false default: 10 interval: description: - Configures the interval in seconds to wait between retries of the command. If the comm...
wlerin/streamlink
src/streamlink/plugins/okru.py
Python
bsd-2-clause
3,774
0.001325
# -*- coding: utf-8 -*- import logging import re from streamlink.compat import html_unescape, unquote from streamlink.exceptions import PluginError from streamlink.plugin import Plugin from streamlink.plugin.api import useragents, validate from streamlink.stream import HLSStream, HTTPStream, RTMPStream from streamlink...
'mobile': 144, } @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None @classmethod def stream_weight(cls, key): weight = cls.QUALITY_WEIGHTS.get(key) if weight: return weight, 'okru' return Plugin.stream_weight(key)...
data = self.session.http.get(self.url, schema=self._data_schema) except PluginError: log.error('unable to validate _data_schema for {0}'.format(self.url)) return metadata = data.get('metadata') metadata_url = data.get('metadataUrl') if metadata_url and not me...
ckolumbus/mikidown
mikidown/highlighter.py
Python
mit
4,883
0.001024
import re from PyQt4.QtGui import QSyntaxHighlighter, QColor, QFont, QTextCharFormat from PyQt4.QtCore import Qt from .mdx_strkundr import DEL_RE, INS_RE, STRONG_RE, EMPH_RE class MikiHighlighter(QSyntaxHighlighter): WORDS = r'(?iu)[\w\']+' def __init__(self, parent=None): super(MikiHighlighter, se...
# escape highlights in fenced_block m = self.fenced_block.match(text) self.setCurrentBlockState(0) if self.previousBlockState() != 1: if m: self.setCurrentBlockState(1) else: if m: self.setCurrentBlo
ckState(0) else: self.setCurrentBlockState(1) self.setFormat(0, len(text), self.fenced_format) self.highlightSpellcheck(text)
Schnouki/git-annex-remote-hubic
setup.py
Python
gpl-3.0
1,813
0.001655
#!/usr/bin/env python3 # Copyright (c) 2014-2016 Thomas Jost and the Contributors # # This file is part of git-annex-remote-hubic. # # git-annex-remote-hubic 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, ei...
nses/>. from setuptools import setup, find_packages setup(name="git-annex-remote-hubic", version="0.3.2", description="A git-annex special remote for hubiC", long_description=open("README.md", "r").read(), author="Thomas Jost", author_email="schnouki@schnouki.net", url="https://git...
-hubic", packages=find_packages(), install_requires=[ "python-dateutil", "python-swiftclient>=2.1.0", "rauth>=0.7", ], entry_points={ "console_scripts": [ "git-annex-remote-hubic = hubic_remote.main:main", "git-annex-remote-hubi...
rectory-school/rectory-apps
paw/migrations/0002_auto_20150119_1938.py
Python
mit
525
0.001905
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import models, migrations import paw.models class Migration(migrations.Migration): dependencies = [ ('paw', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pageicon', name='display_icon'...
width', upload_to=paw.models.iconUploadTo), preserve_default=True, ), ]
bob123bob/Sick-Beard
sickbeard/show_name_helpers.py
Python
gpl-3.0
9,869
0.008613
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
numseasonsSQlResult = myDB.select("SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and season != 0", [episode.show.tvdbid]) numseasons = int(numseasonsSQlResult[0][0]) numepisodesSQlResult = myDB.select("SELECT COUNT(episode) as numepisodes FROM tv_episodes WHERE showid = ? and s...
pisode.airdate != datetime.date.fromordinal(1): epStrings = [str(episode.airdate)] else: epStrings = ["S%02iE%02i" % (int(episode.season), int(episode.episode)), "%ix%02i" % (int(episode.season), int(episode.episode))] # for single-season shows just search for the show name ...
vrcmarcos/elasticmock
tests/fake_elasticsearch/test_index.py
Python
mit
2,017
0.001487
# -*- coding: utf-8 -*- from tests import
TestElasticmock, INDEX_NAME, DOC_TYPE, BODY UPDATED_BODY = { 'author': 'vrcmarcos', 'text': 'Updated Text' } class TestIndex(TestElasticmock): def test_should_index_document(self): data = self.es.index(index=INDEX_NAME, doc_type=DOC_TYPE, body=BODY) self.assertEqual(DOC_TYPE, data.get('...
ssertTrue(data.get('created')) self.assertEqual(1, data.get('_version')) self.assertEqual(INDEX_NAME, data.get('_index')) def test_should_index_document_without_doc_type(self): data = self.es.index(index=INDEX_NAME, body=BODY) self.assertEqual('_doc', data.get('_type')) sel...
opendatapress/open_data_press
tests/dummy.py
Python
mit
2,439
0.00082
# -*- coding: utf-8 -*- # # Dummy parameters for models created in unit tests # from datetime import datetime credentials = '''{ "invalid": false, "token_uri": "https://accounts.google.com/o/oauth2/token", "refresh_token": "", "client_id": "351298984682.apps.googleusercontent.com", "token_expiry": "2050-11-...
'google_locale': u'en-GB', 'google_name': u'Test User', 'google_picture_url': u'https://lh3.googleusercontent.com/image.png', 'last_login_at': datetime.now(), 'modified_at': datetime.now(), 'profile_email': u'test.user@email.com', ...
profile_slug': 'test-user', 'profile_web_address': 'http://test-user.com', } # Params for a valid data source record # Except for DataSource.user which must be defined within tests data_source = { 'created_at': datetime.now(), 'description': u'A Dummy Data Source', 'google...
angelsanz/linkstore
linkstore/links.py
Python
mit
6,633
0.001055
import os from os import path import sqlite3 from .link import Link class Links(object): def __init__(self): self._links = {} def add(self, link): self._links[link.url] = link def find_by_tag(self, tag): return [link for link in self._links.values() if tag in link.tags] def...
: return self._links[url] class SqliteLinks(
object): def __init__(self, table_gateways): self._links_table = table_gateways['links'] self._tags_table = table_gateways['tags'] def add(self, link): self._links_table.save(link.url, link.date) self._tags_table.reset_tags(link.url, link.tags) def find_by_tag(self, tag): ...
DanielDeychakiwsky/python-machine-learning
src/linear_regression/gradient_descent/calculations.py
Python
mit
633
0
from math import pow # u
se weights for slope and intercept def predict(x, slope, intercept): return (slope * x) + intercept def calculate_y_hats(inputs, slope, intercept): return [predict(x, slope, intercept) for x in inputs] def calculate_total_mean_squared_error(inputs, outputs, slope, intercept, n): total_error = 0 y_ha...
return total_error / n def calculate_k(x, y): if len(x) == len(y): return len(x) else: raise Exception('could not calculate "n"')
DrClockwork/H5PP
h5pp/models.py
Python
gpl-2.0
9,008
0.004218
from django.core.urlresolvers import reverse from django.db import models # Stores information about what h5p uses what libraries class h5p_contents_libraries(models.Model): content_id = models.PositiveIntegerField(null=False) library_id = models.PositiveIntegerField(null=False) dependency_type = models....
help_text='The translations defined in json format') class Meta: db_table = 'h5p_libraries_langu
ages' ordering = ['language_code', 'library_id'] verbose_name = 'Library-language' verbose_name_plural = 'Libraries-languages' unique_together = (('library_id', 'language_code')) def __unicode__(self): return self.language_code def __str__(self): return "%s" % (...
desihub/desisim
py/desisim/pixsim.py
Python
bsd-3-clause
30,517
0.006455
""" desisim.pixsim ============== Tools for DESI pixel level simulations using specter """ from __future__ import absolute_import, division, print_function import sys import os import os.path import random from time import asctime import socket import astropy.units as u import numpy as np import desimodel.io impo...
ereal_time(). # It's the initialization of astropy.time.Time() itself that makes the call. from desiutil.iers import freeze_iers from astropy.time import Time def simulate_exposure(simspecfile, rawfile, cameras=None, ccdshape=None, simpixfile=None, addcosmics=None, comm=
None, **kwargs): """ Simulate frames from an exposure, including I/O Args: simspecfile: input simspec format file with spectra rawfile: output raw data file to write Options: cameras: str or list of str, e.g. b0, r1, .. z9 ccdshape: (npix_y, npix_x) primarily us...
valmynd/MediaFetcher
src/plugins/youtube_dl/youtube_dl/extractor/tumblr.py
Python
gpl-3.0
6,399
0.030023
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_str from ..utils import ( ExtractorError, int_or_none, urlencode_postdata ) class TumblrIE(InfoExtractor): _VALID_URL = r'https?://(?P<blog_name>[^/?#&]+)\.tumblr\.com/(?:post|video)/(...
: { 'format': 'hd', }, }, { 'url': 'http://naked-yogi.tumblr.com/post/118312946248/naked-smoking-stretching', 'md5': 'de07e5211d60d4f3a2c3df757ea9f6ab', 'info_dict': { 'id': 'Wmur', 'ext': 'mp4', 'title': 'naked smoking & stretching', 'upload_date': '20150506', 't
imestamp': 1430931613, 'age_limit': 18, 'uploader_id': '1638622', 'uploader': 'naked-yogi', }, 'add_ie': ['Vidme'], }, { 'url': 'http://camdamage.tumblr.com/post/98846056295/', 'md5': 'a9e0c8371ea1ca306d6554e3fecf50b6', 'info_dict': { 'id': '105463834', 'ext': 'mp4', 'title': 'Cam Damage-HD...
spacetelescope/stsci.tools
lib/stsci/tools/fitsdiff.py
Python
bsd-3-clause
1,825
0.000548
"""fitsdiff is now a part of Astropy. Now this module just provides a wrapper around astropy.io.fits.diff for backwards compatibility with the old interface in case anyone uses it. """ import os import sys from astropy.io.fits.diff import FITSDiff from astropy.io.fits.scripts.fitsdiff import log, main def fitsdiff(...
e_list): """Parse a comma-separated list of values, or a filename (starting with @) containing a list value on each line. """ if name_list and name_list[0] == '@': value = name_list[1:] if not os.path.exists(value): log.warning('The file %s does not exist' % value) ...
try: return [v.strip() for v in open(value, 'r').readlines()] except IOError as e: log.warning('reading %s failed: %s; ignoring this file' % (value, e)) else: return [v.strip() for v in name_list.split(',')] if __name__ == "__main__": sys.e...
rishig/zulip
zerver/views/messages.py
Python
apache-2.0
69,921
0.003661
from django.utils.translation import ugettext as _ from django.utils.timezone import now as timezone_now from django.conf import settings from django.core import validators from django.core.exceptions import ValidationError from django.db import connection, IntegrityError from django.http import HttpRequest, HttpRespon...
operty, we hold all the `by_*` # methods to the same criterion. See the class's block comment # for details. # We have to be careful here because we're letting users call a method # by name! The prefix 'by_' prevents it from colliding with builtin # Python __magic__ stuff. ...
place('-', '_') method = getattr(self, method_name, None) if method is None: raise BadNarrowOperator('unknown operator ' + operator) if negated: maybe_negate = not_ else: maybe_negate = lambda cond: cond return method(query, operand, maybe_ne...
DragonRoman/rhevm-utils
monitoring/rhev-nagios-table-host-mem.py
Python
gpl-3.0
2,283
0.003504
#!/usr/bin/env python # # Author: Pablo Iranzo Gomez (Pablo.Iranzo@redhat.com) # # Description: Script for monitoring host Memory status and VM's rhevm-sdk # api and produce NAGIOS valid output # # Requires rhevm-sdk to work # # This program is free software; you can redistribute it and/or modify # it under the terms o...
Foundation, version 2 of the License. # # 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. import sys import optparse from ovi...
""" RHEV-nagios-table-host-mem output is a script for querying RHEVM via API to get host status It's goal is to output a table of host/vm status for simple monitoring via external utilities """ # Option parsing p = optparse.OptionParser("rhev-nagios-table-host-mem.py [arguments]", description=description) p.add_opt...
django-json-api/rest_framework_ember
rest_framework_json_api/django_filters/backends.py
Python
bsd-2-clause
5,902
0.003219
import re from django_filters.rest_framework import DjangoFilterBackend from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings from rest_framework_json_api.utils import undo_format_field_name class DjangoFilterBackend(DjangoFilterBackend): """ A Django-style O...
st of FilterSet keys :param filterset_class: :py:class:`django_filters.rest_framework.FilterSet` :raises ValidationError: if key not in FilterSet keys or no FilterSet. """ for k in keys: if (not filterset_class) or (k not in filterset_class.base_filters): rais...
ilterset(self, request, queryset, view): """ Sometimes there's no `filterset_class` defined yet the client still requests a filter. Make sure they see an error too. This means we have to `get_filterset_kwargs()` even if there's no `filterset_class`. """ # TODO: .base_filt...
texttheater/produce
t/test_pretend_up_to_date.py
Python
mit
763
0.003932
from prodtest import ProduceTestCase class PretendUpToDateTest(ProduceTestCase): def test_pretend_up_to_date(self):
# a # | # b # / \ # c d normal = lambda: self.produce('a') pretending = lambda: self.produce('a', **{'-u':
'b'}) self.assertDirectoryContents(('produce.ini',)) self.assertUpdates((), normal, ('a', 'b', 'c', 'd'), ()) self.assertUpdates(('c',), normal, ('a', 'b'), ('c', 'd')) self.assertUpdates(('c',), pretending, (), ('a', 'b', 'c', 'd')) self.assertUpdates((), normal, ('a', 'b'), ('c...
firebitsbr/ZCR-Shellcoder
lib/encoder/linux_x86/xor_random.py
Python
gpl-3.0
2,327
0.037387
#!/usr/bin/env python ''' ZCR Shellcoder ZeroDay Cyber Research Z3r0D4y.Com Ali Razmjoo ''' import random,binascii,string chars = string.digits + string.ascii_letters def start(shellcode,job): if 'chmod(' in job: t = True eax = str('0x0f') while t: eax_1 = binascii.b2a_hex(''.join(random.choice(chars) for i...
(l,command) shellcode = start + middle + end if 'd
ir_create(' in job: shellcode = 'N' + shellcode if 'download_execute(' in job: shellcode = 'N' + shellcode if 'download(' in job: shellcode = 'N' + shellcode if 'exec(' in job: shellcode = 'N' + shellcode if 'file_create(' in job: shellcode = 'N' + shellcode if 'script_executor(' in job: shellcode = 'N...
jobliz/solid-state-kinetics
ssk/models/theoretical.py
Python
mit
1,630
0.025767
from __future__ import division import numpy as np def iP2(a): return a**(1/2) def iP3(a): return a**(1/3) def iP4(a): return a**(1/4) def iPN(a, n=None): return a**(1/n) def iA2(a): return (-np.log(1-a))**(1/2) def iA3(a): return (-np.log(1-a))**(1/3) def iA4(a): return (-np.log(...
(a, n=None): return (-np.log(1-a))**(1/n) def iB1(a): return np.log(a/(1-a)) def iR2(a): return 1 - (1 - a)**(1/2) def iR3(a): return 1 - (1 - a)**(1/3) def iD1(a): return a**2 def iD2(a): return ((1-a) * np.log(1-a)) + a def iD3(a): return (1 - (1-a)**(1/3)) ** 2 def iD4(a): ...
-a)**-1 - 1 def iF3(a): return 0.5 * ((1-a)**-2 - 1) def dP2(a): return 2*a**(1/2) def dP3(a): return 3*a**(2/3) def dP4(a): return 4*a**(3/4) def dA2(a): return 2 * (1-a) * (-np.log(1-a))**(1/2) def dA3(a): return 3 * (1-a) * (-np.log(1-a))**(2/3) def dA4(a): return 4 * (1-a) * (-np....
UB-Heidelberg/UBHD-OMPArthistorikum
languages/plural-ru.py
Python
gpl-3.0
743
0.001869
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'выбрана': ['выбраны', 'выбрано'], 'запись': ['записи', 'записей'], 'изменена': ['изменены', 'изменено'], 'строка': ['строки', 'строк'], 'удалена': ['удалены', 'удалено'], 'день': ['дня',...
['минуты', 'минут'], 'секунду':
['секунды', 'секунд'], }
hastef88/andes
modules/andes-core/systests/etc/bin/fail.py
Python
apache-2.0
3,242
0.005244
#!/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 #...
ore_true", default=False, help="run tests after failures, don't stop") (options, args) = parser.parse_args() # determine command to run if (options.test != None): cmd = (BASE_CMD % ("-Dtest="+options.test)) else: cmd = (BASE_CMD % ("")) run_forever = options...
ompile("BUILD SUCCESSFUL") done = False while (run_forever or not (len(failed_runs) > 0)): iteration = iteration + 1 if (run_forever): extra_text = (", %d failures so far: %s:" % (len(failed_runs), failed_runs)) else: extra_text = "" print ("%s Test run %...
antoniodemora/git-cola
qtpy/__init__.py
Python
gpl-2.0
5,141
0.000778
# -*- coding: utf-8 -*- # # Copyright © 2009- The Spyder Development Team # Copyright © 2014-2015 Colin Duquesnoy # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) """ **QtPy** is a shim over the various Python Qt bindings. It is used to write Qt binding indenpendent libraries or applicat...
" import os import platform import sys # Version of QtPy f
rom ._version import __version__ class PythonQtError(RuntimeError): """Error raise if no bindings could be selected.""" pass class PythonQtWarning(Warning): """Warning if some features are not implemented in a binding.""" pass # Qt API environment variable name QT_API = 'QT_API' # Names of the ex...
PaulWay/insights-core
insights/core/specs.py
Python
apache-2.0
5,582
0.001971
import re import os import logging from collections import defaultdict from insights.config.static import get_config from insights.config import AnalysisTarget, META_FILE_LIST, CommandSpec logger = logging.getLogger(__name__) logger.setLevel(logging.FATAL) class SpecMapper(object): """ This class wraps a tar...
= unroot
ed_files - commands if logger.level == logging.DEBUG: logger.debug("\n".join(uf for uf in sorted(unrooted_files))) for symbolic_name, spec_group in file_map.iteritems(): for spec in spec_group.get_all_specs(): # Usually just one item in paths is_command = isinst...
masom/doorbot-api-python
doorbot/views/dashboard/forms/login.py
Python
mit
333
0
# -*- coding: utf-8 -*- from wtforms import Form, PasswordField, StringField, validators class PasswordLoginForm(Form): email = StringField('Email', [validators.Email]) passw
ord = PasswordField('Password', [validators.Length(m
in=4)]) class ForgotPasswordForm(Form): email = StringField('Email', [validators.Email])
openmash/medsphere-test
select_provider.sikuli/select_provider.py
Python
apache-2.0
214
0.009346
doubleClick("1370381210737.png") click("1370381239650.png") wheel(Pattern("1
370381239650.png").targetOffset(-1,30), WHEEL_DOWN, 7) click(Pattern("mary_hager.png").targetOffset(97,
-2)) find("1370381955817.png")