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
tmenjo/cinder-2015.1.0
cinder/volume/manager.py
Python
apache-2.0
115,641
0
# 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 with the License. You may obtain # a ...
ts to :class:`cinder.volume.drivers.lvm.LVMISCSIDriver`. :volume_group: Name of the group that will contain exported volumes (de
fault: `cinder-volumes`) :num_shell_tries: Number of times to attempt to run commands (default: 3) """ import time from oslo_config import cfg from oslo_log import log as logging import oslo_messaging as messaging from oslo_serialization import jsonutils from oslo_utils import excutils from oslo_ut...
joeyginorio/Action-Understanding-with-Rational-Rules
model_src/grid_world.py
Python
mit
9,591
0.033886
# Joey Velez-Ginorio # Gridworld Implementation # --------------------------------- from mdp import MDP from grid import Grid from scipy.stats import uniform from scipy.stats import beta from scipy.stats import expon import numpy as np import random import pyprind import matplotlib.pyplot as plt class GridWorld(MDP):...
) self.valueIteration() self.extractPolicy() def isTerminal(self, state): """ Specifies terminal conditions for gridworld. """ return True if tuple(self.scalarToCoord(state)) in self.grid.objects.values() else False def isObst
acle(self, sCoord): """ Checks if a state is a wall or obstacle. """ if tuple(sCoord) in self.grid.walls: return True if sCoord[0] > (self.grid.row - 1) or sCoord[0] < 0: return True if sCoord[1] > (self.grid.col - 1) or sCoord[1] < 0: return True return False def takeAction(self, sCoord, ...
justincely/classwork
UMD/AST615/HW6_2/plot_orbit.py
Python
bsd-3-clause
1,806
0.035991
import pylab import string import matplotlib matplotlib.rcParams['figure.subplot.hspace']=.45 matplotlib.rcParams['figure.subplot.wspace']=.3 labels=('Step=1','Step=.5','Step=.25','Step=.01') steps=(1,.5,.25,.01) pylab.figure(figsize=(8.5,11)) for i,intxt in enumerate((
'O_RK1.txt','O_RK_5.txt','O_RK_25.txt','O_RK_1.txt')): infile=open(intxt,'r') t=[]
xs=[] ys=[] Es=[] for line in infile.readlines(): line=string.split(line) t.append(float(line[0])) xs.append(float(line[1])) ys.append(float(line[2])) Es.append(float(line[5])) pylab.subplot(4,2,2*i+1) pylab.plot(xs,ys,'-',lw=2) pylab.ylim(-1,1) pylab....
datawire/ambassador
python/tests/kat/t_ingress.py
Python
apache-2.0
16,179
0.00309
import os import sys import json import pytest import subprocess import time from kat.harness import Query, is_ingress_class_compatible from abstract_tests import AmbassadorTest, HTTP, ServiceType from kat.utils import namespace_manifest from tests.utils import KUBESTATUS_PATH from ambassador.utils import parse_bool ...
ext = json.dumps(self.status_update) update_cmd = [KUBESTATUS_PATH, 'Service', '-n', 'default', '-f', f'metadata.name={self.name.k8s}', '-u', '/dev/fd/0'] subprocess.run(update_cmd, input=text.encode('utf-8'), timeout=10) # If you run these tests individually, the time between runni...
e ingress resource actually getting updated is longer than the # time spent waiting for resources to be ready, so this test will fail (most of the time) time.sleep(1) yield Query(self.url(self.name + "/")) yield Query(self.url(f'need-normalization/../{self.name}/')) ...
quattor/aquilon
tests/broker/test_add_alias.py
Python
apache-2.0
18,764
0.001439
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2011,2012,2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licen...
cmd) def test_150_add_alias2diff_environment(self): self.event_add_dns( fqdn='alias2host.aqd-unittest-ut-env.ms.com', dns_environment='ut-env', dns_records=[ { 'target': 'arecord13.aqd-unittest.ms.com', ...
ternal', 'rrtype': 'CNAME' }, ], ) cmd = ['add', 'alias', '--fqdn', 'alias2host.aqd-unittest-ut-env.ms.com', '--dns_environment', 'ut-env', '--target', 'arecord13.aqd-unittest.ms.com', '--target_environment', 'i...
dbbhattacharya/kitsune
kitsune/sumo/tests/test_googleanalytics.py
Python
bsd-3-clause
15,153
0
from datetime import date from mock import patch from nose.tools import eq_ from kitsune.sumo import googleanalytics from kitsune.sumo.tests import TestCase from kitsune.wiki.tests import document, revision class GoogleAnalyticsTests(TestCase): """Tests for the Google Analytics API helper.""" @patch.object...
execute = _build_request.return_value.get.return_value.execute execute.return_value = VISITORS_BY_LOCALE_RESPONSE visits = googleanalytics.
visitors_by_locale( date(2013, 01, 16), date(2013, 01, 16)) eq_(50, len(visits)) eq_(221447, visits['en-US']) eq_(24432, visits['es']) @patch.object(googleanalytics, '_build_request') def test_pageviews_by_document(self, _build_request): """Test googleanalytics.page...
huffpostdata/python-pollster
setup.py
Python
bsd-2-clause
756
0.003968
# coding: utf-8 import sys from setuptools import setup, find_packages NAME = "pollster" VERSION = "2.0.2" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >=
1.15", "six >= 1.10", "certifi", "python-dateutil", "pandas >= 0.19.1"] setup( name=NAME, version=VERSION, description="Pollster
API", author_email="Adam Hooper <adam.hooper@huffingtonpost.com>", url="https://github.com/huffpostdata/python-pollster", keywords=["Pollster API"], install_requires=REQUIRES, packages=find_packages(), include_package_data=True, long_description="""Download election-related polling data fro...
IntegralDefense/ptauto
bin/pt_query.py
Python
apache-2.0
19,839
0.00005
#!/usr/bin/env python3 import argparse import datetime import getpass import json import logging import logging.config import os import re import sys import tabulate import uuid from critsapi.critsapi import CRITsAPI from critsapi.critsdbapi import CRITsDBAPI from lib.pt.common.config import Config from lib.pt.commo...
# Build our mongo connection if args.dev: crits_mongo = CRITsDBAPI(mongo_uri=config.crits.mongo_uri_dev, db_name=config.crits.database) else: crits_mongo = CRITsDBAPI(mongo_uri=config.crits.mongo_uri, db_name=config.crits.datab...
e) crits_mongo.connect() # Connect to the CRITs API crits = CRITsAPI( api_url=crits_url, api_key=crits_api_key, username=crits_username, proxies=crits_proxy, verify=config.crits.crits_verify ) query = args.QUERY.rstrip() # Get the user launching all this user = g...
mvaled/sentry
tests/sentry/api/endpoints/test_monitor_checkins.py
Python
bsd-3-clause
5,664
0.001589
from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from freezegun import freeze_time from sentry.models import CheckInStatus, Monitor, MonitorCheckIn, MonitorStatus, MonitorType from sentry.testutils import APITestCase @freeze_time("2019-01-01") c...
lient.post( "/api/0/monitors/{}/checkins/".format(monitor.guid), data={"status": "error"} ) assert resp.status_code == 404, resp.content def test_deletion_in_progress(self): user = self.create_user() org = self.create_organization(owner=user) team = self...
oject = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, status=MonitorStatus.DELETION_IN_PROGRESS, ...
akx/license-grep
license_grep/models.py
Python
mit
1,190
0.002521
from dataclasses import asdict, dataclass from typing import List, Optional from license_grep.licenses import UnknownLicense, canonicalize_licenses from license_grep.utils import unique_in_order @dataclass class PackageInfo: name: str version: str type: str raw_licenses: Optional[List
[str]] location: str context: Optional[str] @property def licenses(self): for license, canonicalized_license in canonicalize_licenses(self.raw_licenses): yield canonicalized_license @property def licenses_string(self):
return ", ".join( unique_in_order(str(license or "<UNKNOWN>") for license in self.licenses) ) @property def spec(self): return f"{self.name}@{self.version}" @property def full_spec(self): return f"{self.type}:{self.name}@{self.version}" def as_json_dict(self): ...
M4sse/chromium.src
native_client_sdk/src/test_all.py
Python
bsd-3-clause
3,095
0.006462
#!/usr/bin/env python # 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. """Top level script for running all python unittests in the NaCl SDK. """ from __future__ import print_function import argparse i...
h SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) TOOLS_DIR = os.path
.join(SCRIPT_DIR, 'tools') BUILD_TOOLS_DIR = os.path.join(SCRIPT_DIR, 'build_tools') sys.path.append(TOOLS_DIR) sys.path.append(os.path.join(TOOLS_DIR, 'tests')) sys.path.append(os.path.join(TOOLS_DIR, 'lib', 'tests')) sys.path.append(BUILD_TOOLS_DIR) sys.path.append(os.path.join(BUILD_TOOLS_DIR, 'tests')) import bui...
ncclient/ncclient
test/unit/devices/test_alu.py
Python
apache-2.0
1,917
0.003652
import unittest from ncclient.devices.alu import * from ncclient.xml_ import * import re xml = """<rpc-reply xmlns:junos="http://xml.alu.net/alu/12.1x46/alu"> <routing-engin> <name>reX</name> <commit-success/> <!-- This is a comment --> </routing-engin> <ok/> </rpc-reply>""" class TestAluDevice(unittest.TestCase): ...
r'<?xml version="1.0" encoding="UTF-8"?><rpc-reply>', xml) self.assertEqual(expected, to_xml(remove_namespaces(xmlObj))) def test_get_capabilities(self): expected = ["urn:ietf:params:netconf:base:1.0", ] self.assertListEqual(expected, self.obj.get_capabilities()) def test_...
def test_get_xml_extra_prefix_kwargs(self): expected = dict() expected["nsmap"] = self.obj.get_xml_base_namespace_dict() self.assertDictEqual(expected, self.obj.get_xml_extra_prefix_kwargs()) def test_add_additional_operations(self): expected=dict() expected["get_configu...
SahilTikale/haas
hil/cli/network.py
Python
apache-2.0
2,277
0
"""Commands related to networks are in this module""" import click import sys from hil.cli.client_setup import client @click.group() def network(): """Commands related to network""" @network.command(name='create', short_help='Create a new network') @click.argument('network') @click.argument('owner') @click.opti...
ent.network.list() for item in q.items(): sys.stdout.write('%s \t : %s\n' % (item[0], item[1]))
@network.command('list-attachments') @click.argument('network') @click.option('--project', help='Name of project.') def list_network_attachments(network, project): """Lists all the attachments from <project> for <network> If <project> is `None`, lists all attachments for <network> """ print client.n...
elopezga/ErrorRate
ivi/lecroy/lecroyWR64XIA.py
Python
mit
1,644
0.001825
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012 Alex Forencich 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 righ...
NTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .lecroyWRXIA import * class lecroyWR64XIA(lecroyWRXIA): "Lecroy WaveRunner 64Xi-A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__
dict__.setdefault('_instrument_id', 'WaveRunner 64Xi-A') super(lecroy104MXiA, self).__init__(*args, **kwargs) self._analog_channel_count = 4 self._digital_channel_count = 0 self._channel_count = self._analog_channel_count + self._digital_channel_count self._bandwidth = 600e6 ...
HBPNeurorobotics/nest-simulator
testsuite/manualtests/test_pp_psc_delta_stdp.py
Python
gpl-2.0
2,827
0
# -*- coding: utf-8 -*- # # test_pp_psc_delta_stdp.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 ...
'archiver_length' # (printed at the end of the script) import nest import nest.raster_plot import numpy as np import pylab Dt = 1. nsteps = 100 w_0 = 100. nest.ResetKernel() nrn_pre = nest.Create('parrot_neuron') nrn_post1 = nest.Create('iaf_psc_delta') nrn_post2 = nest.Create('pp_psc_delta') nest.Connect(nrn_pre...
2 = nest.GetConnections(nrn_pre, nrn_post2) sg_pre = nest.Create('spike_generator') nest.SetStatus(sg_pre, {'spike_times': np.arange(Dt, nsteps * Dt, 10. * Dt)}) nest.Connect(sg_pre, nrn_pre) mm = nest.Create('multimeter') nest.SetStatus(mm, {'record_from': ['V_m']}) nest.Connect(mm, nrn_post1 + nrn_post2) sd = nest...
jjgomera/pychemqt
lib/EoS/cubic.py
Python
gpl-3.0
18,485
0.000759
#!/usr/bin/python3 # -*- coding: utf-8 -*- r"""Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.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 Softwa...
δ,x [-] firdt: [∂²fir/∂
τ∂δ]x [-] firdd: [∂²fir/∂δ²]τ,x [-] """ b = kw["b"] a = kw["a"] dat = kw["dat"] datt = kw["datt"] dattt = kw["dattt"] Delta1 = kw["Delta1"] Delta2 = kw["Delta2"] R = kw["R"] # This parameters are necessary only for multicomponent mixtures to # calculate fugacity co...
talumbau/webapp-public
webapp/apps/taxbrain/migrations/0003_taxsaveinputs_parameters.py
Python
mit
448
0
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('taxbrain', '0002_taxoutput_tax_result'), ] operations = [ migrations.AddField( model_name='taxsaveinputs', name='parameters', ...
ult=True, ), ]
JackDanger/sentry
src/sentry/api/endpoints/project_filters.py
Python
bsd-3-clause
923
0.001083
from __future__ import absolute_import from rest_framework.response import Response from sentry import filters from sentry.api.bases.project import ProjectEndpoint class ProjectFiltersEndpoint(ProjectEndpoint): def get(self, request, project): """ List a project's filters Retrieve a lis...
roject) results.append({ 'id': filter.id, # 'active' will be either a boolean or list for the legacy browser filters # all other filters will be boolean 'active': filter.is_enabled(), 'description': filter.description, ...
=lambda x: x['name']) return Response(results)
lmazuel/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/virtual_machine_update.py
Python
mit
6,810
0.001028
# 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 ...
]'}, } def __init__(self, **kwargs): super(VirtualMachineUpdate, self).__init__(**kwargs)
self.plan = kwargs.get('plan', None) self.hardware_profile = kwargs.get('hardware_profile', None) self.storage_profile = kwargs.get('storage_profile', None) self.os_profile = kwargs.get('os_profile', None) self.network_profile = kwargs.get('network_profile', None) self.diagnostic...
bdell/pyPWA
pythonPWA/dataTypes/resonance.py
Python
mit
464
0.032328
class resonance(): """ This class represents a resonance. """ def __init__(self,cR=1.0,wR=[],w0=1.,r0=.5,phase=0.): self.wR=wR self.cR=cR self.w0=w0 self.r0=r0 self
.phase=phase def toString(self): """ Returns a string of the resonance data memebers delimited by newlines. """ return "\n".join(["wR="+str(s
elf.wR),"cR="+str(self.cR),"w0="+str(self.w0),"r0="+str(self.r0)])
raymonwu/Managing_Your_Biological_Data_with_Python_3
07-tabular_data/7.4.3_convert_table.py
Python
mit
1,222
0
''' Convert a table from a nested list to a nested dictionary and back. ----------------------------------------------------------- (c) 2013 Allegra Via and Kristian Rother Licensed under the conditions of the Python License This code appears in section 7.4.3 of the book "Managing Biological Data with Py...
---------------------------- ''' table = [ ['protein', 'ext1', 'ext2', 'ext3'], [0.16, 0.038, 0.044, 0.040], [0.33, 0.089, 0.095, 0.091], [0.66, 0.184, 0.191, 0.191], [1.00, 0.280, 0.292, 0.283],
[1.32, 0.365, 0.367, 0.365], [1.66, 0.441, 0.443, 0.444] ] # convert nested list to nested dict nested_dict = {} n = 0 key = table[0] # to include the header , run the for loop over # All table elements (including the first one) for row in table[1:]: n = n + 1 entry = {key[0]: row[0], key[1]: row[1...
klahnakoski/ActiveData
vendor/pyLibrary/aws/s3.py
Python
mpl-2.0
18,596
0.001559
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divisi...
nection: self.connection.close() def __getattr__(self, item): return getattr(self.bucket, item) def get_key(self, key, must_exist=True): if must_exist: meta = self.get_meta(key) if not meta: Log.error( "Key {{key}} does no...
n File(self, key) def delete_key(self, key): # self._verify_key_format(key) DO NOT VERIFY, DELETE BAD KEYS ANYWAY!! try: meta = self.get_meta(key, conforming=False) if meta == None: return self.bucket.delete_key(meta.key) except Exception...
mscuthbert/abjad
abjad/tools/pitchtools/test/test_pitchtools_PitchClass_is_pitch_class_number.py
Python
gpl-3.0
727
0.001376
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_PitchClass_is_pitch_class_number_01(): assert pitchtools.PitchClass.is_pitch_class_number(0) assert pitchtools.PitchClass.is_pitch_class
_number(0.5) assert pitchtools.PitchClass.is_pitch_class_number(11) assert pitchtools.PitchClass.is_pitch_class_number(11.5) def test_pitchtools_PitchClass_is_pitch_class_number_02(): assert not pitchtools.PitchClass.is_pitch_class_number(-1) assert not pitchtools.PitchClass.is_pitch_class_number(-0....
tchClass.is_pitch_class_number('foo')
i5o/openshot-sugar
openshot/openshot/blender/scripts/neon_curves.py
Python
gpl-3.0
5,877
0.020759
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor is free software: you can redistribute it and/or modify # it under the terms of the GNU G...
erial_object = bpy.data.materials["Material.line4"] material_object.diffuse_color = params["line4_color"] # Set the render options. It is important that these are set # to
the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params["output_path"] bpy.context.scene.render.fps = params["fps"] #bpy.context.scene.render.quality = params["quality"] try: bpy.context.scene.render.file_format = params["file_forma...
dotCID/Graduation
Robot code/Sensors/simpleCV_3.py
Python
gpl-2.0
4,363
0.013981
#!/user/bin/python ''' This script uses SimpleCV to grab an image from the camera and numpy to find an infrared LED and report its position relative to the camera view centre and whether it is inside the target area. Attempted stabilisation of the output by tracking a circular object instead and altering exposure of t...
tive = img.colorDistance(color=(255,255,255)).invert() seg_objective = objective.stretch(200,255) blobs = seg_objective.findBlobs() if blobs: center_point = (blobs[-1].x, blobs[-1].y) if frame is renderF
rame: img.drawCircle((blobs[-1].x, blobs[-1].y), 10,SimpleCV.Color.YELLOW,3) img.dl().rectangle2pts((xTgt[0], yTgt[0]), (xTgt[1],yTgt[1]), box_clr) img.show() frame = 0 frame +=1 return center_point if frame is renderFrame: img.dl()...
zomux/nlpy
nlpy/util/feature_container.py
Python
gpl-3.0
1,660
0.001205
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 NLPY.ORG # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html import numpy as np from line_iterator import LineIterator class FeatureContainer(object): def __init__(self, path=None, dtype="libsvm", feature_n=-1): s...
""" Read feature matrix from data :param path: data path :param type: libsvm (only) """ ys = [] xs = [] for line in LineIterator(self.path): items = line.split(" ") feature_map = {} y = 0 for item in items: ...
= int(item) if self.feature_n == -1: max_key = max(feature_map.keys()) if feature_map else 0 else: max_key = self.feature_n features = [] for fidx in range(1, max_key + 1): if fidx in feature_map: featur...
wdmchaft/taskcoach
tests/unittests/widgetTests/DragAndDropTest.py
Python
gpl-3.0
2,283
0.005694
''' Task Coach - Your friendly task manager Copyright (C) 2004-2010 Task Coach developers <developers@taskcoach.org> Task Coach 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 ...
def assertEventIsVetoed(self, event): self.failUnless(event.vetoed) self.failIf(event.allowed) def assertEventIsAllowed(self, event): self.failUnless(event.allowed) self.failIf(event.vetoed) def testEventIsVetoedWhenDragBeginsWithoutItem(self): even...
lf.item) self.treeCtrl.OnBeginDrag(event) self.assertEventIsAllowed(event) def testEventIsAllowedWhenDragBeginWithSelectedItem(self): self.treeCtrl.SelectItem(self.item) event = DummyEvent(self.item) self.treeCtrl.OnBeginDrag(event) self.assertEventIsAllowed(...
kumar303/addons-server
src/olympia/zadmin/views.py
Python
bsd-3-clause
9,220
0
from django import http from django.apps import apps from django.conf import settings from django.contrib import admin from django.core.exceptions import PermissionDenied from django.core.files.storage import default_storage as storage from django.shortcuts import get_object_or_404, redirect from django.views import de...
s = search.get_es() indexes = set(settings.ES_INDEX
ES.values()) es_mappings = { 'addons': get_addons_mappings(), 'addons_stats': get_stats_mappings(), } ctx = { 'index': INDEX, 'nodes': es.nodes.stats(), 'health': es.cluster.health(), 'state': es.cluster.state(), 'mappings': [(index, es_mappings.get(in...
ViaSat/luigi
luigi/format.py
Python
apache-2.0
14,652
0.001092
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
. signal.signal(signal.SIGPIPE, signal.SIG_DFL) return subprocess.Popen(command, stdin=self._input_pipe, stdout=subprocess.PIPE, preexec_fn=subprocess_setup,
close_fds=True) def _finish(self): # Need to close this before input_pipe to get all SIGPIPE messages correctly self._process.stdout.close() if not self._original_input and os.path.exists(self._tmp_file): os.remove(self._tmp_file) if self._input_pipe is ...
munhyunsu/Hobby
2018F_SCSCAlgorithm/week2/card_tests.py
Python
gpl-3.0
528
0
import unittest from card import
Card class CardTest(unittest.TestCase): def test_create(self): suit = 'Hearts' rank = 'Ace' card1 = Card(suit, rank) self.assertEqual((suit, rank), card1.get_value()) def test___eq__(self): card1 = Card('Spades', 'Queen') card2 = Card('Spades', 'Queen') ...
Card('Hearts', 'Queen') self.assertNotEqual(card1, card3) if __name__ == '__main__': unittest.main(verbosity=2)
mandrive/FlaskTest
__init__.py
Python
mit
2,578
0.002327
import logging from logging.handlers import RotatingFileH
andler from flask import Flask, render_template from flask_login import LoginManager from flask_restful import Api from flask_wtf.csrf import CsrfProtect from itsdangerous import URLSafeTimedSerializer from sqlalchemy import create_engine import AppConfig from RestResources.Resources import PostsList, Posts from servi...
st, Admin app = Flask(__name__) CsrfProtect(app) login_serializer = URLSafeTimedSerializer(AppConfig.APPSECRETKEY) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 # set the secret key. keep this really secret: app.secret_key = AppConfig.APPSECRETKEY def register_mods(...
simpleenergy/bughouse-ranking
tests/bughouse/ratings/test_overall_overall_ratings.py
Python
mit
2,377
0
import pytest from bughouse.models import ( BLACK, WHITE, OVERALL_OVERALL, ) from bughouse.ratings.engines.overall import ( rate_teams, rate_players, ) def test_rate_single_game(factories, models, elo_settings): game = factories.GameFactory() r1, r2 = rate_teams(game) assert r1.ratin...
ng_team=team_b)) assert team_a.get_latest_rating(OVERALL_OVERALL) == 1012 assert team_b.get_latest_rating(OVERALL_OVERALL) == 988 @pytest.mark.parametrize( 'losing_color', (BLACK, WHITE), ) def test_individual_ratings(factories, models, losing_color): game = factories.GameFactory(losing_color=los...
rt wtbr.player.get_latest_rating(OVERALL_OVERALL) == 1006 assert ltwr.player.get_latest_rating(OVERALL_OVERALL) == 994 assert ltbr.player.get_latest_rating(OVERALL_OVERALL) == 993 else: wtwr, wtbr, ltwr, ltbr = rate_players(game) assert wtwr.player.get_latest_rating(OVERALL_OVERALL...
OCA/l10n-spain
l10n_es_aeat_mod123/models/__init__.py
Python
agpl-3.0
87
0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from . im
por
t mod123
jrichte43/ProjectEuler
Problem-0283/solutions.py
Python
gpl-3.0
1,243
0.008045
__problem_title__ = "Integer sided triangles for which the area/perimeter ratio is integral" __problem_url___ = "https://projecteuler.net/problem=283" __problem_description__ = "Consider the triangle with sides 6, 8 and 10. It can be seen that the " \ "perimeter and the area are both equal t...
"area/perimeter ratios are equal to positive integers not exceeding " \ "1000." import timeit class Solution(): @staticmethod def solution1(): pass @staticmethod def time_solutions(): setup = 'from __main__ import Solution' p...
s.time_solutions()
profxj/old_xastropy
xastropy/xguis/spec_guis.py
Python
bsd-3-clause
22,801
0.006316
""" #;+ #; NAME: #; spec_guis #; Version 1.0 #; #; PURPOSE: #; Module for Spectroscopy Guis with QT #; These call pieces from spec_widgets #; 12-Dec-2014 by JXP #;- #;------------------------------------------------------------------------------ """ from __future__ import print_function, absolute_import, ...
# Initialize if absid_list is None: # Automatically
search for ID files if srch_id: absid_list = glob.glob(id_dir+'*id.fits') else: absid_list = [] # Grab the pieces and tie together self.abssys_widg = xspw.AbsSysWidget(absid_list) self.pltline_widg = xspw.PlotLinesWidget(status=self.status...
varses/awsch
examples/using_blocks/example1-simpleloop.py
Python
bsd-3-clause
1,304
0.003067
# -*- coding: utf-8 -*- """ example1-simpleloop ~~~~~~~~~~~~~~~~~~~ This example shows how to use the loop block backend and frontend. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ # From lantz, you import a helper function. from...
of iterations # overrun - a boolean indicating if the time required for the operation # is longer than the interval. def measure(counter, iterations, overrun): print(counter, iterations, overrun) data = osci.measur
e() print(data) # You instantiate the loop app = Loop() # and assign the function to the body of the loop app.body = measure # Finally you start the program start_gui_app(app, LoopUi) # This contains a very complete GUI for a loop you can easily create a customized version!
bitmazk/cmsplugin-filer-image-translated
cmsplugin_filer_image_translated/migrations/0004_auto__add_imagetranslationtranslation__add_unique_imagetranslationtran.py
Python
mit
12,501
0.007919
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ImageTranslationTranslation' db.create_table('cmsplugin_filer_image_translated_imagetranslat...
django.db.models.fields.AutoField')(primary_key=True)), ('image', self.gf('django.db.models.fields.related.OneToOneField')(related_name='translation', unique=True, t
o=orm['filer.Image'])), )) db.send_create_signal('cmsplugin_filer_image_translated', ['ImageTranslation']) def backwards(self, orm): # Removing unique constraint on 'ImageTranslationTranslation', fields ['language_code', 'master'] db.delete_unique('cmsplugin_filer_image_translated_...
matternet/ardupilot
libraries/AP_Terrain/tools/create_terrain.py
Python
gpl-3.0
11,310
0.004156
#!/usr/bin/env python ''' create ardupilot terrain database files ''' from MAVProxy.modules.mavproxy_map import srtm import math, struct, os, sys import crc16, time, struct # MAVLink sends 4x4 grids TERRAIN_GRID_MAVLINK_SIZE = 4 # a 2k grid_block on disk contains 8x7 of the mavlink grids. Each # grid block overlaps...
ERRAIN_GRID_BLOCK_SPACING_Y * float(GRID_SPACING)) self.lat = ref_lat self.lon = ref_lon def fill(self, gx, gy, altitude): '''fill a sq
uare''' self.height[gx][gy] = int(altitude) def blocknum(self): '''find IO block number''' stride = east_blocks(self.lat_degrees*1e7, self.lon_degrees*1e7) return stride * self.grid_idx_x + self.grid_idx_y class DataFile(object): def __init__(self, lat, lon): if lat < 0...
sundrome21/FilterZZ
program.py
Python
mit
519
0.001927
import os class Program: socketColorBoTe = "255 255 255 255" socketColorBa = "77 87 152 255" progColorRareBoTe = "0 0 0 255" progColorRareBa = "240 220 180 255
" progColorElseBoTe = "77 87 152 255" progColo
rElseBa = "0 0 0 255" def createFile(self): filepath = os.path.join('~/dest', "filterZZ.filter") if not os.path.exists('~/dest'): os.makedirs('~/dest') setattr(self, 'f', open(filepath, "w")) def addNewLine(self): self.f.write("\n\n")
timberline-secondary/hackerspace
src/courses/migrations/0016_grades_initialdata.py
Python
gpl-3.0
963
0.001038
# Generated by Django 2.2.12 on 2020-05-09 06:28 from django.db import migrations # Can't use fixtures because load_fixtures method is janky with django-tenant-schemas def load_initial_data(apps, schema_editor): Grade = apps.get_model('courses', 'Grade') # add some initial data if none has been created yet ...
de.objects.create( name="10", value=10 ) Grade.objects.create( name="11", value=11 ) Grade.objects.create( name="12", value=12 ) class Migration(migrations.Migration): dependencies = [ ('course...
200508_1957'), ] operations = [ migrations.RunPython(load_initial_data), ]
slackhq/python-slackclient
slack/web/async_slack_response.py
Python
mit
6,347
0.000788
"""A Python module for interacting and consuming responses from Slack.""" import logging import slack.errors as e from slack.web.internal_utils import _next_cursor_is_present class AsyncSlackResponse: """An iterable container of response data. Attributes: data (dict): The json-encoded content of th...
removed at anytime. """ def __init__( self, *, client, # AsyncWebClient http_verb: str, api_url: str, req_args: dict, data: dict, headers: dict, status_code: int, ):
self.http_verb = http_verb self.api_url = api_url self.req_args = req_args self.data = data self.headers = headers self.status_code = status_code self._initial_data = data self._iteration = None # for __iter__ & __next__ self._client = client ...
saltstack/salt
salt/states/ddns.py
Python
apache-2.0
4,297
0.000699
""" Dynamic DNS updates =================== Ensure a DNS record is present or absent utilizing RFC 2136 type dynamic updates. :depends: - `dnspython <http://www.dnspython.org/>`_ .. note:: The ``dnspython`` module is required when managi
ng DDNS using a TSIG key. If you are not using a TSIG key, DDNS is allowed by ACLs based on IP address and the ``dnspython`` module is not required. Example: .. code-block:: yaml webserver: ddns.present: - zone: example.com - ttl: 60 - data: 111.222.333.444 - nameser...
__virtual__(): if "ddns.update" in __salt__: return "ddns" return (False, "ddns module could not be loaded") def present(name, zone, ttl, data, rdtype="A", **kwargs): """ Ensures that the named DNS record is present with the given ttl. name The host portion of the DNS record, e.g....
rabipanda/tensorflow
tensorflow/python/debug/wrappers/local_cli_wrapper.py
Python
apache-2.0
25,959
0.003929
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
arsers["print_feed"] = command_parser.get_print_tensor_argparser( "Print the value of a feed in feed_dict.") def add_tensor_filter(self, filter_name, tensor_filter): """Add a tensor filter. Args: filter_name: (`str`) name of the filter. tensor_filter: (`callable`) the filter callable. Se...
ession_init(self, request): """Overrides on-session-init callback. Args: request: An instance of `OnSessionInitRequest`. Returns: An instance of `OnSessionInitResponse`. """ return framework.OnSessionInitResponse( framework.OnSessionInitAction.PROCEED) def on_run_start(self...
kevgathuku/compshop
store/tests/test_forms.py
Python
bsd-3-clause
1,654
0.008464
from django.test import TestCase from store.forms import ReviewForm from store.models import Review from .factories import * class ReviewFormTest(TestCase): def test_form_validation_for_blank_items(self): p1 = ProductFactory.create() form = ReviewForm( data={'name':'', 'text': '', '...
prod = ProductFactory.create() form = ReviewForm( data={'name':'Kevin', 'text': 'Review', 'rating': 3, 'product':prod.id}) new_review = form.save() self.assertEqual(new_review, Review.objects.first()) self.assertEqual(new_review.name, 'Kevin') self.assertEq...
iew.product, prod)
veryberry/website-addons
website_crm_sales_team/__openerp__.py
Python
lgpl-3.0
361
0.024931
{ "name" : "Add
sales team to website leads (OBSOLETE)",
"version" : "0.1", "author" : "IT-Projects LLC, Ivan Yelizariev", 'license': 'GPL-3', "category" : "Website", "website" : "https://yelizariev.github.io", "depends" : ["website_crm"], #"init_xml" : [], #"update_xml" : [], #"active": True, "installable": True }
jeonghoonkang/BerePi
apps/check/monitor.py
Python
bsd-2-clause
1,308
0.021407
#-*- coding: utf-8 -*- # Author : Jeonghoonkang, github.com/jeonghoonkang import platform import sys import os import time import traceback import requests import RPi.GPIO as GPIO from socket import gethostname hostname = gethostname() SERVER_ADDR = '211.184.76.80' GPIO.setwarnings(False) GPIO.cleanup() GPIO.setm...
ating def query_last_data_point(bridge_id): url = 'http://%s/api/raw_bridge_last/?bridge_id=%d' % (SERVER_ADDR, bridge_id) try: ret = requests.get(url, timeout=10) if ret.ok: ctx = ret.json() if ctx['code'] == 0: return ctx['result']['time'], ctx['resu
lt']['value'] except Exception: #print Exception pass return None bridge_id = int(hostname[5:10]) GPIO.output(26, True) # server connection is OK, showing through LED while True: try: ret = query_last_data_point(bridge_id) except: pass if ret is not None: t, v = ret if t...
CLLKazan/iCQA
qa-engine/forum/templatetags/extra_tags.py
Python
gpl-3.0
7,925
0.007823
import time import os import posixpath import datetime import math import re import logging from django import template from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision from django.util...
class ItemSeparatorNode(template.Node): def __init__(self, separator): sep = separator.strip() if sep[0] == sep[-1] and sep[0] in ('\'', '"'): sep = sep[1:-1] else: raise template.TemplateSyntaxError('separator in joinitems tag must be quoted') sel
f.content = sep def render(self, context): return self.content class BlockMediaUrlNode(template.Node): def __init__(self, nodelist): self.items = nodelist def render(self, context): prefix = settings.APP_URL + 'm/' url = '' if self.items: url += '/' ...
EricIO/pasteit
pasteit/PasteSites.py
Python
gpl-2.0
3,878
0.005931
# Copright (C) 2015 Eric Skoglund # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in t...
': return Mozilla() else: raise NotSupported("This site is not supported") def parse(self, args): """ Internal method used by the PasteSite class. Returns a dictionary of the parsed input arguments. Parses the arguments given at the command line. Man...
Site. See the slexy class for an example of how to implement this method for subclasses. """ self.data = args def paste(self): """Posts the data to the paste site. This method tries to post the data to the paste site. If the resulting request does not have ...
sadanandb/pmt
src/pyasm/prod/checkin/maya_checkin_test.py
Python
epl-1.0
1,263
0.008709
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
nd import Command from pyasm.prod.biz import Asset from pyams.prod.maya import * from maya_checkin import * class MayaCheckinTest(unittest.TestCase): def setUp(my): batch = Batch() def test_all(my): # create a scene that will be checked in asset_code = "prp101" sid = "12345"...
mel('sphere -n sphere1') mel('circle -n circle1') mel('group -n |%s |circle1 |sphere1' % asset_code ) # convert node into a maya asset node = MayaNode("|%s" % asset_code ) asset_node = MayaAssetNode.add_sid( node, sid ) # checkin the asset checkin = MayaAss...
sandeepdsouza93/TensorFlow-15712
tensorflow/contrib/learn/python/learn/learn_io/pandas_io.py
Python
apache-2.0
6,001
0.004999
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
pe='" + data[column].dtype.name + "'") for column in bad_data] raise ValueError('Data type
s for extracting pandas data must be int, ' 'float, or bool. Found: ' + ', '.join(error_report)) def extract_pandas_matrix(data): """Extracts numpy matrix from pandas DataFrame. Args: data: `pandas.DataFrame` containing the data to be extracted. Returns: A numpy `ndarray` of the D...
aarestad/euler-solutions
euler_38.py
Python
gpl-2.0
471
0.029724
f
rom euler_functions import is_pandigital_set, number_digits for x in range(9123, 9876): # much smaller range: http://www.mathblog.dk/project-euler-38-pandigital-multiplying-fixed-number/ products = [] n = 1 num_digits_in_products = 0 while num_digits_in_products < 9: products.append(x * n) n += 1 num_dig...
mezz64/home-assistant
tests/components/yeelight/test_init.py
Python
apache-2.0
22,950
0.001438
"""Test Yeelight.""" import asyncio from datetime import timedelta from unittest.mock import AsyncMock, patch import pytest from yeelight import BulbException, BulbType from yeelight.aio import KEY_CONNECTED from homeassistant.components.yeelight.const import ( CONF_DETECTED_MODEL, CONF_NIGHTLIGHT_SWITCH, ...
ack_discovery(hass: HomeAssistant): """Test Yeelight ip changes and we fallback to discovery.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_ID: ID, CONF_HOST: "5.5.5.5"}, unique_id=ID ) config_entry.add_to_hass(hass) mocked_fail_bulb = _mocked_bulb(cann
ot_connect=True) mocked_fail_bulb.bulb_type = BulbType.WhiteTempMood with patch( f"{MODULE}.AsyncBulb", return_value=mocked_fail_bulb ), _patch_discovery(): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.st...
nburn42/tensorflow
tensorflow/python/grappler/hierarchical_controller.py
Python
apache-2.0
43,598
0.005069
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tensorflow.python.training import training_util class PlacerParams(object): """Class to
hold a set of placement parameters as name-value pairs. A typical usage is as follows: ```python # Create a PlacerParams object specifying names and values of the model # parameters: params = PlacerParams(hidden_size=128, decay_steps=50) # The parameters are available as attributes of the PlacerParams o...
osamak/medcloud-registration
register/temp/views.py
Python
agpl-3.0
9,644
0.002771
# -*- coding: utf-8 -*- import json import os import random import requests import re import subprocess import string from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.core.mail import send_mail from djang...
stration fields = ['email', 'college', 'number', 'unisersity_id'] widgets = { 'university_id': forms.T
extInput(), } class ResetPasswordForm(forms.Form): email = forms.EmailField(label=u'بريدك الجامعي', max_length=100) @csrf_exempt def register(request): if request.method == 'POST': password = generate_password() initial_registration = Registration(password=password) form = Regi...
InspectorIncognito/visualization
AndroidRequests/migrations/0904_transformation_eventforbusv2_half_hour_period.py
Python
gpl-3.0
2,254
0.00976
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils import timezone from django.db import models, migrations def fill_tables(apps, schema_editor): eventsforbusv2 = apps.get_model('AndroidRequests', 'EventForBusv2') eventsforbusstop = apps.get_model('AndroidRequests', 'EventForBus...
bjects.get(initial_time__lte = creationTime , end_time__gte = creationTime) ev.halfHourPeriod = hhperiod ev.save() class Migration(migrations.Migration): dependencies = [ ('AndroidRequests', '0903_transformation_halfhourperiod'), ] operations = [ migrations.AddField( ...
reignKey(verbose_name=b'Half Hour Period', to='AndroidRequests.HalfHourPeriod', null=True), preserve_default=False, ), migrations.AddField( model_name='eventforbusstop', name='halfHourPeriod', field=models.ForeignKey(verbose_name=b'Half Hour Period', to='A...
zooko/egtp
common/MojoErrors.py
Python
agpl-3.0
355
0.014085
import exceptions # throws by anything which doesn't like what was passed to it class DataError(exceptions.StandardError): pass # thrown by MojoMessage class MojoMessageError(DataError): pass #
thrown by DataTypes class BadFormatError(DataError): pass #
throws by things which do block reassembly class ReassemblyError(IOError): pass
babadoo/zml
setup.py
Python
bsd-3-clause
1,343
0.018615
from setuptools import setup setup( name = "zml", packages = ["zml"], version = "0.8.1", description = "zero markup language", author = "Christof Hagedorn", author_email = "team@zml.org", url = "http://www.zml.org/", download_url = "https://pypi.python.org/pypi/zml", keywords = ["zml...
TTP :: WSGI", "Topic :: Software Development :: Libraries :: Python Modules", ], long_description = """\ zml - zero markup language ------------------------------------- Features - zero markup templates - clean syntax - extensible - components - namespaces - lean code This ve
rsion requires Python 3 or later. """ )
jsirois/pants
src/python/pants/help/help_info_extracter.py
Python
apache-2.0
19,574
0.002963
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses import inspect import json from dataclasses import dataclass from enum import Enum from typing import Any, Callable, Dict, Generic, L...
ted: Tuple[OptionHelpInfo, ...] def collect_unscoped_flags(self) -> List[str]: flags: List[str] = [] for options in (self.basic, self.advanced, self.
deprecated): for ohi in options: flags.extend(ohi.unscoped_cmd_line_args) return flags def collect_scoped_flags(self) -> List[str]: flags: List[str] = [] for options in (self.basic, self.advanced, self.deprecated): for ohi in options: ...
xeechou/mkblogs
mkblogs/tests/build_tests.py
Python
bsd-2-clause
10,943
0.001828
#!/usr/bin/env python # coding: utf-8 import os import shutil import tempfile import unittest from mkdocs import build, nav, config from mkdocs.compat import zip from mkdocs.exceptions import MarkdownNotFound from mkdocs.tests.base import dedent class BuildTests(unittest.TestCase): def test_empty_document(self...
xpected = '<p>An <a href="http://example.com/external.md">external link</a>.</p>' html, toc, meta = build.convert_markdown(md_text) self.assertEqual(html.strip(), expected.strip()) def test_not_use_directory_urls(self): md_text = 'An [internal link](internal.md) to another document.' ...
to another document.</p>' pages = [ ('internal.md',) ] site_navigation = nav.SiteNavigation(pages, use_directory_urls=False) html, toc, meta = build.convert_markdown(md_text, site_navigation=site_navigation) self.assertEqual(html.strip(), expected.strip()) def t...
siosio/intellij-community
python/testData/intentions/PyInvertIfConditionIntentionTest/commentsIf.py
Python
apache-2.0
136
0.014706
def func(): value = "not
-none" # Is none <caret>if value is Non
e: print("None") else: print("Not none")
sckott/pygbif
pygbif/utils/wkt_rewind.py
Python
mit
1,305
0.003065
from geojson_rewind import rewind from geomet import wkt import decimal import statistics def wkt_rewind(x, digits=None): """ reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean num...
Decimal(str(w)).as_tuple().exponent for w in nums] digits = abs(statistics.mean(dec_n)) else: if not isinstance(digits, int): raise TypeError("'digits' must be an int") wound = rewind(z) back_to_wkt = wkt.dumps(wound, decimals=digits) return back_to_wkt # from http
s://stackoverflow.com/a/12472564/1091766 def __flatten(S): if S == []: return S if isinstance(S[0], list): return __flatten(S[0]) + __flatten(S[1:]) return S[:1] + __flatten(S[1:])
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_8_0/device_service_service_broker.py
Python
apache-2.0
49,305
0.002109
from ..broker import Broker class DeviceServiceServiceBroker(Broker): controller = "device_service_services" def show(self, **kwargs): """Shows the details for the specified device service service. **Inputs** | ``api version min:`` None | ``api version max:`` N...
ach device service service returned and included in the output. Available methods are: parent_device_service, child_device_service, data_source, device. :type methods: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False ...
include in the output. The listed associations will be returned as outputs named according to the association name (see outputs below). Available includes are: parent_device_service, child_device_service, data_source, device. :type include: Array of String | ``api version min:`` None ...
ColinIanKing/autotest
server/autoserv.py
Python
gpl-2.0
8,389
0.001788
""" Library for autotest-remote usage. """ import sys, os, re, traceback, signal, time, logging, getpass try: import autotest.common as common except ImportError: import common from autotest.client.shared.global_config import global_config require_atfork = global_config.get_config_value( 'AUTOSERV', ...
chines) if machines: for machine in machines: if not machine or re.search('\s', machine): parser.parser.error("Invalid m
achine: %s" % str(machine)) machines = list(set(machines)) machines.sort() if group_name and len(machines) < 2: parser.parser.error("-G %r may only be supplied with more than one machine." % group_name) kwargs = {'group_name': group_name, 'tag': execution_tag} if con...
automl/SpySMAC
cave/reader/configurator_run.py
Python
bsd-3-clause
16,612
0.003792
import copy import logging import os import tempfile from collections import OrderedDict from contextlib import contextmanager import numpy as np from pimp.importance.importance import Importance from smac.runhistory.runhistory import RunHistory, DataOrigin from smac.utils.io.input_reader import InputReader from smac....
cenario.cs.get_default_configuration() self.incumbent = self.trajectory[-1]['incumbent'] if self.trajectory else None self.feature_names = self._get_feature_names() # Create combined runhistory to collect all "real" runs self.combined_runhistory = RunHistory() self.combined_runh...
if self.validated_runhistory is not None: self.combined_runhistory.update(self.validated_runhistory, origin=DataOrigin.EXTERNAL_SAME_INSTANCES) # Create runhistory with estimated runs (create Importance-object of pimp and use epm-model for validation) self.epm_runhistory = RunHistory()...
django-stars/dash2011
presence/apps/workflow/admin.py
Python
bsd-3-clause
703
0
from
django.cont
rib import admin from workflow.models import State, StateLog, NextState, Project, Location from workflow.activities import StateActivity class NextStateInline(admin.StackedInline): model = NextState fk_name = 'current_state' extra = 0 class StateAdmin(admin.ModelAdmin): inlines = [NextStateInline, ...
chuckeles/genetic-treasures
test_instruction_set.py
Python
mit
2,849
0.002808
import unittest import instruction_set class TestInstructionSet(unittest.TestCase): def test_generate(self): self.assertIsInstance(instruction_set.generate(), list) self.assertEqual(len(instruction_set.generate()), 64) self.assertEqual(len(instruction_set.generate(32)), 32) inse...
instruction_set.crossover(parent1, parent2) random_children = instruction_set.crossover(parent1, parent2, take_random=True) self.assertIsInstance(children, tuple) self.assertIsInstance(children[0], list)
self.assertIsInstance(children[1], list) self.assertEqual(len(children[0]), len(parent1)) self.assertEqual(len(children[1]), len(parent1)) for i, _ in enumerate(parent1): self.assertTrue( (children[0][i] in parent1 and children[1][i] in parent2) or ...
OliverCole/ZeroNet
src/Test/TestContent.py
Python
gpl-2.0
12,511
0.004876
import json import time from cStringIO import StringIO import pytest from Crypt import CryptBitcoin from Content.ContentManager import VerifyError, SignError from util.SafeRe import UnsafePatternError @pytest.mark.usefixtures("resetSettings") class TestContent: privatekey = "5KUh3PvNm5HUWoCfSUfcYvfQ2g3PrRNJWr6Q...
] == "content.json" assert site
.content_manager.getFileInfo("data/users/hello.png")["content_inner_path"] == "data/users/content.json" assert site.content_manager.getFileInfo("data/users/content.json")["content_inner_path"] == "data/users/content.json" assert not site.content_manager.getFileInfo("notexist") # Optional file ...
studybuffalo/studybuffalo
study_buffalo/rdrhc_calendar/migrations/0014_auto_20171016_1922.py
Python
gpl-3.0
813
0
# pylint: disable=missing-module-docstring, missing-class-docstring from __future__ import unicode_literals from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrati
ons.swappable_dependency(settings.AUTH_USER_MODEL), ('rdrhc_calendar', '0013_auto_20171016_1915'), ] operations = [ migrations.RenameField( model_name='shift', old_name='user', new_name='sb_user', ), migrations.RenameField( model_n...
e='user', new_name='sb_user', ), migrations.AlterUniqueTogether( name='shiftcode', unique_together=set([('code', 'sb_user', 'role')]), ), ]
SDoc/py-sdoc
sdoc/sdoc1/data_type/StringDataType.py
Python
mit
3,015
0
from sdoc.sdoc1.data_type.DataType import DataType class StringDataType(DataType): """ Class for string data types. """ # ------------------------------------------------------------------------------------------------------------------ def __init__(self, value: str): """ Object c...
pe.StringDataType.StringDataType """ return StringDataType(self._value) # ------------------------------------------------------------------------------------------------------------------ def get_value(self) -> str: """ Returns the underling value of this data type. """...
-------------------------------------------------------- def get_type_id(self) -> int: """ Returns the ID of this data type. """ return DataType.STRING # ------------------------------------------------------------------------------------------------------------------ def is...
mitmproxy/mitmproxy
test/mitmproxy/addons/test_intercept.py
Python
mit
1,632
0
import pytest from mitmproxy.addons import intercept from mitmproxy import exceptions from mitmproxy.test import taddons from m
itmproxy.test import tflow @pytest.mark.asyncio async def test_simple(): r = intercept.Intercept() with taddons.context(r) as tctx: assert not r.filt tctx.configure(r, intercept="~q") assert r.filt assert tctx.options.intercept_active with pytest.raises(exceptions.Optio...
tive tctx.configure(r, intercept="~s") f = tflow.tflow(resp=True) await tctx.cycle(r, f) assert f.intercepted f = tflow.tflow(resp=False) await tctx.cycle(r, f) assert not f.intercepted f = tflow.tflow(resp=True) r.response(f) assert f....
glemaitre/scikit-learn
examples/svm/plot_svm_nonlinear.py
Python
bsd-3-clause
1,136
0.002641
""" ============== Non-linear SVM ============== Perform binary classification using non-linear SVC with RBF kernel. The target to predict is a XOR of the inputs. The color map illustrates the decision function learned by the SVC. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn imp...
oint on the grid Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.imshow(Z, interpolation='nearest
', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', origin='lower', cmap=plt.cm.PuOr_r) contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linestyles='dashed') plt.scatter(X[:, 0], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired, edgecolors='k') pl...
AnnalisaS/migration_geonode
geonode/layers/models.py
Python
gpl-3.0
29,589
0.004968
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # 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 versio...
e: params['height'] = height # Avoid using urllib.urlencode here because it breaks the url. # commas and slashes in values get encoded and then cause trouble # with the WMS parser. p = "&".join("%s=%s"%item for item in params.items())
return ogc_server_settings.LOCATION + "wms/reflect?" + p def verify(self): """Makes sure the state of the layer is consistent in GeoServer and Catalogue. """ # Check the layer is in the wms get capabilities record # FIXME: Implement caching of capabilities record site wi...
taurenk/Flask-Angular-TaskList
backend/app/user_api.py
Python
mit
1,159
0.001726
__author__ = 'tauren' from flask import abort from flask_restful import Resource from flask.ext.restful import fields, marshal, reqparse from flask_login import current_user from models import User, db user_fields = { 'username': fields.String, 'id
': fields.Integer, 'uri': fields.Url('user') } class UserApi(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=True, help='No username provided', location='json') sel...
super(UserApi, self).__init__() def post(self): args = self.reqparse.parse_args() new_user = User(args['username'], args['password']) db.session.add(new_user) db.session.commit() return 201 def get(self): user = User.query.filter_by(id=current_user.id).al...
MansoorMajeed/encrypted-notes
app/forms.py
Python
gpl-2.0
138
0.014493
from flask
.ext.wtf import Form from w
tforms import StringField, BooleanField, PasswordField, SelectField, DateTimeField, TextAreaField
bugobliterator/MAVProxy
MAVProxy/modules/mavproxy_map/mp_elevation.py
Python
gpl-3.0
3,785
0.004756
#!/usr/bin/python ''' Wrapper for the SRTM module (srtm.py) It will grab the altitude of a long,lat pair from the SRTM database Created by Stephen Dade (stephen_dade@hotmail.com) ''' import os import sys import time import numpy from MAVProxy.modules.mavproxy_map import srtm class ElevationModel(): '''Elevation...
%.1f FPS" % (lat, lon, alt, 1/(t1
-t0))) lat = opts.lat+0.001 lon = opts.lon+0.001 t0 = time.time() alt = EleModel.GetElevation(lat, lon, timeout=10) t1 = time.time()+.000001 print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0))) lat = opts.lat-0.001 lon = opts.lon-0.001 t0 = tim...
osrg/bgperf
quagga.py
Python
apache-2.0
5,099
0.003334
# Copyright (C) 2016 Nippon Telegraph and Telephone Corporation. # # 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...
E), 'w') as
f: f.write(config) for n in list(flatten(t.get('neighbors', {}).values() for t in scenario_global_conf['testers'])) + [scenario_global_conf['monitor']]: f.write(gen_neighbor_config(n)) if 'policy' in scenario_global_conf: seq = 10 for...
digibyte/digibyte
test/lint/check-rpc-mappings.py
Python
mit
6,062
0.003299
#!/usr/bin/env python3 # Copyright (c) 2009-2019 The Bitcoin Core developers # Copyright (c) 2014-2019 The DigiByte Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Check RPC argument consistency.""" from collect...
line) assert m, 'No match to table expression: %s' % line name = parse_string(m.group(1)) idx = int(m.group(2)) argname = parse_string(m.group(3)) cmds.app
end((name, idx, argname)) assert not in_rpcs and cmds return cmds def main(): root = sys.argv[1] # Get all commands from dispatch tables cmds = [] for fname in SOURCES: cmds += process_commands(os.path.join(root, fname)) cmds_by_name = {} for cmd in cmds: cmds_by_name[...
eliben/luz-cpu
luz_asm_sim/lib/asmlib/linker.py
Python
unlicense
17,370
0.001267
# Linker - the linker for assembled objects # # Input: one or more ObjectFile objects # Output: an executable suitable for loading into the Luz # simulator or CPU memory. # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # import pprint, os, sys, string from collections import defaultdict from ..commonl...
self): sp_ptr = self.initial_offset + se
lf.mem_size - 4 startup_code = LINKER_STARTUP_CODE.substitute(SP_POINTER=sp_ptr) asm = Assembler() startup_object = asm.assemble(str=startup_code) return startup_object def _compute_segment_map(self, object_files, offset=0): """ Compute a segment memory map from the list of...
testing-cabal/extras
setup.py
Python
mit
1,687
0.000593
#!/usr/bin/env pytho
n """Distutils installer for extras.""" from setuptools import setup import os.path import extras testtools_cmd = extras.try_import('t
esttools.TestCommand') def get_version(): """Return the version of extras that we are building.""" version = '.'.join( str(component) for component in extras.__version__[0:3]) return version def get_long_description(): readme_path = os.path.join( os.path.dirname(__file__), 'README.rs...
laudaa/bitcoin
test/functional/segwit.py
Python
mit
42,732
0.007208
#!/usr/bin/env python3 # Copyright (c) 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the SegWit changeover logic.""" from test_framework.test_framework import BitcoinTestFramework fr...
CTransaction, CT
xIn, COutPoint, CTxOut, COIN, ToHex, FromHex from test_framework.address import script_to_p2sh, key_to_p2pkh, key_to_p2sh_p2wpkh, key_to_p2wpkh, script_to_p2sh_p2wsh, script_to_p2wsh, program_to_witness from test_framework.script import CScript, OP_HASH160, OP_CHECKSIG, OP_0, hash160, OP_EQUAL, OP_DUP, OP_EQUALVERIFY, ...
neonbadger/DestinationUnknown
yelp_api.py
Python
mit
2,082
0.004803
"""Yelp API setup and random business selection function""" import io import json import random from yelp.client import Client from yelp.oauth1_authenticator import Oauth1Authenticator with io.open('config_yelp_secret.json') as cred: creds = json.load(cred) auth = Oauth1Authenticator(**creds) yelp_clien...
'acupuncture', 'ayurveda', 'chiropractors', 'venues', 'galleries', 'landmarks', 'gardens', 'museums', 'paintandsip', 'beaches'] night_activity = ['cabaret', 'movietheaters', 'musicvenues', 'opera', 'theater', 'cocktailbars', 'lounges', 'sportsbars', 'wine_bar', ...
= ['wineries', 'farmersmarket', 'cafes', 'bakeries', 'bubbletea', 'coffee', 'restaurants','beer_and_wine', 'icecream', 'gourmet', 'juicebars', 'asianfusion', 'japanese', 'seafood', 'breweries'] def yelp_random_pick(event, city): """Generate a top business pick for user.""" if ...
tkingless/webtesting
venvs/dev/lib/python2.7/site-packages/selenium/webdriver/support/select.py
Python
mit
9,249
0.003027
# Licensed to the
Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for addi
tional information # regarding copyright ownership. The SFC 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 requir...
mick-d/nipype
nipype/interfaces/minc/tests/test_auto_Voliso.py
Python
bsd-3-clause
1,379
0.023205
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..minc import Voliso def test_Voliso_inputs(): input_map = dict(args=dict(argstr='%s', ), avgstep=dict(argst
r='--avgstep', ), clobber=dict(argstr='--clobber', usedefault=True, ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), input_file=dict(argstr='%s', mandatory=True, position=-2, ), maxstep=dict(argstr='--maxs...
, name_template='%s_voliso.mnc', position=-1, ), terminal_output=dict(deprecated='1.0.0', nohash=True, ), verbose=dict(argstr='--verbose', ), ) inputs = Voliso.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): ...
yephper/django
django/contrib/gis/db/models/functions.py
Python
bsd-3-clause
16,825
0.002377
from decimal import Decimal from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.sql import AreaField from django.contrib.gis.measure import ( Area as AreaMeasure, Distance as DistanceMeasure, ) from django.core.exceptions import FieldError from django.db.models i...
# No version parameter self.source_expressions.pop(0) return super(AsKML, self).as_sql(compiler, connection) class AsSVG(GeoFunc): output_field_class = TextField def __init__(self, expression, relative=False, precision=8, **extra): relative = relative if hasattr(rel...
, 'precision', six.integer_types), ] super(AsSVG, self).__init__(*expressions, **extra) class BoundingCircle(GeoFunc): def __init__(self, expression, num_seg=48, **extra): super(BoundingCircle, self).__init__(*[expression, num_seg], **extra) class Centroid(OracleToleranceMixin,...
bendudson/freegs
freegs/_aeqdsk.py
Python
lgpl-3.0
12,250
0.001551
""" fields - Lists the variables stored in the file, a default value, and a description """ from . impo
rt _fileutils as fu import warnings # List of file data variables, default values, and documentation # This is used in both reader and writer fields = [ ( "tsaisq", 0.0, "total chi2 from magnetic probes, flux loops, Rogowski and external coils", ), ("rcencm", 100.0, "major radius i...
toroidal magnetic field in Tesla at RCENCM"), ("pasmat", 1e6, "measured plasma toroidal current in Ampere"), ("cpasma", 1e6, "fitted plasma toroidal current in Ampere-turn"), ("rout", 100.0, "major radius of geometric center in cm"), ("zout", 0.0, "Z of geometric center in cm"), ("aout", 50.0, "plas...
nicko96/Chrome-Infra
appengine/test_results/appengine_module/test_results/handlers/test/redirector_test.py
Python
bsd-3-clause
1,228
0.008143
# Copyright 2014 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 unittest from appengine_module.test_results.handlers import redirector class RedirectorTest(unittest.TestCase): def test_url_from_commit_position...
astG91kaV9uxC3-P-4NolRM6s/U8-bHfeejPZOn0ELRGhed-nrIX4\\\"" }''' % (git_sha, git_sha) old_load_url = redirector.load_url try: redirector.load_url = mock_load_url expected = ('https://chromium.googlesource.com/chromium/src/+log/' 'aaaaaaa^..bbbbbbb?pretty=fuller') self.assertEqual(redi...
nally: redirector.load_url = old_load_url
roscopecoltran/scraper
.staging/meta-engines/xlinkBook/outline.py
Python
mit
2,141
0.012611
#!/usr/bin/env python # -*- coding: utf-8-*- import getopt import time import re import os,sys reload(sys) sys.setdefaultencoding('utf-8') from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from bs4 import BeautifulSoup import requests import webbrowser import subprocess class Ou...
toOutline(self, source): if source.endswith('.pdf') and source.startswith('http') == False: items = '' for item in self.getToc(source): items += item[1] + '\n' return items elif source.startswith('http'):
#url = 'https://gsnedders.html5.org/outliner/process.py?url=' + source #webbrowser.open(url) r = requests.get('https://gsnedders.html5.org/outliner/process.py?url=' + source) return r.text #soup = BeautifulSoup(r.text) #for li in soup.find_all('li'): ...
o-kei/design-computing-aij
ch5/curve.py
Python
mit
983
0.001017
import numpy as np import matplotlib.pyplot as plt def bernstein(t, n, i): cn = 1.0 ci = 1.0 cni = 1.0 for k in range(2, n, 1): cn = cn * k for k in range(1, i, 1): if i == 1: break ci = ci * k for k in range(1, n - i + 1, 1): if n == i: ...
ef bezierplot(t, cp): n = len(cp) r = np.zeros([len(t), 2]) for k in range(len(t)): sum1 =
0.0 sum2 = 0.0 for i in range(1, n + 1, 1): bt = bernstein(t[k], n, i) sum1 += cp[i - 1, 0] * bt sum2 += cp[i - 1, 1] * bt r[k, :] = [sum1, sum2] return np.array(r) cp = np.array([[0, -2], [1, -3], [2, -2], [3, 2], [4, 2], [5, 0]]) t = np.arange(0, 1 + 0....
pygraz/old-flask-website
pygraz_website/tests/test_filters.py
Python
bsd-3-clause
1,577
0.005707
from pygraz_website import filters class TestFilters(object): def test_url_detection(self): """ Test that urls are found correctly. """ no_urls_string = '''This is a test without any urls in it.''' urls_string = '''This string has one link in it: http://pygraz.org . But it a...
p://pygraz.org">http://pygraz.org</a> . But it also has some text after it :D''' assert filters.urlize(urls_string, True).matches == {'urls': set(['http://pygraz.org'])} assert filters.urlize(None) == u'' assert filters.urlize("'http://test.com'") == """'<a href="http://test.com">http://test
.com</a>'""" def test_namehandles(self): """ Tests the discory of linkable names. """ string_with_handles = 'Hallo @pygraz.' assert filters.urlize(string_with_handles) == 'Hallo <a href="http://twitter.com/pygraz">@pygraz</a>.' assert filters.urlize(string_with_handl...
jhasse/sleeptimer
main.py
Python
gpl-3.0
8,446
0.004026
#!/usr/bin/env python3 import configparser, subprocess, platform import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib, Gdk class SleepTimer(Gtk.Builder): def __init__(self): super().__init__() self.add_from_file("main.glade") self.connect_signals(self) sel...
.destroy() Gtk.main_quit() return False self.spin_buttons[0].set_value(hours - 1)
self.spin_buttons[1].set_value(minutes - 1) self.spin_buttons[2].set_value(seconds - 1) self.css_provider.load_from_data(".install-progress {{ background-size: {}%; }}".format( int(self.get_seconds_left() * 100 / self.start_seconds_left) ).encode()) return True ...
imincik/gis-lab
utils/send-message.py
Python
gpl-3.0
1,440
0.008333
#!/usr/bin/env python """ Send message to '#gis.lab' IRC chat room. Requires to run script 'utils/join-gislab-network.py' first to get connection with server. USAGE: send-message.py <message> """ import os, sys import re import socket try: message = sys.argv[1] except IndexError: print __doc__ sys.exit(0...
TWORK = get_config("GISLAB_NETWORK") HOST="{0}.5".format(GISLAB_NETWORK) PORT=6667 NICK=IDENT=os.environ['USER'] REALNAME="script" CHANNEL="gis.lab" s=socket.socket( socket.AF_INET, soc
ket.SOCK_STREAM ) s.connect((HOST, PORT)) print s.recv(4096) s.send("NICK %s\r\n" % NICK) s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) s.send("JOIN #%s\r\n" % CHANNEL) s.send("PRIVMSG #gislab :%s\r\n" % message) s.send("QUIT: End of message.\r\n") s.recv(4096) s.close() print "Done." # vim: ts=8 sts=4 s...
wxwilcke/MINOS
directives/pakbonLD_B3.py
Python
gpl-3.0
7,661
0.00496
#!/usr/bin/python3 import logging from operator import itemgetter from timeit import default_timer as timer import rdflib from .abstract_instruction_set import AbstractInstructionSet from readers import rdf from writers import rule_set, pickler from samplers import by_definition as sampler from algorithms.semantic_rul...
hyperparameters["max_cbs_
size"] = 4 hyperparameters["minimal_local_support"] = 0.0 hyperparameters["minimal_support"] = 0.0 hyperparameters["minimal_confidence"] = 0.0 print(" Importing Data Sets...") dataset = self.load_dataset(abox, tbox) print(" Initiated Pattern Learning...") output...
TUDelftNAS/SDN-NaaSPlatform
NaaSPlatform/Load_Balancing_App.py
Python
gpl-3.0
62,701
0.003397
#!/usr/bin/env python # -*- coding: utf-8 -*- # #Copyright (C) 2015, Delft University of Technology, Faculty of Electrical Engineering, Mathematics and Computer Science, Network Architectures and Services and TNO, ICT - Service Enabling and Management, Mani Prashanth Varma Manthena, Niels van Adrichem, Casper van den ...
r more details. # # You should have received a copy of the GNU General Public License # along with NaaSPlatform. If not, see <http://www.gnu.org/licenses/>. # Network-as-a-Service (NaaS) platform's load balancing application # Importing Python modules import sys # Python module for system (i.e. interpreter) spec...
rt time # Python module to perform various time related functions # Importing NaaS platform's main application for performing NaaS related operations and functions from Main_App import * # Importing NaaS platform's sFlow based edge flow monitoring application for monitoring and detecting large traffic flows at t...
simonolander/euler
euler-106.py
Python
mit
450
0.002222
import it
ertools import numpy import math def ncr(n, r): f = math.factorial return f(n) // f(r) // f(n-r) def subset_pairs(s):
for a_size in range(1, len(s)): for a in itertools.combinations(s, a_size): remaining = s.difference(a) for b_size in range(1, len(remaining) + 1): for b in itertools.combinations(remaining, b_size): yield a, b [11, 18, 19, 20, 22, 25]
pliniopereira/ccd10
src/business/configuration/configProject.py
Python
gpl-3.0
2,363
0.003386
from PyQt5 import QtCore from src.business.configuration.constants import project as p from src.ui.commons.verification import cb class ConfigProject: def __init__(self): self._settings = QtCore.QSettings(p.CONFIG_FILE, QtCore.QSettings.IniFormat) def get_value(self, menu, value): return sel...
Lunar, lunarph, lunarpos): self._settings.beginGroup(p.SUN_MOON_TITLE) self._settings.setValue(p.MAX_SOLAR_ELEVATION, solarelev) self._settings.setVal
ue(p.IGNORE_LUNAR_POSITION, ignoreLunar) self._settings.setValue(p.MAX_LUNAR_PHASE, lunarph) self._settings.setValue(p.MAX_LUNAR_ELEVATION, lunarpos) self._settings.endGroup() def save_settings(self): self._settings.sync() def get_site_settings(self): return self.get_va...
ArcticWarriors/scouting-app
ScoutingWebsite/Scouting2017/model/get_stastics.py
Python
mit
4,360
0.004358
from Scouting2017.model.models2017 import ScoreResult from django.db.models.aggregates import Avg from django.db.models.expressions import Case, When import json import math import collections def get_statistics(regional_code, teams_at_competition, team=0): ''' The get_statistics function() returns two lists ...
sr_rope = 0 - rope_avg sr_gear = sr.tele_gears - gear_avg sr_fuel = ((sr.auto_fuel_high_score) + (sr.tele_fuel_high_score / 3)) - fuel_avg gear_v2 += sr_gear * sr_gear fuel_v2 += sr_fuel * sr_fuel rope_v2 += sr_rope * sr_rope num_srs += 1 if num_srs == 0:...
tdev = 0 fuel_stdev = 0 rope_stdev = 0 else: gear_stdev = math.sqrt(gear_v2 / num_srs) fuel_stdev = math.sqrt(fuel_v2 / num_srs) rope_stdev = math.sqrt(rope_v2 / num_srs) team_avgs = collections.defaultdict(int) # This part of the function (above) obtains overall st...
miing/mci_migo
identityprovider/fields.py
Python
agpl-3.0
1,229
0
# Copyright 2010 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import re from django import forms from django.utils.translation import ugettext as _ from identityprovider.widgets import CommaSeparatedWidget class CommaSeparatedField(forms.M...
# remove any whitespace from the string if value: value = value.strip().replace(' ', '') value = super(OATHPasswordField, self).clean(value) if self.SIX.match(value): return value elif self.EIGHT.ma
tch(value): return value raise forms.ValidationError( _('Please enter a 6-digit or 8-digit one-time password.'))
ganga-devs/ganga
ganga/GangaGUI/test/test_internal_templates_api.py
Python
gpl-3.0
3,358
0.001489
from GangaCore.testlib.GangaUnitTest import GangaUnitTest from GangaGUI.api import internal # ******************** Test Class ******************** # # Templates API Tests class TestGangaGUIInternalTemplatesAPI(GangaUnitTest): # Setup def setUp(self, extra_opts=[]): super(TestGangaGUIInternalTemplat...
# Flask test client self.app = internal.test_client() # Templates API - GET Method def test_GET_method_templates_list(self): from GangaCore.GPI import templates, JobTemplate, GenericSplitter, Local # Create 20 test templates for i in range(0, 20):
t = JobTemplate() t.name = f"Template Test {i}" t.application.exe = "sleep" t.splitter = GenericSplitter() t.splitter.attribute = 'application.args' t.splitter.values = [['3'] for _ in range(0, 3)] t.backend = Local() # GET request...
CamJam-EduKit/EduKit3
CamJam Edukit 3 - RPi.GPIO/Code/7-pwm.py
Python
mit
2,662
0
# CamJam EduKit 3 - Robotics # Worksheet 7 - Controlling the motors with PWM import RPi.GPIO as GPIO # Import the GPIO Library import time # Import the Time library # Set the GPIO modes GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Set variables for the GPIO motor pins pinMotorAForwards = 10 pinMotorABackwards ...
ChangeDutyCycle(Stop) pwmMotorBForwards.ChangeDutyCycle(Stop) pwmMotorBBackwards.ChangeDutyCycle(DutyCycle) # Your code to control the robot goes below this line forwards() time.sleep(1) # Pause for 1 second left() time.sleep(0.5) # Pause for half a second forwards() time.sleep(1) right() time.sleep(0.5)...
nup()
thezakman/CTF-Scripts
Differ.py
Python
artistic-2.0
631
0.011094
#!/usr/bin/python # Script to Che
ck the difference in 2 files # 1 fevereiro de 2015 # https://github.com/thezakman file1 = raw_input('[file1:] ') modified = open(file1,"r").readlines()[0] file2 = raw_inpu
t('[file2:] ') pi = open(file2, "r").readlines()[0] # [:len(modified)] resultado = "".join( x for x,y in zip(modified, pi) if x != y) resultado2 = "".join( x for x,y in zip(pi, modified) if x != y) print "[Differ:] print '\n-------------------------------------' print "[file1] -> [file2]", resultado print '---------...