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
ismailof/mopidy-json-client
mopidy_json_client/methods_2_0/tracklist.py
Python
apache-2.0
12,680
0.001341
from ..mopidy_api import MopidyWSController class TracklistController (MopidyWSController): def index(self, tl_track=None, tlid=None, **options): '''The position of the given track in the tracklist. If neither *tl_track* or *tlid* is given we return the index of the currently playing trac...
he tracklist by the given criterias. A criteria consists of a model field to check and a list of values to compare it against. If the model field matches one of the values, it may be returned. Only tracks that matches all
the given criterias are returned. Examples:: # Returns tracks with TLIDs 1, 2, 3, or 4 (tracklist ID) filter({'tlid': [1, 2, 3, 4]}) # Returns track with URIs 'xyz' or 'abc' filter({'uri': ['xyz', 'abc']}) # Returns track with a matching TLIDs (1, 3 or...
cevaris/pants
contrib/go/src/python/pants/contrib/go/tasks/go_thrift_gen.py
Python
apache-2.0
5,677
0.008631
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re ...
arget thrift_imports = self.context.resolve(thrift_import_target) return thri
ft_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+...
ruijie/quantum
quantum/tests/unit/test_db_plugin.py
Python
apache-2.0
122,027
0.000156
# Copyright (c) 2012 OpenStack, 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 wr...
import timeutils from quantum.tests.unit import test_extensions from quantum.tests.unit.testlib_api import create_request from quantum.wsgi import Serializer, JSONDeseri
alizer LOG = logging.getLogger(__name__) DB_PLUGIN_KLASS = 'quantum.db.db_base_plugin_v2.QuantumDbPluginV2' ROOTDIR = os.path.dirname(os.path.dirname(__file__)) ETCDIR = os.path.join(ROOTDIR, 'etc') def etcdir(*p): return os.path.join(ETCDIR, *p) class QuantumDbPluginV2TestCase(unittest2.TestCase): def ...
lodevil/cpy
cpy/parser/ast_builder.py
Python
mit
38,253
0.000758
from . import ast from .pystates import symbols as syms from .grammar.sourcefile import SourceFile import token import six import re class ASTError(Exception): pass class ASTMeta(type): def __new__(cls, name, bases, attrs): handlers = {} attrs['handlers'] = handlers newcls = type.__n...
arg.annotation = node[i][2].val kwonlyargs.append(arg) if node[i + 1].val == '=': kw_defaults.append(self.handle_test(node[i + 2])) i += 4 else: i += 2 if i < len(node) and node[i].val =...
.val kwargannotation = node[i + 1][2] if len(node[i + 1]) == 3 else None else: kwarg, kwargannotation = None, None return ast.arguments(args=[], vararg=vararg, varargannotation=varargannotation
jrief/django-angular
djng/forms/angular_model.py
Python
mit
4,211
0.004275
from django.forms.utils import ErrorDict from django.utils.html import format_html from djng.forms.angular_base import NgFormBaseMixin, SafeTuple class NgModelFormMixin(NgFormBaseMixin): """ Add this NgModelFormMixin to every class derived from ``forms.Form``, if that custom ``Form`` shall be managed thro...
th its scope_prefix") def _post_clean(self): ""
" Rewrite the error dictionary, so that its keys correspond to the model fields. """ super(NgModelFormMixin, self)._post_clean() if self._errors and self.prefix: self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items()) def get_init...
karlht/services-tools
fxa-l10n/genContentPages.py
Python
mpl-2.0
752
0.00266
langs = [ "ca", "cs",
"cy", "da", "de", "en-US", "es", "es-CL", "et", "eu", "fr", "fy", "he", "hu", "id", "it", "ja", "ko", "lt", "nb-NO", "nl", ...
"sr", "sr-LATN", "sv", "tr", "zh-CN", "zh-TW", "xx"] print '#!/bin/sh' print for lang in langs: print "node_modules/phantomjs/bin/phantomjs fxa-l18n/page-scrape/loadPage.js %s" % lang
KenetJervet/mapensee
python/pedal/pedal/test/test_pedal_syntax.py
Python
gpl-3.0
2,077
0.000481
# coding: utf-8 from pedal import ( parse, transcript, _pedal ) import unittest class PedalParseTest(TestCase): _sample_code = r''' title "No trans" input { historical_samplings: int recent_n_min_no_
trans_func: func } tweaks { sample_days: int daily_sample_points: int check_interval: int hs_u: int hs_l: int n_u: int n_l: int } "Historical samplings" { } trigger "Alert trigger condition" { if historical_samplings > hs_u { ...
''' def test_parse(self): ast = parse(self._sample_code) assert len(ast) == 3 # Test hello section assert ast[0].name == 'hello' stmts = ast[0].stmts num_stmt = stmts[0] assert num_stmt.varname.identifier == 'num' assert num_stmt.val.val == 123 ...
Dima73/enigma2
lib/python/Components/Sources/StreamService.py
Python
gpl-2.0
2,074
0.024108
from Source import Source from Components.Element import cached from Components.SystemInfo import SystemInfo from enigma import eServiceReference StreamServiceList = [] class StreamService(Source): def __init__(self, navcore): Source.__init__(self) self.ref = None self.__service = None self.navcor
e = navcore def serviceEvent(self, event): pass @cached def getService(self): return self.__service service = property(getService) def handleCommand(self, cmd): print "[StreamService] handle command", cmd self.ref = eServiceReference(cmd) def recordEvent(se
lf, service, event): if service is self.__service: return print "[StreamService] RECORD event for us:", service self.changed((self.CHANGED_ALL, )) def execBegin(self): if self.ref is None: print "[StreamService] has no service ref set" return print "[StreamService]e execBegin", self.ref.toString() ...
saintpai/sos
sos/plugins/tuned.py
Python
gpl-2.0
1,399
0
# Copyright (C) 2014 Red Hat, Inc., Peter Portante <[email protected]> # 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 v...
_cmd_output([ "tuned-adm list", "t
uned-adm active", "tuned-adm recommend" ]) self.add_copy_spec([ "/etc/tuned.conf", "/etc/tune-profiles" ]) self.add_copy_spec([ "/etc/tuned", "/usr/lib/tuned", "/var/log/tuned/tuned.log" ]) # vim: et ts=4 sw...
Smart-Torvy/torvy-home-assistant
homeassistant/components/media_player/sonos.py
Python
mit
13,962
0
""" Support to interface with Sonos players (via SoCo). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.sonos/ """ import datetime import logging from os import path import socket import voluptuous as vol from homeassistant.components.media_...
Sonos device "%s" '
'not available in this mode', func.__name__, args[0].name) else: _LOGGER.debug('Ignore command "%s" for Sonos device "%s" (%s)', func.__name__, args[0].name, 'not coordinator') return wrapper # pylint: disable=too-many-instanc...
codeif/crimg
crimg/api.py
Python
mit
2,205
0.000454
# -*- coding: utf-8 -*- from PIL import Image def get_target_size(img_size, size, exact_size=False): assert img_size[0] and img_size[1] assert size[0] or size[1] size = list(size) if not size[0]: size[0] = size[1] * img_size[0] // img_size[1] if not size[1]: size[1] = size[0] * im...
def crop_by_aspect_ratio(image, aspect_ratio): """crop image by scale without aspect rati
o distortion :param image: a PIL image object :param aspect_ratio: aspect ratio, as a 2-tuple: (width, height). :returns: An :py:class:`~PIL.Image.Image` object. """ size = image.size size1 = (size[0], size[0] * aspect_ratio[1] // aspect_ratio[0]) size2 = (size[1] * aspect_ratio[0] // aspe...
TwistingTwists/sms
data/module_locator.py
Python
apache-2.0
418
0.014354
"""Locate the data files in the eggs to open""" "Special thanks to https://github.com/Orko
Hunter/ping
-me/tree/master/ping_me/data" import os import sys def we_are_frozen(): return hasattr(sys, "frozen") def modeule_path(): encoding = sys.getfilesystemencoding() if we_are_frozen(): return os.path.dirname(unicode(sys.executable, encoding)) return os.path.dirname(unicode(__file__, encoding))
funkring/fdoo
addons-funkring/at_project_sale/wizard/correct_time_wizard.py
Python
agpl-3.0
3,859
0.022286
# -*- coding: utf-8 -*- ############################################################################# # # Copyright (c) 2007 Martin Reisenhofer <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
her 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 PARTICUL
AR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv im...
ruuk/script.web.viewer2
lib/webviewer/cssutils/__init__.py
Python
gpl-2.0
15,021
0.002197
#!/usr/bin/env python """cssutils - CSS Cascading Style Sheets library for Python Copyright (C) 2004-2013 Christof Hoeke cssutils is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either ver...
>>> print sheet.cssText a { color: red } """ __all__ = ['css', 'stylesheets', 'CSSParser', 'CSSSerializer'] __docformat__ = 'restructuredtext' __author__ =
'Christof Hoeke with contributions by Walter Doerwald' __date__ = '$LastChangedDate:: $:' VERSION = '0.9.10' __version__ = '%s $Id$' % VERSION import sys if sys.version_info < (2,6): bytes = str import codec import os.path import urllib import urlparse import xml.dom # order of impo...
anoopkunchukuttan/transliterator
src/cfilt/transliteration/analysis/analysis_commands.py
Python
gpl-3.0
3,540
0.031356
#Copyright Anoop Kunchukuttan 2015 - present # #This file is part of the IITB Unsupervised Transliterator # #IITB Unsupervised Transliterator 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...
ND_INCLUSIVE-langinfo.COORDINATED_RANGE_START_INCLUSIVE+1)) for i,lang in enumerate(langs): for c,v in lang_data[i]['char_proportions'].iteritems(): charratio_mat[i,c]=v ## plot matplotlib.rc('font', family='Lohit
Hindi') fig, ax = plt.subplots() plt.pcolor(charratio_mat,cmap=plt.cm.hot_r,edgecolors='k') plt.colorbar() plt.xticks(np.arange(0,charratio_mat.shape[1])+0.5,[ langinfo.offset_to_char(o,'hi') for o in xrange(langinfo.COORDINATED_RANGE_START_INCLUSIVE,langinfo.COORDINATED_RANGE_END_INCLUSIVE+1)]) p...
PaloAltoNetworks/minemeld-core
tests/test_ft_st.py
Python
apache-2.0
8,708
0.00023
# Copyright 2015 Palo Alto 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 law or agre...
arDown(self): try: shutil.rmtree(TABLENAME) except: pass def test_add_delete(self): st = minemeld.ft.st.ST(TABLENAME, 8, truncate=True) sid = uuid.uuid4().bytes st.put(sid, 1, 5, 1) st.delete(sid, 1, 5, 1) st.close() def test_q...
id.uuid4().bytes st.put(sid1, 1, 70, 1) st.put(sid2, 50, 100, 1) eps = [ep[0] for ep in st.query_endpoints( start=0, stop=st.max_endpoint, reverse=False, include_start=False, include_stop=False )] self.assertEqual(eps...
tashigaofei/BlogSpider
scrapy/tests/test_http_headers.py
Python
mit
4,934
0.001824
import unittest import copy from scrapy.http import Headers class HeadersTest(unittest.TestCase): def test_basics(self): h = Headers({'Content-Type': 'text/html', 'Content-Length': 1234}) assert h['Content-Type'] assert h['Content-Length'] self.assertRaises(KeyError, h.__getitem__...
html'])]) self.assertEqual(h.va
lues(), ['ip2', 'text/html']) def test_update(self): h = Headers() h.update({'Content-Type': 'text/html', 'X-Forwarded-For': ['ip1', 'ip2']}) self.assertEqual(h.getlist('Content-Type'), ['text/html']) self.assertEqual(h.getlist('X-Forwarded-For'), ['ip1', 'ip2']) def test_copy(...
tangyanhan/homesite
manage_videos/import_videos.py
Python
mit
11,680
0.00214
# coding=utf8 # encoding: utf-8 import os import platform import re import signal import sys import traceback from subprocess import Popen, PIPE from threading import Thread, current_thread from Queue import Queue from util.log import get_logger, log from video.models import Video, KeywordVideoId from django.db.mode...
if not os.path.isdir(FLIP_DIR): os.mkdir(FLIP_DIR) for _ in range(MAX_THREAD_NUM): if THREAD_STOP_FLAGS[_]: t = Thread(target=import_worker
, kwargs={'thread_index': _}) t.name = str(_) t.daemon = False t.start() task_queue.join() def add_keywords_to_db(task_list): blacklist = load_keyword_blacklist_from_file() for task in task_list: base_path = task.base_path file_path = task.file_path ...
criteo/biggraphite
biggraphite/cli/import_whisper.py
Python
apache-2.0
8,945
0.001006
#!/usr/bin/env python # Copyright 2016 Criteo # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
return 0 def _parse_opts(args): parser = argparse.ArgumentParser( description="Import whisper files into BigGraphite." ) parser.add_argument( "root_directory
", metavar="WHISPER_DIR", help="directory in which to find whisper files", ) parser.add_argument( "--filter", type=str, default=r".*\.wsp", help="Only import metrics matching this filter", ) parser.add_argument( "--prefix", metavar="WHISPER...
ahmedaljazzar/edx-platform
cms/envs/test.py
Python
agpl-3.0
11,745
0.001703
# -*- coding: utf-8 -*- """ This config file runs the simplest dev environment using sqlite, and db-based sessions. Assumes structure: /envroot/ /db # This is where it'll write the database file /edx-platform # The location of this repo /log # Where we're going to write log files """ # We ...
ort, unused-wildcard-import from .common import * import os from path import Path as path
from uuid import uuid4 from util.db import NoOpMigrationModules from openedx.core.lib.derived import derive_settings # import settings from LMS for consistent behavior with CMS # pylint: disable=unused-import from lms.envs.test import ( WIKI_ENABLED, PLATFORM_NAME, SITE_NAME, DEFAULT_FILE_STORAGE, ...
mscuthbert/abjad
abjad/tools/pitchtools/test/test_pitchtools_Registration___init__.py
Python
gpl-3.0
1,317
0.000759
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_Registration___init___01(): r'''Initialize from items. ''' mapping = pitchtools.Registration([('[A0, C4)', 15), ('[C4, C8)', 27)]) assert isinstance(mapping, pitchtools.Registration) def test_pitch
tools_Registration___ini
t___02(): r'''Initialize from instance. ''' mapping_1 = pitchtools.Registration([('[A0, C4)', 15), ('[C4, C8)', 27)]) mapping_2 = pitchtools.Registration(mapping_1) assert isinstance(mapping_1, pitchtools.Registration) assert isinstance(mapping_2, pitchtools.Registration) assert mapping_1 ...
bertptrs/adventofcode
2019/tests/test_day22.py
Python
mit
944
0.001059
import pytest from aoc2019.day22 import shuffle SAMPLE_INSTRUCTIONS = [ """deal with increment 7 deal into new stack deal into new stack""", """cut 6 deal with increment 7 deal into new stack""", """deal with increment 7 deal with increment 9 cut -2""", """deal into new stack ...
cut 8 cut -4 deal with increment 7 cut 3 deal with increment 9 deal with increment 3 cut -1""", ] CORRECT_SHUFFLES = [ "0 3 6 9 2 5 8 1 4 7", "3 0 7 4 1 8 5 2 9 6", "6 3 0 7 4 1 8 5 2 9", "9 2 5 8 1 4 7 0 3 6", ] @pytest.mark.parametrize('instructions,correct', zip(SAMPLE_IN...
correct = [int(i) for i in correct.split(" ")] result = shuffle(instructions, 10) assert result == correct
RomanBelkov/qreal
plugins/tools/visualInterpreter/examples/robotsCodeGeneration/reactionsStorage/Initialization.py
Python
apache-2.0
3,823
0.022134
import os max_used_id = -1 cur_node_is_processed = False conditions = {} if_nodes = [] if_nodes_with_2_branches = [] branch_end = {} branch_end_type = {} branch_type = {} code = [] init_code = [] terminate_code = [] variables_code = [] balancer_code = '' id_to_pos_in_code = {} proce
ssed_loops = {} processed_ends = [] def ifGeneration(): global if_nodes global code global id_to_pos_in_code global branch_type global branch_end global branch_end_type global if_nodes_with_2_branches if len(if_nodes) > 0: while len(if_nodes) > 0 and if_nodes[0] not in if_nodes_with_2_branches: ...
0: if branch_type[if_nodes[0]] == 1: cond = conditions[if_nodes[0]] code[id_to_pos_in_code[if_nodes[0]]].insert(0, "if (" + cond + ") {\n") code.append(["}\n"]) branch_end[if_nodes[0]] = len(code) - 1 branch_end_type[if_nodes[0]] = 1 elif branch_type[if_nodes...
AleksNeStu/ggrc-core
test/selenium/bin/run_selenium.py
Python
apache-2.0
1,534
0.008475
#!/usr/bin/env python2.7 # Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Basic selenium test runner This script is used for running all selenium tests against the server defined in the configuration yaml file. The script will wait a defined time for ...
# pylint: disable=import-error # add src to path so that we can do imports from our
src PROJECT_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) + "/../" sys.path.append(PROJECT_ROOT_PATH + "src") from lib import file_ops # NOQA from lib import environment # NOQA def wait_for_server(): """ Wait for the server to return a 200 response """ sys.stdout.write("Wating on server: ") for _...
maxamillion/product-definition-center
pdc/apps/package/filters.py
Python
mit
4,125
0.012848
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # from django.conf import settings from django.forms import SelectMultiple import django_filters from pdc.apps.common.filters import MultiValueFilter, NullableCharFilter from . import models class RPMFilter(dj...
rpm_names).distinct() else: return queryset.filter(rpms__srpm_name__in=value).distinct() else: return queryset class Meta: model = models
.BuildImage fields = ('component_name', 'rpm_version', 'rpm_release', 'image_id', 'image_format', 'md5', 'archive_build_nvr', 'archive_name', 'archive_size', 'archive_md5', 'release_id')
twitter/pants
src/python/pants/backend/jvm/tasks/classpath_entry.py
Python
apache-2.0
4,098
0.009761
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals class ClasspathEntry(object): """Represents a java classpath entry. :API: public ...
elf._directory_digest = directory_digest @property def path(self): """Returns the pants internal path of this classpath entry. Suitable for use in constructing classpaths for pants executions and pants generated artifacts. :API: public
:rtype: string """ return self._path @property def directory_digest(self): """Returns the directory digest which contains this file. May be None. This API is experimental, and subject to change. :rtype: pants.engine.fs.Digest """ return self._directory_digest def is_excluded_b...
yt4766269/pytorch_zoo
LeNet/CONSTANT.py
Python
apache-2.0
100
0.01
TR
AIN_BATCH_SIZE = 64 TEST_BATCH_SIZE = 64 EPOCH = 32 CALCULATE_LOSS = 100 DATA_PATH = '.
./dataset/'
carragom/modoboa
modoboa/admin/tests/test_domain_alias.py
Python
isc
1,687
0
# coding: utf-8 from django.core.urlresolvers import reverse from modoboa.lib.tests import ModoTestCase from .. import factories from ..models import Domain, DomainAlias, Alias class DomainAliasTestCase(ModoTestCase): @classmethod def setUpTestData(cls): """Create test data.""" super(Domai...
AliasTestCase, cls).setUpTestData() fa
ctories.populate_database() cls.dom = Domain.objects.get(name='test.com') def test_model(self): dom = Domain.objects.get(name="test.com") domal = DomainAlias() domal.name = "domalias.net" domal.target = dom domal.save() self.assertEqual(dom.domainalias_count,...
balazs-bamer/FreeCAD-Surface
src/Mod/Spreadsheet/InitGui.py
Python
lgpl-2.1
3,295
0.010926
#*************************************************************************** #* * #* Copyright (c) 2013 - Yorik van Havre <[email protected]> * #* * #* This pr...
ite to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #******************************************************
********************* class SpreadsheetWorkbench(Workbench): "Spreadsheet workbench object" Icon = """ /* XPM */ static char * Spreadsheet_xpm[] = { "16 16 5 1", " c None", ". c #151614", "+ c #575956", "@ c #969895", "# c #F7F9F6", ...
azumimuo/family-xbmc-addon
plugin.video.genesisreborn/resources/lib/sources/watchepisodes.py
Python
gpl-2.0
3,918
0.025013
import re import urllib import requests import urlparse import json import xbmc from BeautifulSoup import BeautifulSoup from resources.lib.modules.common import random_agent from resources.lib.modules import control from resources.lib.modules import cleantitle from schism_commons import quality_tag, google_tag, parseD...
query, headers=headers, timeout=30).json() results = html['series'] for item in results: r_title = item['label'].encode('utf-8') r_link = item['seo'].encode('utf-8') if cleaned_title == cleantitle.get(r_title): r_page = self.base_link + "/" + r_link print("WATCHEPISODES r1"...
BeautifulSoup(requests.get(r_page, headers=headers, timeout=30).content) r = r_html.findAll('div', attrs={'class': re.compile('\s*el-item\s*')}) for container in r: try: r_href = container.findAll('a')[0]['href'].encode('utf-8') r_title = container.findAll('a')[0]['title'].encode('utf-8') ...
qsnake/gpaw
oldtest/hund.py
Python
gpl-3.0
1,082
0
from ase import * from gpaw im
port * atoms = Atoms('H') atoms.center(vacuum=4.
) params = dict(h=.3, convergence=dict(density=.005, eigenstates=1e-6)) # No magmom, no hund atoms.set_calculator(GPAW(**params)) E_nom_noh = atoms.get_potential_energy() assert np.all(atoms.get_magnetic_moments() == 0.) assert atoms.calc.get_number_of_spins() == 1 # No magmom, hund atoms.set_calculator(GPAW(hund=Tr...
huard/scipy-work
scipy/fftpack/tests/test_basic.py
Python
bsd-3-clause
18,018
0.036408
#!/usr/bin/env python # Created by Pearu Peterson, September 2002 """ Test functions for fftpack.basic module """ __usage__ = """ Build fftpack: python setup_fftpack.py build Run tests if scipy is installed: python -c 'import scipy;scipy.fftpack.test()' Run tests if fftpack is not installed: python tests/test_bas...
y2 = numpy_fft(x) y1 = zeros((n,),dtype=double) y1[0] = y2[0].real y1[-1] = y2[n/2].real for k in range(1,n/2): y1[2*k-1] = y2[k].real y1[2*k] = y2[k].imag y = fftpack.drfft(x) assert_array_almost_equal(y,y1)...
uble(_TestRFFTBase): def setUp(self): self.cdt = np.cdouble self.rdt = np.double class TestRFFTSingle(_TestRFFTBase): def setUp(self): self.cdt = np.complex64 self.rdt = np.float32 class _TestIRFFTBase(TestCase): def test_definition(self): x1 = [1,2,3,4,1,2,3,4] ...
detrout/python-htseq
HTSeq/StepVector.py
Python
gpl-3.0
25,079
0.020894
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.4 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import ...
_StepVector._Pair_int_float_first_get if _newclass:first = _swig_property(_StepVector._Pair_int_float_first_get, _StepVector._Pair_int_float_first_set) __swig_setmethods__["second"] = _StepVector._Pair_int_float_second_set __swig_getmethods__["second"] = _StepVector._Pair_int_float_second_get if _newcla...
*args): this = _StepVector.new__Pair_int_float(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _StepVector.delete__Pair_int_float __del__ = lambda self : None; _Pair_int_float_swigregister = _StepVector._Pair_int_float_swigregister _Pair_int_float_swigregi...
tebeka/pythonwise
ansiprint.py
Python
bsd-3-clause
2,287
0.010931
#!/usr/bin/env python '''Print message using ANSI terminal codes''' __author__ = "Miki Tebeka <[email protected]>" from sys import stdout, stderr # Format bright = 1 dim = 2 underline = 4 blink = 5 reverse = 7 hidden = 8 # Forground black = 30 red = 31 green = 32 yellow = 33 blue = 34 magenta = 35 cyan = 36 white...
ht" : bright, "dim" : dim, "underline" : underline, "blink" : blink, "reverse" : reverse, "hidden
" : hidden, "black" : black, "red" : red, "green" : green, "yellow" : yellow, "blue" : blue, "magenta" : magenta, "cyan" : cyan, "white" : white, "on_black" : on_black, "on_red" : on_red, "on_green" : on_green, "on_yellow" :...
slippers/Flask-Prose
tests/security_models.py
Python
mit
2,079
0.002886
from flask_security import ( SQLAlchemyUserDatastore, UserMixin, RoleMixin, ) from sqlalchemy.ext.declarative import ( declarative_base, declared_attr, as_declarative ) from sqlalchemy.orm import relationship, backref from sqlalchemy import ( Table, Column, Integer, String, B...
) return SQLAlchemyUserDatastore(db, User, Role) def SetupUsers(user_datastore): user_datastore.find_or_create_role(name='prose_admin', description='prose administrator') user_datastore.find_or_create_role(name='reader', description='prose reader') if not user_datastore.get_user('[email protected]'...
r('[email protected]', 'reader') if not user_datastore.get_user('[email protected]'): user_datastore.create_user(email='[email protected]', password='test123') user_datastore.add_role_to_user('[email protected]', 'prose_admin')
Nexenta/s3-tests
virtualenv/lib/python2.7/site-packages/boto/mturk/connection.py
Python
mit
42,336
0.001323
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
security_token=security_token, profile_name=profile_name) def _required_auth_capability(self): return ['mturk'] def get_account_balance(self): """ """ params = {} return self._process_request('GetAccoun...
[('AvailableBalance', Price), ('OnHoldBalance', Price)]) def register_hit_type(self, title, description, reward, duration, keywords=None, approval_delay=None, qual_req=None): """ Register a new HIT Type ...
kit-cel/gr-drm
python/qa_cell_mapping_cc.py
Python
gpl-3.0
1,593
0.008161
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 <+YOU OR YOUR COMPANY+>. # # This 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) # any later version. #...
# from gnuradio import gr, gr_unittest from gnuradio import blocks import drm_swig as drm class qa_cell_mapping_cc (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () self.tp = drm.transm_params(1, 3, False, 0, 1, 0, 1, 1, 0, False, 24000, "station label", "text message") ...
len_msc = self.tp.msc().N_MUX() * self.tp.ofdm().M_TF() vlen_sdc = self.tp.sdc().N() vlen_fac = self.tp.fac().N() * self.tp.ofdm().M_TF() self.cell_mapping = drm.cell_mapping_cc(self.tp, (vlen_msc, vlen_sdc, vlen_fac)) def tearDown (self): self.tb = None def test_001_t (self): ...
googleads/google-ads-python
google/ads/googleads/v9/services/services/account_budget_service/transports/__init__.py
Python
apache-2.0
1,063
0
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #
You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is
distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict from typing import Dict, Type from .base import AccountBudgetServiceTr...
mmaker/bridgedb
lib/bridgedb/runner.py
Python
bsd-3-clause
4,313
0.000696
# -*- coding: utf-8 -*- # # This file is part of BridgeDB, a Tor bridge distribution system. # # :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <[email protected]> # please also see AUTHORS file # :copyright: (c) 2007-2013, The Tor Project, Inc. # (c) 2007-2013, all entities within the AUTHORS file...
ints, and sign the descriptors, among other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number of mocked bridges to generate descriptor for. (d
efault: 3) :type rundir: string or None :param rundir: If given, use this directory as the current working directory for the bridge descriptor generator script to run in. The directory MUST already exist, and the descriptor files will be created in it. If None, use the whatever directory...
dreieinhalb/canteenie
archive/canteenie_v1.py
Python
apache-2.0
3,987
0.029678
#!/usr/bin/env python3 """canteenie.py: A small python script that prints today's canteen/mensa menu for FAU on console.""" import requests import datetime import argparse from lxml import html from colorama import Fore, Style import textwrap import xmascc # command line arguments parser = argparse.ArgumentParser(de...
e_amount] if not args['lite']: wrap(meal_special_string) else: print(meal_special_string) if not args['lite']: print(Style.RESET_ALL + '', end="") i += 1 else: meal_special_count += 1 i += 1 print("") if not args['lite']: print("") #xmascc #if not args['lite']: print(Fore.MAGENTA + '', end=...
"")
circlesabound/matchr
server/Auth.py
Python
apache-2.0
4,880
0.005123
# Credit to original post from Amar Birgisson at # http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions # Form based authentication for CherryPy. Requires the # Session tool to be loaded. import cherrypy import urllib import DB from jinja2 import Environment, FileSystemLoader env = Environment(loader=F...
"""A tool that looks in config for 'auth.require'. If found and it is not None, a login is required and the entry is evaluated as alist of conditions that the user must fulfill""" conditions = cherrypy.request.config.get('auth.require', None) # format GET params get_parmas = urllib.parse.quote(c...
if username: cherrypy.request.login = username for condition in conditions: # A condition is just a callable that returns true or false if not condition(): # Send old page as from_page parameter raise cherrypy.HTTPR...
aroth-arsoft/arsoft-meta-packages
grp_java.py
Python
gpl-3.0
2,247
0.040498
#!/usr/bin/python # -*- coding: utf-8 -*- # kate: space-indent on; indent-width 4; mixedindent off; indent-mode python; java = [ {'name':'common', 'mainpackage':True, 'shortdesc':'Installs the latest version of Java', 'description':'', 'packages-trusty':['openjdk-7-jre-lib'], 'packages-xenia...
ckages-bionic':['openjdk-8-jre'], 'packages-focal':['openjdk-11-jre'], 'packages-groovy':['openjdk-11-jre'], }, {'name':'jdk', 'shortdesc':'Installs
the latest version of the Java Development Kit', 'description':'', 'depends':['jre'], 'packages-trusty':['openjdk-7-jdk', 'openjdk-8-jdk'], 'packages-xenial':['openjdk-8-jdk'], 'packages-bionic':['openjdk-8-jdk'], 'packages-focal':['openjdk-11-jdk'], 'packages-groovy':['openjdk-11-jdk'], ...
yayoiukai/signalserver
signals/urls.py
Python
mit
541
0
from django.conf.urls import url from . import views app_name = 'signals' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^process/$', views.process, name='process'), url(r'^file_process_status/$', views.file_process_status, name='file_process_status'), url(r'^get_graph/$', views....
data/$', views.get_graph_data, name='get_graph_data'),
url(r'^delete_output/(?P<process_pk>[\w.]{0,256})$', views.delete_output, name='delete_output'), ]
meshy/django-conman
example/example/migrations/0001_initial.py
Python
bsd-2-clause
1,026
0.000975
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-03 07:40 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ('routes'...
ToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='routes.Route')), ('raw_html', models.TextField(verbose_name='Raw HTML')), ], options={
'abstract': False, }, bases=('routes.route',), managers=[ ('objects', django.db.models.manager.Manager()), ('base_objects', django.db.models.manager.Manager()), ], ), ]
depp/sglib
script/d3build/msvc/project.py
Python
bsd-2-clause
11,200
0.000982
# Copyright 2014 Dietrich Epp. # This file is part of SGLib. SGLib is licensed under the terms of the # 2-clause BSD license. For more information, see LICENSE.txt. import uuid as uuid_module import xml.etree.ElementTree as etree from ..util import indent_xml from ..error import ConfigError import io import os Elemen...
r gelem in doc.getroot(): if gelem.tag == gtag: for pelem in gelem: if pelem.tag == ptag: return uuid_module.UUID(pelem.text) raise ConfigError('could not de
tect project UUID: {}'.format(path)) def get_configs(): gtag = etree.QName(XMLNS, 'ItemGroup') itag = etree.QName(XMLNS, 'ProjectConfiguration') ctag = etree.QName(XMLNS, 'Configuration') ptag = etree.QName(XMLNS, 'Platform') configs = [] for gelem in doc.getroot(): ...
rodrigolucianocosta/ProjectParking
ProjectParking/Parking/django-localflavor-1.1/tests/test_generic.py
Python
mpl-2.0
12,114
0.001486
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.exceptions import ValidationError, ImproperlyConfigured from django.test import SimpleTestCase, TestCase from django.utils import formats from localflavor.generic.models import BICField, IBANField from localflavor.generic.validators impo...
_date_input_formats) self.
assertInputFormats(time_field, ()) def test_init_custom_input_formats(self): date_input_formats = ('%m/%d/%Y', '%m/%d/%y') time_input_formats = ('%H:%M', '%H:%M:%S') field = SplitDateTimeField(input_date_formats=date_input_formats, input_time_formats=time_...
sjaa/scheduler
sched_core/models.py
Python
gpl-3.0
352
0.011364
from django.db import models class TimeStampedModel(models.Model): ''' Ab abstract base class model that provides self- updating 'created' and 'modified' fields. ''' created = models.DateTimeField(auto_now_add=True) modified = models.DateT
imeField(auto_now =True) class Meta: abs
tract = True
andycavatorta/oratio
Roles/avl-formant-3/main.py
Python
mit
7,853
0.006494
import commands import os import Queue import settings import time import threading import wiringpi as wpi import sys import traceback #BASE_PATH = os.path.dirname(os.path.realpath(__file__)) #UPPER_PATH = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0] #DEVICES_PATH = "%s/Hosts/" % (BASE_PATH ) #THIRTYB...
quest": self.get_device_status() if topic == "voice_3": master_volume = msg[1] * 100 master_volume = 0 if master_volume < 10 else master_volume - 10 except Queue.Empty: pass #i...
: #print "upside A master_volume=", master_volume, "self.last_master_volume_level", self.last_master_volume_level self.last_master_volume_level = self.last_master_volume_level + 1 gain = int(102 + (self.last_master_volume_level)) if self.last_master_volume_lev...
rddim/Notepad-plus-plus
scintilla/scripts/ScintillaData.py
Python
gpl-3.0
10,927
0.005583
#!/usr/bin/env python3 # ScintillaData.py - implemented 2013 by Neil Hodgson [email protected] # Released to the public domain. # Common code used by Scintilla and SciTE for source file regeneration. # The ScintillaData object exposes information about Scintilla as properties: # Version properties # versi...
trip() if l.endswith("\""): l = l[:-1] # Fix escaped double quotes l = l.replace("\\\"", "\"") documents[name] += l else: name = "" for name in list(documents.keys()): ...
stage = 0 with historyFile.open(encoding="utf-8") as f: for l in f.readlines(): l = l.strip() if stage == 0 and l == "<table>": stage = 1 elif stage == 1 and l == "</table>": stage = 2 if stage == 1 and l.startswit...
RudolfCardinal/crate
crate_anon/preprocess/preprocess_pcmis.py
Python
gpl-3.0
35,444
0
#!/usr/bin/env python """ crate_anon/preprocess/preprocess_pcmis.py =============================================================================== Copyright (C) 2015-2021 Rudolf Cardinal ([email protected]). This file is part of CRATE. CRATE is free software: you can redistribute it and/or modify i...
sion 3 of the License, or (at your option) any later version. CRATE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CRATE. If not, see <https://www.gnu.org/licenses/>. ...
werbk/task-5.14
tests_group/group_lib.py
Python
apache-2.0
3,504
0.001427
from sys import maxsize class Group: def __init__(self, group_name=None, group_header=None, group_footer=None, id=None): self.group_name = group_name self.group_header = group_header self.group_footer = group_footer self.id = id def __repr__(self): return '%s:%s' % (se...
class GroupBase: def __init__(self, app): self.app = app def open_group_page(self): wd = self.app.wd if not (wd.current_url.endswith('/group.php') and len(wd.find_elements_by_name('new')) > 0): wd.find_element_by_link_text("grou
ps").click() def count(self): wd = self.app.wd self.open_group_page() return len(wd.find_elements_by_name("selected[]")) def validation_of_group_exist(self): if self.count() == 0: self.create(Group(group_name='test')) self.click_group_page() def gro...
renalreg/radar
tests/test_round_age.py
Python
agpl-3.0
257
0
import pytest from radar.utils import round_age @pytest.m
ark.parametrize(['months', 'expected'], [ (3, 3), # 3 months (60, 60), # 5 years (61, 60), # 5 years, 1 month ]) def test(months, expected):
assert round_age(months) == expected
DinoCow/airflow
airflow/providers/amazon/aws/operators/cloud_formation.py
Python
apache-2.0
3,375
0.001481
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
self.stack_name = stack_name self.params = params self.aws_conn_id = aws_conn_id def execute(self, context): self.log.info('Parameters:
%s', self.params) cloudformation_hook = AWSCloudFormationHook(aws_conn_id=self.aws_conn_id) cloudformation_hook.create_stack(self.stack_name, self.params) class CloudFormationDeleteStackOperator(BaseOperator): """ An operator that deletes a CloudFormation stack. :param stack_name: stack...
emersonsoftware/ansiblefork
lib/ansible/galaxy/role.py
Python
gpl-3.0
14,352
0.003344
######################################################################## # # (C) 2015, Brian Coca <[email protected]> # # 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...
display.vvvvv("Unable to load metadata for %s" % self.name) return False finally: f.close() return self._metadata @property def install_info(self): """ Returns role install info """ if self._install_in...
info_path, 'r') self._install_info = yaml.safe_load(f) except: display.vvvvv("Unable to load Galaxy install info for %s" % self.name) return False finally: f.close() return self._install_info def...
psiq/gdsfactory
pp/components/waveguide.py
Python
mit
4,434
0.001804
from typing import List, Tuple import hashlib import pp from pp.name import autoname from pp.components.hline import hline from pp.component import Component @autoname def waveguide( length: float = 10.0, width: float = 0.5, layer: Tuple[int, int] = pp.LAYER.WG, layers_cladding: List[Tuple[int, int]...
er0 ) return component @autoname def waveguide_slab(length=10.0, width=0.5, cladding=2.0, slab_layer=pp.LAYER.SLAB90): width = pp.bias.width(width) ymin = width / 2 ymax = ymin + cladding windows = [(-ymin, ymin, pp.LAYER.WG), (-ymax, ymax, slab_layer)] return _arbitrary_straight_waveguid...
nches( length=10.0, width=0.5, layer=pp.LAYER.WG, trench_width=3.0, trench_offset=0.2, trench_layer=pp.LAYER.SLAB90, ): width = pp.bias.width(width) w = width / 2 ww = w + trench_width wt = ww + trench_offset windows = [(-ww, ww, layer), (-wt, -w, trench_layer), (w, wt, trenc...
nicogid/Projet4Moc1
api/projet-old/distributor_api/migrations/0011_sensor_id_distributor.py
Python
mit
605
0.001653
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-20 13:13 from __future__ import unicode_lit
erals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('distributor_api', '0010_remove_sensor_id_distributor'), ] operations = [ migrations.AddField( model_name='sensor', ...
ignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='distributor_api.Distributor'), ), ]
mathiasertl/django-xmpp-server-list
account/migrations/0001_initial.py
Python
gpl-3.0
2,915
0.004803
from django.db import models, migrations import django.utils.timezone import django.core.validators class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='LocalUser', fields=[ ...
rue, primary_key=True)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=django.utils.t
imezone.now, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(help_text='Required. 30 characters ...
Fierydemise/ShadowCraft-Engine
shadowcraft/calcs/__init__.py
Python
lgpl-3.0
30,637
0.00457
from __future__ import division from future import standard_library standard_library.install_aliases() from builtins import zip from builtins import str from builtins import object import gettext import builtins import math import os import subprocess _ = gettext.gettext from shadowcraft.core import exceptions from s...
e(spec=self.spec) * proc.duration / 60
e_lambda = math.e ** lambd e_minus_lambda = math.e ** (-1 * lambd) proc.uptime = 1.1307 * (e_lambda - 1) * (1 - ((1 - e_minus_lambda) ** proc.max_stacks)) else: mean_proc_time = 60 / (haste * proc.get_rppm_proc_rate(spec=self.spec)) + proc.icd - min(proc.icd, 10) ...
iLoop2/ResInsight
ThirdParty/Ert/devel/python/test/ert_tests/ecl/test_grdecl.py
Python
gpl-3.0
3,995
0.00776
#!/usr/bin/env python # Copyright (C) 2011 Statoil ASA, Norway. # # The file 'sum_test.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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...
fileH = open(tmp_file2, "w") kw1.write_grdec
l(fileH) fileH.close() self.assertFilesAreEqual(tmp_file1, tmp_file2) def test_fseek( self ): file = open(self.src_file, "r") self.assertTrue(EclKW.fseek_grdecl(file, "PERMX")) self.assertFalse(EclKW.fseek_grdecl(file, "PERMY")) file.close() file = open(se...
awildeone/Wusif
pyborg.py
Python
gpl-2.0
42,867
0.034893
# -*- coding: utf-8 -*- # # PyBorg: The python AI bot. # # Copyright (c) 2000, 2006 Tom Morton, Sebastien Dailly # # # This bot was inspired by the PerlBorg, by Eric Bock. # # 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 th...
you ge
t KeyError crashes", "rebuilddict": "Owner command. Usage: !rebuilddict\nRebuilds dictionary links from the lines of k
branto1/ceph-deploy
ceph_deploy/hosts/centos/install.py
Python
mit
6,289
0.002067
from ceph_deploy.util import templates from ceph_deploy.lib import remoto from ceph_deploy.hosts.common import map_components from ceph_deploy.util.paths import gpg NON_SPLIT_PACKAGES = ['ceph-osd', 'ceph-mon', 'ceph-mds'] def rpm_dist(distro): if distro.normalized_name in ['redhat', 'centos', 'scientific'] and...
rt, )
elif version_kind == 'testing': url = 'http://ceph.com/rpm-testing/{repo}/'.format(repo=repo_part) remoto.process.run( distro.conn, [ 'rpm', '-Uvh', '--replacepkgs', '{url}noarc...
WilliamQLiu/django-cassandra-prototype
cass-prototype/reddit/management/commands/cassandra_initialize.py
Python
mit
522
0.003831
from django.core.management.base import BaseCommand from cassandra.cluster import Cluster, NoHostAvailable class Command(BaseCommand): #http://datastax.github.io/python-driver/getting_started.html def handle(self, *arg
s, **options): print "Running Cassandra Initialize" cluster = Cluster(['127.0.0.1']) try: session = cluster.connect() except NoHostAvaila
ble: print "No Cassandra Host Available: Check Cassandra has started" cluster.shutdown()
brsbilgic/django-quick-reports
quick_reports_demo/main/migrations/0001_initial.py
Python
mit
1,707
0.002929
# -*- codin
g: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settin
gs class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto...
basti2342/simple-ledstrip
extended-dioder.py
Python
mpl-2.0
5,582
0.03565
#!/usr/bin/env python # -*- coding: utf-8 -*- import colorsys, time, random, signal from dioder import Dioder, SerialLogic from threading import Thread class ExtendedDioder(Dioder, Thread): def __init__(self, *args, **kwargs): super(ExtendedDioder, self).__init__(*args, **kwargs) # thread status self.running =...
reen(self): self.colorWipe((0, 255, 0)) def wipeBlue(self): self.colorWipe((0, 0, 255)) def colorWipe(self, color, waitMs=50): for i in range(self.limits[1]): if self.shouldBreak(): return self.setColor(i, *color) self.show() time.sleep(waitMs*0.001) # like colorWipe() but from center def color...
!= self.limits[1]: if self.shouldBreak(): return self.setColor(i, *color) self.setColor(j, *color) self.show() time.sleep(waitMs*0.001) i -= 1 j += 1 # like colorWipe() but from first and last LED def colorWipeCenterReverse(self, color=(0, 255, 0), waitMs=50): center = int(round(self.limits[1...
kdeloach/gwlf-e
gwlfe/AnnualMeans.py
Python
apache-2.0
5,840
0.000342
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division """ Imported from AnnualMeans.bas """ import logging log = logging.getLogger(__name__) def CalculateAnnualMeanLoads(z, Y): # UPDATE SEPTIC SYSTEM AVERAGES z.AvSeptNitr += z...
m = sum(z.AvTileDrainP) z.AvTileDrainSedSum = sum(z.AvTileDrainSed) z.AvPrecipitationSum = sum(z.AvPrecipitation) z.AvEvapoTransSum = sum(z
.AvEvapoTrans) z.AvGroundWaterSum = sum(z.AvGroundWater) z.AvRunoffSum = sum(z.AvRunoff) z.AvErosionSum = sum(z.AvErosion) z.AvSedYieldSum = sum(z.AvSedYield) z.AvDisNitrSum = sum(z.AvDisNitr) z.AvTotNitrSum = sum(z.AvTotNitr) z.AvDisPhosSum = sum(z.AvDisPhos) z.AvTotPhosSum = sum(z.AvTo...
madhat2r/plaid2text
src/python/plaid2text/online_accounts.py
Python
gpl-3.0
2,305
0.004338
#! /usr/bin/env python3 from collections import OrderedDict import datetime import os import sys import textwrap from plaid import Client from plaid import errors as plaid_errors import plaid2text.config_manager as cm from plaid2text.interact import prompt, clear_screen, NullValidator from plaid2text.interact import...
d_date.strftime("%Y-%m-%d"), account_ids=account_array, offset=len(ret)) except plaid_errors.ItemError as ex: print("Unable to update plaid account [%s] due to: " % account_ids, file=sys.stderr) print(" %s" % ...
ret.extend(response['transactions']) if len(ret) >= total_transactions: break print("Downloaded %d transactions for %s - %s" % ( len(ret), start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))) return ret
swift-lang/swift-e-lab
parsl/configs/comet_ipp_multinode.py
Python
apache-2.0
1,364
0.002933
from parsl.channels import SSHChannel from parsl.providers import SlurmProvider from parsl.launchers import
SrunLauncher from parsl.config import Config from parsl.executors.ipp import IPyParallelExecutor from parsl.executors.ipp_controller import Con
troller # This is an example config, make sure to # replace the specific values below with the literal values # (e.g., 'USERNAME' -> 'your_username') config = Config( executors=[ IPyParallelExecutor( label='comet_ipp_multinode', provider=SlurmProvider( ...
WarrenWeckesser/scipy
scipy/stats/_discrete_distns.py
Python
bsd-3-clause
50,628
0.000316
# # Author: Travis Oliphant 2002-2011 with contributions from # SciPy Developers 2004-2011 # from functools import partial from scipy import special from scipy.special import entr, logsumexp, betaln, gammaln as gamln, zeta from scipy._lib._util import _lazywhere, rng_integers from numpy import floor, ceil, ...
boost._binom_variance(n, p) g1, g2 = None, None if 's' in moments:
g1 = _boost._binom_skewness(n, p) if 'k' in moments: g2 = _boost._binom_kurtosis_excess(n, p) return mu, var, g1, g2 def _entropy(self, n, p): k = np.r_[0:n + 1] vals = self._pmf(k, n, p) return np.sum(entr(vals), axis=0) binom = binom_gen(name='bin...
PyCQA/pylint
tests/functional/n/non/non_ascii_name.py
Python
gpl-2.0
133
0.00813
""" Tests for non-ascii-name checker. """ áéíóú = 4444 # [non-ascii-name] def úóíé
á(): # [non-a
scii-name] """yo"""
appuio/ansible-role-openshift-zabbix-monitoring
vendor/openshift-tools/ansible/roles/lib_openshift_3.2/build/src/oc_version.py
Python
apache-2.0
2,732
0.001464
# pylint: skip-file # pylint: disable=too-many-instance-attributes class OCVersion(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' # pylint allows 5 # pylint: disable=too-many-arguments def __init__(self, config, debug): ''' Constructor for OCVer...
es not return
an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict @staticmethod def add_custom_versions(versions): ''' create custom versions strings ''' versions_dict = {} for tech, version in v...
aspose-words/Aspose.Words-for-Cloud
Examples/Python/Examples/ReadingAllHyperlinksFromDocument.py
Python
mit
1,469
0.012253
import asposewordscloud from asposewordscloud.WordsApi import WordsApi from asposewordscloud.WordsApi import ApiException from asposewordscloud.models import ProtectionRequest import asposestoragecloud from asposestoragecloud.StorageApi import StorageApi from asposestoragecloud.StorageApi import ResponseMessage apiK...
rue) storageApi = StorageApi(storage_apiClient) #Instantiate Aspose Words API SDK api_client = asposewordscloud.ApiClient.ApiClient(apiKey, appSid, True) wordsApi = WordsApi(api_client) #set input file name filename = "SampleWordDocument.docx" #upload file to aspose cloud storage storageApi.PutCreate(Path=filename, f...
ds Cloud SDK API to get all the hyperlinks in a word document response = wordsApi.GetDocumentHyperlinks(name=filename) if response.Status == "OK": #display the hyperlinks info for hyperlink in response.Hyperlinks.HyperlinkList: print "Display Text: " + hyperlink.DisplayText + " Va...
nagyistoce/devide
modules/vtk_basic/vtkImageHSIToRGB.py
Python
bsd-3-clause
489
0.002045
# class generated by DeVIDE::createDeVIDEMod
uleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkImageHSIToRGB(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageHSIToRGB(), 'Processing.', ...
s=None)
ruiting/opencog
opencog/python/pln_old/examples/tuffy/smokes/smokes_agent.py
Python
agpl-3.0
5,370
0.00149
""" PLN representation of the "smokes" sample from Tuffy Markov Logic Networks More details on this sample are available here: https://github.com/opencog/opencog/tree/master/opencog/python/pln_old/examples/tuffy/smokes https://github.com/cosmoharrigan/tuffy/tree/master/samples/smoke http://hazy.cs.wisc.edu/hazy/tuffy/...
oms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True,
delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) # stimulateAtoms is only enabled when the agent is ran insid...
andrei4ka/fuel-web-redhat
nailgun/nailgun/objects/serializers/release.py
Python
apache-2.0
1,707
0
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, 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 requi...
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 express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nailgun...
objects.serializers.base import BasicSerializer class ReleaseSerializer(BasicSerializer): fields = ( "id", "name", "version", "can_update_from_versions", "description", "operating_system", "modes_metadata", "roles", "roles_metadata", ...
grezesf/Research
Reservoirs/Task5-Memory_Tuning/task5.py
Python
mit
2,640
0.007576
import mdp import Oger import numpy import pylab import random ### README # study the memory capacities of same size reservoirs def main(): num_waves = 100 waves = [gen_test_wave(2.0*random.random()-1.0) for x in range(num_waves)] print "Shape of waves" , numpy.shape(waves[0]) ### Create reservoir...
s nx = 5+1 ny = 1 # #plot the input for wave in waves: pylab.subplot(nx, ny, 1) pylab.plot(wave) # plot the activity
for first 5 inputs for num in range(5): pylab.subplot(nx, ny, num+2) pylab.plot(reservoir.inspect()[num]) pylab.show() # end of main return None def gen_test_wave(max_value = 1): # generates a 1D test wave # simple step function # tunable parameters # the max value ...
luci/recipes-py
recipes/engine_tests/proto_properties.py
Python
apache-2.0
1,095
0.004566
# Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. from PB.recipes.recipe_engine.engine_tests import proto_properties PYTHON_VERSION_COMPATIBILITY = 'PY2+3' DEPS = [ 'assertions', 'proper...
100, some_string='hey there', ), ignored_prop='yo') + api.properties.environ( proto_properties.EnvProperties( STR_ENV="sup",
INT_ENV=9000, )) + api.post_process(lambda _check, _steps: {}))
mrunge/openstack_horizon
openstack_horizon/dashboards/project/data_processing/cluster_templates/forms.py
Python
apache-2.0
2,210
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-
2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the Licen...
ort ugettext_lazy as _ from horizon_lib import exceptions from horizon_lib import forms from openstack_horizon.api import sahara as saharaclient from openstack_horizon.dashboards.project.data_processing. \ utils import workflow_helpers LOG = logging.getLogger(__name__) class UploadFileForm(forms.SelfHandlingFo...
tomjelinek/pcs
pcs/cli/file/metadata.py
Python
gpl-2.0
1,201
0
import os.path from pcs.common import file_type_codes as code from pcs.common.file import FileMetadata _metadata = { code.BOOTH_CONFIG: lambda path: FileMetadata( file_type_code=code.BOOTH_CONFIG, path=path, owner_user_name=None, owner_group_name=None, permissions=None, ...
), code.COROSYNC_CONF: lambda path: FileMetadata( file_type_code=code.COROSYNC_CONF, path=path, owner_user_name=None, owner_group_name=None, permissions=0o644, is_binary=False, ), code.PCS_KNOWN_HOSTS: lambda: FileMetadata( file_type_code=code.PCS_K...
S, path=os.path.join(os.path.expanduser("~/.pcs"), "known-hosts"), owner_user_name=None, owner_group_name=None, permissions=0o600, is_binary=False, ), } def for_file_type(file_type_code, *args, **kwargs): return _metadata[file_type_code](*args, **kwargs)
mahabs/nitro
nssrc/com/citrix/netscaler/nitro/resource/stat/qos/qos_stats.py
Python
apache-2.0
18,855
0.052453
# # Copyright (c) 2008-2015 Citrix Systems, 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 l...
f ipcmessagessentrate(self) : """Rate (/s) counter for ipcmessagessent. """ try : return self._ipcmessages
sentrate except Exception as e: raise e @property def qoslink02sentrate(self) : """Rate (/s) counter for qoslink02sent. """ try : return self._qoslink02sentrate except Exception as e: raise e @property def qosrewritemacsrate(self) : """Rate (/s) counter for qosrewritemacs. """ try : re...
swindonmakers/axCutHost
backend/filereaders/svg_tag_reader.py
Python
gpl-3.0
9,861
0.003144
__author__ = 'Stefan Hechenberger <[email protected]>' import re import math import logging from .utilities import matrixMult, parseFloats from .svg_attribute_reader import SVGAttributeReader from .svg_path_reader import SVGPathReader log = logging.getLogger("svg_reader") class SVGTagReader: def __init__(sel...
sform and style attributes if self._has_valid_stroke(node): w = node.get('width') or 0.0 h =
node.get('height') or 0.0 x = node.get('x') or 0.0 y = node.get('y') or 0.0 rx = node.get('rx') ry = node.get('ry') if rx is None and ry is None: # no rounded corners d = ['M', x, y, 'h', w, 'v', h, 'h', -w, 'z'] self._pathRea...
mxmzdlv/pybigquery
tests/unit/test_select.py
Python
mit
15,799
0.002469
# Copyright (c) 2021 The sqlalchemy-bigquery Authors # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, mer...
AIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import datetime from decimal import Decimal import packaging.version import pytest
import sqlalchemy import sqlalchemy_bigquery from conftest import ( setup_table, sqlalchemy_version, sqlalchemy_1_3_or_higher, sqlalchemy_1_4_or_higher, sqlalchemy_before_1_4, ) def test_labels_not_forced(faux_conn): table = setup_table(faux_conn, "t", sqlalchemy.Column("id", sqlalchemy.Int...
elainenaomi/sciwonc-dataflow-examples
dissertation2017/Experiment 2/instances/7_2_wikiflow_1sh_1s_noannot_wmj/init_0/DataStoreInit.py
Python
gpl-3.0
1,335
0.006742
#!/usr/bin/env python from pymongo import MongoClient import pymongo HOST = "wfSciwoncWiki:[email protected]:27001/?authSource=admin" c = MongoClient('mongodb://'+HOST) dbname = "wiki" sessions = "sessions" contributors = "contributors" user_sessions = "user_sessions" top_sessio
ns = "top_sessions" c[dbname].drop_collection(contributors) c[dbname].create_collection(contributors) c[dbname].drop_collection(user_sessions) c[dbname].create_collection(user_sessions) c[dbname].drop_collection(top_sessions) c[dbname].
create_collection(top_sessions) db = c[dbname] sessions_col = db[sessions] contributors_col = db[contributors] user_sessions_col = db[user_sessions] top_sessions_col = db[top_sessions] sessions_col.create_index([("contributor_username", pymongo.ASCENDING)]) sessions_col.create_index([("timestamp", pymongo.ASCENDING...
dakrauth/picker
picker/urls/picks.py
Python
mit
1,495
0.00602
from django.urls import include, re_path from .. import views management_urls = [ re_path(r'^$', views.ManagementHome.as_view(), name='picker-manage'), re_path(r'^game/(\d+)/$', views.ManageGame.as_view(), name='picker-manage-game'), re_path(r'^(?P<season>\d{4})/', include(
[ re_path(r'^$', views.ManageSeason.as_view(), name='picker-manage-season'), re_path(r'^(-?\d+)/$', views.ManageWeek.as_view(), name='picker-manage-week'), ])), ] picks_urls = [ re_path(r'^$', views
.Picks.as_view(), name='picker-picks'), re_path(r'^(?P<season>\d{4})/', include([ re_path(r'^$', views.PicksBySeason.as_view(), name='picker-season-picks'), re_path(r'^(-?\d+)/$', views.PicksByGameset.as_view(), name='picker-picks-sequence'), ])), ] results_urls = [ re_path(r'^$', views.Res...
gonicus/gosa
backend/src/tests/backend/components/test_jsonrpc_objects.py
Python
lgpl-2.1
11,005
0.003635
# This file is part of the GOsa framework. # # http://gosa-project.org # # Copyright: # (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de # # See the LICENSE file in the project's top-level directory for details. from unittest import mock, TestCase import datetime from gosa.backend.components.jsonrpc_objects im...
rt user.commit.called def test_diffObject(self): assert self.mapper.diffObject('admin', 'unkown_ref') is None res = self.openObject('admin', None, 'object', 'cn=Frank Reich,ou=people,dc=example,dc=net') ref = res["__jsonclass__"][1][1] with pytest.raises(ValueError): s...
se', ref) self.mapper.setObjectProperty('admin', ref, 'uid', 'val') delta = self.mapper.diffObject('admin', ref) assert 'uid' in delta['attributes']['changed'] def test_removeObject(self): res = self.openObject('admin', None, 'object', 'cn=Frank Reich,ou=people,dc=example,dc=net') ...
kslundberg/pants
contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py
Python
apache-2.0
20,160
0.007192
# coding=utf-8 # Copyright 2014 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 ast import lo...
s in a BUILD target's dependencies section. """ def __init__(self, spec, comments_above=None, side_comment=None): self.spec = spec self.comments_above = comments_above or [] self.side_comment = side_comment def comments
_above_lines(self): for line in self.comments_above: line = line.strip() if line: yield '# {line}'.format(line=line) else: yield '' def indented_lines(self, lines, indent=4): indent_spaces = ' ' * indent for line in lines: line = line.strip() if not line: ...
aqualid/aqualid
make/aql_linker.py
Python
mit
11,736
0
import re import os.path import datetime import base64 import aql # ============================================================================== info = aql.get_aql_info() HEADER = """#!/usr/bin/env python # # THIS FILE WAS AUTO-GENERATED. DO NOT EDIT! # # Copyright (c) 2011-{year} of the {name} project, site: {ur...
ded # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLD...
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """.format(year=datetime.date.today().year, name=info.name, url=info.url) # ============================================================================== AQL_DATE = '_AQL_VERSION_INFO.date = "{date}"'.format( date=datetime.date.today().isoformat()) # ...
cornelinux/django-linotp-auth
django_linotp/linotp_auth.py
Python
gpl-3.0
2,749
0.036741
''' Add the following to your project/settings.py AUTHENTICATION_BACKENDS = ('django_linotp.linotp_auth.LinOTP', ) LINOTP = { 'url' : 'https://puckel/validate/check', 'timeout' : 5, 'ssl_verify' : False, 'host_verify' : False, 'create_user' : False, } 'create_user': if set to True...
gs.LINOTP.get('url', self.url) self.timeout = settings.LINOTP.get('timeout', self.timeout) self.ssl_verify = settings.LINOTP.get('ssl_verify', self.ssl_verify) self.host_verify = settings.LINOTP.get('host_verify', self.host_verify) self.create_user = settings.LINOTP.get('create_user', self.create_us...
pycurl.Curl() params = { 'user' : username, 'pass' : password } url = str("%s?%s" % (self.url, urlencode(params))) print "Connecting to %s" % url c.setopt(c.URL, url) c.setopt(c.WRITEFUNCTION, t.body_callback) c.setopt(c.HEADER, False) c.setopt(c.SSL_VERIFYPEER, self.ssl_ver...
victorpoluceno/webrtc-sample-client
app/__init__.py
Python
mit
314
0.025478
from flask import
Flask from flask import render_template, request app = Flask(__name__) @app.route("/") def main(): room = request.args.get('room', '') if room: return render_template('watch.html') return render_template('index.html'
) if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
daisychainme/daisychain
daisychain/config/settings_local.py
Python
mit
1,754
0.00057
from .settings_base import * from config.keys import keys # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = keys['DJANGO
']['LOCAL'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES =
{ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'require_debug_false': { ...
digibyte/digibyte
test/functional/wallet_accounts.py
Python
mit
8,572
0.001633
#!/usr/bin/env python3 # Copyright (c) 2016-2017 The DigiByte Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test account RPCs. RPCs tested are: - getaccountaddress - getaddressesbyaccount - listadd...
ccount.name, to_account.receive_address, amount_to_send) node.generate(1) for account in accounts: account.add_receive_address(node.getaccountaddress(account.name)) account.verify(node)
assert_equal(node.getreceivedbyaccount(account.name), 2) node.move(account.name, "", node.getbalance(account.name)) account.verify(node) node.generate(101) expected_account_balances = {"": 5200} for account in accounts: expected_account_balances[account...
jelmer/xandikos
xandikos/store/config.py
Python
gpl-3.0
4,820
0
# Xandikos # Copyright (C) 2016-2017 Jelmer Vernooij <[email protected]>, et al. # # 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; version 3 # of the License or (at your option) any later version ...
essage):
if self._save_cb is None: return self._save_cb(self._configparser, message) @classmethod def from_file(cls, f): cp = configparser.ConfigParser() cp.read_file(f) return cls(cp) def get_source_url(self): return self._configparser["DEFAULT"]["source"] ...
redvasily/django-emailauth
emailauth/tests.py
Python
bsd-3-clause
14,812
0.003983
import re from datetime import datetime, timedelta from django.test.client import Client from django.test.testcases import TestCase from django.core import mail from django.contrib.auth.models import User from django.conf import settings from emailauth.models import UserEmail from emailauth.utils import email_verific...
) self.assertStatusCode(response, Status.OK) def testAddEmail(self): response = self.client.post('/account/addemail/', { 'email': '[email protected]', }) self.assertRedirects(response, '/account/addemail/continue/user%40example.org/') self.assertEqual(len(
mail.outbox), 1) email = mail.outbox[0] addr_re = re.compile(r'.*http://.*?(/\S*/)', re.UNICODE | re.MULTILINE) verification_url = addr_re.search(email.body).groups()[0] response = self.client.get(verification_url) self.assertRedirects(response, '/account/') client =...
ahmadpriatama/Flask-Simple-Ecommerce
appname/assets.py
Python
bsd-2-clause
490
0
from
flask_assets import Bundle common_css = Bundle( 'css/vendor/bootstrap.min.css', 'css/vendor/helper.css',
'selectize/dist/css/selectize.bootstrap3.css', # 'css/main.css', filters='cssmin', output='public/css/common.css' ) common_js = Bundle( 'js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'selectize/dist/js/standalone/selectize.min.js', Bundle( 'js/main.js', filters...
cpennington/edx-platform
openedx/core/djangoapps/schedules/management/commands/__init__.py
Python
agpl-3.0
2,311
0.001731
""" Base management command for sending emails """ import datetime import pytz from six.moves import range from django.contrib.sites.models import Site from django.core.management.base import BaseCommand from openedx.core.djangoapps.schedules.utils import PrefixedDebugLoggerMixin class SendEmailBaseCommand(Prefix...
m_weeks) + 1 self.offsets = range(-7, -num_days, -7) current_date = datetime.datetime( *[int(x) for x in options['date'].spl
it('-')], tzinfo=pytz.UTC ) self.log_debug(u'Current date = %s', current_date.isoformat()) site = Site.objects.get(domain__iexact=options['site_domain_name']) self.log_debug(u'Running for site %s', site.domain) override_recipient_email = options.get('override_recipi...
asedunov/intellij-community
python/testData/deprecation/deprecatedProperty.py
Python
apache-2.0
202
0.029703
class Foo: @property def bar(self): import warnings warnings.warn("this is deprecated", DeprecationWarni
ng, 2) foo = Foo() foo.<warning descr="
this is deprecated">bar</warning>
konstantint/eio-userdb
tests/conftest.py
Python
mit
273
0.003663
from
pytest import fixture from eio_userdb.main import app from eio_userdb.model import init_db @fixture def client(): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' app.config['TESTING'] = True client = app.test_cl
ient() init_db() return client
bamos/dotfiles
.xmonad/xmobar.py
Python
mit
655
0
#!/usr/bin/env python3 from datetime import datetime import psutil import sys import argparse parser = argparse.ArgumentParser() parser.add_argument('direction', type=str,
choices=['left', 'right']) args = parser.parse_args() status = '' if args.direction == 'left': status = '<fc=#B27AEB><fn=2>❤</fn></fc>' elif args.direction == 'right': battery = psutil.sensors_battery() if not battery.power_plugged:
status += f'<fc=#D43737><fn=1></fn>{int(battery.percent)}%</fc> ' now = datetime.now() time_str = now.strftime('%Y.%m.%d %-I:%M%p') status += f'<fc=#ABABAB>{time_str}</fc>' print(status)
iLoveTux/unitils
test/test_ls.py
Python
gpl-3.0
3,856
0.002075
import unittest import unitils from io import StringIO try: from unittest import mock except ImportError: import mock return_value = ( 'that', 'that', 'that', 'the other', 'the other', 'the other', 'this', 'this', 'this' ) column_test_return_value = ( "appveyor.yml", ...
"setup.cfg", "stats.dat", "test-data", "unitils.egg-info", ) class TestLsCLI(unittest.TestCase): @mock.patch("unitils.ls", return_value=ret
urn_value) def test_can_be_called_without_arguments(self, mock_ls): args = [] unitils.cli.ls(args) mock_ls.assert_called_with(path=".", _all=False, almost_all=False) @mock.patch("unitils.ls", return_value=column_test_return_value) @mock.patch("unitils.cli.get_terminal_size", return_...
ashepelev/TopologyWeigher
source/migrate_versions/243_topology_tables.py
Python
apache-2.0
2,616
0.019495
from migrate.changeset import UniqueConstraint from migrate import ForeignKeyConstraint from sqlalchemy import Boolean, BigInteger, Column, DateTime, Enum, Float from sqlalchemy import dialects from sqlalchemy import ForeignKey, Index, Integer, MetaData, String, Table from sqlalchemy import Text from sqlalchemy.types i...
e), Column('updated_at', DateTime), Column('deleted_at', DateTime), Column('deleted', Integer), Column('id',
Integer, primary_key=True, nullable=False), Column('start',Integer,nullable=False), Column('end',Integer,nullable=False), mysql_engine='InnoDB', mysql_charset='utf8' ) try: node_info.create() except Exc...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/IPython/core/magics/script.py
Python
bsd-2-clause
8,835
0.004754
"""Magic functions for running cells in various scripts.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import errno import os import sys import signal import time from subprocess import Popen, PIPE import atexit from IPython.core import magic_arguments from I...
cript cell magics to define This generates simple wrappers of `%%script foo` as `%%foo`. If you want to add script magics that aren't on your path, specify them in scri
pt_paths """, ).tag(config=True) @default('script_magics') def _script_magics_default(self): """default to a common list of programs""" defaults = [ 'sh', 'bash', 'perl', 'ruby', 'python', 'python2', ...