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
ufaks/addons-yelizariev
pitch_booking/models.py
Python
lgpl-3.0
6,779
0.005163
from datetime import datetime, timedelta import logging import traceback from openerp import api, models, fields, tools, SUPERUSER_ID from openerp.addons.booking_calendar.models import SLOT_START_DELAY_MINS, SLOT_DURATION_MINS _logger = logging.getLogger(__name__) class pitch_booking_venue(models.Model): _name =...
itch' _inherits = {'resource.resource': 'resource_id'} _defaults = { 'to_calendar': True, } venue_id = fields.Many2one('pitch_booking.venue', required=True)
resource_id = fields.Many2one('resource.resource', ondelete='cascade', required=True) class sale_order_line(models.Model): _inherit = 'sale.order.line' venue_id = fields.Many2one('pitch_booking.venue', string='Venue', related='product_id.venue_id') pitch_id = fields.Many2one('pitch_booking.pitch', string...
valesi/electrum
lib/bitcoin.py
Python
gpl-3.0
24,923
0.007182
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pu
blic 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 PURPOS...
censes/>. import hashlib import base64 import re import hmac import version from util import print_error, InvalidPassword import ecdsa import aes ################################## transactions RECOMMENDED_FEE = 50000 COINBASE_MATURITY = 100 COIN = 100000000 # supported types of transction outputs TYPE_ADDRESS = ...
patrick-winter-knime/deep-learning-on-molecules
smiles-vhts-embedding/train.py
Python
gpl-3.0
726
0.009642
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import gc import argparse from util import learn def get_arguments(): parser = argparse.ArgumentParser(description='Train a model') parser.add_argument('data', type=str, help='Training data set') parser.add_argument('model', type=str
, help='Model') parser.add_argument('--epochs', type=int, default=1, help='Number of epochs')
parser.add_argument('--batch_size', type=int, default=100, help='Size of a batch') parser.add_argument('--validation', type=str, default=None, help='Validation data set') return parser.parse_args() args = get_arguments() learn.train(args.data, args.validation, args.model, args.epochs, args.batch_size) gc.coll...
hazrpg/calibre
src/calibre/devices/smart_device_app/driver.py
Python
gpl-3.0
89,254
0.004459
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) ''' Created on 29 Jun 2012 @author: charles ''' import socket, select, json, os, traceback, time, sys, random import posixpath from coll...
), 0) if len(ans[0]) > 0: try: packet = self.driver.broadcast_socket.recvfrom(100) remote = packet[1] content_server_port = b'' try : ...
except: pass message = str(self.driver.ZEROCONF_CLIENT_STRING + b' (on ' + str(socket.gethostname().partition('.')[0]) + b');' + content_server_port + ...
bung87/moto-moe
moto/moe/api/serializers.py
Python
mit
6,799
0.014267
from rest_framework import serializers from moto.moe import models from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.conf import settings from six.moves.urllib.parse import urlparse import os from django_comments_threaded.api.serializers import CommentSerializer as...
e, 'author':UserSerializer(obj.user).data } def create(self, val
idated_data): validated_data.update( content_type=ContentType.objects.get(model = self.get_context_kwargs('content_type'),app_label='moe'), object_pk=self.get_context_kwargs('object_pk'), ) return get_model().objects.create(**validated_data) class CommentReplySerializer(...
aronsky/home-assistant
homeassistant/components/fritz/services.py
Python
apache-2.0
2,187
0.000457
"""Services for Fritz integration.""" import logging from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.service import async_extract_config_entry_ids from .const import DOMAIN, FRITZ_SERVICES, SERVICE_REBOOT, SERVICE_RECONNECT ...
RVICES):
return hass.data[FRITZ_SERVICES] = False hass.services.async_remove(DOMAIN, SERVICE_REBOOT) hass.services.async_remove(DOMAIN, SERVICE_RECONNECT)
juan-cardelino/matlab_demos
ipol_demo-light-1025b85/app_available/87/__init__.py
Python
gpl-2.0
69
0
""" Gau
ssian Convolution ipol demo web app """ from .app i
mport app
lpantano/ASMfinder
asm/select.py
Python
mit
16,220
0.003453
""" Functions to spot hemy regions """ import os.path as op import datetime from collections import defaultdict, Counter from tabulate import tabulate from scipy import stats import numpy as np import pybedtools import pysam import vcf from bcbio.distributed.transaction import file_transaction from bcbio.provenance ...
sense
_pval = False # if len(link_as) > 1: # anti_pval = _prop(link_as) # else: # anti_pval = True if sense_pval: return True return False def _valid(link, link_as): """ Only if one snp allele is associated with the Cu/Cm """ if len(link) == 2: gen = link.keys(...
maru/fiubar
fiubar/tests.py
Python
mit
13,946
0
from django.contrib.messages import constants as MSG from django.core.exceptions import ObjectDoesNotExist from django.test import RequestFactory from django.urls import reverse from django.utils.translation import ugettext as _ from test_plus.test import TestCase from .forms import SignupForm from fiubar.facultad.mo...
response = self.client.post(reverse('account_login'), {'login': self.user.username, 'password': self.user.password}, follow=True) self.assertEqual(len(response.redirect_chain), 2) self.a...
[(reverse('home'), 302), (reverse('facultad:home'), 302)]) self.assertIsNone(response.cookies.get('create_alumno')) self.assertIsNone(response.cookies.get('plancarrera')) self.assertIsNone(response.cookies.get('materias')) messages = list(response.c...
ryanpetrello/pecan
pecan/middleware/__init__.py
Python
bsd-3-clause
73
0
from . import errordocument from . import recursi
ve from . import
static
astrorafael/ema
ema/notifier.py
Python
mit
6,211
0.019643
# ---------------------------------------------------------------------- # Copyright (c) 2014 Rafael Gonzalez. # # 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...
path to the external script file # 2) Knows what its execution mode is (run once, run many times) # 3) Forks the script in background and does not wait for its completion # # We use an exception to signal notifier about an porcess already being # executed. I think this is cleaner than carrying return information # ac...
================================= import logging import subprocess import os log = logging.getLogger('notifier') class ExecutedScript(Exception): '''Signals a script has executed''' def __init__(self, name, *args): self.name = name self.args = args def __str__(self): '''Prints useful information''' tm...
danielvdao/facebookMacBot
venv/lib/python2.7/site-packages/sleekxmpp/plugins/xep_0071/stanza.py
Python
mit
2,862
0.001048
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2012 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.stanza import Message from sleekxmpp.util import unicode from sleekxmpp.thirdparty import OrderedDict from sleekxmpp.xmlstream im...
= set(['body']) lang_interfaces = set(['body']) plugin_attrib = name def set_body(self, content, lang=None): if lang is None: lang = self.get_lang()
self.del_body(lang) if lang == '*': for sublang, subcontent in content.items(): self.set_body(subcontent, sublang) else: if isinstance(content, type(ET.Element('test'))): content = unicode(ET.tostring(content)) else: ...
lukas-hetzenecker/home-assistant
homeassistant/components/zha/cover.py
Python
apache-2.0
10,222
0.00088
"""Support for ZHA covers.""" from __future__ import annotations import asyncio import functools import logging from zigpy.zcl.foundation import Status from homeassistant.components.cover import ( ATTR_CURRENT_POSITION, ATTR_POSITION, DEVICE_CLASS_DAMPER, DEVICE_CLASS_SHADE, DOMAIN, CoverEnti...
e is closed.""" if self._is_open is None: return None return not self._is_open async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._on_
off_channel, SIGNAL_ATTR_UPDATED, self.async_set_open_closed ) self.async_accept_signal( self._level_channel, SIGNAL_SET_LEVEL, self.async_set_level ) @callback def async_restore_last_state(self, last_state): """Restore previous state.""" self._is_open = last...
zak-k/iris
lib/iris/analysis/_interpolate_private.py
Python
gpl-3.0
35,306
0.002832
# (C) British Crown Copyright 2010 - 2016, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any l...
r import iris.cube import iris.coord_systems import iris.coords from iris._deprecation import warn_deprecated import iris.exceptions def _ll_to_cart(lon, lat): # Based on cartopy.img_transform.ll_to_cart() x = np.sin(np.deg2rad(90 - lat)) * np.cos(np.deg2rad(lon)) y = np.sin(np.deg2rad(90 - lat)) * np.sin...
nts(sample_points, sample_point_coord_names): # Replace geographic latlon with cartesian xyz. # Generates coords suitable for nearest point calculations with scipy.spatial.cKDTree. # # Input: # sample_points[coord][datum] : list of sample_positions for each datum, formatted for fast use of _ll_to_ca...
wavesoft/LiveQ
liveq-common/liveq/reporting/postmortem.py
Python
gpl-2.0
11,208
0.036938
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # 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 ...
l"): """ Store additional information, useful to identif
y bugs """ # Ensure we have info group if not group in self.sections["info"]: self.sections["info"][group] = {} # Store value self.sections["info"][group][key] = value def addTrace(self): """ Snapsot the current backtrace """ # Generate backtrace stackLines = traceback.format_stack() # ...
bvcms/bvcms
CmsWeb/Lib/ssl.py
Python
gpl-2.0
37,843
0.001453
# Wrapper module for _ssl, providing some additional facilities # implemented in Python. Written by Bill Janssen. """This module provides some more Pythonic support for SSL. Object types: SSLSocket -- subtype of socket.socket which does SSL over the socket Exceptions: SSLError -- exception raised for I/O erro...
* Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE) # * Prefer ECDHE over DHE for better performance # * Prefer AEAD over CBC for better performance and security # * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI # * Prefer any AES-GCM and Cha
Cha20 over any AES-CBC for better # performance and security # * Then Use HIGH cipher suites as a fallback # * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and # 3DES for security reasons _RESTRICTED_SERVER_CIPHERS = ( 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+...
zhanqxun/cv_fish
pythonwin/pywin/scintilla/scintillacon.py
Python
apache-2.0
47,114
0.000085
# Generated by h2py from Include\scintilla.h # Included from BaseTsd.h def HandleToUlong(h): return HandleToULong(h) def UlongToHandle(ul): return ULongToHandle(ul) def UlongToPtr(ul): return ULongToPtr(ul) def UintToPtr(ui): return UIntToPtr(ui) INVALID_POSITION = -1 SCI_START = 2000 SCI_OPTIONAL_STA...
ETEOLMODE = 2031 SCI_STARTSTYLING = 2032 SCI_SETSTYLING = 2033 SCI_GETBUFFEREDDRAW = 2034 SCI_SETBUFFEREDDRAW = 2035 SCI_SETTABWIDTH = 2036 SCI_GETTABWIDTH = 2121 SC_CP_UTF8 = 65001 SC_CP_DBCS = 1 SCI_SETCODEPAGE = 2037 SCI_SETUSEPALETTE = 2039 MARKER_MAX = 31 SC_MARK_CIRCLE = 0 SC_MARK_ROUNDRECT = 1 SC_M...
= 4 SC_MARK_EMPTY = 5 SC_MARK_ARROWDOWN = 6 SC_MARK_MINUS = 7 SC_MARK_PLUS = 8 SC_MARK_VLINE = 9 SC_MARK_LCORNER = 10 SC_MARK_TCORNER = 11 SC_MARK_BOXPLUS = 12 SC_MARK_BOXPLUSCONNECTED = 13 SC_MARK_BOXMINUS = 14 SC_MARK_BOXMINUSCONNECTED = 15 SC_MARK_LCORNERCURVE = 16 SC_MARK_TCORNERCURVE = 17 SC_MARK_CI...
jarrodhroberson/appengine-gcs-client
python/test/api_utils_test.py
Python
apache-2.0
8,866
0.006993
# Copyright 2013 Google Inc. All Rights Reserved. """Tests for api_utils.py.""" import os import threading import time import unittest import mock from google.appengine.ext import ndb from google.appengine import runtime from google.appengine.api import apiproxy_stub_map from google.appengine.ext import testbed tr...
with cv: set_count[0] += 1 if set_count[0] != 3: cv.wait() cv.notify() self.assertEqual(retry_params, api_utils._get_default_retry_params()) threading.Thread(target=Target, args=(retry_params1,)).start() threading.Thread(target=Target, args=(retry_params2,)).start...
rams(max_retries=1000) api_utils.set_default_retry_params(retry_params) self.assertEqual(retry_params, api_utils._get_default_retry_params()) os.environ['REQUEST_LOG_ID'] = '2' self.assertEqual(api_utils.RetryParams(), api_utils._get_default_retry_params()) def testDelay(self): ...
mganeva/mantid
qt/python/mantidqt/widgets/workspacewidget/workspacetreewidget.py
Python
gpl-3.0
536
0.001866
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2017 ISIS Rutherford Appleton Laboratory UKRI, #
NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # # from __future__ import (absolute_import, unicode_literals) from mantidqt.ut
ils.qt import import_qt WorkspaceTreeWidget = import_qt('..._common', 'mantidqt.widgets.workspacewidget', 'WorkspaceTreeWidgetSimple')
s20121035/rk3288_android5.1_repo
external/lldb/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py
Python
gpl-3.0
3,895
0.003338
""" Test watchpoint condition API. """ import os, time import unittest2 import lldb import lldbutil from lldbtest import * class WatchpointConditionAPITestCase(TestBase): mydir = os.path.join("python_api", "watchpoint", "condition") def setUp(self): # Call super's setUp(). TestBase.setUp(sel...
) @expectedFailureFreeBSD('llvm.org/pr16706') # Watchpoints fail on FreeBSD @dwarf_test def test_watchpoint_cond_api_with_dwarf(self): """Test watchpoint condition API.""" self.buil
dDwarf(dictionary=self.d) self.setTearDownCleanup(dictionary=self.d) self.watchpoint_condition_api() def watchpoint_condition_api(self): """Do watchpoint condition API to set condition as 'global==5'.""" exe = os.path.join(os.getcwd(), self.exe_name) # Create a target by th...
czcorpus/kontext
lib/plugins/default_auth/scripts/usercorp.py
Python
gpl-2.0
4,023
0.002734
# Copyright (c) 2019 Charles University, Faculty of Arts, # Institute of the Czech National Corpus # Copyright (c) 2019 Tomas Machalek <tomas.machalek@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as publis...
nt corpora for the user:\n\t{0}'.format(', '.join(curr_list)))) new_list = [] for corp in curr_list: if corp not in corpora: new_list.append(corp) db.set(mk_list_key(user_id), new_list) print(('New corpora for the user:\n\t
{0}'.format(', '.join(new_list)))) def remove_all_corpora(user_id): with plugins.runtime.DB as db: curr_items = db.get(mk_list_key(user_id)) db.set(mk_list_key(user_id), []) print('Removed access to any corpus for the user.') print(('Removed values:\n\t{0}'.format(', '.join(curr_it...
box/flaky
test/test_pytest/test_flaky_pytest_plugin.py
Python
apache-2.0
15,590
0.000064
from io import StringIO from unittest.mock import Mock, patch # pylint:disable=import-error import pytest from _pytest.runner import CallInfo # pylint:enable=import-error from flaky import flaky from flaky import _flaky_plugin from flaky.flaky_pytest_plugin import ( runner, FlakyPlugin, FlakyXdist, PLUG...
ef getoption(self, key, default): # pylint:disable=unused-argument,no-self-use return default @pytest.fixture def mock_config(): return MockConfig() class MockFlakyCallInfo(CallInfo): def __init__(self, item, when): # pylint:disable=super-init-not-called # super init not call...
report = 'Flaky tests passed; others failed. ' \ 'No more tests; that ship has sailed.' expected_string_io = StringIO() expected_string_io.write('===Flaky Test Report===\n\n') expected_string_io.write(flaky_report) expected_string_io.write('\n===End Flaky Test Report===\n') mock_i...
hinesmr/mica
util/pydevd/pysrc/tests_python/test_debugger.py
Python
apache-2.0
33,317
0.013116
''' The idea is that we record the commands sent to the debugger and reproduce them from this script (so, this works as the client, which spawns the debugger as a separate process and communicates to it as if it was run from the outside) Note that it's a python script but it'll spawn a process to r...
self.sock.close() def Write(self, s): last = self.readerThread.lastReceived if SHOW_WRITES_AND_READS: print 'Test Writer Thread Written %s' % (s,) self.sock.send(s + '\n') time.sleep(0.2) i = 0 while last == self.readerThread.lastRe...
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', port)) s.listen(1) if SHOW_WRITES_AND_READS: print 'Waiting in socket.accept()' newSock, addr = s.accept() if SHOW_WRITES_AND_READS: print 'Test Writer Thread Socket:', newSock, addr ...
adamcandy/QGIS-Meshing
plugins/boundary_identification/resources.py
Python
lgpl-2.1
6,749
0.000741
# -*- coding: utf-8 -*- # Resource object code # # Created: Thu Jul 25 00:08:39 2013 # by: The Resource Compiler for PyQt (Qt v4.8.4) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x05\x3e\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x...
\x43\xe8\xc2\x09\x60\x36\x28\x1a\x41\x09\x09\x25\x37\x4a\xb2\xff\ \x62\xf0\x91\x78\xc7\xc0\x60\xfb\x8c\x41\xfa\xf2\x43\x06\xe9\x0f\ \xf2\x70\x03\x41\x59\x18\x1b\x60\x42\x36\xa0\xe9\x96\x1c\x84\x13\ \x05\x8d
\xe7\xe8\x57\x0c\x0c\xcb\x20\x25\x4f\xa6\xd5\x72\x30\x46\ \x2e\xd3\x61\x5e\x00\x59\xf3\xe0\xd9\x0f\x36\x06\x5e\x96\xbf\x60\ \x0c\x07\xd0\x82\x95\x01\xea\x92\xc4\x15\xad\xe0\x52\x09\x5a\x98\ \xa0\x94\xca\xf2\x58\x8b\xf5\x37\x40\xc3\x44\x98\xb1\xb9\xfc\x02\ \x50\x73\x21\x88\x01\x10\x60\x8c\x68\x0d\x00\x90\x41\x05\xb8\x32...
KarimAllah/nova
nova/api/openstack/compute/flavors.py
Python
apache-2.0
3,905
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # 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/...
t('name') elem.set('id') if detai
led: elem.set('ram') elem.set('disk') for attr in ("vcpus", "swap", "rxtx_factor"): elem.set(attr, xmlutil.EmptyStringSelector(attr)) xmlutil.make_links(elem, 'links') flavor_nsmap = {None: xmlutil.XMLNS_V11, 'atom': xmlutil.XMLNS_ATOM} class FlavorTemplate(xmlutil.Template...
ktomala/microsan
src/network.py
Python
mit
1,992
0.009538
# -*- coding: utf-8 -*- """ MicroSAN Network Module """ import socket, traceback IPADDR_BROADCAST = '<broadcast>' IPADDR_ANY = '' SOCK_BUF_SIZE = 8192 SOCK_TIMEOUT = 1 MICROSAN_PORT = 20001 APP_PORT = 51000 class UDPSocket(object):
def __init__(self, addr = None, reuse_addr = False): """ Create socket for use """ self.buf = [] if addr is None: addr = (IPADDR_ANY, APP_PORT) self.sock = socket.socket(socket.AF_INET, socket
.SOCK_DGRAM) if reuse_addr: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if addr[0] == IPADDR_ANY: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.sock.settimeout(SOCK_TIMEOUT) self.sock.bind(addr) def send_data(self,...
ProgVal/Limnoria-test
plugins/Channel/test.py
Python
bsd-3-clause
13,250
0.003321
### # Copyright (c) 2002-2005, Jeremiah Fincher # Copyright (c) 2009, James McCoy # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyr...
sgs.op(self.channel, self.nick)) self.assertNotError('devoice %s' % self.nick) def testOp(self): self.assertError('op') self.irc.feedMsg(ircmsgs.op(self.channel, self.nick)) self.assertNotError('op') m
= self.getMsg('op foo') self.failUnless(m.command == 'MODE' and m.args == (self.channel, '+o', 'foo')) m = self.getMsg('op foo bar') self.failUnless(m.command == 'MODE' and m.args == (self.channel, '+o', 'foo')) m = self.irc.takeMsg() ...
saltastro/timDIMM
hrstar_with_precess.py
Python
bsd-3-clause
5,463
0.015742
#!/usr/bin/env python """Functions for loading a catalog of stars, determining the RA/DEC for a given star, and choosing the best star to observe. """ import math from astropy.coordinates import Angle from astropy.coordinates import FK5 from astropy.time import Time import astropy.units as u salt_lat = Angle("-32...
it. The catalog should have the format of id, name (2 columns), rah, ram, ras, ded, de
m, des, Vmag, B-V color, and Spectral type. Only uses catalog if star_dict is None Returns ------- sid: string key for object in star_dict ra: astropy.coordinates.Angle RA for best star dec: astropy.coordinates.Angle Declination for best star Exceptions ...
wrhansen/MarkupToTextTag
markuptotexttag/properties.py
Python
gpl-3.0
2,195
0.034624
# This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will b...
self.properties = []#Sequence containing all the properties, and values, organized by like start and end indices self.text = ""#The raw text without any markup def add( self, label, value, start, end ): ''' Add a property to MarkupProps. If the start and end indices are already in a property dictionary, th...
: if prop['start'] == start and prop['end'] == end: prop['properties'].update({label:value}) break else: new_prop = { 'properties': {label:value}, 'start': start, 'end':end, } self.properties.append( new_prop ) def __iter__(self): ''...
shaneknapp/spark
python/pyspark/sql/pandas/conversion.py
Python
apache-2.0
28,028
0.003818
# # 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 us...
' is set to true, but ha
s " "reached the error below and will not continue because automatic fallback " "with 'spark.sql.execution.arrow.pyspark.fallback.enabled' has been set to " "false.\n %s" % str(e) ) warnings.warn(msg) ...
levi-lq/flask-vue-example
api_rest/error_handlers.py
Python
mit
669
0
# coding=utf-8 """ desc: 错误处理handler author: congqing.li date: 2016-10-28 """ from werkzeug.exceptions import HTTPException class CustomError(HTTPException): code = None description = "NIMABI" def __init__(self, description=None, response=None): if isinstance(description, tuple): ...
ion, self.code = description class ObjectNotExists(CustomError): pass class TokenExpired(CustomError): pass class BadToken(CustomError): pass class MissToken(CustomError): pass class Forbidden(CustomError): pass class BadRequest(CustomError): pass
class UpdateError(CustomError): pass
mdsitton/fofix
fofix/core/Audio.py
Python
gpl-2.0
7,008
0.005993
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
ame.mixer.music.stop() def rewind(self): pygame.mixer.music.rewind() def pause(self): pygame.mixer.music.pause() def unpause(self): pygame.mixer.music.unpause() def setVolume(self, volume): pygame.mixer.music.set_volume(volume) def fadeout
(self, time): pygame.mixer.music.fadeout(time) def isPlaying(self): return pygame.mixer.music.get_busy() def getPosition(self): return pygame.mixer.music.get_pos() class Channel(object): def __init__(self, id): self.channel = pygame.mixer.Channel(id) self.id = id ...
mancoast/CPythonPyc_test
cpython/265_test_doctest.py
Python
gpl-3.0
77,423
0.000568
# -*- coding: utf-8 -*- """ Test script for doctest. """ from test import test_support import doctest import warnings # NOTE: There are some additional t
ests relating to interaction with # zipimport in the test_zipimport_support test module. ############################################
########################## ## Sample Objects (used by test cases) ###################################################################### def sample_func(v): """ Blah blah >>> print sample_func(22) 44 Yee ha! """ return v+v class SampleClass: """ >>> print 1 1 >>> # comme...
MrNuggles/HeyBoet-Telegram-Bot
temboo/Library/Google/Contacts/GetAllGroups.py
Python
gpl-3.0
4,869
0.004929
# -*- coding: utf-8 -*- ############################################################################### # # GetAllGroups # Retrieve data for all groups in an account. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use ...
returned in the Choreo output.) """ return self._output.get('AccessToken', None) class GetAllGroupsChoreographyExecution(ChoreographyExecution): def _make_result_set(self
, response, path): return GetAllGroupsResultSet(response, path)
schets/scikit-learn
sklearn/cross_validation.py
Python
bsd-3-clause
57,650
0.000017
""" The :mod:`sklearn.cross_validation` module includes utilities for cross- validation and performance evaluation. """ # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>, # Gael Varoquaux <gael.varoquaux@normalesup.org>, # Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause from...
---- n : int Total number of elements in dataset. Examples -------- >>> from sklearn import cross_validation >>> X = np.array([[1, 2], [3, 4]]) >>> y = np.array([1, 2]) >>> loo = cross_validation.LeaveOneOut(2) >>> len(loo) 2 >>> print(loo) sklearn.cross_validation.L
eaveOneOut(n=2) >>> for train_index, test_index in loo: ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] ... print(X_train, X_test, y_train, y_test) TRAIN: [1] TEST: [0] [...
beernarrd/gramps
gramps/gen/utils/test/callback_test.py
Python
gpl-2.0
8,780
0.012415
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # # 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 you...
def fn(i,r=rl): rl.append(i) t = TestSignalsSubclass() t.connect('test-signal',fn) t.emit('test-signal',(1,)) self.assertEqual(len(rl), 1, "No signal emitted") self.assertEqual(rl[0], 1, "Wrong argument recieved") t.connect('test-sub-signal',fn) ...
tEqual(rl[1], 1, "Wrong argument recieved in subclass") def test_signal_block(self): class TestSignals(Callback): __signals__ = { 'test-signal' : (int,) } rl = [] def fn(i,r=rl): rl.append(i) t = TestSignals...
Brilliant/ImageNet-Downloader
main.py
Python
mit
1,588
0.011965
from multiprocessing.dummy import Pool import logging import os import threading import urllib2 TARGET = "target" PATH = "/tmp/save/" URL = "http://image-net.org/api/text/imagenet.synset.geturls?wnid=" POOLSIZE = 128 TIMEOUT = 44 logging.basicConfig(filename = "download.log", filemode = "a", format = '%(asctime)s %(le...
_helper, parms) down.close(
) down.join()
jetskijoe/SickGear
sickbeard/providers/bithdtv.py
Python
gpl-3.0
5,627
0.005865
# coding=utf-8 # # This file is part of SickGear. # # SickGear is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickGear is distribu...
with BS4Parser(html, 'html.parser') as soup: torrent_table = soup.find('table')
torrent_rows = [] if not torrent_table else torrent_table.find_all('tr') if 2 > len(torrent_rows): raise generic.HaltParseException head = None for tr in torrent_rows[1:]: cells = tr.find_al...
ipa-josh/ratslam_ros
script/count_loop_closures.py
Python
gpl-3.0
563
0.060391
#!/usr/bin/python import rosbag import sys for fn in sys.argv[1:]: nums=[0,0,0,0] sce
nes=[0,0] for topic, msg, t in rosbag.Bag(fn).read_messages(): if topic == "/irat_red/PoseCell/TopologicalAction" and msg.action: nums[msg.action] += 1 if topic == "/feature2view/view_id" and msg.data: scenes[0] = max(scenes[0], msg.data) scenes[1]+= 1 if scenes[1]<scenes[0]: scenes[1]=scenes[0]
print fn print ["","CREATE_NODE","CREATE_EDGE","SET_NODE"] print nums print "found ",scenes[1]," scenes, recognized ",scenes[1]-scenes[0]," scenes"
jtoppins/beaker
IntegrationTests/src/bkr/inttest/server/selenium/test_system_loan.py
Python
gpl-2.0
10,755
0.00186
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. import unittest from selenium.webdriver.support.ui import WebDriverWai...
s.dyn_activity.filter(SystemActivity.field_name == \ u'Loan Comment').first() self.assertEqual(sys_activity_comment.old_value, u'') self.assertEqual(sys_activity_comment.new_value, comment) # Let's return the loan sel
f.return_loan() self.verify_loan_update('') # Test going from 'admin' -> '' in SystemActivity sys = System.by_fqdn(self.system.fqdn, user) sys_activity_name = sys.dyn_activity.filter(SystemActivity.field_name == \ u'Loaned To').first() self.assertEqual(sys_activity_na...
benhoff/ava
src/ideas/migrations/0003_auto_20150314_2006.py
Python
gpl-3.0
502
0.001992
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [
('ideas', '0002_auto_20150314_1917'), ] operations = [ migrations.AlterField( model_name='idea', name='owner', field=models.ForeignKey(related_name='ideas', to=settings.AUT
H_USER_MODEL), preserve_default=True, ), ]
gleicher27/Tardigrade
moose/framework/contrib/nsiqcppstyle/nsiqcppstyle_rulemanager.py
Python
lgpl-2.1
10,691
0.005893
# Copyright (c) 2009 NHN Inc. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the follow...
th) : self.availRuleNames = [] basePath = os.path.join(runtimePath, "rules") ruleFiles = os.listdir(basePath) rulePattern
= sre_compile.compile("^(.*)\.py$") for eachRuleFile in ruleFiles : if os.path.isfile(os.path.join(basePath, eachRuleFile)) : ruleMatch = rulePattern.match(eachRuleFile) if ruleMatch != None and eachRuleFile.find("__init__") == -1 : ruleName = rule...
nzjoel1234/sprinkler
driver/lcd_simulator.py
Python
mit
2,457
0.001628
import threading import pygame # Char LCD plate button names. SELECT = 32 RIGHT = 275 DOWN = 274 UP = 273 LEFT = 276 FONT_HEIGHT = 80 FONT_WIDTH = int(FONT_HEIGHT * 0.6) class Adafruit_CharLCDPlate: def __init__(self, width=16, height=2): pygame.init() self._width = width self.screen = p...
line, 2, lcd_text_color, lcd_back_color) self.screen.blit(rendered_line, (0, FONT_HEIGHT * i)) i += 1 pygame.display.flip() def message(self, text): self._lines = text.splitlines() self._update_screen() def set_cursor(self, row, col): return def set...
: with self._thread_lock: return self._key_states[button] def run(self): crashed = False clock = pygame.time.Clock() while not crashed: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: with self._thread_lo...
obsidianforensics/hindsight
hindsight.py
Python
apache-2.0
15,659
0.003832
#!/usr/bin/env python3 """Hindsight - Internet history forensics for Google Chrome/Chromium. This script parses the files in the Chrome data folder, runs various plugins against the data, and then outputs the results in a spreadsheet. """ import argparse import datetime import importlib import logging import os impo...
print("Exiting... ") sys.exit() elif re.search(over_re, user_
input): os.remove(output_file) print(("Deleted old \"%s\"" % output_file)) elif re.search(rename_re, user_input): output_file = "{}_1.sqlite".format(output_file[:-7]) print(("Renaming new output to {}".format(output_file))) ...
nextgis/quickmapservices
src/groups_list.py
Python
gpl-2.0
5,024
0.002986
# -*- coding: utf-8 -*- """ /*************************************************************************** QuickMapServices A QGIS plugin Collection of internet map services ------------------- begin : 2014-11-21 git sha ...
: (C) 2014 by NextGIS email : info@nextgis.com ***************************************************************************/ /*************************************
************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version ...
rahulunair/nova
nova/tests/unit/api/openstack/compute/test_image_metadata.py
Python
apache-2.0
17,106
0.000058
# Copyright 2011 OpenStack Foundation # 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...
lf.controller.update_all, req, '100', body=body) self.assertFalse(quota_mocked.called) @mock.patch(CHK_QUOTA_ST
R) @mock.patch('nova.image.api.API.update') @mock.patch('nova.image.api.API.get', return_value=get_image_123()) def test_update_item(self, _get_mocked, update_mocked, quota_mocked): req = fakes.HTTPRequest.blank(self.base_path + '123/metadata/key1') req.method = 'PUT' body = {"meta":...
dims/ironic
ironic/api/controllers/v1/port.py
Python
apache-2.0
16,875
0.000119
# Copyright 2013 UnitedStack 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...
and self._node_uuid != value: try: # FIXME(comstud): One should only allow UUID here, but # there seems to be a bug in that tes
ts are passing an # ID. See bug #1301046 for more details. node = objects.Node.get(pecan.request.context, value) self._node_uuid = node.uuid # NOTE(lucasagomes): Create the node_id attribute on-the-fly # to satisfy the ap...
shanestockall/EECS-Grading-Rig
src/packages/EECS-211-Grader/acceptancetest.py
Python
mit
2,184
0.035714
import hashlib import shutil import os from datetime import datetime list_of_paths_and_strings = [ ["assignment1.cpp", "main()"] ] def main(): if acceptance_test(): make_txt_file() zip_dir() def get_md5_hash(file): # opening file file_to_hash = open(file) read_file = file_to_hash.read() ...
th) as file: for string in list_of_strings: if string in file.read(): print "Found " + string + " in file." else: print string + "not found in file." return False file.close() return True except: print 'File does not exist. Please make sure all necessary files are ...
he hashes for each of the files using MD5 write_file = open("hash.txt", "w+") write_file.write("Write time: " + str(get_current_time()) + '\n') for file in os.listdir(os.getcwd()): if "." in file: f_name, file_hash = get_md5_hash(file) write_file.write(f_name + '\n') write_file.write(file_hash + ...
sam-bretz/Gin-AI
src/Deck.py
Python
bsd-3-clause
807
0.045849
""" Authored by Samuel Bretz. bretzsam@gmail.com 7.20.17 """ from Card import Card import random class Deck: def __init__(self): suits = ['Spades','Diamonds','Hearts','Clubs'] self.instance = [] for s in suits: for v in range(1,14): card = Card(s,v) self.instance.append(card) random.shuffle(self.in...
def remove(self, deck, place): deck[place] = None def notEmpty(self): for card in self.instance: if card != None: return True return False #Get the next card that is not None (next card for play) def nextCard(self): for i
in range(0, len(self.instance)): if self.instance[i] == None: pass else: returnCard = self.instance[i] self.instance[i] = None return returnCard if __name__ == "__main__": __package__ = "__Deck__"
edlabh/SickRage
sickbeard/providers/btn.py
Python
gpl-3.0
12,087
0.002647
# -*- coding: utf-8 -*- # Author: Daniel Heimans # URL: http://code.google.com/p/sickbeard # # This file is part of SickRage. # # SickRage 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 th...
keep requesting until we've got everything. # max 150 requests per hour so limit at that. Scan every 15 minutes. 60 / 15 = 4. max_pages = 150
results_per_page = 1000 if 'results' in parsedJSON and int(parsedJSON[b'results']) >= results_per_page: pages_needed = int(math.ceil(int(parsedJSON[b'results']) / results_per_page)) if pages_needed > max_pages: pages_needed = max_pages ...
danalec/dotfiles
sublime/.config/sublime-text-3/Packages/Anaconda/anaconda_lib/phantoms.py
Python
mit
3,660
0.00082
# Copyright (C) 2015 - Oscar Campos <oscar.campos@member.fsf.org> # This program is Free Software see LICENSE file for details import os import glob import logging from string import Template import sublime from .helpers import get_settings class Phantom(object): """Just a wrapper around Sublime Text 3 phanto...
-> None: """ Load any css theme found in the anaconda CSS themes directory or in the User/Anaconda.themes directory """ css_files_pattern = os.path.join( os.path.dirname(__fi
le__), os.pardir, 'css', '*.css') for css_file in glob.glob(css_files_pattern): logging.info('anaconda: {} css theme loaded'.format( self._load_css(css_file)) ) packages = sublime.active_window().extract_variables()['packages'] user_css_path = os.path.joi...
maistrovas/My-Courses-Solutions
MITx-6.00.1x/ProblemSet1/PS1.py
Python
mit
864
0.011574
''' Problem 1: Counting Vowels '''
vowels = ['a', 'i', 'o', 'u', 'e'] count = 0 for i in s: if i in vowels: count +=1 print count ''' Problem 2: Counting 'bob's ''' s = 'azcbobobegghakl' def count_word_parts(word_part, word): ''' Function counts number times word_part occurs in all woed ''' occurs = 0 for i in range(le...
t_word_parts('bob', s) ''' Problem 3: Alphabetical Substrings Findes londest substring occurs in alphabetical order. ''' curString = s[0] longest = s[0] for i in range(1, len(s)): if s[i] >= curString[-1]: curString += s[i] if len(curString) > len(longest): longest = curString else:...
CUFCTL/DLBD
face-detection-code/object_detection/exporter_test.py
Python
mit
41,327
0.005832
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
BytesList(value=[value])) example = tf.train.Example(features=tf.train.Features(feature={ 'image/encoded': _bytes_feature(encoded_image), 'image/format': _bytes_feature('jpg'), 'image/source_id': _bytes_feature('image_id')
})).SerializeToString() return example def test_export_graph_with_image_tensor_input(self): tmp_dir = self.get_temp_dir() trained_checkpoint_prefix = os.path.join(tmp_dir, 'model.ckpt') self._save_checkpoint_from_mock_model(trained_checkpoint_prefix, use...
smurfix/MoaT
modules/wago.py
Python
gpl-3.0
25,482
0.043106
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division, unicode_literals ## ## This file is part of MoaT, the Master of all Things. ## ## MoaT is Copyright © 2007-2016 by Matthias Urlichs <matthias@urlichs.de>, ## it is licensed under the GPLv3. See the file `README.rst` for details...
msg=buf)
else: if line.startswith("."): line = line[1:] self.buf.append(line) return elif line == "": self.msgReceived(type=MT_OTHER, msg=line) elif line[0] == "=": self.buf = [line[1:]] return elif line[0] == "?": self.msgReceived(type=MT_ERROR, msg=line[1:].strip()) return elif line[0] =...
UmassJin/Leetcode
Array/combination_sum1.py
Python
mit
1,940
0.029564
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums
to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). The solution set must not contain duplicate combinations. For example, giv...
# @param candidates, a list of integers # @param target, integer # @return a list of lists of integers # Recursion # Sort the array at first, then use the recursion to find # the result, Time O(n^2) # 96ms def combinationSum(self, candidates, target): candidates.sort() ...
genialwang/lambda-image
script/mehi_local.py
Python
bsd-3-clause
2,385
0.010901
############################### # Author : septicmk # Date : 2015/07/25 16:14:09 # FileName : main.py ################################ from lambdaimage import preprocess as prep from lambdaimage import registration as reg from lambdaimage import fusion as fus from pyspark import SparkContext, SparkConf from lamb...
p.squeeze(np.array(fused_img.values().collect()))
log('info')('subtract background start ...') sb_img = prep.subtract_Background(fused_img) log('info')('sbutract background over ... ') log('info')('saving ...') sb_img.exportAsTiffs('/home/wb/data/lambdaimage/subtract',overwrite = True)
cbclab/MDT
mdt/gui/maps_visualizer/config_tabs/tab_general.py
Python
lgpl-3.0
18,294
0.003006
import copy import os from PyQt5.QtCore import pyqtSlot, Qt, QPoint, QUrl from PyQt5.QtGui import QDesktopServices from PyQt5.QtWidgets import QWidget, QAbstractItemView, QMenu, QWidgetAction, QLabel from mdt.gui.maps_visualizer.actions import SetDimension, SetSliceIndex, SetVolumeIndex, SetColormap, SetRotate, \ ...
lf.gener
al_zoom_reset.clicked.connect(lambda: self._controller.apply_action(SetZoom(Zoom.no_zoom()))) self.general_zoom_fit.clicked.connect(self._zoom_fit) self.general_display_order.items_reordered.connect(self._reorder_maps) self.general_show_axis.clicked.connect(lambda: self._controller.apply_action...
jiadaizhao/LeetCode
0201-0300/0226-Invert Binary Tree/0226-Invert Binary Tree.py
Python
mit
430
0.002326
#
Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if root is None: return None left = self.invertTree(root.left) ...
ght root.right = left return root
jaredhoney/pyrad
pyrad/packet.py
Python
bsd-3-clause
21,519
0.001394
# packet.py # # Copyright 2002-2005,2007 Wichert Akkerman <wichert@wiggy.net> # # A RADIUS packet as defined in RFC 2138 import struct import random try: import hashlib md5_constructor = hashlib.md5 except ImportError: # BBB for python 2.4 import md5 md5_constructor = md5.new import six from pyrad...
stance(key, six.string_types): (key, item) = self._EncodeKeyValues(key, items) dict.__setitem__(self, key, item) else: assert isinstance(item, list) dict.__setitem__(self, key, item) def keys(self): return [self._DecodeKey(key) for key in dict.keys(se...
h is used to authenticate replies from the RADIUS server and in the password hiding algorithm. This function returns a suitable random string that can be used as an authenticator. :return: valid packet authenticator :rtype: binary string """ data = [] for i in r...
Habidatum/slayer
slayer/plugin_loader.py
Python
mit
421
0.002375
import pkgutil def get_plugins(plugins_module): plugins = {}
prefix = plugins_module.__name__ + "." for importer, modname, ispkg in pkgutil.iter_modules(plugins_module.__path__,
prefix): module = importer.find_module(modname).load_module(modname) modname = modname.split('.')[-1] plugins[modname] = module return plugins
huaiping/pandora
photo/views.py
Python
mit
1,348
0.011869
from django.shortcuts import render from django.db.models import Count from django.core import serializers from django.http import HttpResponse from photo.models import Photo def index(request): categories = Photo.objects.raw('select id, category from swan_photo group by category') subcategories = Photo.object...
, 'photo_lists.html', {'categories':categories, 'subcategories':subcategories, 'photos':photos}) def view(request, id): if id: photos = Photo.objects.raw('select * from swan_photo where subcategory=(select subcategory from swan_photo where id=%s)', [id]) else: id = 1 photos = Photo.obje...
ect subcategory from swan_photo where id=%s)', [id]) return render(request, 'photo_items.html', {'photos':photos}) def waterfall(request): return render(request, 'photo_waterfall.html') def loading(request): data = serializers.serialize("json", Photo.objects.all(), fields=('url','description')) return...
gagoncal/Selenium
pywinauto/examples/windowmediaplayer.py
Python
lgpl-2.1
2,572
0.00311
# GUI Application automation and testing library # Copyright (C) 2015 Intel Corporation # Copyright (C) 2006 Mark Mc Mahon # # This library is free software; you can redistribute it and/or # modify it under the terms of the GN
U Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty
of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place, # Suite 330, ...
studio1247/gertrude
controls.py
Python
gpl-3.0
45,793
0.002293
# -*- coding: utf-8 -*- # This file is part of Gertrude. # # Gertrude is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. #...
.stattext.GenStaticText(self, -1, ' ' + title, size=(-1, 28), style=wx.BORDER_SUNKEN | wx.ST_NO_AUTORESIZE) font = st.GetFont() font.SetPointSize(14) st.SetFont(font) st.SetBackground
Colour(wx.Colour(10, 36, 106)) st.SetBackgroundStyle(wx.BG_STYLE_COLOUR) st.SetForegroundColour(wx.Colour(255, 255, 255)) sizer.Add(st, 1, wx.EXPAND) self.sizer.Add(sizer, 0, wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, 5) self.SetSizer(self.sizer) self.SetAutoLayout...
ivanovwaltz/wavelet_sound_microscope
profileit.py
Python
mit
261
0
#!/usr/bin/env python import pstats import sys from s
ubprocess import check_call stat_file = '/tmp/profile_data' check_call(['python', '-m', 'cProfile', '-o', stat_file] + sys.argv[1:]) p = pstats.Stats(stat_file) p.sort_stats('cumulative').print_stats(8)
googleapis/python-dialogflow-cx
samples/generated_samples/dialogflow_v3beta1_generated_experiments_delete_experiment_sync.py
Python
apache-2.0
1,446
0.000692
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
, # 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. # # Generated code. DO NOT EDIT! # # Snippet for DeleteExperiment # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the followin...
melmothx/jsonbot
jsb/plugs/socket/__init__.py
Python
mit
406
0.002463
# jsb socket related plugins # # """ this package contains all the socket related plugins. """ import os (f, tail) = os.path.split(__file__) __all__ = [] for i in os.listdir(f): if i.endswith('.py'): __all__.append(i[:-3]) elif o
s.path.isdir(f + os.sep + i) and not i.startswith('.'): __all__.append(i) try: __all__.remove('_
_init__') except: pass __plugs__ = __all__
mozilla/popcorn_maker
vendor-local/lib/python/bleach/tests/test_css.py
Python
bsd-3-clause
3,630
0.000275
from functools import partial from nose.tools import eq_ from bleach import clean clean = partial(clean, tags=['p'], attributes=['style']) def test_allowed_css(): tests = ( ('font-family: Arial; color: red; float: left; ' 'background-color: red;', 'color: red;', ['color']), ('border: ...
tyle: dotted; """ """border-right-style: dotted; border-bottom-style: dotted; """ """border-left-style: dotted; border-top-color: rgb(203, 200, """ """185)
; border-right-color: rgb(203, 200, 185); """ """border-bottom-color: rgb(203, 200, 185); border-left-color: """ """rgb(203, 200, 185); background-image: initial; """ """background-attachment: initial; background-origin: initial; """ """background-clip: initial; backg...
rmelchorv/TDD-Cuervos
superlists/urls.py
Python
mit
896
0.001116
"""superlists URL Configuration The `urlpatterns` list routes URLs to views. For
more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$',
views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_u...
konstantinoskostis/sqlalchemy-utils
sqlalchemy_utils/aggregates.py
Python
bsd-3-clause
15,378
0
""" SQLAlchemy-Utils provides way of automatically calculating aggregate values of related models and saving them to parent model. This solution is inspired by RoR counter cache, `counter_culture`_ and `stackoverflow reply by Michael Bayer`_. Why? ---- Many times you may have situations where you need to calculate d...
( 'Order', primaryjoin= 'sa.and_(Order.c
ustomer_id == Customer.id, Order.invoiced)', viewonly=True ) class Order(Base): __tablename__ = 'order' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) price = sa.Column(sa.Numeric) invoiced = sa.Column(sa.Boolean, default=...
jbeluch/smartclient
smartclient/client.py
Python
mit
5,176
0.002125
import time import functools import itertools as it import requests from requests.exceptions import ConnectTimeout, ReadTimeout,
ConnectionError from circuit import CircuitOpenError import logging from .breaker import CircuitBreakerSet from .exce
ptions import AllHostsUnreachableException, MaxRetriesReached logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class Retriable(object): def __init__(self, func, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs def __call__(self, **new_kwarg...
mhbu50/frappe
.github/helper/documentation.py
Python
mit
1,220
0.02562
import sys import requests from urllib.parse import urlparse docs_repos = [ "frappe_docs", "erpnext_documentation", "erpnext_com", "fr
appe_io", ] def uri_validator(x): result = urlparse(x) return all([result.scheme, result.netloc, result.path]) def docs_link_exists(body): for line in body.splitlines(): for word in line.split(): if word.startswith('http') and uri_validator(word): parsed_url = urlparse(word) if parsed_url.netloc == "...
b.com": parts = parsed_url.path.split('/') if len(parts) == 5 and parts[1] == "frappe" and parts[2] in docs_repos: return True if __name__ == "__main__": pr = sys.argv[1] response = requests.get("https://api.github.com/repos/frappe/frappe/pulls/{}".format(pr)) if response.ok: payload = response....
yavalvas/yav_com
build/matplotlib/tools/github_stats.py
Python
mit
6,681
0.00449
#!/usr/bin/env python """Simple tools to query github.com and gather stats about issues. """ #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function import json import ...
ormat=%ai', tag] tagday, tz = check_output(cmd).strip().rsplit(' ', 1) since = datetime.strptime(tagday, "%Y-%m-%d %H:%M:%S") else: since = datetime.now() - timedelta(days=days) print("fetching GitHub stats since %s (tag: %s)" %
(since, tag), file=sys.stderr) # turn off to play interactively without redownloading, use %run -i if 1: issues = issues_closed_since(since, pulls=False) pulls = issues_closed_since(since, pulls=True) # For regular reports, it's nice to show them in reverse chronological order issues =...
merckhung/bokken
lib/web/wsgi.py
Python
gpl-2.0
2,060
0.01165
""" WSGI Utilities (from web.py) """ import os, sys import http import webapi as web from utils import listget from net import validaddr, validip import httpserver def runfcgi(func, addr=('localhost', 8000)): """Runs a WSGI function as a FastCGI server.""" import flup.server.fcgi as flups return flup...
ERVER_SOFTWARE'): # cgi os.environ['FCGI_FORCE_CGI'] = 'Y' if (os.environ.has_key('PHP_FCGI_CHILDREN') #lighttpd fastcgi or os.environ.has_key('SERVER_SOFTWARE')): return runfcgi(func, None) if 'fcgi' in sys.argv or 'fastcgi' in sys.argv: args = sys.argv[1:] if 'fastc...
f 'fcgi' in args: args.remove('fcgi') if args: return runfcgi(func, validaddr(args[0])) else: return runfcgi(func, None) if 'scgi' in sys.argv: args = sys.argv[1:] args.remove('scgi') if args: return runscgi(func, validaddr(args[0])) ...
IfcOpenShell/IfcOpenShell
src/blenderbim/test/tool/test_misc.py
Python
lgpl-3.0
7,558
0.001191
# BlenderBIM Add-on - OpenBIM Blender Add-on # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of BlenderBIM Add-on. # # BlenderBIM Add-on 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 Foundati...
() storey.Elevation = 3000 tool.Ifc.set(ifc) assert subject.get_storey_elevation_in_si(storey) == 3.0 class TestGetStoreyHeight(test.bim.bootstrap.NewFile): def test_run(self): ifc = ifcopenshell.file() ifc.createIfcProject() unit = ifcopenshell.api.run("unit.add_si...
reateIfcBuildingStorey() storey.Elevation = 3000 storey2 = ifc.createIfcBuildingStorey() storey2.Elevation = 5000 ifcopenshell.api.run("aggregate.assign_object", ifc, product=storey, relating_object=building) ifcopenshell.api.run("aggregate.assign_object", ifc, product=storey2, r...
RutledgePaulV/django-commands
commands/decorators/plugin.py
Python
mit
2,097
0.020029
# This module defines a plugin decorator that can be used on a base class in order # to automatically register classes that inherit from it across django apps within your project. from
django.utils.module_loading import autodiscover_modules # creating a decorator that effectively sets the above class as the meta class and passes along the key and module de
f Plugin(key, module): class Plug(type): # here because we need to allow kwargs but not pass them to the type constructor def __new__(cls, name, bases, namespace, **kwargs): return super().__new__(cls, name, bases, namespace) # overriding the init method of the meta class def __init__(cls, what, bases, n...
caiopo/riemann-bot
src/calculus.py
Python
mit
1,421
0.036594
import sympy from math import e, sin, cos, tan def make_func(f): f = f.replace('-x', '(-x)') f = f.replace('x', '(x)') f = f.replace('^', '**') return lambda x: eval(f) def solve(msg): _, fstr = msg.split(' ') f = make_func(fstr) x = sympy.Symbol('x') return sympy.solvers.solve(f(x)) def limit(msg): _, ...
te('/integrate x^2 fro
m 0 to 1')) # print(-sympy.oo)
dmlc/tvm
python/tvm/relay/op/vision/_yolo.py
Python
apache-2.0
1,131
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
age governing permissions and limitations # under the License. # pylint: disable=invalid-name, unus
ed-argument """Backend compiler related feature registration""" from __future__ import absolute_import from ..op import register_pattern, OpPattern from ..op import register_injective_schedule # reorg register_pattern("vision.yolo_reorg", OpPattern.INJECTIVE) register_injective_schedule("vision.yolo_reorg")
Magicked/crits
crits/screenshots/handlers.py
Python
mit
13,241
0.002115
import hashlib import json from PIL import Image from django.http import HttpResponse from django.shortcuts import render try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from crits.core.class_mapper import class_from_id from crits.core.crits_mongoengine i...
:param otype: The top-level object type. :type otype: str :returns: dict with keys: 'success' (boolean), 'message' (str), 'id' (str) if successful, 'html' (str) if successful, """ result = {'success': False} if not source: result['mes...
obj = class_from_id(otype, oid) if not obj: result['message'] = "Could not find the top-level object." return result final_screenshots = [] if screenshot_ids: if not isinstance(screenshot_ids, list): screenshot_list = screenshot_ids.split(',') else: ...
ignatenkobrain/firewalld
src/firewall/core/fw_zone.py
Python
gpl-2.0
62,523
0.004494
# -*- coding: utf-8 -*- # # Copyright (C) 2011-2012 Red Hat, Inc. # # Authors: # Thomas Woerner <twoerner@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the Li...
_chains or \ table not in self._chains[zone] or \ chain not in self._chains[zone][table]: return chains = [ ] rules = [ ] zones = [ DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) ] ...
ipvs.append("ipv4") if self._fw.is_table_available("ipv6", table): ipvs.append("ipv6") for ipv in ipvs: OUR_CHAINS[table].update(set([_zone, "%s_log" % _zone, ...
arkadoel/directORM
python/salida/directORM/forProductos.py
Python
gpl-2.0
2,989
0.00368
import sqlite3 import directORM class Producto: def __init__(self): self.idProducto = -1 self.nombre_producto = '' self.precio_unidad = 0.0 self.iva = 0 self.foto_producto = '' self.ingredientes = '' self.familia = '' class TbProductos: INSERT = ''' ...
idad, iva, foto_producto, ingredientes, familia) values (?,?,?,?,?,?) ''' DELETE = 'delete from Productos where idProducto = ?' SELECT = 'select * from Productos' UPDATE = ''' update Productos set
nombre_producto = ?, precio_unidad = ?, iva = ?, foto_producto = ?, ingredientes = ?, familia = ? where idProducto = ? ''' def __init__(self): self.gestorDB = directORM.Db() def remove(self, producto ): sql = self.DELETE self.ge...
Angoreher/xcero
votes/forms.py
Python
mit
488
0
# -*- coding: utf-8 -*- """ Forms for the votes application. """ # standard library # django from django import forms # models from .models import Vote # v
iews from base.forms import BaseModelForm class VoteForm(BaseModelForm): """ Form Vote model. """ score = forms.IntegerField(required=True) class Meta:
model = Vote widgets = { 'user': forms.HiddenInput(), 'card': forms.HiddenInput(), } exclude = ()
obmarg/toolz
toolz/tests/test_curried.py
Python
bsd-3-clause
378
0
import toolz from toolz.curri
ed import take, first, second, sorted, merge_with def test_take(): assert list(take(2)([1, 2, 3])) == [1, 2] def test_first(): assert first is toolz.itertoolz.core.first def test_merge_with(): assert merge_with(sum)({1: 1}, {1: 2}) == {1: 3} def test_sorted(): assert sorted(key=second)([(1, 2), ...
(1, 2)]
keras-team/keras
keras/distribute/keras_image_model_correctness_test.py
Python
apache-2.0
6,668
0.006149
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
.multi_worker_mirrored_eager() + keras_correctness_test_base.test_combinations_with_tpu_strategies_graph()) def test_cnn_correctness_with_partial_last_batch_eval(self, distribution,
use_numpy, use_validation_data): self.run_correctness_test( distribution, use_numpy, use_validation_data, partial_last_batch=True, training_epochs=1) @tf.__inte...
evangeline97/localwiki-backend-server
localwiki/links/views.py
Python
gpl-2.0
942
0.002123
from django.views.generic import TemplateView from regions.views import RegionMixin from pages.models import Pa
ge, slugify from .models import Link class LinksForPageView(RegionMixin, TemplateView): template_name = 'links/links_for_page.html' def get_context_data(self, *args, **kwargs): context = super(LinksForPageView, self) .get_context_data(*args, **kwargs) page = Pag
e.objects.get( slug=slugify(self.kwargs.get('slug')), region=self.get_region() ) context['page'] = page context['links_to_page'] = page.links_to_here.all() context['links_from_page'] = page.links.all() return context class OrphanedPagesView(RegionMixin, ...
leesavide/pythonista-docs
Documentation/matplotlib/users/recipes-8.py
Python
apache-2.0
493
0.01217
np.
random.seed(1234) fig, ax = plt.subplots(1) x = 30*np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std() textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma) ax.hist(x, 50) # these are matplotlib.patch.Patch properties props = dict(boxstyle='round', facecolor='wheat', ...
text box in upper left in axes coords ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14, verticalalignment='top', bbox=props)
GNOME/buoh
build-aux/dist-news.py
Python
gpl-2.0
258
0.007813
import subprocess
import sys if len(sys.argv) < 2: sys.exit("usage: dist-news.py <appstream_util>") appstream_util = sys.argv[1] print('Generating NEWS file…') subprocess.call([appstream_util, 'appdata-to-news', 'data/o
rg.gnome.buoh.appdata.xml.in'])
dubourg/openturns
python/test/t_NonCentralChiSquare_std.py
Python
gpl-3.0
4,582
0.003055
#! /usr/bin/env python from __future__ import print_function from openturns import * TESTPREAMBLE() RandomGenerator.SetSeed(0) try: # Instanciate one distribution object distribution = NonCentralChiSquare(1.5, 2.5) print("Distribution ", repr(distribution)) print("Distribution ", distribution) #...
PDF(point) - NonCentralChiSquare(distribution.getNu() - eps, distribution.getLambda()).computePDF(point)) / (2.0 * eps) PDFgrFD[1] = (NonCentralChiSquare(distribution.getNu(), distribution.getLambda() + eps).computePDF(point) - NonCentralChiSquare(distribution.getNu(), distributi...
uteCDFGradient(point) print("cdf gradient =", repr(CDFgr)) CDFgrFD = NumericalPoint(2) CDFgrFD[0] = (NonCentralChiSquare(distribution.getNu() + eps, distribution.getLambda()).computeCDF(point) - NonCentralChiSquare(distribution.getNu() - eps, distribution.getLambda()).computeCDF(point)...
pylayers/pylayers
pylayers/em/openems/probebox.py
Python
mit
1,149
0.015666
import pdb import numpy as np from xml.etree.ElementTree import Element from xml.etree import ElementTree class ProbeBox(Element): def __init__(self, Name='port_ut1', Type='wv', Weight='1'): """ type: 0 for voltage probing => 'vp' 1 for current probing => 'cp' 2 for E-field probing...
if Type=='Hfp': self.attrib['Type']='3' if Type=='wv': self.attrib['Type']='10' if Type=='wc': self.attrib['Type']='11' self.append(Attributes('Attributes',a)) class Attributes(Element):
def __init__(self, name, a): Element.__init__(self, name, ModeFunctionX=str(a[0]), ModeFunctionY=str(a[1]), ModeFunctionZ=str(a[2]))
zinic/pyrox
tests/http/request_performance_test.py
Python
mit
856
0.001168
import unittest import time from pyrox.http import RequestParser, ParserDelegate NORMAL_REQUEST = """GET /test/12345?field=f1&field2=f2#fragment HTTP/1.1\r Connection: keep-alive\r Content-Length: 12\r\n \r This is test""" def performance(duration=10, print_output=True): parser = RequestParser(ParserDelegate()...
seconds for {} runs per second.'.format( runs, duration, runs / float(duration))) if __name__ == '__main__': print('Executing warmup') performance(5, False) print('Executing performance test') performance(5) print('Profiling...') import cP
rofile cProfile.run('performance(5)')
Sound-Colour-Space/sound-colour-space
website/apps/museum/migrations/0007_auto_20160510_1214.py
Python
mit
2,006
0.003988
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-05-10 10:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('museum', '0006_museumsres...
eField( model_name='museumsresource', name='copyright',
), migrations.DeleteModel( name='Copyright', ), migrations.AddField( model_name='museumsresource', name='source', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='museums_resources', to...
ArcherSys/ArcherSys
compiler.py
Python
mit
186
0.016129
infile = open(input("App Zip"),"rb") outfile = open
(input("App
FileName:") + ".bryapp","wb") outfile.write("BRYANTCOMPILERAPPLICATIONPACKAGE".encode('utf-8')) outfile.write(infile.read())
slub/vk2-georeference
georeference/utils/logger.py
Python
gpl-3.0
1,115
0.008969
# -*- coding: utf-8 -*- ''' Copyright (c) 2014 Jacob Mendt Created on Jul 2, 2015 @author: mendt ''' import logging def createLogger(name, logLevel, logFile=None, formatter=None, handler = None): """ Initialize a logger :param string: name :param int: logLevel :param string: logFile (Default=Non...
logger.setLevel(logLevel) if logFile and formatter: logHandler = logging.FileHandler(logFile) logHandler.setFormatter(formatter) logger.addHandler(logHandler) elif handler: logger.addHandler(handler) retu
rn logger def getLoggerFileHandler(file, formatter): """ Create a logger file handler :param string file :param string: formatter :return: logging.FileHandler """ formatter = logging.Formatter(formatter) handler = logging.FileHandler(file) handler.setFormatter(formatter) return ha...
vakaras/db-utils
src/db_utils/decorators/__init__.py
Python
lgpl-3.0
74
0
#!/us
r/bin/python """ Variuos decorators for function
s and methods. """
hodger/cyclus
cyclus/system.py
Python
bsd-3-clause
1,065
0.000939
"""Some system-specific info for cyclus.""" import sys import importlib from cyclus.lazyasd import lazyobject @lazyobject def PY_VERSION_TUPLE(): return sys.version_info[:3] @lazyobject def curio(): if PY_VERSION_TUPLE < (3, 5, 2): return None else: try: return importlib.imp...
import c
oncurrent.futures as m return m except ImportError: return None
m4ll0k/Spaghetti
plugins/fingerprint/framework/play.py
Python
gpl-3.0
415
0.036145
#!/usr/bin/env python # -*- coding:utf-8 -*- # # @name: Wascan - Web Application Scanner # @repo: https://github.com/m4ll0k/Wascan # @author: Momo Outaadi (M4ll0k) # @license: See the file 'LICENSE.txt from re import search,I def play(hea
ders,content): _ = False for header in headers.items(): _ |= search("play! framework;",hea
der[1]) is not None if _ : break if _ : return "Play - Java Framework"
palindromed/data-structures2
src/insertion_sort.py
Python
mit
1,651
0.003634
# _*_ encoding: utf-8 _*_ import timeit def insertion_sort(nums): """Insertion Sort.""" for ind
ex in range(1, len(nums)): val = nums[index] left_index = index - 1 while left_index >= 0 and nums[left_index] > val: nums[left_index + 1] = nums[left_index] left_index -= 1 nums[left_index + 1] = val return nums def insertion_sort_tuples(nums): """Inser...
n Sort.""" for index in range(1, len(nums)): val = nums[index] left_index = index - 1 while left_index >= 0 and nums[left_index][1] > val[1]: nums[left_index + 1] = nums[left_index] left_index -= 1 nums[left_index + 1] = val return nums if __name__ == '_...
skolsuper/pybbm
pybb/permissions.py
Python
bsd-2-clause
7,490
0.004673
# -*- coding: utf-8 -*- """ Extensible permission system for pybbm """ from __future__ import unicode_literals from django.db.models import Q from pybb import defaults, util class DefaultPermissionHandler(object): """ Default Permission handler. If you want to implement custom permissions (for example, ...
aults.PYBB_PREMODERATION or user.is_superuser: # superuser may see all posts, also if premoderation is turned of
f moderation # flag is ignored return qs elif user.is_authenticated(): # post is visible if user is author, post is not on moderation, or user is moderator # for this forum qs = qs.filter(Q(user=user) | Q(on_moderation=False) | Q(topic__forum__moderat...
PAIR-code/lit
lit_nlp/api/dataset.py
Python
apache-2.0
11,296
0.007171
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
_to_lit_example = self._base.bytes_to_lit_example # Override from direct arguments. self._examples = examples if examples is not None else self._examples self._spec = spec or self._spec self._description = description or self._description def description(self) -> str: """Return a human-readable ...
of this component. Defaults to class docstring, but subclass may override this (or simply set self._description) to be instance-dependent - for example, including the path from which the data was loaded. Returns: (string) A human-readable description for display in the UI. """ return sel...
jabesq/home-assistant
homeassistant/components/ads/__init__.py
Python
apache-2.0
9,717
0
"""Support for Automation Device Specification (ADS).""" import threading import struct import logging import ctypes from collections import namedtuple import asyncio import async_timeout import voluptuous as vol from homeassistant.const import ( CONF_DEVICE, CONF_IP_ADDRESS, CONF_PORT, EVENT_HOMEASSISTANT_STOP) ...
R.error("Unknown device notification handle: %d", hnotify) return # Parse data to desired datatype if notification_item.plc_datatype == self.PLCTYPE_BOOL: value = bool(struct.unpack('<?', bytearray(data)[:1])[0]) elif notification_item.plc_datatype == self.PLCTYPE_INT: ...
bytearray(data)[:1])[0] elif notification_item.plc_datatype == self.PLCTYPE_UINT: value = struct.unpack('<H', bytearray(data)[:2])[0] elif notification_item.plc_datatype == self.PLCTYPE_DINT: value = struct.unpack('<i', bytearray(data)[:4])[0] elif notification_item.plc_d...
topisani/sagenb
sagenb/testing/grinder/simpleeval_multi.py
Python
gpl-3.0
1,778
0.015186
from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from HTTPClient import NVPair from java.util import Random newCellTest = Test(1, "Make a new Cell") evaluationTest = Test(2, "Evaluate") updateTest = Test(3, "Poll until evaluated") delete...
print 'wait',count,'test',a,'*',b,'=', strip_answer(result.text) break request = deleteCellTest.wrap(HTTPRequest(url=base_url + "/delete_cell")) g
etData = ( NVPair("id", new_cell),) result = request.POST(getData) def strip_answer(text): #<pre class="shrunk">532962756677</pre> st = text.find('<pre') end = text.find('</pre>') return text[st + 20 : end]