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
darkwing/kuma
vendor/packages/mock/tests/testpatch.py
Python
mpl-2.0
55,260
0.002678
# Copyright (C) 2007-2012 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # http://www.voidspace.org.uk/python/mock/ import os import sys import unittest2 as unittest from mock.tests import support from mock.tests.support import inPy3k, SomeClass, is_instance, callable from mock import ...
] def __iter__(self): return iter(self.values) class PatchTest(unittest.TestCase): def assertNotCallable(self, obj, magic=True): MockClass = NonCallableMagicMock if not magic: MockClass = NonCallableMock self.assertRaises(TypeError, obj) self.assertTrue(...
attribute = sentinel.Original @patch.object(Something, 'attribute', sentinel.Patched) def test(): self.assertEqual(Something.attribute, sentinel.Patched, "unpatched") test() self.assertEqual(Something.attribute, sentinel.Original, "patch not restor...
simonluijk/django-blog
setup.py
Python
bsd-3-clause
2,546
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import re import os import sys def get_version(package): """ Return package version as listed in `__
version__` in `init.py`.
""" init_py = open(os.path.join(package, '__init__.py')).read() return re.match("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) def get_packages(package): """ Return root package and all sub-packages. """ return [dirpath for dirpath, dirnames, filenames in os.walk(packa...
ghofranehr/foobar
manage.py
Python
bsd-3-clause
1,092
0.002747
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask.ext.script import Manager, Shell, Server from flask.ext.migrate import MigrateCommand from foobar.app import create_app from foobar.user.models import User from foobar.settings import DevConfig, ProdConfig from foobar.datab...
est(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server()) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', M
igrateCommand) if __name__ == '__main__': manager.run()
davidedmundson/telepathy-hangups
telepathy/interfaces.py
Python
lgpl-2.1
1,435
0.000697
# telepathy-python - Base classes defining the interfaces of the Telepathy framework # # Copyright (C) 2005, 2006 Collabora Limited # Copyright (C) 2005, 2006 Nokia Corporation # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as pub...
NN_INTERFACE = CONNECTION CHANNEL_INTERFACE = CHANNEL CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER # More backwards compatibility CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AV
ATARS CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
UMDIEEE/ieee-web
migrations/versions/5ddd839de57c_.py
Python
gpl-3.0
312
0.00641
"""empty message Revision ID: 5ddd839de57c Revises: 0b1bd71fb58d Create Date: 2016-02-22 07:40:21.142754 """ # revision identifiers, used by Alembic. revision = '5ddd839de57c' down_revision = '0b1bd71fb58d' from alembic import op import sqlalchemy as sa def upgrade(): pass def downgrade(): pas
s
Arno-Nymous/pyload
module/plugins/internal/Crypter.py
Python
gpl-3.0
3,435
0.001164
# -*- coding: utf-8 -*- from .Base import Base from .misc import parse_name, safename class Crypter(Base): __name__ = "Crypter" __type__ = "crypter" __version__ = "0.20" __status__ = "stable" __pattern__ = r'^unmatchable$' __config__ = [("activated", "bool", "Activated", True), ...
def _create_packages(self): """ Create new packages from self.packages """ pack_folder = self.pyfile.package().folder pack_password = self.pyfile.package().password pack_queue = self.pyfile.packag
e().queue folder_per_package = self.config.get('folder_per_package', "Default") if folder_per_package == "Default": folder_per_package = self.pyload.config.get( 'general', 'folder_per_package') else: folder_per_package = folder_per_package == "Yes" ...
jcass77/mopidy
tests/audio/test_actor.py
Python
apache-2.0
22,260
0.00009
import threading import unittest from unittest import mock import pykka from mopidy import audio from mopidy.audio.constants import PlaybackState from mopidy.internal import path from mopidy.internal.gi import Gst from tests import dummy_audio, path_to_data_dir # We want to make sure both our real audio class and t...
] class AudioEventTest(BaseTest): def setUp(self): # noqa: N802 super().setUp() self.audio.enable_sync_handler().get() self.listener = DummyAudioListener.start().proxy() def tearDown(self): # noqa: N802 super().tearDown() def assertEvent(self, event, **kwargs): # noqa:...
ert (event, kwargs) not in self.listener.get_events().get() # TODO: test without uri set, with bad uri and gapless... # TODO: playing->playing triggered by seek should be removed # TODO: codify expected state after EOS # TODO: consider returning a future or a threading event? def test_state_change...
ucb-sejits/ast_tool_box
test/sample.py
Python
mit
101
0.009901
impor
t ast
def square_it(x): return x * x class Transformer1(ast.NodeTransformer): pass
aoyono/sicpy
Chapter2/exercises/exercise2_60.py
Python
mit
3,259
0.002762
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60 """ from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list from Chapter2.themes.sequences_as_conventional_interfaces import accumulate def element_of_set(x, set): """...
tes intersection of set1 and set2""" if set1 is nil or set2 is nil: return nil if element_of_set(car(set1), set2): return cons(car(set1), intersection_set(cdr(set1), set2)) return intersection_set(cdr(set1), set2) def run_the_magic(): s1 = lisp_list(2, 3, 2, 1, 3, 2, 2) s2 = lisp_l...
tion_set(s1, s2)) print_lisp_list(union_set(s1, s2)) from timeit import Timer t1_element_of = Timer(stmt='element_of_set(3, %(s1)s)' % locals(), setup='from Chapter2.exercise2_60 import element_of_set') t2_element_of = Timer(stmt='element_of_set(3, %(s1)s)' % locals(), ...
chriskiehl/Gooey
gooey/gui/components/widgets/bases.py
Python
mit
9,873
0.001823
import re from functools import reduce from typing import Optional, Callable, Any, Type, Union import wx # type: ignore from gooey.gui import formatters, events from gooey.gui.util import wx_util from gooey.python_bindings.types import FormField from gooey.util.functional import getin, ifPresent from gooey...
idget created # - assumes those widgets are all created in `getWidget` # - all the above make for extremely awkward lifecycle management # - no clear point at which binding is correct. # - I think the core problem here is that I couple the interface # for shared presentation layo...
broken apart. # - presentation can be ad-hoc or composed # - behavioral just needs a typeclass of get/set/format for Gooey's purposes widget_class = None # type: ignore def __init__(self, parent, widgetInfo, *args, **kwargs): super(TextContainer, self).__init__(parent, *args, **k...
KlubJagiellonski/Politikon
events/tests.py
Python
gpl-2.0
41,180
0.001142
# -*- coding: utf-8 -*- """ Test events module """ from datetime import timedelta from freezegun import freeze_time import json from django.contrib.auth.models import AnonymousUser from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from django....
t.price_for_outcome(Bet.YES, Bet.SELL) self.assertEqual(event.current_sell_for_price, outcome2) outcome3 = event.price_for_outcome(Bet.NO) self.assertEqual(event.current_buy_against_price, outcome3) outcome4 = event.price_for_outcome(Bet.NO, Bet.SELL) self.assertEqual(event.curre...
OPS', 'MY MISTAKE') # TODO: FIXME # teraz nie interpolujemy punktów ;( # @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, # CELERY_ALWAYS_EAGER=True, # BROKER_BACKEND='memory') # def test_get_chart_points(self): # """ # Get chart ...
shakamunyi/neutron-vrrp
neutron/neutron_plugin_base_v2.py
Python
apache-2.0
14,707
0
# Copyright 2011 VMware, 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 ...
ork): """Create a network. Create a network, which represents an L2 network segment which can have a set of subnets and ports associated with it. :param context: neutron api request context :param network: dictionary describing the network, with keys as ...
AP` object in :file:`neutron/api/v2/attributes.py`. All keys will be populated. """ pass @abc.abstractmethod def update_network(self, context, id, network): """Update values of a network. :param context: neutron api request cont...
JessicaGarson/MovieSentiment
baggedmovies.py
Python
unlicense
1,258
0.011129
#bagging to make it better import pandas as pd import numpy as np from ggplot import * from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import Logis
ticRegression from sklearn.cross_validation import cross_val_score from sklearn.metrics import auc_score train = pd.read_csv('/Users/jessicagarson/Downloads/Movie Reviews/train.csv') test = pd.read_csv('/Users/jessicagarson/Downloads/Movie Reviews/test.csv') def bagmodel(s): vectorizer = CountVectorizer() X_d...
es,:] X_train = vectorizer.transform(s.Phrase) model = LogisticRegression().fit(X_train, list(s.Sentiment)) return model models = [] for i in range(5): print i models.append(bagmodel(train)) from collections import Counter def combination(s): thing = Counter(s) return thing.most_common(1...
msultan/msmbuilder
msmbuilder/tests/test_vmhmm.py
Python
lgpl-2.1
5,110
0.000196
from __future__ import print_function, division import random from itertools import permutations import numpy as np from scipy.stats.distributions import vonmises import pickle import tempfile from sklearn.pipeline import Pipeline from msmbuilder.example_datasets import AlanineDipeptide from msmbuilder.featurizer i...
appatol: match = False break for j in range(numStates): diff = transmat[i, j] - model.transmat_[order[i], order[j]] if abs(diff) > transmattol: match = False break if match: # It match...
= np.array([[0.0], [2.0]]) kappas = np.array([[4.0], [8.0]]) X = [create_timeseries(means, kappas, transmat) for i in range(10)] # For each value of various options, # create a 2 state HMM and see if it is correct. for reversible_type in ('mle', 'transpose'): model = VonMisesHMM(n_states=...
maleficarium/youtube-dl
youtube_dl/extractor/glide.py
Python
unlicense
1,988
0.002012
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import unified_strdate class GlideIE(InfoExtractor): IE_DESC = 'Glide mobile video messages (glide.me)' _VALID_URL = r'https?://share\.glide\.me/(?P<id>[A-Za-z0-9\-=_+]+)' _TEST = { 'url': 'http...
rch_video_url(webpage) thumbnail = self._proto_relative_url(self._search_regex( r'<img[^>]+id=["\']video-thumbnail["\'][^>]+src=(["\'])(?P<url>.+?)\1', webpage, 'thumbnail url', default=None, group='url')) or self._og_search_thumbnail(webpage) uploader = self._search_...
r'<div[^>]+class=["\']info-name["\'][^>]*>([^<]+)', webpage, 'uploader', fatal=False) upload_date = unified_strdate(self._search_regex( r'<div[^>]+class="info-date"[^>]*>([^<]+)', webpage, 'upload date', fatal=False)) return { 'id': video_id, ...
quantumlib/Cirq
cirq-core/cirq/protocols/inverse_protocol_test.py
Python
apache-2.0
2,069
0
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
rse(val, NotImplemented) is NotImplemented assert cirq.inverse(val, 5) == 5 @pytest.mark.parametrize( 'val,inv', ( (ReturnsFive(), 5), (ImplementsReversible(), 6), (SelfInverse(),) * 2, (1, 1), (2, 0.5), (1j, -1j), ((), ()), ([], ()), ...
ects_with_inverse(val, inv): assert cirq.inverse(val) == inv assert cirq.inverse(val, 0) == inv
mohawkhq/mohawk-data-platform
data/urls.py
Python
bsd-3-clause
479
0.010438
from django.conf.urls im
port url, patterns
from data import views urlpatterns = patterns("data.views", url(r"^$", views.IndexView.as_view()), url(r"^a/(?P<application_external_id>[^/]{,255})\.json$", views.ApplicationInstanceListView.as_view()), url(r"^(?P<model_external_id>[^/]{,255})\.json$", views.InstanceListView.as_view()), url(r"^(...
hyphyphyph/lascaux
crepehat/kitchen.py
Python
mit
1,587
0.00063
import os.path from crepehat import SObject class Kitchen(SObject): sources = [] extensions = [] def __init__(self, sources, extensions=None): if not hasattr(sources, "__iter__"): s
ources = [sources] self.sources = sources if extensions and not hasattr(extensions, "__iter__"): extensions = [extensions] self.extensions = extensions
def get(self, path, extensions=None, overridable=True): if self.extensions and extensions != False or extensions: path = os.path.splitext(path)[0] if not hasattr(extensions, "__iter__"): extensions = self.extensions if not overridable: if extensions: ...
ddsc/ddsc-api
ddsc_api/models.py
Python
mit
216
0
# (c) Nelen & Schuurmans. MI
T licensed, see LICENSE.rst. from __future__ import unicode_literals # from django.db import models # from django.utils.translati
on import ugettext_lazy as _ # Create your models here.
Ecogenomics/GTDBNCBI
scripts_dev/type_genome_selection/generate_date_table.py
Python
gpl-3.0
10,985
0.006372
#!/usr/bin/env python3 ############################################################################### # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public L...
gger.info(' - read priority for {:,} species.'.format(len(scraped_sp_priority))) self.logger.info('Reading priority references from LPSN GSS file.') gss_sp_priority = self.parse_lpsn_gss_priorities(lpsn_gss_file) self.logger.info(' - read priority for {:,} species.'
.format(len(gss_sp_priority))) self.logger.info('Scrapped pr
hamzehd/edx-platform
openedx/core/djangoapps/content/course_overviews/tests.py
Python
agpl-3.0
21,034
0.003803
""" Tests for course_overviews app. """ import datetime import ddt import itertools import math import mock import pytz from django.utils import timezone from lms.djangoapps.certificates.api import get_active_web_certificate from lms.djangoapps.courseware.courses import course_image_url from xmodule.course_metadata_u...
_since_epoch(course_overview_cache_miss.enrollment_end), get_seconds_since_epoch(course_overview_cache_hit.enrollment_end), ), ] for (course_value, cache_miss_value, cache_hit_value) in others_to_test: self.assertEqual(course_value, cache_miss_value) s...
nd cached hit courses for course_overview in [course_overview_cache_miss, course_overview_cache_hit]: course_overview_tabs = course_overview.tabs.all() course_resp_tabs = {tab.tab_id for tab in course_overview_tabs} self.assertEqual(self.COURSE_OVERVIEW_TABS, course_resp_tabs...
egid/stratux
test/screen/screen.py
Python
bsd-3-clause
3,003
0.005994
#!/usr/bin/env python from oled.device import ssd1306, sh1106 from oled.render import canvas from PIL import ImageDraw, ImageFont, Image import urllib2 import json import time font2 = ImageFont.truetype('/root/stratux/test/screen/CnC_Red_Alert.ttf', 12) oled = ssd1306(port=1, address=0x3C) with canvas(oled) as dra...
us') getStatusHTML = response.read() getStatusData = json.loads(getStatusH
TML) CPUTemp = getStatusData["CPUTemp"] uat_current = getStatusData["UAT_messages_last_minute"] uat_max = getStatusData["UAT_messages_max"] es_current = getStatusData["ES_messages_last_minute"] es_max = getStatusData["ES_messages_max"] response = urllib2.urlopen('http://localhost/getTowers'...
alanfranz/mock
py/mockchain.py
Python
gpl-2.0
12,065
0.005305
#!/usr/bin/python -tt # by skvidal@fedoraproject.org # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is...
opts.logfile = os.path.join(local_tmp_dir, opts.logfile) if os.path.exists(opts.logfile): os.unlink(opts.logfile)
log(opts.logfile, "starting logfile: %s" % opts.logfile) opts.local_repo_dir = os.path.normpath(local_tmp_dir + '/results/' + cfg + '/') if not os.path.exists(opts.local_repo_dir): os.makedirs(opts.local_repo_dir, mode=0755) local_baseurl="file://%s" % opts.local_repo_dir log(opts.logfile,...
jmatthed/avatar-python
avatar/__init__.py
Python
apache-2.0
90
0.033333
#from configuration.manager import ConfigurationManag
er #config = Configuration
Manager()
837468220/python-for-android
python3-alpha/python3-src/Tools/freeze/checkextensions_win32.py
Python
apache-2.0
6,199
0.00613
"""Extension management for Windows. Under Windows it is unlikely the .obj files are of use, as special compiler options are needed (primarily to toggle the behavior of "public" symbols. I dont consider it worth parsing the MSVC makefiles for compiler options. Even if we get it just right, a specific freeze applicat...
ame(ini),"...", defn = get_extension_defn( mod, ini, prefix ) if defn is not None: # print "Yay - found it!" ret.append( defn ) break # print "Nope!" else: # For not broken! sys.stderr.write("...
(mod)) return ret def get_extension_defn(moduleName, mapFileName, prefix): if win32api is None: return None os.environ['PYTHONPREFIX'] = prefix dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName) if dsp=="": return None # We allow environment variables in the file name ...
Kagami/kisa
lib/twisted/internet/_newtls.py
Python
cc0-1.0
8,938
0.002014
# -*- test-case-name: twisted.test.test_ssl -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ This module implements memory BIO based TLS support. It is the preferred implementation and will be used whenever pyOpenSSL 0.10 or newer is installed (whenever L{twisted.protocols.tls} is impor...
self._tlsWaiting = _TLSDelayed([], ctx, normal) return False startTLS(self, ctx, normal, FileDescriptor) def write(self, bytes): """ Write some bytes to this connection, passing them through a TLS layer if necessary, or discarding them if the
connection has already been lost. """ if self.TLS: if self.connected: self.protocol.write(bytes) elif self._tlsWaiting is not None: self._tlsWaiting.bufferedData.append(bytes) else: FileDescriptor.write(self, bytes) def writeSeque...
deenjohn/TimelineJS
website/core/settings/loc.py
Python
mpl-2.0
279
0.014337
"""Local settings and globals.""" import sys from os.
path import normpath, join from .base import * # Import secrets -- not needed #sys.path.append( # abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg')) #) #from secrets import * # Set static
URL STATIC_URL = '/static'
LLNL/spack
var/spack/repos/builtin/packages/openslide/package.py
Python
lgpl-2.1
803
0.003736
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Openslide(AutotoolsPackage): """Op
enSlide reads whole slide image files.""" homepage = "https://openslide.org/" url = "https://github.com/openslide/openslide/releases/download/v3.4.1/openslide-3.4.1.tar.xz" version('3.4.1', sha256='993803
4dba7f48fadc90a2cdf8cfe94c5613b04098d1348a5ff19da95b990564') depends_on('pkgconfig', type='build') depends_on('openjpeg') depends_on('jpeg') depends_on('libtiff') depends_on('libxml2') depends_on('sqlite@3.6:') depends_on('glib') depends_on('cairo+pdf') depends_on('gdk-pixbuf')
radiantflow/django-comments
tests/testapp/tests/feed_tests.py
Python
bsd-3-clause
1,879
0.009047
from __future__ import absolute_import from xml.etree import ElementTree as ET from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from comments.models import Comment from . import CommentTestCase from ..models import Article cla...
= "http://example.com/~joe/", comment = "A comment for the second site.", site = site_2, ) def test_feed(self): response = self.client.get(self.feed_url) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/rss+x...
mstring(response.content) self.assertEqual(rss_elem.tag, "rss") self.assertEqual(rss_elem.attrib, {"version": "2.0"}) channel_elem = rss_elem.find("channel") title_elem = channel_elem.find("title") self.assertEqual(title_elem.text, "example.com comments") link_elem = ...
adamsumm/CausalMario
HiddenCauses/rescal.py-master/Mario/parse.py
Python
mit
2,164
0.063771
import sys import re import random vevent = re.compile("V\s+([\-\d\w]+)\s+(\w+)") sevent = re.compile("S\s+([\-\d\w]+)\s+([\-\d\w]+)") aevent = re.compile("A\s+([\-\d\w]+)") devent = re.compile("D\s+([\-\d\w]{2,})") cevent = re.compile("C\s+([\-\d\w]+)\s+[\-\d]*\s*([\-\d\w]+)\s+([\-\d\w]+)") animate = ["Goomba","Mario"...
]) for cause in causes: if not effects: print ",".join(cause) + ",None,None,None,None" for effect in effects: print ",".join(cause) + "," + ",".join(effect) causes = [] effects = [] else:
amatch = aevent.search(line) dmatch = devent.search(line) smatch = sevent.search(line) cmatch = cevent.search(line) vmatch = vevent.search(line) if amatch: effects.append(["append",amatch.group(1),"None","None"]) if vmatch: effects.append(["VelChange",vmatch.group(1),"None",vmatch.group(2)])...
WillianPaiva/ycmd
ycmd/server_state.py
Python
gpl-3.0
4,592
0.02635
#!/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...
completer.SupportedFiletypes() ) for supported_filetype in supported_filetypes: self._filetype_completers[ supported_filetype ] = completer return completer def GetFiletypeCompleter( self, current_filetypes ): completers = [ self._GetFiletypeCompleterForFiletype( filetype ) ...
return completer raise ValueError( 'No semantic completer exists for filetypes: {0}'.format( current_filetypes ) ) def FiletypeCompletionAvailable( self, filetypes ): try: self.GetFiletypeCompleter( filetypes ) return True except: return False def FiletypeCompletionUsab...
zjuwangg/scrapy
tests/test_pipeline_files.py
Python
bsd-3-clause
8,013
0.002496
import os import time import hashlib import warnings from tempfile import mkdtemp from shutil import rmtree from twisted.trial import unittest from twisted.internet import defer from scrapy.pipelines.files import FilesPipeline, FSFilesStore from scrapy.item import Item, Field from scrapy.http import Request, Response...
self.assertEqual(result['files'][0]['checksum'], 'abc')
for p in patchers: p.stop() @defer.inlineCallbacks def test_file_expired(self): item_url = "http://example.com/file2.pdf" item = _create_item_with_files(item_url) patchers = [ mock.patch.object(FSFilesStore, 'stat_file', return_value={ 'checksu...
youtube/cobalt
third_party/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py
Python
bsd-3-clause
4,479
0.001116
"""Test that adding, deleting and modifying watchpoints sends the appropriate events.""" from __future__ import print_function import os import time import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestWatchpointEvents (TestBase): ...
.SBFileSpec(self.main_source) break_in_main = target.BreakpointCreateBySourceRegex( '// P
ut a breakpoint here.', self.main_source_spec) self.assertTrue(break_in_main, VALID_BREAKPOINT) # Now launch the process, and do not stop at entry point. process = target.LaunchSimple( None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VAL...
pombredanne/pants
contrib/go/src/python/pants/contrib/go/subsystems/go_import_meta_tag_reader.py
Python
apache-2.0
2,676
0.01009
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import re import re...
memoized_method def get_imported_repo(self, import_path): """Looks for a go-import meta tag for the provided import_path. Returns an ImportedRepo inst
ance with the information in the meta tag, or None if no go-import meta tag is found. """ try: session = requests.session() # TODO: Support https with (optional) fallback to http, as Go does. # See https://github.com/pantsbuild/pants/issues/3503. session.mount("http://", ...
mseln/klufweb
klufweb/feed/migrations/0004_auto_20141229_1211.py
Python
apache-2.0
1,090
0.002752
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.utils.timezone import utc import datetime class Migration(migrations.Migration): dependencies = [
('feed', '0003_auto_20141227_2343'), ] operations = [ migrations.AddField( model_name='newsarticle', name=
'created', field=models.DateTimeField(default=datetime.datetime(2014, 12, 29, 11, 11, 7, 540368, tzinfo=utc), auto_now_add=True), preserve_default=False, ), migrations.AddField( model_name='newsarticle', name='slug', field=models.SlugField(defa...
zb89/pyrogue
console.py
Python
unlicense
1,242
0.024155
from unicurses import * class Console: de
f __init__(self): stdscr = initscr() noecho()
cbreak() curs_set(False) start_color() use_default_colors() init_pair( 0, COLOR_WHITE, COLOR_BLACK) init_pair( 1, COLOR_RED, COLOR_BLACK) init_pair( 2, COLOR_YELLOW, COLOR_BLACK) init_pair( 3, COLOR_GREEN, COLOR_BLACK) init_pair( 4, COLOR_CYAN, COLOR_BLACK) init_pair( 5...
DavidMcDonald1993/ghsom
laplacian.py
Python
gpl-2.0
376
0.007979
# codi
ng: utf-8 # In[9]: import numpy as np import networkx as nx # In[2]: G = nx.karate_club_graph() # In[3]: L = nx.laplacian_matrix(G) # In[4]: L # In[11]: d = np.array([v for k,v in nx.degr
ee(G).items()]) # In[12]: d # In[14]: L.dot(d) # In[16]: e = np.array([v for k,v in nx.betweenness_centrality(G).items()]) # In[17]: L.dot(e) # In[ ]:
JeffRoy/mi-dataset
mi/dataset/driver/adcps_jln/stc/test/test_adcps_jln_stc_recovered_driver.py
Python
bsd-2-clause
1,063
0.007526
__author__ = 'Mark Worden' from mi.core.log import get_logger log = get_logger() from mi.idk.config import Config import unittest import os from mi.dataset.driver.adcps_jln.stc.adcps_jln_stc_recovered_driver import parse from mi.dataset.dataset_driver import ParticleDataHandler class SampleTest(unittest.TestCase...
source', 'adcpt_20130929_091817.DAT') particle_data_hdlr_obj = ParticleDataHandler() particle_data_hdlr_obj = parse(Config().base_dir(), sourceFilePat
h, particle_data_hdlr_obj) log.debug("SAMPLES: %s", particle_data_hdlr_obj._samples) log.debug("FAILURE: %s", particle_data_hdlr_obj._failure) self.assertEquals(particle_data_hdlr_obj._failure, False) if __name__ == '__main__': test = SampleTest('test_one') test.test_one()
barentsen/iphas-dr2
scripts/summary.py
Python
mit
1,682
0.001784
#!/usr/bin/env python # -*- coding: utf-8 -*- """Prints a summary of the contents of the IPHAS source catalogue. """ import os from astropy.io import fits from astropy import log import numpy as np import sys from dr2 import constants n_sources = 0 n_r20 = 0 n_reliable = 0 n_deblend = 0 n_reliable_deblend = 0 n_pair =...
rightNeighb'].sum() print "{0} sources so far".format(n_sources) with open('summary.txt', 'w') as out: out.write("#Unique sources: {0}\n".format(n_sourc
es)) out.write("#Sources r < 21: {0}\n".format(n_r20)) out.write("#Reliable sources: {0}\n".format(n_reliable)) out.write("#Deblend sources: {0}\n".format(n_deblend)) out.write("#Reliable+deblend: {0}\n".format(n_reliable_deblend)) out.write("#Paired sources: {0}\n".format(n_pair)) out.write("#S...
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/templatetags/tz.py
Python
mit
5,400
0.000185
from datetime import datetime, tzinfo import pytz from django.template import Library, Node, TemplateSyntaxError from django.utils import timezone register = Library() # HACK: datetime instances cannot be assigned new attributes. Define a subclass # in order to define new attributes in do_timezone(). class datetim...
automatic conversion of the value to local time. result = datetimeobject(result.year, result.month, result.day, result.hour, result.minute, result.second, result.microsecond, result.tzinfo) result.convert_to_local_time = False return result # T...
t__(self, nodelist, use_tz): self.nodelist = nodelist self.use_tz = use_tz def render(self, context): old_setting = context.use_tz context.use_tz = self.use_tz output = self.nodelist.render(context) context.use_tz = old_setting return output class TimezoneN...
nirs/vdsm
tests/network/functional/conftest.py
Python
gpl-2.0
3,091
0
# # Copyright 2018-2020 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed ...
e Free Software # Foundation, Inc., 51 Franklin Street, Fifth Fl
oor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from contextlib import contextmanager from unittest import mock import pytest from . import netfunctestlib as nftestlib from .netfunctestlib import NetFuncTestAdapter from .netfunctestlib import Target from v...
sheeprine/khal
tests/event_test.py
Python
mit
11,219
0.000357
# vim: set fileencoding=utf-8 : import datetime import textwrap import pytest import pytz from khal.khalendar.event import Event from .aux import normalize_component def test_normalize_component(): assert normalize_component(textwrap.dedent(""" BEGIN:VEVENT DTSTART;TZID=Europe/Berlin;VALUE=DATE-TIME:2...
M:-0400 TZOFFSETTO:-0500 END:STANDARD END:VTIMEZONE BEGIN:VEVENT SUMMARY:An Event DTSTART;TZID=America/Bogota;VALUE=DATE-TIME:20140409T093000 DTEND;TZID=America/Bogota;VALUE=DATE-TIME:20140409T103000 DTSTAMP;VALUE=DATE-TIME:20140401T234817Z UID:event_no_dst END:VEVENT
END:VCALENDAR """.split('\n') event_dt_duration = """BEGIN:VEVENT SUMMARY:An Event DTSTART;TZID=Europe/Berlin;VALUE=DATE-TIME:20140409T093000 DURATION:PT1H0M0S DTSTAMP;VALUE=DATE-TIME:20140401T234817Z UID:V042MJ8B3SJNFXQOJL6P53OFMHJE8Z3VZWOU END:VEVENT""" event_dt_no_tz = """BEGIN:VEVENT SUMMARY:An Event DTSTART;VALU...
pastgift/seed-website-py
app/models.py
Python
mit
4,907
0.004687
# -*- coding: utf-8 -*- import uuid import hashlib from datetime import datetime from flask import current_app, request from flask.ext.login import UserMixin, AnonymousUserMixin from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serial...
r_id = db.Column(db.String(64)) operation_note = db.Column(db.Text()) created_timestamp = db.Column(db.D
ateTime(), default=db.func.now()) updated_timestamp = db.Column(db.DateTime(), default=db.func.now(), onupdate=db.func.now()) def __init__(self, **kwargs): super(OperationRecord, self).__init__(**kwargs) @staticmethod def new(**kwargs): kwargs['id'] = uuid.uuid4().hex return Op...
rebase-helper/rebase-helper
containers/integration.py
Python
gpl-2.0
5,136
0.000974
import cgi import hashlib import http.server import io import os import posixpath import ssl import threading import time import urllib.parse import pyftpdlib.authorizers import pyftpdlib.handlers import pyftpdlib.servers class FTPServer: def __init__(self, port, root, report_size): class FTPHandlerNoSI...
ver.serve_forever() class HTTPServer: def __init__(self, port, cert, root, report_size): class RequestHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): path = self.path.split('?', 1)[0].split('#', 1)[0] path = urllib.parse.unquote(path) ...
path = os.path.join(root, path.lstrip('/')) try: with open(path, 'rb') as f: data = f.read() self.send_response(200) content_type = 'application/json' if 'versioneers' in path else 'application/octet-stream' ...
akanimax/CL-3_lab_2017
Assignment_B2/Plag_checker.py
Python
gpl-3.0
2,002
0.050949
#from app import app, lm #from app import socketio from flask import request, redirect, render_template, url_for, flash from flask.ext.wtf import Form from wtforms import StringField from wtforms.validators import DataRequired import os from flask import Flask class TextForm(Form): """Login form to access writing ...
cess") else: print "Text is plagiarised.\nApproximate plagiarism percentage: ",(float(repeated_sentences)/len(text))*100 flash_text="Text is plagiarised.\nApproximate plagia
rism percentage: "+ str((float(repeated_sentences)/len(text))*100) flash(flash_text,category="success") return render_template('home.html',form=form) if __name__ == '__main__': app.run(debug = True)
rollstudio/djangodash-2013
bakehouse/wsgi.py
Python
mit
1,439
0.00139
""" WSGI config for bakehouse project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`...
"bakehouse.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware...
.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Krakn/learning
src/python/python_koans/python3/another_local_module.py
Python
isc
280
0.010714
#!/usr/bin/env python # -*- coding: utf-8 -*- class Goose: @property def name(self): return "Mr Stabby" class Hamster: @p
roperty def name(self): return "Phil" class _SecretSquirrel: @property def name(s
elf): return "Mr Anonymous"
pipermerriam/flex
flex/loading/schema/info.py
Python
mit
933
0
from flex.constants import ( STRING, OBJECT, EMAIL, URI ) from flex.validation.common import ( generate_object_validator, ) info_schema = { 'required': [ 'title', ], 'properties': { 'title': { 'type': STRING, }, 'description': {'type': STRING}, '...
: OBJECT, 'properties': { 'name': {'type': STRING}, 'url': {'type': STRING, 'format': URI}, }, }, 'versi
on': {'type': STRING}, } } info_validator = generate_object_validator( schema=info_schema, )
skjena/Assemblyx86
changeOfBase/tester.py
Python
gpl-2.0
13,322
0.022069
#this is the base class for tester objects import sys import subprocess import logging import os from time import clock from result import Result studentLogger = logging.getLogger('errorLogger.progressLogger.studentLogger') studentLogger.setLevel(logging.INFO) h = logging.StreamHandler() h.setLevel(logging....
er._PROGRAM_COMPLETED except subprocess.TimeoutExpired: studentLogger.warning('%s %s timed out', ' '.join(self.cmdArgs), self.executable) program.kill() return Tester._PROGRAM_TIMED_OUT #end _runOne def testOne(self, inFile, solFile): ...
File @inFile: the name of the file containing the inputs @solFile: the name of the file containg the solution @returns: a Result """ progStatus = self._runOne(inFile, self.userOut)#run the program testName = os.path.basename(inFile) #the name of the test if(progStatus == Tester._PROGR...
rtucker/imap2maildir
simpleimap.py
Python
mit
17,416
0.002354
""" simpleimap.py, originally from http://p.linode.com/2693 on 2009/07/22 Copyright (c) 2009 Timothy J Fontaine <tjfontaine@gmail.com> Copyright (c) 2009 Ryan S. Tucker <rtucker@gmail.com> """ import email import imaplib import logging import platform import re import time class __simplebase: """ __simple base ...
at pos %(pos)d text %(text)s' % {'pos':pos, 'text': text}) pos += 1 # We now have a list
of lists. Dict this a bit... outerdict = self.__listdictor(result) replydict = {} for i in list(outerdict.keys()): replydict[i] = self.__listdictor(outerdict[i]) return replydict def __listdictor(self, inlist): """ __listdictor """ outdict = ...
Flowdalic/bitcoin
test/functional/p2p_fingerprint.py
Python
mit
5,771
0.00104
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If a stale block more than a month old or its header are requ...
self.send_block_request(stale_hash, node0) test_function = lambda: self.last_block_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Check that getheader request for stale block header succeeds sel
f.send_header_request(stale_hash, node0) test_function = lambda: self.last_header_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Longest chain is extended so stale is much older than chain tip self.nodes[0].setmocktime(0) tip = self.nodes[0].generate(nblocks=1)...
dionyziz/thefuck
thefuck/rules/no_command.py
Python
mit
848
0
from difflib import get_close_matches import os from pathlib import Path def _safe(fn, fallback): try: return fn() except OSError: return fallback def _get_all_bins(): return [exe.name for path in os.environ.get('PATH', '').split(':') for exe in _safe(lambda: list...
t_close_matches(command.script.split(' ')[0], _get_all_bins())) def get_new_command(command, settings): old_command = command.script.split(' ')[0] new_command = get_close_matches(old_command,
_get_all_bins())[0] return ' '.join([new_command] + command.script.split(' ')[1:])
StefanBruens/libsigrokdecode
decoders/cec/pd.py
Python
gpl-3.0
11,367
0.004487
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2018 Jorge Solla Rubiales <jorgesolla@gmail.com> ## ## 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 ...
one self.fall_start = None self.fall_end = None self.rise = None self.reset_frame_vars() def reset_frame_vars(self): self.eom = None self.bit_count = 0 self.byte_count = 0 self.byte = 0 self.byte_start = None self.frame_start = None ...
self.is_nack = 0 self.cmd_bytes = [] def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value self.precalculate() def handle_frame(self, is_nack): if self.fall_start is None or self.fall_end is None: return ...
andim/scipydirect
doc/tutorialfig.py
Python
mit
947
0.006336
from __future__ import division from scipydirect import minimize import numpy as np from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm import os def obj(x): """Six-hump camelback function""" x1 = x[0] x2 = x[1] f = (4 - 2.1*(x1*x1) ...
+ x1*x2 + (-4 + 4*(x2*x2))*(x2*x2) return f bounds = [(-3, 3), (-2, 2)] res = minimize(obj, bounds) # # Plot the results. # fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = res.x X, Y = np.mgrid[x[0]-1:x[0]+1:50j, x[1]-1:x[1]+1:50j] Z = np.zeros_like(X) for i in range(X.size): ...
Y, Z, rstride=1, cstride=1, cmap=cm.jet) ax.scatter(x[0], x[1], res.fun, c='r', marker='o') ax.set_title('Six-hump Camelback Function') ax.view_init(30, 45) fig.tight_layout() plt.show()
wilbertom/fileconversions
tests/test_text_to_pdf_conversion.py
Python
mit
295
0.00339
from fileconversions.testing import ConversionTestCase from fileconver
sions.conversions import TextToPdf class TestTextToPdfConversion(Conve
rsionTestCase): conversion_cls = TextToPdf def test_command_is_installed(self): self.assertCommandExists(self.conversion.command_name)
home-assistant/home-assistant
homeassistant/util/color.py
Python
apache-2.0
23,863
0.000377
"""Color util methods.""" from __future__ import annotations import colorsys import math from typing import NamedTuple import attr # mypy: disallow-any-generics class RGBColor(NamedTuple): """RGB hex values.""" r: int g: int b: int # Official CSS3 colors from w3.org: # https://www.w3.org/TR/2010...
50, 240), "forestgreen": RGBColor(34, 139, 34), "fuchsia": RGBColor(255, 0, 255), "gainsboro": RGBColor(220, 220, 220), "ghostwhite": RGBColor(248, 248, 255), "gold": RGBColor(255, 215, 0), "goldenrod": RGBColor(218, 165, 32), "gray": RGBColor(128, 128, 128), "green": RGBColor(0, 128, 0)...
"grey": RGBColor(128, 128, 128), "honeydew": RGBColor(240, 255, 240), "hotpink": RGBColor(255, 105, 180), "indianred": RGBColor(205, 92, 92), "indigo": RGBColor(75, 0, 130), "ivory": RGBColor(255, 255, 240), "khaki": RGBColor(240, 230, 140), "lavender": RGBColor(230, 230, 250), "lave...
luci/luci-py
appengine/third_party/python-adb/adb/fastboot_debug.py
Python
apache-2.0
1,879
0.005322
#!/usr/bin/env python # Copyright 2014 Google Inc. All rights reserved. #
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in co
mpliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expre...
FePhyFoFum/quartetsampling
pysrc/phylo/tree_reader.py
Python
gpl-3.0
3,393
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 """ this takes a newick string as instr and reads the string and makes the nodes and returns the root node http://www.github.com/FePhyFoFum/quartetsampling This file is part of 'quartetsampling'. 'quartetsampling' is free software: you can redis...
if nextchar is ',' or nextchar == ')' or nextchar is ':' \ or nextchar is ';' or nextchar is '[': break brlen += nextchar index += 1 nextchar = instr[index] curnode.length = float(brlen) index -= 1 ...
dex += 1 nextchar = instr[index] else: # this is an external named node newnode = Node() curnode.add_child(newnode) curnode = newnode curnode.istip = True name = "" while True: if nextchar is ',' or nextchar == ...
martakus/advent-of-code
y2017/tests/test5.py
Python
mit
274
0
import unittest
from y2017.day5 import * class TestDay5(unittest.TestCase): def test_part_A(self): self.assertEqual(jump_increment('0\n3\n0\n1\n-3\n'), 5) def test_part_B(self): self.assertEqual(jump_conditional_increment('0\n3\n0\n1\n-3\n'
), 10)
bryteise/ister
vm-installation-image-post-update-version.py
Python
gpl-3.0
3,122
0.001281
#!/usr/bin/python3 import os import sys INSTALLER_VERSION = '"latest"' def create_installer_config(path): """Create a basicl installation configuration file""" config = u"template=file:///etc/ister.json\n" jconfig = u'{"DestinationType" : "physical", "PartitionLayout" : \ [{"disk" : "vda", "partition...
"512M", "type" : "EFI"}, \ {"disk" : "vda", "partition" : 2, \ "size" : "512M", "type" : "swap"}, {"disk" : "vda", "partition" : 3, \ "size" : "rest", "type" : "linux"}], \ "FilesystemTypes" : \ [{"disk" : "vda", "partition" : 1, "type" : "vfat"}, \ {"disk" : "vda", "partition" : 2, "type" : "s...
"/boot"}, \ {"disk" : "vda", "partition" : 3, "mount" : "/"}], \ "Version" : 0, "Bundles" : ["kernel-native", "telemetrics", "os-core", "os-core-update"]}\n' if not os.path.isdir("{}/etc".format(path)): os.mkdir("{}/etc".format(path)) with open("{}/etc/ister.conf".format(path), "w") as cfile: ...
duahimanshu100/credit_computing_machine
credit_computing_machine/app/models.py
Python
mit
3,284
0.008222
from django.db import models from credit_computing_machine.models import TimestampModel from privateurl.models import PrivateUrl from django.db.models.signals import pre_save from django.dispatch import receiver # Create your models here. class CreditManager(models.Manager): def get_credit_all_user(self, credit_g...
class CreditScore(TimestampModel): score = models.FloatField() from_credit_user = models.ForeignKey( CreditUser, related_name='from_credit_user') to_credit_user = models.ForeignKey( CreditUser, related_name='to_credit_user') credit_group = models.ForeignKey(CreditGroup) objects = Cr...
@property def to_credit_user_email(self): return self.to_credit_user.email def __str__(self): return '%s to %s from %s'%(self.from_credit_user,self.to_credit_user,self.credit_group)
jaeilepp/eggie
mne/commands/utils.py
Python
bsd-2-clause
1,576
0.005076
#emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- #ex: set sts=4 ts=4 sw=4 noet: """Some utility functions for commands (e.g. for cmdline handling) """ # Authors: Yaroslav Halchenko <debian@onerussian.com> # # License: BSD (3-clause) import imp, os, re from optparse import O...
ame(cmdpath) if re.match('mne_(.*).py', comman
d): command = command[4:-3] # Fetch description mod = imp.load_source('__temp', cmdpath) if mod.__doc__: doc, description, epilog = mod.__doc__, None, None doc_lines = doc.split('\n') description = doc_lines[0] if len(doc_lines) > 1: epilog = '\n'.join(d...
jbergantine/django-blog
django_blog/migrations/0001_initial.py
Python
mit
2,509
0.004783
# Generated by Django 3.0 on 2019-12-03 17:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_...
rue, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(help_text='Maximum 250 characters.', max_length=250)), ('slug', models.SlugField(help_text='Suggested value automatically generated from title. Must be unique.', unique=True)), ], ...
teModel( name='Entry', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250)), ('slug', models.SlugField(help_text='Suggested value automatically gener...
eroicaleo/LearningPython
interview/leet/137_Single_Number_II.py
Python
mit
1,076
0.027881
#!/usr/bin/env python class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ sum1, sum2, lb = 0, 0, min(nums) mask1 = int('55555555', base=16) mask2 = int('AAAAAAAA', base=16) for num in nums: sum1 += ((nu...
# print('after mod: ', num, bin(sum1)[2:], bin(sum2)[2:]) return sum1 + (sum2 << 1) + lb mask1 = int('55555555', base=16) mask2 = int('AAAAAAAA', base=16) nums1 = 2 int1 = (nums1 & mask1) int2 = (nums1 & mask2) >> 1 nums = [0,1,0,1,0,1,99] nums = [2,2,3,2] nums = [2,2,5,5,1,5,1,1,0,2] nums = [-2,-...
-4,-2] print(int1) print(int2) sol = Solution() print(sol.singleNumber(nums))
qedsoftware/commcare-hq
corehq/apps/fixtures/download.py
Python
bsd-3-clause
13,120
0.002058
from cStringIO import StringIO from couchdbkit import ResourceNotFound from datetime import datetime, timedelta from django.template.defaultfilters import yesno from django.utils.translation import ugettext as _ from corehq.apps.fixtures.exceptions import FixtureDownloadError from corehq.apps.fixtures.models import F...
max_field_pro
p_combos[field_key] = max_combos item_helpers = { "max_users": max_users, "max_groups": max_groups, "max_locations": max_locations, "max_field_prop_combos": max_field_prop_combos, } item_helpers_by_type[data_type.tag] = item_helpers # Prepare...
F5Networks/f5-openstack-agent
f5_openstack_agent/utils/clean_partition.py
Python
apache-2.0
2,380
0
# coding=utf-8 # Copyright (c) 2016-2018, F5 Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
to clear out the contents of a corrupted tenant', ) parser.add_argument( '--config-file', help="Path to f5-openstack-agent.ini", metavar='config_file', required=True ) parser.add_argument( '--partition', help="Partion on the device to clean", required=True ) ...
) bigips = [] try: config_addrs = config.get("DEFAULT", 'icontrol_hostname') config_user = config.get("DEFAULT", 'icontrol_username') config_pass = config.get("DEFAULT", 'icontrol_password') except ConfigParser.NoOptionError as err: print(err.message) return bigips ...
rgeyer/terminator_for_rs_ss
skynet/urls.py
Python
mit
1,885
0.001061
"""skynet URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1
. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to url
patterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import inc...
hyounggyu/datamanager
datamanager/create.py
Python
gpl-2.0
6,741
0.00356
import os import getopt import re import sys import time from pathlib import Path from PyQt4 import QtCore, QtGui from xni.manage import dataset class Worker(QtCore.QObject): finished = QtCore.pyqtSignal() relay = QtCore.pyqtSignal(int) isFinished = False def __init__(self, output, images, bgnds=[...
iff)$'.format(prefix) match = re.compile(pattern, re.I).match result = [] for fn in os.listdir(self._dir): fn = os.path.no
rmcase(fn) if match(fn) is not None: result.append(os.path.join(self._dir, fn)) return sorted(result) def countImages(self, prefix): fns = self._list(prefix) self.statusBar().showMessage('{} image files selected.'.format(len(fns))) def run(self): ima...
peterdemin/mutant
src/mutant/app.py
Python
isc
2,308
0.000433
import logging import sys from mutant.parsers.python_parser import PythonParser logger = logging.getLogger(__name__) class MutantApp(object): """ App stores all readers, parser middlewares generators. All plugins can register themselves on this instance. And finally it has `parse` and `mutate` meth...
asattr(middleware, 'before_parse'): data = middleware.before_parse(data) schema = self.parser.parse(data) for middleware in reversed(self.parser_middlewares): if hasattr(middleware, 'after_parse'): schema = middleware.after_parse(schema) self.schema = ...
gen = self.generators[generator_name](self.schema) for ext in self.generator_extensions.get(generator_name, []): gen.register_extension(ext) return gen.render() def _read(self, reader_name, file_or_name): reader = self.readers[reader_name] if hasattr(file_or_name, 'read...
looran/tailosd
__init__.py
Python
isc
23
0
from .ta
ilosd
import *
iclosure/coolkits
src/jplot3d-py/com/smartsoft/j3d/GLExtensionFunctions.py
Python
gpl-2.0
438
0.015982
''' Created on Dec 28, 2015 @author: iclosure ''' class
GLExtensionFunctions(object): ''' classdocs ''' def __init__(self, params): ''' Constructor ''' def resolve(self, context): pass def fboSupported(self): pas
s def openGL15Supported(self): pass _instance = GLExtensionFunctions() def getGLExtensionFunctions(): return _instance
iohannez/gnuradio
gnuradio-runtime/python/pmt/qa_pmt_to_python.py
Python
gpl-3.0
1,610
0.001863
#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # ...
t, # Boston, MA 02110-1301, USA. # from __future__ import absolute_import import unittest import pmt from pmt import pmt_to_python as pmt2py class test_pmt_to_python(unittest.TestCase): def test_pmt_fro
m_double(self): b = pmt.from_double(123765) self.assertEqual(pmt.to_python(b), 123765) t = pmt.to_pmt(list(range(5))) def test_numpy_to_uvector_and_reverse(self): import numpy as np N = 100 narr = np.ndarray(N, dtype=np.complex128) narr.real[:] = np.random.un...
bwrsandman/openerp-hr
hr_employee_seniority/hr.py
Python
agpl-3.0
5,976
0.002677
#-*- coding:utf-8 -*- # # # Copyright (C) 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>. # All Rights Reserved. # # 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, eith...
employee.contract_ids: l = len(contracts) if l == 0: contracts.append(c) else: dCStart = datetime.strptime(c.date_start, OE_DATEFORMAT).date() i = l - 1 while i >= 0: dContractStart = datetime.strptim...
ntracts[i + 1:] break elif i == 0: contracts = [c] + contracts i -= 1 return contracts def _get_days_in_month(self, d): last_date = d - timedelta(days=(d.day - 1)) + relativedelta( months= +1) + re...
justanr/JSONConfigParser
jsonconfigparser/configparser.py
Python
mit
1,847
0.001624
''' Build a JSON Configuration Parser that can view, write and edit a JSON conf file. copyright 2014 Alec Nikolas Reiter license MIT ''' import json from collections import UserDict from pprint import pprint from jsonpath_rw import parse from .utils import root class JSONConfigParser(UserDict): ...
as much, for now, we'll ignore it pass def view(self, path=root): '''Pretty prints an endpoint in the JSON. ''' expr = parse(path) matches = expr.find(self.data) print('\n') for m in matches: print("{}:".format(m.full_path)) pprin...
te(self): '''Persists the current instance information to disk.''' with open(self.storage, 'w+') as fh: json.dump(self.data, fh, indent=4, sort_keys=True, cls=self.encoder)
caseywstark/dimensionful
example/gravity.py
Python
bsd-2-clause
702
0.001425
""" Compute the force of gravity between the Earth and Sun. Copyright 2012, Casey W. Stark. See LICENSE.txt for more information. """ # Import the g
ravitational constant and the Quantity class from dimensionful import G, Quantity # Supply the mass of Earth, mass of Sun, and the distance between. mass_earth = Quantity(5.9742e27, "g") mass_sun = Quantity(1.0, "Msun") distance = Quantity(1.0, "AU") # Calculate it force_gravity = G * mass_earth * mass_sun / distance...
"" # prints "The force of gravity between the Earth and Sun is 3.54296304519e+27 cm*g/s**2"
BadSingleton/pyside2
tests/QtCore/bug_408.py
Python
lgpl-2.1
697
0.004304
import unittest from PySide2.QtCore import * class My
Device(QIODevice): def __init__(self, txt): QIODevice.__init__(self) self.txt = txt self.ptr = 0 def readData(self, size): size = min(len(self.txt
) - self.ptr, size) retval = self.txt[self.ptr:size] self.ptr += size return retval class QIODeviceTest(unittest.TestCase): def testIt(self): device = MyDevice("hello world\nhello again") device.open(QIODevice.ReadOnly) s = QTextStream(device) self.assertEq...
tzpBingo/github-trending
codespace/python/telegram/replymarkup.py
Python
mit
1,200
0.000833
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2022 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
n) 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 Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. ...
vojtechtrefny/blivet
tests/formats_test/selinux_test.py
Python
lgpl-2.1
2,792
0.001791
#!/usr/bin/python import os import selinux import tempfile import unittest import blivet from tests import loopbackedtestcase import blivet.formats.fs as fs from blivet.size import Size @unittest.skipUnless(selinux.is_selinux_enabled() == 1, "SELinux is disabled") class SELinuxContextTestCase(loopbackedtestcase.LoopB...
iceSpec=[Size("100 MiB")]) def testMountingExt2FS(self): """ Test that lost+found directory gets assigned correct SELinux context if installer_mode is True, and retains some random old context if installer_mode is False. """ LOST_AND_FOUND_CONTEXT = 'system_u:object_...
self.assertIsNone(an_fs.create()) blivet.flags.installer_mode = False mountpoint = tempfile.mkdtemp("test.selinux") an_fs.mount(mountpoint=mountpoint) lost_and_found = os.path.join(mountpoint, "lost+found") self.assertTrue(os.path.exists(lost_and_found)) lost_and_...
Kjili/analysis-preservation.cern.ch
cap/modules/experiments/scripts/lhcb/lhcb.py
Python
gpl-2.0
3,286
0.006391
# -*- coding: utf-8 -*- # # This file is part of CERN Analysis Preservation Framework. # Copyright (C) 2016 CERN. # # CERN Analysis Preservation Framework 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...
= '../../static/jsonschemas/fields' if not os.path.exists(output_dir): os.makedirs(output_dir) for filename in filenames: base_field = "analysis" title_list = [] s = shelve.open(filename) # Get list of "title" for Anal.Name Autocomplete title_...
ng_group = working_group.replace(".shelve", "") with open('../../static/jsonschemas/fields/lhcb_ana_titles_'+working_group+'.json', 'w') as fp: json.dump(tmp_title_list, fp) def resolveObj(s, f, k): newk = {} for p in s[f][k]: if (hasattr(s[f...
diekhans/ga4gh-server
tests/end_to_end/test_oidc.py
Python
apache-2.0
3,844
0
""" Performs a request via the client with OpenID Connect enabled, with a local OP server. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import requests import subprocess from urlparse import urlparse import lxml.html as html import client import se...
utomatically performs the steps that the user would usually perform manually in order to obtain a token. """ session = requests.session() # Load the login page (this request includ
es the redirect to the OP) loginPage = session.get("{}/".format(server_url), verify=False) # Extract the state data from the login form loginTree = html.fromstring(loginPage.text) inputTags = loginTree.iterdescendants('input') state = (tag for tag in inputTags if tag.name == 'state').next().value ...
MangoMangoDevelopment/neptune
lib/genpy-0.5.8/src/genpy/generate_struct.py
Python
bsd-3-clause
5,490
0.006193
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above...
ern(pattern) add_pattern(pattern) return serialize("_struct_%s.pack(%s)"%(pattern, vars)) def pack2(pattern, vars): """ create struct.pack call for when pattern is the name of a variable :param pattern: name of variable storing string pattern, ``struct`` :param vars: name of variables to pack, `...
str`` """ return serialize("struct.pack(%s, %s)"%(pattern, vars)) def unpack(var, pattern, buff): """ create struct.unpack call for when pattern is a string pattern :param var: name of variable to unpack, ``str`` :param pattern: pattern for pack, ``str`` :param buff: buffer to unpack from, ...
sztosz/invoices
config/wsgi.py
Python
bsd-3-clause
1,618
0
""" WSGI config for invoices project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION``...
e defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJAN...
development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Use Whitenoise to serve static files # See: https://whitenoise.readthedocs.org/ application = DjangoWhiteNoise(application) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # appl...
kalaspuff/tomodachi
tests/services/dummy_protobuf_service.py
Python
mit
838
0
import tomodachi from tomodachi.discovery.dummy_registry import DummyRegistry from tomodachi.envelope.protobuf_base import ProtobufBase @tomodachi.service class DummyService(tomodachi.Service): name = "test_dummy_protobuf" discovery = [DummyRegistry] message_envelope = ProtobufBase options = { ...
tart_service(self) -> None: s
elf.start = True async def _started_service(self) -> None: self.started = True async def _stop_service(self) -> None: self.stop = True
googleapis/python-channel
google/cloud/channel_v1/types/channel_partner_links.py
Python
apache-2.0
3,498
0.001144
# -*- 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...
ber=7,) channel_partner_cloud_identity_info = proto.Field( proto.MESSAGE, number=8, message=common.CloudIdentityInfo
, ) __all__ = tuple(sorted(__protobuf__.manifest))
fhahn/django-endless-pagination
setup.py
Python
mit
1,430
0.008392
from distutils.core import setup import os root_dir = os.path.dirname(__file__) if root_dir: os.chdir(root_dir) data_files = [] for dirpath, dirnames, filenames in os.walk('endless_pagination'): for i, dirname in enumerate(dirnames): if dirname.startswith('.'): del dirnames[i] if '__init__.py' in ...
dless_pagination', 'endless_pagination.templatetags', ], package_data={'endless_pagination': data_files}, c
lassifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python'...
rs2/pandas
pandas/tests/arrays/period/test_constructors.py
Python
bsd-3-clause
3,116
0.000963
import numpy as np import pytest from pandas._libs.tslibs import iNaT from pandas._libs.tslibs.period import IncompatibleFrequency import pandas as pd import pandas._testing as tm from pandas.core.arrays import ( PeriodArray, period_array, ) @pytest.mark.parametrize( "data, freq, expected", [ ...
g", [ ( [pd.Period("2017", "D"), pd.Period("2017", "A")], None, "Input has different freq", ), ([pd.Period("2017", "D")], "A", "Input has different freq"), ], ) def test_period_array_raises(data, freq, msg): with pytest.raises(IncompatibleFrequency...
atch="dtype"): PeriodArray(ser, freq="D") def test_period_array_freq_mismatch(): arr = period_array(["2000", "2001"], freq="D") with pytest.raises(IncompatibleFrequency, match="freq"): PeriodArray(arr, freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): PeriodArray(...
kickstandproject/sarlacc
sarlacc/tests/asterisk/agi/test_say_number.py
Python
apache-2.0
2,994
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2013 PolyBeacon, Inc. # # Author: Paul Belanger <paul.belanger@polybeacon.com> # # 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 # #...
h('sys.stdin', cStringIO.StringIO("200 result=49")) def test_say_number_digit_pressed(self): with mock.patch( 'sys.stdout', new_callable=cStringIO.StringIO) as mock_stdout: res, dtmf = self.agi.s
ay_number(string='5000', digits='1234') self.assertEqual( mock_stdout.getvalue(), 'SAY NUMBER 5000 "1234"\n' ) self.assertTrue(res) self.assertEqual(dtmf, '1')
jorsea/vertical-ngo
framework_agreement_requisition/model/purchase.py
Python
agpl-3.0
4,603
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2013, 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # ...
al_workflow(cr, uid, [agr_id], 'select_agreement', context=context) def po_tender_agreement_selected(self, cr, uid, ids, context=None): """Workflow function that write state 'Agreement selected'""" return self.write(cr, uid, ids, {'state': AGR_SELECT}, ...
ood way to supress SQL constraint to add # Python constraint... _sql_constraints = [( 'quantity_bid', 'CHECK(true)', 'Selected quantity must be less or equal than the quantity in the bid' )] def _check_quantity_bid(self, cr, uid, ids, context=None): for line in self.brow...
softtyphoon/tz
tools/17173/ymxk/复件 game_spider.py
Python
gpl-2.0
839
0.017271
 from news_spider import news_spider from video_spider import video_spider if __name__ == "__main__": print u'开始爬取咨询信息...' # 设置资讯的存储位置,必须以 \\ 结尾,分为绝对路径和相对路径 # c:\资讯\\ C:\咨询 目录下存放 txt,c:\资讯\图片 目录下存放图片 # 咨询\ 程序当前文件夹下的 资讯 目录存储 txt, 里面的 图片目录存放图片 news_path = u'c:\资讯\\' # 设置视频目...
u'视频信息的的存放路径是:' + video_path a = video_spider(path = video_path)
a.run() pass
denys-duchier/Scolar
ZopeProducts/exUserFolder/AuthSources/pgAuthSourceAlt/pgAuthSource.py
Python
gpl-2.0
10,712
0.033701
# # Extensible User Folder # # Postgres Authentication Source for exUserFolder # # (C) Copyright 2000,2001 The Internet (Aust) Pty Ltd # ACN: 082 081 472 ABN: 83 082 081 472 # All Rights Reserved # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,...
eUserRoles) sqlInsertUser=SQL( 'sqlInsertUser', 'Insert One User', self.connection, 'userTable=%s usernameColumn=%s passwordColumn=%s username:string password:string'%( self.userTable, self.usernameColumn, self.passwordColumn), _sqlInsertUser) self._setObject('sqlInsertUser', sqlInsertUser) s...
e=%s usernameColumn=%s roleColumn=%s username:string rolename:string'%( self.roleTable, self.usernameColumn, self.roleColumn), _sqlInsertUserRole) self._setObject('sqlInsertUserRole', sqlInsertUserRole) sqlUpdateUserPassword=SQL( 'sqlUpdateUserPassword', 'Update just the password', self.connection,...
ant30/s3authbasic
s3authbasic/tests/test_views.py
Python
mit
1,402
0
from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON class ViewsTests(BaseAppTest): def test_validpath(self): for (path, expect) in ( ('/', 'home'), ('/index.html', 'home'), ('/level1', 'level 1'), ('/level1/', 'level 1'), ('/level1/index.h...
('/index.html', 'text/html'), ('/example.jpeg', 'image/jpeg'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON) self.assertEqual(result.content_type, mi
metype)
levilucio/SyVOLT
mbeddr2C_MM/Contracts/HSimple_IsolatedLHS.py
Python
mit
21,285
0.012074
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HSimple_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HSimple_IsolatedLHS. """ # Flag this instance as c...
shall be matched by this rule. # You can access the value of the current node's attribute value by: attr_value. # You can access any attribute x of this node by: this['x']. # If the constraint relies on attribute values from other nodes, # use the LHS/NAC constraint instead. # The given constraint must evaluate to a b...
return True """ self.vs[6]["MT_label__"] = """7""" self.vs[6]["MT_dirty__"] = False self.vs[6]["mm__"] = """MT_pre__InitializeConfiguration""" self.vs[6]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'') # match class StatementList() node ...
RoyXiang/ehForwarderBot
config.sample.py
Python
gpl-3.0
1,192
0.000839
# ####
########################## # Configs for EH Forwarder Bot # ############################## # # Basic settings # ---------------- # # Master/Slave Channels # # Master channel: # The channel that is
mainly used to view/manage messages # from slave channels. # Currently only 1 master channel is supported. # # Slave channels: # Channels that are hosted on the server and being delivered # to and from the master channel. # You may have more than 1 slave channel. # master_channel = 'plugins.eh_telegram_master', 'Tele...
silly-wacky-3-town-toon/SOURCE-COD
toontown/pets/PetTraits.py
Python
apache-2.0
9,416
0.004142
from toontown.toonbase.ToonPythonUtil import randFloat, normalDistrib, Enum from toontown.distributed.PythonUtil import clampScalar from toontown.toonbase import TTLocalizer, ToontownGlobals import random, copy TraitDivisor = 10000 def getTraitNames(): if not hasattr(PetTraits, 'TraitNames'): traitNames = ...
aitDivisor) self.higherIsBetter = distrib.getHigherIsBetter() self.percentile = distrib.getPercentile(self.value) self.quality = distrib.getQuality(self.value) self.howExtreme = distrib.getExtremeness(self.value) retur
n def __repr__(self): return 'Trait: %s, %s, %s, %s' % (self.name, self.value, TraitDistribution.TraitQuality.getString(self.quality), self.howExtreme) def __init__(self, traitSeed, safeZoneId, traitValueList = []): self.traitSeed = traitSeed ...
szu-stu/ezFund
fund/apps.py
Python
apache-2.0
83
0
from dja
ngo.apps import AppConfig class FundConfig(AppConfig): name = '
fund'
python-dirbtuves/website
pylab/core/helpers/factories.py
Python
agpl-3.0
2,104
0.000951
import datetime import faker class FakerFactoryBoyWrapper(object): """Small wrapper around faker for factory boy. Usage: >>> from factory import LazyAttribute >>> from pylab.core.helpers.factories import fake >>> LazyAttribute(fake.company()) # doctest: +ELLIPSIS <factory.d...
_replace_kwargs(**kwargs): return {k: v for k, v in kwargs.items() if k in { 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzi
nfo', }} def _get_datetime(dt, date=False, **kwargs): if date: dt = dt.date() replace_kwargs = _get_datetime_replace_kwargs(**kwargs) if replace_kwargs: dt = dt.replace(**replace_kwargs) return dt def now(): def func(obj=None): # pylint: disable=unused-argument re...
Lucas-Armand/genetic-algorithm
dev/9ºSemana/testes of speed.py
Python
gpl-3.0
3,255
0.036252
# -*- coding: utf-8 -*- import os import csv import random import numpy as np import timeit import time as Time import matplotlib.pyplot as plt import matplotlib.animation as animation from itertools import product, combinations class Block: def __init__(self,point,a,b,c,weight,btype): self.p=point ...
vic = [vicinity[x] for x in chromo] time = sum((time_vector(x,y) for x,y in zip(chromo,vic))) return time chromo = [44, 39, 56, 47, 49, 37, 42, 46, 51, 58, 60, 62, 52, 41, 35, 33, 50, 61, 54, 34, 59, 43, 48, 45, 55, 53, 38, 57, 64, 67, 68, 63, 40, 36, 21, 66, 22, 6, 20, 65, 18, 5, 17, 69, 28, 27, ...
30, 13, 14, 26, 31, 24, 19, 2, 3, 4, 25, 11, 32, 10, 15, 16, 9, 23, 7, 8] import cProfile cProfile.run('time(bNumb,vicinity,chromo)') ## ##print timeit.timeit(setup='from __main__ import chromo;'+ ## 'from __main__ import bNumb;'+ ## 'from __main__ import time;'+ ## ...
foobacca/django-multilingual-search
tests/testproject/translation.py
Python
mit
321
0.003115
# coding: utf-8 from __future__ import ab
solute_import, unicode_literals from modeltranslation.translator import translator, TranslationOptions from .models import Document class DocumentTranslationOptions(TranslationOptions): fields = ('title', 'text') translator.register(Document, DocumentTranslationOpt
ions)
toofar/qutebrowser
tests/unit/scripts/test_check_coverage.py
Python
gpl-3.0
6,650
0
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
un() assert covtest.check() == [] def test_untested(covtest): covtest.makefile(""" def func(): pass def untested(): pass """) covtest.run() expected = check_coverage.Message( ch
eck_coverage.MsgType.insufficent_coverage, 'module.py', 'module.py has 75.00% line and 100.00% branch coverage!') assert covtest.check() == [expected] def test_untested_floats(covtest): """Make sure we don't report 58.330000000000005% coverage.""" covtest.makefile(""" def func(): ...
hobson/pug-nlp
pug/nlp/segmentation.py
Python
mit
13,806
0.004346
import os import re import string from itertools import chain from .detector_morse import Detector from .detector_morse import slurp # from .penn_treebank_tokenizer import word_tokenize import nlup from pug.nlp.constant import DATA_PATH from pug.nlp.util import generate_files # regex namespace only conflicts with reg...
self.strip = None elif strip is True: self.strip_chars = '-_*`()"' + '"' strip = strip or None # strip whitespace, overrides strip() method self.strip = strip if callable(strip) else (str_strip if strip else None) self.doc = to_ascii(doc) self.regex = regex ...