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
sbordt/markovmixing
markovmixing/tests/test_distributions.py
Python
mit
612
0.055556
import mark
ovmixing as mkm import numpy def tets_distributions(): # not distributions d = numpy.ones((3,3)) assert(mkm.is_distribution(d) == False) d = mkm.delta_distribution(10) d[1] = 1 assert(mkm.is_distribution(d) == False) assert(mkm.is_distribution(mkm.delta_distribution(10),n=11) == False) assert(mkm.is_distr...
,1,1e-16]),numpy.array([0.001,1,1e-16])) if __name__=="__main__": tets_distributions()
ssato/python-anyconfig
tests/api/load/test_multi_types.py
Python
mit
423
0
# # Copyright (C) 2021 Satoru SATOH <satoru.satoh@gmail.com> #
License: MIT # # pylint: disable=missing-docstring, relative-beyond-top-level from ..multi_load import test_multi_types as multi from ..single_load import test_multi_types as single from . import common class SingleTestCase(common.SingleBase, single.TestCase): pass class MultiTestCase(common.Mult
iBase, multi.TestCase): pass # vim:sw=4:ts=4:et:
hansroh/skitai
tests/level3/test_futures.py
Python
mit
6,757
0.037591
import skitai import confutil import pprint def test_futures (app, dbpath): @app.route ("/") def index (was): def respond (was, rss): return was.response.API (status_code = [rs.status_code for rs in rss.dispatch ()], a = rss.a) reqs = [ was.get (...
as): def repond (was, rss): return was.response.API (status_code_db = [rs.status_code for rs in rss.dispatch ()], b = rss.b, status_code = rss.status_code) def checkdb (was, rss): reqs = [was.backend ("@sqlite").execute ('SELECT * FROM stocks WHERE symbol=?', ('RHAT',))...
egin (): reqs = [ was.get ("@pypi/project/skitai/"), was.get ("@pypi/project/rs4/") ] return was.Tasks (reqs, a = 100).then (checkdb) begin () @app.route ("/3") def index3 (was): def respond (was, rss): ...
mravikumar281/staging-server
postman/forms.py
Python
mit
8,644
0.002892
""" You may define your own custom forms, based or inspired by the following ones. Examples of customization: recipients = CommaSeparatedUserField(label=("Recipients", "Recipient"), min=2, max=5, user_filter=my_user_filter, channel='my_channel', ) can_overwrite_limits = Fals...
channel and hasattr(self.fields['recipients'], 'set_arg'): self.fields['recipients'].set_arg(channel) error_messages = { 'filtered': _("Writing to some users is not possible: {users}."), 'filtered_user': _("{username}"), 'filtered_user_with_reason': _("{username} ({reason})"...
xchange.""" recipients = self.cleaned_data['recipients'] exchange_filter = getattr(self, 'exchange_filter', None) if exchange_filter: errors = [] filtered_names = [] recipients_list = recipients[:] for u in recipients_list: try: ...
jefftc/changlab
web2py/gluon/myregex.py
Python
mit
743
0.036339
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ import re # pattern to find defined tables regex_tables = re.compile( """^[\w]+\.define_table\(\s...
d functions in controller regex_expose = re.compile( '^def\s+(?P<name>(?:[a-zA-Z0-9]\w*)|(?:_[a-zA-Z0-9]\w
*))\(\)\s*:', flags=re.M) regex_include = re.compile( '(?P<all>\{\{\s*include\s+[\'"](?P<name>[^\'"]*)[\'"]\s*\}\})') regex_extend = re.compile( '^\s*(?P<all>\{\{\s*extend\s+[\'"](?P<name>[^\'"]+)[\'"]\s*\}\})', re.MULTILINE)
mbahri/vote_ensimag
votes/models.py
Python
mit
4,084
0.003686
from django.db import models from django.contrib.auth.models import User # Create your models here. from django.utils.html import format_html # Représente un type de liste : BDE, BDA, BDS... # nom : nom du type # deux_tours : booléen qui indique s'il y aura deux tours pour ce type de liste class TypeListe(models.Mode...
eight:15px; border-radius:5px;"></div>'.format(self.liste_c
ouleur)) color_box.short_description = 'Couleur' # Renvoie l'url du logo si spécifiée ou le logo par défaut sinon def logo(self): if self.liste_logo and hasattr(self.liste_logo, 'url'): return self.liste_logo.url else: return '/media/logos/blank.png' logo.short_d...
jeremiah-c-leary/vhdl-style-guide
vsg/vhdlFile/classify/primary_unit_declaration.py
Python
gpl-3.0
510
0.001961
from vsg.token import primary_unit_declaration as token from vsg.vhdlFile import utils def detect(iToken, lObjects): ''' primary_uni
t_declaration ::= identifier; ''' return classify(iToken, lObjects) def classify(iToken, lObjects): iCurrent = iToken while not utils.is_next_token(';', iC
urrent, lObjects): iCurrent = utils.assign_next_token(token.identifier, iCurrent, lObjects) iCurrent = utils.assign_token(lObjects, iCurrent, token.semicolon) return iCurrent
ivyl/patchwork
patchwork/views/xmlrpc.py
Python
gpl-2.0
22,918
0.000044
# Patchwork - automated patch tracking system # Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org> # # This file is part of the Patchwork package. # # Patchwork 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; eith...
t): try: params, method = six.moves.xmlrpc_client.loads(request.body) response = self._dispatch(request, method, params) # wrap response in a singleton tuple response = (response,) response = self.dumps(response, methodresponse=1) except six.m...
ault: response = self.dumps(fault) except Exception: # report exception back to server response = self.dumps( six.moves.xmlrpc_client.Fault(1, '%s:%s' % (sys.exc_info()[0], sys.exc_info()[1])), ) return response d...
Daniel2357/tetris
tetris.py
Python
mit
346
0.00289
#!/usr/bin/python3 from PyQt4 import QtGui import sys import TetrisMainWindow import GameWidget import
TetrisGame app = QtGui.QApplication(sys.argv) gameWidget = GameWidget.GameWidget() mainWindow = TetrisMainWindow.TetrisMainWindow(gameWidget) game = TetrisGame.TetrisGame(mainWindow, gameWidget) mainWindow.show() sys.exit(app.exec_())
gusmaogabriels/optinpy
optinpy/mcfp/mcfp.py
Python
gpl-3.0
798
0.012531
# -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function def bigm(network,mcost,verbose=False
): """ big-M assumes non-negative flows .. network as graph object .. mcost as numeric, the input cost of artificial arcs. """ network.set_root_weight(mcost) while True: non_basic = [arc for arc in netwo
rk.non_basic] i = 1 while len(non_basic)>0: print i += 1 arc = non_basic.pop(0) if arc.c_hat() <= 0: print(arc(),arc.c_hat()) arc.pivot() break else: pass if le...
diofant/diofant
diofant/vector/vector.py
Python
bsd-3-clause
12,728
0.000157
from __future__ import annotations from ..core import AtomicExpr, Integer, Pow, Symbol, diff from ..core.assumptions import StdFactKB from ..functions import sqrt from ..matrices import ImmutableMatrix from .basisdependent import (BasisDependent, BasisDependentAdd, BasisDependentMul, Basis...
nction. If this function is applied to a scalar expression, it returns the directional derivative of the scalar field wrt this Vector. Parameters ========== other: Vector/Dyadic/Del The Vector or Dyadic we are dotti
ng with, or a Del operator . Examples ======== >>> C = CoordSysCartesian('C') >>> C.i.dot(C.j) 0 >>> C.i & C.i 1 >>> v = 3*C.i + 4*C.j + 5*C.k >>> v.dot(C.k) 5 >>> (C.i & C.delop)(C.x*C.y*C.z) C.y*C.z >>> d = C.i.o...
HarborYuan/cashier
Errors.py
Python
mit
79
0.012658
class RepeatErr
or(ValueError): pass class NoneE
rror(ValueError): pass
jettisonjoe/openhtf
openhtf/util/multicast.py
Python
apache-2.0
7,038
0.005968
# Copyright 2016 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 agre...
socket.SOCK_DGRAM) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) if local_only: # Set outgoing interface to localhost to ensure no packets leave this host. sock.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_IF, struct.pack('!L', LOCALHOST_ADDRESS)) sock.set...
ue.Queue() def _handle_responses(): while True: try: data, address = sock.recvfrom(MAX_MESSAGE_BYTES) data = data.decode('utf-8') except socket.timeout: recv_queue.put(None) break else: _LOG.debug('Multicast response to query "%s": %s:%s', ...
brburns/netdisco
netdisco/discoverables/openhome.py
Python
apache-2.0
583
0
"""Discover Openhome devices.""" from . import SSDPDiscoverable # pylint: disable=too-few-public-methods class Discoverable(SSDPDiscoverable): """Add support for discovering Openhome compliant devices.""" def info_from_entry(self, entry): """Return the most important info from a uPnP entry.""" ...
Get all the Openhome compliant device uPnP entries.""" return self.find_by_st("urn:av-openhome-org:service:Produ
ct:2")
ema/conpaas
conpaas-services/contrib/libcloud/compute/drivers/ec2.py
Python
bsd-3-clause
53,777
0.000037
# 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 ...
U Quadruple Extra Large Instance', 'ram': 22528, 'disk': 1690, 'bandwidth': None }, 'cc1.4xlarge': { 'id': 'cc1.4xlarge', 'name': 'Cluster Compute Quadruple Extra Large Instance',
'ram': 23552, 'disk': 1690, 'bandwidth': None }, 'cc2.8xlarge': { 'id': 'cc2.8xlarge', 'name': 'Cluster Compute Eight Extra Large Instance', 'ram': 63488, 'disk': 3370, 'bandwidth': None }, 'cr1.8xlarge': { 'id': 'cr1.8xlarge', '...
MrMaidx/godot
misc/scripts/svgs_2_pngs.py
Python
mit
4,991
0.002404
# -*- coding: utf-8 -*- # Basic exporter for svg icons from os import listdir from os.path import isfile, join, dirname, realpath import subprocess import sys import rsvg import cairo last_svg_path = None last_svg_data = None SCRIPT_FOLDER = dirname(realpath(__file__)) + '/' theme_dir_base = SCRIPT_FOLDER + '../.....
if special_icon.has_key('output_names'): out_icon_names += special_icon['output_names'] if special_icon.has_key('theme_output_names'): theme_out_icon_names += special_icon['theme_output_names'] source_path = '%s%s.svg' % (svgs_path, name_only) ...
80) for theme_out_icon_name in theme_out_icon_names: svg_to_png(source_path, theme_dir_base + theme_out_icon_name, 90) def export_theme(): svgs_path = theme_dir_source file_names = [f for f in listdir(svgs_path) if isfile(join(svgs_path, f))] for file_name in file_names: # nam...
Thortoise/Super-Snake
Blender/animation_nodes-master/nodes/spline/trim_spline.py
Python
gpl-3.0
1,134
0.008818
import bpy from ... base_types.node import AnimationNode from . spline_evaluation_base import SplineEvaluationBase class Trim
SplineNode(bpy.types.Node, AnimationNode, SplineEvaluationBase): bl_idname = "an_TrimSplineNode" bl_label = "Trim Spline" def create(self): self.newInput("Spline", "Spline", "spline", defaultDrawType = "PROPERTY_ONLY") self.newInput("Float", "Start", "start", value = 0.0) self.newIn...
t = "") def drawAdvanced(self, layout): col = layout.column() col.active = self.parameterType == "UNIFORM" col.prop(self, "resolution") def execute(self, spline, start, end): spline.update() if spline.isEvaluable and self.parameterType == "UNIFORM": spline.e...
nusdbsystem/incubator-singa
python/singa/opt.py
Python
apache-2.0
5,529
0.000362
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(self, lr=0.1, momentum=0, dampening=0, weight_decay=0, nesterov=False):
if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError( "Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, ...
sharadagarwal/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py
Python
mit
1,520
0.003289
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R
) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ResourceCollection(Model): """ResourceCollection :param productresource: ...
` :param arrayofresources: :type arrayofresources: list of :class:`FlattenedProduct <fixtures.acceptancetestsmodelflattening.models.FlattenedProduct>` :param dictionaryofresources: :type dictionaryofresources: dict """ _attribute_map = { 'productresource': {'key': 'productresource...
amolenaar/gaphor
gaphor/core/modeling/diagram.py
Python
lgpl-2.1
12,125
0.000742
"""This module contains a model element Diagram. Diagrams can be visualized and edited. """ from __future__ import annotations import logging import uuid from dataclasses import dataclass from functools import lru_cache from typing import Callable, Iterable, Iterator, Sequence, TypeVar, overload import gaphas from t...
) if selection else () ) P = TypeVar("P", bound=Presentation) class Diagram(Element): """Diagrams may contain model elements and can be owned by a Package.""" name: attribute[str] element: relation_one[Element] def __init__(self, id: Id | None = None, model: Repo...
ol | None = None): """Initialize the diagram with an optional id and element model. The diagram also has a canvas. """ super().__init__(id, model) self._connections = gaphas.connections.Connections() self._connections.add_handler(self._on_constraint_solved) sel...
VanceKingSaxbeA/GoldSaxEngineChinaMarkets
goldsaxenginestart.py
Python
lgpl-3.0
334
0.008982
/*Owner & Copyrights: Vance King Saxbe. A.*/from GoldSaxEngineChinaMarkets import goldsaxenginechinamarkets goldsaxenginechinamarkets.start() /*email to provide suppor
t at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundrai
sing@powerdominionenterprise.com*/
ProjectSWGCore/NGECore2
scripts/object/tangible/wearables/ring/item_ring_set_commando_dps_01_01.py
Python
lgpl-3.0
1,070
0.024299
import sys def setup(core, object): object.setAttachment('radial_filename', 'ring/unity') object.setAttachment('objType', 'ring') object.setStfFilename('static_item_n') object.setStfName('item_
ring_set_commando_dps_01_01') object.setDetailFilename('static_item_d') object.setDetailName('item_ring_set_commando_dps_01_01') object.setIntAttribute('required_combat_level', 85) object.setStringAttribute('class_required', 'Commando') object.setIntAttribute('cat_skill_mod_bonus.@stat_n:fast_attack_line_co_grenad...
cat_skill_mod_bonus.@stat_n:expertise_action_line_co_grenade', 3) object.setIntAttribute('cat_skill_mod_bonus.@stat_n:expertise_freeshot_co_grenade', 2) object.setStringAttribute('@set_bonus:piece_bonus_count_3', '@set_bonus:set_bonus_commando_dps_1') object.setStringAttribute('@set_bonus:piece_bonus_count_4', '@set...
watchdogpolska/feder
feder/cases/migrations/0006_alias.py
Python
mit
1,017
0.000983
# Generated by Django 1.11.9 on 2018-01-10 00:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [("cases", "0005_auto_20160917_1347")] operations = [ migrations.CreateModel( name="Alias", fields...
verbose_name="ID", ), ), ("email", models.CharField(db_index=True, max_length=75, unique=True)), (
"case", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="cases.Case", verbose_name="Case", ), ), ], ) ]
pysam-developers/pysam
pysam/samtools.py
Python
mit
1,671
0
from pysam.utils import PysamDispatcher # samtools command line options to export in python SAMTOOLS_DISPATCH = { # samtools 'documented' commands "view": ("view", None), "sort": ("sort", None), "mpileup": ("mpileup", None), "depth": ("depth", None), "faidx": ("faidx", None), "fqidx": ("fqi...
ad2unpad
", None), "bedcov": ("bedcov", None), "coverage": ("coverage", None), "bamshuf": ("bamshuf", None), "collate": ("collate", None), "stats": ("stats", None), "fasta": ("fasta", None), "fastq": ("fastq", None), "quickcheck": ("quickcheck", None), "split": ("split", None), "flags": (...
aronsky/home-assistant
tests/components/roku/test_media_player.py
Python
apache-2.0
23,037
0.001302
"""Tests for the Roku Media Player platform.""" from datetime import timedelta from unittest.mock import patch from rokuecp import RokuError from homeassistant.components.media_player import DEVICE_CLASS_RECEIVER, DEVICE_CLASS_TV from homeassistant.components.media_player.const import ( ATTR_APP_ID, ATTR_APP_...
et(MAIN_ENTITY_ID).state == STATE_UNAVAILABLE future += timedelta(minutes=1) with patch("homeassistant.util.dt.utcnow", return_value=future): async_fire_time_changed(hass, future) await hass.async_block_till_done() assert hass.states.get(M
AIN_ENTITY_ID).state == STATE_HOME async def test_supported_features( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test supported features.""" await setup_integration(hass, aioclient_mock) # Features supported for Rokus state = hass.states.get(MAIN_ENTITY_ID) assert ...
openpermissions/auth-srv
auth/oauth2/token.py
Python
apache-2.0
3,918
0.001021
# -*- coding: utf-8 -*- # Copyright 2016 Open Permissions Platform Coalit
ion # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may obtain a copy of
the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language gover...
swcurran/TheOrgBook
tob-api/tob_api/inspector.py
Python
apache-2.0
1,086
0.002762
from drf_yasg.inspectors import PaginatorInspector from drf_yasg import openapi from collections import OrderedDict class PageNumberPaginatorInspectorClass(PaginatorInspector): def get_paginated_r
esponse(self, paginator, response_schema): paged_schema = openapi.Schema( type=openapi.TYPE_OBJECT, properties=OrderedDict(( ("total", openapi.Schema(type=openapi.TYPE_INTEGER)), ("page_size", openapi.Schema(type=openapi.TYPE_INTEGER)), ("p...
openapi.TYPE_INTEGER)), ("last_index", openapi.Schema(type=openapi.TYPE_INTEGER)), ("next", openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI, x_nullable=True)), ("previous", openapi.Schema(type=openapi.TYPE_STRING, format=openapi.FORMAT_URI, x_nullable=T...
dz0ny/mopidy-api-explorer
mopidy_explorer/__init__.py
Python
mit
762
0
from __future__ import unicode_literals import os from mopidy import ext, config __version__ = '1.0.1' __url__ = 'https://github.com/dz0ny/mopidy-api-explorer' class APIExplorerExtension(ext.Extension): dist_name = 'Mopidy-API-Explorer' ext_name = 'api_explorer' version = __version__ def get_defa...
return config.read(conf_file) def get_config_schema(self): schema = super(APIExplorerExtension, self).get_config_schema() return schema def setup(self, registry): registry.add('http:static', { 'name': self.ext_name, 'path': os.path.join(os.path.
dirname(__file__), 'public'), })
google-research/google-research
non_semantic_speech_benchmark/distillation/compression_lib/compression_op.py
Python
apache-2.0
17,758
0.002816
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
n. Size is taken from spec. """ raise NotImplementedError() class LowRankDecompMatrixCompressor(MatrixCompressorInferface): """Low rank decomposition compressor. Implements matrix compression interface for the low rank decomposition algorithm. """ def __init__(self, spec): """Initializer....
self._spec = spec self.uncompressed_size = 0 self.compressed_size = 0 def get_spec(self): return self._spec @staticmethod def get_default_hparams(): """Get a tf.HParams object with the default values for the hyperparameters. name: string name of the low-rank matrix decompressor...
waynedovey/fig
tests/unit/cli_test.py
Python
apache-2.0
2,233
0
from __future__ import unicode_literals from __future__ import absolute_import import logging import os from .. import unittest import mock from fig.cli import main from fig.cli.main import TopLevelCommand from fig.packages.six import StringIO class CLITestCase(unittest.TestCase): def test_default_project_name(...
command.base_dir = 'tests/fixtures/longer-filename-figfile' with mock.patch('fig.cli.command.log', autospec=True) as mock_log: self.assertTrue(command.get_config_path()) self.assertEqual(mock_log.warning.call_count, 2) def test_get_project(self): command = TopLevelCommand...
command.base_dir = 'tests/fixtures/longer-filename-figfile' project = command.get_project(command.get_config_path()) self.assertEqual(project.name, 'longerfilenamefigfile') self.assertTrue(project.client) self.assertTrue(project.services) def test_help(self): command = TopL...
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/v8/gypfiles/get_landmines.py
Python
gpl-3.0
1,128
0.01773
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This file emits the list of reasons why a partic
ular build needs to be clobbered (or a list of 'landmines'). """ import sys def main(): """ ALL LANDMINES ARE EMITTED FROM HE
RE. """ print 'Need to clobber after ICU52 roll.' print 'Landmines test.' print 'Activating MSVS 2013.' print 'Revert activation of MSVS 2013.' print 'Activating MSVS 2013 again.' print 'Clobber after ICU roll.' print 'Moar clobbering...' print 'Remove build/android.gypi' print 'Cleanup after window...
tobegit3hub/cinder_docker
cinder/tests/unit/volume/drivers/netapp/dataontap/test_block_base.py
Python
apache-2.0
38,413
0
# Copyright (c) 2014 Alex Meade. All rights reserved. # Copyright (c) 2014 Clinton Knight. All rights reserved. # Copyright (c) 2014 Andrew Kerr. All rights reserved. # Copyright (c) 2015 Tom Barron. All rights reserved. # Copyright (c) 2015 Goutham Pacha Ravi. All rights reserved. # All Rights Reserved. # # Lic...
return_value=fake.POOL_NAME)) self.mock_object(self.library, '_setup_qos_for_volume', mock.Mock(return_value=None)) self.mock_object(self.library, '_create_lun') self.mock_object(self.library, '_create_lun_handle') self.mock_object(self.library, '_add...
lf.library, '_mark_qos_policy_group_for_deletion') self.library.create_volume(fake.VOLUME) self.library._create_lun.assert_called_once_with( fake.POOL_NAME, fake.LUN_NAME, volume_size_in_bytes, fake.LUN_METADATA, None) self.assertEqual(0, self.library. ...
crisisking/skybot
test/__main__.py
Python
unlicense
712
0
from os import path from unittest import TestSuite, TestLoader, TextTestRunner import sys if __name__ == '__main__': # Because the project is structured differently than # any tooling expects, we need to modify the python # path during runtime (or before) to ge
t it to # properly import pl
ugins and other code correctly. project_root_directory = path.dirname(path.dirname(__file__)) sys.path.append(path.join(project_root_directory, 'plugins')) sys.path.append(path.join(project_root_directory)) discovered_tests = TestLoader().discover(path.dirname(__file__)) run_result = TextTestRunne...
abbgrade/confdown
setup.py
Python
lgpl-3.0
399
0.002506
from setuptools import setup setup(name='confdown', version='0.1', descr
iption='A Markdown-based self documenting configuration lib', url='http://github.com/abbgrade/confdown', author='Steffen Kampmann', author_email='confdown@abbgra.de', license='LGPL3', packages=['confdown'], install_requires=[ 'markdown',
], zip_safe=False)
mikegraham/dask
dask/array/optimization.py
Python
bsd-3-clause
6,346
0
from __future__ import absolute_import, division, print_function from operator import getitem import numpy as np from .core import getarray from ..core import flatten from ..optimize import cull, fuse, inline_functions def optimize(dsk, keys, **kwargs): """ Optimize dask for array computation 1. Cull tas...
elif type(a_index) is tuple and all(type(s) is slice an
d not s.start and s.stop is None and s.step is None for s in a_index): dsk[k] = a ...
spk921/scrapers
bloomberg/archive/getOldBloomberg.py
Python
mit
1,395
0.010753
#!/usr/bin/python # Made by Sangpil Kim # June 2016 import json from google import search import csv def searchGoogle(query,dic): bloomberg = [] forbes = [] # later do forbes as well for url in search(query, stop=10): print(url) if 'bloomberg.com/research/stocks/private/person' in u...
mes, companies # Read CSV file with colum name by DictReader tuples = readCSV('ceoname.csv') # Unpacking tuples names , _ = tuples print(names) conj = [] #Scrap info for name in names: conj.append(scrapInfo(name)) print(conj[len(conj)-1]) #Dump as json dstJson = 'oldBloomberg.json' with open(dstJson, mode='...
json.dump(conj,f)
rosarior/mayan
apps/metadata/links.py
Python
gpl-3.0
3,605
0.00638
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ from documents.permissions import PERMISSION_DOCUMENT_TYPE_EDIT from .permissions import (PERMISSION_METADATA_DOCUMENT_EDIT, PERMISSION_METADATA_DOCUMENT_ADD, PERMISSION_METADATA_DOCUMENT_REMOVE, PERMISSION_METADAT...
} setup_metadata_set_delete = {'text': _(u'delete'), 'view': 'setup_metadata_set_delete', 'args': 'object.pk', 'famfam': 'table_delete', 'permissions': [PERMISSION_METADATA_SET_DELETE]} setup_metadata_set_create = {'text': _(u'create new'), 'view'
: 'setup_metadata_set_create', 'famfam': 'table_add', 'permissions': [PERMISSION_METADATA_SET_CREATE]} setup_document_type_metadata = {'text': _(u'default metadata'), 'view': 'setup_document_type_metadata', 'args': 'document_type.pk', 'famfam': 'xhtml', 'permissions': [PERMISSION_DOCUMENT_TYPE_EDIT]}
Strain88/VKapi2
api.py
Python
mit
2,857
0.025201
#!-*-coding:utf8-*- from urllib import urlopen class Api(object): def __init__(self, session, **default_api_kwargs): self._session=session self._defauld_api_kwargs=default_api_kwargs self._defauld_api_kwargs.update({'access_token': self._session.at}) self.stats.trackVisitor() def make_...
request_obj: req = request_obj['fromApiHelper'] method_url=req.get_method_name() method_args=req.get_me
thod_args() if method_url=="audio.save": #TODO: make this method more practical """ :param link_to_file: required parameter """ self._defauld_api_kwargs.update(method_args) upload_vk_url = self.audio.getUploadServer()['response']['upload_url'] f = method_args...
simbha/mAngE-Gin
lib/django/core/management/utils.py
Python
mit
2,822
0.000709
from __future__ import unicode_literals import os from subprocess import PIPE, Popen import sys from django.utils.encoding import force_text, DEFAULT_LOCALE_ENCODING from django.utils import six from .base import CommandError def popen_wrapper(args, os_err_exc_type=CommandError): """ Friendly wrapper aroun...
r p in path: f = os.path.join(p, cmd) if os.path.isfile(f): return f for ext in pathext:
fext = f + ext if os.path.isfile(fext): return fext return None
gkotian/zulip
analytics/management/commands/realm_stats.py
Python
apache-2.0
7,855
0.00522
from __future__ import absolute_import import datetime import pytz from django.core.management.base import BaseCommand from django.db.models import Count from zerver.models import UserProfile, Realm, Stream, Message, Recipient, UserActivity, \ Subscription, UserMessage, get_realm MOBILE_CLIENT_LIST = ["Android",...
help="realm to generate statistics for") def active_users(self, realm): # Has been active (on the website, for now) in the last 7 days. activity_cutoff = datetime.datetime.now(tz=pytz.utc) - datetime.timedelta(da
ys=7) return [activity.user_profile for activity in \ UserActivity.objects.filter(user_profile__realm=realm, user_profile__is_active=True, last_visit__gt=activity_cutoff, ...
shawnsi/ansible
lib/ansible/playbook/task.py
Python
gpl-3.0
14,128
0.004813
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
return "%s : %s" % (self._role.get_name(), self.name) elif self.name: return self.name else: flattened_args = self._merge_kv(self.args) if self._role: return "%s : %s %s" % (self._role.get_name(), self.action, flattened_args) else: ...
merge_kv(self, ds): if ds is None: return "" elif isinstance(ds, string_types): return ds elif isinstance(ds, dict): buf = "" for (k,v) in iteritems(ds): if k.startswith('_'): continue buf = buf +...
Anjali2906/lifetab
journal/migrations/0001_initial.py
Python
mit
1,264
0.003165
# encoding: utf8 from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Entry', fields=...
('content', models.CharField(max_length=100000)), ('feeling', models.CharField(default=b'HAPP', max_length=4, choices=[(b'HAPP', b'happy'), (b'SADD', b'sad'), (b'NOST', b'nostalgic'), (b'CURI', b'curious'), (b'WOND', b'wonderful')])), ], options={ 'abstract...
bases=(models.Model,), ), ]
yosshy/nova
nova/tests/functional/test_login.py
Python
apache-2.0
1,197
0
# Copyright 2011 Justin Santa Barbara # 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 requ...
_api_version = 'v2' def test_login(self): # Simple check - we list flavors - so we know we're logged in. flavors = self.api.get_flavors() for flavor in flavors: LOG.debug("flavor: %s", flavor) class Logi
nTestV3(client.TestOpenStackClientV3Mixin, LoginTest): _api_version = 'v2.1'
tudennis/LeetCode---kamyu104-11-24-2015
Python/merge-k-sorted-lists.py
Python
mit
3,117
0.002887
from __future__ import print_function # Time: O(nlogk) # Space: O(1) # Merge k sorted linked lists and return it as one sorted list. # Analyze and describe its complexity. # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __...
2.next curr = curr.next curr.next = l1 or l2 return dummy.next if not lists:
return None left, right = 0, len(lists) - 1; while right > 0: if left >= right: left = 0 else: lists[left] = mergeTwoLists(lists[left], lists[right]) left += 1 right -= 1 return lists[0] # Time: O(nlo...
spWang/gitHooks
xcodetemplate.py
Python
mit
5,507
0.009726
#!/usr/bin/env python # coding=utf-8 import subprocess import os import shutil import filecmp TEMPLATE_VERSION = 2 new_default_file_path = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/Source" new_file_category_path = "/Applications/Xcode.app...
int "脚本未提供xcode模板文件,无需复制xcode模板" return False pass #1.2未安装xcode,不复制 xcode_app = "/Applications/Xcode.app" if not os.path.exists(xcode_app): print "未安装xcode,不需要复制xcode模板" return False pass #1.3xcode文件没有,复制 if not os.path.exists(xcode_file): print ...
return True pass #2.内容不同,复制 equale = filecmp.cmp(xcode_file,xcode_template_file) if not equale: print "你的xcode的模板和提供的模板不一致,正在帮你复制模板..." return True pass #3.内容相同,看标记版本 template_version = check_out_put(template_version_cammand, False, None) ...
nickchen-mitac/fork
src/avashell/cli/shell.py
Python
apache-2.0
632
0.003165
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import time import logging from avashell.base.shell import ShellBase, STR_EXIT, STR_OPEN_HELP _logger = logging.getLogger(__name__) class Shell(
ShellBase): def __init__(self): super(Shell, self).__init__() def _run(self): while True: try: time.sleep(0.1) self.process_idle_tasks() except KeyboardInterrupt:
_logger.info("Interrupted.") break if __name__ == '__main__': shell = Shell() shell.run()
shapiromatron/amy
workshops/management/commands/check_badges.py
Python
mit
1,785
0.002241
import sys import os from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand, CommandError from workshops.models import Award, Badge, Person SKIP_DIRS = ['class'] class Command(BaseCommand): args = '/path/to/site' help = 'Report inconsistencies in badges.' ...
print('{0} {1}'.format(badge_name, title)) for i in sorted(list(items)): try: p = Person.objects.get(username=i) print(' {0}: {1}'.format(i, p)) except ObjectDo
esNotExist: print(' {0}'.format(i))
ui/rq-scheduler
rq_scheduler/utils.py
Python
mit
2,088
0.000958
import calendar import croniter import datetime from datetime import datetime, timedelta, tzinfo import logging from rq.utils import ColorizingStreamHandler # from_unix from times.from_unix() def from_unix(string): """Convert a unix timestamp into a utc datetime""" return datetime.utcfromtimestamp(float(str...
datefmt='%H:%M:%S') handler = ColorizingStreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) def rationalize_until(until=None): """ Rationalizes the `until` argument used by other functions. This function accepts datetime and timedelta instances as well as in...
until = to_unix(until) elif isinstance(until, timedelta): until = to_unix((datetime.utcnow() + until)) return until class UTCTimezone(tzinfo): def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return timedelt...
Hackplayers/Empire-mod-Hpys-tests
lib/modules/powershell/situational_awareness/network/powerview/get_localgroup.py
Python
bsd-3-clause
4,013
0.013456
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-NetLocalGroup', 'Author': ['@harmj0y'], 'Description': ('Returns a list of all current users in a specified local group ' 'on ...
min' : False, 'OpsecSafe' : True, 'Language' : 'powershell', 'MinLanguageVersion' : '2', 'Comments': [ 'https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/' ] } # any options needed by the...
d, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'ComputerName' : { 'Description' : 'The hostname or IP to query for local group users.'...
bit0001/trajectory_tracking
src/util/angle.py
Python
mit
435
0.002299
#!/usr/bin/env python from math import pi from tf.transformations import euler_from_quaternion def get_euler_orientation(orientation): quaternion = ( orientation.x, orientation.y, orientation.z, orientation.w ) return euler_from_quaternion(quaternion)
def get_angle_between_0_and_2_pi(angle): angle %= 2 * pi
if -pi <= angle < 0: return 2 * pi + angle return angle
hpcugent/easybuild-framework
test/framework/sandbox/easybuild/easyblocks/generic/makecp.py
Python
gpl-2.0
1,888
0.002648
## # Copyright 2009-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
s.generic.configuremake import ConfigureMake from easybuild.framework.easyconfig import BUILD, MANDATORY class MakeCp(ConfigureMake): """Dummy support f
or software with no configure and no make install step.""" @staticmethod def extra_options(extra_vars=None): """ Define list of files or directories to be copied after make """ extra = { 'files_to_copy': [None, "List of files or dirs to copy", MANDATORY], ...
akhambhati/dyne
dyne/version.py
Python
bsd-3-clause
15
0.133333
VER
SION='0.6.4'
PyThaiNLP/pythainlp
pythainlp/transliterate/thaig2p.py
Python
apache-2.0
11,448
0
# -*- coding: utf-8 -*- """ Thai Grapheme-to-Phoneme (Thai G2P) GitHub : https://github.com/wannaphong/thai-g2p """ import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pythainlp.corpus import get_corpus_path device = torch.device("cuda:0" if torch.cuda.is_availabl...
.dropout = nn.Dropout(dropout) def forward(self, sequences, sequences_lengths): # sequences: (batch_size, sequence_length=MAX_LENGTH) # sequences_lengths: (batch_size) batch_size = sequences.size(0) self.hidden = self.init_hidden(batch_size) sequences_lengths = np.sort(se...
index_unsort = np.argsort(index_sorted) # to unsorted sequence index_sorted = torch.from_numpy(index_sorted) sequences = sequences.index_select(0, index_sorted.to(device)) sequences = self.character_embedding(sequences) sequences = self.dropout(sequences) sequences_pack...
qtproject/qt-creator
tests/system/suite_CCOM/tst_CCOM02/test.py
Python
gpl-3.0
2,818
0.002839
############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the co...
th the terms contained in # a written agreement between you and The Qt Company. For licensing terms # and conditions see https://www.qt.io/terms-conditions. For further # information use the contact form at https://www.qt.io/contact-us. # # GNU General Public License Usage # Alternatively, this file may be used under t...
3 as published by the Free Software # Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT # included in the packaging of this file. Please review the following # information to ensure the GNU General Public License requirements will # be met: https://www.gnu.org/licenses/gpl-3.0.html. # ###########...
moonso/extract_vcf
extract_vcf/config_parser.py
Python
mit
10,637
0.007522
#!/usr/bin/env python # encoding: utf-8 """ read_config.py The main point with this package is how to retreive the corect entry from a vcf file. In the best case one should be able to specify any kind of entry in the config file and how it is extracted. ConfigParser will read these files and check if they are on the ...
f[plugin] try: vcf_field = vcf_section['field'] if not vcf_field in self.vcf_columns: raise ValidateError( "field has to be in {0}\n" "Wrong field name in plugin: {1}".format( self.vcf_colum...
'INFO': try: info_key = vcf_section['info_key'] if info_key == 'CSQ': try: csq_key = vcf_section['csq_key'] except KeyError: raise ValidateError(
aronsky/home-assistant
tests/components/abode/test_sensor.py
Python
apache-2.0
1,877
0.000533
"""Tests for the Abode sensor device.""" from homeassistant.components.abode import ATTR_DEVICE_ID from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, DEVICE_CLASS_HUMIDITY, PERCENTAGE,...
e correct.""" await setup_platform(hass, SENSOR_DOMAIN) state = hass.states.get("sensor.environment_sensor_humidity") assert state.state == "32.0" assert state.attributes.get(ATTR_DEVICE_ID) == "RF:02148e70" assert not state.attributes.get("battery_low")
assert not state.attributes.get("no_response") assert state.attributes.get("device_type") == "LM" assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Environment Sensor Humidity" assert state.attributes.get(ATTR_DEVICE_CLASS) == DEV...
pongem/python-bot-project
monitoring/api/v3/api-client/custom_metric_test.py
Python
apache-2.0
3,125
0
#!/usr/bin/env python # 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 # di...
has been created, use the get call to wait until # a response comes back with the new metric custom_metric = None while not custom_metric: time.sleep(1) custom_metric = get_custom_metric( client, PROJECT_RESOURCE, METRIC_RESOURCE) write_timeseries_value(client, PROJECT_RESOU...
METRIC_KIND) # Sometimes on new metric descriptors, writes have a delay in being # read back. Use eventually_consistent to account for this. @eventually_consistent.call def _(): response = read_timeseries(client, PROJECT_RESOURCE, METRIC_RESOURCE) value = int( ...
yukim/cassandra-dtest
replication_test.py
Python
apache-2.0
10,925
0.004302
from dtest import Tester, debug, PRINT_DEBUG from tools import no_vnodes from ccmlib.cluster import Cluster import re, os, time from collections import defaultdict from cassandra.query import SimpleStatement from cassandra import ConsistencyLevel TRACE_DETERMINE_REPLICAS = re.compile('Determining replicas for mutation...
ce_wait = 120 replication_factor = 3 self.create_ks(cursor, 'test', replication_factor) cursor.execute('CREATE TABLE test.test (id int PRIMARY KEY, value text)', trace=False) # Wait for table creation, otherwise trace times out - # CASSANDRA-5658 time.sleep(5) f...
query = SimpleStatement("INSERT INTO test (id, value) VALUES (%s, 'asdf')" % key, consistency_level=ConsistencyLevel.ALL) future = cursor.execute_async(query, trace=True) future.result() trace = future.get_query_trace(max_wait=120) self.pprint_trace(trace) ...
dydek/django
tests/postgres_tests/test_array.py
Python
bsd-3-clause
23,682
0.001309
import decimal import json import unittest import uuid from django import forms from django.apps.registry import Apps from django.core import exceptions, serializers, validators from django.core.management import call_command from django.db import IntegrityError, connection, models from django.test import TransactionT...
tgreSQLModel, ) try: from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.forms import SimpleArrayField, SplitArrayField exce
pt ImportError: pass class TestSaveLoad(PostgreSQLTestCase): def test_integer(self): instance = IntegerArrayModel(field=[1, 2, 3]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_char(self): instance...
sandeep6189/Pmp-Webapp
oauth.py
Python
bsd-3-clause
5,795
0.004142
from rauth import OAuth1Service, OAuth2Service from flask import current_app, url_for, request, redirect, session import json class OAuthSignIn(object): providers = None def __init__(self, provider_name): self.provider_name = provider_name credentials = current_app.config['OA
UTH_CREDENTIALS'][provider_name]
self.consumer_id = credentials['id'] self.consumer_secret = credentials['secret'] def authorize(self): pass def callback(self): pass def get_callback_url(self): return url_for('oauth_callback', provider=self.provider_name, _external=True) ...
OpenAcademy-OpenStack/nova-scheduler
nova/tests/api/openstack/compute/contrib/test_aggregates.py
Python
apache-2.0
18,751
0.00064
# Copyright (c) 2012 Citrix Systems, 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 ...
ATE, result["aggregate"]) def test_update_with_only_name(self): body = {"aggregate": {"name": "new_name"}} def stub_update_aggregate(context, aggregate, values): return
AGGREGATE self.stubs.Set(self.controller.api, "update_aggregate", stub_update_aggregate) result = self.controller.update(self.req, "1", body=body) self.assertEqual(AGGREGATE, result["aggregate"]) def test_update_with_only_availability_zone(self): body = {"ag
ryanmiao/libvirt-test-API
repos/virconn/cpu_stats.py
Python
gpl-2.0
2,792
0.000358
#!/usr/bin/env python # test libvirt cpu stats import libvirt from libvirt import libvirtError from src import sharedmod from utils import utils required_params = ('cpuNum',) optional_params = {'conn': '', } STATFILE = "/proc/stat" GETCPUSTAT = "cat /proc/stat | grep cpu%s" USR_POS = 1 NI_POS = 2 SYS_POS = 3 IDLE_P...
md(cmd, shell=True) if status != 0: logger.error("Exec %s fails" % cmd) return False logger.debug("get cpu%s stats: %s" % (cpu, out)) stats = out[0].split() logger.debug("cpu stats: %s" % stats)
if stat_type == "kernel": target_stat = int(stats[SYS_POS]) + int(stats[IRQ_POS]) + \ int(stats[SOFTIRQ_POS]) delta = 1 elif stat_type == "idle": target_stat = int(stats[IDLE_POS]) delta = 10 elif stat_type == "user": target_stat = int(stats[USR_PO...
avehtari/GPy
GPy/models/gp_coregionalized_regression.py
Python
bsd-3-clause
1,917
0.013041
# Copyright (c) 2012 - 2014 the GPy Austhors (see AUTHORS.txt) # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from ..core import GP from .. import likelihoods from .. import kern from .. import util class GPCoregionalizedRegression(GP): """ Gaussian Process model for heterosced...
:param X_list: list of input observations corresponding to each output :type X_list: list of numpy arrays :param Y_list:
list of observed values related to the different noise models :type Y_list: list of numpy arrays :param kernel: a GPy kernel, defaults to RBF ** Coregionalized :type kernel: None | GPy.kernel defaults :likelihoods_list: a list of likelihoods, defaults to list of Gaussian likelihoods :type likelihoo...
sdws1983/bioinfo-relate
Blast-relate/E-value-distribution.py
Python
gpl-3.0
1,085
0.057143
#!/usr/bin/env python2 import sys, getopt import re import time de
f get_option(): opts, args = getopt.getopt(sys.argv[1:], "hi:o:") input_file = "" output_file = "" h = "" for op, value in opts: if op == "-i": input_file = value elif op == "-o": output_file = value elif op == "-h": h = "E-value distribut
ion.\n-i : inputfile\n-o : outputfile\n" return input_file,output_file,h def main(input_file, output_file): o = a = b = c = d = e = g = 0 fout = open(output_file, 'w') with open (input_file) as f: for i in f: i = float(i[:-1]) if i == 0: o +=1 elif i < float(1e-150): a +=1 elif i < float(1e-1...
rananda/cfme_tests
cfme/web_ui/__init__.py
Python
gpl-2.0
143,413
0.002524
"""Provides a number of objects to help with managing certain elements in the CFME UI. Specifically there are two categories of objects, organizational and elemental. * **Organizational** * :py:class:`Region` * :py:mod:`cfme.web_ui.menu` * **Elemental** * :py:class:`AngularCalendarInput` * :py:class:`Angu...
ilter` * :py:class:`Form` * :py:class:`InfoBlock` * :py:class:`Input` * :py:class:`MultiFill`
* :py:class:`Quadicon` * :py:class:`Radio` * :py:class:`ScriptBox` * :py:class:`Select` * :py:class:`ShowingInputs` * :py:class:`SplitCheckboxTable` * :py:class:`SplitTable` * :py:class:`StatusBox` * :py:class:`Table` * :py:class:`Tree` * :py:mod:`cfme.web_ui.accordion` * :py:mod:`cfme.web_ui.c...
tudennis/LeetCode---kamyu104-11-24-2015
Python/implement-rand10-using-rand7.py
Python
mit
1,761
0.003407
# Time: O(1.189), counted by statistics, limit would be O(log10/log7) = O(1.183) # Space: O(1) # Given a function rand7 which generates a uniform random integer in the range 1 to 7, # write a function rand10 which generates a uniform random integer in the range 1 to 10. # # Do NOT use system's Math.random(). # # Exam...
7() function? # - Could you minimize the number of calls to rand7()? # # The rand7() API is already defined for you. import random def rand7(): return random.randint(1, 7) # Reference: https://leetcode.com/problems/implement-rand10-using-rand7/discuss/151567/C++JavaPython-Average-1.199-Call-rand7-Pe
r-rand10 class Solution(object): def __init__(self): self.__cache = [] def rand10(self): """ :rtype: int """ def generate(cache): n = 32 curr = sum((rand7()-1) * (7**i) for i in xrange(n)) rang = 7**n while curr < rang//10*...
jamesbulpin/xcp-xen-4.1
tools/xm-test/tests/security-acm/07_security-acm_pol_update.py
Python
gpl-2.0
10,824
0.002772
#!/usr/bin/python # Copyright (C) International Business Machines Corp., 2006 # Author: Stefan Berger <stefanb@us.ibm.com> # Test to exercise the xspolicy class from XmTestLib import xapi from XmTestLib.XenAPIDomain import XmTestAPIDomain from XmTestLib import * from xen.xend import XendAPIConstants import xen.util....
policystate = session.xenapi.XSPolicy.get_xspolicy() if int(policystate['flags']) != xsconstants.XS_INST_BOOT | \ xsconstants.XS_INST_
LOAD: FAIL("Flags (%x) are not indicating the correct state of the policy.", int(policystate['flags'])) policystate = session.xenapi.XSPolicy.get_xspolicy() xs_ref = policystate['xs_ref'] newpolicyxml = None f = open("xm-test-new-security_policy.xml", 'r') if f: newpolicyxml = f.read() f.close() ...
robzenn92/EpTODocker
epto_project/api/stabilityOracle.py
Python
mit
530
0
#!/usr/bin/env python3 import threading class StabilityOracle(object): def __init__(self, ttl): self.lock = threading.Lock() self.logical_clock = 0 self.ttl = ttl def is_deliverable(self, event): return event.ttl > self.ttl def get_clock(self): with self.lock: ...
lock: if ts > self.logical_clock: self.logical_clock = ts
Lobosque/python_wpapi
setup.py
Python
mit
1,489
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.md') as history_file: history = history_file.read() requirements = [ 'requests' ] test_requirements = [ # TODO: put package test requireme...
cense", zip_safe=False, keywords='python_wpapi', classifiers=[ 'Development Status :: 2 -
Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language ...
toobaz/pandas
pandas/tests/plotting/test_groupby.py
Python
bsd-3-clause
2,294
0.001308
# coding: utf-8 """ Test cases for GroupBy.plot """ import numpy as np import pandas.util._test_decorators as td from pandas import DataFrame, Series from pandas.tests.plotting.common import TestPlotBase import pandas.util.testing as tm @td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase): def te...
0, 3.0], ) df.groupby("def")["val"].plot() tm.close() df.groupby("def")["val"].apply(lambda x: x.plot()) tm.close() def test_hist_single_row(self): # GH10214 bins = np.arange(80, 100 + 2, 1) df = DataFrame({"Name": ["AAA", "BBB"], "ByCol": [1, 2], "M...
ins) df = DataFrame({"Name": ["AAA"], "ByCol": [1], "Mark": [85]}) df["Mark"].hist(by=df["ByCol"], bins=bins) def test_plot_submethod_works(self): df = DataFrame({"x": [1, 2, 3, 4, 5], "y": [1, 2, 3, 2, 1], "z": list("ababa")}) df.groupby("z").plot.scatter("x", "y") tm.close...
wazeerzulfikar/scikit-learn
sklearn/tests/test_multioutput.py
Python
bsd-3-clause
18,250
0
from __future__ import division import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_raises_regex from sklearn.utils.testing import asse...
# weighted regressor Xw = [[1, 2, 3], [4, 5, 6]] yw = [[3.141, 2.718], [2.718, 3.141]] w = [2., 1.] rgr_w = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) rgr_w.fit(Xw, yw, w) # unweighted, but with repeated samples X = [[1, 2, 3], [1, 2,
3], [4, 5, 6]] y = [[3.141, 2.718], [3.141, 2.718], [2.718, 3.141]] rgr = MultiOutputRegressor(GradientBoostingRegressor(random_state=0)) rgr.fit(X, y) X_test = [[1.5, 2.5, 3.5], [3.5, 4.5, 5.5]] assert_almost_equal(rgr.predict(X_test), rgr_w.predict(X_test)) # Import the data iris = datasets.loa...
balloob/pychromecast
pychromecast/controllers/spotify.py
Python
mit
2,978
0
""" Controller to interface with Spotify. """ import logging import threading from . import BaseController from
..config import APP_SPOTIFY from ..error import LaunchError APP_NAMESPACE = "urn:x-cast:com.spotify.chromecast.secure.v1" TYPE_GET_INFO = "getInfo" TYPE_GET_INFO_RESPONSE = "getInfoResponse" TYPE_SET_CREDENT
IALS = "setCredentials" TYPE_SET_CREDENTIALS_ERROR = "setCredentialsError" TYPE_SET_CREDENTIALS_RESPONSE = "setCredentialsResponse" # pylint: disable=too-many-instance-attributes class SpotifyController(BaseController): """ Controller to interact with Spotify namespace. """ # pylint: disable=useless-super-de...
zwChan/VATEC
~/eb-virt/Lib/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py
Python
apache-2.0
973
0
from __future__ import division from datetime import datetime def total_seconds(td): """Python 2.6 compatability""" i
f hasattr(td, 'total_seconds'): return td.total_seconds() ms = td.microseconds secs = (td.seconds + td.days * 24 * 3600) return (ms + secs * 10**6) / 10**6 class RedisCache(object): def __init__(self, conn): self.conn = conn def get(self, key): return self.conn.get(key) ...
expires - datetime.now() self.conn.setex(key, total_seconds(expires), value) def delete(self, key): self.conn.delete(key) def clear(self): """Helper for clearing all the keys in a database. Use with caution!""" for key in self.conn.keys(): self.conn.del...
catapult-project/catapult-csm
dashboard/dashboard/models/sheriff.py
Python
bsd-3-clause
3,043
0.009201
# 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. """The database model Sheriff, for sheriff rotations.""" import re import urlparse from google.appengine.ext import ndb from dashboard.models import inter...
email addresses are stored at a url. If there is a url # specified here, it will be used as the perf sheriff address. But the email # below will also be cc-ed, so that
alerts can be archived to groups. url = ndb.StringProperty(validator=_UrlValidator, indexed=False) email = ndb.StringProperty(validator=_EmailValidator, indexed=False) internal_only = ndb.BooleanProperty(indexed=True) summarize = ndb.BooleanProperty(indexed=True, default=False) # A list of patterns. Each pa...
oihane/odoo-addons
contacts_school_permission/wizards/__init__.py
Python
agpl-3.0
44
0
from . im
port res_partner_permiss
ion_create
CloudFramework-io/js-cloudframework
test/simple_server.py
Python
mit
848
0.021226
import SimpleHTTPServer, SocketServer import urlparse, os PORT = 8002 class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): # Pa
rse query data to find out what was requested parsedParams = urlparse.urlparse(self.path) # See if the file requested exists if os.access('.' + os.sep + parsedParams.path, os.R_OK): # File exists, serve it up SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self); else: ...
.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() with open('index.htm', 'r') as fin: self.copyfile(fin, self.wfile) Handler = MyHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()...
johyphenel/sublime-expand-region
expand_to_quotes.py
Python
mit
1,231
0.01381
import re try: import utils except: from . import utils def expand_to_quotes(string, selection_start, selection_end): quotes_regex = re.compile("(['\"])(?:\\\.|.)*?\\1") # iterate over all found quotes pairs for match in quotes_regex.finditer(string): quotes_start = match.start() quotes_end = match...
ls.create_return_obj(quotes_start, quotes_end, string, "quotes") # selection is within the found quote pairs, return "quotes content" if(selection_start > quotes_start and selection_end
< quotes_end): return utils.create_return_obj(quotes_content_start, quotes_content_end, string, "quotes")
huijunwu/heron
heron/shell/src/python/handlers/filehandler.py
Python
apache-2.0
1,796
0.006682
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apach...
ilehandler.py ''' import tornado.web from tornado.template import Template from heron.shell.src.python import utils class FileHandler(tornado.web.RequestHandler): """ Responsible for creating the web page for files. The html will in turn call the /filedata/ endpoint to get the file data. """ @tornado.web.as...
= Template(utils.get_asset("file.html")) if path is None: self.set_status(404) self.write("No such file") self.finish() return if not utils.check_path(path): self.write("Only relative paths are allowed") self.set_status(403) self.finish() return args = dict(...
JConwayAWT/PGSS14CC
lib/python/multimetallics/ase/tasks/bulk.py
Python
gpl-2.0
5,236
0.001146
import optparse import numpy as np from ase.lattice import bulk from ase.tasks.task import OptimizeTask from ase.data import chemical_symbols, reference_states from ase.utils.eos import EquationOfState from ase.io.trajectory import PickleTrajectory class BulkTask(OptimizeTask): taskname = 'bulk' def __init...
ttice_constant self.c_over_a = c_over_a self.cubic = cubic self.orthorhombic = orthorhombic self.fit = fit self.repeat = None OptimizeTask.__init__(self, **kwargs) self.summary_keys = ['energy', 'fitted energy', 'volume', 'B'] def expand(self, name...
bcc, hcp and diamond. The name fcc will be expanded to all the elements with the fcc stucture and so on.""" names = OptimizeTask.expand(self, names) newnames = [] for name in names: if name in ['fcc', 'bcc', 'hcp', 'diamond']: for Z in ...
enthought/etsproxy
enthought/pyface/api.py
Python
bsd-3-clause
40
0
# pr
oxy module from pyface.api import *
MetrodataTeam/incubator-airflow
airflow/contrib/operators/file_to_gcs.py
Python
apache-2.0
2,453
0.000815
# -*- coding: utf-8 -*- # # 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 ...
args) self.src = src self.dst = dst self.bucket = bucket self.google_cloud_storage_conn_id = google_cloud_storage_conn_id self.mime_type = mime_type self.delegate_to = delegate_to def execute(self, context): """ Uploads the file to Google cloud storag...
_id=self.google_cloud_storage_conn_id, delegate_to=self.delegate_to) hook.upload( bucket=self.bucket, object=self.dst, mime_type=self.mime_type, filename=self.src)
juix/scripts
motherless-ai/control.py
Python
gpl-3.0
2,116
0.011832
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Authr: João Juíz ''' import sys,os, argparse class Main(object): def argparser(self): parser = argparse.ArgumentPar
ser(description='What this program does') #parser.add_argument("param", type=str, help='Parameter Description') parser.add_argument("-d",'--database', default=False, action='store_true', help='Update database') parser.add_argument("-m",'--matrix', default=False
, action='store_true', help='Update feature matrix') parser.add_argument("-c",'--classify', default=False, action='store_true', help='Classify and symlink files predicted as like to config.predictedLikesDir') #parser.add_argument('--erase', default=False, action='store_true', help='Print destinations of...
shirtsgroup/pygo
analysis/MBAR_foldingcurve.py
Python
gpl-2.0
8,778
0.019822
#!/usr/bin/python2.4 import sys import numpy import pymbar # for MBAR analysis import timeseries # for timeseries analysis import os import os.path import pdb # for debugging import wham from optparse import OptionParser def parse_args(): parser=OptionParser() #parser.add_option("-t", "--temprange", nargs=2,...
py.zeros([K,K,N_max], numpy.float64) # u_kln is reduced pot. ener. of segment n of temp k evaluated at temp l for k in range(K): for l in range(K): u_kln[k,l,0:Nall_k[k]] = beta_k[l] * E_kn[k,0:Nall_k[k]]
#------------------------------------------------------------------------ # Initialize MBAR #------------------------------------------------------------------------ # Initialize MBAR with Newton-Raphson print "" print "Initializing MBAR:" print "--K = number of Temperatures" p...
dahlstrom-g/intellij-community
python/testData/highlighting/multiplePositionalContainers.py
Python
apache-2.0
264
0.045455
def handle(foo, *args, <e
rror descr="multiple * parameters are not allowed">*moreargs</error>): print(foo, args, moreargs) def handle(foo, *args: int, <error descr="multiple * parameters are not allowed
">*moreargs: int</error>): print(foo, args, moreargs)
Elico-Corp/openerp-7.0
purchase_price_list_item/__openerp__.py
Python
agpl-3.0
1,073
0.004664
# -*- encoding: utf-8 -*- # © 2014 Elico Corp (https://www.elico-corp.com) # Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html) { 'name': 'Purchase Price List Item', 'version': '
7.0.1.0.0', 'category': 'Purchase', 'sequence': 19, 'summary': 'Purchase Price List Item', 'description': """
Improve purchase price managment ================================ * In Purchase List Item, the price is fixed based on price_surchage if base is 'fixed on UOP' * If 'fixed on UOP', if product UOP change, the price list price will be change automtically. * Add field '...
yland/mailman3
src/mailman/core/tests/test_pipelines.py
Python
gpl-2.0
5,910
0.000508
# Copyright (C) 2012-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at you...
me='default-posting-pipeline') self.assertEqual(self._msg['list-id'], '<test.example.com>') self.assertEqual(self._msg['list-post'], '<mailto:test@example.com>') def test_discarding_pipeline(self): # If a handler in the pipeline raises DiscardMessage, the message will # be thrown aw...
self.assertTrue(line.endswith( '<ant> discarded by "test-discarding" pipeline handler ' '"discarding": by test handler')) def test_rejecting_pipeline(self): # If a handler in the pipeline raises DiscardMessage, the message will # be thrown away, but with a log message....
pshchelo/heat
heat/tests/aws/test_instance_network.py
Python
apache-2.0
12,448
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
766', 'status': 'ACTIVE', 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f' }} def delete_port(self, port_id): return None class instancesTest(common.HeatTestCase): def setUp(self): super(instancesTest, self).setUp() self.fc = fakes_nova.FakeC...
gin.get_image_id( imageId_input).MultipleTimes().AndReturn(imageId) def _test_instance_create_delete(self, vm_status='ACTIVE', vm_delete_status='NotFound'): return_server = self.fc.servers.list()[1] instance = self._create_test_instance(return_server...
waytai/open
python/st.py
Python
bsd-2-clause
396
0.007576
class Student(object): def __init__(self, name): self.name = name def __repr__(self): print
"8"*20 return 'Student object (name: %s)' % self.name def __str__(self): print "*"*20 return 'Student object
str (name: %s)' % self.name def __call__(self): print "my name is __call__" print Student('liu') s = Student("how are you") s()
MikeLing/shogun
applications/tapkee/samples/isomap.py
Python
gpl-3.0
1,025
0.00878
import shogun as sg import data import numpy as np # load data feature_matrix = data.swissroll() # create features instance features = sg.RealFeatures(feature_matrix) # create Isomap converter instance converter = sg.Isomap() # set number of neighbors to be used converter.set_k(15) # set target dimensionality conve...
pproximate embedding approx_embedding = converter.embed(features) # disable landmark approximation converter.set_landmark(False) # compute cosine distance matrix 'manually' N = features.get_num_vectors() distance_matrix = np.zeros((N,N)) for i in range(N): for j in range(N): distance_matrix[i,j] = \ np.linalg.n...
edding based on created distance converter.embed_distance(distance)
uvNikita/fsm_builder
fsm_builder/handlers/__init__.py
Python
mit
239
0.004184
from .menu import menu_handle
rs
from .main import main_handlers from .toolbar import toolbar_handlers handlers = {} handlers.update(menu_handlers) handlers.update(main_handlers) handlers.update(toolbar_handlers) __all__ = ['handlers']
NikolaYolov/invenio_backup
modules/websubmit/lib/functions/Ask_For_Record_Details_Confirmation.py
Python
gpl-2.0
5,952
0.009409
## This file is part of Invenio. ## Copyright (C) 2008, 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 your option) any later versio...
)]) if rec_other_reportnums != "": rec_reportnums += "".joi
n(["%s<br />\n" % cgi.escape(repnum.strip()) \ for repnum in \ rec_other_reportnums.split("\n")]) raise InvenioWebSubmitFunctionStop(CFG_DOCUMENT_DETAILS_MESSAGE % \ { 'report-numbers' : rec_reportnums, \ ...
OpenMA/openma
modules/instrument/test/python/forceplatetype5Test.py
Python
bsd-3-clause
9,411
0.014557
import ma.instrument import numpy as np import unittest fp5_rso = [0., 0., -16.33887] fp5_sc1 = [-501.800001, 497.799993, 0] fp5_sc2 = [-4.0, 497.799993, 0.] fp5_sc3 = [-4.0, 0., 0.] fp5_sc4 = [-501.800001, 0., 0.] fp5_calib6x8 = [ -1.6121, 0.976148, 105.019852, -19528.01563, -19094.32813, -158.667999, 2.45026...
0.040742, -0.03006, -0.039826, -0.04684
5, -0.066987, -0.048981, -0.04654, -0.020905, -0.043488, -0.027924, -0.034028, -0.07187, -0.044709, -0.041352, -0.031891, -0.033112, -0.036164, -0.029755, -0.037385, -0.043793, -0.049592, -0.080415, -0.027924, -0.027619, -0.007782, -0.019989, -0.017548, -0.029755, -0.037995, -0.017853, -0.006867, -0.012055, -...
jvanz/core
solenv/gdb/boost/smart_ptr.py
Python
gpl-3.0
2,423
0.002476
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- # GDB pretty printers for Boost.Smart Ptr. # # Copyright (C) 2012 Red Hat, Inc., David Tardon <dtardon@redhat.com> # # This file is part of boost-gdb-printers. # # This program is free software; you can redistribute it and/or modify # it under the terms...
es/>. import gdb import boost.util.printing as printing class SmartPtrPrinter: """Prints smart pointers based on Boost.SmartPtr""" def __init__(self, typename, value): self.typename = typename self.value = value def to_string(self): if self.value['px']: print_object...
.parameter('print object') value = self.value['px'].dereference() if print_object: dynamic_type = self.value['px'].dynamic_type value = self.value['px'].cast(dynamic_type).dereference() return "%s %s" % (self.typename, value) else: ...
jobovy/mwdust
mwdust/util/fortranfile.py
Python
bsd-3-clause
8,822
0.003741
# Copyright 2008-2010 Neil Martinsen-Burrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
on's struct module. One can change the default endian-ness and header precision:: >>> f = FortranFile('filename', endian='>', header_prec='l') for a file with little-endian data whose record headers are long integers. """ __docformat__ = "restructuredtext en" import sys _PY3= sys.version > '3'
if _PY3: from io import FileIO file= FileIO import numpy class FortranFile(file): """File with methods for dealing with fortran unformatted data files""" def _get_header_length(self): return numpy.dtype(self._header_prec).itemsize _header_length = property(fget=_get_header_length) d...
hryamzik/ansible
lib/ansible/modules/cloud/vmware/vmware_local_user_manager.py
Python
gpl-3.0
6,371
0.002197
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, IBM Corp # Author(s): Andreas Nafpliotis <nafpliot@de.ibm.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE...
'absent': self.state_create_user, } } local_account_manager_states[self.state][self.check_local_user_manager_state()]() except vmodl.RuntimeFault as runtime_fault: self.module.fail_json(msg=runtime_fault.msg) excep
t vmodl.MethodFault as method_fault: self.module.fail_json(msg=method_fault.msg) except Exception as e: self.module.fail_json(msg=str(e)) def check_local_user_manager_state(self): user_account = self.find_user_account() if not user_account: return 'absent...
ilastikdev/ilastik
ilastik/applets/counting/countingGui.py
Python
gpl-3.0
69,303
0.02857
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
f.editor.brushingInterpreter = DotInterpreter(self.editor.navCtrl,self.editor.brushingControler) self.dotInterpreter=self.editor.brushingInterpreter
#======================================================================= # Init Label Control Ui Custom setup #======================================================================= self._viewerControlUi.label.setVisible(False) self._viewerControlUi.checkShowPredictions.setV...
siliconsmiley/QGIS
python/plugins/GdalTools/tools/doRgbPct.py
Python
gpl-2.0
6,558
0.028362
# -*- coding: utf-8 -*- """ *************************************************************************** doRgbPct.py --------------------- Date : June 2010 Copyright : (C) 2010 by Giuseppe Sucameli Email : brush dot tyler at gmail dot com *******************...
QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit ) QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir ) QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir ) else: self.label.setText( se...
IGNAL( "selectClicked()" ), self.fillInputDir ) QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir ) QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile ) QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOu...
bradallred/gemrb
gemrb/GUIScripts/iwd2/GUIINV.py
Python
gpl-2.0
8,644
0.040375
# -*-python-*- # GemRB - Infinity Engine Emulator # Copyright (C) 2003-2004 The GemRB Project # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your opt...
l = Window.GetControl (0x10000039) Label.SetText (str (hp)) # hp max hpmax = GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS) Label =
Window.GetControl (0x1000003a) Label.SetText (str (hpmax)) # party gold Label = Window.GetControl (0x10000040) Label.SetText (str (GemRB.GameGetPartyGold ())) Button = Window.GetControl (62) Color = GemRB.GetPlayerStat (pc, IE_MAJOR_COLOR, 1) & 0xFF Button.SetBAM ("COLGRAD", 0, 0, Color) Button = Window.GetC...
Weasyl/weasyl
weasyl/test/test_character.py
Python
apache-2.0
2,994
0.003674
import unittest import pytest from libweasyl import ratings from weasyl.test import db_utils from weasyl import character @pytest.mark.usefixtures('db') class SelectCountTestCase(unittest.TestCase): def setUp(self): self.user1 = db_utils.create_user() self.user2 = db_utils.create_user() ...
self.pivotid)) def test_count_nextid(self): self.assertEqual( self.pivot, character.select_count(self.user1, ratings.GENERAL.code, nextid=self.pivotid)) def test_see_friends_character(self):
""" Should be able to see a friend's friends-only character in a listing. """ c = db_utils.create_character(self.friend1, friends_only=True) self.assertEqual( self.count + 1, character.select_count(self.user1, ratings.GENERAL.code)) self.assertEqual( ...
graphicore/multitoner
ghostscript_runner.py
Python
gpl-3.0
5,837
0.005483
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2013 by Lasse Fister <commander@graphicore.de> # # This file is part of Multitoner. # # Multitoner 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, eith...
.set_display_callback(self.instance, c
.byref(self._references['display'])) def cleanup(self): """ Purge the ghostscript instance """ gs.delete_instance(self.instance) self.instance = None def run(self, eps): """ Render the string in eps to a buffer in a format suitable for Cairo surfaces. Return a t...