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
trungdtbk/faucet
faucet/valve_table.py
Python
apache-2.0
11,432
0.001924
"""Abstraction of an OF table.""" # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2019 The Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fi...
ted.""" return self.set_field(**{valve_of.EXTERNAL_FORWARDING_FIELD: valve_of.PCP_NONEXT_PORT_FLAG}) def set_vlan_vid(sel
f, vlan_vid): """Set VLAN VID with VID_PRESENT flag set. Args: vid (int): VLAN VID Returns: ryu.ofproto.ofproto_v1_3_parser.OFPActionSetField: set VID with VID_PRESENT. """ return self.set_field(vlan_vid=valve_of.vid_present(vlan_vid)) # TODO: verify...
nirdizati/nirdizati-runtime
PredictiveMethods/RemainingTime/batch/PredictiveMonitor.py
Python
lgpl-3.0
3,958
0.002527
""" Copyright (c) 2016-2017 The Nirdizati Project. This file is part of "Nirdizati". "Nirdizati" is free software; you can redistribute it and
/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. "Ni
rdizati" is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with...
Nickil21/Indeed-ML-codesprint-2017
source/data_preprocessing.py
Python
mit
776
0.006443
import re from functools import reduce from nltk import word_tokenize from nltk.corpus import stopwords stop = set(stopwords.words("english")) repls = ("(", ""), (")", ""), ("'s", "") def tokenize(text): lev1 = re.sub("[!#*%:,.;&-]", "", text) # Remove specific chars lev2 = re.sub(r'...
emove non ASCII chars lev3 = reduce(lambda a, kv: a.replace(*kv), repl
s, lev2) # Replace using functional approach tokens = map(lambda word: word.lower(), word_tokenize(lev3)) # Lowercase strings words = [word for word in tokens if word not in stop] # Select words not present in stopwords set return words def join_strings(x): return " ".join(sorted(x...
RCheungIT/phoenix
bin/queryserver.py
Python
apache-2.0
7,659
0.003395
#!/usr/bin/env python ############################################################################ # # 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 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, # W...
ayypot/dillys-place
test.py
Python
bsd-2-clause
3,208
0.063279
#!/usr/bin/python3 from lib.Element import * from lib.Page import * from lib.Site import * import random import shutil import pprint random.seed() def makeChoice(): print( '\nSelect a lib to check: ' ) print( ' (1) Element.py' ) print( ' (2) Page.py' ) print( ' (3) Site.py' ) print( ' (e) Exit test.py' )...
r()) except PageError as why: print( why.reason) print( 'render() OK.') print( 'Testing remove()...') try: test_page.remove( test_element.id) except PageError as why: print( why.reason) print( 'remove() OK.') shutil.rmtree( test_page.name) def
checkSite_py(): print( 'Testing instantiation...') try: test_site = Site( "test_site") except SiteError as why: print( why.reason) print( 'Instantiation OK.') print( 'Testing add()...') test_page = makeDummyPage( test_site.name + '/') test_page.add( makeDummyEle()) test_site.add( test_page) print( 'add()...
ntucker/django-user-accounts
account/forms.py
Python
mit
7,903
0.002657
from __future__ import unicode_literals import re try: from collections import OrderedDict except ImportError: OrderedDict = None from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib import auth from django.contrib.auth import get_user_model from account.conf...
(self): if "password" in self.cleaned_data and "password_confirm" in self.cleaned_data: if self.cleaned_data["password"] != self.cleaned_data["password_confirm"]: raise forms.ValidationError(_("You must ty
pe the same password each time.")) return self.cleaned_data["password_confirm"] class SettingsForm(forms.Form): email = forms.EmailField(label=_("Email"), required=True) timezone = forms.ChoiceField( label=_("Timezone"), choices=[("", "---------")] + settings.ACCOUNT_TIMEZONES, ...
pamfilos/invenio
modules/websubmit/lib/functions/Create_Modify_Interface.py
Python
gpl-2.0
15,906
0.006035
## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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...
Note that the function will display WebSubm
it Response elements, but will not be able to set an initial value: this must be done by the Response element iteself. Additionally the function creates an internal field named 'Create_Modify_Interface_DONE' on the interface, that can be retrieved in curdir after the form has been submitted. Th...
vivekanand1101/fedmsg
fedmsg/tests/common.py
Python
lgpl-2.1
1,482
0
import os import socket import fedmsg.config from nose.tools.nontrivial import make_decorator try: import unittest2 as unittest except ImportError: import unittest def load_config(name='fedmsg-test-config.py'): here = os.path.sep.join(__file__.split(os.path.sep)[:-1]) test_config = os.path.sep.join(...
where and should be encapsulated in a func # Massage the fedmsg config into the moksha config. config['zmq_subscribe_endpoints'] = ','.join( ','.join(bunch) for bunch in config['endpoints'].values() ) hub_name = "twisted.%s" % socket.gethostname().split('.', 1)[0] config['zmq_publish_endpoin...
ires_network(function): """ Decorator to skip tests if FEDMSG_NETWORK is not in os.environ """ @make_decorator(function) def decorated_function(*args, **kwargs): """ Decorated function, actually does the work. """ if not os.environ.get('FEDMSG_NETWORK'): raise unittest.SkipTest("...
DailyActie/Surrogate-Model
01-codes/deap-master/deap/tools/emo.py
Python
mit
22,227
0.001575
from __future__ import division import bisect import math import random from collections import defaultdict from itertools import chain from operator import attrgetter, itemgetter ###################################### # Non-Dominated Sorting (NSGA-II) # ###################################### def selNSGA2(indivi...
r of individuals to select. :param first_front_only: If :obj:`True` sort only the first front and exit. :returns: A list of Par
eto fronts (lists), the first list includes nondominated individuals. .. [Deb2002] Deb, Pratab, Agarwal, and Meyarivan, "A fast elitist non-dominated sorting genetic algorithm for multi-objective optimization: NSGA-II", 2002. """ if k == 0: return [] map_fit_ind = ...
jcdavis/yasp-stats
yasp_util.py
Python
apache-2.0
437
0.032037
import ConfigParser import json def get_player_id(): config = ConfigParser.ConfigParser() config.read('yasp.cfg') return config.get('yasp', 'player_id') def get_hero_id(): config = ConfigParser.ConfigParser() config.read(
'yasp.cfg') return config.get('yasp', 'hero_id') def get_her
o_data(): file = open("heroes.json") data = json.load(file) file.close() return dict([hero['id'], hero] for hero in data['heroes'])
EmreAtes/spack
var/spack/repos/builtin/packages/py-pyani/package.py
Python
lgpl-2.1
2,432
0.000411
############################################################################## # 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...
330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyPyani(PythonPackage): """pyani is a Python3 module that provides support for calculating average nucleotide identity (ANI) and related measures for whole genome compari...
. Where available, it takes advantage of multicore systems, and can integrate with SGE/OGE-type job schedulers for the sequence comparisons.""" homepage = "http://widdowquinn.github.io/pyani" url = "https://pypi.io/packages/source/p/pyani/pyani-0.2.7.tar.gz" version('0.2.7', '239ba630d375a81c...
Arabidopsis-Information-Portal/PMR_API
services/experiments_api/experiments_service.py
Python
gpl-2.0
4,048
0.002717
# PMR WebServices # Copyright (C) 2016 Manhoi Hur, Belyaeva, Irina # This file is part of PMR WebServices API. # # PMR API 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 ...
: """ Retrieves all experiments in json format return experiments in json format :t
ype url: string :param url: request url :type args: string :param args: request parameters :rtype: list :return: Returns list of Experiment objects in json format if success raises exception otherwise """ response = rh.build_payload(url, args, 'list') return response # This function ...
williambout/Aira
wind/air.py
Python
mit
2,815
0.019538
#!/usr/bin/env python import os import re import xively import subprocess import time import datetime import requests import sys temperature = 0 humidity = 0 # extract feed_id and api_key from environment variables FEED_ID = "YOUR_FEED_ID" #CHANGE IT API_KEY = "YOUR_KEY" #CHANG
E IT DEBUG = False # initialize api client api = xively.XivelyAPIClient(API_KEY) # Run the DHT program to get the humidity and temperature readings! def read_dht(): while(True): output = subprocess.check_output(["./Adafruit_DHT", "2302", "4"]); if DEBUG: print output matches = re.search("Temp =\...
([0-9.]+)", output) if (not matches): time.sleep(3) continue humidity = float(matches.group(1)) if DEBUG: print "Temperature: %.1f C" % temperature print "Humidity: %.1f %%" % humidity return {'temperature':temperature,'humidity':humidity} #time.sleep(10) def get_datastr...
dagorim/mytools
ssngen.py
Python
bsd-2-clause
524
0
#!/usr/bin/python ''' Generate ps
eudo-random SSNs and save to a text file. ''' import random try: myfile = open(str(raw_input("Output filename: ")), "w") except ValueError: print "Invalid input. Please enter a valid filename." try: for i in range(int(raw_input("How many random numbers?: "))): line = str(random.randint(100000000,...
rint "User entered invalid input. Please only enter integers." myfile.close()
llou/gpg_ansible
plugins/action_plugins/gpg_key.py
Python
gpl-3.0
45,135
0.004786
#!/usr/bin/python # -*- coding: utf-8 -*- import os import re import types import StringIO from functools import wraps import tempfile import shutil from pipes import quote from ansible.runner.return_data import ReturnData from ansible import utils from ansible.utils import template DEFAULT_KEYRING = "" DEFAULT_GPG_...
extra.write(data) if child_stderr in readables: line = child_stderr.readline() if line == "": status_closed = True child_stderr.close() else: if self.verbose: print line ...
if child_stdout in readables: data = child_stdout.read(self.chunk_size) if data == "": output_closed = True else: result.write_data(data) result.set_code(p.poll()) return result def temporary_homedir(m...
yoziru-desu/locomo-pebble
mock-server/app.py
Python
mit
1,150
0
"""Main Tornado app.""" from tornado import gen from tornado.options import parse_command_line from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.web import Application import logging from tornado.options import options from settin
gs import settings from urls import url_patterns class TornadoApp(Application): """Tornado Applition + rethinkDB + settings.""" def __init__(self): """Init function.""" Application.__init__(self, url_patterns, **settings) @gen.coroutine def main(): """Main function.""" logging.info(...
parse_command_line() if options.debug is True: logging.getLogger().setLevel(logging.DEBUG) logging.info('Running in debug mode') else: logging.getLogger().setLevel(logging.INFO) # Single db connection for everything thanks a lot Ben and Jeese logging.info('starting server on...
eldarion/django-chunked-uploads
docs/conf.py
Python
bsd-3-clause
645
0.00155
import os import sys extensions = [] templates_path = [] source_suffix = '.rst' master_doc = 'index' project = u'django-chunked-upl
oads' copyright_holder = 'Eldarion' copyright = u'2012, %s' % copyright_holder exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' htmlhelp_basename = '%sdoc' % project latex_documents = [ ('index', '%s.tex' % project, u'%s Documentation' % project, copyright_holder, 'manual'), ] man_page...
sion = m.__version__ release = version
timrchavez/capomastro
projects/templatetags/projects_tags.py
Python
mit
543
0
from django.template.base import Library from django.core.urlresolvers import reverse from projects.models import Proj
ectBuild register = Library() @register.simple_tag() def build_url(build_id): """ Fetches the ProjectBuild for a given build_id, if any. """ try: build = ProjectBuild.objects.get(build_id=build_id) return reverse( "project_projectbuild_detail", kwargs={"projec...
except ProjectBuild.DoesNotExist: return ""
ildoc/ildoc.it
publishconf.py
Python
mit
488
0.004098
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future
__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'https://ildoc.dev' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' DELETE_OUTPUT_DIRECTORY = ...
" #GOOGLE_ANALYTICS = ""
eterevsky/animations
pyrene/pbrt.py
Python
mit
4,687
0.007041
import logging import numpy as np import os import subprocess import tempfile from . import scene from . import rman ZERO = scene.npvector((0, 0, 0)) _film = rman.Identifier( 'Film', positional=['string'], named={ 'xresolution': 'integer', 'yresolution': 'integer', 'cropwindow': 'fl...
}) _sampler = rman.Identifier( 'Sampler', positional=['string'], named={ 'pixelsamples': 'integer', }) _area_light_source = rman.Identifier( 'AreaLightSource', positional=['string'], named={'L': 'rgb'}) _translate = rman.Identifier('Translate', positional=['vector']) _rotate = rman.Iden...
ntifier( 'Shape', positional=['string'], named={ 'radius': 'float', 'indices': 'integer[]', 'P': 'point[]' }) class PbrtRenderer(object): def __init__(self, executable=None, output_file=None, scene_file=None, width=384, height=256, samples_per_pixel=None, slaves=No...
intake/filesystem_spec
fsspec/implementations/arrow.py
Python
bsd-3-clause
6,762
0.000739
import errno import io import os import secrets import shutil from contextlib import suppress from functools import wraps from fsspec.spec import AbstractFileSystem from fsspec.utils import infer_storage_options, mirror_from, stringify_path def wrap_exceptions(func): @wraps(func) def wrapper(*args, **kwargs)...
ath).rstrip("/") if self.isdir(path): if recursive: self.fs.delete_dir(path) else: raise ValueError("Can't delete directories without recursive=False") else: self.fs.delete_file(path) @wrap_exceptions def _open(se
lf, path, mode="rb", block_size=None, **kwargs): if mode == "rb": stream = self.fs.open_input_stream(path) elif mode == "wb": stream = self.fs.open_output_stream(path) else: raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}") return A...
sdiehl/rpygtk
rpygtk/runtests.py
Python
gpl-3.0
818
0.02445
import unittest import os from ui import main print os.getcwd() class TestMain(unittest.TestCase): def setUp(self): se
lf.m = m
ain.MainWindow() def test_mainWindow(self): assert(self.m) def test_dataframe(self): import numpy #Random 25x4 Numpy Matrix self.m.render_dataframe(numpy.random.rand(25,4) ,name='devel',rownames=xrange(0,25)) assert(self.m.active_robject) assert(self.m.a...
unixfreak0037/mwzoo
mwzoo.py
Python
mit
1,715
0.004082
#!/usr/bin/env python # vim: ts=4:sw=4:et # # malware zoo # import mwzoo import argparse import os import logging parser = argparse.ArgumentParser(description='MalwareZoo') parser.add_argument( '--mwzoo-home', action='store', dest='mwzoo_home', default=None, required=False, help='Path to the base installation...
sys.exit(1) logging.config.fileConfig(args.logging_co
nfig_path) mwzoo.load_global_config(args.config_path) zoo = mwzoo.MalwareZoo(args.maximum_process_count) zoo.start() logging.info("starting malware zoo http server") mwzoo.HTTPServer(zoo).start()
prologic/mio
tests/test_objects.py
Python
mit
4,906
0
from pytest import raises from mio import runtime from mio.errors import AttributeError, TypeError def test_clone(mio): mio.eval("World = Object clone()") assert mio.eval("World") assert mio.eval("World parent") == runtime.find("Object") def test_type(mio): assert mio.eval("Object type") == "Objec...
out, err = capfd.readouterr() assert out == "Hello World!\n" def test_print_sep(mio, capfd): assert mio.eval("print(1, 2, 3, sep=\", \")").value is None out, err = capfd.readouterr() assert out == "1, 2, 3\n" def test_print_end(mio, capfd): assert mio.eval("print(1, 2, 3, end=\"\")").value is No...
.eval("\"foo\"__repr__()") == "u\"foo\"" def test_str(mio): assert mio.eval("1 __str__()") == "1" assert mio.eval("\"foo\" __str__()") == "foo" def test_bool(mio): assert mio.eval("bool(1)") assert not mio.eval("bool(0)") assert mio.eval("bool(\"foo\")") assert not mio.eval("bool(\"\")") d...
bbengfort/memorandi
reading/__init__.py
Python
apache-2.0
539
0.003711
# reading # Manag
es current reading from sources like Instapaper and Goodreads # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Fri Jan 01 09:01:03 2021 -0500 # # Copyright (C) 2020 Bengfort.com # For license information, see LICENSE # # ID: __init__.py [] benjamin@bengfort.com $ """ Manages current reading from sou...
#################################
ascott1/college-costs
paying_for_college/config/urls.py
Python
cc0-1.0
801
0.001248
from django.conf.urls import url, include from django.conf import settings from paying_for_college.views import LandingView from django.contrib import admin # from django.conf.urls.static import static urlpatterns = [ # url(r'^admin/', include(adm
in.site.urls)), url(r'^$', LandingView.as_view(), name='pfc-landing'), url(r'^compare-financial-aid-and-college-cost/', include('paying_for_college.disclosures.urls', namespace='disclosures')), url(r'^repay-stu
dent-debt/', include('paying_for_college.debt.urls', namespace='debt')), url(r'^guides/', include('paying_for_college.guides.urls', namespace='guides')), ] # if settings.DEBUG: # urlpatterns += static(settings.STATIC_URL, # document_root=settings.STATIC_ROOT)
tony-joseph/livre
items/views.py
Python
bsd-3-clause
22,123
0.001718
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse from django.contrib import messages from django.core.urlresolvers import reverse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPa...
=request.user, ) messages.add_message(request, messages.SUCCESS, 'New language added.') return redirect(language.get_absolute_url()) else: form = LanguageForm() context = { 'form': form, } return render(request, 'items/add-language.html', context) d...
s.""" return render(request, 'items/list-languages.html', {'languages': Language.objects.all()}) def view_language(request, slug): """View to display language details.""" language = get_object_or_404(Language, short_code=slug) return render(request, 'items/view-language.html', {'language': language}...
gpospelov/BornAgain
Examples/fit52_Advanced/multiple_datasets.py
Python
gpl-3.0
6,791
0
""" Fitting example: simultaneous fit of two datasets """ import numpy as np import matplotlib from matplotlib import pyplot as plt import bornagain as ba from bornagain import deg, angstrom, nm def get_sample(params): """ Returns a sample with uncorrelated cylinders and pyramids. """ radius_a = para...
create_real_data(0.4*deg) fit_objective = ba.FitObjective() fit_objective.addSimulationAndData(simulation1, data1, 1.0) fit_objective.addSimulationAndData(simulation2, data2, 1.0) fit_objective.initPrint(10) # creating custom observer which will draw fit progress plotter = PlotObserver() ...
() params.add("radius_a", 4.*nm, min=2.0, max=10.0) params.add("radius_b", 6.*nm, vary=False) params.add("height", 4.*nm, min=2.0, max=10.0) minimizer = ba.Minimizer() result = minimizer.minimize(fit_objective.evaluate, params) fit_objective.finalize(result) if __name__ == '__main__': run...
chatelak/RMG-Py
rmgpy/molecule/parserTest.py
Python
mit
2,890
0.007612
import unittest from rmgpy.molecule.molecule import Molecule from .parser import * class ParserTest(unittest.TestCase): def test_fromAugmentedInChI(self): aug_inchi = 'InChI=1S/CH4/h1H4' mol = fromAugment
edInChI(Molecule(), aug_inchi) self.assertTrue(not mol.InChI == '') aug_inchi = 'InChI=1/CH4/h1H4' mol = fromAugmentedInChI(Molecule(), aug_inchi) self.assertTrue(not mol.InChI == '') def test_toRDKitMol(self): """ Test that toRDKitMol returns correct indices and at...
mol = fromSMILES(Molecule(), 'C1CCC=C1C=O') rdkitmol, rdAtomIndices = mol.toRDKitMol(removeHs=False, returnMapping=True, sanitize=True) for atom in mol.atoms: # Check that all atoms are found in mapping self.assertTrue(atom in rdAtomIndices) # Check that all bond...
amyliu345/zulip
zerver/management/commands/realm_alias.py
Python
apache-2.0
2,022
0.000989
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from zerver.models import Realm, RealmAlias, get_realm, can_add_alias from zer
ver.lib.actions import do_get_realm_aliases import sys class Command(BaseCommand): help = """Manage aliases for the specified realm""" def add_arguments(self, parser): # type: (ArgumentParser) -> None parser.add_argume
nt('-r', '--realm', dest='string_id', type=str, required=True, help='The subdomain or string_id of the realm.') parser.add_argument('--op', dest='op', ...
Krakn/learning
src/python/hackerrank/algorithms/compare_the_triplets/compare_the_triplets.py
Python
isc
597
0.005025
#!/bin/python3 import sys def s
olve(a0, a1, a2, b0, b1, b2): score = [0, 0] alist = [a0, a1, a2] blist = [b0, b1, b2] clist = zip(alist, blist) for pair in clist: if pair[0] > pair[1]: score[0] += 1 elif pair[0] < pair[1]: score[1] += 1 else: continue return s
core a0, a1, a2 = input().strip().split(' ') a0, a1, a2 = [int(a0), int(a1), int(a2)] b0, b1, b2 = input().strip().split(' ') b0, b1, b2 = [int(b0), int(b1), int(b2)] result = solve(a0, a1, a2, b0, b1, b2) print (" ".join(map(str, result)))
taigaio/taiga-back
taiga/base/utils/diff.py
Python
agpl-3.0
1,614
0
# -*- coding: utf-8 -*- # Copyright (C) 2014-present Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ver...
first[key], not_found_value) elif first[key] != second[key]: diff[key] = (first[key], second[key]) # Check all keys in second dict to fi
nd missing for key in second: if key not in first: diff[key] = (not_found_value, second[key]) # Remove A -> A changes that usually happens with None -> None for key, value in list(diff.items()): frst, scnd = value if frst == scnd: del diff[key] # Removed...
yylangchen/Sample_CPP_Cocos2dx
tools/cocos2d-console/bin/cocos_project.py
Python
mit
18,116
0.005078
import os import re import json import cocos class Project(object): CPP = 'cpp' LUA = 'lua' JS = 'js' CONFIG = '.cocos-project.json' KEY_PROJ_TYPE = 'project_type' KEY_HAS_NATIVE = 'has_native' KEY_CUSTOM_STEP_SCRIPT = "custom_step_script" CUSTOM_STEP_PRE_BUILD = "pre-build" ...
list()): raise cocos.CCPluginError("The value of \"%s\" must be one of (%s)" % (Project.KEY_PROJ_TYPE, ', '.join(Project.list_for_display()))) # record the dir & language of the project self._
project_dir = proj_path self._project_lang = lang # if is script project, record whether it has native or not self._has_native = False if (self._is_script_project() and project_info.has_key(Project.KEY_HAS_NATIVE)): self._has_native = project_info[Project.KEY_HAS_NATIVE] ...
patrick91/pycon
backend/api/schedule/types.py
Python
mit
1,130
0
from typing import TYPE_CHECKING, List, Optional import strawberry from api.languages.types import Language from api.submissions.types import Submission from api.users.types import User from strawberry.types.datetime import DateTime if TYPE_CHECKING: # pragma: no cover from api.conferences.types import Conferenc...
tr type: str duration: Optional[int] highlight_color: Optional[str] speakers: List[User]
language: Language audience_level: Optional["AudienceLevel"] @strawberry.field def rooms(self, info) -> List[Room]: return self.rooms.all() @strawberry.field def image(self, info) -> Optional[str]: if not self.image: return None return info.context["request"...
vsco/grpc
tools/run_tests/run_tests.py
Python
bsd-3-clause
56,812
0.010068
#!/usr/bin/env python # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list o...
= False self._docker_distro, self._make_options = self._compiler_options(self.args.use_docker, self.args.compiler) if args.iomgr_platform == "uv": cflags = '-DGRPC_UV ' try: cflags += subprocess.check_output(['pkg-conf
ig', '--cflags', 'libuv']).strip() + ' ' except (subprocess.CalledProcessError, OSError): pass try: ldflags = subprocess.check_output(['pkg-config', '--libs', 'libuv']).strip() + ' '
pastgift/seed-website-py
app/site_users/__init__.py
Python
mit
139
0.007194
# -*- coding:
utf-8 -*- from flask import Blu
eprint site_users_blueprint = Blueprint('site_users', __name__) from . import views, hooks
Alex-Ian-Hamilton/sunpy
sunpy/tests/setup_command.py
Python
bsd-2-clause
4,158
0.000481
# -*- coding: utf-8 -*- """ Created on Sat Jun 7 19:36:08 2014 @author: Stuart Mumford This file is designed to be imported and ran only via setup.py, hence it's dependency on astropy_helpers which will be available in that context. """ from __future__ import absolute_import, division, print_function import os fro...
'P', "The name of a specific package to test, e.g. 'io' or 'utils'. " "If nothing is specified, all default tests are run."), # Print all the things ('verbose-results', 'V', 'Turn on verbose output from pytest.'), # plugins to e
nable ('plugins=', 'p', 'Plugins to enable when running pytest.'), # Run online tests? ('online', 'R', 'Also run tests that do require a internet connection.'), # Run only online tests? ('online-only', None, 'Only run test that do require a internet con...
OaklandPeters/task_logger
task_logger/logger.py
Python
mit
27,065
0.010309
""" @TODO: ProcessLogger().attempts - update/interact based on __enter__/__exit__ @TODO: Review ProcessLoggerABC, and make ProcessLogger inherit from it @TODO: ProcessingAttempt: make uncaught exception in switch_on_exit() cause parent to close all other attempts. @TODO: Write ProcessLoggerABC in task_logger/. Th...
y: del self.data[key] except TypeError as exc: raise KeyError( "'{0}' not found likely because log file is not open.".format(k
ey)) # States used to track state of ProcessingAttempt States = enum.Enum([ ('new','untried'), ('completed','complete','done','finished'), ('errored','error','exception','stopped'), ('attempting','attempted','in progress','in_progress','running') ]) class ProcessingAttempt...
sylvestre/rna
rna/models.py
Python
mpl-2.0
6,479
0.000309
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from datetime import datetime from django.conf import settings from django.db import models from django_extensions.db.f...
reverse=True, key=lambda r: r.version.split('.')[1])[0] def equivalent_android_release(self): if self.product == 'Firefox': return self.equivalent_release_for_product('Firefox for Android') def equivalent_desktop_release(self): if self.product == 'Firefox for Android': ...
release, grouped as either new features or known issues, and sorted first by sort_num highest to lowest, which is applied to both groups, and then for new features we also sort by tag in the order specified by Note.TAGS, with untagged notes coming first, then finally moving any note ...
nbir/gambit-scripts
scripts/LAnhoodAnalysis/src/disp_combined.py
Python
apache-2.0
3,378
0.043517
# Gambit scripts # # Copyright (C) USC Information Sciences Institute # Author: Nibir Bora <nbora@usc.edu> # URL: <http://cbg.isi.edu/> # For license information, see LICENSE import os import sys import numpy import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import FuncFo
rmatter import settings as my sys.path.insert(0, os.path.abspath('..')) # # DISPLACEMENT FROM HOME -
COMBINED PLOTS # DATA = {'all_days': {'hbk': (2.51862656908 , -0.784949777304), 'south-la': (0.443342017512 , -0.584871677246), 'west-la': (1.84785616418 , -0.752511521025), 'south-bay': (1.90968037696 , -0.755235428729)}, 'weekdays': {'hbk': (5.29351309589 , -0.875495033521), 'south-la': (0.44681...
mirageglobe/upp-tracker
tracer/ftraceadvance.py
Python
apache-2.0
6,390
0.006416
from ftracer_script import * ## note the capture details file is ## warnings is needed to suppress errors from mousehook tracker ## Function: This is the main script file which houses all the scripts import sys import pythoncom, pyHook import win32con, win32com.client import win32gui, win32api import codecs imp...
.Window) print 'WindowName:', strutf8encode(event.WindowName) print 'Position:', event.Position
print 'Wheel:', event.Wheel #not used in wheel detection print 'Injected:', event.Injected #rarely used print time.time() if event.WindowName == None: window_name = 'None' else: window_name = event.WindowName ftemp_wfore = strutf8encode(win32gui.GetWindowText(win32g...
akosyakov/intellij-community
python/testData/formatter/trailingBlankLinesWithBackslashesAtFunctionEndNoNewLine.py
Python
apache-2.0
25
0.08
d
ef foo(): pass
\ \ \
phrocker/accumulo
test/system/auto/sleep.py
Python
apache-2.0
856
0
# 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 regar
ding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this fi
le 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 KI...
sussexstudent/falmer
falmer/frontend/views.py
Python
mit
1,727
0.004053
from django.http import Http404, HttpResponse from django.template.context_processors import csrf from rest_framework.authentication import TokenAuthentication from rest_framework.parsers import JSONParser from rest_framework.permissions import DjangoModelPermissions from rest_framework.views import APIView from .model...
request): FrontendDeployment.objects.create( co
ntent=request.data['contents'], ) return HttpResponse(status=200)
d-kiss/candyland
trees/binary_tree.py
Python
gpl-3.0
3,771
0.00053
from immutable import Immutable class BinaryTree(Immutable): """Immutable Binary Tree. Left child always smaller than the parent. Right child always bigger than the parent. Each element exists only once in a binary tree. Attributes: left (BinaryTree): left node. right (BinaryTree...
None, element)) def add_subtree(self, subtree): if subtree is None: return self if self.value == subtree.value: # Need to merge subtree's children with this tree's children new_left = (self.left.add_subtree(subtree.left) if self.left is n...
return BinaryTree(new_left, new_right, self.value) elif subtree.value > self.value: # Element goes on right if self.right is not None: return BinaryTree(self.left, self.right.add_subtree(subtree), self.value) else: r...
zhenxuan00/mmdgm
conv-mmdgm/optimization/optimizer_separated.py
Python
mit
6,121
0.01405
''' Different optimizer for minimization ''' import numpy as np import theano import theano.tensor as T from collections import OrderedDict def shared32(x, name=None, borrow=False): return theano.shared(np.asarray(x, dtype='float32'), name=name, borrow=borrow) def get_momentum_optimizer_max(learning_rate=0.01, ...
): print 'momentum', learning_rate.get_value(), momentum, weight_decay def get_optimizer(w, g, l, d): # Store the parameters in dict or in list #updates = OrderedDict() updates = [] for i in xrange(len(w)): gi = g[i] if weight_decay > 0: ...
mentum * mom + learning_rate * l[i] * (1 - momentum) * gi # Do update w_new = w[i] - mom_new updates = updates + [(w[i], w_new),(mom, mom_new)] return updates return get_optimizer def get_adam_optimizer_max(learning_rate=0.001, decay1=0.1, decay2=0.001, weight_decay=0.0...
AWegnerGitHub/IRVING
irving/dashboard/management/commands/exportirvingdata.py
Python
gpl-2.0
2,221
0.029716
from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from django.core import serializers from django.db.models.loading import get_model from dashboard import models import re, o
s, sys class Command(BaseCommand): args = 'system_model [system_id]' help = 'Exports data and prepares for import in another system' def handle(self, *args, **options): if len(args) > 1: self.dump_system_data(args[0], system_id = args[1]) else: if args[0] == 'Permissions': self.dump_permi
ssions() else: self.dump_system_data(args[0]) def dump_system_data(self, model = None, system_id = None): if model: modelN = get_model(model.split(".")[0],model.split(".")[1]) if modelN == models.QueryData: if not system_id: data = serializers.serialize("json", modelN.objects.all()) d...
bendemott/solr-zkutil
solrzkutil/util.py
Python
mit
13,103
0.0087
from __future__ import unicode_literals from __future__ import print_function import socket import time import six import math import threading from random import choice import logging from kazoo.client import KazooClient from kazoo.client import KazooState from kazoo.protocol.states import EventType fro...
ish its own connections. Connections to Zookeeper are the most time consuming part of most interactions so caching connections enables much
faster running of tests health checks, etc. """ global CONNECTION_CACHE_ENABLED CONNECTION_CACHE_ENABLED = enable def kazoo_client_cache_serialize_args(kwargs): ''' Returns a hashable object from keyword arguments dictionary. This hashable object can be used as the key in another ...
RK70825/TogePy
pkmn_test.py
Python
gpl-2.0
2,964
0.008772
""" togePy.pkmn_test This module tests functionality for togePy """ import pokeStructs import cPickle as pickle import random import numpy as np # Load Data with open('pokedex', 'rb') as f: pokedex = pickle.load(f) with open('abilities', 'rb') as f: abilities = pickle.load(f) with open('items...
eturn moves[random.choice(moves.keys())] def random_Moveset(only_dmg = True): ms = pokeStructs.Moveset() ms.set_All([random_Move(only_dmg) for _ in xrange(4)]) return ms def random_Poke(): def random_EVs(): EV = np.random.randint(256, size=6).astype(float) wh
ile EV.sum() != 510 or any(EV > 255): EV_old = EV if EV.sum() != 510: EV = np.round(510./EV.sum()*EV) EV[EV > 255] = 255 if all(EV_old == EV): EV = np.random.randint(256, size=6).astype(float) return pokeStructs.createEVs(EV....
codeMarble/codeMarble_Web
codeMarble_Web/resource/otherResource.py
Python
gpl-3.0
214
0.004673
# -*- coding: utf-8 -*- TRIPLE_DES_KEY = '1234567812345678' LIMIT_TITLE_VIEW_L
ENGTH = 25 RANK_LIST = 5 BLOCK = 11 LIST = 25 VIEW_SERVER_NOTICE =
2 VIEW_NOTICE = 3 TEXTAREA_ROW = 400 MAX_ROW = 700 REPLY_ROW = 50
pytorch/fairseq
examples/wav2vec/unsupervised/scripts/filter_tsv.py
Python
mit
955
0
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("--tsv", required=True...
: p = os.path.basename(line.split("\t")[0]) p = os.path.splitext(p)[0] return p # filenames to exclude seen = set() with open(params.tsv) as f: if not params.no_skip: root = next(f).rstrip() for line in f: seen.add(get_fname(line)) for i, line in enumerate(sys.stdin): exists =...
eep) if i == 0 or keep: print(line, end="")
mabl/PyPylon
pypylon/__init__.py
Python
bsd-3-clause
142
0.007042
from pyp
ylon.cython.fa
ctory import Factory from pypylon.cython.version import PylonVersion factory = Factory() pylon_version = PylonVersion()
leveille/blog.v1
wurdig/lib/helpers.py
Python
mit
1,130
0.004425
"""Helper functions Consists of functions to typically be used wi
thin templates, but also available to Controllers. This module is available to templates as 'h'. """ from routes import url_for from webhelpers.html import literal from webhelpers.htm
l.secure_form import secure_form from webhelpers.html.tags import * from webhelpers.html.tools import auto_link, mail_to from webhelpers.text import truncate, chop_at, plural from webob.exc import strip_tags from wurdig.lib import auth from wurdig.lib.comment import * from wurdig.lib.cookie import * from wurdig.lib.co...
liweitianux/atoolbox
astro/query_ned.py
Python
mit
3,683
0.004344
#!/usr/bin/env python3 # # Copyright (c) 2016-2018 Weitian LI <wei
tian@aaronly.me> # MIT License # # TODO: # * allow to query by coordinates & radius range # * filter queried results according to the type/other... # * if not queried by name, then try query by coordinates #
""" Query NED with the provided name or coordinate. NASA/IPAC Extragalactic Database: http://ned.ipac.caltech.edu/ References ---------- * astroquery: NedClass https://astroquery.readthedocs.org/en/latest/api/astroquery.ned.NedClass.html """ import sys import argparse import csv from collections import OrderedDict ...
deepmind/pysc2
pysc2/lib/renderer_human.py
Python
apache-2.0
73,287
0.008405
# Copyright 2017 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 ...
th import os import platform import re import subprocess import threading import time import enum from future.builtins import range # pylint: disable=redefined-builtin import numpy as np import pygame import queue from pysc2.lib import buffs from pysc2.lib import colors from pysc2.lib import features from pysc2.lib i...
m pysc2.lib import stopwatch from pysc2.lib import transform from pysc2.lib import video_writer from s2clientprotocol import error_pb2 as sc_err from s2clientprotocol import raw_pb2 as sc_raw from s2clientprotocol import sc2api_pb2 as sc_pb from s2clientprotocol import spatial_pb2 as sc_spatial from s2clientprotocol i...
pyblish/pyblish-maya
pyblish_maya/version.py
Python
lgpl-3.0
230
0
VERSION_MAJOR = 2 VE
RSION_MINOR = 1 VERSION_PATCH = 10 version_info = (VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH) version = '%i.%i.%i' % version_info __version__ = version __all__ = ['version',
'version_info', '__version__']
FelixCao/ProjectEuler
Problem1.py
Python
mit
310
0.016129
#If we li
st all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. Th
e sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. result = 0 for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: result += + i print(str(result)) print(result)
vroncevic/py_util
ats_utilities/singleton/base.py
Python
gpl-3.0
2,465
0
# -*- coding: UTF-8 -*- ''' Module __init__.py Copyright Copyright (C) 2017 Vladimir Roncevic <elektron.ronca@gmail.com> ats_utilities 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, ei...
er__ = 'Vladimir Roncevic' __email__ = 'elektron.ronca@gmail.com' __status__ = 'Updated' class Singleton: ''' Defined class Singleton with attribute(s) and method(s). Created API for auto-register singleton object. It defines: :attributes: | __INSTANCES - class...
or collecting instances. :methods: | __new__ - set class instance. | __str__ - dunder method for Singleton. ''' __INSTANCE = None def __new__(class_, *args, **kwargs): ''' Set class instance. :param *args: iteration object. ...
stweil/letsencrypt
windows-installer/windows_installer/construct.py
Python
apache-2.0
5,560
0.003417
#!/usr/bin/env python3 import ctypes import os import shutil import struct import subprocess import sys import time PYTHON_VERSION = (3, 8, 9) PYTHON_BITNESS = 32 NSIS_VERSION = '3.06.1' def main(): if os.name != 'nt': raise RuntimeError('This script must be run under Windows.') if ctypes.windll.she...
install NSIS through Chocolatey raise RuntimeError('This script must be run wit
h administrator privileges.') if sys.version_info[:2] != PYTHON_VERSION[:2]: raise RuntimeError('This script must be run with Python {0}' .format('.'.join(str(item) for item in PYTHON_VERSION[0:2]))) if struct.calcsize('P') * 8 != PYTHON_BITNESS: raise RuntimeError('...
titilambert/home-assistant
homeassistant/components/bond/fan.py
Python
apache-2.0
4,093
0.001222
"""Support for Bond fans.""" import math from typing import Any, Callable, List, Optional from bond_api import Action, DeviceType, Direction from homeassistant.components.fan import ( DIRECTION_FORWARD, DIRECTION_REVERSE, SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, SPEED_OFF, SUPPORT_DIRECTION, ...
ntity import BondEntity from .utils import BondDevice, BondHub async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up Bond fan devices.""" hub: BondHub = hass.data[DOMAIN][entry.entry_id]
fans = [ BondFan(hub, device) for device in hub.devices if DeviceType.is_fan(device.type) ] async_add_entities(fans, True) class BondFan(BondEntity, FanEntity): """Representation of a Bond fan.""" def __init__(self, hub: BondHub, device: BondDevice): """Create HA entity represe...
sameetb-cuelogic/edx-platform-test
cms/djangoapps/contentstore/views/videos.py
Python
agpl-3.0
12,545
0.001594
""" Views related to the video upload feature """ from boto import s3 import csv from uuid import uuid4 from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseNotFound from django.utils.translation import ugettext as _, ugettext_noop...
encoded string objects, because the CSV module doesn't play well with unicode objects. """ # Translators: This is listed as the duration for a video that has not # yet reached the point in its processing by the servers where its # duration is determined. duration_val = st...
et = dict( [ (name_col, video["client_video_id"]), (duration_col, duration_val), (added_col, video["created"].isoformat()), (video_id_col, video["edx_video_id"]), (status_col, video["status"]), ] + [ ...
blm08/omxWebRemote
manage.py
Python
apache-2.0
255
0
#!/usr/b
in/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "omxwebremote.settings") from django.core.management import execute_from_command_line execute_from_com
mand_line(sys.argv)
kleisauke/pyvips
examples/try16.py
Python
mit
302
0
#!/usr/bin/python3 import logg
ing import sys import pyvips logging.basicConfig(level=logging.DEBUG) # pyvips.cache_set_trace(True) a = pyvips.Image.new_from_file(sys.argv[1]) x = a.erode([[128, 255, 128], [255, 255, 255], [128, 255, 128]]) x.write_to_file(sys.ar
gv[2])
plotly/python-api
packages/python/plotly/plotly/validators/layout/xaxis/_rangebreaks.py
Python
mit
3,243
0.000617
import _plotly_utils.basevalidators class RangebreaksValidator(_plotly_utils.basevalidators.CompoundArrayValidator): def __init__(self, plotly_name="rangebreaks", parent_name="layout.xaxis", **kwargs): super(RangebreaksValidator, self).__init_
_( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Rangebreak"), data_docs=kwargs.pop( "data_docs", """ bounds Sets the lower and upper bounds of this axis ...
Sets the size of each `values` item. The default is one day in milliseconds. enabled Determines whether this axis rangebreak is enabled or disabled. Please note that `rangebreaks` only work for "date" axis type. name ...
pez2001/sVimPy
test_scripts/test5.py
Python
gpl-2.0
172
0.052326
x =
1 x = x + 1 x = x + x + 2 print("x:",x,"\n") x = "Hallo Welt" print("x:",x,"\n") y = "Gute Nacht" print("y:",y,"\n") v = "Und bis morgen"
print("y:"+ y+ " " + v +"\n")
fretboardfreak/potty_oh
experiments/signal_generator.py
Python
apache-2.0
2,261
0
#!/usr/bin/env python3 # Copyright 2016 Curtis Sand
# # 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 # distribute...
uage governing permissions and # limitations under the License. """A basic Signal Generator program.""" from potty_oh import common from potty_oh.signal_generator import Generator def whitenoise(args, generator): """Generate some whitenoise.""" generator.whitenoise() def sin_constant(args, generator):...
dsuch/sec-wall
code/tests/test_constants.py
Python
gpl-3.0
672
0.002976
# -*- coding: utf-8 -*- """ Copyright (C) 2010 Dariusz Suchojad <dsuch at gefira.pl> Licensed under LGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_liter
als # stdlib import re from uuid import uuid4 # nose from nose.tools import assert_true, eq_ def test_constants(): """ Makes sure the number of constants defined is as expected and there are no duplicates amongst them. """ _locals = {} _globals = {} exe
c 'from secwall.constants import *' in _globals, _locals expected = 19 eq_(len(_locals), expected) eq_(len(set(_locals.values())), expected)
ryankaiser/django-super-favicon
favicon/__init__.py
Python
bsd-3-clause
334
0
""" Dja
ngo app for: - Generate favicon in multiple format - Put in a storage backend - Include HTML tags for use favicon """ VERSION = (0, 6, 0) __version__ = '.'.join([str(i) for i in VERSION]) __author__ = 'Anthony Monthe (ZuluPro)' __email__ = 'anthony.monthe@gmail.com' __url__ = '
https://github.com/ZuluPro/django-super-favicon'
cancerregulome/gidget
commands/feature_matrix_construction/main/addGnabFeatures.py
Python
mit
38,773
0.004384
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# # these are system modules import numpy import sys # these are my local ones from env import gidgetConfigVars import tsvIO # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# NA_VALUE = -999999 # -#-#-#-#-...
eList[1:] if (len(geneList) == 0): continue if (len(geneList) == 0): continue pathwayName = cleanUpName(shortPathwayName) if (pathwayName not in pwDict.keys()): # print " adding pathway %s (%d) " % ( pathwayName, len(geneList) ) ...
len(geneList)): # print " substituting shorter list of genes for %s (%d) " % ( # pathwayName, len(geneList) ) pwDict[pathwayName] = geneList # else: # print " NOT substituing list for %s " % pathwayName fh.close() print " " print ...
spahan/unixdmoain
lib/test/Classes.py
Python
bsd-3-clause
1,575
0.013333
import unittest import UniDomain.Classes as Classes #---- unittest Test Classes below here class TestConfig(unittest.TestCase): """Test Config Class""" def test_Config(self): """Check if required config defaults are set""" self.config = Classes.Config() self.assertTrue('plugin_authen' ...
('policydir' in self.config.config, 'no policy directory in default config') self.assertTrue('dnszone' in self.config.config, 'no dnszone in default config') self.assertTrue('passwdfile' in self.config.config, 'no passwdfile in default c
onfig') self.assertTrue('groupfile' in self.config.config, 'no groupfile in default config') def test_readconf(self): """check if readconf behaves like we want""" self.config = Classes.Config(file = 'testconf.xml', passwdfile = 'xyz') self.assertEqual(len(self.config.ldapservers), 1,...
cloakedcode/CouchPotatoServer
couchpotato/core/providers/torrent/thepiratebay/main.py
Python
gpl-3.0
5,523
0.010139
from bs4 import BeautifulSoup from couchpotato.core.helpers.encoding import toUnicode, tryUrlencode from couchpotato.core.helpers.variable import tryInt, cleanHost from couchpotato.core.logger import CPLog from couchpotato.core.providers.torrent.base import TorrentMagnetProvider from couchpotato.environment import Env ...
s')) != None] moderated = (0, 50)[result.find('img', alt = re.compile('Moderator')) != None] return confirmed + trusted + vip + moderated results.append({ 'id': re.search('/(?P<id>\d+)/
', link['href']).group('id'), 'name': link.string, 'url': download['href'], 'detail_url': self.getDomain(link['href']), 'size': self.parseSize(size), 'seeders':...
eHealthAfrica/LMIS
LMIS/locations/urls.py
Python
gpl-2.0
151
0.019868
#!/usr/bin/env python # encoding=utf-8 # locations.urls f
rom dj
ango.conf.urls import patterns, url urlpatterns = patterns('', # ex: /afp/ )
iulian787/spack
var/spack/repos/builtin/packages/ocl-icd/package.py
Python
lgpl-2.1
2,788
0.005022
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class OclIcd(AutotoolsPackage): """This package aims at creating an Open Source alternative to v...
) depends_on('ruby', type='build') depends_on('asciidoc-py3', type='build') depends_on('xml
to', type='build') depends_on('opencl-headers@2.2:', when='+headers') provides('opencl@:2.2', when='@2.2.12:+headers') provides('opencl@:2.1', when='@2.2.8:2.2.11+headers') provides('opencl@:2.0', when='@2.2.3:2.2.7+headers') def flag_handler(self, name, flags): if name == 'cflags' and ...
matrix-org/synapse
scripts-dev/dump_macaroon.py
Python
apache-2.0
532
0
#!/usr/bin/env pyth
on import sys import pymacaroons if len(sys.argv) == 1: sys.stderr.write("usage: %s macaroon [key]\n" % (sys.argv[0],)) sys.exit(1) macaroon_string = sys.argv[1] key = sys.argv[2] if len(sys.argv) > 2 else None macaroon = pymacaroons.Macaroon.deserialize(macar
oon_string) print(macaroon.inspect()) print("") verifier = pymacaroons.Verifier() verifier.satisfy_general(lambda c: True) try: verifier.verify(macaroon, key) print("Signature is correct") except Exception as e: print(str(e))
ryfeus/lambda-packs
pytorch/source/torch/nn/modules/module.py
Python
mit
41,372
0.001015
from collections import OrderedDict import functools import itertools import torch from ..backends.thnn import backend as thnn_backend from ..parameter import Parameter import torch.utils.hooks as hooks def _addindent(s_, numSpaces): s = s_.split('\n') # don't do anything for single-line stuff if len(s) ...
r("module name should be a string. Got {}".format( torch.typename(name))) elif hasattr(self, name) and name not in self._modules: raise KeyError("attribute '{}' already exists".format(name)) elif '.' in name: raise KeyError("module name can't contain \".\"") ...
ule in self.children(): module._apply(fn) for param in self._parameters.values(): if param is not None: # Tensors stored in modules are graph leaves, and we don't # want to create copy nodes, so we have to unpack the data. param.data = fn(...
biswajitsahu/kuma
vendor/packages/translate/storage/placeables/interfaces.py
Python
mpl-2.0
1,302
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # 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...
ses/>. """ This file contains abstract (semantic) interfaces for placeable implementations. """ from translate.storage.placeables.strelem import StringElem class BasePlaceable(StringElem): """Base class for all placeables.""" parse = None class InvisiblePlaceable(BasePlaceable): pass class MaskingP...
e): pass class ReplacementPlaceable(BasePlaceable): pass class SubflowPlaceable(BasePlaceable): pass class Delimiter(object): pass class PairedDelimiter(object): pass
nrego/westpa
lib/examples/stringmethodexamples/examples/Mueller/get_strings.py
Python
gpl-3.0
1,298
0.009245
import numpy as np import westpa import cPickle as pickle def dist(pt1, pt2): return np.sum((pt1-pt2)**2) def mueller(x, y): aa = [-1, -1, -6.5, 0.7] bb = [0, 0, 11, 0.6] cc = [-10, -10, -6.5, 0.7] AA = [-200, -100, -170, 15] XX = [1, 0, -0.5, -1] YY = [0, 0.5, 1.5, 1] V1 = 0 for ...
mgrid[-1.5:1.2:0.01, -0.2:2.0:0.01] assert xx.shape == yy.shape nx = xx.shape[0] ny = xx.shape[1] ene
rgy = mueller(xx, yy) energy -= energy.min() dm = westpa.rc.get_data_manager() dm.open_backing() hashes = dm.we_h5file['bin_topologies']['index']['hash'] mapper = dm.get_bin_mapper(hashes[0]) strings = np.zeros((len(hashes), mapper.centers.shape[0], mapper.centers.shape[1])) for i, hashval in enumerate(hashes): m...
t3dev/odoo
addons/hr_org_chart/models/hr_employee.py
Python
gpl-3.0
1,787
0.003917
# -*- c
oding: utf-8 -*- # Part of Odoo. See LICENSE file for ful
l copyright and licensing details. from odoo import api, fields, models class Employee(models.Model): _name = "hr.employee" _inherit = "hr.employee" child_all_count = fields.Integer( 'Indirect Surbordinates Count', compute='_compute_subordinates', store=False) subordinate_ids = field...
felliott/waterbutler
tests/providers/s3/fixtures.py
Python
apache-2.0
5,588
0.000537
import os from collections import OrderedDict import pytest from waterbutler.providers.s3.metadata import (S3Revision, S3FileMetadata, S3FolderMetadata, S3FolderKeyMetadata, ...
Size=434234, StorageClass='STANDARD', Owner=Orde
redDict( ID='75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a', DisplayName='mtd@amazon.com' ) ) return S3Revision(content) @pytest.fixture def create_session_resp(): file_path = 'fixtures/chunked_uploads/create_session_resp.xml' with open(os.path.join(...
openstack/mistral
mistral/tests/unit/config.py
Python
apache-2.0
992
0
# Copyright 2015 - StackStorm, 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 agr...
itations under the License. import os from oslo_config import cfg def parse_args(): # Look for .mistral.conf
in the project directory by default. project_dir = '%s/../../..' % os.path.dirname(__file__) config_file = '%s/.mistral.conf' % os.path.realpath(project_dir) config_files = [config_file] if os.path.isfile(config_file) else None cfg.CONF(args=[], default_config_files=config_files)
kekoa428/Interview-Prep
words_in_string.py
Python
gpl-3.0
712
0.016854
""" Given a string 's' and a dictionary of words 'dict', determine if s can be segmented into a space-separated sequence of one or more dictionary words. Return true is so, and false otherwise. For example: s = "practicemakespermanent", dict = ["makes", "permanent", "practice"]. f(s) // true """ s = ...
in_string(s): subs = [] for size in range(1, len(s)+1): for index in range(len(s)+1-size): substring = s[index:index+size] subs.append(substring) subs = set(subs) print subs for word in subs: if word in dict: return True else: return False print words_
in_string(s)
OpenJUB/jay
jay/settings.py
Python
mit
2,511
0
""" Django settings for jay project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths in...
) ROOT_URLCONF = 'jay.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplat
es', 'DIRS': [BASE_DIR + "/templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', ...
webcamoid/webcamoid.github.io
internal/tasks.py
Python
agpl-3.0
2,105
0.004276
# -*- coding: utf-8 -*- import os import shutil import sys import datetime from invoke import task from invoke.util import cd from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer CONFIG = { # Local path configuration (can be absolute or relative to tasks.py) 'deploy_path': '..', # Githu...
` 'port': 8000, } @task def clean(c): """Remove generated files""" if os.path.isdir(CONFIG['deploy_path']): shutil.rmtree(CONFIG['deploy_path']) os.makedirs(CONFIG['deploy_path']) @task def build(c): """Build local version of site""" c.run('pelican -s pelicanconf.py') @task def re...
@task def regenerate(c): """Automatically regenerate site upon file modification""" c.run('pelican -r -s pelicanconf.py') @task def serve(c): """Serve site at http://localhost:8000/""" class AddressReuseTCPServer(RootedHTTPServer): allow_reuse_address = True server = AddressReuseTCPServer...
Exploit-install/Veil-Pillage
modules/impacket/smbexec_shell.py
Python
gpl-3.0
2,025
0.004938
""" Execute impacket's smbexec shell on a partiular host. This creates a semi-interactive shell without uploading a binary, but creates lots of shit in the event logs! All cred to the the awesome Impacket project ! https://code.google.com/p/impacket/ Module built by @harmj0y """ from lib import impacket_smbex...
self.description = ("Execute Impacket's smbexec.py module to create a " "semi-interactive shell on a target without "
"uploading any binaries.") # internal list() that holds one or more targets set by the framework self.targets = targets # internal list() that holds one or more cred tuples set by the framework # [ (username, pw), (username2, pw2), ...] self.creds = creds ...
platformio/platformio-core
platformio/commands/device/filters/time.py
Python
apache-2.0
1,381
0
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
r class Timestamp(DeviceMonitorFilter): NAME = "time" def __init__(self, *args, **kwargs): super(Timestamp, self).__init__(*args, **kwargs)
self._line_started = False def rx(self, text): if self._line_started and "\n" not in text: return text timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3] if not self._line_started: self._line_started = True text = "%s > %s" % (timestamp, text) ...
Spirals-Team/apolline-python
apolline/Alphasense_ADC/AlphasenseADC.py
Python
agpl-3.0
3,147
0.010486
#!/usr/bin/env python """ Alphasense ADC Driver for Apolline """ import argparse import se
rial import time from influxdb import InfluxDBClient from influxdb import SeriesHelper class ADCSensor: """ ? Alphasense ADC """ def __init__(self,database='apolline'): self.dbname = database self.parser = argparse.ArgumentParser(description='Apolline agent for Alphasense ADC sensor') ...
uired=False, default='apolline.lille.inria.fr', help='hostname of Apolline backend') self.parser.add_argument('--port', type=int, required=False, default=8086, help='port of Apolline backend') self.parser.add_argument('--device', type=str, required=False, default='/de...
ric2b/Vivaldi-browser
chromium/testing/unexpected_passes_common/expectations_unittest.py
Python
bsd-3-clause
21,813
0.003668
#!/usr/bin/env vpython3 # Copyright 2020 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. from __future__ import print_function import datetime import os import sys import tempfile import unittest if sys.version_info[0] =...
861d0 (Some R. Author {older_date} 00:00:00 +0000 7)[ tag1 ] othertest [ Failure ]""" # pylint: enable=line-too-long blame_output = blame_output.format(today_date=today_str, yesterday_date=yesterday_str, older_date=older_str) ...
lure ] [ tag1 ] othertest [ Failure ]""" self.assertEqual(self.instance._GetNonRecentExpectationContent('', 1), expected_content) def testNegativeGracePeriod(self): """Tests that setting a negative grace period disables filtering.""" today_date = datetime.date.today() yesterday_...
gammu/python-gammu
gammu/worker.py
Python
gpl-2.0
10,344
0
# vim: expandtab sw=4 ts=4 sts=4: # # Copyright © 2003 - 2018 Michal Čihař <michal@cihar.com> # # This file is part of python-gammu <https://wammu.eu/python-gammu/> # # 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 ...
ation with Gammu. It spaws own thread and then passes all commands to this thread. When task is done, caller is notified via callback. """ def __init__(self, callback, pull_func=gammu_pull_device): """ Initializes worker class. @param callback: See L{GammuThread.__init__} for d...
e self._callback = callback self._config = {} self._lock = threading.Lock() self._queue = queue.Queue() self._pull_func = pull_func def enqueue_command(self, command, params): """ Enqueues command. @param command: Command(s) to execute. Each command ...
mylokin/mustache
mustache/template.py
Python
mit
1,242
0.006441
import os import re from . import utils PARTIAL = re.compile('(?P<tag>{{>\s*(?P<name>.+?)\s*}})') PARTIAL_CUSTOM = re.compile('^(?P<whitespace>\s*)(?P<tag>{{>\s*(?P<name>.+?)\s*}}(?(1)\r?\n?))', re.M) # def get_template(path, ext='html', partials=None): # path = os.path.join(TEMPLATES_DIR, '{}.{}'.format(path, ...
(template) for regex in (PARTIAL_CUSTOM, PARTIAL): for match in regex.finditer(template): if partials is None: substitution = get_template(match.group('name')) else: substitution = partials.get(match.group('name'), u'') if substitution: ...
: pass else: substitution = substitution[len(match.group('whitespace')):] template = template.replace(match.group('tag'), substitution) return utils.purify(template)
zhangyuygss/WSL
evaluate/py_demo.py
Python
bsd-3-clause
3,102
0.020954
import numpy as np import sys caffe_root = '/home/guillem/git/caffe/' sys.path.insert(1, caffe_root+'python/') import caffe import cv2 from py_returnCAMmap import py_returnCAMmap from py_map2jpg import py_map2jpg import scipy.io def im2double(im): return cv2.normalize(im.astype('float'), None, 0.0, 1.0, cv2.NORM_MINM...
_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1)) #transformer.set_channel_swap('data', (2,1,0)) # the refe
rence model has channels in BGR order instead of RGB weights_LR = net.params[out_layer][0].data # get the softmax layer of the network # shape: [1000, N] N-> depends on the network image = cv2.imread('img2.jpg') image = cv2.resize(image, (256, 256)) # Take center crop. center = np.array(image.shape[:2]) / 2.0 crop =...
hellowebbooks/hellowebbooks-website
blog/migrations/0001_initial.py
Python
mit
5,381
0.002602
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-03-18 10:05 from __future__ import unicode_literals import datetime from django.db import migrations, models import django.db.models.deletion import modelcluster.contrib.taggit import modelcluster.fields import wagtail.contrib.routable_page.models import wag...
etion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')), ('body', wagtail.core.fields.StreamField((('heading', wagtail.core.blocks.CharBlock(classname='full title')), ('paragraph', wagtail.core.blocks.RichTextBlock()), ('image', wagtail.images.blocks.ImageChooserBlock...
', wagtail.core.blocks.StreamBlock((('heading', wagtail.core.blocks.CharBlock(classname='full title')), ('paragraph', wagtail.core.blocks.RichTextBlock()), ('image', wagtail.images.blocks.ImageChooserBlock())), icon='arrow-right', label='Left column content')), ('right_column', wagtail.core.blocks.StreamBlock((('headin...
vdeluca/tfi
geonode/contrib/dynamic/postgis.py
Python
gpl-3.0
10,137
0.000197
# -*- coding: utf-8 -*- # vim: set fileencoding=utf-8 : # Copyright (C) 2008 Neogeo Technologies # # This file is part of Opencarto project # # Opencarto 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. # # Opencarto is distributed in the hope that it will be useful, # but WITHOUT ANY ...
License for more details. # You should have received a copy of the GNU General Public License # along with Opencarto. If not, see <http://www.gnu.org/licenses/>. # from django import db from django.contrib.gis.gdal import DataSource, SpatialReference, OGRGeometry from django.utils.text import slugify def...
ingenieroariel/webandgis
manage.py
Python
mit
252
0
#!/usr/bin/env python import os
import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webandgis.setting
s") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
keras-team/keras
keras/feature_column/dense_features_test.py
Python
apache-2.0
43,567
0.005624
# Copyright 2019 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...
dding_column_initializer(shape, dtype, partition_info=None): del shape # unused del dtype # unused del partition_info # unused embedding_values = ( (1, 0), # id 0 (0,
1), # id 1 (1, 1)) # id 2 return embedding_values embedding_column = tf.feature_column.embedding_column( categorical_column, dimension=embedding_dimension, initializer=_embedding_column_initializer) dense_features = df.DenseFeatures([embedding_column]) features =...
qiankunshe/sky_engine
sky/tools/skydoc.py
Python
bsd-3-clause
1,262
0.001585
#!/usr/bin/env python # Copyright 2015 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. import argparse import os import subprocess import sys import webbrowser SKY_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)
) SKY_ROOT = os.path.dirname(SKY_TOOLS_DIR) SRC_ROOT = os.path.dirname(SKY_ROOT) WORKBENCH_DIR = os.path.join(SRC_ROOT, 'sky', 'packages', 'workbench') SKY_PACKAGE = os.path.join(SRC_ROOT, 'sky', 'package
s', 'sky') DART_SDK = os.path.join(SRC_ROOT, 'third_party', 'dart-sdk', 'dart-sdk', 'bin') DARTDOC = os.path.join(DART_SDK, 'dartdoc') PUB_CACHE = os.path.join(SRC_ROOT, 'dart-pub-cache') def main(): parser = argparse.ArgumentParser(description='Sky Documentation Generator') parser.add_argument('--open', acti...
gnmiller/craig-bot
craig-bot/lib/python3.6/site-packages/discord/player.py
Python
mit
10,909
0.001467
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2019 Rapptz 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 u...
NCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE...
DEALINGS IN THE SOFTWARE. """ import threading import subprocess import audioop import asyncio import logging import shlex import time from .errors import ClientException from .opus import Encoder as OpusEncoder log = logging.getLogger(__name__) __all__ = ( 'AudioSource', 'PCMAudio', 'FFmpegPCMAudio', ...
qalhata/Python-Scripts-Repo-on-Data-Science
SQL_Det_Pop_Sum_by_Column.py
Python
gpl-3.0
1,516
0.00066
# -*- coding: utf-8 -*- """ Created on Sun Jan 22 23:03:45 2017 @author: Shabaka """ # import pandas import pandas as pd # Import Pyplot as plt from matplotlib import matplotlib.pyplot as plt from sqlalchemy import create_engine # Import func from sqlalchemy.sql import func from sqlalchemy import ...
Print the keys/column names of the results returned print(results[0].keys()) # Create a DataFrame from the results: df df = pd.DataFrame(results) # Set column names df.columns = results[0].keys()
# Print the Dataframe print(df) # Create a DataFrame from the results: df df = pd.DataFrame(results) # Set Column names df.columns = results[0].keys() # Print the DataFrame print(df) # Plot the DataFrame df.plot.bar() plt.show()
node13h/droll
droll/core/tests/factories.py
Python
agpl-3.0
1,048
0
# Copyright (C) 2017 Sergej Alikov <sergej.alikov@gmail.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # ...
. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import fa
ctory from ..models import Link from droll.access.tests.factories import UserFactory class LinkFactory(factory.django.DjangoModelFactory): class Meta: model = Link title = factory.Sequence(lambda n: 'Link nr. {}'.format(n)) user = factory.SubFactory(UserFactory) url = 'http://www.google.com/...
django-leonardo/django-constance
constance/models.py
Python
bsd-3-clause
1,142
0.001751
from django.db.models import signals def create_perm(*args, **kwargs): """ Creates a fake content type and permission to be able to check for permissions """ from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django import VERS...
model='con
fig') permission, created = Permission.objects.get_or_create( name='Can change config', content_type=content_type, codename='change_config') if hasattr(signals, 'post_syncdb'): signals.post_syncdb.connect(create_perm, dispatch_uid="constance.create_perm") else: sig...
balamuruhans/avocado-vt
virttest/libvirt_xml/nwfilter_protocols/base.py
Python
gpl-2.0
3,970
0
""" Common base classes for filter rule protocols """ from six import StringIO from virttest import xml_utils from virttest.libvirt_xml import base, xcepts, accessors class UntypedDeviceBase(base.LibvirtXMLBase): """ Base class implementing common functions for all rule protocol XML w/o a type attr. ...
tag_name=protocol_tag, attribute='type') super(TypedDeviceBase, self).__init__(protocol_tag=protocol_tag, virsh_instance=virsh_instance) # Calls accessor to modify xml self.type_name = type_name @clas...
sh): """ Hides type_name from superclass new_from_element(). """ type_name = element.get('type', None) # subclasses must hide protocol_tag parameter instance = cls(type_name=type_name, virsh_instance=virsh_instance) instance.from_element(ele...