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
fagusMcFagel/ticketsystem
ticketsystem/tickets/views.py
Python
mit
49,979
0.008066
#standard library from _functools import reduce import imghdr ### IMPORT THE APPLICABLE SETTINGS SET IN manage.py ### from manage import USED_SETTINGS import importlib used_settings = importlib.import_module(USED_SETTINGS) settings_media_root = used_settings.MEDIA_ROOT settings_media_url = used_settings.MED...
et the form and set error to true else: error = True form = LoginForm() # if called normally (with GET-Request) else: # display currently logged in user, if existent if request.user.is_authenticated: logged_in_user = request.user ...
rlich!' return render( request, 'ticket_login.djhtml', {'form':form, 'error':error, 'login_user':logged_in_user, 'infomsg':infomsg} ) # view function for logging a user out and redirecting to the login page ''' #parameter: HttpRequest request #URL:...
klahnakoski/TestFailures
pyLibrary/queries/containers/tests/test_container.py
Python
mpl-2.0
5,642
0.00319
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import division from __future_...
"add": {"name": "a.b", "type": "nested", "nested_path": NullOp()} }]) self.assertEqual(collection, { ".": { "rows": [ {"__id__": 3, "a.$object": "."} ], "active_columns": {wrap({"es_column": "a.$object"}), wrap({"es_c...
"rows":[ {"__id__": 4, "__parent__": 3, "__order__": 0, "a.b.$number": 0}, {"__id__": 5, "__parent__": 3, "__order__": 1, "a.b.$number": 1} ], "active_columns": {wrap({"es_column": "a.b.$number"})} } }) ...
SerialShadow/SickRage
sickbeard/__init__.py
Python
gpl-3.0
114,709
0.005048
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
ERN = None NAMING_ABD_PATTERN = None NAMING_CUSTOM_ABD = False NAMING_SPORTS_PATTERN = None NAMING_CUSTOM_SPORTS = False NAMING_ANIME_PATTERN = None NAMING_CUSTOM_ANIME = False NAMING_FORCE_FOLDERS = False NAMING_STRIP_YEAR = False NAMING_ANIME = None USE_NZBS = False USE_TORRENTS = False NZB_METHOD = None NZB_DIR = ...
None DOWNLOAD_PROPERS = False CHECK_PROPERS_INTERVAL = None ALLOW_HIGH_PRIORITY = False SAB_FORCED = False RANDOMIZE_PROVIDERS = False AUTOPOSTPROCESSER_FREQUENCY = None DAILYSEARCH_FREQUENCY = None UPDATE_FREQUENCY = None BACKLOG_FREQUENCY = None SHOWUPDATE_HOUR = None DEFAULT_AUTOPOSTPROCESSER_FREQUENCY = 10 DEFAUL...
milinbhakta/flaskmaterialdesign
venv/Lib/importlib/util.py
Python
gpl-2.0
7,227
0.000692
"""Utility code for constructing importers, etc.""" from ._bootstrap import MAGIC_NUMBER from ._bootstrap import cache_from_source from ._bootstrap import decode_source from ._bootstrap import source_from_cache from ._bootstrap import spec_from_loader from ._bootstrap import spec_from_file_location from ._bootstrap im...
dule in sys.modules # (otherwise an optimization shortcut in import.c be
comes wrong) module.__initializing__ = True sys.modules[name] = module try: yield module except Exception: if not is_reload: try: del sys.modules[name] except KeyError: pass finally: module.__initializing__ = Fal...
dominikl/openmicroscopy
components/tools/OmeroPy/src/omero/plugins/cecog.py
Python
gpl-2.0
6,684
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Methods for working with cecog Copyright 2010 University of Dundee, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import os import re import sys from omero.cli import BaseControl, CLI import omero import omero.consta...
client.sf.getUpdateService() pixelsService = client.sf.getPixelsService() # if we don't have any folders in the 'dir' E.g. # CecogPackage/Data/Demo_data/0037/ # then 'Demo_data' becomes a dataset subDirs = [] for f in os.listdir(path): fullpath = path + f ...
ect name from path if len(subDirs) == 0: p = path[:-1] # will remove the last folder p = os.path.dirname(p) else: if os.path.basename(path) == "": p = path[:-1] # remove slash datasetName = os.path.basename(p) # e.g. Demo_data p ...
idalin/calibre-web
cps/fb2.py
Python
gpl-3.0
2,739
0.00146
# -*- coding: utf-8 -*- # This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) # Copyright (C) 2018 lemmsh, cervinko, OzzieIsaacs # # 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 S...
org/license
s/>. from __future__ import division, print_function, unicode_literals from lxml import etree from .constants import BookMeta def get_fb2_info(tmp_file_path, original_file_extension): ns = { 'fb': 'http://www.gribuser.ru/xml/fictionbook/2.0', 'l': 'http://www.w3.org/1999/xlink', } fb2_...
chrisspen/django-pjm
django_pjm/management/commands/import_pjm_loads.py
Python
mit
1,807
0.006641
from datetime import date from monthdelta import MonthDelta as monthdelta from optparse import make_option from django.core.management.base import NoArgsCommand, BaseCommand import dateutil.parser from django_pjm import models class Command(BaseCommand): help = "Imports PJM load values." args = '' opti...
e.day) else: end_date = date.today() segments = [_ for
_ in options['segments'].split(',') if _.strip()] while start_date <= end_date: for segment in segments: print 'Calculating for segment %s on start date %s.' % (segment, start_date) models.Load.calculate( year=start_date.year, ...
FabriceSalvaire/grouped-purchase-order
GroupedPurchaseOrder/bootstrap/components.py
Python
agpl-3.0
6,955
0.006039
#################################################################################################### # # GroupedPurchaseOrder - A Django Application. # Copyright (C) 2014 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic...
', 'primary', 'success', 'info', 'warning', 'danger', 'link') if style in button_styles: classes.append('btn-' + style) else: raise ValueError('Parameter style must be {} ("{}" given)', ', '.join(button_styles), style) # size = text_value(size).lower().strip() i...
: classes.append('btn-sm') elif size == 'lg' or size == 'large': classes.append('btn-lg') else: raise ValueError('Parameter "size" should be "xs", "sm", "lg" or empty ("{}" given)', format(size)) attrs['class'] = merge_new_words(butto...
brianwc/courtlistener
cl/citations/tasks.py
Python
agpl-3.0
5,964
0.000503
import re from django.core import urlresolvers from django.db import IntegrityError from cl.citations import find_citations, match_citations from cl.custom_filters.templatetags.text_filters import best_case_name from cl.search.models import Opinion, OpinionsCited from celery import task def get_document_citations(opi...
repl = u'</pre>%s<pre class="inline">' % citation.as_html() inner_html = re.sub(citation.as_regex(), repl, inner_html) new_html = u'<pre class="inline">%s</pre>' % inner_html return new_html.encode('utf-8') @task def update_document(opinion, index=True): """Get the citations f...
d add it to the index if requested.""" DEBUG = 0 if DEBUG >= 1: print "%s at %s" % ( best_case_name(opinion.cluster), urlresolvers.reverse( 'admin:search_opinioncluster_change', args=(opinion.cluster.pk,), ) ) citation...
lgp171188/fjord
fjord/base/middleware.py
Python
bsd-3-clause
5,915
0
""" The middlewares in this file do mobile detection, provide a user override, and provide a cookie override. They must be used in the correct order. MobileMiddleware must always come after any of the other middlewares in this file in `settings.MIDDLEWARE_CLASSES`. """ import urllib from warnings import warn from djan...
""" Add querystring override for mobile. This allows the
user to override mobile detection by setting 'mobile=1' in the querystring. This will persist in a cookie that other the other middlewares in this file will respect. """ def process_request(self, request): # The 'mobile' querystring overrides any prior MOBILE # figuring and we put it in...
facebook/fbthrift
thrift/compiler/test/fixtures/types/gen-py/include/__init__.py
Python
apache-2.0
147
0
# # Autogenerated by Thrift # # DO NOT EDIT UNLESS YOU ARE SURE THAT
YOU KNOW W
HAT YOU ARE DOING # @generated # __all__ = ['ttypes', 'constants']
dnanexus/rseqc
rseqc/lib/qcmodule/twoList.py
Python
gpl-3.0
2,098
0.039561
'''manipulate ndarray list''' from itertools import imap,starmap,izip from operator import mul,add,sub def check_list(v1,v2): '''check if the length of two list is same''' if v1.size != v2.size: raise ValueError,"the lenght of both arrays must be the same" pa...
check_list(v1,v2) return imap(max,izip(v1,v2)) def Min(v1,v2): '''pairwise comparison two list. return the max one between two paried number''' check_list(v1,v2) return imap(min,izip(v1,...
check_list(v1,v2) return (sum((v1.__sub__(v2))**2) / v1.size)**0.5
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/moto/sqs/urls.py
Python
agpl-3.0
267
0.011236
from .respons
es import QueueResponse, QueuesResponse url_bases = [ "https
?://(.*?)(queue|sqs)(.*?).amazonaws.com" ] url_paths = { '{0}/$': QueuesResponse().dispatch, '{0}/(?P<account_id>\d+)/(?P<queue_name>[a-zA-Z0-9\-_]+)': QueueResponse().dispatch, }
nextgis-extra/tests
lib_gdal/ogr/ogr_sde.py
Python
gpl-2.0
10,401
0.011826
#!/usr/bin/env python ############################################################################### # $Id: ogr_sde.py 33793 2016-03-26 13:02:07Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: Test OGR ArcSDE driver. # Author: Howard Butler <hobu.inc@gmail.com> # ############################################...
from osgeo import ogr from osgeo import osr from osgeo import gdal ############################################################################### # Open ArcSDE datasource. sde_server = '172.16.1.193' sde_port = '5151' sde_db = 'sde' sde_user = 'sde' sde_passwo
rd = 'sde' gdaltest.sde_dr = None try: gdaltest.sde_dr = ogr.GetDriverByName( 'SDE' ) except: pass def ogr_sde_1(): "Test basic opening of a database" if gdaltest.sde_dr is None: return 'skip' base = 'SDE:%s,%s,%s,%s,%s' % (sde_server, sde_port, sde_db, sde_user, sde_password) ds = o...
waterxt/tensorflowkaldi
neuralNetworks/nnet.py
Python
mit
9,220
0.005748
'''@file nnet.py contains the functionality for a Kaldi style neural network''' import shutil import os import itertools import numpy as np import tensorflow as tf import classifiers.activation from classifiers.dnn import DNN from trainer import CrossEnthropyTrainer from decoder import Decoder class Nnet(object): ...
n the neural network Args: dispenser: a batchdispenser for training data dispenser_dev: a batchdispenser for dev data ''' #put the DNN in a training environment epoch = int(self.conf['epoch']) max_epoch = int(self.conf['max_epoch'])
halve_learning_rate = int(self.conf['halve_learning_rate']) start_halving_impr = float(self.conf['start_halving_impr']) end_halving_impr = float(self.conf['end_halving_impr']) trainer = CrossEnthropyTrainer( self.dnn, self.input_dim, dispenser.max_input_length, dispen...
saurabhbajaj207/CarpeDiem
venv/Lib/site-packages/pyasn1_modules/rfc2251.py
Python
mit
26,833
0.004398
# # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # # LDAP message syntax # # ASN.1 source from: # http://www.trl.ibm.com/projects/xml/xss4j/data/asn1/grammars/ldap.asn # # Sample captures from: # http://wiki.wire...
().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2))), namedtype.NamedType('equalityMatch', AttributeValueAssertion().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))), namedtype.NamedType('substrings', SubstringFilter().subtype( ...
), namedtype.NamedType('greaterOrEqual', AttributeValueAssertion().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 5))), namedtype.NamedType('lessOrEqual', AttributeValueAssertion().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstru...
smallyear/linuxLearn
salt/salt/utils/yamlloader.py
Python
apache-2.0
3,478
0.000575
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import import warnings # Import third party
libs import yaml from yaml.nodes import MappingNode from yaml.constructor import ConstructorError try: yaml.Loader = yaml.CLoader yaml.Dumper = yaml.CDumper except Exception: pass # This function is safe and needs to stay as yaml.load. The load function # accepts a custom loader, and every time this funct...
e custom loader to be explicitly added. load = yaml.load # pylint: disable=C0103 class DuplicateKeyWarning(RuntimeWarning): ''' Warned when duplicate keys exist ''' warnings.simplefilter('always', category=DuplicateKeyWarning) # with code integrated from https://gist.github.com/844388 class SaltYamlSa...
ic-labs/django-icekit
icekit/plugins/iiif/apps.py
Python
mit
1,144
0
from django.apps import AppConfig from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType class AppConfig(AppConfig): name = '.'.join(__name__.split('.')[:-1]) label = 'icekit_plugins_iiif' verbose_name = "...
to hang it off for now... # TODO This is a hack, find a better way User = get_user_model() try: # this doesn't work if migrations haven't been updated, resulting # in "RuntimeError: Error creating new content types. Please make # sure contenttypes is migrated...
et_for_model(User) Permission.objects.get_or_create( codename='can_use_iiif_image_api', name='Can Use IIIF Image API', content_type=content_type, ) except RuntimeError: pass
wojtekwalczak/kaggle_titanic
titanic/transformers/FamilyCounter.py
Python
apache-2.0
946
0.005285
from __future__ import print_function import pandas as pd from sklearn.base import
TransformerMixin class FamilyCounter(TransformerMixin): def __init__(self, use=True): self.use = use def transform(self, feature
s_raw, **transform_params): if self.use: features = features_raw.copy(deep=True) family = features_raw[['SibSp', 'Parch']]\ .apply(lambda x: x[0] + x[1], axis=1) features.drop('SibSp', axis=1, inplace=True) features.drop('Parch', axis=1, inplace=Tr...
cr0hn/OMSTD
examples/develop/lp/002/lp-002-s1.py
Python
bsd-2-clause
2,001
0.002999
# -*- coding: utf-8 -*- """ Project name: Open Methodology for Security Tool Developers Project URL: https://github.com/cr0hn/OMSTD Copyright (c) 2014, cr0hn<-AT->cr0hn.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ...
NG, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVI...
hn.com (@ggdaniel)' from multiprocessing.pool import Pool # ---------------------------------------------------------------------- def hello(i): print(i) # ---------------------------------------------------------------------- def main(): p = Pool(10) p.map(hello, range(50)) if __name__ == '__main__...
Micronaet/micronaet-xmlrpc
xmlrpc_operation_product/__openerp__.py
Python
agpl-3.0
1,769
0.004522
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # 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 ...
tion) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received ...
#################################################################### { 'name': 'XMLRPC Operation Product', 'version': '0.1', 'category': 'ETL', 'description': ''' XMLRPC Import product ''', 'author': 'Micronaet S.r.l. - Nicola Riolini', 'website': 'http://www.micronaet.i...
agry/NGECore2
scripts/mobiles/tatooine/variegated_womprat.py
Python
lgpl-3.0
1,684
0.026128
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
eType("Leathery Hide") mobi
leTemplate.setBoneAmount(3) mobileTemplate.setBoneType("Animal Bone") mobileTemplate.setHideAmount(2) mobileTemplate.setSocialGroup("variegated womprat") mobileTemplate.setAssistRange(6) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE) templates = Vect...
davish/Twitter-World-Mood
twython/twython.py
Python
mit
22,902
0.00262
#!/usr/bin/env python """ Twython is a library for Python that wraps the Twitter API. It aims to abstract away all the API endpoints, so that additions to the library and/or the Twitter API won't cause any overall problems. Questions, comments? ryan@venodesigns.net """ __author__ = "Ryan McGrath <rya...
'api_error': None, 'cookies': response.cookies, 'error': response.error, 'headers': response.headers, 'status_code': response.status_code, 'url': response.url, 'content': content, } try: content = simplejson.loads(cont...
rror message, use a default. error_msg = content.get( 'error', 'An error occurred processing your request.') self._last_call['api_error'] = error_msg if response.status_code == 420: exceptionType = TwythonRateLimitError else: ...
nhynes/neon
tests/test_optimizer.py
Python
apache-2.0
6,823
0.001319
# ---------------------------------------------------------------------------- # Copyright 2015 Nervana 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.o...
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. # ---------------------------------------------------------------------------- ''' Test of the optimizers '...
rt copy from neon import NervanaObject from neon.backends import gen_backend from neon.optimizers import GradientDescentMomentum, RMSProp, Adadelta, Adam, Adagrad from neon.optimizers import MultiOptimizer from neon.layers import Conv, Affine, LSTM, GRU from neon.initializers import Gaussian, Constant from neon.transf...
bloyl/mne-python
mne/tests/test_transforms.py
Python
bsd-3-clause
21,423
0
import os import os.path as op import pytest import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_allclose, assert_array_less, assert_almost_equal) import itertools import mne from mne.datasets import testing from mne.fixes import _get_img_fdata from mne im...
(base_dir, 'test_ctf_raw.fif') hp_fif_fname = op.join(base_dir, 'test_chpi_raw_sss.fif') def test_tps(): """Test TPS warping.""" az = np.linspace(0., 2 * np.pi, 20, endpoint=False) pol = np.linspace(0, np.pi, 12)[1:-1] sph = np.array(np.meshgrid(1, az, pol, indexing='ij')) sph.shape = (3, -1) ...
art(sph.T) destination = source.copy() destination *= 2 destination[:, 0] += 1 # fit with 100 points warp = SphericalSurfaceWarp() assert 'no ' in repr(warp) warp.fit(source[::3], destination[::2]) assert 'oct5' in repr(warp) destination_est = warp.transform(source) assert_allclo...
BD2KGenomics/brca-website
django/users/migrations/0005_myuser_email_me.py
Python
apache-2.0
450
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 o
n 2016-04-08 11:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0004_myuser_is_approved'), ] operations = [ migrations.AddField( model_name='myuser',
name='email_me', field=models.BooleanField(default=True), ), ]
mcdaniel67/sympy
sympy/solvers/tests/test_inequalities.py
Python
bsd-3-clause
13,455
0.001189
"""Tests for tools for solving inequalities and systems of inequalities. """ from sympy import (And, Eq, FiniteSet, Ge, Gt, Interval, Le, Lt, Ne, oo, Or, S, sin, sqrt, Symbol, Union, Integral, Sum, Function, Poly, PurePoly, pi, root) from sympy.solvers.inequalities import (reduce_...
0), Ge(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False)) assert reduce_rational_inequalities( [[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=
False ) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True)) assert reduce_rational_inequalities( ...
ajitabhpandey/learn-programming
python/characterPictureGrid.py
Python
gpl-2.0
597
0.0067
#!/usr/bin/python def characterPictureGrid(grid): for dim1 in range(0, len(grid)): for dim2 in range(0, len(grid[dim1])): print grid[dim1][dim2], print "\n" grid =
[['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O',
'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] characterPictureGrid(grid)
whitepages/nova
nova/tests/functional/api_sample_tests/test_quota_sets.py
Python
apache-2.0
4,046
0.001236
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
aults. response = self._do_get
('os-quota-sets/fake_tenant/defaults') self._verify_response('quotas-show-defaults-get-resp', {}, response, 200) def test_update_quotas(self): # Get api sample to update quotas. response = self._do_put('os-quota-sets/fake_tenant', ...
bear/parsedatetime
tests/TestStartTimeFromSourceTime.py
Python
apache-2.0
2,109
0
# -*- coding: utf-8 -*- """ Test parsing of strings that are phrases with the ptc.StartTimeFromSourceTime flag set to True """ import sys import time import datetime import unittest import parsedatetime as pdt from parsedatetime.context import pdtContext from . import utils class test(unittest.TestCase): @utils....
atetime.datetime(yr, mth, 1, 13, 14, 15) t = datetime.datetime(yr, 12, 31, 13, 14, 15) start =
s.timetuple() target = t.timetuple() self.assertExpectedResult( self.cal.parse('eoy', start), (target, pdtContext(pdtContext.ACU_MONTH))) self.assertExpectedResult( self.cal.parse('meeting eoy', start), (target, pdtContext(pdtContext.ACU_MONTH)))...
outlierbio/ob-pipelines
ob_pipelines/apps/fastqc/fastqc.py
Python
apache-2.0
1,841
0.002173
import os.path as op import logging import shutil from subprocess import check_out
put from tempfile import mkdtemp import click from ob_pipelines.s3 import ( s3, download_file_or_folder, remove_file_or_folder, SCRATCH_DIR, path_to_bucket_and_key ) logger = logging.getLogger('ob-pipelines') @click.command() @click.argument('fq1') @click.argument('fq2') @click.argument('out_dir') @click.argum...
f out_dir.endswith('/') else out_dir + '/' temp_dir = mkdtemp(dir=SCRATCH_DIR) fq1_local = op.join(temp_dir, name + '_1.fastq.gz') fq2_local = op.join(temp_dir, name + '_2.fastq.gz') if fq1.startswith('s3://'): # Assume that if fq1 is in S3, so is fq2 download_file_or_folder(fq1, fq1_l...
Valeureux/wezer-exchange
__TODO__/project_crowdfunding/project_crowdfunding.py
Python
agpl-3.0
1,117
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Buron and Valeureux # Copyright 2013 Yannick Buron and Valeureux # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General ...
########
####################################### from openerp.osv import orm class ProjectProject(orm.Model): _name = 'project.project' _inherit = ['project.project', 'crowdfunding.campaign']
LPgenerator/django-db-mailer
dbmail/providers/google/android.py
Python
gpl-2.0
1,265
0
# -*- encoding: utf-8 -*- try: from httplib import HTTPSConnection from urlparse import urlparse except ImportError: from http.client import HTTPSConnection from urllib.parse import urlparse from json import dumps, loads from django.conf import settings class GCMError(Exception): pass def send...
) } hook_url = 'https://android.googleapis.com/gcm/send' data = { "registration_ids": [user], "data": { "title": kwargs.pop("event"), 'message': message, } } data['data'].update(
kwargs) up = urlparse(hook_url) http = HTTPSConnection(up.netloc) http.request( "POST", up.path, headers=headers, body=dumps(data)) response = http.getresponse() if response.status != 200: raise GCMError(response.reason) body = response.read() if loads(body...
openstack/bifrost
bifrost/inventory.py
Python
apache-2.0
10,872
0
#!/usr/bin/env python3 # # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # 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 # # U...
st] variable to a list of desired groups. Moreover, users can override the default 'baremetal' group by assigning a list of default groups to the test_vm_default_group variable. Presently, the base mode of operation reads a JSON/YAML file in the format originally utilized by bifrost and returns structured JSON that is...
erpreted by Ansible. Conceivably, this inventory module can be extended to allow for direct processing of inventory data from other data sources such as a configuration management database or other inventory data source to provide a consistent user experience. How to use? ----------- export BIFROST_INVENTORY_SOU...
mivade/cfbrank
dataparse.py
Python
gpl-3.0
3,352
0.004177
""" cfbrank -- A college football ranking algorithm dataparse.py: A module for parsing datafiles containing the
relevant statistics for the cfbrank algorithm. See the readme for full details on the data formats and sources supported. Written by Michael V.
DePalatis <depalatis@gmail.com> cfbrank is distributed under the terms of the GNU GPL. """ import csv from team import Team from conference import Conference ncaa_names = [x.strip() for x in open('data/NCAANames2012.txt', 'r').readlines()] sun_names = [x.strip() for x in open('data/SunNames2013.txt', 'r').readlines(...
cloudControl/django-celery-migration-app
minestrone/urls.py
Python
mit
781
0.010243
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() import minestrone.soup.vie
ws urlpatterns = patterns('', # Examples: # url(r'^$', 'minestrone.views.home', name='home'), # url(r'^minestrone/', include('minestrone.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contr
ib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$', minestrone.soup.views.JobsView.as_view()), url(r'^jobs/$', minestrone.soup.views.JobsView.as_view()), url(r'^editor/$', minestrone.soup.views.EditorView.as_view()), )
StackStorm/st2
st2common/st2common/content/loader.py
Python
apache-2.0
14,094
0.001064
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme 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 ...
adata files. """ def load(self, file_path, expected_type=None): """ Loads content from file_path if file_path's extension is one of allowed ones (See ALLOWED_EXTS). Throws UnsupportedMetaException on disallowed filetypes. Throws ValueError on malformed meta. :p...
or the loaded and parsed content (optional). :type expected_type: ``object`` :rtype: ``dict`` """ file_name, file_ext = os.path.splitext(file_path) if file_ext not in ALLOWED_EXTS: raise Exception( "Un
nathanshammah/pim
setup.py
Python
mit
3,679
0.015222
#!
/usr/bin/env python """PIQS: Permutational Invariant Quantum Solver PIQS is an open-source Python solver to study the exact Lindbladian dynamics of open quantum systems consisting of identical qubits. """ DOCLINES = __doc__.split('\n') CLASSIFIERS = """\ Development Status :: 3
- Alpha Intended Audience :: Science/Research License :: OSI Approved :: BSD License Programming Language :: Python Programming Language :: Python :: 3 Topic :: Scientific/Engineering Operating System :: MacOS Operating System :: POSIX Operating System :: Unix Operating System :: Microsoft :: Windows """ import os impo...
nitrotc/tc-bout-board
app/tc_bout_board.py
Python
gpl-3.0
27,003
0.003444
#!/usr/bin/env python # # "TC BOUT BOARD" a wrestling Match Bout Board application for youth matches or tournaments # Copyright (C) 2016 Anthony Cetera # # 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 # t...
.add_cascade(label="Get Started", menu=self.init_menu) # Quit Menu self.quit_menu = Menu(self.menubar, tearoff=0) self.quit_menu.add_command(label="Close Board", command=self.stop_board) self.quit_menu.add_command(label="Quit!", command=self.adminframe.quit) self.menubar.add_casc...
nd(label="About", command=help_about) self.menubar.add_cascade(label="Help", menu=self.help_menu) # Populate the menu bar with options above self.master.config(menu=self.menubar) # Build grid of up to 6 potential mats for i in range(self.maxmats): matnum = i + 1 ...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_07_01/operations/_network_watchers_operations.py
Python
mit
105,992
0.00551
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ing import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azu
re.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dic...
fllamber/show_do_milhao
Show_do_milhao/Teste.perguntas.py
Python
unlicense
5,657
0.004908
# -*- coding: utf-8 -*- import anydbm import random arquivo = anydbm.open('dados' , 'c') arquivo['P1N1'] = 'Longbottom era o sobrenome de quem, nas séries de livros de Harry Potter?' arquivo['P1C1'] = 'Neville' arquivo['P1R2'] = 'Hermione' arquivo['P1R3'] = 'Snape' arquivo['P1R4'] = 'Dumbledore' arquivo['P2N1'] = 'Qu...
Barata' arquivo['P14C3'] = 'Jacaré' arquivo['P14R4'] = 'Minhoca' arquivo['P15N4'] = 'linha 11 do metro de Moscovo também é referida como:' arquivo['P15R1'] = 'Трусость и образования' arquivo['P15R2'] = 'Не инвестировать в возобновляемые' arquivo['P15R3'] = 'В один прекрасный день мы будем вторглись китайские' arqui
vo['P15C4'] = 'Linha Kakhovskaia' arquivo['P16N4'] = 'O Qutb Minar é o minarete de tijolo mais alto do mundo, exemplo de arquitetura:' arquivo['P16C1'] = 'Indo-islâmica' arquivo['P16R2'] = 'De alguém que gostava de empilhar tijolos' arquivo['P16R3'] = 'Dos primos da áfrica' arquivo['P16R4'] = 'Cimento Mauá, Melhor não...
kwinczek/tvseries
tvs/cache.py
Python
gpl-2.0
5,742
0.003657
#!/usr/bin/env python #-*- coding: utf8 -*- # Copyright 2009-2012 Kamil Winczek <kwinczek@gmail.com> # # This file is part of series.py. # # series.py 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 ve...
showid = self.__get_id_from_tvrage() if
showid: self.__save_id_to_cache(showid) return showid return None def __get_show(self): """Returns show instance with data from tvrage.""" if self.showid == None: # Previously not found show id return None if self.options.cache and not ...
ChinaMassClouds/copenstack-server
openstack/src/ceilometer-2014.2.2/ceilometer/hardware/pollsters/cpu.py
Python
gpl-2.0
1,650
0
# # Copyright 2013 ZHAW SoE # Copyright 2014 Intel Corp. # # Authors: Lucas Graf <gr
aflu0@students.zhaw.ch> # Toni Zehnder <zehndton@students.zhaw.ch> # Lianhao Lu <lianhao.lu@intel.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 # # http://www.ap...
rg/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...
crhaithcock/RushHour
Analytics/shared_code/RHconstants.py
Python
cc0-1.0
1,791
0.007259
''' Created on Jun 8, 2015 @author: cliff ''' CAR_SYMBOLS = ['Q', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L'] TRUCK_SYMBOLS = ['T', 'R', 'W', 'Z'] CAR_COLORS_NO_HASH = ['7FFF00', '7FFFD4', 'D2691E', '8B008B', 'BDB76B',\ '8B0000', 'FF1493', '1E90FF', 'FFD700', 'ADFF2F', \ ...
implementation, want to use matrix math. Need to contrive values such that # for z in values, x + y = z if an only if x or y = 0. BLANK_SPACE = '000' HORIZONTAL_CAR = '010' HORIZONTAL_TRUCK = '100' VERTICAL_CAR = '011' VERTICAL_TRUCK = '101' blank = 0 vcar = 4 vtruck = 5 hcar = 6 htruck = 7 # Relabel
ing These 2017-08-28 # Coding Scheme: # 3-bits: x y z # x - orientation (0 = horizontal, 1 = vertical) # y - Truck Bit (0 = Not Truck, 1 = Truck ) # z - Car Bit (0 = Not Car, 1 = car) # 000 - Horizontal, Not Car, Not Truck (i.e. Empty Space) # BLANK_SPACE = '000' # HORIZONTAL_CAR = '001' # HORIZONTAL_TRUCK = '010' ...
naturali/tensorflow
tensorflow/contrib/framework/python/framework/tensor_util.py
Python
apache-2.0
11,844
0.006079
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
st of integers defining the expected shape, or tensor of same. actual_tensor: Tensor to test. Returns: New assert tensor. """ with ops.name_scope('assert_shape', values=[actual_tensor]) as scope: actual_shape = array_ops.shape(actual_tensor, name='actual') is_shape = _is_shape(expected_sha...
l].' % actual_tensor.name, expected_shape, actual_shape ], name=scope) def with_same_shape(expected_tensor, tensor): """Assert tensors are the same shape, from the same graph. Args: expected_tensor: Tensor with expected shape. tensor: Tensor of actual values. Returns: ...
cristina0botez/m3u8
m3u8/__init__.py
Python
mit
2,171
0.006909
# coding: utf-8 # Copyright 2014 Globo.com Player authors. All rights reserved. # Use of this source code is governed by a MIT License # license that can be found in the LICENSE file. import sys PYTHON_MAJOR_VERSION = sys.version_info import os import posixpath try: import urlparse as url_parser import urlli...
rom m3u8.model import M3U8, Playlist, IFramePlaylist, Media, Segment from m3u8.parser import parse, is_url, ParseError __all__ = ('M3U8', 'Playlist', 'IFramePlaylist', 'Media', 'Segment', 'loads', 'load', 'parse', 'ParseError') def loads(content): ''' Given a string with a m3u8
content, returns a M3U8 object. Raises ValueError if invalid content ''' return M3U8(content) def load(uri): ''' Retrieves the content from a given URI and returns a M3U8 object. Raises ValueError if invalid content or IOError if request fails. ''' if is_url(uri): return _load_f...
tofu-rocketry/apel
test/test_record.py
Python
apache-2.0
1,067
0.004686
import unittest from apel.db.records import Record, InvalidRecordException class RecordTest(unittest.TestCase): ''' Test case for Record ''' # test for public interface def test_set_field(self): record = Record() self.assertRaises(InvalidRecordException, ...
'value') record._db_fields = ['Test'] record.set_field('Test', 'value') self.assertEqual(record._record_content['Test'], 'value') def test_set_all(self): record = Record() self.assertRaises(InvalidRecordException, record.set_all, {'Test':'value...
ntent['Test'], 'value') def test_get_field(self): record = Record() record._db_fields = ['Test'] record._record_content['Test'] = 'value' self.assertEqual(record.get_field('Test'), 'value') if __name__ == '__main__': unittest.main()
tshrinivasan/open-tamil
examples/solpattiyal.py
Python
mit
3,639
0.016213
# -*- coding: utf-8 -*- # # This file is distributed under MIT License or default open-tamil license. # (C) 2013-2015 Muthiah Annamalai # # This file is part of 'open-tamil' examples # It can be used to identify patterns in a Tamil text files; # e.g. it has been used to identify patterns in Tamil Wikipedia # article...
if len(buf) > 0: yield u"".join( buf ) buf = [] if len(buf) > 0: yield u"".join(buf) # sentinel def __init__(self,tatext=u''): object.__init__(self) self.frequency = {} # process data ...
text): for taline in new_text.split(u"\n"): self.tamil_words_process( taline ) return # finalize def display(self): self.print_tamil_words( ) return # processor / core def tamil_words_process( self, taline ): taletters = tamil.utf8.get_letters_i...
ceos-seo/data_cube_utilities
dea_tools/dea_tools/spatial.py
Python
apache-2.0
34,337
0.009145
## dea_spatialtools.py ''' Description: This file contains a set of python functions for conducting spatial analyses on Digital Earth Australia data. License: The code in this notebook is licensed under the Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Australia data is li...
20 ''' # Import required packages import collections import numpy as np import xarray as xr import geopandas as gpd import rasterio.features import scipy.interpolate from scipy import ndimage as nd from skimage.measure import label from rasterstats import zonal_stats from skimage.measure import
find_contours from datacube.utils.cog import write_cog from datacube.helpers import write_geotiff from datacube.utils.geometry import assign_crs from datacube.utils.geometry import CRS, Geometry from shapely.geometry import LineString, MultiLineString, shape def xr_vectorize(da, attribute_col='attrib...
nijel/weblate
weblate/vcs/tests/test_gpg.py
Python
gpl-3.0
3,459
0.000869
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Lice
nse as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See t...
Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # import subprocess from distutils.version import LooseVersion from unittest import SkipTest from django.core.cache import cache from django.test import TestCase from django.test.utils import override_settings import weblate.vcs...
pbfy0/visvis
examples/surfaceFromRandomPoints.py
Python
bsd-3-clause
6,186
0.023278
#!/usr/bin/env python """ Examples of using qhull via scipy to generate 3D plots in visvis. Requires numpy ver 1.5, scipy ver 0.9 and qhull from http://www.qhull.org/ (on Windows this comes with Scipy). plot3D meshes and plots random convex transformable data in both cartesian and spherical coordinates Play around wi...
ange=[-1,0], raised=False) # Sperical plot numOfPts = 1000 # Create random points ThetaPhiR = np.zeros((numOfPts,3)) ThetaPhiR[:,0] = np.pi * np.random.rand(numOfPts) # theta is 0 to 180 deg ThetaPhiR[:,1] = 2 * np.pi * np.random.rand(numOfPts) # phi is 0 to 360 deg ThetaP...
2] = 10 * np.log10((np.sin(ThetaPhiR[:,0])**4) * (np.cos(ThetaPhiR[:,1])**2)) # Plot vv.subplot(122) vv.title('Sperical coordinates') plot3D(ThetaPhiR, coordSys='Spherical') #plot3D(ThetaPhiR, coordSys='Spherical', raised=False) # Run main loop app = vv.use() app.Run()
Petraea/jsonbot
jsb/plugs/socket/dns.py
Python
mit
1,189
0.015139
# jsb/plugs/socket/dns.py # # """ do a fqdn loopup. """ ## jsb imports from jsb.lib.commands import cmnds from jsb.lib.examples import examples ## basic imports from socket import gethostbyname from socket import getfqdn import re ## dns command def handle_dns(bot, event): """ arguments: <ip>|<hostname> - do...
event.rest: event.missing("<ip>|<hostname>") ; return query = event.rest.strip() ippattern = re.match(r"^([0-9]{1,3}\.){3}[0-9]{1,3}$", query) hostpattern = re.match(r"(\w+://)?(?P<hostname>\S+\.\w+)", query) if ippattern: try: answer = getfqdn(ippattern.group(0)) even...
Couldn't lookup ip") elif hostpattern: try: answer = gethostbyname(hostpattern.group('hostname')) event.reply("%(ip)s is %(answer)s" % {"ip": query, "answer": answer}) except: event.reply("Couldn't look up the hostname") else: return cmnds.add("dns", handle_dns, ["OPER"...
TwolDE2/enigma2
lib/python/Components/Renderer/CiModuleControl.py
Python
gpl-2.0
2,404
0.027454
from Components.Renderer.Renderer import Renderer from enigma import eDVBCI_UI, eLabel, iPlayableService from skin import parameters from Components.SystemInfo import SystemInfo from Components.VariableText import VariableText from Tools.Hex2strColor import Hex2strColor from os import popen class CiModuleControl(Rende...
lse self.no_visible_state1 = "ciplushelper" in popen("top -n 1").read() self.colors = parameters.get("CiModuleControlColors", (0x007F7F7F, 0x00FFFF00, 0x00FFFF00, 0x00FF2525)) # "state 0 (no module) gray", "state 1 (init module) yellow", "state 2 (module ready) g
reen", "state -1 (error) red" GUI_WIDGET = eLabel def applySkin(self, desktop, parent): attribs = self.skinAttributes[:] for (attrib, value) in self.skinAttributes: if attrib == "allVisible": self.allVisible = value == "1" attribs.remove((attrib, value)) break self.skinAttributes = attribs re...
Rouslan/NTracer
lib/ntracer/tests/test.py
Python
mit
16,831
0.03149
import unittest import random import pickle from ..wrapper import NTracer,CUBE,SPHERE from ..render import Material,Color def pydot(a,b): return sum(ia*ib for ia,ib in zip(a,b)) def and_generic(f): def inner(self): with self.subTest(generic=False): f(self,False) with self.subTest...
b = nt.Vector(x+12 for x in range(d-1,-1,-1)) self.assertAlmostEqual(nt.dot(a,b),pydot(a,b),4) d = d >> 1 @and_generic def test_math(self,generic): nt = self.get_ntracer(4,generic) ma = nt.Matrix([[10,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,
16]]) mb = nt.Matrix([13,6,9,6,7,3,3,13,1,11,12,7,12,15,17,15]) mx = ma * mb my = nt.Matrix([195,159,200,167,210,245,283,277,342,385,447,441,474,525,611,605]) self.listlike_equal(mx.values,my.values) self.vector_almost_equal((mb * mb.inverse()).values,[1,0,0,0,0,1,0,0,0,0,1,0,0,...
phretor/django-academic
academic/apps/people/context_processors.py
Python
bsd-3-clause
168
0.005952
from academic import settings def default_picture_url(context): return {
'ACADEMIC_PEOPLE_DEFAULT_PICTURE': settings.PEOPLE_DEF
AULT_PICTURE, }
pirata-cat/agora-ciudadana
userena/models.py
Python
agpl-3.0
15,318
0.002742
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.contrib.auth.models import User from django.template.loader import render_to_string from django.conf import settings from django.contrib.sites.models import Site from django.core.urlresolve...
'extension': extension} class UserenaSignup(models.Model): """ Userena model which stores all the necessary information to have a full functional user implementation on your Djan
go website. """ user = models.OneToOneField(User, verbose_name=_('user'), related_name='userena_signup') last_active = models.DateTimeField(_('last active'), blank=True, ...
atrick/swift
utils/gyb_syntax_support/NodeSerializationCodes.py
Python
apache-2.0
7,910
0
from .Node import error SYNTAX_NODE_SERIALIZATION_CODES = { # 0 is 'Token'. Needs to be defined manually # 1 is 'Unknown'. Needs to be defined manually 'UnknownDecl': 2, 'TypealiasDecl': 3, 'AssociatedtypeDecl': 4, 'IfConfigDecl': 5, 'PoundErrorDecl': 6, 'PoundWarningDecl': 7, 'Pou...
'PrefixOperatorExpr': 39, 'BinaryOperatorExpr': 40, 'ArrowExpr': 41, 'FloatLiteralExpr': 42, 'TupleExpr': 43, 'ArrayExpr': 44, 'DictionaryExpr': 45, 'ImplicitMemberExpr': 46, 'IntegerLiteralExpr': 47, 'StringLiteralExpr': 48, 'BooleanLiteralExpr': 49, 'TernaryExpr': 50, ...
ClosureExpr': 56, 'UnresolvedPatternExpr': 57, 'FunctionCallExpr': 58, 'SubscriptExpr': 59, 'OptionalChainingExpr': 60, 'ForcedValueExpr': 61, 'PostfixUnaryExpr': 62, 'SpecializeExpr': 63, 'KeyPathExpr': 65, 'KeyPathBaseExpr': 66, 'ObjcKeyPathExpr': 67, 'ObjcSelectorExpr': 68...
OCA/margin-analysis
account_invoice_margin_sale_delivered_sync/__manifest__.py
Python
agpl-3.0
676
0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name
": "Account Invoice Margin Sale Delivered Sync", "summary": "Sync invoice margin between invoices and sale orders", "version": "12.0.1.0.1", "development_status": "Beta", "maintainers": ["sergio-teruel"], "category": "Account", "website": "https://github.com/OCA/margin-analysis", "author": "...
d", "account_invoice_margin_sale", ], }
eccles/lnxproc
lnxproc/vmstat.py
Python
mit
3,041
0
''' Contains Vmstat() class Typical contents of vmstat file:: nr_free_pages 1757414 nr_inactive_anon 2604 nr_active_anon 528697 nr_inactive_file 841209 nr_active_file 382447 nr_unevictable 7836 nr_mlock 7837 nr_anon_pages 534070 nr_mapped 76013 nr_file_pages 1228693 nr_dirty 21 nr_...
eal_kswapd_dma 0 pgsteal_kswapd_dma32 0 pgsteal_kswapd_normal 0 pgsteal_kswapd_movable 0 pgsteal_direct_dma 0 pgsteal_direct_dma32 0 pgsteal_direct_normal 0 pgsteal_direct_movable 0 pgscan_kswapd_dma 0 pgscan_kswapd_dma32 0 pgscan_kswapd_normal 0 pgscan_kswapd_movable 0 pgscan_direct...
zone_reclaim_failed 0 pginodesteal 0 slabs_scanned 0 kswapd_inodesteal 0 kswapd_low_wmark_hit_quickly 0 kswapd_high_wmark_hit_quickly 0 kswapd_skip_congestion_wait 0 pageoutrun 1 allocstall 0 pgrotated 23 compact_blocks_moved 0 compact_pages_moved 0 compact_pagemigrate_failed 0 co...
valmynd/MediaFetcher
src/plugins/youtube_dl/youtube_dl/extractor/meta.py
Python
gpl-3.0
2,155
0.027855
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from .pladform import PladformIE from ..utils import ( unescapeHTML, int_or_none, ExtractorError, ) class METAIE(InfoExtractor): _VALID_URL = r'https?://video\.meta\.ua/(?:iframe/)?(?P<id>[0-9]+)' _TESTS = [{ 'url': 'htt...
'' for i in range(0, len(st_html5), 3): json_str += '&#x0%s;' % st_html5[i:i + 3] uppod_data = self._parse_json(unescapeHTML(json_str), video_id) error = uppod_data.get('customnotfound') if error: raise ExtractorError('%s said: %s' % (self.IE_NAME, error), expected=Tru
e) video_url = uppod_data['file'] info = { 'id': video_id, 'url': video_url, 'title': uppod_data.get('comment') or self._og_search_title(webpage), 'description': self._og_search_description(webpage, default=None), 'thumbnail': uppod_data.get('poster') or self._og_search_thumbnail(webpage), ...
fabioz/mu-repo
mu_repo/umsgpack_s_conn.py
Python
gpl-3.0
15,598
0.003526
# Fork: https://github.com/fabioz/u-msgpack-python # ''' This module provides a way to do full-duplex communication over a socket with umsgpack_s. Basic usage is: # Create our server handler (must handle decoded messages) class ServerHandler(ConnectionHandler, UMsgPacker): def _handle_d...
thread_class = threading.Thread self._thread_class = thread_class if connection_handler_class is None: connection_handler_class = EchoHandler self.connection_handler_class = connection_handler_class self._params = params self._block = None self._sh...
ing.Event() self._thread_name = thread_name def serve_forever(self, host, port, block=False): if self._block is not None: raise AssertionError( 'Server already started. Please create new one instead of trying to reuse.') if not block: self.thr...
repotvsupertuga/repo
plugin.video.pancas/resources/lib/libraries/control.py
Python
gpl-2.0
9,795
0.00827
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any l...
.LOGNOTICE): #return level = xbmc.LOGNOTICE print('[SPECTO]: %s' % (msg)) try: if isinstance(msg, unicode): msg = msg.encode('utf-8') xbmc.log('[SPECTO]: %s' % (msg), level) except Exception as e: try: #xbmc.log('Logging Failure: %s' % (e), l
evel) a=1 except: pass # just give up def randomagent(): BR_VERS = [ ['%s.0' % i for i in xrange(18, 43)], ['37.0.2062.103', '37.0.2062.120', '37.0.2062.124', '38.0.2125.101', '38.0.2125.104', '38.0.2125.111', '39.0.2171.71', '39.0.2171.95', '39.0.2171.99', '40.0.2214.93', '4...
mhabrnal/abrt
src/python-problem/doc/conf.py
Python
gpl-2.0
8,344
0.00755
# -*- coding: utf-8 -*- # # python-problem documentation build configuration file, created by # sphinx-quickstart on Tue Dec 4 12:03:58 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. ...
th.abspath('../problem/.libs')) # _pyabrt # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extens
ion module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The su...
bearstech/modoboa-admin
modoboa_admin/views/alias.py
Python
mit
4,252
0.000235
from django.contrib.auth.decorators import ( login_required, permission_required ) from django.core.urlresolvers import reverse from django.db import IntegrityError from django.shortcuts import render from django.utils.translation import ugettext as _, ungettext import reversion from modoboa.lib import events fr...
list created") ) @login_required @permission_required("modoboa_admin.add_alias") @reversion.create_revision() def newalias(request): return _new_alias( request, _("New alias"), reverse("modoboa_admin:alias_add"), _("Alias created") ) @login_required @permission_required("modoboa_admin.ad...
n _new_alias( request, _("New forward"), reverse("modoboa_admin:forward_add"), _("Forward created") ) @login_required @permission_required("modoboa_admin.change_alias") @reversion.create_revision() def editalias(request, alid, tplname="modoboa_admin/aliasform.html"): alias = Alias.objects.get(...
canhhs91/greenpointtrees
src/paypal/pro/south_migrations/0001_initial.py
Python
mit
7,020
0.008832
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User else: User = get_user_mode...
() # With the default User model these will be 'auth.User' and 'auth.user' # so instead of using orm['auth.User'] we can use orm[user_orm_label] user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._met
a.module_name) class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'PayPalNVP' db.create_table('paypal_nvp', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('method', self.gf('django.db.models.fields.CharField')(max_length=6...
blha303/ytbot
plugins/core_misc.py
Python
gpl-3.0
2,257
0.000886
import socket import time import re from util import hook socket.setdefaulttimeout(10) nick_re = re.compile(":(.+?)!") # Auto-join on Invite (Configurable, defaults to True) @hook.event('INVITE') def invite(paraml, conn=None): invite_join = conn.conf.get('invite_join', True) if invite_join: conn.jo...
conn=None, chan=None): # if the bot has been kicked, remove from the channel list if paraml[1] == conn.nick: conn.channels.remove(chan) auto_rejoin = conn.conf.get('auto_rejoin', False) if auto_rejoin: co
nn.join(paraml[0]) @hook.event("NICK") def onnick(paraml, conn=None, raw=None): old_nick = nick_re.search(raw).group(1) new_nick = str(paraml[0]) if old_nick == conn.nick: conn.nick = new_nick print "Bot nick changed from '{}' to '{}'.".format(old_nick, new_nick) @hook.singlethread @hook...
geberl/droppy-workspace
Tasks/DropPy.Common/file_tools.py
Python
mit
1,999
0.0005
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import distutils.dir_util import os import shutil import sys def touch_file(file_path): """ Create a new empty file at file_path. """ parent_dir = os.path.abspath(os.path.join(file_path, os.pardir)) if...
else: sys.exit('File exists, unable to continue: %s' % output_file) else: shutil.copyfile(input_file, output_file) def copy_tree(input_dir, output_dir, overwrite=False): """ Helper function to copy
a directory tree that adds an overwrite parameter. """ if os.path.isdir(output_dir): if overwrite: print('Directory exists, overwriting') distutils.dir_util.copy_tree(input_dir, output_dir) else: sys.exit('Directory exists, unable to continue: %s' % output_di...
activityhistory/selfspy
selfspy/helpers.py
Python
gpl-3.0
3,410
0.006452
import calendar from dateutil.parser import parse import os from os import listdir from os.path import isfile, join from selfspy import config as cfg from objc import YES, NO from AppKit import * from CBGraphView import CBGraphView TIMELINE_WIDTH = 960 TIMELINE_HEIGHT = 20 WINDOW_PADDING = 18 def unixTimeFromStr...
(self.processNameResponse[0])) self.processNameResponse = [] reviewer.nested_timeline_views.append(this_view) ## TIMELINE HEL
PERS # def addProcessNameTextLabelToTimeline(self, process_id, reviewer): # self.processNameQuery = process_id # NSNotificationCenter.defaultCenter().postNotificationName_object_('getProcessNameFromID', self) # # textField_frame = NSRect(NSPoint(0, TIMELINE_HEIGHT / TIMELINE_MAX_ROWS * process_id), # ...
eric-stanley/robotframework
src/robot/model/stats.py
Python
apache-2.0
6,017
0.000166
# Copyright 2008-2014 Nokia Solutions and Networks # # 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...
`tag`. type = 'tag' d
ef __init__(self, name, doc='', links=None, critical=False, non_critical=False, combined=''): Stat.__init__(self, name) #: Documentation of tag as a string. self.doc = doc #: List of tuples in which the first value is the link URL and #: the second is the link ti...
dnanexus/rseqc
rseqc/lib/bx/intervals/__init__.py
Python
gpl-3.0
204
0.009804
""" Tools and data structures
for working with genomic intervals (or sets of regions on a line in general) efficiently. """ # For compatiblity with existing stuff from bx.intervals.intersecti
on import *
sechacking/MITMf
core/banners.py
Python
gpl-3.0
4,693
0.012703
# -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Marcello Salvati # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # ...
@@@@@@@@@@@ @@@ @@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@! @@! @@! @@! @@! @@! @@! @@! @@! !@! !@! !@! !@! !@! !@! !@! !@! !@! @!! !!@ @!@
!!@ @!! @!! !!@ @!@ @!!!:! !@! ! !@! !!! !!! !@! ! !@! !!!!!: !!: !!: !!: !!: !!: !!: !!: :!: :!: :!: :!: :!: :!: :!: ::: :: :: :: ::: :: :: : : : : : : : """ def get_banner(): ...
emanuele/jstsp2015
classif_and_ktst.py
Python
mit
9,044
0.000442
"""Classification-based test and kernel two-sample test. Author: Sandro Vega-Pons, Emanuele Olivetti. """ import os import numpy as np from sklearn.metrics import pairwise_distances, confusion_matrix from sklearn.metrics import pairwise_kernels from sklearn.svm import SVC from sklearn.cross_validation import Stratifi...
random_state=None, param_grid=[{'C': np.logspace(-5, 5, 25)}]): """Compute cross-validated score of SVM using precomputed kernel. """ cv = Stratifi
edKFold(y, n_folds=n_folds, shuffle=True, random_state=random_state) scores = np.zeros(n_folds) for i, (train, test) in enumerate(cv): cvclf = SVC(kernel='precomputed') y_train = y[train] cvcv = StratifiedKFold(y_train, n_folds=n_folds, ...
gdietz/OpenMEE
common_wizard_pages/ui_effect_size_locations_page.py
Python
gpl-3.0
5,558
0.001799
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'effect_size_locations_page.ui' # # Created: Tue Aug 27 16:49:55 2013 # by: PyQt4 UI code generator 4.10.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fro...
ticalLayout_2.addItem(spacerItem1) self.horizontalLayout.addLayout(self.verticalLayout_2) self.verticalLayout_3.addLayout(self.horizontalLayout) self.retranslateUi(wizardPage) QtCore.QMetaObject
.connectSlotsByName(wizardPage) def retranslateUi(self, wizardPage): wizardPage.setWindowTitle(_translate("wizardPage", "WizardPage", None)) wizardPage.setTitle(_translate("wizardPage", "Effect Size Column Locations", None)) self.label_6.setText(_translate("wizardPage", "Where is your data ...
django-settings/django-settings
myproject/myproject/user_settings.py
Python
unlicense
2,239
0.003126
# Imports environment-specific settings. import os import sys try: from colorama import init as colorama_init except ImportError: def colorama_init(autoreset=False, convert=None, strip=None, wrap=True): """ Fallback function that initializes colorama. """ pass try: from t...
hon colors get confused. if not win32 or not 'shell' in sys.argv: colorama_init() current_settings = [] if production: current_settings.append(colored('Production', 'green', attrs=['bold'])) from production_settings import * if local: current_settings.append(
colored('Local', 'yellow', attrs=['bold'])) from local_settings import * if linux: current_settings.append(colored('Linux', 'blue', attrs=['bold'])) from linux_settings import * if os_x: current_settings.append(colored('OS X', 'blue', attrs=['bold'])) from os_x_settings import * if win32: curren...
cupy/cupy
examples/gemm/utils.py
Python
mit
551
0
import cupy as cp def read_code(code_filename, params): with open(code_filename, 'r') as f: c
ode = f.read() for k, v in params.items(): code = '#define ' + k + ' ' + str(v) + '\n' + code return code def benchmark(func, args, n_run): times = [] for _ in range(n_run): start = cp.cuda.Event() end = cp.cuda.Event() start.record() func(*args) end.rec...
return times
alxgu/ansible
test/units/modules/network/f5/test_bigip_device_facts.py
Python
gpl-3.0
4,137
0.001209
# -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, ...
(data) except Exception: pass fixture_data[path] = data return data class FakeVirtualAddress: def __init__(self, *args, **kwargs): attrs = kwargs.pop('params', {}) for key, valu
e in iteritems(attrs): setattr(self, key, value) class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( gather_subset=['virtual-servers'], ) p = Parameters(params=args) assert p.gather_subset == ['virtual-servers'] class Te...
rwl/PyCIM
CIM15/IEC61970/Informative/InfAssets/Medium.py
Python
mit
4,176
0.002155
# Copyright (C) 2010-2011 Richard Lincoln # # 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, merge, publish...
self._Specification._Mediums = filtered self._Specification = value if self._Specification is not None: if self not in self._Specification._Mediums: self._Specification._Mediums.append(self) Specification = property(getSpecification, setSpecification) def...
tAssets(self): return self._Assets def setAssets(self, value): for p in self._Assets: filtered = [q for q in p.Mediums if q != self] self._Assets._Mediums = filtered for r in value: if self not in r._Mediums: r._Mediums.append(sel...
samuelgarcia/python-neo
neo/test/iotest/test_pickleio.py
Python
bsd-3-clause
3,272
0.000306
""" Tests of the neo.io.pickleio.PickleIO class """ import os import unittest import numpy as np import quantities as pq from neo.core import Block, Segment, AnalogSignal, SpikeTrain, Epoch, Event, \ IrregularlySampledSignal, Group from neo.io import PickleIO from numpy.testing import assert_array_equal from ne...
kl") reader.write(blk) reader = PickleIO(filename="blk.pkl") r_blk = reader.read_block() r_seg = r_blk.segments[0] self.assertIsInstance(r_seg.irregularlysampledsignals[0]
.segment, Segment) os.remove('blk.pkl') if __name__ == '__main__': unittest.main()
kamyu104/LeetCode
Python/magic-squares-in-grid.py
Python
mit
1,889
0
# Time: O(m * n) # Space: O(1) # A 3 x 3 magic square is a 3 x 3 grid filled with # distinct numbers from 1 to 9 such that each row, column, # and both diagonals all have the same sum. # # Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? # (Each subgrid is contiguous). # # Example 1: # # I...
+j]) nums.add(grid[r+i][c+j]) sum_r += grid[r+i][c+j] sum_c += grid[r+j][c+i] if not (sum_r == sum_c == expect): return False return sum_diag == sum_anti == expect and \ len(nums) == k**2 and \ ...
min_num == 1 k = 3 result = 0 for r in xrange(len(grid)-k+1): for c in xrange(len(grid[r])-k+1): if magic(grid, r, c): result += 1 return result
JustinTulloss/harmonize.fm
libs.py/facebook/__init__.py
Python
mit
32,593
0.002976
#! /usr/bin/env python # # pyfacebook - Python bindings for the Facebook API # # Copyright (c) 2008, Samuel Cormier-Iijima # 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 o...
es = urllib2.urlopen(url, data=data) return res.read() __all__ = ['Facebook'] VERSION = '0.1' # REST URLs # Change these to /bestserver.php to use the bestserver. FACEBOOK_URL = 'http://api.facebook.com/restserver.php' FACEBOOK_SECURE_URL = 'https://api.facebook.com/restserver.php' class json(object): p...
), ('image_1', str, ['optional']), ('image_1_link', str, ['optional']), ('image_2', str, ['optional']), ('image_2_link', str, ['optional']), ('image_3', str, ['optional']), ('image_3_link', str, ['optional']), ('image_4', str, ['optiona...
stevenzhang18/Indeed-Flask
lib/pandas/msgpack/_unpacker.py
Python
apache-2.0
297
0.016835
def __bootstrap__():
global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__, '_unpacker.cp35-win32.pyd') __loader__ = None; del __bootstrap__, __loader__ imp.load_dynamic(__name__,__fil
e__) __bootstrap__()
Antiun/carrier-delivery
delivery_carrier_label_postlogistics/delivery.py
Python
agpl-3.0
10,691
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Vaucher # Copyright 2013 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 # pub...
ame = 'postlogistics.license' _description = 'PostLogistics Franking License' _order = 'sequence' name = fields.Char(string='Description', translate=True, required=True) number = fields.Char(string='Number', required=True) comp...
red=True) sequence = fields.Integer( string='Sequence', help="Gives the sequence on company to define priority on license " "when multiple licenses are available for the same group of " "service." ) class PostlogisticsServiceGroup(models.Model): _name = 'postlogis...
google-research/google-research
axial/config_imagenet32.py
Python
apache-2.0
1,760
0.000568
# coding=u
tf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf def get_config(): return tf.contrib.training.HParams(**{...
OpenDaisy/daisy-api
daisy/cmd/cache_cleaner.py
Python
apache-2.0
2,104
0.000951
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance wi...
periodic task from cron. If something goes wrong while we're caching an image (for example the fetch times out, or an exception is raised), we create a
n 'invalid' entry. These entires are left around for debugging purposes. However, after some period of time, we want to clean these up. Also, if an incomplete image hangs around past the image_cache_stall_time period, we automatically sweep it up. """ import os import sys from oslo_log import log as logging # If .....
bluestemscott/librarygadget
librarygadget/paypal/pro/forms.py
Python
mit
1,840
0.003261
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from paypal.pro.fields import CreditCardField, CreditCardExpiryField, CreditCardCVV2Field, CountryField class PaymentForm(forms.Form): """Form used to process direct payments.""" firstname = forms.CharField(255, label="First Name...
lass ConfirmForm(forms.Form): """Hidden form used b
y ExpressPay flow to keep track of payer information.""" token = forms.CharField(max_length=255, widget=forms.HiddenInput()) PayerID = forms.CharField(max_length=255, widget=forms.HiddenInput())
Germanika/plover
plover/system/english_stenotype.py
Python
gpl-2.0
6,232
0.024069
KEYS = ( '#', 'S-', 'T-', 'K-', 'P-', 'W-', 'H-', 'R-', 'A-', 'O-', '*', '-E', '-U', '-F', '-R', '-P', '-B', '-L', '-G', '-T', '-S', '-D', '-Z', ) IMPLICIT_HYPHEN_KEYS = ('A-', 'O-', '5-', '0-', '-E', '-U', '*') SUFFIX_KEYS = ('-S', '-G', '-Z', '-D') NUMBER_KEY = '#' NUMBERS = { 'S-': '...
# cherry + s = cherries (consonant + y pluralization) (r'^(.+[bcdfghjklmnpqrstvwxz])y \^ s$', r'\1ies'), # == y == # die+ing = dying (r'^(.+)ie \^ ing$', r'\1ying'), # metallurgy + ist = metallurgist (r'^(.+[cdfghlmnpr])y \^ ist$', r'\1ist'), # beauty + ful = beautiful (y -> i) (r'^(.+[...
([a-hj-xz].*)$', r'\1i\2'), # == e == # write + en = written (r'^(.+)te \^ en$', r'\1tten'), # free + ed = freed (r'^(.+e)e \^ (e.+)$', r'\1\2'), # narrate + ing = narrating (silent e) (r'^(.+[bcdfghjklmnpqrstuvwxz])e \^ ([aeiouy].*)$', r'\1\2'), # == misc == # defer + ed = deferr...
0xf4/pythonrc
pythonrc.py
Python
mit
19,310
0.000414
#!/usr/bin/python r""" PYTHONRC ======== Initialization script for the interactive Python interpreter. Its main purpose is to enhance the overall user experience when working in such an environment by adding some niceties to the standard console. It also works with IPython and BPython, although its utility in that kin...
ending on the user's system, the compilation of the packages' and modules' list for completing `import ...` and `from ... import ...` commands can take a long time, es
pecially the first time it is invoked. - When completing things like a method's name, the default is to also include the closing parenthesis along with the opening one, but the cursor is placed after it no matter what, instead of between them. This is because of the python module `readline`'s limitations. You can turn...
skunkwerks/netinf
python/nilib/nicl.py
Python
apache-2.0
8,160
0.003922
#!/usr/bin/python """ @package nilib @file nicl.py @brief Basic command line client for NI names, make 'em and check 'em @version $Revision: 0.04 $ $Author: elwynd $ @version Copyright (C) 2012 Trinity College Dublin This is an adjunct to the NI URI library developed as part of the SAIL project. (http://sai...
parser.add_option("-w", "--well-known", default=False, action="store_true", dest="well_known", h
elp="Generate hash based on content file, " + \ "and output name with encoded hash in the .well_known URL " + \ "after the hashalg string. Applies to ni: scheme only.") parser.add_option("-v", "--verify", default=False, action="store_true",...
cogeorg/econlib
test_paralleltools.py
Python
gpl-3.0
601
0.003328
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- __author__ = """Co-Pierre Georg (co-pierre.georg@uct.ac.za)""" import sys from src.paralleltools import Parallel #
------------------------------------------------------------------------- # # conftools.py is a simple module to manage .xml configuration files # #------------------------------------------------------------------------- if __name__ == '__main__': """ VARIABLES """ args = sys.argv config_file_nam...
les(config_file_name)
duncan-r/SHIP
ship/tuflow/tuflowmodel.py
Python
mit
22,689
0.003261
""" Summary: Container and main interface for accessing the Tuflow model and a class for containing the main tuflow model files (Tcf, Tgc, etc). There are several other classes in here that are used to determine the order of the files in the model and key words for reading in the files. ...
_type].control_files: raise AttributeError("model_file doesn't exists in %s control_files" % model_file.model_type) self.control_files[model_file.model_type].removeControlFile(model_file) self.control_files['TCF'].parts.remove(model_file) def replaceTcfModelFile(self, model_file, contr...
Note: You can call this function directly if you want to, but it is also hooked into a callback in the TCF ControlFile. This means that when you use the standard ControlFile add/remove/replaceControlFile() methods these will be called automatically. Args...
fangeugene/the-blue-alliance
tests/suggestions/test_media_url_parse.py
Python
mit
10,138
0.004636
import json import unittest2 from google.appengine.ext import testbed from consts.media_type import MediaType from helpers.media_helper import MediaParser from helpers.webcast_helper import WebcastParser class TestMediaUrlParser(unittest2.TestCase): def setUp(cls): cls.testbed = testbed.Testbed() ...
self.assertEqual(MediaParser.partial_media_dict_from_url("http://imgur.com/r/aww"), None) self.assertEqual(MediaParser.partial_media_dict_from_url("http://imgur.com/a/album"), None) def test_fb_profile_parse(self): result = MediaParser.partial_media_dict_from_url("http://facebook.com/theuberbots")...
qual(result['media_type_enum'], MediaType.FACEBOOK_PROFILE) self.assertEqual(result['is_social'], True) self.assertEqual(result['foreign_key'], 'theuberbots') self.assertEqual(result['site_name'], MediaType.type_names[MediaType.FACEBOOK_PROFILE]) self.assertEqual(result['profile_url'], '...
Tasignotas/topographica_mirror
topo/base/arrayutil.py
Python
bsd-3-clause
4,625
0.017514
""" General utility functions and classes for Topographica that require numpy. """ import re from numpy import sqrt,dot,arctan2,array2str
ing,fmod,floor,array, \ unravel_index,concatenate,set_printoptions,divide,maximum,minimum from numpy import ufunc import param # Ask numpy to print even relatively large arrays by default set_printoptions(threshold=200*200) def ufunc_script_repr(f,imports,prefix=None,settings=None): """ Return a runnab...
module. """ # (could probably be generalized if required, because module is # f.__class__.__module__) imports.append('import numpy') return 'numpy.'+f.__name__ from param import parameterized parameterized.script_repr_reg[ufunc]=ufunc_script_repr def L2norm(v): """ Return the L2 norm of ...
ninjin/simsem
experiment/learning.py
Python
isc
17,339
0.006863
''' Learning-curve test functionality. Author: Pontus Stenetorp <pontus stenetorp se> Version: 2011-08-29 ''' from collections import defaultdict from itertools import chain, izip from operator import itemgetter from os.path import join as path_join from random import sample, seed from sys import stderr fr...
worker_pool, verbose=False, no_simstring_cache=False, use_test_set=False, folds=10, min_perc=5, max_perc=100, step_perc=5,
it_factor=1): # XXX: Not necessary any more! if verbose: print >> stderr, 'Calculating train set size...', train_size = 0 for d in train: for s in d: for a in s: train_size += 1 if verbose: print >> stderr, 'Done!' # XXX: if not no_...
vprusso/youtube_tutorials
algorithms/recursion/str_len.py
Python
gpl-3.0
615
0.00813
# YouTube Video: https://www.youtube.com/watch?v=RRK0gd7
7Ln0 # Given a string, calculate the length of the string. input_str = "LucidProgramming" # Standard Pythonic way: # prin
t(len(input_str)) # Iterative length calculation: O(n) def iterative_str_len(input_str): input_str_len = 0 for i in range(len(input_str)): input_str_len += 1 return input_str_len # Recursive length calculation: O(n) def recursive_str_len(input_str): if input_str == '': return 0 ret...
mcook42/Py_R_Converters
py2r-syntax-converter.py
Python
mit
11,063
0.003073
""" Written by Matthew Cook Created August 4, 2016 mattheworion.cook@gmail.com Script to do basic sytax conversion between Python 3 and R syntax. What it does convert: -assignment operator -function definitions -filename -inline arithmetic (*=, +=, -=, **) -':' to '{' -'not' to '!...
ine = fname + ' <- function' + params else: line = opfunc(line, key) return line # TESTED-Works def chglinecontent(line): """Changes content contained within a si
ngle line""" # Perform simple changes for key in simple_change.keys(): # Ignore if string version exists in line check_str_s, check_str_d = stringify(key) if not check_str_d in line or not check_str_s in line: line = ignoreStrReplace(line, key, simple_change[key]) ...
gunan/tensorflow
tensorflow/python/kernel_tests/pool_test.py
Python
apache-2.0
14,854
0.00579
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
input_shape=input_shape, window_shape=window_shape, padding=padding,
pooling_type=pooling_type, dilation_rate=[1, 1], strides=strides) def testPool3D(self): if test.is_built_with_rocm(): self.skipTest("Pooling with 3D tensors is not supported in ROCm") with self.session(use_gpu=test.is_gpu_available()): ...
StamusNetworks/scirius
rules/migrations/0058_source_public_source.py
Python
gpl-3.0
440
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-05 09:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies
= [ ('rules', '0057_auto_20180302_1312'), ] operations = [ migrations.AddField( model_name='source', name='public_source', fi
eld=models.CharField(blank=True, max_length=100, null=True), ), ]
boada/ICD
sandbox/legacy_plot_code/ston_test.py
Python
mit
488
0.004098
import pyfits as pyf import pylab as pyl full = pyf.getdata('./data/gs_all_tf_h_130511b_multi.fits') sample = pyf.getdata('../samples/sample_1.5_3.5_gs_all.fits') f = pyl.fig
ure(1) f1 = f.add_subplot(111) for i in range(len(sample)): ID = sample['ID'][i] H_flux = full['WFC3_F160W_FLUX'][i-1] H_flux_err = full['WFC3_F160W_FLUXERR'][i-1] H_flux_weight = full['WFC3_F160W_WEIGHT'][i-1] H_mag = sample['Hmag'][i] f1.scatter(H_mag,H_
flux/H_flux_err) pyl.show()
git-artes/GNUWiNetwork
gwn/gwnevents/api_events.py
Python
gpl-3.0
2,996
0.00534
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of GNUWiNetwork, # Copyright (C) 2014 by # Pablo Belzarena, Gabriel Gomez Sena, Victor Gonzalez Barbone, # Facultad de Ingenieria, Universidad de la Republica, Uruguay. # # GNUWiNetwork is free software: you can redistribute it ...
ent of the given event nickname. @param nickname: a valid event nickname, i.e. one that is a key in dictionary of valid nicknames. @param kwargs: a
dictionary of variables depending on the type of event. Field C{ev_dc} is a dictionary of fields and values for the corresponding event type; field C{frmpkt} is a binary packed frame. @return: an Event object. ''' from evtimer import dc_nicknames as ev_dc_nicknames import utils.framers.ieee80211.evfram...
tamac-io/jenkins-job-builder
jenkins_jobs/cli/entry.py
Python
apache-2.0
5,508
0.000182
#!/usr/bin/env python # Copyright (C) 2015 Wayne Warren # # 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...
mmand; instead, python scripts may be written that pass `jenkins_jobs` args directly to this class to allow programmatic setting of various command line parameters. """ def __init__(self, args=None, **kwargs): if args is None: args = [] self.parser = create_parser() ...
s) self.jjb_config = JJBConfig(self.options.conf, **kwargs) if not self.options.command: self.parser.error("Must specify a 'command' to be performed") if (self.options.log_level is not None): self.options.log_level = getattr(logging, ...