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
lypzln/seaborn
examples/facets_with_custom_projection.py
Python
bsd-3-clause
767
0
""" FacetGrid with custom projection ================================ _thumb: .33, .5 """ import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns sns.set() # Ge
nerate an example radial datast r = np.linspace(0, 10, num=100) df = pd.DataFrame({'r': r, 'slow': r, 'medium': 2 * r, 'fast': 4 * r}) # Convert the dataframe to long-form or "tidy" format df = pd.melt(df, id_vars=['r'], var_name='speed', value_name='theta') # Set up a grid of axes with a polar projection g = sns.Fac...
="speed", subplot_kws=dict(projection='polar'), size=4.5, sharex=False, sharey=False, despine=False) # Draw a scatterplot onto each axes in the grid g.map(plt.scatter, "theta", "r")
NoneGG/aredis
aredis/commands/geo.py
Python
mit
7,328
0.001092
from aredis.exceptions import RedisError from aredis.utils import b, nativestr def parse_georadius_generic(response, **options): if options['store'] or options['store_dist']: # `store` and `store_diff` cant be combined # with other command arguments. return response if type(response) ...
invalid unit") elif kwargs['unit']: pieces.append(kwargs['unit']) else: pieces.app
end('m', ) for token in ('withdist', 'withcoord', 'withhash'): if kwargs[token]: pieces.append(b(token.upper())) if kwargs['count']: pieces.extend([b('COUNT'), kwargs['count']]) if kwargs['sort'] and kwargs['sort'] not in ('ASC', 'DESC'): ra...
julianwang/cinder
cinder/db/sqlalchemy/migrate_repo/versions/038_add_driver_initiator_data_table.py
Python
apache-2.0
2,020
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
) try: initiator_data.create() except Exception: LOG.error(_LE("
Table |%s| not created!"), repr(initiator_data)) raise def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine table_name = 'driver_initiator_data' initiator_data = Table(table_name, meta, autoload=True) try: initiator_data.drop() except Exception: L...
daviderill/expedients
src/exp_om_dialog.py
Python
gpl-3.0
661
0.009077
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui from ui_exp_om import Ui_Dialog class ExpOmDialog(QtGui.QDialo
g): def __init__(self): QtGui.QDialog.__init__(self) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-u...
) # Set up the user interface from Designer. self.ui = Ui_Dialog() self.ui.setupUi(self)
MyRobotLab/pyrobotlab
home/Humanoid/ghost.py
Python
apache-2.0
934
0.002141
################################################### # This is a basic script to carry on a conversation # with ghost ################################################### # create service ghost = Runtime.start("ghost", "WebGui") ear = Runtime.start("ear", "WebkitSpeechRecognition") ghostchat = Runtime.start("ghostchat"...
tmlfilter", "HtmlFilter") mouth = Runtime.start("mouth", "NaturalReaderSpeech") # creating the connections and routes # - I'll need to check on these - might # need to just "attach" some services together ear.addTextListener(ghostchat) ghostchat.addTextListener(htmlfil
ter) htmlfilter.addTextListener(mouth) # start a chatbot session ghostchat.startSession("ProgramAB/bots", "ghostchat") voices = mouth.getVoices() # I've also tried removing this because I got an iteration error for this line # for voice in voices: # NaturalReaderSpeech.setVoice("Ryan")
nlehuby/osm2gtfs
osm2gtfs/tests/creators/tests_br_florianopolis.py
Python
gpl-3.0
2,872
0.002089
import unittest import os import logging import overpy from mock import patch from osm2gtfs.tests.creators.creators_tests import CreatorsTestsAbstract from osm2gtfs.core.osm_connector import OsmConnector from osm2gtfs.core.cache import Cache # Define logging level logging.basicConfig(level
=os.environ.get("LOGLEVEL", "INFO")) class TestCreatorsBrFlorianopolis(CreatorsTestsAbstract): def _get_selector(self): return "br_florianopolis" def _get_required_variables(self): # Define required values for the tests of this provider return { 'routes_count': 73, ...
3, 'route_id_to_check': 20, 'gtfs_files': [ "agency.txt", "calendar.txt", "routes.txt", "shapes.txt", "stops.txt", "stop_times.txt", "trips.txt" ], } def _override_configuration(self): # Overriding some of the configuration options...
aptivate/ivr-twilio-demo
twilio_app/urls.py
Python
gpl-2.0
972
0.001029
from django.conf.urls import patterns, url from .views import ( say_words, ga
ther, process_demo, LoopWithGather, ) from .branching_demo import ( gather_branch, gather_branch_a, gather_branch_b, process_branch, process_branch_a, process_branch_b, ) urlpatterns = patterns('', url(r'^$', say_words, name='home'), url(r'^gather$', gather, nam
e='gather'), url(r'^process_demo$', process_demo, name='process_demo'), url(r'^loop_gather$', LoopWithGather.as_view(), name='loop_gather'), url(r'^gather_branch$', gather_branch, name='gather_branch'), url(r'^gather_branch_a$', gather_branch_a, name='gather_branch_a'), url(r'^gather_branch_b$', ga...
ntijanic/pdl
pypdl/wrapper/schema/io_list.py
Python
agpl-3.0
1,376
0.001453
from pypdl.wrapper.schema.io_value import IOValue from pypdl.util import DotAccessDict, intersect_dicts class IOList(object): def __init__(self, value=None): value = value or [] if isinstance(value, basestring): value = [value] self._values = [IOValue(v) for v in value or []] ...
v.meta for v in self._values]), **kwargs) def _save_meta(self): for val in self: val._save_meta() def _load_me
ta(self): for val in self: val._load_meta()
keybar/keybar
src/keybar/api/endpoints/registration.py
Python
bsd-3-clause
351
0
from rest_framework.
generics import CreateAPIView from rest_framework.permissions import AllowAny from keybar.api.serializers.registration import RegisterSerializer class RegisterView(CreateAPIView): serializer_class = RegisterSerializer permission_classes = (AllowAny,)
def perform_create(self, serializer): serializer.save()
sapcc/monasca-api
monasca_api/common/messaging/kafka_publisher.py
Python
apache-2.0
2,843
0.002462
# Copyright 2014,2017 Hewlett-Packard # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
self.partitions = cfg.CONF.kafka.partitions self.drop_data = cfg.CONF.kafka.drop_data self.statsd_kafka_producer_error_count = STATSD_CLIENT.get_counter(KAFKA_PRODUCER_ERRORS, dimensions={'topic': self.topic}) self._p...
= kafka_producer.KafkaProducer(self.uri) def close(self): pass def send_message(self, message): try: self._producer.publish(self.topic, message) except (kafka_common.KafkaUnavailableError, kafka_common.LeaderNotAvailableError): LOG.exception('Er...
brandnetworks/base-flask-api
api/health/controller.py
Python
apache-2.0
229
0
from flask import Blueprint, jsonify from .model import Health blueprint = Blueprint('health', __name__) @blueprint.route('/', methods=['GET']) def
__get_health__(): health = Health() retu
rn jsonify(health.get_data())
ec429/quIRC
gen_numerics_text.py
Python
gpl-3.0
610
0.016393
#!/usr/bin/python # gen_numerics_text.py: generate numeric_text.c import numerics print """/* quIRC - simple terminal-based IRC client Copyright (C) 2010-13 Edward Cree See quirc.c for license information numeric_text: names of IRC numeric replies */ /*** This file is generated by gen_numerics_text.py from mas...
it the masters instead. ***/ #include <stdlib.h> // for NULL const char *numeric_names[1000]={""
" for i in xrange(1000): if i in numerics.nums: print '"'+numerics.nums[i].getname()+'",' else: print 'NULL,' print '};'
zillow/ctds
tests/test_tds_parameter.py
Python
mit
7,779
0.0009
import re import warnings import ctds from .base import TestExternalDatabase from .compat import PY3, PY36, unicode_ class TestTdsParameter(TestExternalDatabase): def test___doc__(self): self.assertEqual( ctds.Parameter.__doc__, '''\ Parameter(value, output=False) Explicitly de...
) ): self.assertEqual(repr(parameter), expected) def _test__cmp__(self, __cmp__, expected, oper): cases = ( (ctds.Parameter(b'1234'), ctds.Parameter(b'123')), (ctds.Parameter(b'12
3'), ctds.Parameter(b'123')), (ctds.Parameter(b'123'), ctds.Parameter(b'123', output=True)), (ctds.Parameter(b'123'), ctds.Parameter(b'1234')), (ctds.Parameter(b'123'), b'123'), (ctds.Parameter(b'123'), ctds.Parameter(123)), (ctds.Parameter(b'123'), unicode_('...
project-owner/Peppy
ui/screen/info.py
Python
gpl-3.0
9,237
0.003356
# Copyright 2020-2021 Peppy Player peppy.player@gmail.com # # This file is part of Peppy Player. # # Peppy Player is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at you...
lf.bg[5] self.screen_w = self.config[SCREEN_INFO][WIDTH] self.screen_h = self.config[SCREEN_INFO][HEIGHT] self.lines = 14 font_vertical_percent = 6 self.bounding_box = util.screen_rect Container.__init__(self, util, self.bounding_box, background=self.bg[1], content=self....
box.h)/100) self.f = util.get_font(font_size) center_layout = BorderLayout(self.bounding_box) center_layout.set_percent_constraints(0, 0, 44, 0) left_layout = center_layout.LEFT right_layout = center_layout.CENTER label_layout = GridLayout(left_layout) ...
edisonlz/fruit
web_project/base/site-packages/django/contrib/comments/admin.py
Python
apache-2.0
3,736
0.003747
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext_lazy from django.contrib.comments import get_model from django.contrib.comments.v...
r',) search_fields = ('comment', UsernameSearch(
), 'user_name', 'user_email', 'user_url', 'ip_address') actions = ["flag_comments", "approve_comments", "remove_comments"] def get_actions(self, request): actions = super(CommentsAdmin, self).get_actions(request) # Only superusers should be able to delete the comments from the DB. if no...
obi-two/Rebelion
data/scripts/templates/object/intangible/ship/shared_ywing_pcd.py
Python
mit
443
0.047404
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROP
ERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result =
Intangible() result.template = "object/intangible/ship/shared_ywing_pcd.iff" result.attribute_template_id = 8 result.stfName("space_item_n","ywing_pcd") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
Tinkerforge/brickv
src/brickv/plugin_system/plugins/multi_touch/__init__.py
Python
gpl-2.0
922
0
# -*- coding: utf-8 -*- """ Multi Touch Plugin Copyright (C) 2013 Olaf Lüke <olaf@tinkerforge.com> __init__.py: package initialization 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 ...
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a cop
y of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from brickv.plugin_system.plugins.multi_touch.multi_touch import MultiTouch device_class = MultiTouch
batxes/4Cin
SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/SHH_WT_models47488.py
Python
gpl-3.0
17,589
0.025072
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_set...
7, 6558.27), (0.7, 0.7, 0.7), 856.786) if "particle_3 geometry" not in marker_sets: s=new_marker_set('particle_3 geometr
y') marker_sets["particle_3 geometry"]=s s= marker_sets["particle_3 geometry"] mark=s.place_marker((-1105.23, 6466.69, 7375.34), (0.7, 0.7, 0.7), 963.679) if "particle_4 geometry" not in marker_sets: s=new_marker_set('particle_4 geometry') marker_sets["particle_4 geometry"]=s s= marker_sets["particle_4 geometry"]...
PaulSchweizer/tinypipeline
tinypipeline/core/paths.py
Python
gpl-3.0
1,191
0
"""Map paths based on patterns defined in the config file.""" import os from functools import partial from tinypipeline.core import config class Paths(object): """Handle paths within the pipeline.""" def __getattr__(self, attr): """Get the path behind the given attr pattern.""" if attr in c...
.format(
**kwargs)) # end def get def __str__(self): """All available patterns.""" return ('Available patterns:\n\t{0}' .format('\n\t'.join(['{0}: {1}'.format(k, v) for k, v in config.patterns.items()]))) # end def __str__ # end class paths Path...
titilambert/home-assistant
homeassistant/components/mqtt/light/schema_basic.py
Python
apache-2.0
32,866
0.001035
"""Support for MQTT lights.""" import logging import voluptuous as vol from homeassistant.components import mqtt from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_WHITE_VALUE, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR...
tion as cv from homeassistant.helper
s.restore_state import RestoreEntity import homeassistant.util.color as color_util from ..debug_info import log_messages from .schema import MQTT_LIGHT_SCHEMA_SCHEMA _LOGGER = logging.getLogger(__name__) CONF_BRIGHTNESS_COMMAND_TOPIC = "brightness_command_topic" CONF_BRIGHTNESS_SCALE = "brightness_scale" CONF_BRIGHT...
frePPLe/frePPLe
freppledb/common/migrations/0026_permissions.py
Python
agpl-3.0
1,300
0
# # Copyright (C) 2021 by frePPLe bv # # This library 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 library is distri...
def remove_permissions(apps, _unused): Permission = apps.get_model("auth.Permission") Permission.objects.filter( codename__in=( "add_follower", "change_follower", "view_follower", "delete_follower", "add_scenario", "c
hange_scenario", "delete_scenario", "view_scenario", ) ).delete() class Migration(migrations.Migration): dependencies = [("common", "0025_user_horizonbefore")] operations = [migrations.RunPython(remove_permissions)]
melodous/designate
designate/tests/test_api/test_v2/extensions/test_quotas.py
Python
apache-2.0
5,778
0.001731
# coding=utf-8 # COPYRIGHT 2014 Rackspace # # Author: Tim Simmons <tim.simmons@rackspace.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.apache.org/licenses/LICENSE-2...
]['zones'] self.assertNotEqual(current_count, new_count) respon
se = self.client.delete('/quotas/%s' % 'a', headers={'X-Test-Tenant-Id': context.tenant}, status=204) response = self.client.get('/quotas/%s' % 'a', headers={'X-Test-Tenant-Id': ...
aazen/DayOne
slybot/slybot/settings.py
Python
bsd-3-clause
425
0.004706
SPIDER_MANAGER_CLASS = 'slybot.spidermanager.SlybotSpiderManager' EXTENSIONS = {'slybot.closespider.SlybotCloseSpider': 1} ITEM_PIPELINES = ['slybot.dupefilter.DupeFilterPipelin
e'] SPIDER_MIDDLEWARES = {'slybot.spiderlets.SpiderletsMiddleware': 999} # as close as possible to spider output SLYDUPEFILTER_ENABL
ED = True PROJECT_DIR = 'slybot-project' try: from local_slybot_settings import * except ImportError: pass
regeciovad/rpg
tests/unit/test_guess.py
Python
gpl-2.0
794
0.001259
from tests.support import RpgTestCase from rpg import Base class GuessTest(RpgTestCase): def setUp(self): self.base = Base() def test_guess_name(self): self.base._input_name = self.test_project_dir self.assertEqual(str(self.base.guess_name()), str(self.test_project_dir)) self...
.base._input_name = "vec.tar.gz" self.assertEqual(str(self.base.guess_name()), "vec") self.base._input_name = "vec.zip.zip" self.assertEqual(str(self.base.guess_name()), "vec.zip") def test_gues
s_name_fail(self): self.base._input_name = self.test_project_dir / "NotADir" self.assertEqual(str(self.base.guess_name()), str(""))
hughsie/fwupd
contrib/generate-version-script.py
Python
lgpl-2.1
4,566
0.001095
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2017 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identi
fier: LGPL-2.1+ import sys import argparse import xml.etree.ElementTree as ET from pkg_resources import parse_version XMLNS = "{http://www.gtk.org/introspection/core/1.0}" XMLNS_C = "{http://www.gtk.org/introspection/c/1.0}" def usage(return_code): """print usage and exit with the supplied return code""" i...
lse: out = sys.stderr out.write("usage: %s <NAME> <INPUT> <OUTPUT>\n" % sys.argv[0]) sys.exit(return_code) class LdVersionScript: """Rasterize some text""" def __init__(self, library_name): self.library_name = library_name self.releases = {} self.overrides = {} de...
cluck/dnspython
tests/test_namedict.py
Python
isc
3,521
0.000568
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "...
[n2] = 2 def testDepth(self): self.failUnless(self.ndict.max_depth == 3) def testLookup1(self): k = dns.name.from_text('foo.bar.')
self.failUnless(self.ndict[k] == 1) def testLookup2(self): k = dns.name.from_text('foo.bar.') self.failUnless(self.ndict.get_deepest_match(k)[1] == 1) def testLookup3(self): k = dns.name.from_text('a.b.c.foo.bar.') self.failUnless(self.ndict.get_deepest_match(k)[1] == 1) ...
Julius2342/pyvlx
pyvlx/log.py
Python
lgpl-3.0
100
0
"""Module for global PyVLX logg
ing object.""" import logging PYVLXLOG = logging.getLogger(
"pyvlx")
sdhawan21/euclidIR
error_kcorrect.py
Python
mit
6,142
0.013188
""" A routine to calculate the dispersions in K-correction; using SN(oo)Py heavily Has several potentially useful functions for convolving the spectrum with a filter transmission curve """ import numpy as np import scipy.interpolate import os import sys try: import pyfits have_FITS=0 #variable naming is kep...
turn (0.0, 0) else: # Finally calculate the cross-band K Correction # Since we blueshift the spectrum (instead of redshift the filter) # the sign of the 2.5 is now positive
kf1f2 = 2.5*np.log10(1+z) + 2.5*np.log10(f1flux_0/f2flux_z) - \ zpt1 + zpt2 return (kf1f2, 1) def main(): inputval=read_input() filtdir = inputval['filtdir'] obs_dir = inputval['obsdir'] filtname = inputval['filtinp'] zval = float(inputval['z']) phasei...
sogapalag/problems
leetcode/135.Candy.py
Python
mit
1,335
0.001498
class Solution(object): def candy_2(self, rati
ngs): """ :type ratings: List[int] :rtype: int """ n = len(ratings) cdy = [1,] * n # climb from left -> right
v, p = 0, 0 while p < n: # local min v = p while v < n-1 and ratings[v] >= ratings[v+1]: v += 1 # local max p = v + 1 while p < n and ratings[p] > ratings[p-1]: cdy[p] = max(cdy[p], 1 + cdy[p-1]) ...
giuseppe/virt-manager
virtcli/cliconfig.py
Python
gpl-2.0
2,910
0
# # Copyright (C) 2013, 2014 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distrib...
th(__file__) _srcdir = os.path.abspath(os.path.join(os.path.dirname(_filepath), "..")) cfgpath = os.path.join(os.path.dirname(_filepath), "cli.cfg") _istest = "VIRTINST_TEST_SUITE" in os.environ if os.path.exists(cfgpath): cfg.read(cfgpath) def _split_list(commastr): return [d for d in commastr.split(",") if ...
turn cfg.get("config", name) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): return default def _setup_gsettings_path(schemadir): """ If running from the virt-manager.git srcdir, compile our gsettings schema and use it directly """ import subprocess os.environ["G...
larsoner/mne-python
mne/io/base.py
Python
bsd-3-clause
103,617
0
# -*- coding: utf-8 -*- # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Matti Hämäläinen <msh@nmr.mgh.harvard.edu> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Denis Engemann <denis.engemann@gmail.com> # Teon Brooks <teon.brooks@gmail.com> # Marijn van Vliet...
Returns ------- index : ndarray Indices corresponding to the times supplied. """ from ..source_estimate import _BaseSourceEstimate if isinstance(self, _BaseSourceEstimate): sfreq = 1. / self.tstep else: sfreq = self.info['sfreq'] ...
f, tmin, tmax): """Convert seconds to index into data. Parameters ---------- tmin : int | float | None Start time of data to get in seconds. tmax : int | float | None End time of data to get in seconds. Returns ------- start : int...
ChromiumWebApps/chromium
tools/telemetry/telemetry/test_runner.py
Python
bsd-3-clause
6,124
0.012737
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Parses the command line, discovers the appropriate tests, and runs them. Handles test configuration, but all the logic for actually running the test ...
, 'Multiple tests named "%s".' % input_test_name print >> sys.stderr print >> sys.stderr, 'Did you mean one of these?' _PrintTestList(matching_tests) sys.exit(1) self._test = matching_tests.popitem()[1] def Run(self, options, args): return min(255, self._test().Run(copy.copy(options)...
nspect.getmembers(sys.modules[__name__]) if inspect.isclass(cls) and cls is not command_line.OptparseCommand and issubclass(cls, command_line.OptparseCommand)] def _GetScriptName(): return os.path.basename(sys.argv[0]) def _GetTests(): base_dir = util.GetBaseDir() tests = d...
makinacorpus/Geotrek
geotrek/common/tests/test_models.py
Python
bsd-2-clause
1,208
0.000828
from geotrek.common.factories import LabelFactory from geotrek.common.models import Theme from django.core.files import File from django.test import TestCase import os class ThemeModelTest(TestCase): def setUp(self): self.directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') ...
h.join(self.directory, 'picto.png') self.assertEqual(os.pa
th.getsize(self.path), 6203) self.theme = Theme.objects.create() with open(self.path, 'rb') as picto_file: self.theme.pictogram = File(picto_file) file = self.theme.pictogram_off path_off = os.path.join(self.directory, 'picto_off.png') self.assertEqual(os....
Nikea/VisTrails
scripts/update_email_contact.py
Python
bsd-3-clause
1,077
0.002786
# Finds all files matching extensions recursively in current directory (.) # and updates tthe contact e-mail address import re import os OLD_EMAIL = "Copyright (C) 2011-2012, NYU-Poly" NEW_EMAIL = "Copyright (C) 2011-2014, NYU-Poly" EXTENSIONS = [".py", ".xml", ".xsd", ".php", ".sql", ".sh", ".rst", ".tex", ...
for ext in EXTENSIONS: if fn.endswith(ext) and fn not in IGNORE_LIST: files.append(os.path.join(path, fn)) break print len(files), " files will be processed." count = 0 for fname in files: fin = open(fname) all_lines = fin.read() fin.close() pos = all_...
newlines = all_lines.replace(OLD_EMAIL, NEW_EMAIL) fout = file(fname, 'w') fout.write(newlines) fout.close() count += 1 print count, " files updated "
okuta/chainer
chainermn/links/multi_node_chain_list.py
Python
mit
10,503
0
from six.moves import queue import chainer import chainermn import chainermn.communicators import chainermn.functions class MultiNodeChainList(chainer.ChainList): """Combining multiple non-connected components of computational graph. This class combines each ``chainer.Chain``, which represents one of the ...
m): chainer.utils.experimental('chainermn.MultiNodeChainList') super(MultiNodeChainL
ist, self).__init__() self._comm = comm self._rank_inouts = [] def add_link(self, link, rank_in=None, rank_out=None): """Register one connected link with its inout rank. Args: link (chainer.Link): The link object to be registered. rank_in (int, list, or None...
abrt/faf
src/pyfaf/actions/pull_reports.py
Python
gpl-3.0
6,719
0.002381
# Copyright (C) 2013 ABRT Team # Copyright (C) 2013 Red Hat, Inc. # # This file is part of faf. # # faf 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) ...
om the server ureport = self._get_report(report) if ureport is None: # Ignore if the report can't be found -- don't add it to the # knonw set. continue # We prefer that the incoming repor...
filename = os.path.join(self.incoming_dir, report) # If a report with the same name already exists directory, keep # generating a name at random until one that is available is found while os.path.isfile(filename): filename = os.pa...
shellydeforte/PDB
pdb/tests/test_pdb_chain_uni.py
Python
mit
3,731
0
# -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals) import os import re import sys import unittest from contextlib import contextmanager from io import open from shutil import rmtree from tempfile import mkdtemp from pdb.lib.data_paths import ProjectFolder...
b_chain_uniprot with existing file""" success_msg = re.compile( r'^Found local copy of.*', re.IGNORECASE ) chain_fp = os.path.join( self.test_data_dp,
'data', 'initial_filtering_data', 'tsv_data', 'pdb_chain_uniprot.tsv') with captured_stdout() as stdout: fetch_pdb_chain_uniprot(chain_fp) result = stdout.getvalue().strip() print(result) self.assertTrue(success_msg.search(result)) ...
timokoola/timoechobot
transitions/extensions/__init__.py
Python
apache-2.0
273
0.003663
from .diagrams im
port GraphMachine from .nesting import HierarchicalMachine from .locking import LockedMachine from .factory import MachineFactory, HierarchicalGraphMachine, LockedHierarchicalGraphMachine from .factory import LockedHierarchicalMachine, Lock
edGraphMachine
muccg/rdrf
rdrf/rdrf/migrations/0014_rdrfcontext.py
Python
agpl-3.0
1,093
0.004575
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('rdrf', '0013_auto_20151201_1410'),
] operations = [ migrations.CreateModel( name='RDRFContext', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object_id', models.PositiveIntegerField()), ('created_at', model...
blank=True)), ('content_type', models.ForeignKey(to='contenttypes.ContentType', on_delete=models.CASCADE)), ('registry', models.ForeignKey(to='rdrf.Registry', on_delete=models.CASCADE)), ...
ihciah/xk-database
models/coursekinds.py
Python
gpl-2.0
2,456
0.023724
#!/usr/bin/env python # -*- coding: utf-8 -*- from _base import * class Kinds(db.Model,SessionMixin): __tablename__ = "kinds" #课程种类和描述 __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8', 'mysql_collate': 'utf8_general_ci' } kindid = db.Column(db.String(50), pr...
gs__ = { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8', 'mysql_collate': 'utf8_general_ci' } majorid = db.Column(db.String(50), primary_key =True, nullable=False)#专业代码,like:COMP1 majorname = db.Column(db.String(50),nullable=True) class Scheme(db.Model
,SessionMixin): __tablename__ = "scheme"#培养方案 __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8', 'mysql_collate': 'utf8_general_ci' } majorid = db.Column(db.String(100), ForeignKey('majors.majorid'), nullable=False, primary_key=True) kindid = db.Column(db.S...
gltn/stdm-documentation-editor
xml_util.py
Python
gpl-2.0
3,792
0.000527
from collections import OrderedDict from PyQt4.QtCore import QFile from PyQt4.QtGui import QApplication from PyQt4.QtXml import QDomDocument TAG_NAME = 'item' KEY = 'link' CHANGING_KEY = 'name' class XmlUtil(): def __init__(self, xml_path): """ A utility class to read xml file contents. :pa...
_NAME) elements = [] for node in nodes: element = node.toElement() if value == element.attribute(keyword_key): elements.append(element) return
elements def change_title( self, changing_val, keyword_val, changing_key=CHANGING_KEY, keyword_key=KEY): elements = self.find_tree_item(keyword_val, keyword_key) for element in elements: element.setAttribute(changing_key, changing_val) self.write_to_xml(...
Bakterija/log_fruit
src/app_modules/global_things.py
Python
unlicense
2,302
0.006082
from app_modules.widgets.text_editor import TextEditorPopup from kivy.clock import Clock, mainthread from kivy.core.clipboard import Clipboard from kivy.app import App from . import key_binder opened_popups = set() def init(): APP = App.get_running_app() ROOT = APP.root LOG_VIEW = ROOT.ids.rv LOG_BOX ...
top_categories('n/a') else: key_binder.start_categories('n/a') def do_stringinstruction(instr): if ins
tr['method'] == 'context_menu0_task': text = instr['text'] if text == 'Edit': # selected = LOG_BOX.get_widget_from_index(LOG_BOX.selected_widgets) text = '' for x in LOG_BOX.selected_widgets: text = ''.join((text, LOG_VIEW.data[x]['text0'], '\n')) ...
PhobosXIII/qc
qc/urls.py
Python
apache-2.0
1,450
0.004828
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from main import views as main_views from main.forms import AuthForm from qc import settings from qc.admin import admin_site urlpatterns = [ url(r'^{}/'.format(settings.ADMIN_URL_PATH), include(admin_site.urls)), url(...
change_done, name='password_change_done'), ])), url(r'^news/', include([
url(r'^$', main_views.all_news, name='news'), url(r'^(?P<news_id>[0-9]+)/$', main_views.detail_news, name='news_detail'), ])), url(r'^help/', include([ url(r'^$', main_views.help, name='help'), url(r'^(?P<category_id>[0-9]+)/$', main_views.help_category, name='help_category'), ...
dreinhold/pregnancy
contractions/views.py
Python
bsd-2-clause
2,352
0.011054
# Create your views here. import json from django.views.generic import ( Lis
tView, UpdateView, CreateView, ) from django.core.urlresolvers import reverse from contractions.models import Contraction from d
jango.http import HttpResponse from django.http import HttpResponseRedirect class AjaxableResponseMixin(object): """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def render_to_json_response(self, context, **response_kwargs): data = j...
HideMode/ShanBay
data/script.py
Python
mit
1,642
0.006807
# -*- coding: utf-8 -*- """ 将json文件中的数据存到数据库中 """ import requests import json import os from word.models import (Word, EnDefinition, CnDefinition, Audio, Pronunciation, Example, Note) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(BASE_DIR) def process_data(data): data = data...
def save_files(tp, word, url): filepath = '%s/media/audio/%stp/%s.mp3' % (BASE_DIR, tp, word) with open(BASE_DIR + '/media/audio/'+ tp +'/'+word+'.mp3', 'wb') as handle: response = requests.get(url, stream=True) if response.ok: # Something went wrong for block in respon...
open(file_name, 'r') as f: data = json.loads(f.read()) process_data(data) # data = requests.get('', stream=True) if __name__ == "__main__": serialize_data("data1.json")
BetterWorks/pysaml2
src/saml2/mcache.py
Python
bsd-2-clause
7,249
0.00469
#!/usr/bin/env python import memcache from saml2 import time_util from saml2.cache import ToOld, CacheError # The assumption is that any subject may consist of data # gathered from several different sources, all with their own # timeout time. def _key(prefix, name): return "%s_%s" % (prefix, name) ...
iled") def get_identity(self, subject_id, entities=None): """ Get all the identity information that has been received and are still valid about the subject. :param subject_id: The identifier of the subject
:param entities: The identifiers of the entities whoes assertions are interesting. If the list is empty all entities are interesting. :return: A 2-tuple consisting of the identity information (a dictionary of attributes and values) and the list of entities whoes informatio...
TUM-E21-ThinFilms/Controller
devcontroller/encoder_old/z.py
Python
gpl-3.0
4,616
0.00195
# Copyright (C) 2016, see AUTHORS.md # # 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. # # This program is distributed i...
der.getAbsolutePosition(False) return (position) / 1000 - self._calibration# in mm def calibrate(self, position): print("Warning: This does no calibration. Infact it will only tell you the new calibration value ...") old_calib = self._calibration self._calibration = 0 new_ca...
b
her0e1c1/pystock
stock/params.py
Python
gpl-3.0
1,959
0.00051
import inspect from stock import line, signals params = { "rolling_mean": [[25], [50], [100]], "bollinger_band": [[25, i] for i in range(-3, 4) if i != 0], "stochastic_k": [[14]], "stochastic_d": [[14, 3]], "stochastic_sd": [[14, 3, 3]], "rsi": [[14]], "macd_line": [[26, 12, 9]], # Chris M...
f) in inspect.getmembers(signals, inspect.isfunction): vals = params2.get(f_name, []) if len(vals) ==
1: def g(f, vs): def h(x): return f(x, *vs) return h funcs[f_name] = g(f, vals[0]) for vs in vals: name = f_name + "_" + "_".join(str(v) for v in vs) def g(f, vs): def h(x): ...
capy-inc/django-stdnet
tests/fields/one_to_one_field.py
Python
mit
10,516
0.000285
from ..testcase import BaseTestCase class OneToOneFieldTestCase(BaseTestCase): def test_model_relation(self): from django.db import models as dj_models from djangostdnet import models class ADjangoParentModel(dj_models.Model): name = dj_models.CharField(max_length=255) ...
l(child_obj3.parent, parent_obj3) self.assertEqual(child_obj3, parent_obj3.achildmodel) # change parent parent_dj_obj4 = ADjangoParentModel.objects.create(name='parent4') child_dj_obj3.parent = parent_dj_obj4 child_dj_obj3.save() parent_obj4 = AParentModel.objects.get(i...
t(id=child_dj_obj3.pk) self.assertEqual(child_obj3.parent, parent_obj4) self.assertEqual(child_obj3, parent_obj4.achildmodel) # change child parent_dj_obj3.adjangochildmodel = child_dj_obj3 parent_dj_obj3.adjangochildmodel.save() parent_obj3 = AParentModel.objects.get(id...
NicovincX2/Python-3.5
Algorithmique/Algorithme/Algorithme de la théorie des graphes/graph_algorithms_test.py
Python
gpl-3.0
5,705
0.001052
# -*- coding: utf-8 -*- import os import sys sys.path.append(os.path.join(os.getcwd(), os.path.pardir)) import unittest from digraph import digraph from graph import graph from graph_algorithms import * class test_graph(unittest.TestCase): def setUp(self): self.gr = graph() self.gr.add_nodes(["s...
_edges([("g", "h"), ("f", "g")]) self.gr.add_edges([("j", "
k"), ("j", "l")]) self.digr = digraph() self.digr.add_nodes(['s', 'a', 'b', 'c', 'd', 'e', 'f']) self.digr.add_edges([("s", "a"), ("a", "b"), ("b", "a"), ("c", "b")]) self.digr.add_edges([("b", "s"), ("s", "d"), ("d", "e"), ("e", "d")]) self.digr.add_edges([("b", "f"), ("e", "f"...
TheShellLand/pies
v3/scripts/clean-repo.py
Python
mit
1,569
0.003187
#!/usr/bin/env python # -*- coding: utf8 -*- # # Python script to compile an
d compare locally installed programs with files listed in the repository # If the file doesn't exist in the repository, delete it, or move it to another folder # import os import platform import re import chardet import argparse import logging from subpr
ocess import Popen, PIPE # Argparse # add logging todo parser = argparse.ArgumentParser(description='A script for condensing local repository') parser.add_argument('-v', '--verbose', help='increase output verbosity', action='store_true') args = parser.parse_args() if args.verbose: logging.basicConfig(level=loggin...
beeftornado/sentry
tests/sentry/receivers/test_core.py
Python
bsd-3-clause
2,858
0.0007
# coding: utf-8 from __future__ import absolute_import from django.apps import apps from django.conf import settings from sentry.models import Organization, Project, ProjectKey, Team, User from sentry.receivers.core import create_default_projects, DEFAULT_SENTRY_PROJECT_ID from sentry.testutils import TestCase cla...
Team.objects.filter(slug="sentry").delete() Project.objec
ts.filter(id=DEFAULT_SENTRY_PROJECT_ID).delete() config = apps.get_app_config("sentry") create_default_projects(config) project = Project.objects.get(id=DEFAULT_SENTRY_PROJECT_ID) assert project.public is False assert project.name == "Internal" a...
trevor/calendarserver
txdav/carddav/datastore/test/test_sql.py
Python
apache-2.0
32,730
0.002933
## # Copyright (c) 2010-2014 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
sql import AddressBook from txdav.xml.rfc2518 import GETContentLanguage, ResourceType class AddressBookSQLStorageTests(AddressBookCommonTests, unittest.TestCase): """ AddressBook SQL storage tests. """
@inlineCallbacks def setUp(self): yield super(AddressBookSQLStorageTests, self).setUp() yield self.buildStoreAndDirectory( extraUids=( u"home_empty", u"homeNew", ) ) yield self.populate() @inlineCallbacks def populate...
blaedd/miscutils
ktmerge/ktmerge.py
Python
apache-2.0
6,839
0.000292
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple utility to merge multiple Kerberos keytabs into one. This also cleans out duplicate and old keytab entries. """ import functools import struct # from http://pig.made-it.com/kerberos-etypes.html ETYPES = { 1: 'des-cbc-crc', 2: 'des-cbc-md4', 3: 'des...
parser = argparse.ArgumentParser(description='Merge keytabs') parser.add_argument('keytabs', metavar='ktfile', type=file, nargs='+', help='a kerberos
keytab to read in') parser.add_argument('-o', '--outfile', dest='outfile', type=str, help='output file') args = parser.parse_args() main(args)
tboyce021/home-assistant
homeassistant/components/fitbit/sensor.py
Python
apache-2.0
19,671
0.000966
"""Support for the Fitbit API.""" import datetime import logging import os import time from fitbit import Fitbit from fitbit.api import FitbitOauth2Client from oauthlib.oauth2.rfc6749.errors import MismatchingStateError, MissingTokenError import voluptuous as vol from homeassistant.components.http import HomeAssistan...
URING: configurator.notify_err
ors( _CONFIGURING["fitbit"], "Failed to register, please try again." ) return def fitbit_configuration_callback(callback_data): """Handle configuration updates.""" start_url = f"{get_url(hass)}{FITBIT_AUTH_START}" description = f"Please authorize Fitbit by visiting {s...
MartinHjelmare/home-assistant
tests/test_config_entries.py
Python
apache-2.0
29,755
0
"""Test the config manager.""" import asyncio from datetime import timedelta from unittest.mock import MagicMock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.core import callback from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.setup impo...
) assert result assert len(mock_migrate_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 0 assert entry.state == config_entries.ENTRY_STATE_MIGRATION_ERROR async def test_call_async_m
igrate_entry_failure_not_bool(hass): """Test migration fails if boolean not returned.""" entry = MockConfigEntry(domain='comp') entry.version = 2 entry.add_to_hass(hass) mock_migrate_entry = MagicMock( return_value=mock_coro()) mock_setup_entry = MagicMock(return_value=mock_coro(True)) ...
bmmpxf/suite
docs/postgis/src/conf.py
Python
gpl-2.0
6,298
0.006351
# -*- coding: utf-8 -*- # # GeoServer documentation build configuration file, created by # sphinx-quickstart on Tue Oct 28 10:01:09 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickl...
ments, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. latex_elements = { 'fontpkg': '\\usepackage{palatino}', 'fncychap': '\\usepackage[Sonny]{fncychap}', 'preamble': """\\usepackage[parfill]{parskip} \\hypersetup{ colorli...
r = blue, filecolor = [rgb]{0,0.46,0.63}, pagecolor = [rgb]{0,0.46,0.63}, urlcolor = [rgb]{0,0.46,0.63} } """ } # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
ypid/series60-remote
pc/window/statistics.py
Python
gpl-2.0
22,710
0.005945
# -*- coding: utf-8 -*- # Copyright (c) 2008 - 2009 Lukas Hetzenecker <LuHe@gmx.at> import datetime from PyQt4.QtCore import * from PyQt4.QtGui import * # Matplotlib try: import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt...
r i in range(last - first + 1)] x = [str(first+i) for i in range(last - first + 1)] elif period == StatisticPeriod.YearsAndMonths: f
irst = get[0] last = get[-1] months = last.year() - first.year() + 1 months *= 12 months -= first.month() - 1 months -= 12 - last.month() y1 = list() ...
bitsgalore/omSipCreator
omSipCreator/config.py
Python
apache-2.0
867
0
#! /usr/bin/env python """ Variables that are shared between modules """ import sys import codecs version = "" scriptPath = "" scriptName = "" mediaInfoExe = "" mets_ns = "" mods_ns = "" premis_ns = "" ebucore_ns = "" xlink_ns = "" xsi_ns = "" isolyzer_ns = "" cdInfo_ns = "" dfxml_ns = "" metsSchema = "" mods
Schema = "" premisSchema = "" ebucoreSchema = "" NSMAP = {} failedPPNs = [] errors = 0 warnings = 0 createSIPs = False pruneBatch = False skipChecksumFlag = False batchErr = "" dirOut = "" dirsInMetaCarriers = [] carrierTypeAllowedValues = [] # Set encoding of the terminal to UTF-8 if sys.version.startswith("2"): o...
if sys.version.startswith("3"): out = codecs.getwriter("UTF-8")(sys.stdout.buffer) err = codecs.getwriter("UTF-8")(sys.stderr.buffer)
wohllab/milkyway_proteomics
galaxy_milkyway_files/tools/wohl-proteomics/ssl_converter/ssl_converter.py
Python
mit
43,684
0.020786
import os, sys, re import shutil import optparse import shutil import pandas import numpy import subprocess import fnmatch from joblib import Parallel, delayed import multiprocessing from Bio import SeqIO import glob ##################################### #This is the script to produce SSL file outputs for skyline spec...
10-05-wb-HEK293-BioRep1-F1.mzML" #would belong to fraction "F1" # #VERSION 1.8.0 version="1.8.0" #DATE: 9/18/2017 date="9/18/2017" ##################################### print "-----------------------------------------------------------------------" print "Welcome to th
e SSL file converter for Galaxy, Wohlschlegel Lab UCLA" print "Written by William Barshop" print "Version: ",version print "Date: ",date def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped) return pandas.concat(retLst) de...
mitodl/micromasters
ui/url_utils.py
Python
bsd-3-clause
662
0
""" Utils for URLs (to avoid circular imports) """ DASHBOARD_URL = '/dashboard/' PROFILE_URL = '/profile/' PROFILE_PERSONAL_URL = '{}personal/?'.format(PROFILE_URL) PROFILE_EDUCATION_URL
= '{}education/?'.format(PROFILE_URL) PROFILE_EMPLOYMENT_URL = '{}professional/?'.format(PROFILE_URL) SETTINGS_URL = "/settings/" SEARCH_URL = "/learners/" ORDER_SUMMARY = "/order_summary/" EMAIL_URL = "/automaticemails/" PAYMENT_CALL_BACK_URL = "/payment-callback/" DASHBOARD_URLS = [
DASHBOARD_URL, PROFILE_URL, PROFILE_PERSONAL_URL, PROFILE_EDUCATION_URL, PROFILE_EMPLOYMENT_URL, SETTINGS_URL, SEARCH_URL, ORDER_SUMMARY, EMAIL_URL, ]
craig5/python-ibank
setup.py
Python
apache-2.0
2,638
0.019712
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=4 shiftwidth=4 autoindent smartindent: #from distutils.core import setup import os import logging import setuptools import distutils.cmd import subprocess # TODO add check to make sure required libs are present (eg sqlite3) _PACKAGE_NAME = 'python...
gger(_LOGGER_NAME) class VirtualEnv(distutils.cmd.Command): """Setup virtualenv.""" description = "Setup virtualenv." user_options = [] def __init__(self, dist=None): self.announce('Init virtualenv.', level=3) self.finalized = None def initialize_optio
ns(self): pass def finalize_options(self): pass def run(self): """Create the virtualenv.""" # TODO finish automating virtualenv... manual is ok for now self.announce('Running virtualenv.', level=2) print "Creating virtual env in:", _VIRTUALENV_DIR # TODO...
sonntagsgesicht/regtest
.aux/venv/lib/python3.9/site-packages/pygments/styles/sas.py
Python
apache-2.0
1,417
0
""" pygments.styles.sas ~~~~~~~~~~~~~~~~~~~ Style inspired by SAS' enhanced program editor. Note This is not meant to be a complete style. It's merely meant to mimic SAS' program editor syntax highlighting. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, s...
bold #2e8b57', Other: 'bg:#ffffe0', Keyword: '#2c2cff', Keyword.Reserved: 'bold #353580',
Keyword.Constant: 'bold', Name.Builtin: '#2c2cff', Name.Function: 'bold italic', Name.Variable: 'bold #2c2cff', Generic: '#2c2cff', Generic.Emph: '#008800', Generic.Error: '#d30202', Error: ...
42cc/ripple_api
ripple_api/test_trade.py
Python
bsd-3-clause
12,129
0
# -*- coding: utf-8 -*- import unittest from decimal import Decimal from django.conf import settings from django.test import TestCase from mock import patch from .trade import sell_all part_pay = 0.5 part_get = 0.1 amount_get = 1 amount_pay = 2 sequence = 1 balance_pay = 100 balance_get = 200 AffectedNodes = { ...
gine_result'] = 'error' create_offer_mock.return_val
ue = self.create_data call_api_mock.return_value = self.create_data exchange_result = sell_all( sell_needed={ 'value': amount_pay, 'currency': 'TUS', 'issuer': 'rp2PaYDxVwDvaZVLEQv7bHhoFQEyX1mEx7' }, buy_expected={ 'val...
madgik/exareme
Exareme-Docker/src/exareme/exareme-tools/madis/src/functionslocal/vtable/filtertable.py
Python
mit
3,582
0.012284
import setpath import functions import json registered=True # Filters the input table using the filters argument # For example # lala table : # [1|1[2|tear-prod-rate[3|normal[4|? # --- [0|Column names --- # [1|no [2|colname [3|val [4|nextnode # var 'filters' from select tabletojson(colname,val, "colname,val") from lal...
VTG
enerator(filtertable) if not ('.' in __name__): """ This is needed to be able to test the function, put it at the end of every new function you create """ import sys import setpath from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.set...
joshua-cogliati-inl/raven
tests/framework/ensembleModelTests/EM_C_dummy.py
Python
apache-2.0
692
0.00289
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/
LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the...
erature
Akagi201/learning-python
flask/markup.py
Python
mit
371
0.010782
# -*- coding: utf-8 -*- #!/usr/bin/env p
ython from flask import Markup #Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>') Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' #Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;') Markup.escape('<blink>hacker</blink>') #u'Marked up \xbb HTML' Markup('<em>Marked up</em> &raquo; HTML').
striptags()
Schibum/naclports
build_tools/pnacl-configure-shim.py
Python
bsd-3-clause
1,424
0.004916
#!/usr/bin/env python # Copyright (c) 2014 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Autoconf builds lots of small executables. This wreaks havock with pnacl's slow -O2 build time. Additionally linking nacl_i...
em. Determine if we're configuring and if -Dmain=nacl_main is passed. """ from __future__ import print_function import subprocess import sys cmd = sys.argv[1:] configuring = False nacl_main = False sdl_main = False for arg in cmd: if arg == 'conftest.c': configuring = True if arg == '-Dmain=nacl_main': ...
-lnacl_spawn', '-lppapi_simple', '-lppapi_cpp', '-lppapi', ]) if configuring: cmd = [i for i in cmd if i not in DROP_FLAGS] if nacl_main or sdl_main: cmd = [i for i in cmd if i != '-lcli_main'] if sdl_main: cmd = [i for i in cmd if i != '-lSDLmain'] cmd += ['-O0'] sys.exit(subprocess.call(...
yuuki0xff/nvpy
tests/notes_db/filter.py
Python
bsd-3-clause
5,345
0.001871
import os import shutil import unittest import copy from nvpy.nvpy import Config from nvpy.notes_db import NotesDB notes = { '1': { 'modifydate': 1111111222, 'tags': [], 'createdate': 1111111111, 'syncdate': 0, 'content': 'active note 1', 'savedate': 0, }, '2...
ssertEqual(match_regexp, '') self.assertEqual(active_notes, 3) filtered_notes, match_regexp, active_notes = db.filter_notes_gstyle('') self.assertEqual(len(filtered_notes), 3) self.assertEqual(match_regexp, '') self.assertEqual(active_notes, 3) def test_search_by_tag(self): ...
iltered_notes, match_regexp, active_notes = db.filter_notes_gstyle('tag:foo') self.assertEqual(len(filtered_notes), 1) self.assertEqual(filtered_notes[0].note['content'], notes['3']['content']) self.assertEqual(match_regexp, '') # Should ignore for tag pattern self.assertEqual(active_no...
kalkin/qubes-core-admin
qubes/api/internal.py
Python
gpl-2.0
5,136
0.000779
# -*- encoding: utf8 -*- # # The Qubes OS Project, http://www.qubes-os.org #
# Copyright (C) 2017 Marek Marczykowski-Górecki # <marmarek@invisiblethingslab.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General
Public License as published by # the Free Software Foundation; either version 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 PUR...
newvem/pytz
pytz/zoneinfo/Africa/Conakry.py
Python
mit
555
0.07027
'''tzinfo timezone information for Africa/Conakr
y.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Conakry(DstTzInfo): '''Africa/Conakry timezone definition. See datetime.tzinfo for details''' zone = 'Africa/Conakry' _utc_transition_times = [ d(1,1,1,0,0,0), d(191...
_transition_info = [ i(-3300,0,'LMT'), i(0,0,'GMT'), i(-3600,0,'WAT'), i(0,0,'GMT'), ] Conakry = Conakry()
mbedmicro/pyOCD
pyocd/target/family/target_nRF52.py
Python
apache-2.0
4,862
0.002674
# pyOCD debugger # Copyright (c) 2006-2013 Arm Limited # Copyright (c) 2019 Monadnock Systems Ltd. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
_reg(CTRL_AP_RESET, CTRL_AP_RESET_NORESET) self.ctrl_ap.write_reg(CTR
L_AP_ERASEALL, CTRL_AP_ERASEALL_NOOPERATION) return True
C3Wireless/c3-reference
src/c3reference/listener.py
Python
mit
9,445
0.000741
#!/bin/env python """Simulates the traffic of one or more listeners or beacons.""" import time import argparse import asyncio import os import random import struct # from binascii import unhexlify from enum import IntEnum import lzo # from Crypto.Cipher import AES # from Crypto.Hash import CMAC from .proto.common_p...
(buf.hex(), l_id.hex(), self.id.hex(), # self.nonce.hex(), payload.hex(), # self.clock, self.dk, # self.flags, # tag.hex(), (distance / 100.0), (variance / 100.0))) # # def evolve_dk(self, num: int) -> None: ...
Same algo as the "beacon", but we know we'll # # be masking the unknown bits, so shift in zeros # high, low = self.dk >> 16, self.dk & 0x0000ffff # if num == 0: # low = (low << 1) & 0xffff # if num == 1: # high = high << 1 & 0xffff # self.dk = (high << 16)...
kaleidos/django-sampledatahelper
sampledatahelper/register.py
Python
bsd-3-clause
2,778
0.00108
from django.db import models from sampledatahelper.helper import SampleDataHelper from sampledatahelper import handlers class Register(object): fields = {} ignored_fields = [] _instance = None sd = SampleDataHelper() def __new__(cls, *args, **kwargs): if not cls._instance: cls...
) register.register(models.BigIntegerField, handlers.BigIntegerHandler) register.register(models.CharField, handlers.CharHandler) register.register(models.SlugField, handlers.SlugHandler) register.register(models.EmailField, handlers.EmailHandler) register.register(models.URLField, handlers.URLHandler) register.registe...
lers.TextHandler) register.register(models.IntegerField, handlers.IntegerHandler) register.register(models.SmallIntegerField, handlers.SmallIntegerHandler) register.register(models.PositiveIntegerField, handlers.PositiveIntegerHandler) register.register(models.PositiveSmallIntegerField, handlers.PositiveSmallIntegerHan...
redpandalabs/django-oscar-stripe
oscar_stripe/forms.py
Python
bsd-3-clause
187
0
from django import forms class StripeTokenForm(forms.Form): stripeEmail = forms.EmailField(widget=forms.H
iddenInput()) stripeToken = forms.Ch
arField(widget=forms.HiddenInput())
commonsense/divisi
csc/divisi/graphics.py
Python
gpl-3.0
4,195
0.003099
from numpy import * svg_header = """<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Created with Inkscape (http://www.inkscape.org/) --> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="...
:Work> </rdf:RDF> </metadata> <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1"> """ svg_footer = """ </g> </svg> """ def svg_text(
x, y, text): return """ <text xml:space="preserve" style="font-size:9px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Sans;-inkscape-font-s...
bors-ltd/django-gitstorage
gitstorage/mimetypes.py
Python
gpl-3.0
1,124
0
# Copyright Bors LTD # This file is part of django-gitstorage. # # Django-gitstorage is free software: you can redistr
ibute 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 Licen
se, or # (at your option) any later version. # # Django-gitstorage is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You ...
skyduy/simple-dl
SoftmaxRegression/utils.py
Python
mit
1,832
0
#!/usr/bin/python # coding: utf-8 """ ... ~~~~~~~~~~~~~~~~~~~~~~~~~~ Author: YuJun <cuteuy@gmail.com> """ import struct import numpy import array def load_mnist_images(file_name): """ Loads the images from the provided file name """ image_file = open(file_name, 'rb') # Open the file # Re...
eros((num_rows*num_cols, num_examples)) # Read the actual image data images_raw = array.array('B', image_file.read()) image_file.close() # Arrange the data in columns for i in range(num_examples): limit1 = num_rows * num_cols * i limit2 = num_rows * num_cols * (i + 1) dat...
# Normalize and return the dataset return dataset / 255 def load_mnist_labels(file_name): """ Loads the image labels from the provided file name """ # Open the file label_file = open(file_name, 'rb') # Read header information from the file head1 = label_file.read(4) head2 = label_fi...
vecna/onionshare
onionshare/onionshare.py
Python
gpl-3.0
9,548
0.003456
# -*- coding: utf-8 -*- """ OnionShare | https://onionshare.org/ Copyright (C) 2014 Micah Lee <micah@micahflee.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, o...
5, '127.0.0.1', tor_socks_port) s.connect((self.onion_host, 80)) s.close()
tor_exists = True break except socks.ProxyConnectionError: pass if not tor_exists: raise NoTor(strings._("cant_connect_socksport").format(tor_socks_ports)) ready = True ...
glaudsonml/kurgan-ai
tools/sqlmap/waf/__init__.py
Python
apache-2.0
150
0
#!/usr/bin/env python
""" Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permissi
on """ pass
simongibbons/numpy
numpy/distutils/system_info.py
Python
bsd-3-clause
109,490
0.001059
#!/usr/bin/env python3 """ This file defines a set of system_info classes for getting information about various resources (libraries, library directories, include directories, etc.) in the system. Usage: info_dict = get_info(<name>) where <name> is a string 'atlas','x11','fftw','lapack','blas', 'lapack_src', 'b...
er as ConfigParser # It seems that some
people are importing ConfigParser from here so is # good to keep its class name. Use of RawConfigParser is needed in # order to be able to load path names with percent in them, like # `feature%2Fcool` which is common on git flow branch names. from distutils.errors import DistutilsError from distutils.dist import Dist...
ForgeGreensboro/forge-tool-control-api
access/serializers/MachineSerializer.py
Python
gpl-3.0
570
0
""" Machine model serializer """ from __fu
ture__ import unicode_literals from rest_framework import serializers from access.models import Machine class MachineSerializer(serializers.ModelSerializer): """ Machine model (de)Serializer """ department = serializers.HyperlinkedRelatedField(many=False, ...
view_name='departments') class Meta: model = Machine fields = ('mac_address', 'machine_name', 'department')
ethanhlc/streamlink
src/streamlink/plugins/kanal7.py
Python
bsd-2-clause
1,209
0.000827
from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http from streamlink.plugin.api import validate from streamlink.stream import HLSStream class Kanal7(Plugin): url_re = re.compile(r"https?://(?:www.)?kanal7.com/canli-izle") iframe_re = re.c...
iframe = self.iframe_re.search(res.text) iframe_url = iframe and iframe.group(1) if iframe_url: self.logger.debug("Found iframe: {}", iframe_url) ires = http.get(iframe_url) stream_m = self.stream_re.search(ires.text) stream_url = stream_m and str
eam_m.group(1) if stream_url: yield "live", HLSStream(self.session, stream_url) else: self.logger.error("Could not find iframe, has the page layout changed?") __plugin__ = Kanal7
radish-bdd/radish
src/radish/step_testing/__main__.py
Python
mit
3,589
0.000836
""" radish ~~~~~~ The root from red to green. BDD tooling for Python. :copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com> :license: MIT, see LICENSE for more details. """ from collections import namedtuple from pathlib import Path import click import colorful as cf import radish.loader as loader from radish.__...
radish_debug_mode_click_hook, logger fr
om radish.stepregistry import registry as step_registry from radish.step_testing.matcher import run_matcher_tests #: Holds a type for the coverage configuration CoverageConfig = namedtuple( "CoverageConfig", ["show_missing", "show_missing_templates"] ) def expand_matcher_configs(ctx, param, matcher_configs): ...
RedHatInsights/insights-core
insights/parsers/tests/test_uname.py
Python
apache-2.0
20,093
0.002488
import pytest from insights.parsers import uname from insights.tests import context_wrap from distutils.version import LooseVersion, StrictVersion import doctest UNAME1 = "Linux foo.example.com 2.6.32-504.el6.x86_64 #1 SMP Tue Sep 16 01:56:35 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux" UNAME2 = "Linux rhel7box 3.10.0-...
x86_64 GNU/Linux """.strip() UNAME_FOREMAN_DEBUG = """ COMMAND> uname -a Linux qqhrycsq2 2.6.32-279.el6.x86_64 #1 SMP Wed Jun 13 18:24:36 EDT 2012 x86_64 x86_64 x86_64 GNU/Linux """.strip() UNA
ME_ERROR_BLANK = "" UNAME_ERROR_TOO_SHORT = "Linux localhost.localdomain" UNAME_ERROR_TOO_SHORT2 = "Linux 2.6.32-279.el6.x86_64" UNAME_ERROR_TOO_SHORT3 = "2.6.32-279.el6.x86_64" UNAME_ERROR_ABBR_BAD_NVR = 'Linux bad-nvr 2' UNAME_ERROR_TOO_MANY_REL_PARTS = 'Linux bad-parts 3.10.1.4.16-327.204.108.59.11.el7.x86_64' def...
vivekanand1101/debsources
debsources/app/sources/__init__.py
Python
agpl-3.0
1,057
0
# Copyright (C) 2015 The Debsources developers <info@sources.debian.net>. # See the AUTHORS file at the top-level directory of this distribution and at # https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD # # This file is part of Debsources. Debsources is free software: you can # redistrib...
erms 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. For more information # see the COPYING file at the top-level directory of this distribution and at # https://anonscm.debian.org/gitweb/?p=qa/debsources...
_{dirname} bp_sources = Blueprint('sources', __name__, template_folder='templates', static_url_path='/static/sources', static_folder='static') from . import routes # NOQA
walidsa3d/pirouette
pirouette/core.py
Python
mit
1,843
0.001765
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import import sys import time import os import itertools from termcolor import colored import sys frames = { 'tetris': ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧'...
(self): pass def cursor_on(self): '''turn the cursor on''' os.system('setterm -cursor on') def cursor_off(self): '''turn the cursor off''' os.system('setterm -cursor off') def spin(self, duration=5, color='cyan', shape='tetris'): shape = frames[shape] ...
frame = colored(frame, color) l = len(frame) sys.stdout.write(frame) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b'*l) except KeyboardInterrupt: self.cursor_on() sys.exit(0) self.cursor_on()...
rohitranjan1991/home-assistant
homeassistant/components/ozw/binary_sensor.py
Python
mit
14,428
0.000762
"""Representation of Z-Wave binary_sensors.""" from openzwavemqtt.const import CommandClass, ValueIndex, ValueType from homeassistant.components.binary_sensor import ( DOMAIN as BINARY_SENSOR_DOMAIN, BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from ho...
LUE = "off_value" NOTIFICATION_VALUE_CLEAR = 0 # Translation from values in Notification CC to binary sensors # https://github.com/OpenZWave/open-zwave/blob/master/config/NotificationCCTypes.xml NOTIFICATION_SENSORS = [ { # Index 1: Smoke Alarm - Value Id's 1 and 2 # Assuming here that Value 1 and...
ent at the same time NOTIFICATION_TYPE: ValueIndex.NOTIFICATION_SMOKE_ALARM, NOTIFICATION_VALUES: [1, 2], NOTIFICATION_DEVICE_CLASS: BinarySensorDeviceClass.SMOKE, }, { # Index 1: Smoke Alarm - All other Value Id's # Create as disabled sensors NOTIFICATION_TYPE: V...
iagcl/data_pipeline
ui/app/scheduler_bg.py
Python
apache-2.0
2,334
0.009426
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
elta import time import sys import os from apscheduler.schedulers.background import BackgroundScheduler def tick(): print('Tick! The time is: %s' % datetime.now()) def alarm(time): print('Alarm! This alarm was scheduled at %s.' % time) def job_function(): print('Hello! The time is: %s' % datet...
else 'sqlite:///example.sqlite' scheduler.add_jobstore('sqlalchemy', url=url) #interval example scheduler.add_job(tick, 'interval', seconds=5) #at a specific time example alarm_time = datetime.now() + timedelta(seconds=10) scheduler.add_job(alarm, 'date', run_date=alarm_time, args=[da...
CoresecSystems/signxml
signxml/util/__init__.py
Python
apache-2.0
2,954
0.004062
""" SignXML utility functions bytes_to_long, long_to_bytes copied from https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py """ from __future__ import absolute_import, division, print_function, unicode_literals import sys, re, struct, textwrap from eight import str, bytes USING_PYTHON2 = True if...
testing, this algorithm was deemed to be the fastest s = b'' if USING_PYTHON2: n = long(n) # noqa pack = struct.pack while n > 0: s = pack(b'>I', n & 0xffffffff) + s n = n >> 32 # strip off leading zeros
for i in range(len(s)): if s[i] != b'\000'[0]: break else: # only happens when n == 0 s = b'\000' i = 0 s = s[i:] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and...
biggapoww/Python-CIS-5
interest_earned.py
Python
mit
719
0.006954
#Calculate the Interest for the customer #and Calculate the amoung of time the Interest Compounded #Written by Adrian Anderson Programmer, 9/25/17 print('Welcome to the Interest Calculator') print('Please enter the following') principal = round(float(input('Please enter th
e principal? ')), 2) rate = round(float(input('Please enter the rate? ')), 2) time = int(input('Please enter the time? ')) rate = rate/100 amount = principal * (1 + rate/time) savings = principal + amount print("*****************************") print('Interest rate: ' + str(rate), '\nTime Compounded: ' + str(time), '...
savings, 2)))
quanshengwu/wannier_tools
utility/wannhr_symm/lib/tran.py
Python
gpl-3.0
13,790
0.02161
#!/usr/bin/env python import numpy as np def tran_op(op, tmat): """ transform quantum operator from representation A to another representation B Args: op: the matrix form of operator in representation A tmat: the unitary transform matrix """ return np.dot(np.dot(np.co...
py,pz) (0,0,1)^T t_r2w[2,0] = cone # px = (px,py,pz) (1,0,0)^T t_r2w[0,1] = con
e # py = (px,py,pz) (0,1,0)^T t_r2w[1,2] = cone t_c2w = np.dot(t_c2r,t_r2w) t_c2r = t_c2w elif case.strip() == 't2g': nband = 3 t_c2r = np.zeros((nband, nband), dtype=np.complex128) # dzx --> py=i/sqrt(2)( |1,-1> + |1,1> ) t_c2r[0,0] = ci/sqrt2 ...
Naeka/vosae-app
www/core/tests.py
Python
agpl-3.0
35,934
0.004536
# -*- coding:Utf-8 -*- from django.conf import settings from django.core.files.base import ContentFile from vosae_utils import VosaeApiTest tenant_data = { u"name": u"My Company", u"email": u"contact@naeka.fr", u"phone": u"0102030405", u"fax": u"0102030400", u"billing_address": { u"city":...
rmat='json') self.assertValidJSONResponse(response) self.save_test_result(infos, response) deserialized = self.deserialize(response) self.assertEqual(deserialized.get('name'), u'My Company') self.assertEqual(deserialized.get('slug'), u
'my-company') self.assertEqual(deserialized.get('report_settings').get('font_size'), 10) self.assertEqual(deserialized.get('report_settings').get('font_name'), u'bariol') self.assertEqual(deserialized.get('report_settings').get('language'), u'en') # XML infos.update(serializer='...
dynaryu/inasafe
safe/impact_functions/volcanic/volcano_point_building/test/test_volcano_point_building.py
Python
gpl-3.0
4,136
0
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **Impact function Test Cases.** .. note:: 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; eithe...
sure_layer = read_layer(building_path) impact_function = VolcanoPointBuildingFunction.instance() impact_function.hazard = SafeLayer(hazard_layer) impact_function.exposure = SafeLayer(exposure_layer) impact_function.run() impact_layer = impact_function.impact # Check the...
oint how many buildings might be ' 'affected') message = 'The question should be %s, but it returns %s' % ( expected_question, impact_function.question) self.assertEqual(expected_question, impact_function.question, message) # The buildings should all be categorised into ...
aronsky/home-assistant
script/hassfest/requirements.py
Python
apache-2.0
8,128
0.001476
"""Validate requirements.""" from __future__ import annotations from collections import deque import json import operator import os import re import subprocess import sys from awesomeversion import AwesomeVersion, AwesomeVersionStrategy from stdlib_list import stdlib_list from tqdm import tqdm from homeassistant.con...
ce("_", "-") for commented in CO
MMENT_REQUIREMENTS } PACKAGE_REGEX = re.compile( r"^(?:--.+\s)?([-_\.\w\d\[\]]+)(==|>=|<=|~=|!=|<|>|===)*(.*)$" ) PIP_REGEX = re.compile(r"^(--.+\s)?([-_\.\w\d]+.*(?:==|>=|<=|~=|!=|<|>|===)?.*$)") SUPPORTED_PYTHON_TUPLES = [ REQUIRED_PYTHON_VER[:2], tuple(map(operator.add, REQUIRED_PYTHON_VER, (0, 1, 0)))[:...
rohe/saml2test
src/saml2test/interaction.py
Python
bsd-2-clause
13,079
0.000765
__author__ = 'rohe0002' import json import logging from urlparse import urlparse from bs4 import BeautifulSoup from mechanize import ParseResponseEx from mechanize._form import ControlNotFoundError, AmbiguityError from mechanize._form import ListControl logger = logging.getLogger(__name__) NO_CTRL = "No submit con...
process" def pick_interaction(self, _base="", content="", req=None):
logger.info("pick_interaction baseurl: %s" % _base) unic = content if content: _bs = BeautifulSoup(content) else: _bs = None for interaction in self.interactions: _match = 0 for attr, val in interaction["matches"].items(): ...
hlange/LogSoCR
.waf/waflib/Context.py
Python
agpl-3.0
20,118
0.029874
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2010-2016 (ita) """ Classes and functions enabling the command system """ import os, re, imp, sys from waflib import Utils, Errors, Logs import waflib.Node # the following 3 constants are updated on each new release (do not touch) HEXVERSION=0x1090100 """Constan...
ience """ tools = {} """ A module cache for wscript files; see :py:meth:`Context.Context.load` """ def __init__(self, **kw): t
ry: rd = kw['run_dir'] except KeyError: global run_dir rd = run_dir # binds the context to the nodes in use to avoid a context singleton self.node_class = type('Nod3', (waflib.Node.Node,), {}) self.node_class.__module__ = 'waflib.Node' self.node_class.ctx = self self.root = self.node_class('', No...
sid88in/incubator-airflow
airflow/hooks/mysql_hook.py
Python
apache-2.0
4,636
0.000216
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
QLdb.cursors from airflow.hooks.dbapi_hook import DbApiHook cl
ass MySqlHook(DbApiHook): """ Interact with MySQL. You can specify charset in the extra field of your connection as ``{"charset": "utf8"}``. Also you can choose cursor as ``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details. """ conn_name_attr = 'mysql_conn_id' def...
chirilo/remo
remo/profiles/migrations/0014_auto__add_field_userprofile_wiki_profile_url.py
Python
bsd-3-clause
6,986
0.008445
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'UserProfile.wiki_profile_url' db.add_column('profiles_userprofile', 'wiki_profile_url', se...
lds.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('d
jango.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'dateti...
isvaldo/Ola_Bemobenses
tests/Selenium/environment/lib/python3.4/site-packages/selenium/webdriver/chrome/service.py
Python
cc0-1.0
4,488
0.001337
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ct to the service. - Possibly other Exceptions in rare circumstances (OSError, etc). """ env = self.env or os.environ tr
y: self.process = subprocess.Popen([ self.path, "--port=%d" % self.port] + self.service_args, env=env, stdout=PIPE, stderr=PIPE) except OSError as err: docs_msg = "Please see " \ "https://sites.google.com/a/chromium.org/chromed...