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
ad-m/flanker
tests/mime/message/headers/encodedword_test.py
Python
apache-2.0
7,339
0.004657
# coding:utf-8 from nose.tools import * from mock import * from flanker.mime.message.headers import encodedword from flanker import utils from flanker.mime.message import errors, charsets def encoded_word_test(): def t(value): m = encodedword.encodedWord.match(value) return (m.group('charset'), m...
de(v)) v = ' =?US-ASCII?Q?Foo?= <foo@example.com>' eq_(u'Foo <foo@example.com>', encodedword.mime_to_unicode(v)) v = '''=?UTF-8?Q?=D1=80=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=\n =?UTF-8?Q?_=D0=B8?= english112 =?UTF-8?Q?=D1=81=D0=B0=D0=B1=D0=B6?= subject''' eq_(u'русский и english112 сабж ...
étål Unîcødé', encodedword.mime_to_unicode(v)) def lying_encodings_mime_to_unicode_test(): v = '''=?US-ASCII?Q?=D1=80=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?=\n =?unknonw?Q?_=D0=B8?= english112 =?UTF-8?Q?=D1=81=D0=B0=D0=B1=D0=B6?= subject''' eq_(u'русский и english112 сабж subject', encodedword.mim...
geekaia/edx-platform
lms/djangoapps/analytics/tests/test_basic.py
Python
agpl-3.0
2,084
0.003839
""" Tests for instructor.basic """ from django.test import TestCase from student.models import CourseEnrollment from student.tests.factories import UserFactory from opaque_keys.edx.locations import SlashSeparatedCourseKey from analytics.basic import enrolled_students_features, AVAILABLE_FEATURES, STUDENT_FEATURES, PR...
for userreport in userreports: self.assertEqual(set(userreport.keys()), set(query_features)) self.assertIn(userreport['username'], [user.username for user in self.users]) self.assertIn(userreport['email'], [user.email for user in self.users]) self.assertIn(userreport...
ile.name for user in self.users]) def test_available_features(self): self.assertEqual(len(AVAILABLE_FEATURES), len(STUDENT_FEATURES + PROFILE_FEATURES)) self.assertEqual(set(AVAILABLE_FEATURES), set(STUDENT_FEATURES + PROFILE_FEATURES))
dakside/pydemo
flask/hellojinja/app.py
Python
mit
2,459
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Hello Flask Latest version can be found at https://github.com/dakside/pydemo References: Python documentation: https://docs.python.org/ Flask documentation: http://flask.pocoo.org/ PEP 0008 - Style Guide for Python Code https://ww...
Anh <tuananh.ke@gmail.com> ''' # Copyright (c) 2016, Le Tuan Anh <tuananh.ke@gmail.com> # # 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 limi
tation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or ...
ganwell/rbtree
old_dev/src/test_mpipe.py
Python
mit
712
0
# SPDX-FileCopyrightText: 2019 Jean-Louis Fuchs <ganwell@fangorn.ch> # # SPDX-License-Identifier: AGPL-3.0-or-later """Test mpipe.""" import mpipe from hypothesis import given import hypothesis.strategies as st
@given(st.integers( max_value=2 ** 30, min_value=-2 ** 30, )) def test_mpipe(num): """Test if test_mpipe retuns num + 1.""" with mpipe.open_and_close(["./build/test_mpipe"]) as proc: mpipe.write(proc, (1, num)) res = mpipe.read(proc) assert res[0] == num + 1 if __name__ == "_...
ld/test_mpipe"]) mpipe.write(proc, (1, 0)) res = mpipe.read(proc) print(res) mpipe.write(proc, (0,)) mpipe.close(proc)
shollen/evennia
evennia/contrib/rpsystem.py
Python
bsd-3-clause
43,810
0.002123
""" Roleplaying base system for Evennia Contribution - Griatch, 2015 This module contains the ContribRPObject, ContribRPRoom and ContribRPCharacter typeclasses. If you inherit your objects/rooms/character from these (or make them the defaults) from these you will get the following features: - Objects/Rooms will...
asks to hide your identity (using a simple lock). - pose system to set room-persistent poses, visible in room descriptions and when looking at the person/object. This is a simple Attribute that modifies how the characters is viewed when in a room as sdesc + pose. - in-emote says, includ...
integration with language obscuration routine (such as contrib/rplanguage.py) Examples: > look Tavern The tavern is full of nice people *A tall man* is standing by the bar. Above is an example of a player with an sdesc "a tall man". It is also an example of a static *pose*: The "standing by the bar" has be...
gopythongo/gopythongo
src/py/gopythongo/__init__.py
Python
mpl-2.0
290
0
# -* coding: utf-8 *- # This Source Code Form is su
bject 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/. version = "0.7.7.dev0" program_version = "GoPyt
honGo %s" % version
urbanairship/pasttle
tests/suites/functional.py
Python
mit
9,972
0
#!/usr/bin/env python # # -*- mode:python; sh-basic-offset:4; indent-tabs-mode:nil; coding:utf-8 -*- # vim:set tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8: # import hashlib import os import sys import unittest import urlparse import webtest import util class FunctionalTest(unittest.TestCase): ...
.path.join(util.TEST_DIR, 'pasttle.ini') ct = 'text/plain' fh = open(fn, 'rb') text = fh.read() fh.close() rsp = self.app.post( '/post', { 'upload': text, 'filename': fn, 'syntax': ct, } ) ass...
y) rsp = self.app.get( '/raw{0}'.format(url.path.decode(),), ) assert rsp.status == '200 OK' assert rsp.body == text assert rsp.content_type == ct def test_upload_and_edit(self): "Upload some text, then edit it, expect a 200 in both cases" text = ...
NLNZDigitalPreservation/rosetta_sip_factory
setup.py
Python
mit
614
0.037459
try: from setuptools import setup except ImportError: from distutils.core import setup VERSION="0.1.9" config = { 'name':'rosetta_sip_factory',
'version':VERSION, 'author':'Sean Mosely', 'author_email':'sean.mosely@gmail.com', 'packages':['rosetta_sip_factory',], 'description':'Python library for building Submission Information Packages for the Ex Libris Rosetta digital preservation application', 'install_requires':['lxml>=3.6.4', 'mets_dnx'], 'download_...
+VERSION+'.tar.gz', 'license': 'MIT', } setup(**config)
drmrd/ansible
lib/ansible/plugins/terminal/iosxr.py
Python
gpl-3.0
1,883
0.000531
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
metaclass__ = type import re import json from ansible.plugins.terminal import TerminalBase from ansible.errors import AnsibleConnectionFailure class TerminalModule(TerminalBase): terminal_stdout_re = [ re.compile(br"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"), re.compile(br']]>]]>[\r...
re.compile(br"invalid input", re.I), re.compile(br"(?:incomplete|ambiguous) command", re.I), re.compile(br"connection timed out", re.I), re.compile(br"[^\r\n]+ not found", re.I), re.compile(br"'[^']' +returned error code: ?\d+"), re.compile(br"Failed to commit", re.I) ]...
Signiant/ultron
ultron/plugin.py
Python
mit
585
0.011966
import imp,os pluginFolder = "./plugins" mainFile = "__init__" def getAllPlugins(): plugins = [] possibleplugins = os.listdir(pluginFolder) for i in possibleplugins: location = os.path.join(pluginFolder, i) if not os.path.isdir(location) or not mainFile
+ ".py" in os.listd
ir(location): continue info = imp.find_module(mainFile, [location]) plugins.append({"name": i, "info": info}) return plugins def loadPlugin(pluginName): return imp.load_source(pluginName, os.path.join(pluginFolder, pluginName, mainFile + ".py"))
enlighter/phone-convesation-test-portal
convo_test/conversations/migrations/0003_auto_20160405_2244.py
Python
mit
544
0.001838
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-05 17:14 from __future__ i
mport unicode_literals from django.db import migrations, models import djan
go.utils.timezone class Migration(migrations.Migration): dependencies = [ ('conversations', '0002_auto_20160405_2119'), ] operations = [ migrations.AlterField( model_name='conversation', name='date', field=models.DateTimeField(default=django.utils.time...
lehinevych/cfme_tests
artifactor/plugins/ostriz.py
Python
gpl-2.0
1,605
0.001246
from artifactor import ArtifactorBasePlugin import requests import json def overall_test_status(statuses): # Handle some logic for when to count certain tests as which state for when, status in statuses.iteritems(): if when == "call" and status[1] and status[0] == "skipped": return "xfaile...
configure(self): self.url = self.data.get('url', None) self.configured = True @ArtifactorBasePlugin.check_configured def ostriz_send(self, artifacts, test_location, test_name, slaveid, run_id, version, build, stream): test_ident = "{}/{}".format(test_location, test_name) ...
json_data['slaveid'] = slaveid json_data['source'] = self.data['source'] json_data['version'] = version json_data['build'] = build json_data['stream'] = stream json_data['method'] = "automated" requests.post(self.url, data=json.dumps(json_data)) return None, ...
EuroSentiment/eurosentiment-tutorial-python
utils/text_utils.py
Python
lgpl-3.0
1,154
0.0026
# encoding: utf-8 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in
the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this prog...
import normalize def flatten(text): if not isinstance(text, unicode): text = text.decode('utf-8', errors="ignore") return normalize("NFKD", text).encode("ascii", errors="ignore").lower() def matches_count(text, words): text_words = flatten(text).split() matches = {word:text_words.count(flatten...
kohr-h/odl
odl/test/test_doc.py
Python
mpl-2.0
2,168
0
# Copyright 2014-2020 The ODL contributors # # This file is part of ODL. # # 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 https://mozilla.org/MPL/2.0/. """Run all doctests in the online documentat...
t_suffixes) and filename not in exclude_files): doc_src_files.append(os.path.join(path, filename)) doc_src_file = simp
le_fixture("doc_src_file", doc_src_files) @pytest.mark.suite("doc_doctests") def test_file(doc_src_file): # FIXXXME: This doesn't seem to actually test the file :-( doctest.testfile(doc_src_file, module_relative=False, report=True, extraglobs=doctest_extraglobs, verbose=True, ...
tqdv/info-lstl
Info/TPs/2016-11-22.py
Python
gpl-3.0
4,210
0.036342
from time import clock # Actual Sum def SommePartielle (L, a, b) : s = 0 for i in range (a, b+1) : s += L[i] return s # Partial Sum def SommesPartielles_1 (L) : S = [] for i in range (0, len(L)) : S.append ( SommePartielle (L, 0, i) ) return S # Partial Sum de...
063355361e-06 # # tmw when you write in YAML from random import randint def ListeAleatoire (n) : L = [] for _ in range (n) : L.append (randint ( -100 , 100)) return L from matplotlib.pyplot import scatter , grid , show , close def VisualiserTemps ( Programme
) : Tailles = [ 50 * 2**i for i in range (0, 6+1) ] Temps = [ Chrono ( Programme , ListeAleatoire (n)) for n in Tailles ] grid ( True ) scatter ( Tailles , Temps ) show () from numpy import log as ln , polyfit def ModeliserTemps ( Programme ) : Tailles = [ 50 * 2**i for i in range (0...
bsiegfreid/tkdraw
tkdraw/config.py
Python
mit
859
0
import os from appdirs import AppDirs class Config: def __init__(self): self.app_dir = get_app_dir() def save_geometry(self, window): path = os.path.join(self.app_dir, 'geometry.conf') print(path) with open(path, "w") as conf: conf.write(window.geometry()) de...
except IOError: geometry = '' print(geometry) return geo
metry def get_app_dir(): app_dirs = AppDirs('tkdraw', 'tkdraw') user_config_dir = os.path.normpath(app_dirs.user_config_dir) if not os.path.isdir(user_config_dir): os.makedirs(user_config_dir) return user_config_dir
wichmann/PythonExamples
sense-hat/weatherpublisher.py
Python
gpl-2.0
2,604
0.001925
#!/usr/bin/env python3 import time import json import requests from datetime import datetime import paho.mqtt.client as mqtt from sense_hat import SenseHat BROKER_URL = '192.168.24.25' CYCLE_TIME = 10 # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def get_location(): """Ermit...
me.fromtimestamp(data['sys']['sunset']) return weather, temp, humidity, wind_speed, sunrise, sunset if __name__ == '__main__': try: mqttc = mqtt.Client() mqttc.connect(BROKER_URL, 1883, 60) while True: weather, temp, humidity, wind_speed, sunrise, sunset = get
_weather(get_location()) mqttc.publish('umgebung/wetter', str(weather)) mqttc.publish('umgebung/temperatur', str(temp)) mqttc.publish('umgebung/luftfeuchtigkeit', str(humidity)) mqttc.publish('umgebung/windgeschwindigkeit', str(wind_speed)) mqttc.publish('umge...
Esri/hermes
setup.py
Python
apache-2.0
1,045
0.002871
from setuptools import setup,find_packages with open('src/hermes/version.py') as fin: exec(fin.read()) setup( name='esri-hermes', version=__version__, package_dir={'':'src'}, packages=find_packages('src'), include_package_data=True, # PyPI MetaData author='achapkowski',
author_email='achapkowski@esri.com', description='Collecti
on of Utilities to Read/Write a Dataset\'s Metadata', license='Apache License - 2.0', keywords='esri,arcpy,metadata', url='https://github.com/Esri/hermes', classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English...
harold-b/duktape
tools/dukutil.py
Python
mit
9,031
0.002436
#!/usr/bin/env python2 # # Python utilities shared by the build scripts. # import datetime import json class BitEncoder: "Bitstream encoder." _bits = None _varuint_dist = None _varuint_cats = None _varuint_count = None _varuint_bits = None def __init__(self): self._bits = [] ...
if comment is not None: self.emitLine('#define %-60s %-30s /* %s */' % (name, value, comment)) else: self.emitLine('#define %-60s %s' % (name,
value)) def getString(self): "Get the entire file as a string." return ''.join(self._data) def json_encode(x): "JSON encode a value." try: return json.dumps(x) except AttributeError: pass # for older library versions return json.write(x) def json_decode(x): ...
xia2/xia2
src/xia2/__init__.py
Python
bsd-3-clause
128
0
from __future__ impo
rt annotations import sys if sys
.version_info.major == 2: sys.exit("Python 2 is no longer supported")
gregljohnson/ProjectEuler
problem50.py
Python
mit
1,002
0.038922
''' Name: Problem 50: Consecutive prime sum (29435) The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes
that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? ''' from itertools import permutations from math import sqrt def c...
=0: return False return True primes=[] for n in range(2,1000000): if(checkForPrimality(n)): primes.append(n) checkedPrimes=[] maxCount=0 maxValue=0 for p in primes: count=0 pSum=p for p2 in primes: pSum=pSum + p2 if p2>p and pSum < 1000000: if pSum in primes: if count > maxCount: maxCount=...
sknepneklab/SAMoS
utils/RastkoVisu/dat2vtp.py
Python
gpl-3.0
10,485
0.023557
# * ************************************************************* # * # * Soft Active Mater on Surfaces (SAMoS) # * # * Author: Rastko Sknepnek # * # * Division of Physics # * School of Engineering, Physics and Mathematics # * University of Dundee # * # * (c) 2013, 2014 # * # * School of Scienc...
-------------------------" print print "\tInput files : ", args.input print "\tOutput files : ", args.output print "\tSkip frames : ", args.skip if args.contact != None: print "\tContact network data file : ", args.contact if args.exclude != None: print "\tExclude all contact lines that are longer than : ", args.ex...
iles = sorted(glob(args.input+'*.dat'))[args.skip::args.step] if len(files) == 0: files = sorted(glob(args.input+'*.dat.gz'))[args.skip::args.step] else: files = sorted(glob(args.input+'*.dat'))[args.skip:args.end_sample:args.step] if len(files) == 0: files = sorted(glob(args.input+'*.dat.gz'))[args.skip:...
vdmitriyev/services-to-wordcloud
services/orcid/pyorcid/__init__.py
Python
mit
97
0
__all__ =
('get', 'search', 'Q') from .rest import
get, search from lucenequerybuilder import Q
hmpf/nav
python/nav/ipdevpoll/shadows/interface.py
Python
gpl-3.0
17,311
0.000751
# # Copyright (C) 2009-2012 Uninett AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 3 as published by # the Free Software Foundation. # # This program is distributed in the...
_find_existing_for: " "Found multiple matching interfaces for %r" % snmp_ifc )
elif result: return result[0] def _resolve_changed_ifindexes(self): """Resolves conflicts that arise from changed ifindexes. The db model will not allow duplicate ifindex, so any ifindex that appears to have changed on the device must be nulled out in the database b...
SteveDiamond/cvxpy
examples/extensions/mixed_integer/assign.py
Python
gpl-3.0
2,368
0.000845
""" Copyright 2013 Steven Diamond Licensed under t
he 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 .boolean import Boolean import cvxpy.lin_ops.lin_utils as lu from munkres import Munkres import numpy as ...
jjmark15/age-calculator
age_calculator.py
Python
mit
928
0.005388
from datetime import date def calculate_age(array): for i, val in enumerate(array): array[i] = int(val) born = date(array[2], array[1], array[0]) today = date.today() return today.year - born.year -\ ((today.month, today.day) < (born.month, born.day)) def find_splitter(text): for i, ...
div = find_splitter(i
np) inp = inp.split(div) this_year = date.today().strftime("%Y") this_cent = this_year[:2] + '00' init_year = inp[2] if len(inp[2]) < 4: inp[2] = int(this_cent[:len(this_cent) - len(inp[2])] + inp[2]) if inp[2] > int(this_year): inp[2] -= 100 age = calculate_age(inp)...
saeki-masaki/cinder
cinder/tests/unit/test_smbfs.py
Python
apache-2.0
25,862
0.000039
# Copyright 2014 Cloudbase Solutions Srl # # 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 ...
ing_volume(self): self._test_create_volume(volume_exists=True) def test_create_vhdx(self): self._test_create_volume(volume_format='vhdx')
def test_create_qcow2(self): self._test_create_volume(volume_format='qcow2') def test_create_sparsed(self): self._test_create_volume(volume_format='sparsed') def test_create_regular(self): self._test_create_volume() def _test_find_share(self, existing_mounted_shares=True, ...
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/sklearn/neighbors/base.py
Python
mit
30,908
0
"""Base and mixin classes for nearest neighbors""" # Authors: Jake Vanderplas <vanderplas@astro.washington.edu> # Fabian Pedregosa <fabian.pedregosa@inria.fr> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # Sparseness support by Lars Buitinck # Multi-output support by Arnaud Jol...
<a.joly@ulg.ac.be> # # License: BSD 3 clause (C) INRIA, University of Amsterdam import warnings from abc import ABCMeta, abstractmethod import numpy as np fro
m scipy.sparse import csr_matrix, issparse from .ball_tree import BallTree from .kd_tree import KDTree from ..base import BaseEstimator from ..metrics import pairwise_distances from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS from ..utils import check_X_y, check_array, _get_n_jobs, gen_even_slices from ..uti...
pubnub/pubnub-openshift-quickstart
setup.py
Python
mit
603
0.003317
from setuptools import setup setup(name='PubNubPython27', version='1.0', description='OpenShift Python-2.7 Community Cartridge based application', author='Doron She
rman', author_email='doron@pubnub.com', url='http://www.python.org/sigs/distutils-sig/', # Uncomment one
or more lines below in the install_requires section # for the specific client drivers/modules your application needs. install_requires=['greenlet', 'gevent', # 'MySQL-python', # 'pymongo', # 'psycopg2', ], )
chiluf/visvis.dev
examples/bouncingBall.py
Python
bsd-3-clause
1,483
0.014835
#!/usr/bin/env python """ This example shows a ball that bounces on a surface and has two balls rotating around it. It illustrates the use of timers and how object hierarchy can be used to build (and move) complex models consisting of multiple simple objects. """ import visvis as vv # Create floor floor = vv.solidBox...
f earthRot.angle > 360: earthRot.angle = 0 # Move sun sun.zSpeed -= 0.01 sunTrans.dz += sun.zSpeed # Detect bounce
if sunTrans.dz < 0: sun.zSpeed *= -1 sunTrans.dz = 0 # Update! axes.Draw() # Create time and enter main loop timer = vv.Timer(axes, 100, False) timer.Bind(onTimer) timer.Start() app = vv.use() app.Run()
DirtyCajunRice/PlexShowSilencer
plexshowsilencer/plexshowsilencer/settings.py
Python
gpl-3.0
3,863
0.001812
import os from django.core.exceptions import ImproperlyConfigured try: from plexshowsilencer import configuration except ImportError: raise ImproperlyConfigured( "Configuration file is not present. Please define plexshowsilencer/plexshowsilencer/configuration.py per the documentation." ) VERSION =...
'NAME': 'django.contrib.auth.password_validation.UserAttrib
uteSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ...
DavisNT/mopidy-alarmclock
tests/test_extension.py
Python
apache-2.0
1,459
0.001371
import unittest import mock from mopidy_alarmclock import Extension class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[alarmclock]', config) self.assertIn('enabled = true', config) ...
assertIn('def_time', schema) self.assertIn('def_playlist', schema) self.assertIn('def_random', schema) self.assertIn('def_volume', schema) self.assertIn('def_vol_inc_duration', schema) def test_setup(self): registry = mock.Mock() ext = Extension() ext.setup(...
'factory': registry.add.call_args[0][1]['factory'], })
xgfone/snippet
snippet/example/python/scrapy/crawler/crawler/linkextractors.py
Python
mit
1,740
0
# encoding: utf-8 from __future__ import unicode_literals, print_function from scrapy.linkextractors import LinkExtractor from scrapy.link import Link from scrapy.selector import Selector from crawler.utils import URL # from crawler import settings NEXT = ["next", "下一页"] class NextLinkExtractor(LinkExtractor): ...
).__init__(*args, **kwargs) self.spider = spider @property def css_selector(self): return self.spider.css_selector def get_css(self, css_name, default=None): return self.spide
r.get_css(css_name, default) def extract_next_links(self, response): hxs = Selector(response) next_css = self.get_css("next_css") if not next_css: return [] _next = hxs.css(next_css) for n in _next: nl = n.xpath('text()').extract()[0].lower() ...
verejnedigital/verejne.digital
data/geocoder.py
Python
apache-2.0
14,851
0.002492
# -*- coding: utf-8 -*- import itertools import json import re import urllib.request import urllib.parse import yaml from psycopg2.errors import UniqueViolation, InFailedSqlTransaction # Class to transform address -> address_id. The class takes care of caching and # address normalization (e.g lowercase, remove 'Slove...
test_mode): self.db_address_cache = db_address_cache self.db_address_id = db_address_id self.test_mode = test_mode # Read API key for geocoding lookups. with open("/tmp/geocode_key.txt", 'r') as f: self.geocode_key = yaml.load(f, Loader=yaml.FullLoader)['key'] ...
(' ') or command followed by # space (', ') self.prog = re.compile(" ([0-9]+)/([0-9]+)( |(, ))") # Match psc, either XXXXX or XXX XX. Check that it's in a block with a # nondigit character (or beginning/end of string) before and after self.psc = re.compile("(\D|^)([0-9][0-9][0-9...
LikeABird/tweepy
tweepy/models.py
Python
mit
14,292
0.00014
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from __future__ import absolute_import, print_function from tweepy.utils import parse_datetime, parse_html_value, parse_a_href class ResultSet(list): """A list like object that holds results from a Twitter API query.""" def __init__(...
g': # twitter sets this to null if it is false if v is True: setattr(user, k, True) else: setattr(user, k, False) else: setattr(user, k, v) ret
urn user @classmethod def parse_list(cls, api, json_list): if isinstance(json_list, list): item_list = json_list else: item_list = json_list['users'] results = ResultSet() for obj in item_list: results.append(cls.parse(api, obj)) retu...
nicproulx/mne-python
mne/time_frequency/tfr.py
Python
bsd-3-clause
69,456
0
"""A module which implements the time-frequency estimation. Morlet code inspired by Matlab code from Sheraz Khan & Brainstorm & SPM """ # Authors : Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Hari Bharadwaj <hari@nmr.mgh.harvard.edu> # Clement Moutard <clement.moutard@polytechniq...
mean=False): """Compute Morlet wavelets for the given frequency range. Parameters ---------- sfreq : float The sampling Frequency. freqs : array frequency range of interest (1 x Frequencies) n_cycles: float | array of float, defaults to 7.0 Number of cycles. Fixed number...
It controls the width of the wavelet ie its temporal resolution. If sigma is None the temporal resolution is adapted with the frequency like for all wavelet transform. The higher the frequency the shorter is the wavelet. If sigma is fixed the temporal resolution is fixed lik...
briot/geneapro
backend/backend/middleware/profile.py
Python
gpl-2.0
892
0.001121
from datetime import datetime import cProfile # Invokes the profiler when processing a query. # Postprocess results with: # pyprof2calltree -k -i /tmp/*.pro # # or, when kcachegrind is not available, you
can also use # cprofilev -f /tmp/*.pro # navigate to http://127.0.0.1:4000 class ProfileMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if hasattr(request, 'profiler'): profiler = cProfile.Profile() ...
profiler.dump_stats(f'/tmp/{stamp}.pro') print(f"Dumped profile info in /tmp/{stamp}.pro") return response else: return self.get_response(request)
noironetworks/heat
heat/engine/resources/openstack/senlin/cluster.py
Python
apache-2.0
15,586
0
# Copyright 2015 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 by applicable law or agree...
properties.Schema.INTEGER, _('Maximum number of resources in the cluster. ' '-1 means unlimited.'), default=-1, update_allowed=True, constraints=[ constraints.Range(min=-1) ] ), METADATA: properties.Sche...
OUT: properties.Schema( properties.Schema.INTEGER, _('The number of seconds to wait for the cluster actions.'), update_allowed=True, constraints=[ constraints.Range(min=0) ] ), POLICIES: properties.Schema( properties...
UNINETT/nav
python/nav/web/netmap/urls.py
Python
gpl-2.0
2,459
0
# #
Copyright (C) 2012 Uninett AS # # This file is part of Network Administration Visualized (NAV). # # NAV is fr
ee software: you can redistribute it and/or modify it under the # terms of the GNU General Public License version 3 as published by the Free # Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FI...
rdempsey/jobber
jobber/api/jobber.py
Python
mit
8,719
0.002064
""" jobber.api.jobber ~~~~~~~~~~~~~~~~~ Functions making up the Jobber API """ import connexion import datetime import logging from os import getenv from collections import defaultdict import jobber_orm as jorm import jobber_api_utils as jau db_session = None nested_dict = lambda: defaultdict(nested_dict) def get...
lication is not None else 201) def delete_job_application(job_application_id): """ Delete a job application. :param int job_application_id: ID of the job application :return: success or failure response :rtype: dict """ logging.info("delete_job_application endpoint called") db_respon...
eting job application {}', job_application_id) db_session.query(jorm.JobApplication).filter(jorm.JobApplication.id == job_application_id).delete() db_session.commit() response = jau.create_return_object() return response, 200 else: response = jau.create_return_object(error_st...
jeroendierckx/Camelot
camelot/view/model_thread/signal_slot_model_thread.py
Python
gpl-2.0
10,093
0.013277
# ============================================================================ # # Copyright (C) 2007-2012 Conceptive Engineering bvba. All rights reserved. # www.conceptive.be / project-camelot@conceptive.be # # This file is part of the Camelot Library. # # This file may be used under the terms of the GNU General...
__init__( setup_thread ) self._task_handler = None self._mutex = QtCore.QMutex() self._request_queue = [] self._connected = False self._setup
_busy = True def run( self ): self.logger.debug( 'model thread started' ) self._task_handler = TaskHandler(self) self._task_handler.task_handler_busy_signal.connect(self._thread_busy, QtCore.Qt.QueuedConnection) self._thread_busy(True) try: self._setup_thread() ...
alerta/python-alerta
alertaclient/commands/cmd_tag.py
Python
mit
1,050
0.004762
import click from alertaclient.utils import build_query @click.command('tag', short_help='Tag alerts') @click.option('--ids', '-i', metavar='UUID', multiple=True, help='List of alert IDs (can use short 8-char id)') @click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web') @...
if query: query = [('q', query)] else: query = build_query(filters) total, _, _ = client.get_count(query) ids = [a.id for a in cli
ent.get_alerts(query)] with click.progressbar(ids, label='Tagging {} alerts'.format(total)) as bar: for id in bar: client.tag_alert(id, tags)
christopherdcunha/tastypie_signals
docs/conf.py
Python
bsd-3-clause
8,530
0.005275
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # ...
mentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodo
c', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General i...
GenericMappingTools/gmt-python
pygmt/src/subplot.py
Python
bsd-3-clause
10,779
0.000278
""" subplot - Manage modern mode figure subplot configuration and selection. """ import contextlib from pygmt.clib import Session from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import ( build_arg_string, fmt_docstring, is_nonstr_iter, kwargs_to_strings, use_alias, ) @fmt_docstrin...
). subsize : tuple Specify the dimensions of each subplot directly as (*width*, *height*). Note that only one of ``figsize`` or ``subsize`` can be provided at once. autolabel : bool or str [*autolabel*][**+c**\ *dx*\ [/*dy*]][**+g**\ *fil
l*][**+j**\|\ **J**\ *refpoint*][**+o**\ *dx*\ [/*dy*]][**+p**\ *pen*][**+r**\|\ **R**] [**+v**]. Specify automatic tagging of each subplot. Append either a number or letter [a]. This sets the tag of the first, top-left subplot and others follow sequentially. Surround the number ...
postmanlabs/httpsnippet
test/fixtures/output/python/requests/application-json.py
Python
mit
328
0.003049
import requests url = "http://mockbin.com/har" payload = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"
nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":
{}}]}" headers = {'content-type': 'application/json'} response = requests.request("POST", url, data=payload, headers=headers) print(response.text)
nanshihui/PocCollect
middileware/resin/resin_crackpass.py
Python
mit
2,249
0.026234
#coding:utf-8 import urllib2 from t import T class P(T): def __init__(self): T.__init__(self) def verify(self,head='',context='',ip='',port='',productname={},keywords='',hackinfo=''): timeout=3 target_url = 'http://'+ip+':'+port result = {} result['result']=False ...
nue except: return result finally: if res is not None: res.close() del res for flag in flag_list: if flag in res_html or int(res_code) == 408: ...
dmin Resin Weak password %s:%s'%(target_url,user,password) result['result']=True result['VerifyInfo'] = {} result['VerifyInfo']['type']='Resin Weak password' result['VerifyInfo']['URL'] =target_url re...
eltoncarr/tubular
tubular/exception.py
Python
agpl-3.0
841
0
""" Exceptions used by various utilities. """ # pylint: disable=missing-docstring class TimeoutException(Exception): pass class
ImageNotFoundException(Exception): pass class MultipleImagesFoundException(Exception): pass class MissingTagException(Exception): pass class BackendError(Exception): pass class BackendDataError(BackendError): pass class ResourceDoesNotExistException(Exception): pass class ASGDoesNot...
ption(ResourceDoesNotExistException): pass class ClusterDoesNotExistException(ResourceDoesNotExistException): pass class CannotDeleteActiveASG(Exception): pass class CannotDisableActiveASG(Exception): pass class CannotDeleteLastASG(Exception): pass class ASGCountZeroException(Exception): ...
GuessWhoSamFoo/pandas
pandas/arrays/__init__.py
Python
bsd-3-clause
427
0
""" All of pandas' ExtensionArrays. See :ref:`ext
ending.extension-types` for more. """ from pandas.core.arrays import ( IntervalArray, PeriodArray, Categorical, SparseArray, IntegerArray, PandasArray, DatetimeAr
ray, TimedeltaArray, ) __all__ = [ 'Categorical', 'DatetimeArray', 'IntegerArray', 'IntervalArray', 'PandasArray', 'PeriodArray', 'SparseArray', 'TimedeltaArray', ]
leppa/home-assistant
homeassistant/components/ambient_station/const.py
Python
apache-2.0
252
0
"""Define constants for the Ambient PW
S component.""" DOMAIN = "ambient_station" ATTR_LAST_DATA = "last_data" CONF_APP_KEY = "app_key" DATA_CLIENT = "data_cli
ent" TOPIC_UPDATE = "update" TYPE_BINARY_SENSOR = "binary_sensor" TYPE_SENSOR = "sensor"
lafrenierejm/ietf-cli
ietf/test/xml-fyi.py
Python
isc
1,273
0
#!/usr/bin/env python3 import os import unittest import xml.etree.ElementTree as ET from ietf.sql.base import Base from ietf.sql.fyi import Fyi from ietf.xml.fyi import add_all from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class TestXmlRfc(unittest.TestCase): data_file = os.path.jo...
self.rows = self.session.query(Fyi).order_by(Fyi.id).all() self.assertEqual(1, l
en(self.rows)) def test_title(self): # RFC 8180 self.std0002 = self.session.query(Fyi).filter(Fyi.id == 2).one() self.assertIsNone(self.std0002.title) if __name__ == '__main__': unittest.main()
i2c2-caj/ACM
solutions/devlali/devlali.py
Python
gpl-2.0
842
0.007126
import sys devlali = {} def sum_number(number): str_n = str(number) total = 0 for n in str_n: total += int(n) return total + number def generate_devlali(): for i in range(10001): total = sum_number(i) if (total in devlali.keys()): tmp_list = devlali[total] ...
t else: devlali[total] = [i] def get_devlali(number): if (number in devlali.keys()): if (len(devlali[number]) > 1): return 'junction' else: return 'generated' else:
return 'self' def main(): generate_devlali() lines = int(sys.stdin.readline().strip()) for num in range(lines): n = int(sys.stdin.readline().strip()) print n, get_devlali(n) main()
wathen/PhD
MHD/FEniCS/MHD/CG/common/Forms.py
Python
mit
3,046
0.005909
from dolfin import * class Forms(object): """docstring for Forms""" def __init__(self, mesh, W,F_M,F_NS, u_k,b_k,params,options={}): assert type(options) is dict, 'options must be a dictionary object' self.mesh = mesh self.W = W self.F_M= F_M self.F_NS= F_NS se...
tup'" # a11 = params[1]*params[0]*inner(curl(b),curl(c))*dx # a12 = inner(c,grad(r))*dx # a21 = inner(b,grad(s))*dx # Lmaxwell = inner(c, F_M)*dx # maxwell = a11+a12+a21 # "'NS Setup'" # n = FacetNormal(mesh) # a11 = params[2]*inner(grad(v), grad(u))*dx +inner((grad(u)*u_k),v)*dx+(1/2...
etup'" # CoupleTerm = params[0]*inner(cross(v,b_k),curl(b))*dx - params[0]*inner(cross(u,b_k), b,curl(c))*dx # return ns,maxwell,CoupleTerm,Lmaxwell,Lns
laurentb/weboob
weboob/applications/traveloob/traveloob.py
Python
lgpl-3.0
6,806
0.003236
# -*- coding: utf-8 -*- # Copyright(C) 2010-2013 Romain Bignon, Julien Hébert # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License...
nt_function import datetime from weboob.capabilities.base import Currency, empty from weboob.capabilities.travel import CapTravel, RoadmapF
ilters from weboob.tools.application.repl import ReplApplication, defaultcount from weboob.tools.application.formatters.iformatter import PrettyFormatter __all__ = ['Traveloob'] class DeparturesFormatter(PrettyFormatter): MANDATORY_FIELDS = ('id', 'type', 'departure_station', 'arrival_station', 'time') def...
vschw/smartmeter_release
odroidw_meter.py
Python
gpl-2.0
10,958
0.004745
#! /usr/bin/env python # Filename: odroidw_meter.py # -*- coding: utf-8 -*- """Smart meter application module for Odroid W. Setup Description ################# This application module utilizes the external 12-bit MCP3208 ADC connected to the Odroid W via SPI to be used as a real-time smart-power-meter. Current clamps i...
"" global spi spi = spidev.SpiDev() spi.open(0, 1) print 'SPI initialized' def init_tft(): """Enables TFT screen on fb1. """ os.environ["SDL_
FBDEV"] = "/dev/fb1" os.environ['SDL_VIDEODRIVER']="fbcon" global screen pygame.init() pygame.mouse.set_visible(0) size = width, height = 320, 240 screen = pygame.display.set_mode(size) print 'TFT screen initialized' def init_config(): """Loads configuration data from config.ini "...
pablocastelo/tripadvisor_scraping
get_hotel_reviews.py
Python
apache-2.0
10,086
0.038568
#!/usr/bin/env python from selenium import webdriver from lxml.cssselect import CSSSelector import selenium.webdriver.support.ui as ui import MySQLdb import time class MyDatabase: host = '' user = '' password = '' db = '' def __init__(self): self.connection = MySQLdb.connect(self.host, self.user, self.passwo...
a_hotelreview_user_sel) ta_hotelreviewx_userx.append(ta_hotelreviewx_user.text) except: ta_hotelreviewx_userx.append("anon") try: ta_hotelreviewx_usertitle = rowx.find_element_by_css_selector(ta_hotelreview_usertitle_sel) ta_hotelreviewx_usertitlex.append( ta_hotelreviewx_usertitle.text ) ex...
ctor(ta_hotelreview_city_sel) if not ta_hotelreviewx_city.text: ta_hotelreviewx_cityx.append("unknown") else: ta_hotelreviewx_cityx.append( ta_hotelreviewx_city.text ) except: ta_hotelreviewx_cityx.append( "unknown" ) try: ta_hotelreviewx_revtitle = rowx.find_element_by_css_selector(ta...
cuker/python-ups
ups/addressvalidation/__init__.py
Python
bsd-3-clause
326
0
from base import
StreetAddressValidation, AddressValidation UPS_XAV_CONNECTION = 'https://onlinetools.ups.com/ups.app/xml/XAV' UPS_XAV_CONNECTION_TEST = 'https://wwwcie.ups.com/ups.app/xml/XAV' UPS_AV_CONNECTION = 'https://onlinetools.ups.com/ups.app/xml/AV' UPS_AV_CONNECTION_TEST = 'https://wwwcie.ups
.com/ups.app/xml/AV'
ChantyTaguan/zds-site
zds/mp/tests/tests_utils.py
Python
gpl-3.0
4,013
0.000249
from django.contrib.auth.models import Group from django.core import mail from django.urls import reverse from django.test import TestCase from django.conf import settings from zds.member.factories import ProfileFactory from zds.mp.models import PrivateTopic class MpUtilTest(TestCase): def setUp(self): se...
ofile.save() self.user2 = ProfileFactory().user self.user2.profile.email_for_answer = True self.user2.profile.email_for_new_mp = False self.user2.profile.save() self.user3 = ProfileFactory().use
r self.user3.profile.email_for_answer = True self.user3.profile.email_for_new_mp = True self.user3.profile.save() self.user4 = ProfileFactory().user self.user4.profile.email_for_answer = False self.user4.profile.email_for_new_mp = False self.user4.profile.save() ...
debalance/hp
hp/core/formfields.py
Python
gpl-3.0
5,099
0.003334
# -*- coding: utf-8 -*- # # This file is part of the jabber.at homepage (https://github.com/jabber-at/hp). # # This project 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 (...
) # enrich widgets with label, so we can output it in LinkTargetWidget.render() widgets = [] for fi
eld in fields: w = field.widget w.label = field.label widgets.append(w) self.widget = LinkTargetWidget(widgets=widgets, models=model_choices) super(LinkTargetField, self).__init__(fields=fields, require_all_fields=False,...
dronecrew/px4tools
px4tools/px42csv.py
Python
bsd-3-clause
1,574
0
#!/usr/bin/env python """ Converts px4logs to csv. """ from __future__ import print_function import argparse import os import re import subprocess def run_sdlog_dump(file_path, sdlog2_path="sdlog2_dump.py"): """ Coverts a xp4log to a csv. """ file_out = re.sub('.px4log', '.csv', file_path) cmd =...
raise RuntimeError(err) def main(): """ Entry point for commandline. """ parser = argparse.ArgumentParser(description='C
onvert all px4logs to csv') parser.add_argument('--rm', help='remove px4log files if conversion successful', action='store_true') parser.add_argument('--sdlog2', help='path to sdlog2_dump.py') parser.set_defaults(rm=False, sdlog2='sdlog...
gaberger/pybvc
pybvc/controller/controller.py
Python
bsd-3-clause
69,290
0.000101
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list...
(self, url, data, headers): """Sends HTTP POST request to a remote server and returns the response. :param string url: The complete url including protocol: http://www.example.com/path/to/resource :param string data: The data to include in the body of the request. ...
the request. :return: The response from the http request. :rtype: None or `requests.response` <http://docs.python-requests.org/en/latest/api/#requests.Response> """ resp = None try: resp = requests.post(url, auth=HT...
donnywdavis/Django-faq-views
setup.py
Python
bsd-3-clause
1,185
0.000844
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-faq-views', version='0.1',...
s=['faq'], include_package_data=True, license='BSD License', description='A simple Django app to list frequently asked questions.', long_description=README, #url='http://www.example.com', author='Donny Davis', author_email='donnywdavis@icloud.com', classifiers=[ 'Environment :
: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :...
flyngPig/APM_simulink
ardupilot/Tools/autotest/apmrover2.py
Python
gpl-3.0
5,678
0.004579
# drive APMrover2 in SITL import util, pexpect, sys, time, math, shutil, os from common import * from pymavlink import mavutil import random # get location of scripts testdir=os.path.dirname(os.path.realpath(__file__)) #HOME=mavutil.location(-35.362938,149.165085,584,270) HOME=mavutil.location(40.071374969556928,-1...
if not wait_distance(mav, 50, accuracy=7): return False mavproxy.send('rc 3 1500\n') print("Circuit complete") return T
rue def drive_RTL(mavproxy, mav): '''drive to home''' print("Driving home in RTL") mavproxy.send('switch 3\n') if not wait_location(mav, homeloc, accuracy=22, timeout=90): return False print("RTL Complete") return True def setup_rc(mavproxy): '''setup RC override control''' for...
biztudio/JustPython
syntaxlab/src/test_play_file.py
Python
mit
570
0.003509
# coding: UTF-8 import unittest import play_file class TestAssemblyReader(unittest.TestCase): def test_version_reader(self): assembly_reader = play_file.AssemblyReader() version = assembly_reader.get_assembly_version('AssemblyInfo.cs')
self.assertEqual(version, '7.3.1.0210') def test_version_writer(self): new_version = '7.3.1.0228' assembly_writer = play_file.AssemblyWriter() version = assembly_writer.update_assembly_version('AssemblyInf
o.cs', new_version) self.assertEqual(version, new_version)
azjps/bokeh
examples/models/population_server.py
Python
bsd-3-clause
4,476
0.003128
from __future__ import print_function from math import pi from bokeh.client import push_session from bokeh.document import Document from bokeh.models.glyphs import Line, Quad from bokeh.models import ( Plot, ColumnDataSource, DataRange1d, FactorRange, LinearAxis, CategoricalAxis, Grid, Legend, SingleInter...
label_orientation=pi / 4), 'below') line_known = Line(x="x", y="y", line_color="violet", line_width=2) line_known_glyph = plot.add_glyph(source_known, line_known) line_p
redicted = Line(x="x", y="y", line_color="violet", line_width=2, line_dash="dashed") line_predicted_glyph = plot.add_glyph(source_predicted, line_predicted) plot.add_layout( Legend( location="bottom_right", items=[("known", [line_known_glyph]), ("predicted", [line_predicted_glyp...
pwillworth/galaxyharvester
html/getComponentList.py
Python
gpl-3.0
2,331
0.010296
#!/usr/bin/env python3 """ Copyright 2020 Paul Willworth <ioscode@gmail.com> This file is part of Galaxy Harvester. Galaxy Harvester is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 ...
chemComponent{1}' class='inventoryItem inlineBlock' style='background-image:url(/images/schematics/{2});background-size:64px 64px;' tag='{0}'>".format(row[0], row[2], imageName)) print("<div style='position: absolute;bottom:0;width:100%'>{0
}</div>".format(row[1])) print("</div>") else: print('<option value="'+str(row[0])+'" title="'+row[2]+'">'+row[1]+'</option>') row = cursor.fetchone() cursor.close() conn.close()
Rashitko/up
up/base_module.py
Python
mit
1,652
0
from abc import ABCMeta from up.utils.up_logger import UpLogger class BaseModule(metaclass=ABCMeta): LOAD_ORDER = 0 def __init__(self, silent=False): self.__silent = silent self.__logger = UpLogger.get_logger() self.__up = None def initialize(self, up): self.__up = up ...
cal(self, message): if not self.__silent: self.logger.critical(message) def load(self): return False def is_a(self, module_name): return self.__class__.__name__ == module_name @property def logger(self): return self.__logger @property def class_nam...
turn self.__up @property def telemetry_content(self): return None @classmethod def instance(cls, up): up.get_module(cls)
vikingco/django-kong-admin
kong_admin/receivers.py
Python
bsd-3-clause
3,040
0.002632
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from contextlib import closing from django.db.models.signals import pre_save, pre_delete from django.dispatch.dispatcher import receiver from .models import APIReference, ConsumerReference, BasicAuthReference, KeyAuthReference, OAuth2Refe...
sumer """ instance.synchronized = False ConsumerReference.objects.filter(id=instance.consumer.id, synchronized=True).update(synchronized=False) @receiver(pre_save, sender=PluginConfigurationReference) def before_saving_plugin_configuration(sender, instance, **kwargs):
instance.synchronized = False APIReference.objects.filter(id=instance.api.id, synchronized=True).update(synchronized=False) @receiver(pre_delete, sender=PluginConfigurationReference) def before_delete_plugin_configuration(sender, instance, **kwargs): with closing(get_kong_client()) as client: get_...
weidenba/recovery_sort
filter_system/base.py
Python
gpl-3.0
1,565
0.001278
import os from common_helper_files import get_dir_of_file from pluginbase import PluginBase import logging class FilterSystem(): FILTER_TYPE = None def __init__(self, selected_filters): self._init_plugins() if selected_filters == 'all': self._set_all_filters() else: ...
def _set_all_filters(self): self.filters_to_apply = list(self.filter_plugins.keys()) def _setup_counters(self): self.counter = dict() for item in self.filters_to_apply: self.counter[item] = 0 def _set_filters_to_apply(self, filter_list): self.filters_to_apply ...
logging.error('Filter "{}" is not available!'.format(item))
w1ll1am23/home-assistant
homeassistant/components/sharkiq/vacuum.py
Python
apache-2.0
8,401
0.000595
"""Shark IQ Wrapper.""" from __future__ import annotations import logging from typing import Iterable from sharkiqpy import OperatingModes, PowerModes, Properties, SharkIqVacuum from homeassistant.components.vacuum import ( STATE_CLEANING, STATE_DOCKED, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, ...
return self.sharkiq.get_property_value(Properties.RECHARGE_RESUME) @property
def rssi(self) -> int | None: """Get the WiFi RSSI.""" return self.sharkiq.get_property_value(Properties.RSSI) @property def low_light(self): """Let us know if the robot is operating in low-light mode.""" return self.sharkiq.get_property_value(Properties.LOW_LIGHT_MISSION) ...
SalvusHub/salvus
src/py/pysalvus/code_generation/code_generator.py
Python
mit
7,868
0.005974
import os import io import sympy as sym import re from sympy.physics.quantum import TensorProduct from sympy.utilities.codegen import codegen from quadrature_points_weights import \ gauss_lobatto_legendre_quadruature_points_weights def generating_polynomial_lagrange(N, coordinate, gll_points): """Symbolical...
| v(n+1)|_______________| v(2*(n+1)-1) v0, v1, ..., vn (edge_0) (j) ^ | |_ _ _ > (i) :param N: Order of Lagrange basis. """ # Dofs per component. numPerVertex = 1 numPerEdge = N - 1 numPer...
1)+N)] edge_0 = range(1, N) edge_1 = range(2*(N+1)-1, (N+1)*(N+1)-1, N+1) edge_2 = range((N+1)*(N+1)-2, N*(N+1), -1) edge_3 = range((N-1)*(N+1), 0, -1*(N+1)) return face + edge_0 + edge_1 + edge_2 + edge_3 + vertices def fixHeader(order,element,location): """ fix headers (#include "order4_...
aelguindy/djenerator
djenerator/fields_generator.py
Python
mit
5,111
0
#!/usr/bin/env python """ This module has a function that matches django fields to the corresponding random value generator. """ from django.db.models.fields import BigIntegerField from django.db.models.fields import BinaryField from django.db.models.fields import BooleanField from django.db.models.fields import CharFi...
generate_comma_separated_int from values_generator import generate_date_time from values_generator import generate_decimal from values_generator import generate_email from values_generator import generate_file_path from values_generator import generate_float from values_generator import generate_int from values
_generator import generate_ip from values_generator import generate_positive_integer from values_generator import generate_small_integer from values_generator import generate_string from values_generator import generate_text from values_generator import generate_url from values_generator import generate_uuid def gene...
pyspace/test
pySPACE/missions/nodes/meta/flow_node.py
Python
gpl-3.0
19,395
0.007786
""" Encapsulate complete :mod:`~pySPACE.environments.chains.node_chain` into a single node """ import operator import cPickle import copy import logging import warnings import itertools import pySPACE.missions.nodes from pySPACE.missions.nodes.base_node import BaseNode from pySPACE.missions.nodes.source.external_gene...
oving_window_length : 1 change_parameters : - node : ChannelNameSelector parameters : inverse : False
selected_channels: ["EMG1","EMG2"] :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de) """ def __init__(self, nodes=None, load_path=None, trainable=False, supervised=False, input_dim=None, output_dim=None, dtype=None, ...
4ndreas/ROSCoffeButler
build/roboarm_config/catkin_generated/pkg.develspace.context.pc.py
Python
mit
374
0
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX
= "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "roboarm_config" PROJECT_SPACE_DIR = "/home/fabi/catkin_ws/devel" PROJECT_VERSION =
"0.2.0"
acsone/acsone-addons
hr_utilization/wizard/__init__.py
Python
agpl-3.0
1,429
0
# -*- coding: utf-8 -*- ############################################################################## # # Authors: Stéphane Bidoul & Olivier Laurent # Copyright (c) 2012 Acsone SA/NV (http://www.acsone.eu) # All Rights Reserved # # WARNING: This program as such is intended to be used by professional # programmers who ...
ready-to-use solution with commercial # guarantees and support are strongly advised to contact a Free Software # Service Company. # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU Gen
eral Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR...
simphony/tornado-webapi
doc/source/conf.py
Python
bsd-3-clause
12,106
0.000165
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Simphony-remote documentation build configuration file, created by # sphinx-quickstart on Tue Jun 7 14:01:45 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in t...
tem message" paragraphs in the built documents. keep_warnings = True # If true, `todo`
and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are them...
karllessard/tensorflow
tensorflow/python/data/experimental/ops/parsing_ops.py
Python
apache-2.0
7,348
0.003266
# Copyright 2018 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...
elif deterministic: self._deterministic = "true" else: self._deterministic = "false" # pylint: disable=protected-access self._features = parsing_ops._prepend_none_dimensi
on(features) # TODO(b/112859642): Pass sparse_index and sparse_values for SparseFeature params = parsing_ops._ParseOpParams.from_features(self._features, [ parsing_ops.VarLenFeature, parsing_ops.SparseFeature, parsing_ops.FixedLenFeature, parsing_ops.FixedLenSequenceFeature, parsing_ops....
martinrusev/amonone
amon/apps/devices/models.py
Python
mit
4,472
0.006932
from amon.apps.core.basemodel import BaseModel class BaseDeviceModel(BaseModel): def __init__(self): super(BaseDeviceModel, self).__init__() self.collection = self.mongo.get_collection(self.collection_name) # Pylint displays errors for undefined self, it actually works fine def get_by_name(...
n(server_id=server_id) if devices: for device in devices: params = {'device_id':device['_id'], 't': timestamp} result_dict[device.get('name')] = data_collection.find_one(params) return result_dict def save_data(self, server=None, data=None, time=None,...
t if type(data) == list: formated_data = {} for d in data: name = d.get('name') valid_devices.append(name) formated_data[name] = d # Legacy agent else: formated_data = data try: devic...
sparkslabs/kamaelia
Sketches/MH/KPI.py
Python
apache-2.0
3,026
0.015863
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License...
apache.org/lic
enses/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 und...
harisbal/pandas
pandas/tests/tseries/offsets/test_offsets_properties.py
Python
bsd-3-clause
3,969
0
# -*- coding: utf-8 -*- """ Behavioral based tests for offsets and date_range. This file is adapted from https://github.com/pandas-dev/pandas/pull/18761 - which was more ambitious but less idiomatic in its use of Hypothesis. You may wish to consult the previous version for inspiration on further tests, or when trying...
om data with warnings.catch_warnings(): warnings.simplefilter('ignore') min_dt = pd.Timestamp(1900, 1, 1).to_pydatetime(), max_dt = pd.Timestamp(1900, 1, 1).to_pydatetime(), gen_date_range = st.builds( pd.date_range,
start=st.datetimes( # TODO: Choose the min/max values more systematically min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), max_value=pd.Timestamp(2100, 1, 1).to_pydatetime() ), periods=st.integers(min_value=2, max_value=100), freq=st.sampled_from('Y Q M D H T s ms us ns'.split...
unreal666/outwiker
src/outwiker/actions/new.py
Python
gpl-3.0
566
0
# -*- coding:
utf-8 -*- from outwiker.gui.baseaction import BaseAction from outwiker.core.commands import createNewW
iki class NewAction (BaseAction): """ Создание нового дерева заметок """ stringId = u"NewTree" def __init__(self, application): self._application = application @property def title(self): return _(u"New…") @property def description(self): return _(u"Create...
dcos/dcos
packages/dcos-integration-test/extra/test_ucr.py
Python
apache-2.0
17,516
0.001484
import uuid import pytest from dcos_test_utils.dcos_api import DcosApiSession __maintainer__ = 'Gilbert88' __contact__ = 'core-team@mesosphere.io' def test_if_ucr_app_can_be_deployed_with_image_whiteout(dcos_api_session: DcosApiSession) -> None: """Marathon app deployment integration test using the Mesos Contai...
e': 'host'}] } with dcos_api_session.marathon.deploy_pod_and_cleanup(pod_definition): # Trivial app if it deploys, there is nothing else to check pass def test_if_ucr_pods_can_be_deployed_with_scratch_image(dcos_api_session: DcosApiSession) -> None: """Marathon pods inside ucr deployment i...
tch image means an image that only contains a single binary and its dependencies. """ test_uuid = uuid.uuid4().hex pod_definition = { 'id': '/integration-test-pods-{}'.format(test_uuid), 'scaling': {'kind': 'fixed', 'instances': 1}, 'environment': {'PING': 'PONG'}, 'conta...
Pixdigit/Saufbot
helper.py
Python
mit
5,080
0.007882
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json import pendulum import config import busses def get_message_type(msg): if msg.text is not None: return "text" elif msg.audio is not None: return "audio" elif msg.document is not None: return "document" e...
return (msg.from_user.id == busses.conversation_bus[msg.chat.id]["user"] and busses.conversation_bus[msg.chat.id]["state"] == state) def set_conversation_status(msg, state): busses.conversation_bus[msg.chat.id]["state"] = state def get_current_station_name(): return config.st
ations[busses.status_bus["station"]] def shutdown(): data = {} data["station"] = busses.status_bus["station"] data["line"] = busses.status_bus["line"] data["admin_ids"] = config.admin_ids data["language"] = config.lang data["set_at_time"] = busses.status_bus["set_at_time"] data["arrive_dela...
wizzat/wizzat.py
wizzat/s3table.py
Python
mit
2,568
0.010903
from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import boto.exception import io import json import wizzat.kvtable from boto.s3.key import Key, compute_md5 __all__ = [ 'S3Table', ] class S3Table(wizzat.kvtable.KVTable): """ This is a micro-ORM fo...
encrypt_key = False reduced_redundancy = False json_encoder = staticmethod(json.dumps) json_decoder = staticmethod(json.loads) @classmethod def _remote_bucket(cls): return cls.conn.get_bucket(cls.bucket) @classmethod def dele
te_key(cls, kv_key): cls._remote_bucket().delete_key(kv_key) @classmethod def _remote_key(cls, kv_key): return Key(cls._remote_bucket(), kv_key) @classmethod def _find_by_key(cls, kv_key): try: content_str = cls._remote_key(kv_key).get_contents_as_string() ...
PowerKiKi/mqueue
library/searchengine/nova/engines/torlock.py
Python
mit
4,152
0.002168
#VERSION: 2.1 # AUTHORS: Douman (custparasite@gmx.se) # CONTRIBUTORS: Diego de las Heras (ngosang@hotmail.es) from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from re import compile as re_compile from HTMLParser import HTMLParser class torlock(object): url = "https://www.torl...
elf.item_found: if tag == "td": if "class" in params: self.item_name = self.parser_class.get(params["class"], None) if self.item_name: self.current_item[self.item_name] = "" elif self.article_fou
nd and tag == "a": if "href" in params: link = params["href"] if link.startswith("/torrent"): self.current_item["desc_link"] = "".join((self.url, link)) self.current_item["link"] = "".join((self.url, "/tor/", ...
tritemio/FRETBursts
fretbursts/burst_plot.py
Python
gpl-2.0
96,452
0.000881
# encoding: utf-8 # # FRETBursts - A single-molecule FRET burst analysis toolkit. # # Copyright (C) 2013-2016 The Regents of the University of California, # Antonino Ingargiola <tritemio@gmail.com> # """ This module defines all the plotting functions for the :class:`fretbursts.burstlib.Data` object. The ...
0], period, color=red, **span_style_) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False) def p
lot_alternation_hist_nsalex(d, bins=None, ax=None, ich=0, hist_style={}, span_style={}): """Plot the ns-ALEX alternation histogram for the variable `d`. This function must be called on ns-ALEX data **before** calling :func:`fretbursts.loader.alex_apply_period`. """ ...
AlgorithmLover/OJCodes
qlcoder/data_mining/transform_matrix/population_statistics.py
Python
mit
1,029
0.003887
import numpy as np if __name__ == '__main__': pop_vec = [16389723, 10262186, 20593430, 71685839, 49425543, 88979305, 8060519, 68538709, 33484131, 23071690, 41755874, 26457769, 36884039, 56493891, 33397
663, 42181417, 89855501, 90028072, 52745625, 61911446, 43970320, 26994017, 76207174, 33571308, 43626674, 34462115, 24052594, 2837769, 5284525, 5970133, 20802249] transition_matrix = [[0] * 31] * 31 training_arr = np.loadtxt('population_migration.csv', str, '#', ',') for ele i...
(lambda x, y: x + y, transition_matrix[row_idx], 0.0) transition_matrix[row_idx] = map(lambda x: x / inter_res, transition_matrix[row_idx]) print len(transition_matrix) res = pop_vec for i in xrange(5): res = np.dot(res, transition_matrix) print ','.join(map(str, res))
ithinksw/philo
philo/contrib/waldo/tokens.py
Python
isc
3,279
0.031107
""" Based on :mod:`django.contrib.auth.tokens`. Supports the following settings: :setting:`WALDO_REGISTRATION_TIMEOUT_DAYS` The number of days a registration link will be valid before expiring. Default: 1. :setting:`WALDO_EMAIL_TIMEOUT_DAYS` The number of days an email change link will be valid before expiring. Def...
token_
with_timestamp(user, email, ts) != token: return False # Check that the timestamp is within limit if (self._num_days(self._today()) - ts) > EMAIL_TIMEOUT_DAYS: return False return True def _make_token_with_timestamp(self, user, email, timestamp): ts_b36 = int_to_base36(timestamp) hash = sha1...
open-aerospace/openrocketdoc
tests/test_document.py
Python
gpl-3.0
10,628
0.000094
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_document ---------------------------------- Tests for `document` module. """ import unittest from openrocketdoc import document class TestOpenrocketdoc(unittest.TestCase): def setUp(self): pass def test_spec_a_rocket(self): rocket = d...
: tube.color = (240, 12, 0) self.assertEqual(tube.color, (240, 12, 0)) def test_engine_length(self): engine = document.Engine("test") # length not set self.assertEqual(engine.length, 0) # set directly engine.length = 25.4 self.assertEqual(engine.len...
burn(self): engine = document.Engine("test Name") engine.t_burn = 123.456 self.assertAlmostEqual(engine.t_burn, 123.456) def test_engine_ve(self): engine = document.Engine("test Name") engine.Isp = 123 self.assertAlmostEqual(engine.V_e, 1206.21795) def test_engi...
digital-cube/BASE
base/src/base/lookup/scope_permissions.py
Python
gpl-3.0
79
0
"""
Define scope permissions """ READ
= 2**0 WRITE = 2**1 ALL = READ | WRITE
SEL-Columbia/commcare-hq
corehq/apps/sms/backend/http_api.py
Python
bsd-3-clause
4,882
0.004916
import re from urllib import urlencode from urllib2 import urlopen from corehq.apps.sms.mixin import SMSBackend from corehq.apps.sms.forms import BackendForm from corehq.apps.reminders.forms import RecordListField from django.forms.fields import * from django.core.exceptions import ValidationError from couchdbkit.ext.d...
efaults to False) method = StringProperty(choices=["GET","POST"], default="GET") # "GET" or "POST" (optional, defaults to "GET") additional_params = DictProperty() # a dictionary of additional parameters that will be sent in the request (optional) @classmethod def get_api_id(cls): return "HTTP"...
def get_template(cls): return "sms/http_backend.html" @classmethod def get_form_class(cls): return HttpBackendForm def send(self, msg, *args, **kwargs): if self.additional_params is not None: params = self.additional_params.copy() else: params = {} ...
jicruz/heroku-bot
lib/youtube_dl/extractor/dailymotion.py
Python
gpl-3.0
18,184
0.002035
# coding: utf-8 from __future__ import unicode_literals import re import json import itertools from .common import InfoExtractor from ..utils import ( determine_ext, error_to_compat_str, ExtractorError, int_or_none, parse_iso8601, sanitized_Request, str_to_int, unescapeHTML, mimet...
unt"[^>]+content="UserPlays:([\s\d,.]+)"', r'video_views_count[^>]+>\s+([\s\d\,.]+)'), webpage, 'view count', default=None) if view_count_str: view_count_str = re.sub(r'\s', '', view_count_str) view_count = str_to_int(view_count_str) comment_count = int_or_no...
webpage, 'comment count', default=None)) player_v5 = self._search_regex( [r'buildPlayer\(({.+?})\);\n', # See https://github.com/rg3/youtube-dl/issues/7826 r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);', r'buildPlayer\(({.+?})\);', r'var\s+config\s*=\s*...
samwisehawkins/wrftools
util/timing.py
Python
mit
1,586
0.018916
"""timing.py computes timing information from a rsl output file from WRF Usage: python timing.py rsl_file [namelist.input]""" import sys, os # this is an ugly hack to do a relative import, but it works sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'wrftools')) import namelist as
nl import re def main(): """Reads a rsl file from WRF and works out timing information from that """ args = sys.argv[1:] print('*** Computing timing information ***') rsl_file = args[0] if len(args)>1: namelist = nl.read_namelist(args[1]) timestep = namelist.settings...
et timings on outer domain main_times = [float(l.split()[8]) for l in lines if re.search("^Timing for main: time .* 1:", l)] total = sum(main_times) steps = len(main_times) time_per_step = (total/steps) x_real = timestep / time_per_step if timestep else None m, s = divmod...
z-plot/z-plot
examples/basics/horizontalintervals.py
Python
bsd-3-clause
492
0.018293
#! /usr/bin/env python from zplot import * t = table('horizontalintervals.data') canvas = postscript('horizontalintervals.eps') d = drawable
(canvas, coord=[50,30], xrange=[0,900], yrange=[0,t.getmax('nodes')]) axis(d, xtitle='Throughput (MB)', xauto=[0,900,300], ytitle='Nodes', yauto=[0,t.getmax('nodes'),1]) # ylofield and
yhifield specify the interval range p = plotter() p.horizontalintervals(d, t, yfield='nodes', xlofield='min', xhifield='max') canvas.render()
boggard/jira-telegram-bot
utils/date_util.py
Python
mit
333
0
from
datetime import datetime JIRA_FORMAT = "%Y/%m/%d %H:%M" DB_FORMAT = "%d/%m/%Y %H:%M:%S" def format_jira_date(date: str): return datetime.strptime(date[0:19], "%Y-%m-%dT%H:%M:%S") def to_jira_format(date: datetime): return date.strftime(JIRA_FORMAT) def to_str(date: datetime): return
date.strftime(DB_FORMAT)
IQSS/gentb-site
tb_website/urls.py
Python
agpl-3.0
2,636
0.003035
# # Copyright (C) 2017 Maha Farhat # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distribu...
x.html', Tv.as_view(template_name='home.html'), name="home"), path('about/', Tv.as_view(template_name='about.html'), name="about"), path('data/', Tv.as_view(template_name='data.html'), name="data"), path('data/info/', Tv.as_view(template_name='info.html'), name="info"), path('terms/', Tv.as_view(templa...
, include('apps.tb_users.urls')), url(r'^auth/', include('apps.tb_users.auth_urls')), #url(r'.+', Tv.as_view(template_name='offline.html'), name="offline"), url(r'^predict/', include('apps.predict.urls', namespace='predict')), url(r'^pipeline/', include('apps.pipeline.urls')), url(r'^uploads/', in...
bobjects/BobStack
bobstack/sipmessaging/concreteheaderfields/eventSIPHeaderField.py
Python
apache-2.0
3,899
0.000256
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from ...sipmessaging import SIPHeaderField from ...sipmessaging import classproperty class EventSIPHeaderField(SIPHeaderField): # noinspection PyNestedDecorators @classproperty @classmethod def canonical_fiel...
n self.parameter_named('include-session-description') @include_sessio
n_description.setter def include_session_description(self, a_string): self.parameter_named_put('include-session-description', a_string) @property def max_rate(self): return self.parameter_named('max-rate') @max_rate.setter def max_rate(self, a_string): self.parameter_named_...
jfalkner/report_data
report_data/conf.py
Python
mit
67
0.014925
DATA_DI
R='/tmp/report_data' # Make directory, if it doesn't exist.
JaneliaSciComp/Neuroptikon
Source/lib/CrossPlatform/networkx/convert.py
Python
bsd-3-clause
19,645
0.013031
""" ------- Convert ------- This module provides functions to convert NetworkX graphs to and from other formats. The preferred way of converting data to a NetworkX graph is through the graph constuctor. The constructor calls the from_whatever() function which attempts to guess the input type and convert it automat...
thor__ = """Aric Hagberg (hagberg@lanl.gov)""" # Copyright (C) 2006-2008 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. __all__ = ['from_whatever', 'from_dict_of_dicts', 'to_dict_of_dicts', ...
_edgelist', 'from_numpy_matrix', 'to_numpy_matrix', 'from_scipy_sparse_matrix', 'to_scipy_sparse_matrix'] import networkx import warnings def _prep_create_using(create_using): """Return a graph object ready to be populated. If create_using is None return the default (just networkx.Graph...
lmazuel/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/Validation/auto_rest_validation_test/auto_rest_validation_test.py
Python
mit
12,493
0.001521
# 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 ...
ters used to create this instance are saved as instance attributes. :param subscription_id: Subscription ID. :type subscription_id: str :param str base_url: Service URL """ def __init__( self, subscription_id, base_url=None): if subscription_id is None: raise V...
None.") if not isinstance(subscription_id, str): raise TypeError("Parameter 'subscription_id' must be str.") if not base_url: base_url = 'http://localhost' super(AutoRestValidationTestConfiguration, self).__init__(base_url) self.add_user_agent('autorestvalidati...
simonmikkelsen/roughcut
lib/optparser.py
Python
gpl-2.0
760
0.019737
class OptParser: """Parses the options in the given file and allowed for the content to be returned. The file is expected to contain key/value pairs. Empty lines,
and lines where first non white space is a # are ignored. """ def __init__(self, filename): self.filename = filename def parse(self): myvars = {} with open(self.filename) as myfile: for line in myfile: if line.strip().startswith('#') or len(line.strip()) == 0: continue ...
self.content = myvars def getContent(self): return self.content if __name__ == '__main__': import sys parser = OptParser(sys.argv[1]) parser.parse() print parser.getContent()