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
kobotoolbox/kobo_selenium_tests
kobo_selenium_tests/selenium_ide_exported/create_form_test_template.py
Python
gpl-3.0
7,253
0.011995
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException...
orm__start"): break except: pass ti
me.sleep(1) else: self.fail("time out") # Click the form creation button using JavaScript to avoid element not visible errors. # WARNING: The 'runScript' command doesn't export to python, so a manual edit is necessary. # ERROR: Caught exception [ERROR: Unsupported command [runScript | $(...
IntelLabs/hpat
examples/series/rolling/series_rolling_median.py
Python
bsd-2-clause
1,804
0
# ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of sou...
ING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # E...
** import pandas as pd from numba import njit @njit def series_rolling_median(): series = pd.Series([4, 3, 5, 2, 6]) # Series of 4, 3, 5, 2, 6 out_series = series.rolling(3).median() return out_series # Expect series of NaN, NaN, 4.0, 3.0, 5.0 print(series_rolling_median())
silkyar/570_Big_Little
build/ARM/mem/protocol/DMA_Controller.py
Python
bsd-3-clause
246
0.004065
from m5.
params import * from m5.SimObject import SimObject from Controller import RubyController class DMA_Controller(RubyController): type = 'DMA_Controller' dma_sequencer = Param.DMASequencer("") reque
st_latency = Param.Int(6, "")
armstrong/armstrong.core.arm_access
armstrong/core/arm_access/tests/__init__.py
Python
apache-2.0
230
0
from pkgutil import extend_path __path__ = extend_path(__path__, __name__) from .access_m
emberships import * from .fields import * from .migrations import * from
.subscription import * from .forms import * from .widgets import *
Tesora/tesora-horizon
openstack_dashboard/contrib/trove/content/database_datastores/tabs.py
Python
apache-2.0
2,343
0
# Copyright 2015 Cloudwatt # # 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 t...
emplate_dir = 'project/database_datastores/%s' datastore = self.tab_group.kwargs['datastore'] template_file = '_detail_overview_%s.html' % datastore.name
try: template.loader.get_template(template_file) except template.TemplateDoesNotExist: # This datastore type does not have a template file # Just use the base template file template_file = '_detail_overview.html' return template_dir % template_fil...
pureqml/qmlcore
compiler/grammar2.py
Python
mit
21,146
0.03263
import re from collections import OrderedDict import compiler.lang as lang doc_next = None doc_prev_component = None doc_root_component = None class CustomParser(object): def match(self, next): raise
Exception("Expression should implement match method") escape_re = re.compile(r"[\0\n\r\v\t\b\f]") escape_map = { '\0': '\\0', '\n': '\\n', '\r': '\\r', '\v': '\\v', '\t': '\\t', '\b': '\\b', '\f': '\\f' } def escape(str): return escape_re.sub(lambda m: escape_map[m.group(0)], str) class StringParser(CustomPa...
self, next): n = len(next) if n < 2: return quote = next[0] if quote != "'" and quote != "\"": return pos = 1 while next[pos] != quote: if next[pos] == "\\": pos += 2 else: pos += 1 if pos >= n: raise Exception("Unexpected EOF while parsing string") return next[:pos + 1] skip_...
domenicosolazzo/jroc
jroc/nlp/wordnet/WordnetManager.py
Python
gpl-3.0
8,043
0.005098
# -*- coding: utf-8 -*- import itertools """ Languages | ShortCode | Wordnet Albanian | sq | als Arabic | ar | arb Bulgarian | bg | bul Catalan | ca | cat Chinese | zh | cmn Chinese (...
enLemmas = synset.lemma_names() lemmas['en'].extend(enLemmas) if languageCode != "en" and self.__isLanguageAvailable(code=languageCode):
langLemmas = list(sorted(set(synset.lemma_names(lang=wnCode)))) lemmas[languageCode] = langLemmas lemmas['en'] = list(sorted(set(lemmas.get('en', [])))) return lemmas def getSynonyms(self, words=[], language_code="en"): """ Get the synonyms from a list of word...
alfa-jor/addon
plugin.video.alfa/channels/porndish.py
Python
gpl-3.0
3,595
0.013634
# -*- coding: utf-8 -*- #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os, sys from platformcode import config, logger from core import scrapertools from core.item import Item from core import servertools from core import httptools host = 'https://www.porndish.co...
t.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl, fanart=scrapedthumbnail, thumbnail=scrapedthumbnail , plot=scrapedplot) ) return itemlist def lista(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data ...
rchive-body">(.*?)<div class="g1-row g1-row-layout-page g1-prefooter">') patron = '<article class=.*?' patron += 'src="([^"]+)".*?' patron += 'title="([^"]+)".*?' patron += '<a href="([^"]+)" rel="bookmark">' matches = re.compile(patron,re.DOTALL).findall(data) for scrapedthumbnail,scrapedtitle,...
kkdang/synapsePythonClient
synapseclient/cache.py
Python
apache-2.0
11,025
0.004444
# Note: Even though this has Sphinx format, this is not meant to be part of the public docs """ ************ File Caching ************ Implements a cache on local disk for Synapse file entities and other objects with a `FileHandle <https://rest.synapse.org/org/sagebionetworks/repo/model/file/FileHandle.html>`_. This ...
""" Given a file and file_handle_id, return True if an unmodified cached copy of the file exists at the exact path given or False otherwise. :param file_handle_id: :param path: file path at which to look for a cached
copy """ cache_dir = self.get_cache_dir(file_handle_id) if not os.path.exists(cache_dir): return False with Lock(self.cache_map_file_name, dir=cache_dir): cache_map = self._read_cache_map(cache_dir) path = utils.normalize_path(path) cach...
dana-i2cat/felix
optin_manager/src/python/openflow/optin_manager/urls.py
Python
apache-2.0
2,782
0.006111
from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings from expedient.common.rpc4django.utils import rpc_url from openflow.common.utils.OptinThemeManager import OptinThemeManager OptinThemeManager.initialize() admin.autodiscover() urlpatterns = patterns('', (r'...
views.dashboard', name="dashboard"), url(r'^change_profile$', 'openflow.optin_manager.users.views.change_profile', name="change_profile"), (r'^controls/', include('openflow.optin_manager.controls.urls')), (r'^opts/', include('openflow.optin_manager.opts.urls')), (r'^admin_manager/', include('openflo...
lude('openflow.optin_manager.xmlrpc_server.urls')), # For testing (r'^dummyfv/', include('openflow.optin_manager.dummyfv.urls')), (r'^admin/', include(admin.site.urls)), (r'^accounts/', include('registration.urls')), # sfa rpc_url(r'^xmlrpc/sfa/?$', name='optin_sfa'), rpc_url(r'^...
eduNEXT/edx-platform
lms/djangoapps/mobile_api/utils.py
Python
agpl-3.0
223
0
""" Comm
on utility methods for Mobile APIs. """ API_V05 = 'v0.5' API_V1 = 'v1' def parsed_version(version): """ Converts string X.X.X.Y to int tuple (X, X, X) """ retur
n tuple(map(int, (version.split(".")[:3])))
h2oai/h2o-3
h2o-bindings/bin/custom/python/gen_psvm.py
Python
apache-2.0
7,069
0.003537
examples = dict( disable_training_metrics=""" >>> from h2o.estimators import H2OSupportVectorMachineEstimator >>> splice = h2o.import_file("http://h2o-public-test-data.s3.amazonaws.com/smalldata/splice/splice.svm") >>> svm = H2OSupportVectorMachineEstimator(gamma=0.01, ... ran...
gamma=0.01, ... rank_ratio=0.1, ... sv_threshold=0.01, ... disable_training_metrics=False) >>> svm.train(y="C1", training_frame=splice) >>> svm.mse() """, t
raining_frame=""" >>> splice = h2o.import_file("http://h2o-public-test-data.s3.amazonaws.com/smalldata/splice/splice.svm") >>> train, valid = splice.split_frame(ratios=[0.8]) >>> svm = H2OSupportVectorMachineEstimator(disable_training_metrics=False) >>> svm.train(y="C1", training_frame=train) >>> svm.mse() """, val...
adrianmoisey/github3.py
tests/unit/helper.py
Python
bsd-3-clause
1,888
0
try: from unittest import mock except ImportError: import mock import github3 import unittest def build_url(self, *args, **kwargs): # We want to assert what is happening with the actual calls to the # Internet. We can proxy this. return github3.session.GitHubSession().build_url(*args, **kwargs) ...
g definition described_class = None # Sub-classes must also assign a dictionary to this during definition example_data = {} def create_mocked_session(self): MockedSession = mock.create_a
utospec(github3.session.GitHubSession) return MockedSession() def create_session_mock(self, *args): session = self.create_mocked_session() base_attrs = ['headers', 'auth'] attrs = dict( (key, mock.Mock()) for key in set(args).union(base_attrs) ) session.c...
JulyKikuAkita/PythonPrac
cs15211/BalancedBinaryTree.py
Python
apache-2.0
5,434
0.009201
__source__ = 'https://leetcode.com/problems/balanced-binary-tree/#/description' # https://github.com/kamyu104/LeetCode/blob/master/Python/balanced-binary-tree.py # Time: O(n) # Space: O(h), h is height of binary tree # divide and conquer # # Description: Leetcode # 110. Balanced Binary Tree # # Given a binary tree, de...
h node in the tree, so the overall complexity of isBalanced will be O(N^2). This is a top down approa
ch. DFS 2)The second method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise -1 is returned...
acutesoftware/worldbuild
tests/test_crafting.py
Python
gpl-2.0
1,300
0.013077
#!/usr/bin/python3 # -*- coding: utf-8 -*- # test_crafting.py import os import sys import unittest root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." ) pth = root_folder #+ os.sep + 'worldbuild' sys.path.append(pth) from worldbuild.crafting import craft as mod_craft class Test...
tUp(self): unittest.TestCase.setUp(self) def tearDown(self): unittest.TestCase.tearDown(self) def test_01_recipe(self): res = mod_craft.Recipe('1', 'new recipe','20','mix') #print(res) self.assertEqual(str(res),'new recipe') def test_02_dataset_recipe(self): ...
raft.get_fullname('recipes.csv')) self.assertTrue(len(recipes.object_list) > 18) tot_time_to_build = 0 for recipe in recipes.object_list: #print(recipe) tot_time_to_build += int(recipe.base_time_to_build) #print('total time to build all recipes = ' + str(tot_time...
zstackorg/zstack-woodpecker
integrationtest/vm/virtualrouter/vlan/test_chg_instance_offering_online2.py
Python
apache-2.0
2,179
0.010096
''' @author: Quarkonics ''' import os import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.host_operations as host_ops import zstackwoodpecker.operations.resource_operations as res_ops imp...
ze) test_obj_dict.add_instance_offering(new_offering) new_offering_uuid = new_offering.uuid vm = te
st_stub.create_vm(l3_net_list, image_uuid, 'online_chg_offering_vm', instance_offering_uuid=new_offering_uuid, system_tags=['instanceOfferingOnlinechange::true']) test_obj_dict.add_vm(vm) cpuNum = 1 memorySize = 222 * 1024 * 1024 new_offering2 = test_lib.lib_create_instance_offering(cpuNum = cpuNu...
adambreznicky/python
DanMan/IRI_v5_fixer.py
Python
mit
11,750
0.002128
__file__ = 'IRI_v1' __date__ = '5/15/2014' __author__ = 'ABREZNIC' import arcpy, os, datetime, csv, tpp now = datetime.datetime.now() curMonth = now.strftime("%m") curDay = now.strftime("%d") curYear = now.strftime("%Y") today = curYear + "_" + curMonth + "_" + curDay input = arcpy.GetParameterAsText(0) calRhino = ar...
lPoints" arcpy.CopyFeatures_management(excel, pntfeature) arcpy.AddMessage("Point feature class created.") arcpy.AddField_management(pntfeature, "RTE_ID_Orig", "TEXT", "", "", 30) initial = 0 ids = [] cursor = arcpy.da.UpdateCursor(pntfeature, ["ROUTE_ID", "ROUTE_ID_Good", "RTE_ID_Orig"]) f...
al += 1 if id2 not in ids: ids.append(id2) row[0] = id2 row[2] = id cursor.updateRow(row) del cursor del row arcpy.AddMessage("RTE_IDs compiled.") roadslayer = "" pointslayer = "" # mxd = arcpy.mapping.MapDocument(theMXD) mxd = arcpy.mapping.MapDo...
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/tests/test_client.py
Python
lgpl-3.0
16,414
0.007006
"""Tests for parallel client.py Authors: * Min RK """ #------------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this soft...
m IPython.parallel import AsyncResult, AsyncHubResult from IPython.parallel import LoadBalancedView, DirectView from clienttest import ClusterTestCase, segfault, wait, add_engines def setup(): add_engines(4, total=True) class TestClient(ClusterTestCase): def test_ids(self): n = len(self.client.i...
view_indexing(self): """test index access for views""" self.minimum_engines(4) targets = self.client._build_targets('all')[-1] v = self.client[:] self.assertEquals(v.targets, targets) t = self.client.ids[2] v = self.client[t] self.assert_(isinstance(v, Dir...
rtfd/readthedocs.org
readthedocs/projects/migrations/0065_add_feature_future_default_true.py
Python
mit
594
0.001684
# Generated by Django 2.2.16 on 2020-10-01 18:00 from django.db import migrations, models class Migration(mig
rations.Migration): dependencies = [ ('projects', '0064_add_feature_future_default_true'), ] operations = [ migrations.AlterField( model_name='project', name='privacy_level', field=models.CharField(choices=[('public', 'Public'), ('pr
otected', 'Protected'), ('private', 'Private')], default='public', help_text='Should the project dashboard be public?', max_length=20, verbose_name='Privacy Level'), ), ]
socialwifi/jsonapi-requests
setup.py
Python
bsd-3-clause
1,500
0.001333
try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements from setuptools import find_packages from setuptools import setup def get_long_description(): with open('README.md') as readme_file: return readme_file.read() setup( name='jsonapi...
long_description_content_type='text/markdown', author='Social WiFi', author_email='it@socialwifi.com', url='https://github.com/socialwifi/jsonapi-requests', packages=find_packages(exclude=['tests']), install_requires=[str(ir.req) for ir in parse_requirements('base_requirements.txt', session=False)],...
setup_requires=['pytest-runner'], tests_require=['pytest', 'flask'], extras_require={ 'flask': ['flask'] }, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI...
Situphen/Python-ZMarkdown
markdown/extensions/video.py
Python
bsd-3-clause
6,325
0.002213
#!/usr/bin/env python import markdown from markdown.util import etree from markdown.blockprocessors import BlockProcessor import re class VideoExtension(markdown.Extension): def __init__(self, js_support=False, **kwargs): markdown.Extension.__init__(self) self.config = { 'dailymotion...
md, 'vimeo', Vimeo, r'https?
://(www.|)vimeo\.com/(?P<vimeoid>\d+)\S*') self.add_inline(md, 'yahoo', Yahoo, r'https?://screen\.yahoo\.com/.+/?') self.add_inline(md, 'youtube', Youtube, r'https?://(www\.)?youtube\.com/watch\?\S*v=(?P<youtubeid>\S[^&/]+)' r'(?P<c...
mscansian/SigmaWebPlus
plus/kivyapp.py
Python
gpl-3.0
1,840
0.014706
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' kivyapp.py Este arquivo descreve a classe KivyApp que é a classe derivada de kivy.app.App do kivy. Esta classe é necessaria para inicializar um aplicativo com o kivy. Após inicializar a classe, voce deve setar uma classe parent (atraves de KivyApp.par...
essidade de chamar eles) Dependencias (dentro do projeto) ''' from kivy import Config from kivy.app import App from kivy.clock import Clock class KivyApp(App): parent = None def build(self): if self.parent == None: raise KivyAppException("Variable parent not defined in KivyA...
able', 0) Clock.schedule_interval(self.on_update, 0) #Schedule main update def on_start(self): return self.parent.on_start() def on_stop(self): return self.parent.on_stop() def on_pause(self): return self.parent.on_pause() def on_resume(self): ...
dhalperi/incubator-beam
sdks/python/apache_beam/examples/complete/estimate_pi.py
Python
apache-2.0
4,482
0.006475
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "L...
parser = argparse.ArgumentParser() parser.add_argument('--output', required=True, help='Output file to write results to.') known_args, pipeline_args = parser.parse_known_args(argv) # We use the save_main_session option because one or more DoFn's in this # workflow rel...
orted at module level). pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True p = beam.Pipeline(options=pipeline_options) (p # pylint: disable=expression-not-assigned | EstimatePiTransform() | WriteToText(known_args.output, coder=JsonCoder())) ...
lmazuel/azure-sdk-for-python
azure-keyvault/azure/keyvault/version.py
Python
mit
493
0.002028
# co
ding=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 ...
3.7"
caperren/Archives
OSU Coursework/ROB 456 - Intelligent Robotics/Homework 0 - Robotics Probabilities Examples/HW0.py
Python
gpl-3.0
5,437
0.003862
import numpy import scipy import matplotlib.pyplot as pyplot import time numpy.random.seed(int(time.time())) PART_1_COEFFICIENTS = numpy.array([-0.1, 4.0, -0.1, 10.0], float) PART_1_X_LIMITS = [-10.0, 25.0] def plot_form(axis_handle, x_limit=None, title="", x_label="x", y_label="f(x)"): if x_limit i...
the samples according to bin height") function_handle.savefig("hw0_correct_sample_division.pdf", bbox_inches="tight") y_count_correct = numpy.zeros(x_bin.shape) for i in range(0, len(y_rand)): for j in range(len_bin_cdf): if y_rand[i] < y_bin_cdf[j]: y_count_cor...
] += 1 break function_handle_1, axis_handle_1 = pyplot.subplots() axis_handle_1.bar(x_bin + b_width/2.0, y_count_correct, width=b_width, edgecolor="k") plot_form(axis_handle_1, x_limit=PART_1_X_LIMITS, "Samples per bin (correct)", y_label="samples") function_handle.savefig("hw0_sa...
JulienMcJay/eclock
windows/Python27/Lib/site-packages/pywin32-218-py2.7-win32.egg/test/testall.py
Python
gpl-2.0
5,957
0.004029
import sys, os import re import unittest import traceback import pywin32_testutil # A list of demos that depend on user-interface of *any* kind. Tests listed # here are not suitable for unattended testing. ui_demos = """GetSaveFileName print_desktop win32cred_demo win32gui_demo win32gui_dialog win32gui_...
ror: me = sys.argv[0] me = os.path.abspath(me) files = os.listdir(os.path.dirname(me)) suite = unittest.TestSuite() suite.addTest(unittest.FunctionTestCase(import_all)) for file in files: base, ext = os.path.splitext(file) if ext=='.py' and os.path.basename(me) != file: ...
traceback.print_exc() continue if hasattr(mod, "suite"): test = mod.suite() else: test = unittest.defaultTestLoader.loadTestsFromModule(mod) suite.addTest(test) for test in get_demo_tests(): suite.addTest(test) return...
airbnb/airflow
airflow/contrib/hooks/discord_webhook_hook.py
Python
apache-2.0
1,175
0.001702
# # 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...
in a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """This module is deprecated. Please use `airflow.providers.discord.hooks.discord_webhook`.""" import warnings # pylint: disable=unused-import from airflow.providers.disco...
awesto/django-shop
shop/filters.py
Python
bsd-3-clause
1,512
0
from django_filters import filters from djng.forms import fields class Filter(filters.Filter): field_class = fields.Field class CharFilter(filters.CharFilter):
field_class = fields.CharField class BooleanFilter(filters.BooleanFilter): field_class = fields.NullBooleanField class ChoiceFilter(filters.ChoiceFilter): field_class = fields.ChoiceField class TypedChoiceFilter(filters.TypedChoiceFilter): field_class = fields.TypedChoiceField class UUIDFilter(filt...
oiceFilter): field_class = fields.MultipleChoiceField class TypedMultipleChoiceFilter(filters.TypedMultipleChoiceFilter): field_class = fields.TypedMultipleChoiceField class DateFilter(filters.DateFilter): field_class = fields.DateField class DateTimeFilter(filters.DateTimeFilter): field_class = f...
maljac/odoo-addons
partner_person/__openerp__.py
Python
agpl-3.0
2,095
0.000955
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) #
All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foun
dation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Publi...
poswald/microformats
microformats/forms.py
Python
bsd-3-clause
9,632
0.005613
# -*- coding: UTF-8 -*- """ Example Forms for Microformats. Copyright (c) 2009 Nicholas H.Tollervey (http://ntoll.org/contact) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of sou...
ight notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of ntoll.org nor the names of...
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT...
jherrlin/unipass
tests/test_controller.py
Python
mit
1,722
0.002323
import unittest import os from unipass.controller import controller from unipass.model.models import initdb BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class ControllerTest(unittest.TestCase): def setUp(self): initdb() def tearDown(self): try: os.remove('sqlite3.db')...
self.assertTrue(controller.export_data()) def test_importData_False(self): self.assertFalse(controller.import_data(path=BASE_DIR+'/broken.json')) def test_importData_True(self): se
lf.assertTrue(controller.import_data(path=BASE_DIR+'/correct.json')) def test_generatePassword_True(self): self.assertTrue(len(controller.generate_password( True, True, True, True, 10)) == 10)
M4rtinK/pyside-android
tests/QtGui/bug_972.py
Python
lgpl-2.1
1,124
0.003559
import unittest from PySide.QtCore import QSizeF from PySide.QtGui import QGraphicsProxyWidget, QSizePolicy, QPushButton, QGraphicsScene, QGraphicsView from helper import TimedQApplication def createItem(minimum, preferred, maximum, name): w = QGraphicsProxyWidget() w.setWidget(QPushButton(name)) w.setMi...
(maximum) w.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) return w class TestBug972 (TimedQApplication): # Test if the function QGraphicsProxyWidget.setWidget have the correct behavior def testIt(self): scene = QGraphicsScene() minSize = QSizeF(30, 100) prefSize...
xSize = QSizeF(300, 100) a = createItem(minSize, prefSize, maxSize, "A") b = createItem(minSize, prefSize, maxSize, "B") c = createItem(minSize, prefSize, maxSize, "C") d = createItem(minSize, prefSize, maxSize, "D") view = QGraphicsView(scene) view.show() self....
fedspendingtransparency/data-act-broker-backend
dataactcore/scripts/delete_deleted_fpds_idv.py
Python
cc0-1.0
6,000
0.003
import logging import datetime import pandas as pd import numpy as np import os import boto3 from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.stagingModels import DetachedAwardProcurement from dataactco...
s, data) gather_end = datetime.datetime.now() logger.info("Finished gathering records in {} seconds. Tot
al records to delete: {}". format(gather_end - gather_start, len(delete_list))) # Delete records logger.info("Deleting records") delete_records(sess, delete_list, delete_dict) sess.commit() end = datetime.datetime.now() logger.info("FPDS IDV delete finished in %s seconds", end -...
aroquemaurel/Cuis-In
cuisin/restaurant/migrations/0001_initial.py
Python
gpl-2.0
1,387
0.001442
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tags', '0001_initial'), ] operations = [ migrations.CreateModel( name='Restaurant', fields=[ ...
rField(max_length=128)), ('slug', models.SlugField(default=b'', max_length=128)), ('note', models.IntegerField(max_length=2)), ('date', models.DateTimeField(auto_now_add=True, verbose_name=b"Date d'ajout")), ('reservation', models.BooleanField(default=Fals...
(default=b'', max_length=128)), ('address', models.CharField(default=b'', max_length=128)), ('postalcode', models.CharField(default=b'', max_length=16)), ('city', models.CharField(default=b'', max_length=128)), ('tags', models.ManyToManyField(to='tags.Tag'...
szecsi/Gears
GearsPy/Project/Components/Stimulus/FullfieldGradient.py
Python
gpl-2.0
898
0.040089
import Gears as gears from .. import * from .SingleShape import * class FullfieldGradient(SingleShape) : def boot(self, *, duration : 'Stimulus time in frames (unless superseded by duration_s).' = 1, duration_s : 'Stimulus time in se...
apping component (Tone.*)' = Tone.UiConfigured(), **bargs : Pif.Gr
adient ): super().boot(name=name, duration=duration, duration_s=duration_s, pattern = Pif.Gradient( **bargs ), toneMapping = toneMapping, )
qq40660/rss_spider
script/stop_spider.py
Python
gpl-2.0
1,370
0.00219
#!/usr/bin/env python # _*_ coding: utf-8 _*_ import subprocess try: from simplejson import json except: import json # -> list ["422e608f9f28cef127b3d5ef93fe9399", ""] def list_job_ids(host="http://localhost", port=6800, project="default"): command = "curl %s:%d/listjobs.json?proj
ect=%s" % (host, port, project) command_result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.readline() running_ids = json.loads(command_result).get("running")
ids = [] for i in running_ids: ids.append(i["id"]) return ids # str -> list "43242342342354efklajdf14" -> [4234, grep_pid] def id_to_pid(spider_id): command = "ps aux | grep %s | grep -v grep | awk '{print $2}'" % spider_id info = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE...
BRCDcomm/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_ip_access_list.py
Python
apache-2.0
93,629
0.003407
#!/usr/bin/env python import xml.etree.ElementTree as ET class brocade_ip_access_list(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def ip_acl_ip_access_list_standard_name(self, **kwargs): """Auto Generated Cod...
, xmlns="urn:brocade.com:mgmt:brocade-ip-access-list") ip = ET.SubElement(ip_acl, "ip") access_list = ET.SubElement(ip, "access-list") standard = ET.SubElement(access_list, "standard") name_key = ET.SubElement(standard, "name") name_key.text = kwargs.pop('name') hide_ip_a...
eq, "seq-id") seq_id_key.text = kwargs.pop('seq_id') src_host_ip = ET.SubElement(seq, "src-host-ip") src_host_ip.text = kwargs.pop('src_host_ip') callback = kwargs.pop('callback', self._callback) return callback(config) def ip_acl_ip_access_list_standard_hide_ip_acl...
thombashi/typepy
test/converter/_common.py
Python
mit
276
0
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import typepy EXCEPTION_RESULT = "E" def convert_wrapper(typeobj, method): try: return getattr(typeobj, method)() except (typepy.TypeConversionError): return EXCEPTION_RESULT
shreyankg/Dorrie
mckup/build/translations.py
Python
agpl-3.0
628
0.003185
#!/usr/bin/python import sys file = sys.a
rgv[1] f = open(file) print ''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" py:strip=""> ''' try: for lang in f: ...
and \'selected\' or None}">' + lang + '</option>' finally: f.close() print '''</html> '''
tejal29/pants
tests/python/pants_test/pants_run_integration_test.py
Python
apache-2.0
6,636
0.00859
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import sub...
'-jar', '{bundle_name}.jar'.format(bundle_name=bundle_name)] + optional_args,
stdout=subprocess.PIPE, cwd=workdir) stdout, _ = java_run.communicate() java_returncode = java_run.returncode self.assertEquals(java_returncode, 0) return stdout def assert_success(self, pants_run, msg=None): self.assert_result(pants_run, self....
USGM/suds
tests/saxenc.py
Python
lgpl-3.0
1,896
0.003692
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your
option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Lesser General Public License for more details at # ( http://www.gnu.org/licenses/...
f not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( jortel@redhat.com ) # # sax encoding/decoding test. # from suds.sax.element import Element from suds.sax.parser import Parser def basic(): xml = "<a>Me &amp;&amp; &lt;b&gt;my&...
brycedrennan/internetarchive
internetarchive/cli/ia_configure.py
Python
agpl-3.0
2,377
0.000421
# -*- coding: utf-8 -*- # # The internetarchive module is a Python/CLI interface to Archive.org. # # Copyright (C) 2012-2016 Internet Archive # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundat...
figure 'ia'.\n") config_file_path = configure(config_file=session.config_file) print('\nConfig saved to: {0}'.format(config_file_path)) ex
cept AuthenticationError as exc: # TODO: refactor output so we don't have to have special cases # for adding newlines! if args['--username']: print('error: {0}'.format(str(exc))) else: print('\nerror: {0}'.format(str(exc))) sys.exit(1)
dropbox/changes
tests/changes/jobs/test_update_project_stats.py
Python
apache-2.0
1,357
0
from __future__ import absolute_import from changes.constants import Status, Result from changes.config import db from changes.jobs.update_project_stats import ( update_project_stats, update_project_plan_stats ) from changes.models.project import Project from changes.testutils import TestCase class UpdateProject...
te_build( project=
project, status=Status.finished, result=Result.passed, duration=5050, ) job = self.create_job(build) plan = self.create_plan(project) self.create_job_plan(job, plan) update_project_plan_stats( project_id=project.id.hex, ...
qizxdb/qizx-python
qizx/__init__.py
Python
mit
534
0
""" Qizx Python API bindings :copyright: (c) 2015 by Michael Paddon :license: MIT, see LICENSE for more details. """ from .qizx import ( Client, QizxError, QizxBadRequestError, QizxServerError, QizxNotFoundError
, QizxAccessControlError, QizxXMLDataError, QizxCompilationError, QizxEvaluationError, QizxTimeoutError, QizxImportError, UnexpectedResponseError, TransactionError ) __title__ = 'qizx' __version__ = '1.0.2' __author__ = "Michael Paddon" __license__ = '
MIT' __copyright__ = "Copyright 2015 Michael Paddon"
glarue-ol/sensorlab-observer
observer/m_sensorlab/frame_format.py
Python
mpl-2.0
9,968
0.004916
# -*- coding: utf-8 -*- # Generated by h2py from sensorlab-frame-format.h FIRST_BYTE = 0 LAST_BYTE = -1 NODE_ID_FIELD_LENGTH = 4 ENTITY_ID_FIELD_LENGTH = 1 EVENT_ID_FIELD_LENGTH = 1 PROPERTIES_COUNT_FIELD_LENGTH = 1 NAME_LENGTH_FIELD_LENGTH = 1 LINK_ID_FIELD_LENGTH = 1 FRAME_ID_FIELD_LENGTH = 1 FRAME_DATA_LENGTH_FIELD_...
VENT_PAYLOAD FRAME_TX_ENTITY_ID_FIELD = FRAME_TX_PAYLOAD FRAME_TX_ID_FIELD = (FRAME_TX_ENTITY_ID_FIELD + ENTITY_ID_FIELD_LENGTH) FRAME_TX_DATA_LENGTH_FIELD = (FRAME_TX_ID_FIELD + FRAME_ID_FIELD_LENGTH) FRAME_TX_DATA_FIELD = (FRAME_TX_DATA_LENGTH_FIELD + FRAME_DATA_LENGTH_FIELD_LENGTH) FRAME_CONSUME_PAYLOAD = EVENT_PAYL...
ITY_ID_FIELD = FRAME_CONSUME_PAYLOAD FRAME_CONSUME_ID_FIELD = (FRAME_CONSUME_ENTITY_ID_FIELD + ENTITY_ID_FIELD_LENGTH) FRAME_CONSUME_DATA_LENGTH_FIELD = (FRAME_CONSUME_ID_FIELD + FRAME_ID_FIELD_LENGTH) FRAME_CONSUME_DATA_FIELD = (FRAME_CONSUME_DATA_LENGTH_FIELD + FRAME_DATA_LENGTH_FIELD_LENGTH) PROPERTY_DECLARATION_ID_...
ScienceWorldCA/domelights
backend/artnet-bridge/artnet/scripts/alternating_color_fades.py
Python
apache-2.0
776
0.03866
import time, logging from artnet import dmx, fixtures, rig
from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r
.groups['all'] def all_red(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info("Running script %s" % _...
Ganben/solverify
analyze/ethereum_data1.py
Python
gpl-3.0
508
0.021654
#encoding=utf-8 # th
is the interface to create your own data source # this class pings a private / public blockchain to get the balance and code information from web3 import Web3, KeepAliveRPCProvider class EthereumData: def __init__(self): self.host = 'x.x.x.x' self.port = '8545' self.web3 = Web3(KeepAliveRPCProvider(host=self.h...
, address): return self.web3.eth.getBalance(address) def getCode(self, address): return self.web3.eth.getCode(address)
google/jax
jax/_src/lax/windowed_reductions.py
Python
apache-2.0
42,865
0.007652
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
lat_init_values) jaxpr, consts, out_tree = lax._variadic_reduction_jaxpr( computation, tuple(flat_init_avals), init_value_tree) if operand_tree != out_tree: rais
e ValueError( 'reduce_window output must have the same tree structure as the operands' f' {operand_tree} vs. {out_tree}') out_flat = reduce_window_p.bind( *(flat_operands + flat_init_values), jaxpr=jaxpr, consts=consts, window_dimensions=tuple(window_dimensions), window_strid...
spradeepv/dive-into-python
hackerrank/domain/python/sets/intersection.py
Python
mit
1,336
0.005988
""" Task Students of District College have subscription of English and French newspapers. Some students have subscribed to only English, some have subscribed to only French and some have subscribed to both newspapers. You are given two sets of roll numbers of students, who have subscribed to English and French newspap...
mber of students in college<1000 Output Format Output total number of students who have su
bscriptions in both English and French. Sample Input 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output 5 Explanation Roll numbers of students who have both subscriptions: 1, 2, 3, 6 and 8. Hence, total is 5 students. """ n1 = int(raw_input()) english = set(map(int, raw_input().split())) n2 = int(raw_input()...
aalhour/PyCOOLC
pycoolc/semanalyser.py
Python
mit
18,923
0.003701
#!/usr/bin/env python3 # ----------------------------------------------------------------------------- # semanalyser.py # # Author: Ahmad Alhour (aalhour.com). # Date: TODO # Description: The Semantic Analyser module. Implements Semantic Analysis and # Type Checking. # --------------------...
lass attributes. * `SELF_TYPE` can **not** be used with Static Dispatch (i.e. `T` i
n `m@T(expr1,...,exprN)`). * `SELF_TYPE` can **not** be used as the type of Formal Parameters. #### Least-Upper Bound Relations: * `lub(SELF_TYPE.c, SELF_TYPE.c) = SELF_TYPE.c`. * `lub(SELF_TYPE.c, T) = lub(C, T)`. * `lub(T, SELF_TYPE.c) = lub(C, T)`. ## Semantic Analysis Passes **[incomplete]** 1. Gath...
miniconfig/home-assistant
homeassistant/components/zwave/util.py
Python
mit
3,178
0
"""Zwave util methods.""" import logging from . import const _LOGGER = logging.getLogger(__name__) def check_node_schema(node, schema): """Check if node matches the passed node schema.""" if (const.DISC_NODE_ID in schema and node.node_id not in schema[const.DISC_NODE_ID]): _LOGGER.debug(...
e passed value schema.""" if (const.DISC_COMMAND_CLASS in schema and value.command_class n
ot in schema[const.DISC_COMMAND_CLASS]): _LOGGER.debug("value.command_class %s not in command_class %s", value.command_class, schema[const.DISC_COMMAND_CLASS]) return False if (const.DISC_TYPE in schema and value.type not in schema[const.DISC_TYPE]): _LOGGER...
joberreiter/pyload
module/plugins/crypter/XFileSharingProFolder.py
Python
gpl-3.0
2,857
0.011551
# -*- coding: utf-8 -*- import re from module.plugins.internal.XFSCrypter import XFSCrypter, create_getInfo class XFileSharingProFolder(XFSCrypter): __name__ = "XFileSharingProFolder" __type__ = "crypter" __version__ = "0.14" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?(?:\...
self.req.close() if not self.account: self.account = self.pyload.accountManager.getAccountPlugin(self.PLUGIN_NAME) if not self.account: self.account = self.pyload.accountManager.getAccountPlugin(self.__name__) if self.account: if not self.account.PLUGIN...
` in 0.4.10 self.account.user = self.account.select()[0] if not self.account.logged: self.account = False getInfo = create_getInfo(XFileSharingProFolder)
gotostack/swift
test/probe/test_object_handoff.py
Python
apache-2.0
9,005
0
#!/usr/bin/python -u # Copyright (c) 2010-2012 OpenStack Foundation # # 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 ap...
unt, container)[1]] if obj not in objs: raise Exception( 'Container server %s:%s did not know about object' % (cnode['ip'], cnode['port'])) start_server(onode['port'], self.port2server, self.pids) exc = None try: dir...
f.account, container, obj) except ClientException as err: exc = err self.assertEquals(exc.http_status, 404) # Run the extra server last so it'll remove its extra partition processes = [] for node in onodes: try: ...
mbareta/edx-platform-ft
lms/djangoapps/ccx/migrations/0018_auto_20170721_0611.py
Python
agpl-3.0
472
0.002119
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime class
Migration(migrations.Migration): dependencies = [ ('ccx', '0017_auto_20170721_0437'), ] operations = [ migrations.AlterField( model_name='customcourseforedx', name='time', field=models.DateTimeField(default=datetime.datetime(2017, 7, 21, 6, 10
, 51, 471098)), ), ]
joelsmith/openshift-tools
ansible/roles/lib_git/library/git_rebase.py
Python
apache-2.0
15,173
0.002504
#!/usr/bin/env python # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) | | .` | (_) || | | _|| |) | | ...
' cmd = ["clone"] if bare: cmd += ["--bare"] cmd += [repo, dest] results = self.git_cmd(cmd) return results def _status(self, porcelain=False, show_untracked=True): ''' Do a git status ''' cmd = ["status"] if porcelain: c...
append('--untracked-files=no') results = self.git_cmd(cmd, output=True, output_type='raw') return results def _checkout(self, branch): ''' Do a git checkout to <branch> ''' cmd = ["checkout", branch] results = self.git_cmd(cmd, output=True, output_type='raw') ret...
mozilla/pymake
pymake/parserdata.py
Python
mit
33,522
0.002357
from __future__ import print_function import logging, re, os import data, parser, util from pymake.globrelative import hasglob, glob from pymake import errors try: from cStringIO import StringIO except ImportError: from io import StringIO _log = logging.getLogger('pymake.data') _tabwidth = 4 class Location...
d classes which follow this one in a stream of Statement instances. Instances also contain a boolean property `doublecolon` which says whether this is a doublecolon rule. Doublecolon rules are rules that are always executed, if they are evaluated. Normally, rules are only executed if their target i...
etexp', 'depexp', 'doublecolon') def __init__(self, targetexp, depexp, doublecolon): assert isinstance(targetexp, (data.Expansion, data.StringExpansion)) assert isinstance(depexp, (data.Expansion, data.StringExpansion)) self.targetexp = targetexp self.depexp = depexp self.d...
librallu/cohorte-herald
python/herald/transports/http/beans.py
Python
apache-2.0
3,526
0
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Herald HTTP beans definition :author: Thomas Calmant :copyright: Copyright 2014, isandlaTech :license: Apache License 2.0 :version: 0.0.3 :status: Alpha .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0 (the "License"); you...
------------------------------------------------------------------------- @functools.total_ordering class HTTPAccess(object): """ Description of an HTTP access """ def __init__(self, host,
port, path): """ Sets up the access :param host: HTTP server host :param port: HTTP server port :param path: Path to the Herald service """ # Normalize path if path[0] == '/': path = path[1:] self.__host = host self.__port = ...
renatopp/liac-soccer
clients/python/setup.py
Python
mit
495
0.024242
import sys from
cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need fine tuning. build_exe_options = {"packages": ["math", "json"], "excludes": ["tkinter"]} # GUI applications require a different base on Windows (the default is for a # console application). setup( name = "liac-soccer", ...
xecutables = [Executable("ball_follower.py")])
OpenCMISS/neon
src/opencmiss/neon/ui/simulations/ui_biomeng321lab1.py
Python
apache-2.0
18,237
0.003784
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'res/designer/simulations/biomeng321lab1.ui' # # Created: Fri Mar 4 13:11:44 2016 # by: pyside-uic 0.2.15 running on PySide 1.2.1 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Biome...
Layou
t_6.setObjectName("gridLayout_6") self.label_9 = QtGui.QLabel(self.groupBox_5) font = QtGui.QFont() font.setPointSize(12) font.setWeight(75) font.setBold(True) self.label_9.setFont(font) self.label_9.setObjectName("label_9") self.gridLayout_6.addWidget(sel...
mezz64/home-assistant
tests/components/nest/test_climate_sdm.py
Python
apache-2.0
43,509
0.000207
""" Test for Nest climate platform for the Smart Device Management API. These tests fake out the subscriber/devicemanager, and are not using a real pubsub subscriber. """ from google_nest_sdm.device import Device from google_nest_sdm.event import EventMessage import pytest from homeassistant.components.climate.const...
CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, FAN_LOW, FAN_OFF, FAN_ON, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COO
L, HVAC_MODE_OFF, PRESET_ECO, PRESET_NONE, PRESET_SLEEP, ) from homeassistant.const import ATTR_TEMPERATURE from .common import async_setup_sdm_platform from tests.components.climate import common PLATFORM = "climate" async def setup_climate(hass, raw_traits=None, auth=None): """Load Nest clima...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_route_filter_rules_operations.py
Python
mit
28,535
0.005011
# 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 ...
oute_filter_name: str, rule_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map...
l = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'ruleName': s...
MLAB-project/pymlab
src/pymlab/sensors/i2cpwm.py
Python
gpl-3.0
2,819
0.010287
#!/usr/bin/python import time from pymlab.sensors import Device #TODO: set only one pin, not all bus class I2CPWM(Device): 'Python library for I2CPWM01A MLAB module with NXP Semiconductors PCA9531 I2C-bus LED dimmer' MODES = { 'X': 0b00, 'LOW': 0b01, 'PWM0': 0b10, ...
'PSC1 is used to program the period of the PWM output.' self.PWM_PSC1 = 0x03 'The PWM1 register determines the duty cycle of BLINK1. The outputs are LOW (LED on) when the count is less than the value in PWM1 and HIGH (LED off) when it is greater. If PWM1 is programmed with 00h, then the PWM1 output is...
data.' self.PWM_LS0 = 0x05 self.PWM_LS1 = 0x06 def set_pwm0(self, frequency, duty): # frequency in Hz, Duty cycle in % (0-100) period = int((1.0/float(frequency))*152.0)-1 duty = int((float(duty)/100.0)*255.0) self.bus.write_byte_data(self.address, 0x01, period) se...
SimplyPaper/SimplyPaper.github.io
AzureBus.py
Python
apache-2.0
842
0.008314
from azure.servicebus import ServiceBusService, Message, Queue #c-types bus_service = ServiceBusService( service_namespace='SimplyPaper',
shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value='1Y4YNh7uQ/buNi1v3xunn6F6vfSsJ5+nrmiwKY2WM04') #Endpoint=sb://simplypaper.servicebus.windows.net/; #SharedAccessKeyName=RootManageSharedAccessKey; #SharedAccessKey=1Y4YNh7uQ/buNi1v3xunn6F6vfSsJ5+nrmiwKY2WM04= bus_service.create_qu...
t_message_time_to_live = 'PT1M' bus_service.create_queue('taskqueue', queue_options) msg = Message(b'Test Message Simply Papaer') bus_service.send_queue_message('taskqueue', msg) msg = bus_service.receive_queue_message('taskqueue', peek_lock=False) print(msg.body)
hbrunn/bank-statement-import
account_bank_statement_import/models/account_bank_statement_import.py
Python
agpl-3.0
17,538
0
# -*- coding: utf-8 -*- """Framework for importing bank statement files.""" import logging import base64 from StringIO import StringIO from zipfile import ZipFile, BadZipfile # BadZipFile in Python >= 3.2 from openerp import api, models, fields from openerp.tools.translate import _ from openerp.exceptions import Warn...
ns': list of dict containing : - 'name': string (e.g: 'KBC-INVESTERINGSKREDIET 787-5562831-01') - 'date': date - 'amount': float - 'unique_import_id': string -o 'account_number': string Will be used t...
ner_name': string -o 'ref': string """ raise UserError(_( 'Could not make sense of the given file.\n' 'Did you install the module to support this type of file?' )) @api.model def _check_parsed_data(self, statements): # pylint: disable=no-s...
ebmdatalab/openprescribing
openprescribing/pipeline/migrations/0002_tasklog_formatted_tb.py
Python
mit
402
0
# -*- cod
ing: utf-8 -*- # Generated by Django 1.9.1 on 2017-07-05 10:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pipeline', '0001_initial'), ] operations = [ migrations.AddField(
model_name='tasklog', name='formatted_tb', field=models.TextField(null=True), ), ]
tony-rasskazov/meteo
weewx/bin/weewx/drivers/wmr200.py
Python
mit
77,782
0.002031
# # Copyright (c) 2013 Chris Manton <cmanton@gmail.com> www.onesockoff.org # See the file LICENSE.txt for your full rights. # # Special recognition to Lars de Bruin <l...@larsdebruin.net> for contributing # packet decoding code. # # pylint parameters # suppress global variable warnings # pylint: disable-msg=W0603 # ...
ace) except usb.USBError, exception: logcrt(('open_device() Unable to' ' claim USB interface. Reason: %s' % exception)) raise weewx.WakeupError(exception) def close_device(self): """Close a device for access. NOTE(CMM) There is no busses[].device...
e() so under linux the file descriptor will remain open for the life of the process. An OS independant mechanism is required so 'lsof' and friends will not be cross platform.""" try: self.handle.releaseInterface() except usb.USBError, exception: logcrt('cl...
s1s5/django_busybody
tests/test_models.py
Python
mit
11,615
0.001213
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django_busybody ------------ Tests for `django_busybody` models module. """ from __future__ import unicode_literals import datetime import json import uuid from mock import patch from django.test import TestCase # from django.conf import settings from django.co...
self.assertEqual(models.EncryptTest.objects.filter(with_encrypt_with_log__exact='1').count(), 0) def test_encrypt(self): self.assertEqual(models.EncryptTest.objects.filter(without_encrypt__exact='1').count(), 1) self.assertEqual(models.EncryptTest.objects.filter(with_encrypt__exact='1').count(), 0...
EncryptTest.objects.filter(without_encrypt_with_log__exact='1').count(), 1) self.assertEqual(models.EncryptTest.objects.filter(with_encrypt_with_log__exact='1').count(), 0) def test_unicode(self): obj = models.EncryptTest.objects.create( without_encrypt='日本語', with_encrypt='...
ricardodeazambuja/BrianConnectUDP
examples/OutputNeuronGroup_multiple_inputs.py
Python
cc0-1.0
2,862
0.014675
''' Example of a spike receptor (only receives spikes) In this example spikes are received and processed creating a raster plot at the end of the s
imulation. ''' from brian import * import numpy from brian_multiprocess_udp import BrianConnectUDP # The main function with the NeuronGroup(s) and Synapse(s) must be named "main_NeuronGroup". # It will receive two objects: input_Neuron_Group and the simulation_clock. The input_Neuron_Group # will supply the input s...
must be the same size of the NeuronGroup who is # going to interface with the rest of the system to send spikes. # The function must return all the NeuronGroup objects and all the Synapse objects this way: # ([list of all NeuronGroups],[list of all Synapses]) # and the FIRST (index 0) NeuronGroup of the list MUST be th...
JShadowMan/package
python/multi-process-thread/multiprocess.py
Python
mit
660
0.019697
#!/usr/bin/env python3 from multiprocessing import Process, Pool import os, time def proc(name): print(time.asctime(), 'child process(name: %s) id %s. ppid %s' % (name, os.getpid(), os.getppid(
))) time.sleep(3) print(time.asctime(), 'child process end') if __name__ == '__main__': p = Process(target = proc, args = ('child',)) print(time.asctime(), 'child process will start') p.start() p.join() print('first child process end') pl = Pool(4) f
or index in range(4): pl.apply_async(proc, args = (index,)) pl.close() pl.join() print(time.asctime(), 'parent process end')
mcallaghan/tmv
BasicBrowser/scoping/migrations/0129_auto_20170815_0946.py
Python
gpl-3.0
1,435
0.003484
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-15 09:46 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependenci
es = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('scoping', '0128_auto_20170808_0954'), ] operations = [
migrations.CreateModel( name='ProjectRoles', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('role', models.CharField(choices=[('OW', 'Owner'), ('AD', 'Admin'), ('RE', 'Reviewer'), ('VE', 'Viewer')], ma...
ParkJinSang/SIMONFramework
src/SIMON_Py/SIMON/algorithms/SIMONAlgorithmMain.py
Python
apache-2.0
1,860
0.003763
__author__ = 'PARKJINSANG' from SIMON.algorithms.genetic.SIMONGeneticAlgorithm import SIMONGeneticAlgorithm # # genetic algorithm for learning and evaluating # # def run_genetic_algorithm(group, actionPool, propertyPool): algorithm = SIMONGeneticAlgorithm() for actionName, actionDnaList in actionPool.items...
.crossover_action(selectedPool) mutatedPool = algorithm.mutation_action(crossedPool) update_action(group, actionName, mutatedPo
ol) selectedPool = algorithm.selection_property(group, propertyPool) crossedPool = algorithm.crossover_property(selectedPool) mutatedPool = algorithm.mutation_property(crossedPool) update_property(group, mutatedPool) # # update action dna in the group # # def update_action(group, actionName, actionP...
EdwardJKim/nbgrader
nbgrader/preprocessors/clearsolutions.py
Python
bsd-3-clause
5,142
0.000778
from traitlets import Unicode, Bool from textwrap import dedent from .. import utils from . import NbGraderPreprocessor class ClearSolutions(NbGraderPreprocessor): code_stub = Unicode( "# YOUR CODE HERE\nraise NotImplementedError()", config=True, help="The code snippet that will replace ...
xt_stub.split("\n") new_lines = [] in_solution = False replaced_solution = False for line in lines: # begin the solution area if line.strip() == self.begin_solution: # check to
make sure this isn't a nested BEGIN # SOLUTION region if in_solution: raise RuntimeError( "encountered nested begin solution statements") in_solution = True replaced_solution = True # replace it...
semitki/canales
fileupload/urls.py
Python
mit
514
0.001946
# encoding: utf-8 from django.conf.urls i
mport url from fileupload.views import ( BasicVersionCreat
eView, BasicPlusVersionCreateView, jQueryVersionCreateView, AngularVersionCreateView, PictureCreateView, PictureDeleteView, PictureListView, ) urlpatterns = [ url(r'^new/$', PictureCreateView.as_view(), name='upload-new'), url(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), name='...
akvo/akvo-rsr
akvo/rsr/migrations/0091_auto_20170208_1035.py
Python
agpl-3.0
2,382
0.001679
# -*- coding: utf-8 -*- from django.db import models, migrations def indicator_links(apps, schema_editor): """ Migration generating foreign keys from indicators and indicator periods in child results frameworks to parents of the same object type in the parent results framework """ Result = apps.get_...
child_indicator.parent_indic
ator = parent_indicator # basic saving only super(Indicator, child_indicator).save() # Same pattern applies to IndicatorPeriods parent_periods = IndicatorPeriod.objects.filter(indicator__result=result) for parent_period in parent_periods: child_perio...
eduNEXT/edunext-platform
import_shims/lms/experiments/stable_bucketing.py
Python
agpl-3.0
407
0.009828
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_impo
rt warn_deprecated_import('experiments.stable_bucketing', 'lms.djangoapps.experiments.stable_bucketing') from lms.dja
ngoapps.experiments.stable_bucketing import *
mshuffett/MetaPyMusic
playlister.py
Python
gpl-2.0
1,557
0.001285
import os import cPickle as pkl from collections import namedtuple import requests from bs4 import BeautifulSoup Song = namedtuple('Song', ['title', 'artist', 'album', 'length']) class Playlist(object): def __init__(se
lf, title, url): self.title = title self.file_name = title.lower().replace(' ', '-') + '.pkl' self.url = url if os.path.isfile(self.file_name): self.load_from_pickle() else: self.songs = [] def load_from_pickle(self): with open(self.file_name...
et(url) soup = BeautifulSoup(resp.text) for song_elem in (soup.find(class_='songs') .find_all(class_='media-body')): title = song_elem.h4.text ps = song_elem.find_all('p') artist, album = ps[0].text.split(u' \xb7 ') length =...
jayceyxc/hue
apps/about/src/about/tests.py
Python
apache-2.0
2,701
0.007775
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
rom django.contrib.auth.models import User from django.core.urlresolvers import reverse from nose.tools import assert_true, assert_false, assert_equal from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access from desktop.models import Settings from oozie.tests imp...
"about", "about") self.client_admin = make_logged_in_client(username="about_admin", is_superuser=True) grant_access("about_admin", "about_admin", "about") class TestAbout(TestAboutBase, OozieBase): def test_admin_wizard_permissions(self): response = self.client_admin.get(reverse('about:index')) as...
Thortoise/Super-Snake
Blender/animation_nodes-master/nodes/number/float_range_list.py
Python
gpl-3.0
1,324
0.009819
import bpy from bpy.props import * from ... sockets.info import toListDataType from ... base_types.node import AnimationNode class FloatRangeListNode(bpy.types.Node, AnimationNode): bl_idname = "an_FloatRangeListNode" bl_label = "Number Range" dynamicLabelType = "ALWAYS" onlySearchTags = True sear...
") self.newInput(self.dataType, "Step", "step", value = 1) self.newOutput(toListDataType(self.dataType), "List", "list") def getExecutionCode(self): if self.dataType == "Float": return "list = [start + i * step for i in
range(amount)]" if self.dataType == "Integer": return "list = [int(start + i * step) for i in range(amount)]"
owlabs/incubator-airflow
tests/contrib/hooks/test_gcp_video_intelligence_hook.py
Python
apache-2.0
3,290
0.002736
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
=None,
location_id=None, retry=None, timeout=None, metadata=None, )
wagnerand/zamboni
mkt/developers/urls.py
Python
bsd-3-clause
8,583
0.001864
from django import http from django.conf.urls import include, patterns, url from rest_framework.routers import SimpleRouter from lib.misc.urlconf_decorator import decorate import amo from amo.decorators import write from amo.urlresolvers import reverse from mkt.api.base import SubRouter from mkt.developers.api impo...
resh_manifest'), url('^ownership$', views.ownership, name='mkt.developers.apps.owner'), url('^enable$', views.enable, name='mkt.developers.apps.enable'), url('^delete$', views.delete, name='mkt.developers
.apps.delete'), url('^disable$', views.disable, name='mkt.developers.apps.disable'), url('^publicise$', views.publicise, name='mkt.developers.apps.publicise'), url('^status$', views.status, name='mkt.developers.apps.versions'), url('^blocklist$', views.blocklist, name='mkt.developers.apps.blocklist'), ...
smithsane/openstack-env
openstack_env/openstack.py
Python
bsd-3-clause
3,248
0
# Copyright (c) 2015, Artem Osadchyi # # 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, Versi...
= _get_url("data-processing", credentials) sahara_url += "/" + credentials.tenant_id return
data_processing_client.Client( input_auth_token=credentials.auth_token, project_name=credentials.tenant, sahara_url=sahara_url, ) def _get_url(service_type, credentials): i_client = identity(credentials) service = i_client.services.find(type=service_type) endpoint = i_client....
Debian/devscripts
scripts/devscripts/test/test_help.py
Python
gpl-2.0
2,924
0
# test_help.py - Ensure scripts can run --help. # # Copyright (C) 2010, Stefano Rivera <stefanor@ubuntu.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all c...
for fd in fds: fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK) while time.time() - started < TIMEOUT: for fd in select.select(fds, [], fds,
TIMEOUT)[0]: out.append(os.read(fd, 1024)) if process.poll() is not None: break if process.poll() is None: os.kill(process.pid, signal.SIGTERM) time.sleep(1) if process.poll()...
lmazuel/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/vault_certificate.py
Python
mit
2,185
0
# 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 ...
ertificate_store: str """ _attribute_map = { 'certificate_url': {'key': 'certificateUrl', 'type': 'str'}, 'certificate_store': {'key': 'certificateStore', 'type': 'str'},
} def __init__(self, **kwargs): super(VaultCertificate, self).__init__(**kwargs) self.certificate_url = kwargs.get('certificate_url', None) self.certificate_store = kwargs.get('certificate_store', None)
fernandolobato/balarco
clients/migrations/0001_initial.py
Python
mit
614
0.001629
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-02-17 01:37 from __future__ import unicode_literals from django.db import mig
rations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Client', fields=[ ('id', models.AutoField(auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('address', models.CharField(max_length=100)), ], ), ]
Azure/azure-sdk-for-python
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_03_01/aio/operations/_action_groups_operations.py
Python
mit
24,867
0.005027
# 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 ...
esource :keyword callable cls: A custom type or function that will be passed the direct response :return: ActionGroupResource, or the result of cls(response)
:rtype: ~$(python-base-namespace).v2018_03_01.models.ActionGroupResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ActionGroupResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoun...
jorisvanzundert/sfsf
sfsf/epub_to_txt_parser.py
Python
mit
3,042
0.029934
import sys, getopt import errno import os.path import epub import lxml from bs4 import BeautifulSoup class EPubToTxtParser: # Epub parsing specific code def get_linear_items_data( self, in_file_name ): book_items = [] book = epub.open_epub( in_file_name ) for item_id, linear in book.op...
t_file_name = None, None for o, a in opts: if o == '-i': in_file_name = a elif o == '-o': out_file_name = a return ( in_file_name, out_file_name ) # Main if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], "i:o:") assert( len(opts...
opts( opts ) except getopt.GetoptError as e: print( str( e ) ) print_usage_and_exit() except AssertionError: print_usage_and_exit() try: parser = EPubToTxtParser() narrative_text = parser.narrative_from_epub_to_txt( in_file_name ) if( out_file_name != None ):...
valsson/plumed2
user-doc/tutorials/old_tutorials/munster/SCRIPTS/do_fes.py
Python
lgpl-3.0
2,940
0.019388
import math import sys # read FILE with CVs and weights FILENAME_ = sys.argv[1] # number of CVs for FES NCV_ = int(sys.argv[2]) # read minimum, maximum and number of bins for FES grid gmin = []; gmax = []; nbin = [] for i in range(0, NCV_): i0 = 3*i + 3 gmin.append(float(sys.argv[i0])) gmax.append(float(s...
sto[key] = w # calculate free-energy and minimum value min_fes = 1.0e+15 for
key in histo: histo[key] = -KBT_ * math.log(histo[key]) if(histo[key] < min_fes): min_fes = histo[key] # total numbers of bins nbins = 1 for i in range(0, len(nbin)): nbins *= nbin[i] # print out FES log = open(FESFILE_, "w") # this is needed to add a blank line xs_old = [] for i in range(0, nbins): # ge...
feist/pcs
pcs/rule.py
Python
gpl-2.0
41,255
0.000194
import re import xml.dom.minidom from typing import List, Any, Optional from pcs import utils from pcs.cli.reports.output import warn from pcs.common import ( const, pacemaker, ) from pcs.common.str_tools import format_list_custom_last_separator # pylint: disable=not-callable # main functions def parse_ar...
: exp_parts.append("(id:%s)" % expression.getAttribute("id"
)) return ["Expression: " + " ".join(exp_parts)] def _list_attributes(self, element): attributes = utils.dom_attrs_to_list(element, with_id=False)
white111/CMtestpy
bin/cmtest.py
Python
lgpl-2.1
7,516
0.023018
#!/usr/bin/python ################################################################################ # # Module: cmtest.py # # Author: Paul Tindle ( mailto:Paul@Tindle.org ) # # Descr: Main Test executive # # Version: 0.1 $Id$ # # Changes: 05/18/17 Conversion from perl - JSW # # Still ToDo: # # Licens...
conds)") parser.add_option("-F", "--Force", dest="Force", type="int", default=0, help="Force Session #") parser.add_option("-r", "--regress", dest="Regress", default="null", help="Directly execute a subroutine") parser.add_option("-U", "--User", dest="User",...
le, will default to tmp/cmtest.xml") (options, args) = parser.parse_args() #if not options.Session : #parser.error("-s session# required") Globals.Debug += options.Debug Globals.Verbose += options.Verbose Globals.Menu1 = options.Menu1 Globals.Regress = options.Regress Globals....
OpenGov/python_data_wrap
tests/table_wrap_test.py
Python
lgpl-2.1
4,724
0.005292
# This import fixes sys.path issues from . import parentpath from datawrap import tablewrap import unittest class TableWrapTest(unittest.TestCase): ''' Tests the capability to wrap 2D objects in Tables and transpose them. ''' def setUp(self): # self.table doesn't need the tablewrap.Table objec...
self.assertEqual(translice[1][0], self.table[0][tslice][1]) self.assertEqual(translice[0][2], self.table[2][tslice][0]) self.assertEqual(translice[1][2], self.table[2][tslice][1]) tslice = slice(None, 1, None) translice = self.transpose[tslice] self.assertEqual(len(translice)...
ce[0][0], self.table[0][tslice][0]) self.assertEqual(translice[0][2], self.table[2][tslice][0]) def test_verify(self): # Check that valid finds bad tables bad_table = [[1, 2, 3], ['a', 'b'], [4, 5, 6]] self.assertRaises(ValueError, lambda: tablewrap.Table(bad_table, True, False)) ...
klahnakoski/TestLog-ETL
vendor/mo_collections/persistent_queue.py
Python
mpl-2.0
7,580
0.002111
# 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, divis...
def __getitem__(self, item): return self.db[str(item + self.start)] def pop(self, timeout=None): """ :param timeout: OPTIONAL DURATION :return: None, IF timeout PASSES """ with self.lock: while not self.please_stop: if self.db.status....
value = self.db[str(self.start)] self.start += 1 return value if timeout is not None: with suppress_exception: self.lock.wait(timeout=timeout) if self.db.status.end <= self.start: ...
troismph/matasano-challenges
src/challenge48.py
Python
gpl-3.0
78
0
from
challenge47 import bleichenbacher def crack()
: bleichenbacher(768)
vpramo/contrail-neutron-plugin
neutron_plugin_contrail/plugins/opencontrail/vnc_client/router_res_handler.py
Python
apache-2.0
24,484
0
# Copyright 2015. 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 la...
er(router_q)) rtr_uuid = self._resource_create(rtr_obj) contrail_extensions_enabled = self._kwargs.get( 'contrail_extensions_enabled',
False) # read it back to update id perms rtr_obj = self._resource_get(id=rtr_uuid) self._router_add_gateway(router_q, rtr_obj) return self._rtr_obj_to_neutron_dict( rtr_obj, contrail_extensions_enabled=contrail_extensions_enabled) class LogicalRouterDeleteHandler(res_handl...
Yenthe666/Odoo_Samples
sale/sale.py
Python
agpl-3.0
69,258
0.005761
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
Conditions', translate=True, help="Default terms and conditions for quotations."), } class sale_order(osv.osv): _name = "sale.order" _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = "Sales Order" _track = { 'state': { 'sale.mt_order_confirmed': lambda self, cr, u...
'sale.mt_order_sent': lambda self, cr, uid, obj, ctx=None: obj.state in ['sent'] }, } def _amount_line_tax(self, cr, uid, line, context=None): val = 0.0 for c in self.pool.get('account.tax').compute_all(cr, uid, line.tax_id, line.price_unit * (1-(line.discount or 0.0)/100.0), lin...
arruda/cloudfuzzy
manage.py
Python
mit
253
0
#!/usr/bin/env python
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cloudfuzzy.settings") from django.core.management import execute_from_command_line execute_from_comm
and_line(sys.argv)
kdungs/python-mcheck
mcheck/__init__.py
Python
mit
1,840
0
""" Define a Check monad and corresponding functions. """ from functools import (reduce, partial) class Check: """ This super class is not really necessary but helps make the structure clear. data Check a = Pass a | Fai
l Message """ pass class Pass(Check): def __init__(self, value): self.value = value class Fail(Check): def __init__(self, message): self.message = message def is_(t, x): """ Check whether the type of a given x is a given type t. """ return type(x) is t is_check = part...
a -> m a return = Pass """ return Pass(x) def bind(f): """ Monadic bind for the Check monad. (>>=) :: m a -> (a -> m b) -> m b Fail x >>= f = Fail x Pass x >>= f = f x """ def bind_impl(x): if is_fail(x): return x if is_pass(x): ...
2B5/ia-3B5
module3/preprocessing/errorCorrect.py
Python
mit
232
0.038793
fro
m textblob import TextBlob,Word def correct(text): t = TextBlob(text) return str(t.correct()) def spellcheck(text): txt=["She","is","mw","moom"] for w in txt: word=Word(w) print(word.spellche
ck())
FRidh/python-acoustics
tests/test_power.py
Python
bsd-3-clause
637
0
from __future__ import division import numpy as np from numpy.testing import assert_almost_equal import pytest from acoustics.power import lw_iso3746 @pytest.mark.parametrize("background_noise, expected", [ (79, 91.153934187), (83, 90.187405234),
(88, 88.153934187), ]) def test_lw_iso3746(background_noise, expected): LpAi = np.array([90, 90, 90, 90]) LpAiB = background_noise * np.ones(4) S = 10 alpha = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) surfaces = np.ar
ray([10, 10, 10, 10, 10, 10]) calculated = lw_iso3746(LpAi, LpAiB, S, alpha, surfaces) assert_almost_equal(calculated, expected)
mavlyutovrus/interval_index
python/create_datasets.py
Python
apache-2.0
14,048
0.003702
import random from numpy.random import normal, uniform import numpy as np import math from heapq import heapify, heappush, heappop import os MIN = 0 MAX = 10000000 POINTS_COUNT = 1000000 QUERIES_COUNT = 200000 def save_dataset(filename, intervals, queries): intervals_copy = [value for value in intervals] qu...
+ str(start + length) + "\n") out.close() if 1: # chi_time_mem len_mean = 100 len_stdev = 10 intervals = [] queries = [] lengths = [length >=0 and length or 0.0 for length in normal(len_mean, len_stdev, POINTS_COUN
T)] for point_index in xrange(POINTS_COUNT): start = random.random() * (MAX - MIN) + MIN length = lengths[point_index] intervals += [(start, length)] intervals.sort() overlappings = [] started = [] for start, length in intervals: while started: right_borde...
IdeaSolutionsOnline/ERP4R
core/objs/sr_mulher.py
Python
mit
2,051
0.040236
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'CVtek dev' __credits__ = [] __version__ = "1.0" __maintainer__ = "CVTek dev" __status__ = "Development" __model_name__ = 'sr_mulher.SRMulher' import auth, base_models from orm import * from form import * class SRMulher(Model, View): def __...
onlist=False, search=False) self.endereco_actual = text_field(view_order=7, name='Endereço Fixo Actual', size=70, args="rows=30", onlist=False, search=False) self.observacoes = text_field(view_order=8, name='Observações', size=80, args="rows=30", onlist=False, search=False) self.estado = comb...