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
luizalabs/django-toolkit
django_toolkit/middlewares.py
Python
mit
1,039
0
# -*- coding: utf-8 -*- import logging from django.utils.deprecation import MiddlewareMixin from .shortcuts import get_oauth2_app from .toolkit_settings import API_VERSION, MIDDLEWARE_ACCESS_LOG_FORMAT logger = logging.getLogger(__name__) class VersionHeaderMiddleware(MiddlewareMixin): """ Add a X-API-Vers...
S_LOG_FORMAT UNKNOWN_APP_NAME = 'unknown' def process_response(self, request, response): app
= get_oauth2_app(request) app_name = getattr(app, 'name', self.UNKNOWN_APP_NAME) logger.info( self.LOG_FORMAT.format(app_name=app_name, request=request, response=response) ) return response
gmimano/commcaretest
hqscripts/generic_queue.py
Python
bsd-3-clause
4,471
0.002684
from datetime import datetime from time import sleep from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.conf import settings from dimagi.utils.parsing import string_to_datetime, json_format_datetime from dimagi.utils.couch.cache import cache_core from dimagi.u...
""" Implements a generic enqueuing opera
tion. """ args = "" help = "" def handle(self, *args, **options): if self.use_queue(): self.validate_args(**options) self.keep_fetching_items() else: # If we return right away, supervisor will keep trying to restart # the service. So just ...
sixdub/Minions
scans/migrations/0001_initial.py
Python
gpl-2.0
1,965
0.003562
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
bases=(models.Model,), ), migrations.CreateModel( name='Scan_Profile', fields=[ ('id', models.AutoField(verbo
se_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(default=b'', unique=True, max_length=100)), ('cmdline', models.TextField(default=b'')), ('author', models.ForeignKey(related_name=b'profile_author', to=settings.AUTH_USER_MODEL...
prasanna08/oppia
core/domain/topic_jobs_one_off_test.py
Python
apache-2.0
19,929
0.00005
# coding: utf-8 # # Copyright 2018 The Oppia 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 requi...
self.save_new_topic_with_subtopic_schema_v1( self.TOPIC_ID, self.albert_id, 'A name', 'abbrev', 'topic-two', 'a name', 'description', 'Image.svg', '#C6DCDA', [], [], [], 2, language_code='invalid_language_code') job_id = (
topic_jobs_one_off.TopicMigrationOneOffJob.create_new()) topic_jobs_one_off.TopicMigrationOneOffJob.enqueue(job_id) with self.swap(logging, 'error', _mock_logging_function): self.process_and_flush_pending_tasks() self.assertEqual( observed_log_messages, ...
praekelt/django-admin-api
adminapi/api/views.py
Python
bsd-3-clause
3,675
0
from django.contrib.auth.models import User from django.contrib.contenttypes import models from django.core import exceptions from rest_framework import viewsets, generics from rest_framework.views import APIView from rest_framework.authtoken.models import Token from rest_framework import authentication from rest_fram...
a=request.data) serializer.is_valid(raise_exception=True) serializer.save() user = serializer.data del user['password'] return Response(user) def list(self, request): serializer = UserSerializer(User.objects.all(), many=True) for user in serializer.data: ...
def retrieve(self, request, pk=None): serializer = UserSerializer(self.get_object()) user = serializer.data del user['password'] return Response(user) def update(self, request, pk=None): serializer = UserSerializer( self.get_object(), data=request....
bobrathbone/piradio
radio8x2.py
Python
gpl-3.0
25,317
0.035312
#!/usr/bin/env python # # Raspberry Pi Internet Radio # using an HD44780 LCD display # $Id: radio8x2.py,v 1.7 2017/07/31 07:44:26 bob Exp $ # # Author : Bob Rathbone # Site : http://www.bobrathbone.com # # This program uses Music Player Daemon 'mpd'and it's client 'mpc' # See http://mpd.wikia.com/wiki/Music_Player...
io.MODE_RSS: displayTime(lcd,radio) display_rss(lcd,rss) elif display_mode == radio.MODE_SLEEP: displayTime(lcd,radio) display_sleep(lcd,radio) # Timer function checkTimer(radio) # Check state (pause or play) checkState(radio) # Alarm wakeup function if display_mode == radio.MOD...
if radio.volumeChanged(): lcd.line2("Volume " + str(radio.getVolume())) time.sleep(0.5) time.sleep(0.1) def status(self): # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = ...
rtouze/event_sourcing_example
app.py
Python
mit
1,568
0.001276
#!/usr/bin/env python # -*- coding: utf-8 -*- import bottle from situation_change import * timeline = EventTimeLine() registry = PersonRegistry(timeline) read_registry = PersonRegistryReader() timeline.add_subscriber(read_registry) timeline.add_subscriber(BasicLogger()) app = bottle.Bottle() @app.route('/') def ind...
s', method='POST') def change_status(person_id):
forms = bottle.request.forms registry.change_status(int(person_id), int(forms['new_status'])) bottle.redirect('/{0}'.format(person_id)) bottle.debug(True) app.run(host='localhost', port=8080, reloader=True)
BurtBiel/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/__init__.py
Python
mit
750
0.002667
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest
Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .auto_rest_swagger_bat_file_service import AutoRestSwaggerBATFileService, AutoRestSwaggerBATFileSer
viceConfiguration from .version import VERSION __all__ = [ 'AutoRestSwaggerBATFileService', 'AutoRestSwaggerBATFileServiceConfiguration' ] __version__ = VERSION
skyostil/tracy
src/generator/GeneratorTest.py
Python
mit
4,736
0.011613
# Copyright (c) 2011 Nokia # # Permission is hereby granted, free of charge, to any person obta
ining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim
itation 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...
agarwalt/WikiNearby
map_annotate_app/dto/WikiInfoDTO.py
Python
mit
796
0.001256
""" For more details, see the class documentation. """ class WikiInfoDTO: """ This class represents the data transfer object for a Wikipedia article. """ def __init__(self): """ Constructor to initialize this object. """ self.location = None self.title = "" ...
e'] = self.title return_dict['link'] = self.link return_dict['info'] = self.info return_dict['pageid'] = self.p
ageid return_dict['location'] = self.location.json_dict() return return_dict
waylonflinn/bvec
bvec/__init__.py
Python
mit
94
0
f
rom bvec.carray import carray from bvec.version import __version__
from bcolz import cparams
LABSN/expyfun
doc/conf.py
Python
bsd-3-clause
10,519
0.002567
# -*- coding: utf-8 -*- # # Expyfun documentation build configuration file, created by # sphinx-quickstart on Fri Jun 11 10:45:48 2010. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
ult.css" will overwrite the builtin "default.css". html_static_path = ['_static', '_images'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'L...
yPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pag...
jdzero/foundation
tests/model_fields/models.py
Python
mit
200
0
from foundation import models class BigS(models.Model): s = models.SlugField(max_length=2
55) class UnicodeSlugField(models.Model): s = models.SlugField(max_length=255, allow_unicode=True)
erikdejonge/newsrivr
www_newsrivr_com/twitterpythonapiwrapper.py
Python
gpl-2.0
116,682
0.006779
#!/usr/bin/python2.4 # # Copyright 2007 The Python-Twitter Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
'0.8.1' import base64 import calendar import datetime import httplib import os import rfc822 import sys import tempfile import textwrap import time import calendar import urllib import urllib2 import urlparse import gzip import StringIO try: # Python >= 2.6 import json as simplejson except ImportError: try: ...
# Google App Engine from django.utils import simplejson except ImportError: raise ImportError, "Unable to load a json library" # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl, parse_qs except ImportError: from cgi import parse_qsl, parse_qs try: from hashlib i...
LSS-USP/kiskadee
kiskadee/tests/units/test_report.py
Python
agpl-3.0
1,645
0
import unittest from sqlalchemy.orm import sessionmaker from kiskadee.report import CppcheckReport, FlawfinderReport from kiskadee.database import Database class ReportTestCase(unittest.TestCase): def setUp(self): self.engine = Database('db_test').engine Session = sessionmaker(bind=self.engine) ...
reporter = FlawfinderReport(_reports) result = _flawfinder_reporter
._compute_reports('flawfinder') self.assertEqual(len(result.keys()), 5) self.assertEqual(result['severity_5'], 1) self.assertEqual(result['severity_4'], 1) self.assertEqual(result['severity_3'], 1) self.assertEqual(result['severity_2'], 0) self.assertEqual(result['severit...
krafczyk/spack
var/spack/repos/builtin/packages/py-nbformat/package.py
Python
lgpl-2.1
1,856
0.000539
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
######################################################################### from spack import * class PyNbformat(PythonPackage): """The Jupyter Notebook format""" homepage = "https://github.com/jupyter/nbformat" url = "https://github.com/jupyter/nbformat/archive/4.1.0.tar.gz" version('4.1.0', '82...
epends_on('py-ipython-genutils', type=('build', 'run')) depends_on('py-traitlets', type=('build', 'run')) depends_on('py-jsonschema', type=('build', 'run')) depends_on('py-jupyter-core', type=('build', 'run'))
arbrandes/edx-platform
openedx/core/djangoapps/bookmarks/views.py
Python
agpl-3.0
13,259
0.002715
""" HTTP end-points for the Bookmarks API. For more information, see: https://openedx.atlassian.net/wiki/display/TNL/Bookmarks+API """ import logging import eventtracking from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import gettext as _ from dja...
description="The id of the course to limit the list", ), apidocs.string_parameter( 'fields', apidocs.ParameterLocation.QUERY, description="The fields to return: display_name, path.", ), ], ) def get(self, request, *a...
*kwargs): """ Get a paginated list of bookmarks for a user. The list can be filtered by passing parameter "course_id=<course_id>" to only include bookmarks from a particular course. The bookmarks are always sorted in descending order by creation date. Each page in the ...
rct/rtl_433
examples/rtl_433_statsd_pipe.py
Python
gpl-2.0
1,311
0.000763
#!/usr/bin/env python """Statsd monitoring for rtl_433 using pipes.""" # Needs Python statsd Network plugin, s.a. https://github.com/jsocol/pystatsd # pip install pystatsd # -or- # curl -o statsd.py https://github.com/jsocol/pystatsd/raw/v3.2/statsd/client.py import sys import json from statsd import StatsClient...
port=statsd_port, prefix=statsd_prefix) while True: line = sys.stdin.readline() if not line: break try:
data = json.loads(line) label = sanitize(data["model"]) if "channel" in data: label += ".CH" + str(data["channel"]) if "battery_ok" in data: statsd.gauge(label + '.battery', data["battery_ok"]) if "humidity" in data: ...
bnewbold/diffoscope
tests/comparators/test_java.py
Python
gpl-3.0
2,039
0.004912
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2015 Jérémy Bobbio <lunar@debian.org> # # diffoscope is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ
ic License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # diffoscope 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 <http://www.gnu.org/licenses/>. import os.path import pytest from diffoscope.comparators import specialize from diffoscope.comparators.binary import FilesystemFile, NonExistingFile from diffoscope.comparators.java import ClassFile from diffoscope.config import Config TEST_FILE1_PATH = os.path.join(os.path.dirnam...
wbg-optronix-lab/emergence-lab
core/models/sample.py
Python
mit
16,814
0.000952
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import operator import string import six from django.db import models from django.utils.encoding import python_2_unicode_compatible from mptt import models as mptt from polymorphic.models import PolymorphicModel from simple_history imp...
ecific number of pieces, with an optional comment on the split process itself. :param user: The user that split the sample. :param number: The
number of pieces to split the sample into. :param piece: The piece to split. Defaults to 'a'. :param comment: An optional comment associated with the split. :param force_refresh: Specifies whether to update the sample in-place with the new tree. Set to True if the s...
m3rik/nn
PythonCourse/exercises/ex24.py
Python
apache-2.0
851
0.014101
"""The third person singular verb form in English is distinguished by the suffix -s, which is added to the stem of the infinitive form: run -> runs. A simple set of rules can be given as follows: If the verb ends in y, remove it and add ies If the verb ends in o, ch, s, sh, x or z, add es By default just add s Your ...
function with word
s like try, brush, run and fix. Note however that the rules must be regarded as heuristic, in the sense that you must not expect them to work for all cases. Tip: Check out the string method endswith().""" def make_3sg_form(verb): pass #test print(make_3sg_form('try')) print(make_3sg_form('brush')) print(make_3sg...
amol-/depot
tests/base_ming.py
Python
mit
896
0.001116
from __future__ import absolute_import import os import ming from ming import Session from ming.odm import ThreadLocalODMSession from ming import create_datastore from depot.fields.ming import DepotExtension mainsession = Session() DBSession = ThreadLocalODMSession(mainsession, extensions=(DepotExtension, )) database...
_setup if not
database_setup: setup_database() try: # On MIM drop all data datastore.conn.drop_all() except TypeError: # On MongoDB drop database datastore.conn.drop_database(datastore.db)
dquinteros/sscaThesis
tools/matrixMult.py
Python
mit
168
0.011905
#!/usr/bin/env python import sys import numpy as np import math A = np.matrix("1 2 3; 4 5
6; 7 8 9")
B = np.matrix("2 2 2; 2 2 2; 2 2 2") print np.multiply(A,B)
NDKoehler/DataScienceBowl2017_7th_place
dsb3a_assets/LIDC-annotations_2_nodule-seg_annotations/LIDC_preprocessing/2_get_xml_paths_unblinded_read/write_xml_path_lst_unblinded_read.py
Python
mit
1,388
0.023775
import os,sys import numpy as np import xml.etree.ElementTree as ET import SimpleITK xml_path_lst = np.genfromtxt('/media/philipp/qnap/LIDC/preprocessing/1_get_xml_paths/xml_path_lst.csv', delimiter=",",dtype=str) xml_path_lst_unblinded_read = [] min_slice_thickness = 2.5 counter = 1 for xml_path in xml_path_lst: ...
falls header nciht sauber geschrieben wurde ("," fehlt) if(root.attrib.keys()[0] != "uid"): prefix = root.attrib[ root.attrib.keys()[0] ].split()[0] else: prefix = root.attrib[ root.attrib.keys()[1] ].split()[0]
TaskDescription = root[0].findall('{'+prefix+'}TaskDescription')[0].text if(TaskDescription == "Second unblinded read"): dcm_path = os.path.dirname(os.path.abspath(xml_path)) reader = SimpleITK.ImageSeriesReader() filenamesDICOM = reader.GetGDCMSeriesFileNames(dcm_path) reader.Se...
martinry/gblocks_analogue
alnx.py
Python
gpl-3.0
12,858
0.013532
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from Bio import SeqIO from Bio.Seq import Seq import pandas as pd ### Argparse ### import argparse parser = argparse.ArgumentParser() parser.add_argument( '-v', '--version', action='version', version='%(prog)s 0.8' ) parser.add_argument( '-i'...
(k-before,k+1)]) if(v == 0 and is_gap == False): before += 1 elif(v > 0 and is_gap == False): before = 0 if(v == 0 and is_gap == True): after += 1 elif(v > 0 and is_gap == True): gaps.extend([g for g in range...
!= 0): all_gaps.extend(gaps) find_gaps(flanked_blocks) blocks = {} for block in flanked_blocks: for k,v in block.items(): if(k not in all_gaps): blocks[k] = v # Remove small remaining blocks <= _b4 blocks_to_remove = [] blocks = group_by_consecutives(blocks) for i, block in ...
demisto/content
Packs/CommonScripts/Scripts/Ping/Ping.py
Python
mit
1,264
0.002373
import demistomock as demisto from CommonServerPython import * import subprocess import re def main(): try: dest = demisto.args()['address'] ping_out = subprocess.check_output( ['ping', '-c', '3', '-q', dest], stderr=subprocess.STDOUT, universal_newlines=True ) s = re.s...
if not s: raise ValueError("Couldn't parse ping statistics:\n" + ping_out) res['ret_code'] = '0' res['destination'] = dest res['min_rtt'] = s.group(1) res['avg_rtt'] = s.group(2) res['max_rtt'] = s.group(3) res['mdev_rtt'] = s.group(4) return_outpu...
e(e, subprocess.CalledProcessError): msg = e.output # pylint: disable=no-member else: msg = str(e) return_error(msg) # python2 uses __builtin__ python3 uses builtins if __name__ == "__builtin__" or __name__ == "builtins": main()
bmbove/flask-api-boilerplate
manage.py
Python
mit
291
0
#!/usr/bin/env python
from app import app, db from flask.ext.script import Manager, Server from flask.ext.migrate import MigrateCommand manager = Manager(app) manager.add_command('runserv
er', Server()) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
NiklasRosenstein/flux
flux/utils.py
Python
mit
16,462
0.011602
# Copyright (c) 2016 Niklas Rosenstein # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, ...
return wrapper def with_io_response(kwarg='stream', stream_type='text', **response_kwargs): ''' Decorator for View functions that create a :class:`io.StringIO` or :class:`io.BytesIO` (based on the *stream_type*
parameter) and pass it as *kwarg* to the wrapped function. The contents of the buffer are sent back to the client. ''' if stream_type == 'text': factory = io.StringIO elif stream_type == 'bytes': factory = io.BytesIO else: raise ValueError('invalid value for stream_type: {!r}'.format(stream_type)...
starlure/google_python_class
basic/string1.py
Python
apache-2.0
3,650
0.011781
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Basic string exercises # Fill in the code for the functions below. main() is already se...
e length 2 or more. def mix_up(a, b): # +++your code here+++ c1 = b[:2] + a[2:] c2 = a[:2] + b[2:] return c1 + ' ' + c2 # Provided simple test() function used in main() to prin
t # what each function returns vs. what it's supposed to return. def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) # Provided main() calls the above functions with interesting inputs, # using test() to...
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/utils/datastructures.py
Python
mit
10,194
0.00049
import copy from collections import OrderedDict from collections.abc import Mapping class OrderedSet: """ A set which keeps the ordering of the inserted items. Currently backs onto OrderedDict. """ def __init__(self, iterable=None): self.dict = OrderedDict.fromkeys(iterable or ()) de...
lf, item): try: self.remove(item) except KeyError:
pass def __iter__(self): return iter(self.dict) def __contains__(self, item): return item in self.dict def __bool__(self): return bool(self.dict) def __len__(self): return len(self.dict) class MultiValueDictKeyError(KeyError): pass class MultiValueDic...
EmanueleCannizzaro/scons
src/engine/SCons/Tool/packaging/tarbz2.py
Python
mit
1,780
0.001685
"""SCons.Tool.Packaging.tarbz2 The tarbz2 SRC packager. """ # # Copyright (
c) 2001 - 2016 The SCons Foundation # # 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 Softw
are without restriction, including # without limitation 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 permis...
golismero/golismero
golismero/managers/rpcmanager.py
Python
gpl-2.0
10,792
0.002872
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Manager of RPC calls from plugins. """ from golismero.api.config import Config __license__ = """ GoLismero 2.0 - The web knife - Copyright (C) 2011-2014 Golismero project site: https://github.com/golismero Golismero project mail: contact@golismero-project.com This p...
y 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Fou...
fluidinfo/Tickery
tickery/www/tickerytab.py
Python
apache-2.0
7,178
0.000975
# Copyright 2010 Fluidinfo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
cus(True) def clearResults(self): self.results.clear() def clearCheckResult(self): self.checkResult.clear() def onClick(self, sender): if sender == self.db: width = (Window.getClientWidth() - POPUP_WID
TH) / 2.0 self.popup.setPopupPosition(width, 100) self.popup.show() else: self.process() def process(self): self.clearCheckResult() self.clearResults() text = self.query.getText() query = text.strip() if query: self.que...
pyrrho314/recipesystem
trunk/gempy/gemini/eti/__init__.py
Python
mpl-2.0
283
0
# __init__.
py for gempy.eti module __version__ = '0.1.0 (May 2010)' import gemcombineeti import gireduceeti import gmosaiceti import gsappwaveeti import gs
crrejeti import gsextracteti import gsflateti import gsskysubeti import gstransformeti import gswavelengtheti import sploteti
CropCircleSys/bsd-cloudinit
cloudbaseinit/openstack/common/log.py
Python
apache-2.0
26,597
0.00015
# Copyright 2011 OpenStack Foundation. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance w...
and limitations # under the License. """OpenStack logging handler. This module adds to logging functionality by adding the option to specify a con
text object when calling the various log methods. If the context object is not specified, default formatting is used. Additionally, an instance uuid may be passed as part of the log message, which is intended to make it easier for admins to find messages related to a specific instance. It also allows setting of forma...
spulec/moto
moto/sagemaker/validators.py
Python
apache-2.0
538
0
def is_integer_between(x, mn=None, mx=None, optional=False): if optional and x is None: return True try: if mn is not None and mx is not None: return int(x) >= mn and int(x) < mx elif mn is not None: return int(x) >= mn elif
mx is not None: return int(x) < mx else: return True except ValueError: return False def is_one_of(x, choices, optional=Fal
se): if optional and x is None: return True return x in choices
andialbrecht/django-hvad
setup.py
Python
bsd-3-clause
1,175
0.01617
from setuptools import setup, find_packages from nani import __version__ as version setup( name = 'django-hvad', version = version, description = 'A translations framework for django integrated automatically in the normal ORM. Removes the pain of having to think about translations in a django project.', ...
Status :: 3 - Alpha", "Framework :: Django", "Inten
ded Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Database", "Topic :: I...
mat128/netman
netman/api/__init__.py
Python
apache-2.0
599
0.001669
# Copyright 2015 Internap. # # Licensed under the Apache License, Version 2.0 (the "Licens
e"); # 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 WARRA...
TMAN_API_VERSION = 2
edx/credentials
credentials/apps/records/rest_api/urls.py
Python
agpl-3.0
253
0.007905
from django.conf.urls import include from django.urls import re_path from credentials.apps.reco
rds.rest_api.v1 import urls as v1_records_rest_api_urls urlpatterns = [ re_path(r"^v1/", include((v1_records_rest_api_urls, "v1"),
namespace="v1")), ]
pgexperts/patroni-compose
patroni/patroni/ha.py
Python
mit
20,538
0.004285
import json import logging import psycopg2 import requests import sys from patroni.async_executor import AsyncExecutor from patroni.exceptions import DCSError, PostgresConnectionException from multiprocessing.pool import ThreadPool logger = logging.getLogger(__name__) class Ha: def __init__(self, patroni): ...
self.stat
e_handler.stop('immediate') self.state_handler.move_data_directory() raise self.dcs.take_leader() return 'initialized a new cluster' else: return 'failed to acquire initialize lock' else: return 'wait...
Tomsod/gemrb
gemrb/GUIScripts/bg2/GUICG2.py
Python
gpl-2.0
5,947
0.035312
# GemRB - Infinity Engine Emulator # Copyright (C) 2003 The GemRB Project # # 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 versi...
SetPlayerStat (MyChar, IE_XP, CommonTables.ClassSkills.GetValue (ClassName, "STARTXP")) #create an array to get all the classes from NumClasses = 1 IsMulti = GUICommon.IsMultiClassed (MyChar, 1) if IsMult
i[0] > 1: NumClasses = IsMulti[0] Classes = [IsMulti[1], IsMulti[2], IsMulti[3]] else: Classes = [GemRB.GetPlayerStat (MyChar, IE_CLASS)] #loop through each class and update it's level xp = GemRB.GetPlayerStat (MyChar, IE_XP)/NumClasses for i in range (NumClasses): CurrentLevel = LUCommon.GetNextLevelFromE...
onoga/toolib
toolib/dbg/CatchOutput.py
Python
gpl-2.0
398
0.040201
class CatchOutput
(object): def __init__(self, out, text): self.__out = out self.__text = text def write(self, text): if self.__text in text: raise Exception, text else: return self.__out.write(text) def __getattr__(self, name): return geta
ttr(self.__out, name) if __name__ == '__main__': import sys sys.stdout = CatchOutput(sys.stdout, 'bebe') print 'hello' print 'bebe'
nobukatsu/deep-learning-from-scratch
ch05/two_layer_net.py
Python
mit
2,635
0.010242
import sys, os sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定 from common.layers import * from common.gradient import numerical_gradient from collections import OrderedDict class TwoLayerNet: def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01): # 重みの初期化 self...
# forward self.loss(x, t) # backward dout = 1 dout = self.lastLayer.backward(dout) layers = list(self.layers.values()) layers.reverse() for layer in layers: dout = layer.backward(dout) # 設定 grads = {} grads['W1'], ...
fine2'].dW, self.layers['Affine2'].db return grads
stevenkword/PiCurious
lib/Adafruit-Raspberry-Pi-Code/Adafruit_CharLCDPlate/Adafruit_MCP230xx.py
Python
mit
78
0.012821
../.
./Adafruit-Raspbe
rry-Pi-Python-Code/Adafruit_MCP230xx/Adafruit_MCP230xx.py
oforero/UD-DS617
final-project/post-answer-len/reducer.py
Python
artistic-2.0
1,726
0.013326
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import heapq from itertools import takewhile #### # Helper functions to improve readability #### ### Implement a monoid to accumulate the results zero = [0, 0, 0] def clone(obj): return list(obj); def add(acc, nt, val): if nt =='question': ...
results def print_result(key, result): post_len, number_of_answers, answer_len = result if number_of_answers > 0: print key, "\t", post_len, "\t", answer_len / number_of_answers else: print key, "\t", post_len, "\t", 0 ##### # Implementation of the reducer ##### acc = clone(zero) oldKey ...
e # Loop around the data # For this excercise it will return a row containing the author_id and the hour of maximum posts # returning multiple lines for each author in case there is a tie # # It will use a simple process to reduce the input, this reduce can't be used as a combiner # because it does not preserve the ...
marcsowen/homematicip-rest-api
homematicip/base/constants.py
Python
gpl-3.0
3,363
0.000297
import logging LOGGER = logging.getLogger(__name__) LOGGER.warn( "constants.py is deprecated. Please use the corresponding enums in enums.py" ) # DEVICES DEVICE = "DEVICE" FULL_FLUSH_SHUTTER = "FULL_FLUSH_SHUTTER" PLUGABLE_SWITCH = "PLUGABLE_SW
ITCH" KEY_REMOTE_CONTROL_ALARM = "KEY_REMOTE_CONTROL_ALARM" MOTION_DETECTOR_INDOOR = "MOTION_DETECTOR_INDOOR" ALARM_SIREN_INDOOR = "ALARM_SIREN_INDOOR" PUSH_BUTTON = "PUSH_BUTTON" TEMPERATURE_HUMIDITY_SENSOR_DISPLAY = "TEMPERATURE_HUMIDITY_SENSOR_DISPLAY" PLUGABLE_SWITCH_MEASURING = "PLUGABLE_SWITCH_MEASURING" F...
= "FLOOR_TERMINAL_BLOCK_6" SMOKE_DETECTOR = "SMOKE_DETECTOR" WALL_MOUNTED_THERMOSTAT_PRO = "WALL_MOUNTED_THERMOSTAT_PRO" SHUTTER_CONTACT = "SHUTTER_CONTACT" SHUTTER_CONTACT_INTERFACE = "SHUTTER_CONTACT_INTERFACE" HEATING_THERMOSTAT = "HEATING_THERMOSTAT" SHUTTER_CONTACT_INVISIBLE = "SHUTTER_CONTACT_INVISIBLE" BR...
danlrobertson/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/__init__.py
Python
mpl-2.0
235
0
# flake8: noqa (not ideal, but ni
cer than adding noqa: F401 to every line!) from base import (executor_kwargs, testharness_result_converter, reftest_result_converter, TestExecutor)
tgracchus/spinnaker
pylib/spinnaker/transform_old_config.py
Python
apache-2.0
4,498
0.015118
# Copyright 2015 Google 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 law or a...
f.__environ_content) with open(self.__write_yml_path, 'w') as f: f.write(self.__output) if __name__ == '__main__': if len(sys.argv) != 5: sys.stderr.write('Usage: <content> <environ-path> <local-yml-path> <aws-cred-path>\n') sys.exit(-1)
content = sys.argv[1] environ_path = sys.argv[2] local_yml_path = sys.argv[3] aws_credentials_path = sys.argv[4] processor = Processor(content, environ_path, local_yml_path, aws_credentials_path) processor.process() sys.exit(0)
Ircam-Web/mezzanine-organization
organization/network/migrations/0080_auto_20170106_1642.py
Python
agpl-3.0
849
0.002356
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-01-06 15:42 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('organization_network', '0079_auto_2017...
migrations.AlterField( model_name='personactivitytimesheet', name='validation', field=models.DateField(blank=Tru
e, default=datetime.datetime(2017, 1, 6, 15, 40, 39, 279377, tzinfo=utc)), ), ]
thierry1985/project-1022
translate/STRIPS_SASE/SASE_plain.py
Python
mit
20,076
0.031929
#! /usr/bin/env python2.5 # -*- coding: latin-1 -*- import axiom_rules import fact_groups import instantiate import pddl import sas_tasks import simplify import sys import PrecosatSolver import copy import os import SASE_helper import SolverAdapter from SASE_helper import * from SASE_base import * import math import s...
############################################################################ #### Encoding of each iteration; #### #########################################
################################### def solve_decision( self, task, N ): self.init_encoding() std = sys.stdout #s = minisat.Solver() s = PrecosatSolver.Solver() if self.status.dump != 0 : #assert False global PRINT_OUT_CLAUSES PRINT_OUT_CLAUSES = True s = SolverA...
artas360/pythran
pythran/tests/openmp.legacy/omp_parallel_reduction.py
Python
bsd-3-clause
4,440
0.004505
def omp_parallel_reduction(): import math dt = 0.5 rounding_error = 1.E-9 sum = 0 dsum = 0 dt = 1. / 3. result = True product = 1 logic_and = 1 logic_or = 0 bit_and = 1 bit_or = 0 exclusiv_bit_or = 0 known_sum = (1000 * (1000 + 1)) / 2 'omp parallel for sch...
|:log
ic_or)" result = False logic_or = 0; logics[1000/2]=1 'omp parallel for schedule(dynamic,1) reduction(||:logic_or)' for i in xrange(0, 1000): logic_or = (logic_or or logics[i]) if not logic_or: print "E: reduction(||:logic_or) with logics[1000/2]=1" result = False ...
camilonova/django
tests/forms_tests/field_tests/test_filefield.py
Python
bsd-3-clause
3,932
0.004418
import pickle from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import FileField, ValidationError from django.test import SimpleTestCase class FileFieldTest(SimpleTestCase): def test_filefield_1(self): f = FileField() with self.assertRaisesMessage(ValidationError, "...
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) no_file_msg = "'No file was submitted. Check the encoding type on the form.'" with self.assertRaisesMessage(Val
idationError, no_file_msg): f.clean(SimpleUploadedFile('', b'')) with self.assertRaisesMessage(ValidationError, no_file_msg): f.clean(SimpleUploadedFile('', b''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) with self.assertRaisesMessage(Valid...
mainakibui/kobocat
onadata/libs/data/query.py
Python
bsd-2-clause
3,369
0.000297
from django.conf import settings from django.db import connection from onadata.libs.utils.common_tags import SUBMISSION_TIME def _count_group(field, name, xform): if using_postgres: result = _postgres_count_group(field, name, xform) else: raise Exception("Unsupported Database") return re...
MM-DD'), 'YYYY"\ "-MM-DD')" % string_args return "SELECT %(json)s AS \"%(name)s\", COUNT(*) AS count FROM "\ "%(table)s WHERE %(restrict_field)s=%(restrict_value)s "\ "AND %(exclude_deleted)s "\ "GROUP BY %(json)s" % string_args def _postgres_select_...
e)s\" FROM %(table)s WHERE "\ "%(restrict_field)s=%(restrict_value)s "\ "AND %(exclude_deleted)s" % string_args def _query_args(field, name, xform): return { 'table': 'logger_instance', 'json': _json_query(field), 'name': name, 'restrict_field': 'xform_id', ...
pfitzer/pyvmomi-community-samples
samples/getorphanedvms.py
Python
apache-2.0
8,239
0.000121
#!/usr/bin/env python """ This module demonstrates how to find virtual machines that exist on a datastore, but are not part of the inventory. This can be useful to find orphaned virtual machines that are still taking up datastore space, but not currently being used. Issues: Currently works with Windows based vCent...
print "Caught exception : " + str(e) return -1 def examine_vmx(dsname): """ function to download any vmx file passed to it via the datastore brows
er and find the 'vc.uuid' and 'displayName' """ args = get_args() try: for file_vmx in VMX_PATH: # print file_vmx username = args.user password = args.password request = urllib2.Request(url_fix(file_vmx)) base64string = base64.encodest...
graingert/dockhand
shipwright/docker.py
Python
apache-2.0
1,348
0
from __future__ import absolute_import from docker import errors as d_errors def key_from_image_name(image_name): """ >>> key_from_image_name('shipwright/blah:1234') '1234' """ return image_name.split(':', 1)[1] def key_from_image_info(image_info_dict): """ >>> key_from_image_info({ ...
ontainer, new_ref): tag = encode_tag(new_ref) image = container.name + ':' + container.ref evt = { 'event': 'tag', 'container': container, 'image': image, 'tag': tag, } try: client.tag( image, container.name, tag=tag, ...
rors.NotFound: message = 'Error tagging {}, not found'.format(image) evt.update({ 'error': message, 'errorDetail': {'message': message}, }) return evt
JMMolenaar/cadnano2.5
cadnano/virtualhelix/virtualhelix.py
Python
mit
7,266
0.00289
#!/usr/bin/env python # encoding: utf-8 from cadnano.cnproxy import ProxyObject, ProxySignal import cadnano.util as util from cadnano.enum import StrandType from cadnano.cnproxy import UndoStack, UndoCommand from cadnano.strandset import StrandSet from .removevhelixcmd import RemoveVirtualHelixCommand class Virtua...
AFFOLD: return self._scaf_strandset else: return self._stap_strandset # end def def getStrandSets(self): """Return a tuple of the scaffold and staple StrandSets.""" retur
n self._scaf_strandset, self._stap_strandset # end def def hasStrandAtIdx(self, idx): """Return a tuple for (Scaffold, Staple). True if a strand is present at idx, False otherwise.""" return (self._scaf_strandset.hasStrandAt(idx, idx),\ self._stap_strandset.hasStrandA...
tdf/tdc
tdc/settings.py
Python
gpl-3.0
2,814
0.000355
""" Django settings for tdc project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import...
URLCONF = 'tdc.urls' WSGI_APPLICATION = 'tdc.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, '
db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' ...
evernote/pootle
pootle/core/forms.py
Python
gpl-2.0
6,054
0.00033
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 Evernote Corporation # # This file is part of Pootle. # # 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 L...
nInput()) def __init__(self, *args, **kwargs): """Initalise captcha_question and captcha_token for the form.""" super(MathCaptchaForm, self).__init__(*args, **kwargs) # reset captcha for unbound forms if not self.data: self.reset_captcha() def reset_captcha(self): ...
te_captcha() expires = time.time() + \ getattr(settings, 'CAPTCHA_EXPIRES_SECONDS', 60*60) token = self._make_token(q, a, expires) self.initial['captcha_token'] = token self._plain_question = q # reset captcha fields for bound form if self.data: de...
maoxuxiang/termite_mallet_project
server_src/controllers/ScatterPlot1.py
Python
bsd-3-clause
897
0.021182
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from db.Corpus_DB import Corpus_DB from db.BOW_DB import BOW_DB from db.LDA_DB import LDA_DB from db.ITM_DB import ITM_DB from vis.ScatterPlot
1 import ScatterPlot1 as ScatterPlot1Handler def index(): with Corpus_DB() as corpus_db: with BOW_DB() as bow_db:
with LDA_DB() as lda_db: handler = ScatterPlot1Handler(request, response, corpus_db, bow_db, lda_db) response.delimiters = ('[[', ']]') return handler.GenerateResponse() def gib(): with Corpus_DB() as corpus_db: with BOW_DB() as bow_db: with LDA_DB() as lda_db: handler = ScatterPlot1Handler(request, re...
imobilis/uhub
src/core/config.py
Python
gpl-3.0
8,720
0.029702
#!/usr/bin/env python """ uhub - A tiny ADC p2p connection hub Copyright (C) 2007-2013, Jan Vidar Krey """ from xml.dom import minidom, Node from datetime import datetime import argparse class OptionParseError(Exception): pass class Option(object): def _get(self, node, name): self.__dict__[name] = None if ...
(struct hub_config* config)\n{\n") for option in options: self._write_default_impl(option) self.f.write("}\n\n") self.f.write("static int apply_config(struct hub_config* config, char* key, char* data, int line_count)\n{\n\tint max = 0;\n\tint min = 0;\n\n") for option in options: self._write_apply_impl(op...
n\treturn -1;\n}\n\n") self.f.write("void free_config(struct hub_config* config)\n{\n") for option in options: self._write_free_impl(option) self.f.write("}\n\n") self.f.write("void dump_config(struct hub_config* config, int ignore_defaults)\n{\n") for option in options: self._write_dump_impl(option) ...
calmjs/nunja.stock
src/nunja/stock/testing/case.py
Python
gpl-2.0
1,097
0
# -*- coding: utf-8 -*- import codecs import json import unittest from pkg_resources import resource_filename from calmj
s.parse import es5 class ExamplesTestCase(unittest.TestCase): """ A test case that automatically load the examples JS module into the data attribute for the test instance, and to provide a shortcut for doing assertions. """ data = None test_module_name = 'nunja.stock.tests' test_examp...
def setUpClass(cls): if cls.test_examples is NotImplemented: raise ValueError( 'the class must define the test_examples attribute for data') with codecs.open( resource_filename(cls.test_module_name, cls.test_examples), encoding='utf8') as...
glenpassow/Hello-friend
hellofriend.py
Python
mit
851
0.012926
""" hel
lofriend.py Author: glen passow Credit: Tess S
nyder Assignment: Write and submit an interactive Python program that asks for the user's name and age, then prints how much older Python is than the user (based on a simple comparison of birth year). Python's first public release occurred in 1991. Something like this: Please tell me your name: Guido Please tell m...
smarden1/airflow
airflow/executors/__init__.py
Python
apache-2.0
1,008
0
import logging from airflow.configuration import conf from airflow.executors.base_executor import BaseExecutor from airflow.executors.local_executor import LocalExecutor from airflow.executors.celery_executor import CeleryExecutor from airflow.executors.sequential_executor import SequentialExecutor f
rom airflow.utils import AirflowException _EXECUTOR = conf.get('core', 'EXECUTOR') if _EXECUTOR == 'LocalExecutor': DEFAULT_EXECUTOR = LocalExecutor() elif _EXECUTOR == 'CeleryExecutor':
DEFAULT_EXECUTOR = CeleryExecutor() elif _EXECUTOR == 'SequentialExecutor': DEFAULT_EXECUTOR = SequentialExecutor() else: # Loading plugins from airflow.plugins_manager import executors as _executors for _executor in _executors: globals()[_executor.__name__] = _executor if _EXECUTOR in glo...
AnTAVR/aai2
src/modules/pkgs/m_main.py
Python
gpl-2.0
667
0.001558
import logging from gettext import gettext as _ fro
m typing import Tuple from aai_framework.dial import ColorTxt from aai_framework.interface import ModuleInterface from .main import vars_, Vars logger = logging.getLogger(__name__) class Module(ModuleInterface): ID = 'pkgs' LEN_INSTALL = 2665 @property def vars_(self) -> Vars: return vars_ ...
О') @property def menu_item(self) -> Tuple[str, str]: text = [ColorTxt('(' + _('ВЫПОЛНЕНО') + ')').green.bold if self.is_run else ''] return super().get_menu_item(text)
radjkarl/appBase
appbase/mainWindowRessources/menuShortcuts.py
Python
gpl-3.0
1,016
0.001969
# coding=utf-8 from qtpy import QtWidgets class MenuShortcuts(QtWidgets.QWidget): """ Window displaying the application shortcuts """ def __init__(self): QtWidgets.QWidget.__init__(self) self.setWindowTitle('Shortcuts') l = QtWidgets.QGridLayout() self.s...
el('<b>Description</b>') l.addWidget(lk, 0, 0) l.ad
dWidget(ld, 0, 1) line = QtWidgets.QFrame(self) line.setLineWidth(2) line.setMidLineWidth(1) line.setFrameShape(QtWidgets.QFrame.HLine) line.setFrameShadow(QtWidgets.QFrame.Raised) l.addWidget(line, 1, 0, 1, 2) self._r = 2 def addShortcut(self, k...
jasonehines/mycroft-core
mycroft/tts/google_tts.py
Python
gpl-3.0
1,667
0.0006
# Copyright 2016 My
croft AI, Inc. # # This file is part of Mycroft Core. # # Mycroft Core 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. # # Mycroft Core...
en the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>. from gtts import gTTS from mycroft.tt...
jeremiah-c-leary/vhdl-style-guide
vsg/rules/package/rule_016.py
Python
gpl-3.0
649
0
from vsg import token from vsg.rules import token_suffix
lTokens = [] lTokens.append(token.package_declaration.identifier) lTokens.append(token.package_declaration.end_package_simple_name) class rule_016(token_suffix): ''' This rule checks for valid suffixes on package identifiers. The default package suffix is *_pkg*. |configuring_prefix_and_suffix_rules...
.. code-block:: vhdl package foo is **Fix** .. code-block:: vhdl package foo_pkg is ''' def __init__(self): token_suffix.__init__(self, 'package', '016', lTokens) self.suffixes = ['_pkg']
dbarbier/privot
python/test/t_LogUniformFactory_std.py
Python
lgpl-3.0
1,188
0.004209
#! /usr/bin/env python from openturns import * TESTPREAMBLE() RandomGenerator().SetSeed(0) try : distribution = LogUniform(1.0, 2.5) size = 10000 sample = distribution.getSample(size) factory = LogUniformFactory covariance = CovarianceMatrix estimatedDistribution = factory.build(sample) p...
print "Default distribution=", estimatedDistribution estimatedDistribution = factory.build(distribution.getParametersCollection()) print "Distribution from parameters=", estimatedDistribution estimatedLogUniform = factory.buildAsLogUniform(sample) print "LogUniform =", distribution
print "Estimated logUniform=", estimatedLogUniform estimatedLogUniform = factory.buildAsLogUniform() print "Default logUniform=", estimatedLogUniform estimatedLogUniform = factory.buildAsLogUniform(distribution.getParametersCollection()) print "LogUniform from parameters=", estimatedLogUniform exce...
birsoyo/conan
conans/test/functional/conditional_test_req.py
Python
mit
1,380
0.002174
import unittest from conans.test.utils.tools import TestClient from conans.util.files import load, save class ConditionalReqsTest(unittest.TestCase): def conditional_requirements_test(self): conanfile = """from conans import ConanFile class TestConanLib(ConanFile): name = "Hello" version = "0.1"...
settings = load(settings_path) settings += "\nproduct: [onion, potato]" save(setting
s_path, settings) client.save({"conanfile.py": conanfile, "test_package/conanfile.py": test_conanfile}) client.run("create . lasote/testing -s os=Windows -s product=onion -s build_type=Release") self.assertIn("PROJECT: Conditional test requirement: Windows, Release, onion", ...
xoddark/libretro-arxlibertatis
plugins/blender/arx_addon/main.py
Python
gpl-3.0
5,305
0.002828
# Copyright 2015 Arx Libertatis Team (see the AUTHORS file) # # This file is part of Arx Libertatis. # # Arx Libertatis 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...
u_func_import_tea(self, context): self.layout.operator(ImportTea.bl_idname, text="Tea animation (.tea)") # ============= Registration def register(): log.info("ArxAddon register") bpy.utils.register_class(ArxAddonPreferences) bpy.utils.regis
ter_class(ArxScenesUpdateList) bpy.utils.register_class(ArxScenesImportSelected) bpy.utils.register_class(ArxScenesPanel) bpy.utils.register_class(ArxFacePanel) bpy.utils.register_class(ImportFTL) bpy.utils.register_class(ImportTea) bpy.types.INFO_MT_file_import.append(menu_func_import_ftl) ...
silly-wacky-3-town-toon/SOURCE-COD
toontown/estate/PlantingGUI.py
Python
apache-2.0
18,558
0.001832
from direct.gui.DirectGui import * from panda3d.core import * from panda3d.direct import * from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from direct.task import Task from toontown.estate import GardenGlobals from direct.interva...
, (gui.find('**/FndsLst_ScrollUp'), gui.find('**/FndsLst_ScrollDN'), gui.find('**/FndsLst_ScrollUp_Rllvr'), gui.find('**/FndsLst_ScrollUp')), None), ('incButton_relief', None, None), ('incButton_scale', (1.3, 1.3, -1.3), None), ('incButton_pos', (0, 0, -0.525)...
), gui.find('**/FndsLst_ScrollDN'), gui.find('**/FndsLst_ScrollUp_Rllvr'), gui.find('**/FndsLst_ScrollUp')), None), ('decButton_relief', None, None), ('decButton_scale', (1.3, 1.3, 1.3), None), ('decButton_pos', (0, 0, 0.525), None), ('decButton_image...
thomaskonrad/osm-austria-building-coverage
coverage_score_viewer/views.py
Python
mit
4,894
0.003065
from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.http import Http404 from coverage_score_viewer.models import CoverageBoundary from coverage_score_viewer.models import CoverageScore import pygal from pygal.style import LightStyle from datetime import date import js...
admin_level: coverage_boundaries = CoverageBoundary.objects.filter(admin_level=admin_level).order_by('rank')[:10] for coverage_boundary in coverage_boundaries: coverage_sco
res = CoverageScore.objects.filter(coverage_boundary_id=coverage_boundary.id) values = [] last = len(coverage_scores) - 1 for i, coverage_score in enumerate(coverage_scores): values.append((coverage_score.date, round(coverage_score.coverage, 1))) if...
PatrickChrist/CDTM-Deep-Learning-Drones
Yolonese/utils/MeasureAccuray.py
Python
mit
2,954
0.023697
from keras.models import model_from_json import theano.tensor as T from utils.readImgFile import readImg from utils.crop import crop_detection from utils.ReadPascalVoc2 import prepareBatch import os import numpy as np def Acc(imageList,model,sample_number=5000,thresh=0.3): correct = 0 object_num = 0 cou...
del.predict(img) out = out[0] #for each ground truth, see we have predicted a corresponding result for i in ra
nge(49): preds = out[i*25:i*25+25] row = i/7 col = i%7 box = image.boxes[row][col] if(box.has_obj): for obj in box.objs: obj_num += 1 true_class = obj.class_num #see what we predict ...
majestrate/i2p-tools
i2pcontrol/i2pcontrol/__init__.py
Python
mit
26
0
from .i2pcon
trol import *
ParkHanbum/zigzi
__init__.py
Python
mit
4,427
0.000452
#!/usr/bin/python #
-*- coding: utf-8 -*- """zigzi, Platform independent binary instrumentation module. Copyright (c) 2016-2017 hanbum park <kese111@gmail.com> All rights reserved. For detailed copyright information see the file COPYING in the root of the distribution archive. """ import argparse from PEInstrument import * from PEA...
ystone import * from DataSegment import * from SampleReturnVerifier import * from WindowAPIHelper import * code_rva = 0 def simple_return_address_save_function(): global code_rva allocation = pe_instrument.falloc(0x1000) code = ("push eax;push ebx;" # save register "mov eax, [{0}];" ...
openpreserve/Scape-Tool-Tester
app/md5sumEvaluator.py
Python
apache-2.0
773
0.010349
import os import subprocess import time from config import dataDir __author__ = 'abr' def md5sumRunner(reportfile): with open(reportfile,"w") as fileThing: start = time.time() for dir, dirs, files in os.walk(dataDir): if files: for file in sorted(files): ...
subprocess.check_call(["md5sum",os.path.join(dir,file)],stdout=fileThing) endLocal = time
.time() end = time.time() return end-start csvReportfile = "md5sumreport.csv" print csvReportfile try: time = md5sumRunner(csvReportfile) pass finally: pass print "Time spent analysing the entire archive: "+str(time)+" seconds"
GBGamer/rust
src/etc/generate-deriving-span-tests.py
Python
apache-2.0
4,526
0.005966
#!/usr/bin/env python # # Copyright 2013 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license #...
etime.datetime.now().year TEMPLATE = """// Copyright {year} The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distri
bution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // e...
okoye/COAP
unittests/test-connection.py
Python
bsd-3-clause
7,153
0.004613
import unittest import coapy.options from coapy.connection import * import time import binascii class Test_is_multicast (unittest.TestCase): def testIpv4 (self): self.assertFalse(is_multicast(('localhost', 0))) self.assertTrue(is_multicast(('224.0.0.1', 0))) self.assertTrue(is_multicast(('2...
send(m, self.__address) self.assertTrue(xr.transaction_id is not None) self.assertFalse(xr.next_event_time is None) self.assertFalse(xr.is_unacknowledged) self.assertEqual(0, len(self.__send_history)) ep.process(0) self.assertEqual(1, len(self.__send_history)) tim...
c for transmission timeout' % (timeout_ms / 1000.0) rv = ep.process(timeout_ms) self.assertTrue(rv is None) self.assertTrue(xr.is_unacknowledged) self.assertEqual(coapy.MAX_RETRANSMIT, len(self.__send_history)) for rep in xrange(coapy.MAX_RETRANSMIT-1): lt0 = self.__s...
homeworkprod/byceps
tests/unit/util/iterables/test_index_of.py
Python
bsd-3-clause
728
0
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LI
CENSE` file for details) """ import pytest from byceps.util.iterables import index_of @pytest.mark.parametrize( 'iterable, predicate, expected', [ ( [],
lambda x: x > 3, None, ), ( [2, 3, 4, 5], lambda x: x > 1, 0, ), ( [2, 3, 4, 5], lambda x: x > 3, 2, ), ( [2, 3, 4, 5], lambda x: x > 6, None, ...
burakbayramli/classnotes
work/mrsvd/sasha/wc_mapfinal.py
Python
gpl-3.0
737
0.010855
# python wc_mapfinal.py local -l wc_mapfinal.py --output=wc_out.dat # from the command line, does wordcount on itself import re, job, sys WO
RD_RE = re.compile(r"[\w']+") class WordFreqCount(job.SashaJob): def __init__(self): job.SashaJob.__init__(self) self.psum = 0 def mapper(self, key, line): for word in WORD_RE.findall(line): yield (word.lower(), 1) def mapper_final(self): yield ("f...
yield self.psum if __name__ == "__main__": WordFreqCount.run()
ilveroluca/pydoop
test/mapreduce/test_text_stream.py
Python
apache-2.0
2,212
0
# BEGIN_COPYRIGHT # # Copyright 2009-2015 CRS4. # # 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...
License is distributed on an "AS IS" BASIS, WITHOUT # WARR
ANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # END_COPYRIGHT import unittest import itertools as it from pydoop.mapreduce.streams import ProtocolError from pydoop.mapreduce.text_streams import Text...
DBrianKimmel/PyHouse
Project/src/Modules/Computer/Nodes/nodes.py
Python
mit
3,171
0.001261
""" @name: Modules/Computer/Nodes/nodes.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2014-2030 by D. Brian Kimmel @license: MIT License @note: Created on Mar 6, 2014 @summary: This module does everything for nodes. Nodes are read in from the config Xml file. Then no...
ig - Version:{}'.format(__version__)) return def Start(self): self.m_local.Start() self.m_sync.Start() LOG.info('Started - Version:{}'.format(__
version__)) def SaveConfig(self): # l_xml, l_count = nodesXml.write_nodes_xml(self.m_pyhouse_obj) # p_xml.append(l_xml) Yaml().save_yaml_config(self.m_pyhouse_obj) LOG.info("Saved Config") return def Stop(self): self.m_local.Stop() self.m_sync.Stop() # ...
guorendong/iridium-browser-ubuntu
ui/resources/resource_check/resource_scale_factors.py
Python
bsd-3-clause
4,859
0.007615
# Copyright (c) 2012 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. """Presubmit script for Chromium browser resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about t...
" Initializes ResourceScaleFactors with paths.""" self.input_api = input_api self.output_api = output_api self.paths = paths def RunChecks(self): """Verifies the scale factors of resources being added or modified. Returns: An array of presubmit errors if any images were detected not ...
ilename, 'rb', buffering=0) as f: data = f.read(24) if data[:8] != '\x89PNG\r\n\x1A\n' or data[12:16] != 'IHDR': raise InvalidPNGException return struct.unpack('>ii', data[16:24]) # Returns a list of valid scaled image sizes. The valid sizes are the # floor and ceiling of (base_size...
rolandgeider/wger
wger/nutrition/__init__.py
Python
agpl-3.0
862
0
# -*- coding: utf-8 -*- # This file is part of wger Workout M
anager. # # wger Workout Manager 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. # # wger Workout Manager is distributed in the ...
TNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. # wger from wger import get_version VERSION = get_version() default_app_conf...
zhwa/thunder
thunder/standalone/stats.py
Python
apache-2.0
835
0.003593
""" Example standalone app for calculating series statistics """ import optparse from thunder import ThunderContext if __name__ == "__main__": parser = optparse.OptionParser(description="compute summary statistics on time series data", usage="%prog datafile outputdir mode [opti...
parse_args() try: datafile = args[0] outputdir = args[1] mode = args[2] except IndexError: parser.print_usage() raise Exception("too few arguments"
) tsc = ThunderContext.start(appName="stats") data = tsc.loadSeries(datafile).cache() vals = data.seriesStat(mode) outputdir += "-stats" tsc.export(vals, outputdir, "stats_" + mode, "matlab")
MartinPaulEve/overlay
journal/models.py
Python
gpl-2.0
1,874
0.002134
from django.db import models class Container(models.Model): """Represents a local or remote journal volume and issue.""" volume = models.IntegerField() issue = models.IntegerField() date = models.DateField() url = models.URLField(blank=True) title = models.CharField(max_length=500, blank=True)...
th=500) family = models.CharFiel
d(max_length=500) article = models.ForeignKey(Article) def __unicode__(self): return self.given + ' ' + self.family
aboutsajjad/Bridge
app/app.py
Python
mit
4,800
0.001042
import functools import logging import traceback import sys from flask import Flask, Blueprint, current_app, jsonify, request, redirect, abort import youtube_dl from youtube_dl.version import __version__ as youtube_dl_version __version__ = 1.0 if not hasattr(sys.stderr, 'isatty'): # In GAE it's not defined and...
control def version(): result = { 'youtube-dl': youtube_dl_version, 'youtube-dl-api-server': __version__, } re
turn jsonify(result) app = Flask(__name__) app.register_blueprint(api) app.config.from_pyfile('../application.cfg', silent=True) app.run(port=9191)
meisamhe/GPLshared
Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/zipping_list.py
Python
gpl-3.0
1,575
0
import sys import random from linked_list_prototype import ListNode from reverse_linked_list_iterative import reverse_linked_list # @include def zipping_linked_list(L): if not L or not L.next: return L # Finds the second half of L. slow = fast = L while fast and fast.next: slow, fast ...
i in sys.argv[1:]: curr = ListNode(int(i), head) head = curr else: n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 1000) for i in reversed(range(n + 1)): curr = ListNode(i, head) head = curr curr = zipping_linked_list(head) i...
& 1: assert pre + curr.data == n idx += 1 print(curr.data) pre = curr.data curr = curr.next if __name__ == '__main__': main()
HoussemCharf/FunUtils
backtrack/subsets_unique.py
Python
mit
683
0
""" Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
""" def subsets_unique(nums): def backtrack(res, nums, stack, pos): if pos == len(nums): res.add(tuple(stack)) else: # take stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) st
ack.pop() # don't take backtrack(res, nums, stack, pos+1) res = set() backtrack(res, nums, [], 0) return list(res)
vesellov/bitdust.devel
services/service_http_transport.py
Python
agpl-3.0
3,776
0.001324
#!/usr/bin/python # service_http_transport.py # # Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io # # This file (service_http_transport.py) is part of BitDust Software. # # BitDust is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as publishe...
ef create_service(): return HTTPTransportService() class HTTPTransportService(LocalService): service_name = 'service_http_transport' config_path = 'services/http-transport/enabled' proto = 'http' def enabled(self): # development started return False def dependent
_on(self): return ['service_http_connections', 'service_gateway', ] def start(self): from twisted.internet import reactor from twisted.internet.defer import Deferred from transport.http import http_interface from transport import network_trans...
Jakeand3rson/network_tools
test_echo.py
Python
mit
414
0.002415
from e
cho_client import clientmessage import pytest def test_ping(): assert clientmessage("this is a test") == "this is a test" def test_big(): assert clientmessage("this is a string that is much longer than the 32 bites that it has to force it to loop") == "this is a string that is much longer than the 32 bites ...
clientmessage("") == ""
adityaarun1/faster_rcnn_pytorch
faster_rcnn/rpn_msr/proposal_target_layer.py
Python
mit
10,606
0.001603
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- import yaml import numpy as np import numpy.random as n...
:', dontcare_areas.astype(int) # print 'rois: ' # print all_rois[ignore_inds].astype(int) # Select foregroun
d RoIs as those with >= FG_THRESH overlap fg_inds = np.where(max_overlaps >= cfg.TRAIN.FG_THRESH)[0] fg_inds = np.setdiff1d(fg_inds, ignore_inds) # Guard against the case when an image has fewer than fg_rois_per_image # foreground RoIs fg_rois_per_this_image = min(fg_rois_per_image, fg_inds.size) ...
kalikaneko/pyzqm-deb
zmq/backend/cffi/message.py
Python
lgpl-3.0
1,368
0.002924
"""Dummy Frame object""" # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. from ._cffi import ffi, C import zmq try: view = memoryview except NameError: view = buffer _content = lambda x: x.tobytes() if type(x) == memoryview else x class Frame(object): _data =...
.closed = False if track: self.tracker = zmq.MessageTracker() self.buffer
= view(self.bytes) @property def bytes(self): data = _content(self._data) return data def __len__(self): return len(self.bytes) def __eq__(self, other): return self.bytes == _content(other) def __str__(self): if str is unicode: return self.byt...
hos7ein/firewalld
src/firewall/server/firewalld.py
Python
gpl-2.0
109,845
0.002303
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2016 Red Hat, Inc. # # Authors: # Thomas Woerner <twoerner@redhat.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 Li...
elif prop == "IPSet": return dbus.Boolean(self.fw.ipset_enabled) elif prop == "IPSetTypes": return dbus.Array(self.fw.ipset_supported_types, "s") elif prop == "nf_conntrack_helper_setting": return dbus.Boolean(self.fw.nf_conntrack_helper_setting == 1) elif...
onary(self.fw.nf_nat_helpers, "sas") else: raise dbus.exceptions.DBusException( "org.freedesktop.DBus.Error.InvalidArgs: " "Property '%s' does not exist" % prop) @dbus_service_method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signatur...
myt00seven/svrg
cifar/large_gpu_cifar10_ffn.py
Python
mit
20,715
0.009993
#!/usr/bin/env python from __future__ import print_function """ Batch Normalization + SVRG on MNIST Independent Study May 24, 2016 Yintai Ma """ """ # Use SGD AdaGrad instead """ """ under folder of batch_normalization Before merge; number 1 have options for "mlp", "mlpbn"; "sgd" and "custom_svrg2" and "sgd_adagrad...
n3,y_train3 = load_CIFAR_batch(CIFAR_PATH + "data_batch_3") X_train4,y_train4 = load_CIFAR_batch
(CIFAR_PATH + "data_batch_4") X_train5,y_train5 = load_CIFAR_batch(CIFAR_PATH + "data_batch_5") X_test,y_test = load_CIFAR_batch(CIFAR_PATH + "test_batch") X_train = np.concatenate((X_train1,X_train2,X_train3,X_train4,X_train5)) y_train = np.concatenate((y_train1,y_train2,y_train3,y_train4,y_train5)) ...
ghchinoy/tensorflow
tensorflow/python/tpu/tpu_test.py
Python
apache-2.0
6,223
0.008195
# Copyright 2017 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...
s(shape=(128, 32, 32, 16)) scale = array_ops.ones(shape=()) infeed = tpu_feed.InfeedQueue( tuple_types=[dtypes.float32, dtypes.float32], tuple_shapes=[inputs.shape, scale.shape]) def loop(): return training_loop.repeat(5, training_step, infeed_queue=infeed) # This should not thro...
lder(dtype=dtypes.float32, name="a") b = array_ops.placeholder(dtype=dtypes.float32, name="b") constant_op.constant(1.0, name="constant") x = variable_scope.get_variable( name="x", dtype=dtypes.float32, shape=[], use_resource=True, initializer=init_ops...
tomsib2001/speaker-recognition
preprocess.py
Python
mit
4,594
0.012631
# -*- coding: utf-8 -*- from __future__ import division #division en flottants par défaut # Preprocessing primitives import os import numpy as np import octaveIO as oio import subprocess as sp from sklearn import mixture import string def gmm(x, nbG): g=mixture.GMM(n_components=nbG) g.fit(x) return g de...
ose >= 1): print 'Computing mfcc
s...' c = mfcc(wavFile, verbose=verbose) if (verbose >= 1): print 'Done' l=np.size(c, 0) #nombre total de frames if not ngmm: if not (mfccMatching.has_key(nameInDic)): ...
EIREXE/SpaceDock
import-ckan.py
Python
mit
119
0
from SpaceDock.config import _cfg from SpaceDock.objects import * im
por
t json import os # TODO: anything of use
micha-shepher/oervoer-wizard
oervoer-django/oervoer/src/wizard/migrations/0005_auto_20150414_1052.py
Python
gpl-3.0
1,008
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, mi
grations class Migration(migrations.Migration): dependencies = [ ('wizard', '0004_auto_20150331_1815'), ] operations = [ migrations.AddField( model_name='globals', name='MEAL', field=models.IntegerField(default=500), preserve_default=True, ...
field=models.BooleanField(default=False), preserve_default=True, ), migrations.AlterField( model_name='globals', name='REPEATS', field=models.IntegerField(default=150), preserve_default=True, ), migrations.AlterFiel...
retspen/virtmgr
logs/views.py
Python
apache-2.0
2,329
0.035208
# -*- coding: utf-8 -*- import libvirt from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from virtmgr.model.models import * def redir(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/user/login/') else: return HttpResponseRedirect('/dashbo...
if len(credential[4]) == 0: credential[4] = credential[3] elif credential[0] == libvirt.VIR_CRED_PASSPHRASE: credential[4] = request.session['passwd_kvm'] else: return -1 return 0 else: def creds(credentials, user_data): for credential in credentials: if credential[0] == libvi...
en(credential[4]) == 0: credential[4] = credential[3] elif credential[0] == libvirt.VIR_CRED_PASSPHRASE: credential[4] = kvm_host.passwd else: return -1 return 0 conn = vm_conn() if conn != "error": all_vm = get_vms() return render_to_response('logs.html', locals())