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
hackerspace-silesia/cebulany-manager
migrations/versions/c19852e4dcda_add_unique_key_to_username.py
Python
mit
953
0.001049
"""add unique key to username Revision ID: c19852e4dcda Revises: 1478867a872a Create Date: 2020-08-06 00:39:03.004053 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c19852e4dcda' down_revision = '1478867a872a' branch_labels = None depends_on = None def upgr...
le('user', schema=None) as batch_op: batch_op.drop_index('ix_user_username') batch_op.create_index(batch_op.f('ix_user_username'), ['username'], uni
que=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('user', schema=None) as batch_op: batch_op.drop_index(batch_op.f('ix_user_username')) batch_op.create_index('ix_user_username', ['username'], u...
zbase/disk_mapper
dm_server/lib/urlmapper.py
Python
apache-2.0
2,103
0.000951
#!/bin/env python # Copyright 2
013 Zynga Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re
quired 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. """ Thi...
HayaoSuzuki/django-tutorial
mysite/mysite/settings.py
Python
mit
2,134
0
""" Django settings for mysite project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) imp...
8ehs7uld0g948yj-fy' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'djan...
.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'dja...
cloudbase/nova-virtualbox
nova/tests/unit/conf_fixture.py
Python
apache-2.0
3,169
0
# Copyr
ight 2010 United States Government as repre
sented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apac...
openstenoproject/plover
plover/machine/base.py
Python
gpl-2.0
8,198
0.000732
# Copyright (c) 2010-2011 Joshua Harlan Lifton. # See LICENSE.txt for details. # TODO: add tests for all machines # TODO: add tests for new status callbacks """Base classes for machine types. Do not use directly.""" import binascii import threading import serial from plover import _, log from plover.machine.keymap...
dedStenotypeBase.stop_capture(self)
self._close_port() @classmethod def get_option_info(cls): """Get the default options for this machine.""" sb = lambda s: int(float(s)) if float(s).is_integer() else float(s) converters = { 'port': str, 'baudrate': int, 'bytesize': int, '...
ocefpaf/folium
folium/plugins/fast_marker_cluster.py
Python
mit
3,954
0.000506
# -*- coding: utf-8 -*- from folium.plugins.marker_cluster import MarkerCluster from folium.utilities import if_pandas_df_convert_to_numpy, validate_location from jinja2 import Template class FastMarkerCluster(MarkerCluster): """ Add marker clusters to a map using in-browser rendering. Using FastMarkerC...
are r
etained. Methods such as get_bounds() are therefore not available when using it. Parameters ---------- data: list of list with values List of list of shape [[lat, lon], [lat, lon], etc.] When you use a custom callback you could add more values after the lat and lon. E.g. [[lat, ...
xumiao/pymonk
tests/kafka_tester.py
Python
mit
1,929
0.007258
# -*- coding: utf-8 -*- """ Created on Sat Feb 01 10:45:09 2014 Training models remotely in cloud @author: pacif_000 """ from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer import os import platform if platform.system() == 'Windows': import win32api else: import signal import thread ...
producer if consumer: consumer.commit() consumer.stop() consumer = None if producer: producer.stop() producer = None
if kafka: kafka.close() kafka = None print('remote_rainter {0} is shutting down'.format(os.getpid())) def handler(sig, hook = thread.interrupt_main): global kafka, consumer, producer if consumer: consumer.commit() consumer.stop() consumer = None if producer:...
adamcaudill/yawast
yawast/scanner/plugins/http/servers/rails.py
Python
mit
1,712
0.001752
# Copyright (c) 2013 - 2020 Adam Caudill and Contributors. # This file is part of YAWAST which is released under the MIT license. #
See the LICENSE file or go to https://yawast.org/license/ for full license
details. import re from typing import List from yawast.reporting.enums import Vulnerabilities from yawast.scanner.plugins.result import Result from yawast.shared import network, output _checked: List[str] = [] def reset(): global _checked _checked = [] def check_cve_2019_5418(url: str) -> List[Result]: ...
MingfeiPan/leetcode
dp/213.py
Python
apache-2.0
1,077
0.003865
#因为首尾相连, 考虑第一位抢或不抢 两种情况分开 class Solution: def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 if len(nums) == 1: return nums[0] if len(nums) == 2: return max(nums) l = [] ...
# while nums[1] > nums[0] or nums[len(nums)-1] > nums[0]: # temp = nums[0]
# del nums[0] # nums.append(temp) # print(nums) # l = [0] * len(nums) l.append(nums[0]) l1.append(0) l.append(max(nums[0], nums[1])) l1.append(nums[1]) for i in range(2, len(nums)): if i == len(nums) - 1: l.append(...
CartoDB/geocoder-api
server/lib/python/cartodb_services/test/test_tomtomisoline.py
Python
bsd-3-clause
992
0
import unittest from mock import Mock from cartodb_services.tomtom.isolines im
port TomTomIsolines, DEFAULT_PROFILE from cartodb_services.tools import Coordinate from cred
entials import tomtom_api_key VALID_ORIGIN = Coordinate(-73.989, 40.733) class TomTomIsolinesTestCase(unittest.TestCase): def setUp(self): self.tomtom_isolines = TomTomIsolines(apikey=tomtom_api_key(), logger=Mock()) def test_calculate_isochrone(self): ...
Storj/accounts
accounts/ledger.py
Python
mit
1,481
0.00135
# -*- coding: utf-8 -*- class Ledger(object): def __init__(self, db): self.db = db def balance(self, token): cursor = self.db.cursor(
) cursor.execute("""SELECT * FROM balances WHERE TOKEN = %s""", [token]) row = cursor.fetchone() return 0 if row is None else row[2] def deposit(self, token, amount): cursor = self.db.cursor() cursor.execute( """INSERT INTO balances (token, amount) ...
", [token, token]) cursor.execute( """UPDATE balances SET amount = amount + %s WHERE token = %s""", [amount, token]) cursor.execute( """INSERT INTO movements (token, amount) VALUES(%s, %s)""", [token, amount]) self.db.commit() ...
PaulWay/spacewalk
client/solaris/rhnclient/setup.py
Python
gpl-2.0
610
0.029508
#!/usr/bin/python # # from distutils.core import setup from spacewal
k.common.rhnConfig import CFG, initCFG initCFG('web') setup(name = "rhnclient", version = "5.5.9",
description = CFG.PRODUCT_NAME + " Client Utilities and Libraries", long_description = CFG.PRODUCT_NAME + """\ Client Utilities Includes: rhn_check, action handler, and modules to allow client packages to communicate with RHN.""", author = 'Joel Martin', author_email = 'jmartin@redhat.com', ...
Ultimaker/Cura
plugins/UltimakerMachineActions/__init__.py
Python
lgpl-3.0
366
0.008197
# Copyright (c) 2019 Ultimaker B.
V. # Cura is released under the terms of the LGPLv3 or higher. from . import BedLevelMachineAction from . import UMOUpgradeSelection def getMetaData(): return {} def register(app): return { "machine_action": [ BedLevelMachineAction.BedLevelMachineAct
ion(), UMOUpgradeSelection.UMOUpgradeSelection() ]}
plotly/python-api
packages/python/plotly/plotly/validators/scatter/line/_width.py
Python
mit
523
0.001912
import _plotly_utils.basevalidators class WidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="width", parent_name="scatter.line", **kwargs):
super(WidthValidator, self).__init__( plot
ly_name=plotly_name, parent_name=parent_name, anim=kwargs.pop("anim", True), edit_type=kwargs.pop("edit_type", "style"), min=kwargs.pop("min", 0), role=kwargs.pop("role", "style"), **kwargs )
rohitjogson/pythonwork
assign27.09.py
Python
gpl-3.0
355
0.059155
n=int(input('Enter any number: ')) if n%2
!=0: n=n
+1 for i in range(n): for j in range(n): if (i==int(n/2)) or j==int(n/2) or ((i==0)and (j>=int(n/2))) or ((j==0)and (i<=int(n/2))) or ((j==n-1)and (i>=int(n/2))) or ((i==n-1)and (j<=int(n/2))): print('*',end='') else: print(' ',end='') print()
bitmingw/FindYourSister
sloth/sloth/gui/utils.py
Python
bsd-2-clause
994
0.002012
from PyQt4.QtCore import QSize from PyQt4.QtGui import QVBoxLayout # This is really really ugly, but the QDockWidget for some reason does not notice when # its child widget becomes smaller... # Therefore we manually set its minimum size when our own minimum size changes class
MyVBoxLayout(QVBoxLayout): def __init__(self, parent=None): QVBoxLayout.__init__(self, parent) self._last_size = QSize(0, 0) def setGeometry(self, r): QVBoxLayout.setGeometry(self, r) try: wid = self.parentWidget().parentWidget() new_size = self.minimum...
ize == self._last_size: return self._last_size = new_size twid = wid.titleBarWidget() if twid is not None: theight = twid.sizeHint().height() else: theight = 0 new_size += QSize(0, theight) wid.setMinimumSize(new_s...
barnsnake351/neutron
neutron/tests/unit/extensions/test_agent.py
Python
apache-2.0
7,027
0
# Copyright (c) 2013 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...
llback = agents_db.AgentExtRpcCallback() callback.report_state( self.adminContext, agent_state={'agent_state': lbaas_hosta}, time=datetime.utcnow().strftime(constants.ISO8601_TIME_FORMAT)) callback.report_state( self.adminContext, ...
)) res += [lbaas_hosta, lbaas_hostb] return res def _register_dvr_agents(self): dvr_snat_agent = helpers.register_l3_agent( host=L3_HOSTA, agent_mode=constants.L3_AGENT_MODE_DVR_SNAT) dvr_agent = helpers.register_l3_agent( host=L3_HOSTB, agent_mode=const...
zachary-williamson/ITK
Utilities/Maintenance/VNL_ModernizeNaming.py
Python
apache-2.0
3,528
0.014172
#!/bin/env python # \author Hans J. Johnson # # Prepare for the future by recommending # use of itk::Math:: functions over # vnl_math:: functions. # Rather than converting vnl_math_ to vnl_math:: # this prefers to convert directly to itk::Math:: # namespace. In cases where vnl_math:: is simply # an alias to std:: func...
de "{0}"'.format(fname)]="""#if !defined( ITK_LEGACY_FUTURE_REMOVE ) # include "{0}" #endif #include <{1}>""".format(fname,new_name) ITK_replace_head_names['#include <{0}>'.format(fname)]="""#if !defined( ITK_LEGACY_FUTURE_REMOVE ) # include <{0}> #endif #include <{1}>""".format(fname,new_name) ITK_pat=linevalu...
new_pat=linevalues[2] ITK_replace_functionnames[ITK_pat]=new_pat # Need to fix the fact that both std::ios is a base and a prefix if "std::ios::" in new_pat: ITK_replace_manual[new_pat.replace("std::ios::","std::ios_")] = new_pat #print(ITK_replace_head_names) #print(ITK_replace_functionnames) ...
pllim/astropy
astropy/samp/errors.py
Python
bsd-3-clause
637
0
# Licensed under a 3-
clause BSD style license - see LICENSE.rst """ Defines custom errors and exceptions used in `astropy.samp`. """ import xmlrpc.client as xmlrpc from astropy.utils.exceptions import AstropyUserWarning __all__ = ['SAMPWarning', 'SAMPHubError', 'SAMPClientError', 'SAMPProxyError'] class SAMPWarning(AstropyUserWarnin...
""" SAMP Client exceptions. """ class SAMPProxyError(xmlrpc.Fault): """ SAMP Proxy Hub exception """
mmolero/pcloudpy
pcloudpy/gui/components/ObjectInspectorWidget.py
Python
bsd-3-clause
1,774
0.012401
#Author: Miguel Molero <miguel.molero@gmail.com> from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class ObjectInspectorWidget(QWidget): def __init__(self, parent = None): super(ObjectInspectorWidget, self).__init__(parent) layout = QVBoxLayout() self.ta...
pdate(self, props): self.properties_tree.clear() data_tree = QTreeWidgetItem(self.properties_tree) data_tree.setText(0,"Data") #data_tree.setFont(0,QFont(c.FONT_NAME, c.FONT_SIZE_1, QFont.Bold)) labels = props.keys() values = props.values() self.populateTree(dat...
ls,values): if j is None: continue item = QTreeWidgetItem(parent) item.setText(0,i) #item.setFont(0,QFont(c.FONT_NAME, c.FONT_SIZE_2, QFont.Normal)) if isinstance(j,bool): if j is True: item.setText(1, c.MAR...
olbat/o1b4t
coding/crypto/test_hmac.py
Python
gpl-3.0
10,162
0.000098
import unittest from collections import namedtuple from io import BytesIO import codecs import sha2 import hmac class TestSHA2(unittest.TestCase): # test vectors from https://csrc.nist.gov/projects/cryptographic-standards-and-guidelines/example-values TestVector = namedtuple('TestVector', ['digestcls', 'text'...
9AAAB' 'ACADAEAF' 'B0B1B2B3' 'B4B5B6B7' 'B8B9BABB' 'BCBDBEBF' 'C0C1C2C3' 'C4C5C6C7', 'hex',
), mac=codecs.decode( '5B664436' 'DF69B0CA' '22551231' 'A3F0A3D5' 'B4F97991' '713CFA84' 'BFF4D079' '2EFF96C2' '7DCCBBB6' 'F79B65D5' '48B40E85' '64CEF594', 'hex', ), ), # SHA-512 based HMACs TestVect...
wyzekid/Python_Projects
Perceptron/Rosenblatt_perceptron.py
Python
gpl-3.0
1,928
0.015659
import numpy as np import pandas as pd import matplotlib.pyplot as plt def plot_decision_regions(X, y, clf, res=0.02): x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, res), np.arang...
m(yy.min(), yy.max()) class Perceptron(object): def __init__(self, eta=0.01, epochs=50): self.eta = eta self.epochs = epochs
def train(self, X, y): self.w_ = np.zeros(1 + X.shape[1]) self.errors_ = [] for _ in range(self.epochs): errors = 0 for xi, target in zip(X, y): update = self.eta * (target - self.predict(xi)) self.w_[1:] += update * xi ...
fusionbox/satchless
satchless/contrib/checkout/singlestep/tests/__init__.py
Python
bsd-3-clause
7,298
0.00274
# -*- coding: utf-8 -*- import os from django.conf import settings from django.core.urlresolvers import reverse from django.test import Client from .....checkout.tests import BaseCheckoutAppTests from .....delivery.tests import TestDeliveryProvider from .....order import handler as order_handler from .....payment imp...
1', 'billing_city': 'Beverly Hills', 'billing_country': 'US', 'billing_country_area': 'AZ', 'billing_phone': '555-555-5555', 'billing_postal_code': '90210'} for g, typ, form in dg: data[form.add_prefix('email')] = 'foo@e...
eckout', kwargs={'order_token': order.token}), client_instance=self.anon_client, status_code=302, method='post',...
La0/mozilla-relengapi
src/shipit/api/tests/conftest.py
Python
mpl-2.0
1,089
0.000918
# -*- coding: 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 d
istributed with this # file, You can obtain one at htt
p://mozilla.org/MPL/2.0/. import os import pytest import backend_common @pytest.fixture(scope='session') def app(): '''Load shipit_api in test mode ''' import shipit_api config = backend_common.testing.get_app_config({ 'SQLALCHEMY_DATABASE_URI': 'sqlite://', 'SQLALCHEMY_TRACK_MODIF...
MarineDataTools/pymqdatastream
pymqdatastream/connectors/todl/tools/todl_quickview.py
Python
gpl-3.0
9,129
0.011173
import sys import argparse import numpy as np import pylab as pl import netCDF4 import logging import pymqdatastream.connectors.todl.todl_data_processing as todl_data_processing try: from PyQt5 import QtCore, QtGui, QtWidgets except: from qtpy import QtCore, QtGui, QtWidgets #https://matplotlib.org/3.1.0/gall...
self.plot_button = QtWidgets.QPushButton('Plot') self.plot_button.clicked.connect(self.plot_data) self.var_combo = QtWidgets.QComboBox(self) self.layout.addWidget(self.var_combo,0,0) self.layout.addWidget(self.plot_button,0,1) if(fname is not None): ...
otvar_y = self.var_combo.currentText() plotdata_y = self.data[plotvar_y][plotvar_y][:] plotdata_x = self.data[plotvar_y]['x0'][:] try: lab_unit = '[' + self.data[plotvar_y][plotvar_y].units + ']' except: lab_unit = '' ylabel = plotvar_y + lab_unit ...
glennmckechnie/weewx-wxobs
bin/user/wxobs.py
Python
gpl-3.0
27,446
0.000911
# Copyright (c) 2017-2020 Glenn McKechnie <glenn.mckechnie@gmail.com> # Credit to Tom Keffer <tkeffer@gmail.com>, Matthew Wall and the core # weewx team, all from whom I've borrowed heavily. # Mistakes are mine, corrections and or improvements welcomed # https://github.com/glennmckechnie/weewx-wxobs # # rsync code b...
Will Page <companyguy@gmail.com> and # # See the file LICENSE.txt for your full rights. # # # added text import subprocess import time import errno import os import weewx.engine from weeutil.weeutil import to_bool from weewx.cheetahgenerator import SearchList wxobs_version = "0.7.4" try: # weewx4 logging ...
Logger(__name__) def logdbg(msg): log.debug(msg) def loginf(msg): log.info(msg) def logerr(msg): log.error(msg) except ImportError: # old-style weewx logging import syslog def logmsg(level, msg): syslog.syslog(level, 'wxobs: %s' % msg) def logdbg(msg): ...
OCA/margin-analysis
account_invoice_margin/__init__.py
Python
agpl-3.0
194
0
# © 2017 Sergio T
eruel <sergio.teruel@tecnativa.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from .hooks import pre_init_hook from . import models from . import
report
befelix/GPy
GPy/core/parameterization/transformations.py
Python
bsd-3-clause
194
0
# Copyright (c) 2014, Max Zwiesse
le, James Hensman # Licensed under the BSD 3-clause licen
se (see LICENSE.txt) from paramz.transformations import * from paramz.transformations import __fixed__
mganeva/mantid
scripts/AbinsModules/CalculateS.py
Python
gpl-3.0
2,205
0.004989
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + from __future__ import (absolute_import, divi...
alculators: * SPowderSemiEmpiricalCalculator """ @staticmethod def init(filename=None, temperature=None, sample_form=None, abins_data=None, instr
ument=None, quantum_order_num=None, bin_width=1.0): """ :param filename: name of input DFT file (CASTEP: foo.phonon) :param temperature: temperature in K for which calculation of S should be done :param sample_form: form in which experimental sample is: Powder or SingleCryst...
atomic83/youtube-dl
youtube_dl/extractor/iqiyi.py
Python
unlicense
9,558
0.000745
# coding: utf-8 from __future__ import unicode_literals import hashlib import math import random import time import uuid from .common import InfoExtractor from ..compat import compat_urllib_parse from ..utils import ExtractorError class IqiyiIE(InfoExtractor): IE_NAME = 'iqiyi' IE_DESC = '爱奇艺' _VALID_U...
self._FORMATS_MAP if _format_id == format_id] return matched_bids[0] if len(matched_bids) else None def get_raw_data(self, tvid, video_id, enc_key, _uuid): tm = str(int(time.time())) tail = tm + tvid param = { 'key': 'fvip', 'src': self.md5_text('youtube-dl'...
qyid': _uuid, 'tn': random.random(), 'um': 0, 'authkey': self.md5_text(self.md5_text('') + tail), } api_url = 'http://cache.video.qiyi.com/vms' + '?' + \ compat_urllib_parse.urlencode(param) raw_data = self._download_json(api_url, video_id) ...
upconsulting/IsisCB
isiscb/isisdata/migrations/0020_auto_20160615_1630.py
Python
mit
15,648
0.000831
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-06-15 16:30 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('isisdata', '0019_auto_20160427_1520'), ] operations = [ migrations.AddField(...
ank=True, max_length=255, null=True), ), migrat
ions.AddField( model_name='historicalauthority', name='record_status_value', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AddField( model_name='historicalccrelation', name='data_display_order', field=...
kyunooh/JellyBlog
lifeblog/migrations/0001_initial.py
Python
apache-2.0
900
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-10-14 12:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Documen...
ateTimeField(auto_now_add=True)), ('meta_tag', models.CharField(m
ax_length=150)), ('view_count', models.IntegerField(default=0, editable=False)), ('public_doc', models.BooleanField()), ('update_time', models.DateTimeField(auto_now=True)), ], ), ]
Azure/azure-sdk-for-python
sdk/edgegateway/azure-mgmt-edgegateway/azure/mgmt/edgegateway/models/upload_certificate_response.py
Python
mit
3,198
0.001876
# 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 ...
_audience: str """ _validation = {
'resource_id': {'required': True}, 'aad_authority': {'required': True}, 'aad_tenant_id': {'required': True}, 'service_principal_client_id': {'required': True}, 'service_principal_object_id': {'required': True}, 'azure_management_endpoint_audience': {'required': True}, } ...
codetalkio/TelegramIRCImageProxy
asyncirc/ircbot.py
Python
mit
5,983
0.00234
'''Todo: * Add multiple thread support for async_process functions * Potentially thread each handler function? idk ''' import sys import socket import re import threading import logging import time if sys.hexversion < 0x03000000: #Python 2 import Queue as queue BlockingIOError = socket.error else: imp...
args[2][1:] for handler in self._handlers['nick']: handler(self, nick, new_nick, host) elif command == 'NOTICE': #:nick!user@host NOTICE <userchan> :message channel = args[2] m...
r(self, nick, host, channel, message) else: logger.warning("Unhandled command %s" % command) self._in_queue.task_done() except queue.Empty as e: pass except Exception as e: logger.exception("Error while handling message...
saurabhVisie/appserver
rest_auth/registration/serializers.py
Python
mit
6,316
0.000792
from django.http import HttpRequest from django.conf import settings from django.utils.translation import ugettext_lazy as _ try: from allauth.account import app_settings as allauth_settings from allauth.utils import (email_address_exists, get_username_max_length) from allaut...
def get_cleaned_data(self): return { 'username': self.validate
d_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() ...
HyperloopTeam/FullOpenMDAO
bin/rst2odt_prepstyles.py
Python
gpl-2.0
237
0.004219
#!/
Users/shreyashirday/Personal/openmdao-0.13.0/bin/python # EASY-INSTALL-SCRIPT: 'docutils==0.10','rst2odt_prepstyles.py' __requires__ = 'docutils==0.10' __import__('pkg_resources').run_script('docutils==0.10', 'rst2odt_prepstyles.py')
tst-mswartz/earthenterprise
earth_enterprise/src/server/wsgi/search/common/exceptions.py
Python
apache-2.0
1,602
0.006866
#!/usr/bin/env python2.7 # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
plied. # See the License for the specific language governing permissions and # limitations under the License. """Module for all exception's which search services may raise.""" from search.common import utils class Error(Exception):
"""Generic error.""" def ToString(self, error_prefix): """Builds error message string escaping it for HTML. Args: error_prefix: an error prefix. Returns: HTML escaped error message. """ if error_prefix: return utils.HtmlEscape( "{0}: {1}".format(error_prefix, str("\...
BaileySN/Raspberry-Pi-Shutdown-Button
shutdown_script.py
Python
gpl-3.0
586
0.030717
#! /usr/b
in/env p
ython # coding: utf-8 -*- import RPi.GPIO as GPIO import time import os #config #change the GPIO Port number gpioport=24 sdate = time.strftime("%H:%M:%S") stime = time.strftime("%Y-%m-%d") GPIO.setmode(GPIO.BCM) GPIO.setup(gpioport, GPIO.IN) def sysshutdown(channel): msg="System shutdown GPIO.Low state" logpath="...
cmhill/q-compression
src/compress.py
Python
mit
50,746
0.005656
#!/usr/bin/env python from __future__ import print_function from collections import defaultdict from collections import deque from itertools import islice #from subprocess import call import subprocess from optparse import OptionParser from tempfile import mkstemp import glob import os import random import re import sh...
ression schemes. GB_COMPRESSION_CMD = "./src/good_bad_coding.py -r [READ] -c 2 -b 0 -i [COMPRESSED_FILE]" MAX_VALUE_COMPRESSION_CMD = "./src/good_bad_coding.py -r [READ] -g [MAX_QV
] -b 40 -c 2 -i [COMPRESSED_FILE]" MIN_VALUE_COMPRESSION_CMD = "./src/good_bad_coding.py -r [READ] -g 0 -b 0 -c 2 -i [COMPRESSED_FILE]" POLY_REGRESSION_CMD = "Rscript src/poly_regression_parallel.R [READ] [OUTPUT] [DEGREE] [COMPRESSED_FILE] [NUM_THREADS] [MAX_QV]" PROFILE_COMPRESSION_CMD = "Rscript src/prof...
yongwen/makahiki
makahiki/apps/widgets/popular_tasks/views.py
Python
mit
997
0.008024
"""Prepare rendering of popular smart grid actions widget""" from apps.widgets.smartgrid import smartgrid def supply(request, page_name): """Supply view_objects content, which are the popular actions from the smart grid game.""" _ = request num_results = 5 if page_name != "status" else None #cont...
ar_actions("event", "pend
ing", num_results), "Excursion": smartgrid.get_popular_actions("excursion", "pending", num_results), } count = len(popular_tasks) return { "popular_tasks": popular_tasks, "no_carousel": page_name == "status", "range": count, }
openplans/shareabouts-api
src/sa_api_v2/migrations/0005_add_dimensions_to_attachments.py
Python
gpl-3.0
702
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-02-29 16:58 from __future__ import unicode_literals import django.contrib.auth.validators from django.db import migrations, models import django.db.models.
deletion class Migration(migrations.Migration): dependencies = [ ('sa_api_v2', '0004_django_19_updates'), ] operations = [ migrations.AddField( model_name='attachment', name='height', field=models.IntegerField(blank=True, null=True), ), ...
name='width', field=models.IntegerField(blank=True, null=True), ), ]
meng-sun/hil
haas/auth.py
Python
apache-2.0
4,101
0.000244
"""Authentication and authorization.""" from haas.errors import AuthorizationError from haas import model from abc import ABCMeta, abstractmethod import sys _auth_backend = None class AuthBackend(object): """An authentication/authorization backend. Extensions which implement authentication/authorization b...
ror("This operation is administrator-only.") def require_project_access(self, project): """Like ``require_admin()``, but wraps ``have_project_access()``.""" if not self.have_project_access(project): raise AuthorizationError( "You do not have access to the required projec...
as it's argument. """ global _auth_backend if _auth_backend is not None: sys.exit("Fatal Error: set_auth_backed() called twice. Make sure " "you don't have conflicting extensions loaded.") _auth_backend = backend def get_auth_backend(): """Return the current auth backend....
shamidreza/unitselection
experiment.py
Python
gpl-2.0
3,464
0.018764
""" Author: Seyed Hamidreza Mohammadi This file is part of the shamidreza/uniselection software. Please refer to the LICENSE provided alongside the software (which is GPL v2, http://www.gnu.org/licenses/gpl-2.0.html). This file includes the code for putting all the pieces together. """ from utils import * from extra...
o.wavfile import write as wwrite wwrite('out.wav', 16000, wavs) print 'successfully saved o
ut.wav'
hackaugusto/raiden
raiden/tests/utils/app.py
Python
mit
351
0.002849
import os import os.path from raiden.constants import RAIDEN_DB_VERSION def database_from_privatekey(base_dir, app_number): """ Format a database path based on the p
rivate key and app number. """ dbpath = os.path.join(base_dir, f"app{app_number}", f"v{RAIDEN_DB_VERSION}_log.db") os.makedirs(
os.path.dirname(dbpath)) return dbpath
5monkeys/django-formapi
formapi/tests.py
Python
mit
8,355
0.001078
# coding=utf-8 from datetime import datetime, date, time from decimal import Decimal import json import django from django.forms import IntegerField from django.test import TransactionTestCase, Client from django.utils.functional import curry from django.utils.translation import ugettext_lazy import pytz from formapi...
ads(smart_u(response.content)) s
elf.assertEqual(response_data['errors'], {}) self.assertTrue(response_data['success']) self.assertIsNotNone(response_data['data']) def test_invalid_call(self): response = self.send_request('/api/v1.0.0/math/subtract/', {'username': self.user.username, 'password': 'rosebud'}) self.as...
Jim-Rod/csv_summary
csv_summary.py
Python
mit
2,979
0.006378
''' 20140213 Import CSV Data - Dict Save as JASON? Basic Stats Save to file Find Key Words Generate Reports... Generate Plots ''' import csv import numpy as np import matplotlib as mpl from scipy.stats import nanmean filename = '20140211_ING.csv' ###____________ Helper ___________### def number_fields(data): ...
) for i in fields: print('FIELD: \t\t %s' % i) print('#Values: \t %s' % d[i]['#Values']) print('Max: \t\t %s' % d[i]['Max']) print('Min: \t\t %s' % d[i]['Min']) print('Mean: \t\t %s' % round(d[i]['Mean'], 2)) print('--------------------') print('') ###______...
"") numeric_report(filename) main(filename)
hsoft/musicguru
qt/ignore_box.py
Python
bsd-3-clause
1,816
0.008811
# -*- coding: utf-8 -*- # Created By: Virgil Dupras # Created On: 2009-09-19 # Copyright 2010 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://...
Model.__init__(self, app, app.board.ignore_box, IGNORE_BOX_NAME) self.connect(self.app, SIGNAL('ignoreBoxChanged()'), self.ignoreBoxChanged) #--- Events def ignoreBoxChan
ged(self): self.reset() class IgnoreBox(QWidget, Ui_IgnoreBox): def __init__(self, app): QWidget.__init__(self, None) self.app = app self.boxModel = IgnoreBoxModel(app) self._setupUi() self.connect(self.browserView.selectionModel(), SIGNAL('selectionCha...
WaveBlocks/WaveBlocksND
WaveBlocksND/Interface/EigentransformWavefunction.py
Python
bsd-3-clause
2,041
0.00294
"""The WaveBlocks Project Compute the transformation to the eigen basis for wavefunction. @author: R. Bourquin @copyright: Copyright (C) 2012, 2016 R. Bourquin @license: Modified BSD License """ from WaveBlocksND import BlockFactory from WaveBlocksND import WaveFunction from WaveBlocksND import BasisTransformationWF...
"""Compute the transformation to the eigenbasis for a wavefunction. Save the result back to a file. :param iomin: An :py:class:`IOManager: instance providing the simulation data. :param iomout: An :py:class:`IOManager: instance for saving the transformed data. :param blockidin: The data block from wh...
emilydolson/forestcat
pyrobot/tools/sound.py
Python
agpl-3.0
6,306
0.014589
try: import ossaudiodev except: print "ossaudiodev not installed" ossaudiodev = None try: import FFT except: print "FFT not installed" ossaudiodev = None try: import Numeric except: print "Numeric not installed" ossaudiodev = None import struct, math, time, threading, copy def add(s...
nmax([(v1 + v2) for (v1, v2) in zip(s1, s2)]) def minmax(vector): return [min(max(v,0),255) for v in vector] def scale(sample, value): return minmax([((s
- 128) * value) + 128 for s in sample]) def sine(freqs, seconds, volume = 1.0, sample_rate = 8000.0): sample = [128] * int(sample_rate * seconds) if type(freqs) == type(0): freqs = [freqs] for freq in freqs: for n in range(len(sample)): sample[n] += int(127 * math.sin(n * 2 * m...
kaarolch/ansible
test/units/parsing/vault/test_vault_editor.py
Python
gpl-3.0
6,376
0.000941
# (c) 2014, James Tanner <tanner.jc@gmail.com> # (c) 2014, James Cammarata, <jcammarata@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version ...
ng files if we don't have access to AES, KDF or Counter. if not HAS_AES or not HAS_COUNTER or not HAS_PBKDF2: raise SkipTest v10_file = tempfile.N
amedTemporaryFile(delete=False) with v10_file as f: f.write(to_bytes(v10_data)) ve = VaultEditor("ansible") # make sure the password functions for the cipher error_hit = False try: ve.rekey_file(v10_file.name, 'ansible2') except errors.AnsibleErr...
kumarisneha/practice_repo
techgig_rstrip.py
Python
mit
83
0.024096
def main():
a=raw_input()
print a.lstrip() print "Hello world" main()
ericam/sidesaddle
modules/typogrify.py
Python
mit
620
0.001613
from __future__ import absolute_import from jinja2 import Markup from rstblog.programs import RSTProgram import typogrify class TypogrifyRSTProgram(RSTProgram): def get_fragments(self): if self._fragment_cache is not None: return self._fragment_cache with self.context.open_source_fil...
ment'] = Markup(typogrify.typogrify(rv['fragment'])) self._fragment_cache = rv return rv def setup(builder): bui
lder.programs['rst'] = TypogrifyRSTProgram
abelcarreras/aiida_extensions
plugins/launcher/launch_lammps_md_si.py
Python
mit
2,634
0.002278
from aiida import load_dbenv load_dbenv() from aiida.orm import Code, DataFactory import numpy as np StructureData = DataFactory('structure') ParameterData = DataFactory('parameter') codename = 'lammps_md@boston' ############################ # Define input parameters # ############################ a = 5.404 cell...
uid='{}')".format(calc.uuid) print "Submit file in {}".format(os.path.join( os.path.relpath(subfolder.abspath), script_filename)) else: calc.store_all() print "created calculation; calc=Calculation(uuid='{}') # ID={}".format( ...
ID={}".format( calc.uuid, calc.dbnode.pk)
DataDog/integrations-extras
riak_repl/setup.py
Python
bsd-3-clause
2,385
0.000839
from codecs import open # To use a consistent encoding from os import path from setuptools import setup HERE = path.dirname(path.abspath(__file__)) # Get version info ABOUT = {} with open(path.join(HERE, 'datadog_checks', 'riak_repl', '__about__.py')) as f: exec(f.read(), ABOUT) # Get the long description from...
7', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], # The package we're going to ship packages=['datadog_checks', 'datadog_checks.riak_repl'], # Run-time dependencies install_requires=[CHECKS_BASE_REQ], extras_require={'deps':
parse_pyproject_array('deps')}, # Extra files to ship with the wheel package include_package_data=True, )
khosrow/metpx
sundew/doc/pds_conversion/routing_step1.py
Python
gpl-2.0
1,705
0.039883
import os,sys,re # EXTRACTING ALL FILENAMES AND THEIR CLIENTS # --------------------------------------------------- # read in the log # --------------------------------------------------- f=open(sys.argv[1],'rb') data=f.readlines() f.close() n=0 t=len(data) clients = [] filename = None for l in data : n = n...
have its first client as "allproducts" if filename != None : if len(clients) == 0 : clients.append('allproducts') else : clients.sort() clients.insert(0,'allproducts') print("%s %s" % (filename,','.join(clients)) ) filepath = parts[-1] ...
070409000009 trailing get rid of it if fparts[-1][:2] == '20' and len(fparts[-1]) == 14 : fparts = fparts[:-1] # '::' trailing get rid of it if fparts[-1] == '' : fparts = fparts[:-1] filename = ':'.join(fparts) clients = [] if parts[6] == 'Written' : ...
nortd/bomfu
admin/users.py
Python
lgpl-3.0
4,033
0.002727
# -*- coding: utf-8 -*- import webapp2 from boilerplate import models from boilerplate import forms from boilerplate.handlers import BaseHandler from google.appengine.datastore.datastore_query import Cursor from google.appengine.ext import ndb from google.appengine.api import users as googleusers from collections impor...
der(-models.User.key).fetch_page(PAGE_SIZE, start_cursor=cursor) users = list(reversed(users)) if next_cursor and more: self.view.prev_cursor = next_cursor self.view.next_cursor = cursor.reversed()
def pager_url(p, cursor): params = OrderedDict() if q: params['q'] = q if p in ['prev']: params['p'] = p if cursor: params['c'] = cursor.urlsafe() return self.uri_for('user-list', **params) self.view.p...
erasmospunk/electrumx
tests/server/test_api.py
Python
mit
2,877
0
import asyncio from unittest import mock from aiorpcx import RPCError from server.env import Env from server.controller import Controller loop = asyncio.get_event_loop() def set_env(): env = mock.create_autospec(Env) env.coin = mock.Mock() env.loop_policy = None env.max_sessions = 0 env.max_subs...
value = coro(response) res = await sut.transaction_get('ff'*32, True) assert res == response response = { "hex": "00"*32, "blockhash": None } sut.daemon_request.return_value = coro(response) res = await sut.transaction_get('ff'*32, True) a...
env = set_env() sut = Controller(env) sut.daemon_request = mock.Mock() response = 'cafebabe'*64 sut.daemon_request.return_value = coro(response) res = await sut.transaction_get('ff'*32) assert res == response async def test_verbose_failure(): env = set_env()...
stadelmanma/netl-ap-map-flow
apmapflow/data_processing/histogram_logscale.py
Python
gpl-3.0
2,486
0
""" ======
===================
======================================================= Logscaled Histogram ================================================================================ | Calculates a logarithmically spaced histogram for a data map. | Written By: Matthew Stadelman | Date Written: 2016/03/07 | Last Modifed: 2016/10/20 """ import ...
dergraaf/xpcc
tools/device_file_generator/avr_generator.py
Python
bsd-3-clause
1,677
0.019678
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (c) 2013, Roboterclub Aachen e.V. # All rights reserved. # # The file is part of the xpcc library and is released under the 3-clause BSD # license. See the file `LICENSE` for the full license governing this code. # ----------------------------------------------...
irname(__file__), '..', 'device_files')) from logger import Logger from dfg.device import Device from dfg.merger import DeviceMerger from dfg.avr.avr_reader import AVRDeviceReader from dfg.avr.avr_writer import AVRDeviceWriter if __name__ == "__main__": """ Some test code """ level = 'info' logger = Logger(leve...
ger.setLogLevel(level) continue xml_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'AVR_devices', (arg + '*')) files = glob.glob(xml_path) for file in files: # deal with this here, rather than rewrite half the name merging if os.path.basename(file) != "ATtiny28.xml": part = AVRDevic...
wagnerand/zamboni
mkt/feed/serializers.py
Python
bsd-3-clause
2,948
0.002035
from rest_framework import relations, serializers import amo import mkt.carriers import mkt.regions from addons.models import Category from mkt.api.fields import SplitField, TranslationSerializerField from mkt.api.serializers import URLSerializerMixin from mkt.collections.serializers import (CollectionSerializer, Slug...
d(required=False) pullquote_rating = serializers.IntegerField(required=False) pullquote_text = TranslationSerializerField(required=False) class Meta: fields = ('app', 'description', 'id', 'preview', 'pullquote_attr
ibution', 'pullquote_rating', 'pullquote_text', 'url') model = FeedApp url_basename = 'feedapp' class FeedItemSerializer(URLSerializerMixin, serializers.ModelSerializer): carrier = SlugChoiceField(required=False, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugCho...
jhosmer/PySmile
tests/pysmile_tests.py
Python
apache-2.0
11,679
0.004196
#!/usr/bin/env python import os import glob import unittest import pysmile import json __author__ = 'Jonathan Hosmer' class PySmileTestDecode(unittest.TestCase): def setUp(self): curdir = os.path.dirname(os.path.abspath(__file__)) self.smile_dir = os.path.join(curdir, 'data', 'smile') ...
else: self.fail('Unexpected Type: {!r}'.format(type(a))) def test_test2(self): s = os.path.join(self.smile_dir, 'test2.smi
le') j = os.path.join(self.json_dir, 'test2.jsn') b = json.load(open(j, 'rb')) try: a = pysmile.decode(open(s, 'rb').read()) except pysmile.SMILEDecodeError, e: self.fail('Failed to decode:\n{!r}\n{!r}'.format(b, e.args[1])) else: if isinstance...
atomman/nmrglue
examples/jbnmr_examples/s4_2d_plotting/plot_2d_pipe_spectrum.py
Python
bsd-3-clause
929
0
import nmrglue as ng import matplotlib.pyplot as plt # read in data dic, data = ng.pipe.read("test.ft2") # find PPM limits along each axis uc_15n = ng.pipe.make_uc(dic, data, 0)
uc_13c = ng.pipe.make_uc(dic, data, 1) x0, x1 = uc_13c.ppm_limits() y0, y1 = uc_15n.ppm_limits() # plot the spectrum fig = plt.figure(figsize=(10, 10)) fig = plt.figure() ax = fig.add_subplot(111) cl = [8.5e4 * 1.30 ** x for x in range(20)] ax.contour(data, cl, colors='blue', extent=(x0, x1, y0, y1), linewidths=0.5) ...
c.ppm_scale() s1 = data[uc_15n("105.52ppm"), :] s2 = data[uc_15n("115.85ppm"), :] s3 = data[uc_15n("130.07ppm"), :] ax.plot(x, -s1 / 8e4 + 105.52, 'k-') ax.plot(x, -s2 / 8e4 + 115.85, 'k-') ax.plot(x, -s3 / 8e4 + 130.07, 'k-') # label the axis and save ax.set_xlabel("13C ppm", size=20) ax.set_xlim(183.5, 167.5) ax.set...
tsavola/concrete
python/concrete/tools.py
Python
lgpl-2.1
3,421
0.030108
#!/usr/bin/env python3 # # Copyright (c) 2012 Timo Savola # # This library 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 2.1 of the License, or (at your option) any later version. # ...
data(self, address, size): if address + size > len(self.data): raise Exception("address %u size %u out of arena (size %u)" % (address, size, len(self.data))) return self.data[address:address+size] def main(): parser = argparse.ArgumentParser() subparsers = parser.ad
d_subparsers() arena_parser = subparsers.add_parser("arena") arena_parser.set_defaults(func=arena_command) arena_parser.add_argument("filename", type=str, metavar="FILE") arena_parser.add_argument("--dump", action="store_true") args = parser.parse_args() args.func(args) def arena_command(args): error = None ...
astropy/photutils
photutils/aperture/tests/test_photometry.py
Python
bsd-3-clause
32,618
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tests for the photometry module. """ import pytest import numpy as np from numpy.testing import (assert_allclose, assert_array_equal, assert_array_less) from astropy.coordinates import SkyCoord from astropy.io import fits f...
(5, 8, np.pi / 4), (8, 12, 8, 16./3., np.pi / 8)))) @pytest.mark.parametrize(('aperture_class', 'params'), TEST_APERTURES) def test_outside_array(aperture_class, params): data = np.ones((10, 10), dtype=
float) aperture = aperture_class((-60, 60), *params) fluxtable = aperture_photometry(data, aperture) # aperture is fully outside array: assert np.isnan(fluxtable['aperture_sum']) @pytest.mark.parametrize(('aperture_class', 'params'), TEST_APERTURES) def test_inside_array_simple(aperture_class, params)...
FinalAngel/django-cms
cms/tests/test_cache.py
Python
bsd-3-clause
37,055
0.001538
# -*- coding: utf-8 -*- import time from django.conf import settings from django.template import Context from sekizai.context import SekizaiContext from cms.api import add_plugin, create_page, create_title from cms.cache import _get_cache_version, invalidate_cms_page_cache from cms.cache.placeholder import ( _g...
gacyCachePlugin, NoCachePlugin, SekizaiPlugin, TimeDeltaCacheExpirationPlugin, TTLCacheExpirationPlugin, VaryCacheOnPlugin, ) from cms.test_utils.testcases i
mport CMSTestCase from cms.test_utils.util.fuzzy_int import FuzzyInt from cms.toolbar.toolbar import CMSToolbar from cms.utils import get_cms_setting from cms.utils.helpers import get_timezone_name class CacheTestCase(CMSTestCase): def tearDown(self): from django.core.cache import cache super(Cach...
Zex/Starter
cgi-bin/leave_message.py
Python
mit
1,575
0.010159
#!/usr/bin/python import cgi from redis import Connection from socket import gethostname from navi import * fields = cgi.FieldStorage() title = "Message Box" msg_prefix = 'custom.message.' def insert_msg(cust, tm, msg): conn = Connection(host=gethostname(),port=6379) conn.send_command('set', msg_prefix+cust...
log" + "</h2>" for k, v in zip(keys, vals): ret += "<span>" + k.replace(msg_prefix, '').replace('--', ' ') + "</span>" ret += "<pre readonly=\"true\">" + v + "</pre>" conn.disconnect() ret += "<br>" return ret def reply(): import time, os ret = "" ret +=
"Content-Type: text/html\n\n" ret += "<!DOCTYPE html>" ret += "<html>" ret += default_head(title) ret += default_navigator() ret += "<body>" ret += "<div class=\"content\">" ret += "<h2>Welcome, " + os.environ["REMOTE_ADDR"] + "!</h2>" ret += "<span>" + os.environ["HTTP_USER_AGENT"]...
OCA/social
website_mass_mailing_name/__init__.py
Python
agpl-3.0
91
0
# L
icense LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from . i
mport controllers
wglass/zoonado
tests/protocol/test_response.py
Python
apache-2.0
731
0
import struct import unittest from zoonado.protocol import response, primitives class ResponseTests(unittest.TestCase): def test_deserialize(self): class FakeResponse(response.Response): opcode = 99 parts = ( ("first", primitives.Int), ("second",...
nd opcode are omitted, they're part of a preamble # that a connection would use to determine whic
h Response to use # for deserializing raw = struct.pack("!ii6s", 3, 6, b"foobar") result = FakeResponse.deserialize(raw) self.assertEqual(result.first, 3) self.assertEqual(result.second, u"foobar")
Yukarumya/Yukarum-Redfoxes
testing/mozharness/configs/builds/releng_sub_linux_configs/64_valgrind.py
Python
mpl-2.0
1,603
0.004367
import os MOZ_OBJDIR = 'obj-
firefox' config = { 'default_actions': [ 'clobber', 'clone-tools', 'checkout-sources', #'setup-mock', 'build', #'upload-files', #'sendchange', 'check-test', 'valgrind-test', #'generate-build-stats', #'update', ], 'stage...
tly_en_US_routes': False, 'build_type': 'valgrind', 'tooltool_manifest_src': "browser/config/tooltool-manifests/linux64/\ releng.manifest", 'platform_supports_post_upload_to_latest': False, 'enable_signing': False, 'enable_talos_sendchange': False, 'perfherder_extra_options': ['valgrind'], #...
akademikbilisim/ab-kurs-kayit
abkayit/training/migrations/0007_auto_20160628_1243.py
Python
gpl-3.0
617
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from
django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('training', '0006_auto_20160627_1620'), ] operations = [ migrations.RemoveField( model_name='trainesscourserecord'
, name='approvedby', ), migrations.RemoveField( model_name='trainesscourserecord', name='createdby', ), migrations.RemoveField( model_name='trainesscourserecord', name='createtimestamp', ), ]
shabab12/edx-platform
lms/djangoapps/course_api/blocks/transformers/proctored_exam.py
Python
agpl-3.0
2,327
0.003008
""" Proctored Exams Transformer """ from django.conf import settings from edx_proctoring.api import get_attempt_status_summary from edx_proctoring.models import ProctoredExamStudentAttemptStatus from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin class Proct...
) ): # This section is an exam. It should be excluded unless the # user is not a verified student or has declined taking the exam. user_exam_summary = get_attempt_status_summary( usage_info.user.id
, unicode(block_key.course_key), unicode(block_key), ) return user_exam_summary and user_exam_summary['status'] != ProctoredExamStudentAttemptStatus.declined return [block_structure.create_removal_filter(is_proctored_exam_for_user)]
guille0/space-chess
config.py
Python
mit
5,079
0.024808
from panda3d.core import LPoint3 # EDIT GAMEMODE AT THE BOTTOM (CHESS VARIANTS) # COLORS (for the squares) BLACK = (0, 0, 0, 1) WHITE = (1, 1, 1, 1) HIGHLIGHT = (0, 1, 1, 1) HIGHLIGHT_MOVE = (0, 1, 0, 1) HIGHLIGHT_ATTACK = (1, 0, 0, 1) # SCALE (for the 3D representation) SCALE = 0.5 PIECE_SCALE = 0.3 BOARD_HEIGHT = ...
[ 3, 1, 1, 1, 3], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], ], [ [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0,
0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], ], [ [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0], [-3,-1,-1,-1,-3], [-2,-4,-6,-4,-2], ], ] CARD_PAWN_2STEP = True CARD_BOARD = [ [ [ 2, 5, 6, 2],...
V11/volcano
server/sqlmap/plugins/dbms/sqlite/connector.py
Python
mit
3,003
0.00333
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import sqlite3 except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger f...
lmapMissingDependence from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pysqlite.googlecode.com/ and http://packages.ubuntu.com/quantal/python-sqlite User guide: http://docs.python.org/release/2.5/lib/module-sqlite3.html API: ht...
ite3 (SQLite 3) License: MIT Possible connectors: http://wiki.python.org/moin/SQLite """ def __init__(self): GenericConnector.__init__(self) self.__sqlite = sqlite3 def connect(self): self.initConnection() self.checkFileDb() try: self.connector...
Nebucatnetzer/tamagotchi
pygame/lib/python3.4/site-packages/mixer/backend/sqlalchemy.py
Python
gpl-2.0
8,887
0.000675
""" SQLAlchemy support. """ from __future__ import absolute_import import datetime from types import GeneratorType import decimal from sqlalchemy import func # from sqlalchemy.orm.interfaces import MANYTOONE from sqlalchemy.orm.collections import InstrumentedList from sqlalchemy.sql.type_api import TypeDecorator try:...
(Date, DATE): datetime.date, (DateTime, DATETIME): datetime.datetime, (Time, TIME): datetime.time, (DECIMAL, Numeric, NUMERIC): decimal.Decimal, (Float, FLOAT): float, (Integer, INTEGER, INT): int, (BigInteger, BIGINT): t.BigInteger, (SmallInteger, SMALLINT):...
my. """ factory = GenFactory def __init__(self, cls, **params): """ Init TypeMixer and save the mapper. """ super(TypeMixer, self).__init__(cls, **params) self.mapper = self.__scheme._sa_class_manager.mapper def postprocess(self, target, postprocess_values): """ Fill postp...
NcLang/vimrc
sources_non_forked/YouCompleteMe/third_party/ycmd/third_party/JediHTTP/jedihttp/compatibility.py
Python
mit
2,108
0.019924
# Copyright 2015 Cedraro Andrea <a.cedraro@gmail.com> # Licensed under the Apache License, Ve
rsion 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde
r 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. import sys if sys.version_info[0] >= 3: basestring = str unicode = str def encod...
blattms/opm-common
python/tests/test_emodel.py
Python
gpl-3.0
5,037
0.010125
import unittest import sys import numpy as np from opm.util import EModel try:
from tests.utils import test_path except ImportError: from utils import test_path class TestEModel(unittest.TestCase): def test_open_model(self): refArrList = ["PORV", "CELLVOL", "DEPTH", "DX", "DY", "DZ", "PORO", "PERMX", "PERMY", "PERMZ", "NTG", "TRANX", "TRANY", "TRANZ"...
"IMBNUM", "PVTNUM", "SATNUM", "SWL", "SWCR", "SGL", "SGU", "ISWL", "ISWCR", "ISGL", "ISGU", "PPCW", "PRESSURE", "RS", "RV", "SGAS", "SWAT", "SOMAX", "SGMAX"] self.assertRaises(RuntimeError, EModel, "/file/that/does_not_exists") self.assertRaises(ValueError...
filipenf/ansible
lib/ansible/cli/console.py
Python
gpl-3.0
16,263
0.003136
# (c) 2014, Nandor Sivok <dominis@haxor.hu> # (c) 2016, Redhat Inc # # ansible-console 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. ...
e(self): self.parser = CLI.base_parser( usage='%prog <host-pattern> [options]', runas_opts=True, inventory_opts=True, connect_opts=True, check_opts=True, vault_opts=True, fork_opts=True, module_opts=True, ) ...
self.parser.set_defaults(cwd='*') self.options, self.args = self.parser.parse_args(self.args[1:]) display.verbosity = self.options.verbosity self.validate_conflicts(runas_opts=True, vault_opts=True, fork_opts=True) return True def get_names(self): return dir(self)...
Sybrand/digital-panda
digitalpanda/bucket/abstract.py
Python
mit
2,411
0
from abc import ABCMeta, abstractmethod class ProgressMessage(object): def __init__(self, path, bytes_per_second, bytes_read, bytes_expected): self._path = path self._bytes_per_second = bytes_per_second self._bytes_read = bytes_read self._bytes_expected = bytes_expected @prope...
d = None def get_hash(self): return self._hash def set_hash(self, value): self._hash = value def get_dateModified(self): return self._dateModified def set_dateModified(self, value): self._dateModified = value def get_content_type(self): return self._conte...
@property def path(self): return self._path @property def name(self): return self._name @property def isFolder(self): return self._folder contentType = property(get_content_type, set_content_type) hash = property(get_hash, set_hash) dateModified = propert...
ksmit799/Toontown-Source
toontown/parties/activityFSMs.py
Python
mit
3,442
0.004067
from direct.directnotify import DirectNotifyGlobal from BaseActivityFSM import BaseActivityFSM from activityFSMMixins import IdleMixin from activityFSMMixins import RulesMixin from activityFSMMixins import ActiveMixin from activityFSMMixins import DisabledMixin f
rom activityFSMMixins import ConclusionMixin from activityFSMMixins import WaitForEnoughMixin from activityFSMMixins import WaitToStartMixin from activityFSMMixins import WaitClientsReadyMixin from activityFSMMixins import WaitForServerMixin class FireworksActivityFSM(BaseActivityFSM, IdleMixin, ActiveMixin, DisabledM...
g('__init__') BaseActivityFSM.__init__(self, activity) self.defaultTransitions = {'Idle': ['Active', 'Disabled'], 'Active': ['Disabled'], 'Disabled': []} class CatchActivityFSM(BaseActivityFSM, IdleMixin, ActiveMixin, ConclusionMixin): notify = DirectNotifyGlobal.directNotify.new...
thergames/thergames.github.io
lib/tomorrow-pygments/styles/tomorrownightblue.py
Python
mit
5,509
0.000363
# -*- coding: utf-8 -*- """ tomorrow night blue --------------------- Port of the Tomorrow Night Blue colour scheme https://github.com/chriskempson/tomorrow-theme """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, Text, \ Number, Operator, Generic, Whitespace, ...
Name.Variable.Class: "", # class: 'vc' - to be revised Name.Variable.Global: "", # class: 'vg' - to be revised Name.Variable.Instance: "", # class: 'vi' - to be revised Number: ORANGE, # class: 'm' Number.Float: ...
# class: 'mf' Number.Hex: "", # class: 'mh' Number.Integer: "", # class: 'mi' Number.Integer.Long: "", # class: 'il' Number.Oct: "", # class: 'mo' Literal: ORANGE, # class: 'l' ...
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam
unittests/Applications/test_ConvertToCSV.py
Python
gpl-2.0
106
0.009434
import unittest from PyFoam
.Applications.ConvertToCSV import ConvertToCSV theSuite=unittest.TestSui
te()
dmlc/tvm
tests/python/contrib/test_ethosn/test_mean.py
Python
apache-2.0
2,066
0.001452
# 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...
tvm.testing import requires_ethosn from . import infrastructure as tei def _get_model(shape, axis, keepdims, input_zp, input_sc, output_zp, output_sc, dtype): a =
relay.var("a", shape=shape, dtype=dtype) casted = relay.op.cast(a, "int32") mean = relay.mean(casted, axis, keepdims) model = relay.qnn.op.requantize( mean, input_scale=relay.const(input_sc, "float32"), input_zero_point=relay.const(input_zp, "int32"), output_scale=relay.cons...
HonzaKral/warehouse
warehouse/legacy/tables.py
Python
apache-2.0
12,359
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
ForeignKey( "accounts_user.username", onupdate="CASCADE", ), ), Column("last_modified", Date(), nullable=False), Column("description", String(2
55), nullable=False), ) oauth_nonce = Table( "oauth_nonce", db.metadata, Column("timestamp", Integer(), nullable=False), Column("consumer", String(32), nullable=False), Column("nonce", String(32), nullable=False), Column("token", String(32)), ) oauth_request_tokens = Table( "oauth_reque...
tectronics/mpmath
doc/run_doctest.py
Python
bsd-3-clause
222
0.004505
#!/usr/bin/env python imp
ort os import os.path path = "source" import doctest for f in os.listdir(path): if f.endswith(".txt"): pri
nt f doctest.testfile(os.path.join(path, f), module_relative=False)
ssalevan/cobbler
koan/qcreate.py
Python
gpl-2.0
7,315
0.008612
""" Virtualization installation functions. Copyright 2007-2008 Red Hat, Inc. Michael DeHaan <mdehaan@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 License, or...
% version pass guest.set_name(name) guest.set_memory(ram) guest.set_vcpus(vcpus) # for KVM, we actually can't disable this, since it's the only # console it has other than SDL guest.set_graphics("vnc") if uuid is not
None: guest.set_uuid(uuid) for d in disks: print "- adding disk: %s of size %s" % (d[0], d[1]) if d[1] != 0 or d[0].startswith("/dev"): guest.disks.append(virtinst.VirtualDisk(d[0], size=d[1])) else: raise koan.InfoException("this virtualization type does not...
ai-se/parGALE
epoal_src/parallelfeaturesplitGIA.py
Python
unlicense
33,034
0.009293
''' Created on Nov 21, 2013 @author: ezulkosk ''' from FeatureSplitConfig import ers_optional_names, bdb_optional_names, \ webportal_optional_names, eshop_optional_names, ers_config_split_names, \ webportal_config_split_names, eshop_config_split_names, bdb_config_split_names from consts import METRICS_MAXIMIZE...
intList.append( Real(constraintSplitList[0].strip()) > RealVal(constraintSplitList[1].strip())) else: ConvertedZ3ConstraintList.append( Int(constraintSplitList[0].strip()) > IntVal(constraintSplitList[1].strip())) #print ConvertedZ3...
else: constraintSplitList = constraint.split('<') #print constraintSplitList if constraintSplitList[1].find('/') != -1: ConvertedZ3ConstraintList.append( Real(constraintSplitList[0].strip())...
lbybee/vc_network_learning_project
code/gen_load_data.py
Python
gpl-2.0
177
0
import load_data as ld i
mport sys import os f_list = os.listdir(sys.argv[1]) data = ld.loadIntoPandas(ld.processAllDocuments(sys.argv[1], f_list)) data.to_pickle(sy
s.argv[2])
denisbalyko/checkio-solution
gcd.py
Python
mit
635
0.001575
from fractions import gcd def greatest_common_divisor(*args): args = list(args) a, b = args.pop(), args.pop() gcd_local = gcd(a, b) while len(args): gcd_local = gcd(gcd_local, args.pop()) return gcd_local def test_function(): assert greatest_common_divisor(6, 10, 15) == 1, "12" a...
= 2, "Three argum
ents" assert greatest_common_divisor(2, 3, 5, 7, 11) == 1, "Prime numbers" assert greatest_common_divisor(3, 9, 3, 9) == 3, "Repeating arguments" if __name__ == '__main__': test_function()
angelapper/odoo
addons/account/models/account_bank_statement.py
Python
agpl-3.0
47,237
0.004573
# -*- coding: utf-8 -*- from openerp import api, fields, models, _ from openerp.osv import expression from openerp.tools import float_is_zero from openerp.tools import float_compare, float_round from openerp.tools.misc import formatLang from openerp.exceptions import UserError, ValidationError import time import math...
ds.Date(required=True, states={'confirm': [('readonly', True)]}, select=True, copy=False,
default=fields.Date.context_today) date_done = fields.Datetime(string="Closed On") balance_start = fields.Monetary(string='Starting Balance', states={'confirm': [('readonly', True)]}, default=_default_opening_balance) balance_end_real = fields.Monetary('Ending Balance', states={'confirm': [('readonly', Tru...
cnelson/python-fleet
fleet/v1/errors.py
Python
apache-2.0
1,594
0.002509
class APIError(Exception): """Represents an error returned in a response to a fleet API call This exception will be raised any time a response code >= 400 is returned Attributes: code (int): The response code message(str): The message included with the error response http_error(goo...
on to be raised If you need access to the raw response, this is where you'll find it. """ def __init__(self, code, message, http_error): """Construct an exception representing an error returned by...
http_error(googleapiclient.errors.HttpError): The underlying exception that caused this exception to be raised. """ self.code = code self.message = message self.http_error = http_error def __str__(self): # Ret...
johnjohnlin/nicotb
sim/ahb/Ahb_test.py
Python
gpl-3.0
2,569
0.024912
# Copyright (C) 2018, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw # This file is part of Nicotb. # Nicotb 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 opti...
otocol import Ahb import operator as op import numpy as np from os import getenv def main(): N = 10 scb = Scoreboard() test = scb.GetTest("ahb", ne=op.ne, max_err=10) bg = BusGetter(callbacks=[test.Get]) ms = Ahb.Master(hsel, haddr, hwrite, htrans, hsize, hburst, hready, hresp, rd, wd, ck_ev) yield rs_ev for i ...
ngle R/W\n" f"MAGIC/ADR is {MAGIC}/{ADR}" ) test.Expect(MAGIC) yield from ms.Write(ADR, MAGIC) read_v = yield from ms.Read(ADR) test.Get(read_v) yield ck_ev MAGIC = next(r) ADR = 100 print( "Test Pipelined R/W\n" f"MAGIC/ADR is {MAGIC}/{ADR}" ) wcmd = [(True, ADR+i*4, MAGIC+i) for i in range(N)] rcmd...
ChinaMassClouds/copenstack-server
openstack/src/horizon-2014.2/horizon/browsers/breadcrumb.py
Python
gpl-2.0
1,803
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
= parent.rpartition('/') return self._subfolders def render(self): """Renders the table using the template from the table options.""" breadcrumb_template = template.loader.get_template(self.template) extra_context = {"breadcrumb": self}
context = template.RequestContext(self.request, extra_context) return breadcrumb_template.render(context)
MSEMJEJME/Get-Dumped
renpy/display/im.py
Python
gpl-2.0
45,147
0.005759
# Copyright 2004-2012 Tom Rothamel <pytom@bishoujo.us> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, m...
# First try to grab the image out of the cache without locking it. if image in self.ca
che: ce = self.cache[image] # Now, grab the cache and try again. This deals with the case where the image # was already in the middle of preloading. if ce is None: self.lock.acquire() ce = self.cache.get(image, None) if c...
DBernardes/ProjetoECC
Eficiência_Quântica/Codigo/QE_reduceImgs_readArq.py
Python
mit
7,313
0.012585
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Criado em 19 de Novembro de 2016 @author: Denis Varise Bernardes & Eder Martioli Descricao: esta biblioteca possui as seguintes funcoes: mkDir_saveCombinedImages: pela chamada da funcao LeArquivoReturnLista retorna a lista de todas as imagens ad...
VetorImagens.append(imagem) os.chdir(chdir)
geraArquivo(VetorImagens, n) os.chdir(cwd) VetorImagens = [] n+=1 else: imagem = fits.getdata(images_dir + '\\' + lista[i]) VetorImagens.append(imagem) criaArquivo_listaImagensReduzidas() return def mkDi...
samdmarshall/xcparse
xcparse/Xcode/PBX/PBXLibraryReference.py
Python
bsd-3-clause
307
0.019544
import os from
.PBX_Base_Reference import * from ...Helpers import path_helper class PBXLibraryReference(PBX_Base_Reference): def __init__(self, lookup_func, dictionary, project, identifier): super(PBXLibraryReference, self).__init__(lookup_func, dictionary, project, identifie
r);
lgarren/spack
var/spack/repos/builtin/packages/fastqvalidator/package.py
Python
lgpl-2.1
2,230
0.000897
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. #
LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 PURP...
iscarecrow/sb
server/wsgi.py
Python
mit
387
0.002584
""" WSGI config for server project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployme
nt/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") from django.core.wsgi import get_wsgi_application application = get
_wsgi_application()
Conedy/Conedy
testing/createNetwork/expected/sum_lattice.py
Python
gpl-2.0
68
0
00000 0 output/lattice.
py.err 32074 1 output/lattice.py.
out
anthonysandrin/kafka-utils
tests/kafka_cluster_manager/partition_count_balancer_test.py
Python
apache-2.0
26,033
0
# -*- coding: utf-8 -*- # Copyright 2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
((u'T1', 1), ['0', '2']), ((u'T3', 1), ['0']), ((u'T3', 0), ['0']), ((u'T2', 0), ['0', '5']), ] ) brokers = { '0': mock.MagicMock(), '2': mock.MagicMock(), '5': mock.MagicMock(), } ...
e_cluster_topology(assignment, brokers) cb = create_balancer(ct) # Re-balance brokers cb._rebalance_groups_partition_cnt() # Verify all replication-groups have same partition-count assert len(ct.rgs['rg1'].partitions) == len(ct.rgs['rg2'].partitions) assert len(ct.rgs['...
annarev/tensorflow
tensorflow/python/ops/numpy_ops/integration_test/benchmarks/micro_benchmarks.py
Python
apache-2.0
5,557
0.007558
# Copyright 2020 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...
rom tensorflow.python.ops import n
umpy_ops as tfnp # pylint: disable=g-direct-tensorflow-import from tensorflow.python.ops.numpy_ops.integration_test.benchmarks import numpy_mlp from tensorflow.python.ops.numpy_ops.integration_test.benchmarks import tf_numpy_mlp FLAGS = flags.FLAGS flags.DEFINE_integer('repeat', 100, '#Measurements per benchmark.')...