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
mseroczynski/platformio
tests/commands/test_lib.py
Python
mit
2,036
0
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from os import listdir from os.path import isdir, isfile, join import re from platformio.commands.lib import cli from platformio import util def validate_libfold
er(): libs_path = util.get_lib_dir() installed_libs = listdir(libs_path) for lib in in
stalled_libs: assert isdir(join(libs_path, lib)) assert isfile(join(libs_path, lib, ".library.json")) and isfile( join(libs_path, lib, "library.json")) def test_lib_search(clirunner, validate_cliresult): result = clirunner.invoke(cli, ["search", "DHT22"]) validate_cliresult(result)...
DinoTools/dionaea
modules/python/dionaea/__init__.py
Python
gpl-2.0
6,176
0.001457
# This file is part of the dionaea honeypot # # SPDX-FileCopyrightText: 2009 Markus Koetter # SPDX-FileCopyrightText: 2016-2020 PhiBo (DinoTools) # # SPDX-License-Identifier: GPL-2.0-or-later import glob import logging import pkgutil import traceback from threading import Event, Thread from typing import Callable, Opt...
self.delay is None: self.delay = self.interval self.repeat = repeat self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self._timer: Optional[SubTimer] = None def start(self) -> None: """Start the Timer""" self...
args=self.args, kwargs=self.kwargs, ) self._timer.start() def cancel(self) -> None: """Cancel the Timer""" if self._timer: self._timer.cancel() def reset(self) -> None: """Restart the Timer""" self.cancel() self.start() ...
njsmith/partiwm
xpra/scripts/main.py
Python
gpl-2.0
12,235
0.002452
# This file is part of Parti. # Copyright (C) 2008 Nathaniel Smith <njs@pobox.com> # Parti is released under the terms of the GNU GPL v2, or, at your option, any # later version. See the file COPYING for details. import gobject import sys import os import socket import time from optparse import OptionParser import log...
start_str = "\t%prog start DISPLAY\n" list_str = "\t%prog list\n" upgrade_str = "\t%prog upgrade DISPLAY" note_str = "" else: start_str = "" list_str = "" upgrade_str = "" note_str = "(This xpra install does not support starting local servers.)" parser =...
_str, "\t%prog attach [DISPLAY]\n", "\t%prog stop [DISPLAY]\n", list_str, upgrade_str, note_str])) if XPRA_LOCA...
pcingola/schemas
tools/sphinx/avpr2rest.py
Python
apache-2.0
5,874
0.016513
import sys import json import os import re import argparse def get_file_locations(): parser = argparse.ArgumentParser() parser.add_argument('input', help='Input AVPR filename(s)', nargs='+') parser.add_argument('output', help='Output directory') args = parser.parse_args() return (args.input, args.output) d...
rs = message_def['errors'] output += " .. function:: %s(%s)\n\n" % (message_name, ', '.join(param_names)) for param in request: output += " :param %s: %s: %s\n" % (param['name'], param['type'], param['doc'])...
output += " :throws: %s\n\n" % ', '.join(errors) output += cleanup_doc(doc) output += "\n\n" for item in data['types']: output += '.. avro:%s:: %s\n\n' % (item['type'], item['name']) if item['type'] == 'record': for field in item['fields']: output += ' :field %s:\n...
Gazing/Frawt
django/frawt/api/urls.py
Python
mit
253
0.003953
from django.conf.urls import url from . import views urlpatterns = [
url(r'^$', views.index, name='api_index'), url(r'^time$', views.get_server_time, name='api_time'), url(r'^rooms/available', views.find_available, name='api_a
vailable'), ]
TrentFranks/ssNMR-Topspin-Python
LoadExp.py
Python
mit
1,871
0.02031
""" Load appropriate Pulse Program and acquisition parameters Arguments: -1D: load nD experiment as a 1D -2D: load nD experiment as a 2D (unless 1D experiment) -3D: load nD experiment as a 3D (unless 1D, or 2D then highest) -CC, hCC: load a 2D CC experiment (default to DARR) More to come when it starts working W.T...
tton2"]) == 1 # Variables to track merged elements Hhp, Chp, Nhp, HDec, hC, hN, NCa, NCo, CH, hhC, Nh, CX = 0,0,0,0,0,0,0,0,0,0,0,0 MAS, Phases = 0,0 ######################## # Read in preferences # ######################## i=2 if len(cmds) <= 2 : help() if len(cmds) >= 2 : for cmd in cmds[1:]: if cmd.find(...
nD=1 if cmd.find('-2D') >=0 or cmd.find('-2d') >=0: nD=2 if cmd.find('-3D') >=0 or cmd.find('-3d') >=0: nD=3 if cmd.find('-ex') >=0 or cmd.find('-EXPNO') >=0 or cmd.find('-EX') >=0 : expno=int(cmds[i]) SkipFileDialog=1 if cmd.find('-q') >=0 or cmd.find('-Q') >=0 or cmd.find('-qt') >=0 or cmd.find('-...
Johnzero/OE7
openerp/addons-fg/fg_account/report/period_check.py
Python
agpl-3.0
6,202
0.030795
# -*- coding: utf-8 -*- import tools from osv import fields, osv class reconcile_item(osv.osv_memory): _name = "fg_account.reconcile.item" _columns = { 'ref_doc':fields.reference('单据', selection=[('fg_sale.order','销售订单'),('fg_account.bill','收款单')], size=128, readonly=True), ...
'res_id': record.id, 'target': 'new', 'context': context, } if record.ref_doc._table_name == 'fg_account.bill': r['res_id'] = record.id - 1000000000 return r def button_clear(self, cr, uid, ids, context=None): ...
elf.pool.get('fg_sale.order') #this should all be order. #check_record's id IS the id of order. order_obj.write(cr, uid, ids, {'clear':True}) return True def button_unclear(self, cr, uid, ids, context=None): order_obj = self.pool.get('fg_sale.order') #this should al...
iafan/zing
pootle/runner.py
Python
gpl-3.0
11,729
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle con
tributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os import sys from argparse import SUPPRESS, ArgumentPar...
qa #: Length for the generated :setting:`SECRET_KEY` KEY_LENGTH = 50 #: Default path for the settings file DEFAULT_SETTINGS_PATH = '~/.zing/zing.conf' #: Template that will be used to initialize settings from SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.template' # Python 2+3 support for input() if sys.ver...
jrocketfingers/sanic
sanic/testing.py
Python
mit
3,419
0.000585
import traceback from sanic.log import log HOST = '127.0.0.1' PORT = 42101 class SanicTestClient: def __init__(self, app): self.app = app async def _local_request(self, method, uri, cookies=None, *args, **kwargs): import aiohttp if uri.startswith(('http:', 'https:', 'ftp:', 'ftps://...
isteners['after_server_start'].pop() if exceptions: raise ValueError("Exception during request: {}".format(exceptions)) if gather_request: try:
request, response = results return request, response except: raise ValueError( "Request and response object expected, got ({})".format( results)) else: try: return results[-1] ex...
guschmue/tensorflow
tensorflow/python/ops/control_flow_grad.py
Python
apache-2.0
9,075
0.009477
# Copyright 2015 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...
context() # pylint: enable=protected-access if isinstance(op_ctxt, WhileContext): merge_grad = grad_ctxt.grad_state.switch_map.get(op) if merge_grad is not None: # This is the second time this Switch is visited. It comes from # the non-exit branch of the Switch, so update the
second input # to the Merge. # TODO(yuanbyu): Perform shape inference with this new input. if grad[1] is not None: # pylint: disable=protected-access control_flow_ops._AddNextAndBackEdge(merge_grad, grad[1]) # pylint: enable=protected-access return None, None elif gra...
SCUT16K/SmsSender
server/config/production_sample.py
Python
apache-2.0
272
0.003676
# coding: utf-8 from .default import Config c
lass ProductionConfig(Config): # Site domain SITE_DOMAI
N = "http://www.twtf.com" # Db config SQLALCHEMY_DATABASE_URI = "mysql+pymysql://dbuser:dbpass@localhost/databasename" # Sentry SENTRY_DSN = ''
smkr/pyclipse
plugins/org.python.pydev.jython/jysrc/pyedit_assign_params_to_attributes.py
Python
epl-1.0
3,468
0.012111
"""Assign Params to Attributes by Joel Hedlund <joel.hedlund at gmail.com>. PyDev script for generating python code that assigns method parameter values to attributes of self with the same name. Activates with 'a' by default. Edit global constants ACTIVATION_STRING and WAIT_FOR_ENTER if this does not suit your needs...
==========================================
======================================== if cmd == 'onCreateActions' or (DEBUG and cmd == 'onSave'): from org.python.pydev.editor.correctionassist import PythonCorrectionProcessor #@UnresolvedImport import assign_params_to_attributes_action as helper import assign_params_to_attributes_assist ...
gotthardp/rabbitmq-email
test/send.py
Python
mpl-2.0
327
0
#!/usr/bin/env python import smtplib from email.m
ime.text import MIMEText me = "me@example.com" you = "you@example.com" msg = MIMEText("Hello world!") msg['From'] = me msg['To'] = you msg['Subject'] = 'Gree
tings' s = smtplib.SMTP('localhost', 2525) s.login("guest", "guest") s.sendmail(me, [you], msg.as_string()) s.quit()
hjanime/VisTrails
vistrails/db/versions/v0_3_1/persistence/__init__.py
Python
bsd-3-clause
2,007
0.013453
############################################################################### ## ## Copyright (C) 2014-2015, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
HE POSSIBILITY OF SUCH DAMAGE." ## ###############
################################################################ from __future__ import division from vistrails.db.versions.v0_3_0.persistence import DAOList
lloy/Project
cdsagent/cdsagent/vdisk/disk.py
Python
apache-2.0
205
0
import logging LOG
= log
ging.getLogger(__name__) __author__ = 'Hardy.zheng' class DiskPoller(object): def __init__(self): pass def run(self): LOG.info('DiskPoller start...')
zhantyzgz/polaris
plugins/voicerss.py
Python
gpl-2.0
2,555
0.00274
from core.utils import * commands = [ ('/voicerss', ['language', 'text']) ] description = 'Generates an audio file using Voice RSS API.' shortcut = '/vr ' langs = [ 'af', 'aq', 'ar', 'hy', 'ca', 'zh', 'zh-cn', 'zh-tw', 'zh-yue', 'hr', 'cs', 'da', 'nl', 'en-au', 'en-uk', 'en-us', 'eo', 'fi',...
lang = 'en-us' text = input url = 'https://api.voicerss.org' params = { 'key': config.keys.voicerss, 'src': text, 'hl': lang, 'r': '2', 'c': 'ogg', 'f': '16khz_16bit_stereo' } jstr = requests.get(url, params=params)...
m, lang.errors.connection) voice = download(jstr.url, params=params) if voice: send_voice(m, voice) else: send_message(m, lang.errors.download) def inline(m): input = get_input(m) for v in langs: if first_word(input) == v: lang = v ...
amosnier/python_for_kids
extra_code/03_loopy_turtle_01.py
Python
gpl-3.0
862
0.006961
import turtle turtle.clearscreen() t = turtle.Turtle() #turtle.tracer(0, 0) t.fillcolor(0.9, 0.9, 0.6) t.begin_fill() for i in range(0, 5): t.forward(100) t.right(144) t.end_fill() t.up() t.ba
ckward(200) t.down() t.fillcolor(0.7, 0.95, 0.7) t.begin_fill() for i in range(0, 5): t.forward(100) t.left(72) t.end_fill() t.up() t.right(90) t.forward(200) t.down() t.fillcolor(0.7, 0.9, 0) t.begin_fill() for i in range(0, 6): t.forward(100) t.left(60) t.end_fill() t.up() t.left(90)...
r(0.95, 0, 0.5) t.begin_fill() for i in range(100, 0, -1): t.forward(i) t.left(60) t.end_fill() t.up() t.left(60) t.backward(300) t.down() t.fillcolor(0.80, 0, 0.7) t.begin_fill() for i in range(60, 120): t.forward(180 - i) t.left(i) t.end_fill() turtle.update()
andersbll/ipcv
ipcv/misc/donuts.py
Python
mit
1,393
0.000718
import numpy as np def donut(shape, radius, width, distribution='gaussian'): '''Generate a 2D Gaussian window of the given shape. width specifies the size of the Gaussian. radius specifies the distance to origo such that the window becomes a ring.''' if not distribution in ['gaussian', 'lognormal']: ...
us_max, width_min, width_ratio=1.0, distribution='gaussian'): ra
dii = np.linspace(0, radius_max, n_donuts) widths = [float(width_min)*width_ratio**i for i in range(n_donuts)] weights = [donut(shape, r, w, distribution) for (r, w) in zip(radii, widths)] weights = [w/np.sum(w) for w in weights] return weights
dylanseago/LeagueOfLadders
leagueofladders/apps/myleague/admin.py
Python
apache-2.0
489
0.002045
from django.contrib import admin from leagueofladders.apps.myleague.models import Leagu
e, Membership class MembershipInline(admin.TabularInline): model = Membership extra = 1 @admin.register(League) class LeagueAdmin(admin.ModelAdmin): fields = ('name', 'owner', 'is_public') inlines = [MembershipInline] list_display = ('name', 'owner', 'is_public', 'date_modified') list_filter...
['date_modified', 'is_public'] search_fields = ['name', 'owner__username']
julianwachholz/praw
tests/test_decorators.py
Python
gpl-3.0
311
0
from __future__ import print_function, unicode_literals import unittest from praw.decorators import restrict_access class DecoratorTest(unittest.
TestCase): def test_require_access_failure(self): self.assertRaises(TypeError, restrict_access, scope=None, oau
th_only=True)
MusculoskeletalAtlasProject/mapclient-src
mapclient/tools/ui_pluginmanagerdialog.py
Python
gpl-3.0
5,669
0.003528
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qt/pluginmanagerdialog.ui' # # Created: Wed Jan 28 16:54:28 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_PluginManagerDialog(ob...
loadButton.setToolTip(QtGui.QApplication.translate("PluginManagerDialog", "Reload the plugins from the current plugin directories", None, QtGui.QApplication.UnicodeUTF8)) self.reloadButton.setText(QtGui.QApplication.translate("PluginManagerDialog", "Reload", None, QtGui.QApplication.UnicodeUTF8)) self.a...
uginManagerDialog", "Advanced...", None, QtGui.QApplication.UnicodeUTF8)) from . import resources_rc
aslab/rct
higgs/branches/ros-groovy/higgs_gazebo_simulation/rqt_robot_plugins/rqt_pose_view/setup.py
Python
gpl-3.0
222
0
#!/usr/bin/env python from distutils.core import setup fr
om catkin_pkg.python_setup import generate_distutils_setup d = generate_distutil
s_setup( packages=['rqt_pose_view'], package_dir={'': 'src'} ) setup(**d)
ncliam/serverpos
openerp/addons/mail/tests/test_mail_features.py
Python
agpl-3.0
59,265
0.006109
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
many function field 'follower_ids'. We will test to perform writes using the many2many commands 0, 3, 4, 5 and 6. """ cr, uid, user_admin, part
ner_bert_id, group_pigs = self.cr, self.uid, self.user_admin, self.partner_bert_id, self.group_pigs # Data: create 'disturbing' values in mail.followers: same res_id, other res_model; same res_model, other res_id group_dummy_id = self.mail_group.create(cr, uid, {'name': 'Dummy group'}, {'ma...
vesellov/bitdust.devel
lib/fastjsonrpc/client.py
Python
agpl-3.0
12,736
0.000236
#!/usr/bin/env python """ Copyright 2012 Tadeas Moravec. 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 ...
Fires the finished's callback with data we've receive
d. @type reason: t.p.f.Failure @param reason: Failure, wrapping several potential reasons. It can wrap t.w.c.ResponseDone, in which case everything is OK. It can wrap t.w.h.PotentialDataLoss. Or it can wrap an Exception, in case of an error. @TODO inspect reason for fai...
iotile/coretools
iotilesensorgraph/test/test_datastream.py
Python
gpl-3.0
8,473
0.000354
"""Tests for DataStream objects.""" import pytest from iotile.core.exceptions import InternalError from iotile.sg import DataStream, DataStreamSelector def test_stream_type_parsing(): """Make sure we can parse each type of stream.""" # Make sure parsing stream type works stream = DataStream.FromString('...
DataStreamSelector.FromString(u'constant 1') assert stream.match_type == DataStream.ConstantType stream = DataStreamSelector.FromString('output 1') assert stream.match_type == DataStream.OutputType strea
m = DataStreamSelector.FromString(u'output 1') assert stream.match_type == DataStream.OutputType def test_stream_selector_id_parsing(): """Make sure we can parse stream ids.""" stream = DataStreamSelector.FromString('buffered 1') assert stream.match_id == 1 assert stream.match_spec == DataStreamS...
gwq5210/python_learn
decorator.py
Python
gpl-2.0
116
0.051724
#!/usr/bin/e
nv python # coding=utf-8 def now(): print '2015-9-10'; f = now; print now.__name__; print f.__name__;
lumened/battmonitor
api_charger.py
Python
gpl-2.0
2,610
0.02069
# This handles all interactions needed for interpreting and controlling the charger import time import api_adc, config import apigpio.api_gpio as api_gpio # Charger Control def init_control(): api_gpio.init_pin(27) api_gpio.off_pin(27) # Set line to low def deinit_control(): api_gpio.deinit_pin(27) d...
lt>2.3 and config.led_volt<2.8: config.led_state = config.state['charging'] elif config.led_volt>4.5 and config.led_volt<5.5: config.led_state = config.state['full'] # Madness # elif config.led_volt>5.5 : config.led_state = config.state['detected'] if write_to_file: f = open('/home/pi/touch-f...
ig.led_state==config.state['off']: f.write('U') elif config.led_state == config.state['charging']: f.write('C') else: f.write('P') f.close() return None # Battery State def update_battery(write_to_file=False): ''' This function inputs the battery voltage and updates t...
cactusbin/nyt
matplotlib/examples/pylab_examples/webapp_demo.py
Python
unlicense
1,713
0.001751
#!/usr/bin/env python # -*- noplot -*- """ This example shows how to use the agg backend directly to create images, which may be of use to web application developers who want full control over their code without using the pyplot interface to manage figures, figure closing etc. .. note:: It is not necessary to avo...
Agg from matplotlib.figure import Figur
e import numpy as np def make_fig(): """ Make a figure and save it to "webagg.png". """ fig = Figure() ax = fig.add_subplot(1, 1, 1) ax.plot([1, 2, 3], 'ro--', markersize=12, markerfacecolor='g') # make a translucent scatter collection x = np.random.rand(100) y = np.random.rand(...
pritha-srivastava/sm
drivers/LVHDoFCoESR.py
Python
lgpl-2.1
3,290
0.001216
#!/usr/bin/python # # Copyright (C) Citrix Systems Inc. # # 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 only. # # This program is distributed in the hope that it will be use...
'name': 'LVHD over FCoE', 'description': 'SR plugin which represents disks as VHDs on Logical \
Volumes within a Volume Group created on a FCoE LUN', 'vendor': 'Citrix Systems Inc', 'copyright': '(C) 2015 Citrix Systems Inc', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, 'configuration': CONFIGURATION } class LVHDoFCoESR(LVHDoHBASR.LVHDoHBASR): ...
GoogleCloudPlatform/buildpacks
builders/testdata/python/functions/conflicting_dependencies/main.py
Python
apache-2.0
926
0.00324
# 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, ...
License for the specific language governing permissions and # limitations under the License. # GCF Python 3.7 legacy worker has additional dependencies available by default # to user functions. This test ensures that those dependencies can be overriden # through a user's requirements.txt. import yarl def testF
unction(request): if yarl.__version__ != '1.4.2': return 'FAIL: got %s, want %s' % yarl.__version__, '1.4.2' return 'PASS'
tomvanderlee/youtube-podcaster
setup.py
Python
mit
660
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup file for youtube_podcaster. This file was generated with PyScaffold 2.4.2, a tool that easily puts up a scaffold for your new Python project. Learn more under: http://pyscaffold.readthedocs.org/ """ import sys from setuptools import setup def s...
.intersection(sys.argv) sphinx = ['sphinx'] if needs_sphinx else [] setup(setup_requires=['six', 'pyscaffold>=2.4rc1,<2.5a0'] + sphinx, tests_require=['pytest_cov', 'pytest'], use_pyscaffold=True) if __name__ == "__main__":
setup_package()
plotly/python-api
packages/python/plotly/plotly/validators/layout/annotation/_arrowcolor.py
Python
mit
479
0.002088
impo
rt _plotly_utils.basevalidators class ArrowcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="arrowcolor", parent_name="layout.annotation", **kwargs ): super(ArrowcolorValidator, self).__init__( plotly_name=plotly_name, parent_...
"), role=kwargs.pop("role", "style"), **kwargs )
yaricom/brainhash
src/experiment_cA3_1_dt_th_al_ah.py
Python
gpl-3.0
1,954
0.011771
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ The experiment with 10 Hz/5Hz, wisp, attention, 70, cA 3, delta, theta, alpha low, alpha high, batch size = 1 and balanced data set @author: yaric """ import experiment as ex import config from time import time experiment_name = 'cA_3_1_dt-th-a_l-a_h' # will be use...
= time() # # Run analyzer # """ print("\nStart analysis with parameters:\n%s\n" % analyzer_config) print("Start analysis for signal records: %s" % signal_ids) ex.runEEGAnalyzerWithIDs(ids_list=signal_ids, experiment_name=experiment_name, a_config=analyzer_config) pri...
experiment_name=experiment_name, a_config=analyzer_config) """ # # Run classifiers # signal_dir = "%s/%s" % (config.analyzer_out_dir, experiment_name) noise_dir = "%s/%s/%s" % (config.analyzer_out_dir, experiment_name, noise_ids[0]) out_suffix = experiment_name pr...
Jumpscale/jumpscale6_core
apps/agentcontroller/jumpscripts/core/monitoring_infogathering/info_gather_disks.py
Python
bsd-2-clause
566
0.008834
from JumpScale import j
descr = """ Checks disks' status """ organization = "jumpscale" name = 'check_
disks' author = "zains@codescalers.com" license = "bsd" version = "1.0" category = "system.disks" async = True queue = 'process' roles = [] enable = True period=0 log=False def action(): import JumpScale.lib.diskmanager result = dict() disks = j.system.platform.diskmanager.partitionsFind(mounted=True, pr...
dhuppenkothen/clarsach
clarsach/respond.py
Python
gpl-3.0
10,929
0.001738
# Contains functionality for responses import numpy as np import astropy.io.fits as fits __all__ = ["RMF", "ARF"] class RMF(object): def __init__(self, filename): self._load_rmf(filename) pass def _load_rmf(self, filename): """ Load an RMF from a FITS file. Paramet...
e *first channel* that each channel for each channel set * `n_chan` stores the number of channels in each channel set As a result, for a given energy bin i, we need to look up the number of channel sets in `n_grp` for that energy bin. We then need to loop...
. For each channel set, we look up the first channel into which flux will be distributed as well as the number of channels in the group. We then need to also loop over the these channels and actually use the corresponding elements in the redistribution matrix to redistribute the ...
cuemacro/chartpy
chartpy_examples/xkcd_example.py
Python
apache-2.0
2,081
0.004805
__author__ = 'saeedamen' # Saeed Amen # # Copyright 2016 Cuemacro # # 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 ...
== 0: import pandas, numpy dt = pandas.date_range(start="1 Jan 1950", end="1 Apr 2017", freq='M') data = numpy.arange(len(dt)) df = pandas.DataFrame(index=dt, data=data, columns=['Importance']) # set the style of the plot style = Style(title="Importance of puns", source="@saeedamenfx", xkcd=T...
, chart_type='line', style=style, engine='matplotlib') chart.plot()
klebercode/klebercode
klebercode/blog/migrations/0001_initial.py
Python
gpl-2.0
6,850
0.007737
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Entry' db.create_table(u'blog_entry', ( (u'id...
: 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u...
rmission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), ...
googleapis/python-aiplatform
google/cloud/aiplatform_v1beta1/types/tensorboard_service.py
Python
apache-2.0
42,035
0.000619
# -*- 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...
eriesDataResponse", "ReadTensorbo
ardTimeSeriesDataRequest", "ReadTensorboardTimeSeriesDataResponse", "WriteTensorboardExperimentDataRequest", "WriteTensorboardExperimentDataResponse", "WriteTensorboardRunDataRequest", "WriteTensorboardRunDataResponse", "ExportTensorboardTimeSeriesDataRequest", "E...
explosion/srsly
srsly/tests/test_pickle_api.py
Python
mit
870
0.004598
from .._pickle_api import pickle_dumps, pickle_loads def test_pickle_dumps(): data = {"hello": "world", "test": 123} expected = [ b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.", b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8...
0\x05\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.", ] msg = pickle_dumps(data) assert msg in expected def test_pickle_loads(): msg = pickle_dumps({"hello": "world", "test": 123}) data = pickle_loads(msg) assert len(data) == 2 assert data[...
"world" assert data["test"] == 123
sserrot/champion_relationships
venv/Lib/site-packages/PIL/PSDraw.py
Python
mit
6,735
0.000148
# # The Python Imaging Library # $Id$ # # simple postscript graphics interface # # History: # 1996-04-20 fl Created # 1999-01-10 fl Added gsave/grestore to image method # 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge) # # Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved. # ...
D ne { def } {
pop pop } ifelse } forall /Encoding exch def dup /FontName exch def currentdict end definefont pop } bind def /F { findfont exch scalefont dup setfont [ exch /setfont cvx ] cvx bind def } bind def """ # # VDI.PS -- Postscript driver for VDI meta commands # # History: # 94-01...
karst87/ml
01_openlibs/tensorflow/02_tfgirls/TensorFlow-and-DeepLearning-Tutorial-master/Season1/1-3/run.py
Python
mit
3,407
0.026719
# encoding: utf-8 # 为了 Python3 的兼容,如果你用的 Python2.7 from __future__ import print_function, division import tensorflow as tf print('Loaded TF version', tf.__version__, '\n\n') # Tensor 在数学中是“张量” # 标量,矢量/向量,张量 # 简单地理解 # 标量表示值 # 矢量表示位置(空间中的一个点) # 张量表示整个空间 # 一维数组是矢量 # 多维数组是张量, 矩阵也是张量 # 4个重要的类型 # @Variable 计算图谱中的变量 # ...
ensor) # 省内存?placeholder才是王道 # def use_placeholder():
graph = tf.Graph() with graph.as_default(): value1 = tf.placeholder(dtype=tf.float64) value2 = tf.Variable([3, 4], dtype=tf.float64) mul = value1 * value2 with tf.Session(graph=graph) as mySess: tf.initialize_all_variables().run() # 我们想象一下这个数据是从远程加载进来的 # 文件,网络 # 假装是 10 GB value = load_from_remote() ...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/build/android/pylib/base/test_collection.py
Python
mit
2,343
0.011524
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import threading class TestCollection(object): """A threadsafe collection of tests. Args: tests: List of tests to put in the collection. """ d...
s += 1 def test_completed(self): """Indicate that a test has been fully handled.""" with self._lock: self._tests_in_progress -= 1 if self._tests_in_progress == 0: # All tests have been handled, signal all waiting threads. self._item_available_or_all_done.set() def __iter__(s
elf): """Iterate through tests in the collection until all have been handled.""" while True: r = self._pop() if r is None: break yield r def __len__(self): """Return the number of tests currently in the collection.""" return len(self._tests) def test_names(self): """R...
addition-it-solutions/project-all
openerp/addons/base/tests/test_osv.py
Python
agpl-3.0
4,654
0.004297
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 OpenERP S.A. http://www.openerp.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GN...
uct_product", "res_user", "user_id", "id", "user_id"), implicit=False, outer=True) # outer join self.assertEquals(query.get_sql()[0].strip()
, """"product_product" LEFT JOIN "res_user" as "product_product__user_id" ON ("product_product"."user_id" = "product_product__user_id"."id"),"product_template" JOIN "product_category" as "product_template__categ_id" ON ("product_template"."categ_id" = "product_template__categ_id"."id") """.strip()) ...
Tankobot/mechalature
core/identify.py
Python
gpl-3.0
735
0
from core import MechalatureError import shelve __all__ = [ 'MechalatureEvent', 'get_info' ] word_bank = shelve.open('bin/word_bank') class MechalatureEvent: def __init__(self, name: str): self.name = name self._tags = set() def tag(self, terms: set): self._tags += terms ...
s TagError(MechalatureError): def __init__(self, msg: str, tags: tuple): self.tags = tags super().__init__(msg) possible_tags = ( 'noun', 'adjective', 'verb', 'plural', 'singular' ) def get_info(event: MechalatureEvent): try: tags = word_bank[eve
nt.name] except KeyError: tags = () # TODO
googleapis/python-os-config
google/cloud/osconfig_v1/types/__init__.py
Python
apache-2.0
4,373
0
# -*- 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...
est", "DeletePatchDeploymentRequest", "GetPatchDeploymentRequest", "ListPatchDeploymentsRequest", "ListPatchDeploymentsResponse", "MonthlySchedule", "OneTimeSchedule", "PatchDeployment", "PausePatchDeploymentRequest", "RecurringSchedule", "ResumePatchDeploymentRequest", "Upda...
PatchDeploymentRequest", "WeekDayOfMonth", "WeeklySchedule", "AptSettings", "CancelPatchJobRequest", "ExecStep", "ExecStepConfig", "ExecutePatchJobRequest", "GcsObject", "GetPatchJobRequest", "GooSettings", "Instance", "ListPatchJobInstanceDetailsRequest", "ListPatchJ...
LeotisBuchanan/olpc-datavisualization-
models.py
Python
gpl-2.0
341
0.005865
from olpc import db class User(d
b.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) email = db.Column(db.String(120), unique=True) def __init__(self, name, email): self.name = name self.email = email def __repr__(self): return
'<Name %r>' % self.name
alex8866/cinder
cinder/tests/zonemanager/test_cisco_fc_zone_client_cli.py
Python
apache-2.0
9,495
0
# (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
info') def test_get_active_zone_set(self, get_switch_info_mock): cmd_list = [ZoneConstant.GET_ACTIVE_ZONE_CFG, self.fabric_vsan, ' | no-more'] get_switch_info_mock.return_value = cfgactv active_zoneset_returned = self.get_active_zone_set() get_switch_info_mock.ass...
scoFCZoneClientCLI, '_run_ssh') def test_get_active_zone_set_ssh_error(self, run_ssh_mock): run_ssh_mock.side_effect = processutils.ProcessExecutionError self.assertRaises(exception.CiscoZoningCliException, self.get_active_zone_set) @patch.object(CiscoFCZoneClientCLI, ...
humw/algorithms_in_python
merge_sort/merge_sort.py
Python
gpl-2.0
667
0
def merge(a, b): """ inuput: two sorted lists output: a merged sorted list for example: merge([2,3], [1,4]) --> [1,2,3,4] """ merged = [] w
hile a or b: if a and b: if a[0] < b[0]: merged.append(a.pop(0)) else: merged.append(b.pop(0)) else: merged += a + b break return merged def merge_sort(one_list): # divide if len(one_list) == 1: return ...
middle = int(len(one_list)/2) left = merge_sort(one_list[:middle]) right = merge_sort(one_list[middle:]) # conquer return merge(left, right)
ocefpaf/cartopy
lib/cartopy/tests/conftest.py
Python
lgpl-3.0
1,159
0
# (C) British Crown Copyright 2020, Met Office # # This file is part of cartopy. # # cartopy 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 la...
of the GNU Lesser General Public License # along with cartopy. If not, see <https://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) def pytest_configure(config): # Register additional markers. config.addinivalue_line('markers',
'natural_earth: mark tests that use Natural Earth ' 'data, and the network, if not cached.') config.addinivalue_line('markers', 'network: mark tests that use the network.')
normalnorway/normal.no
django/core/views.py
Python
gpl-3.0
733
0.0191
""" Global views -- i.e., don't tied to any app/model. """ from core.shortcuts import render_to @render_to ('index.html') def index (request): return {} ## /newsletter/ from utils.mailchimp import MailChimp from django.conf import settings #mailchimp = None #if settings.MAILCHIMP_API_KEY: # mailchimp = M...
{'cam
paigns': mailchimp.get_campaigns if mailchimp else None}
colour-science/colour
colour/utilities/tests/test_data_structures.py
Python
bsd-3-clause
17,079
0.000586
"""Defines the unit tests for the :mod:`colour.utilities.data_structures` module.""" import numpy as np import operator import pickle import unittest from colour.utilities import ( Structure, Lookup, CaseInsensitiveMapping, LazyCaseInsensitiveMapping, Node, ) __author__ = "Colour Developers" __co...
) self.
assertListEqual( ["A", "B"], sorted(lookup.keys_from_value(np.array([0, 1, 2]))) ) def test_first_key_from_value(self): """ Test :meth:`colour.utilities.data_structures.\ Lookup.first_key_from_value` method. """ lookup = Lookup(first_name="John", last_name="Doe"...
joequant/pyswagger
pyswagger/tests/v2_0/test_circular.py
Python
mit
3,163
0.002845
from pyswagger import SwaggerApp, utils, primitives, errs from ..utils import get_test_data_folder from ...scanner import CycleDetector from ...scan import Scanner import unittest import os import six class CircularRefTestCase(unittest.TestCase): """ test for circular reference guard """ def test_path_item_...
th_item') ) def _pf(s): return six.moves.urllib.parse.urlunparse(( 'file', '', folder, '', '', s)) app = SwaggerApp.create(folder) s = Scanner(app)
c = CycleDetector() s.scan(root=app.raw, route=[c]) self.assertEqual(sorted(c.cycles['path_item']), sorted([[ _pf('/paths/~1p1'), _pf('/paths/~1p2'), _pf('/paths/~1p3'), _pf('/paths/~1p4'), _pf('/paths/~1p1') ]])) def test_sc...
jenshnielsen/hemelb
Tools/hemeTools/parsers/geometry/__init__.py
Python
lgpl-3.0
1,408
0.035511
# # Copyright (C) University College London, 2007-2012, all rights reserved. # # This file is part of HemeLB and is provided to you under the terms of # the GNU LGPL. Please see LICENSE in the top level directory for full # details. # """Regarding indices, a few conventions: 1) Broadly there are two types of index...
hese are just integers and have the suffix 'Ijk'. 2) Indices can refer to a number of things and have additional naming: - b : Index of a block - sg : Index of a site in the whole domain (site global) - sl : Index of a site in the block (site local) """ import numpy as np GeometryMagicNumber = 0x676d7904 ...
ns = np.array( [[-1,-1,-1], [-1,-1, 0], [-1,-1,+1], [-1, 0,-1], [-1 , 0, 0], [-1, 0,+1], [-1,+1,-1], [-1,+1, 0], [-1,+1,+1], [ 0,-1,-1], [ 0,-1, 0], [ 0,-1,+1], [ 0, 0,-1], #[ 0, 0, 0], <= the null displacement is not part of the Moore N'hood [ 0...
ayoubg/gem5-graphics
gem5-gpu/tests/quick/se_gpu/20.bh/test.py
Python
bsd-3-clause
1,653
0
# Copyright (c) 2006 The Regents of The University of Michigan # 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 ...
ributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the #
documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ...
googlefonts/fontbakery
Lib/fontbakery/sphinx_extensions/profile.py
Python
apache-2.0
24,923
0.003491
from typing import Any, List, Tuple, Dict #cast from sphinx.application import Sphinx # from sphinx.ext.autodoc import Documenter from sphinx.ext.autodoc import ModuleLevelDocumenter from sphinx.pycode import ModuleAnalyzer, PycodeError #from sphinx.domains.python import PythonDomain from sphinx.locale import __ from ...
# dropped and we drop out of signature building. (RAISED here in `_handle_signature` # The ValueError when the regex doesn't match...) # seems like the slash (/) Is killing most of the header! # Otherwise the ids display fine, the dots are fine. # Also, in any case of name change, th...
cument and also genindex.html anchor works so far (with 7 instead of /) # res = super().format_name() if self.objtype == 'fontbakerycheck': # A bit hackish, splitting somwhere else by ::: to retrieve the checkid # we can get the source file first line number of self.objec...
tktrungna/leetcode
Python/dungeon-game.py
Python
mit
2,261
0.006192
""" QUESTION: The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. The knigh...
princess. For example, given the dungeon below, the initial health of the knight must be at
least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. -2 (K) -3 3 -5 -10 1 10 30 -5 (P) Notes: The knight's health has no upper bound. Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. ANSWER:...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_10_01/aio/operations/_security_rules_operations.py
Python
mit
22,275
0.004893
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
on_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_argument
s, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=sel...
spcui/virt-test
virttest/utils_misc.py
Python
gpl-2.0
59,810
0.000686
""" Virtualization test utility functions. :copyright: 2008-2009 Red Hat Inc. """ import time import string import random import socket import os import signal import re import logging import commands import fcntl import sys import inspect import tarfile import shutil import getpass from autotest.client import utils,...
, let's close the log files opened in old directories close_log_file(filename) # Then, let's open the new file try: os.makedirs(os.path.dirname(path)) except OSError: pass _open_log_files[path] = open(path, "w") timestr = time.strftime("%Y-%m-%d %H:%M:...
timestr, line)) _open_log_files[path].flush() def set_log_file_dir(directory): """ Set the base directory for log files created by log_line(). :param dir: Directory for log files. """ global _log_file_dir _log_file_dir = directory def close_log_file(filename): global _open_log_files...
grengojbo/st2
st2client/st2client/client.py
Python
apache-2.0
5,863
0.003752
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
IONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging from st2client import models from st2client.models.core import ResourceManager from st2client.models.core import ActionAliasResourceManager from ...
lt values for the options not explicitly specified by the user DEFAULT_API_PORT = 9101 DEFAULT_AUTH_PORT = 9100 DEFAULT_BASE_URL = 'http://localhost' DEFAULT_API_VERSION = 'v1' class Client(object): def __init__(self, base_url=None, auth_url=None, api_url=None, api_version=None, cacert=None, deb...
aroth-arsoft/arsoft-python
python3/arsoft/ldap/slapd/action_module.py
Python
gpl-3.0
2,292
0.004799
#!/usr/bin/python # -*- coding: utf-8 -*- # kate: space-indent on; indent-width 4; mixedindent off; indent-mode python; import argparse import string import ldap import ldap.modlist as modlist from action_base import * class action_module(action_base): def __init__(self, app, args): action_base.__init__(...
f_not_available=False) ret = self._list() else: self._select_modulelist(add_modulelist_if_not_available=True) mod_attrs = [] if self._add is not None: for mod in self._add: if mod not in self._modules.values(): ...
in self._remove: found = False for (modidx, modname) in self._modules.items(): if modname == mod: found = True mod_attrs.append( (ldap.MOD_DELETE, 'olcModuleLoad', '{' + str(modidx) + '}' + mod) ) ...
adini121/oneanddone
oneanddone/users/urls.py
Python
mpl-2.0
1,193
0.006706
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.conf.urls import patterns, url from oneanddone.users import views urlpatterns = patterns('', url(r'^lo...
]+)
/$', views.UserDetailAPI.as_view(), name='api-user-detail'), )
Mariaanisimova/pythonintask
BITs/2014/KOSTAREV_A_I/task_4_13.py
Python
apache-2.0
1,201
0.024691
#Задача №4 , Вариант 13 #Напишите программу, которая выводит имя, под которым скрывается Жан Батист Поклен. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный м
омент (или момент смерти). #Костарев А. И. #14.03.16 print ("Жан Батист Поклен более известен, как французский комедиограф, актер, театральный деятель, реформатор сценического искусства Жан Батист Мольер.") MR= "Париж, Франция" GR= 1622 V= 1673-GR OI= "французский комедиограф XVII века" print ('Место Рожден...
('Возраст:' , V) print ('Область интересов: ' + OI) input ("Нажмите Enter для выхода.")
sauli6692/ibc-server
rte/serializers/route.py
Python
mit
337
0
from
rest_framework import serializers from ..models import Route class RouteSerializer(serializers.ModelSerializer): class Meta: model = Route fields = ( 'pk', 'name', 'description', 'direction_main', 'direction_extra', 'zone_ma...
lattrelr7/cse881-pcap
ip_structs.py
Python
mit
4,002
0.006497
from ctypes import * # Ether types that we handle # These are types that will be found in the frame header ET_ARP = 0x0806 ET_REV_ARP = 0x8035 ET_IPv4 = 0x0800 ET_IPv6 = 0x86DD # IP types that we handle # These types are found in the ipv4 header IPT_ICMP = 0x01 IPT_TCP = 0x06 IPT_UDP = 0x11 IPT_IPv6 = 0...
ields_ = [("type", c_uint8), ("code", c_uint8),
("checksum", c_uint16), ("rest_of_header", c_uint32)] class udp_header_t(BigEndianStructure): _pack_ = 1 _fields_ = [("src_port", c_uint16), ("dst_port", c_uint16), ("length", c_uint16), ("checksum", c_uint16)] class tcp_h...
codenginebd/django-paypal-driver
paypal/views.py
Python
gpl-2.0
7,535
0.01075
# -*- coding: utf-8 -*- from decimal import Decimal, ROUND_UP from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from django.conf import settings from django.shortcuts...
return HttpResponseRedirect(redirect_url) return render_to_response(template, {'curre
ncy': currency, 'return_url': return_url, 'cancel_url': cancel_url, 'error_url' : error_url, }, context_instance = RequestContext(request)) def docheckout(request, error_url, success_url, templa...
amitgroup/parts-net
scripts/cifar/train_and_test_cifar.py
Python
bsd-3-clause
1,777
0.006753
from __future__ import division, print_function, absolute_import import amitgroup as ag import pnet import pnet.cifar import numpy as np ag.set_verbose(True) def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('parts',metavar='<parts file>', type=argp...
tionLayer(C=None, settings=dict(standardize=True)), ] net = pnet.PartsNet(layers) limit = None error_rate, conf_mat = pnet.cifar.train_and_test(net, samples_per_class=None, seed=0, limit=limit) ...
np.set_printoptions(precision=2, suppress=True) print('Confusion matrix:') norm_conf = conf_mat / np.apply_over_axes(np.sum, conf_mat, [1]) print(norm_conf) print('Column sums') print(norm_conf.sum(0)) from vzlog.default import vz vz.output(net) if pnet.parallel.main(__name__): main(...
bengranett/syncat
syncat/methods/gmm.py
Python
mit
6,003
0.002999
""" synrcat gaussian mixture model """ import sys import os import numpy as np import logging from collections import OrderedDict from astropy.table import Table from pypeline import pype, add_param, depends_on from syn import Syn from syncat.errors import NoPoints import syncat.misc as misc import syncat.fileio a...
to generate random catalogue by sampling from a gaussian mixture model. Parameters ---------- mask : minimask.Mask instance mask describing survey geometry to sample fr
om. If None, sample from full-sky. cat_model : str path to file with catalogue model to load hints_file : str path to file with hints about parameter distributions """ def __init__(self, config={}, mask=None, **kwargs): """ """ self._parse_config(config, **kwargs) ...
LT12/LTPsi
basis/b631Gs.py
Python
gpl-2.0
2,590
0.018533
basis_set = \ { "H": [ [ "S", [ [ 18.731137, 0.0334946 ], [ 2.8253937, 0.23472695 ], [ 0.6401217, ...
6717, 0.0018311 ], [ 825.23495,
0.0139501 ], [ 188.04696, 0.0684451 ], [ 52.9645, 0.2327143 ], [ 16.89757, 0.470193...
HuuHoangNguyen/Python_learning
Tuples.py
Python
mit
3,657
0.004375
#!/usr/bin/python # The list are enclosed in brackets ([]) and their element # and size can be changed, while tuples are enclosed in parenthese # ( () ) and cannot be updated. The Tuples can be thought of as # read-only of list aTuple = ( 'abcd', 786, 2.23, 'John', 70.2) bTuple = ( 123, 'Vien') print aTuple ...
ple print val_list print "============================
======================" tuple1 = ('physics', 'schematic', 1997, 2000) tuple2 = (1,2, 3, 4, 5, 6, 7) print "tuple1[0]: ", tuple1[0] print "tuple2[1:5]: ", tuple2[1:5] print "==================================================" print "Updating Tuples" print "Tuples are immutable which means you can not update or change t...
diogocs1/comps
web/addons/hw_scanner/__init__.py
Python
apache-2.0
1,075
0.002791
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
e implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public Lic
ense # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import controllers # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
moonboy13/brew-journal
brew_journal/recipies/tests.py
Python
apache-2.0
21,233
0.003909
import json from datetime import datetime from django.test import TestCase, Client from authentication.models import Account from recipies.models import Recipe, RecipeSteps from recipies.serializers import RecipeSerializer, RecipeStepsSerializer class Utility(TestCase): """Utility class para testing""" @s...
checkElement(test_instance, model[i], data[i]) @staticmethod def checkDictModel(test_instance, model, data): """Helper function. Check a model dictionary against a data dictionary key by key""" for key in model.keys(): Utility.checkElement(test_instance, model.get(key), data.__dict_...
attached to the Recipe model""" def setUp(self): self.recipe_data = dict( recipe_name="Test Recipe", recipe_style="Kolsch", recipe_notes="This is my first test recipe submited from a unit test.", last_brew_date=datetime.now() ) self.malts_data...
google/llvm-propeller
lldb/test/API/functionalities/target-new-solib-notifications/TestModuleLoadedNotifys.py
Python
apache-2.0
4,739
0.004009
""" Test how many times newly loaded binaries are notified; they should be delivered in batches instead of one-by-one. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ModuleLoadedNotifysTest...
s_removed += solib_count if self.TraceOn(): # print all of the binaries that have been removed removed_files = [] i = 0 while i < solib_count: module = lldb.SBTarget.GetModuleA...
i = i + 1 print("Unloaded files: %s" % (', '.join(removed_files))) # This is testing that we get back a small number of events with the loaded # binaries in batches. Check that we got back more than 1 solib per event. # In practic...
FreddieShoreditch/image_folder_organiser
venv/lib/python2.7/site-packages/PIL/TiffTags.py
Python
mit
9,273
0.000324
# # The Python Imaging Library. # $Id$ # # TIFF tags # # This module provides clear-text names for various well-known # TIFF tags. the TIFF codec works just fine without it. # # Copyright (c) Secret Labs AB 1999. # # See the README file for information on usage and redistribution. #
## # This module provides constants and clear-text names for various # well-known TIFF tags. ## from collections import namedtuple class TagInfo(namedtuple("_TagInfo", "value name type length enum")): __slots__ = [] def __new__(cls, value=None, name="unknown", type=4, length=0, enum=None): return su...
num(self, value): return self.enum.get(value, value) ## # Map tag numbers to tag info. # # id: (Name, Type, Length, enum_values) # TAGS_V2 = { 254: ("NewSubfileType", 4, 1), 255: ("SubfileType", 3, 1), 256: ("ImageWidth", 4, 1), 257: ("ImageLength", 4, 1), 258: ("BitsPerSample", 3, 0), ...
fgaudin/aemanager
notification/migrations/0002_populate_users.py
Python
agpl-3.0
4,216
0.00759
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): for user in orm['auth.user'].objects.all(): notification = orm.Notification() notification.user = user ...
[], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'notification.notification': { 'Meta': {'object_name': 'Notification'}, 'i...
', [], {'primary_key': 'True'}), 'notify_bug_comments': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'notify_invoices_to_send': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'notify_late_invoices': ('django.db.models.fields.BooleanField', []...
shiblon/pytour
3/tutorials/while_loops.py
Python
apache-2.0
1,756
0.008542
# vim:tw=50 """"While" Loops Recursion is powerful, but not always convenient or efficient for processing sequences. That's why Python has **loops**. A _loop_ is just what it sounds like: you do something, then you go round and do it again, like a track: you run around, then you run around again. Loops let you do ...
he indented block if its condition is |True| (nonzero). But, unlike |
if|, it *keeps on doing it* until the condition becomes |False| or it hits a |break| statement. Forever. The code window shows a while loop that prints every element of a list. There's another one that adds all of the elements. It does this without recursion. Check it out. Exercises - Look at |print_all|. Why does i...
markstoehr/phoneclassification
local/CExtractPatches_from_spec.py
Python
gpl-3.0
8,937
0.013651
from __future__ import division import numpy as np import argparse, itertools from scipy.io import wavfile from template_speech_rec import configParserWrapper from TestSVMBernoulli import get_bernoulli_templates from scipy.ndimage.filters import maximum_filter from amitgroup.stats import bernoullimm import matplotlib.p...
d[i].spines['left'].set_color('red') grid[i].spines['right'].set_color('red') for a in grid[i].axis.values():
a.toggle(all=False) plt.savefig('%s' % args.viz_spec_parts ,bbox_inches='tight') if __name__=="__main__": parser = argparse.ArgumentParser("""For each component and model we construct a positive and negative data subset and then tra...
Domatix/stock-logistics-workflow
stock_picking_whole_scrap/__manifest__.py
Python
agpl-3.0
641
0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { 'name': 'Stock Picking Whole Scrap', 'summary': 'Create whole scrap from a picking for move lines', 'version': '11.0.1.0.0', 'development_status': 'Beta', 'category': 'Warehouse', 'websi...
'wizards/stock_pic
king_whole_scrap.xml', 'views/stock_picking_views.xml', ], }
bstroebl/QGIS
python/plugins/sextante/parameters/ParameterVector.py
Python
gpl-2.0
4,042
0.003216
# -*- coding: utf-8 -*- """ *************************************************************************** ParameterVector.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***********************...
"|" + str(self.shapetype) + "|" + str(self.optional) def deserialize(self, s): tokens = s.split("|") return ParameterVector(tokens[0], tokens[1], int(tokens[2]), str(True)
== tokens[3]) def getAsScriptCode(self): return "##" + self.name + "=vector"
hayderimran7/tempest
tempest/api/compute/servers/test_virtual_interfaces_negative.py
Python
apache-2.0
1,691
0
# Copyright 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 requ...
irtualInterfacesNegativeTestJSON, cls).setup_credentials() @classmethod def setup_clients(cls): super(VirtualInterfacesNegativeTestJSON, cls).setup_clients() cls.client = cls.servers_client @test.attr(type=['negative']) @test.idempotent_id('64ebd03c-1089-4306-93fa-60f5eb5c803c') @t...
alid server_id invalid_server_id = str(uuid.uuid4()) self.assertRaises(lib_exc.NotFound, self.client.list_virtual_interfaces, invalid_server_id)
squirrelo/qiita
qiita_db/test/test_base.py
Python
bsd-3-clause
5,463
0.000183
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
s QiitaStatusObjectTest(TestCase): """Tests that the QittaStatusObject class functions act correctly""" def setUp(self): # We need an actual subclass in order to test the equality functions self.tester =
qdb.analysis.Analysis(1) def test_status(self): """Correctly returns the status of the object""" self.assertEqual(self.tester.status, "in_construction") def test_check_status_single(self): """check_status works passing a single status""" self.assertTrue(self.tester.check_statu...
algorithmiaio/algorithmia-python
Algorithmia/util.py
Python
mit
1,473
0.002716
import re import hashlib FNAME_MATCH = re.compile(r'/([^/]+)$') # From the last slash to the end of the string PREFIX = re.compile(r'([^:]+://)(/)?(.+)') # Check
for a prefix like data:// def getParentAndBase(path): match = PREFIX.match(path) if match is None: if path.endswith('/'): stripped_path = path[:-1] else: stripped_path = path base = FNAME_MATCH.search(stripped_path) if base is None: raise Va...
, stripped_path) return parent, base.group(1) else: prefix, leading_slash, uri = match.groups() parts = uri.split('/') parent_path = '/'.join(parts[:-1]) if leading_slash is not None: parent_path = '{prefix}/{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1])) ...
klebercode/rhape
rha/settings.py
Python
mit
2,677
0
""" Django settings for rha project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # impo...
config( 'DATABASE_URL', default='sqlite:///' + BASE_DIR.child('db.sqlite3'), cast=db_url), } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Recife' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS...
a') MEDIA_URL = '/media/' # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'RHAPE <no-reply@rhape.com.br>' EMAIL_USE_TLS = True EMAIL_HOST = config('EMAIL_HOST') EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587
wolfe-pack/moro
public/javascripts/brat/server/src/tag.py
Python
bsd-2-clause
6,002
0.001833
#!/usr/bin/env python # -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*- # vim:set ft=python ts=4 sw=4 sts=4 autoindent: ''' Functionality for invoking tagging services. Author: Pontus Stenetorp Version: 2011-04-22 ''' from __future__ import with_statement from httplib import HTTPCon...
se TaggerConnectionError(tagger_token, '%s %s' % (resp.status, resp.reason)) # Finally, we can read the response data resp_data = resp.read() finally: if conn is not None
: conn.close() try: json_resp = loads(resp_data) except ValueError: raise InvalidTaggerResponseError(tagger_token, resp_data) mods = ModificationTracker() for ann_data in json_resp.itervalues(): assert 'offsets' in ann_data, 'Tagger ...
dww100/sct
python/bin/sctify.py
Python
apache-2.0
1,761
0.000568
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Sctify: converts a CHARMM PSF/PDF pair to a SCT compatible PDB """ # Copyright 2014 University College London # 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 o...
', type=str, dest='pdb_path', help='Path to the input PDB file', required=True) parser.add_argument('-p', '--input_psf', nargs='?', type=str, dest='psf_path', help='Path to the input PSF file', required=True) parser....
return parser.parse_args() def main(): args = parse_arguments() atoms = sct.pdb.process_pdb_psf(args.psf_path, args.pdb_path) sct.pdb.write_pdb(atoms, args.pdb_out) if __name__ == "__main__": main()
atiberghien/makerscience-server
makerscience_catalog/migrations/0004_auto__add_field_makerscienceresource_level__add_field_makersciencereso.py
Python
agpl-3.0
5,685
0.00686
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'MakerScienceResource.level' db.add_column(u'makerscience_...
, 'unique_with': '()'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'projects.projectprogress': { 'Meta': {'ordering': "['or...
jango.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'progress_range': ('django.db.models.fields.related.ForeignKey',...
plotly/plotly.py
packages/python/plotly/plotly/validators/densitymapbox/colorbar/_dtick.py
Python
mit
500
0.002
import _plotly_utils.basevalidators clas
s DtickValidator(_plotly_utils.basevalidators.AnyValidator): def __init__( self, plotly_name="dtick", parent_name="densitymapbox.colorbar", **kwargs ): super(DtickValidator, self).__init__( plotly_name=plotly_name,
parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), implied_edits=kwargs.pop("implied_edits", {"tickmode": "linear"}), **kwargs )
glaudsonml/kurgan-ai
tools/sqlmap/tamper/space2comment.py
Python
apache-2.0
1,319
0.001516
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def dependencies(): pass def tamper(payload, **kwargs): """ Replaces space character (' ') with ...
if payload[i] == '\'': quote = not quote elif payload[i] == '"': doublequote = not doublequote elif payload[i] == " " and not doublequote and not quote: retVal += "/**/" continue retVal +
= payload[i] return retVal
sinnwerkstatt/ecg-balancing
ecg_balancing/migrations/0012_auto__add_unique_company_slug.py
Python
mit
10,698
0.007758
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'Company', fields ['slug'] db.create_unique(u'ecg_balancing_company', ['slug']...
], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', []...
.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'ecg_balancing.company': { 'Meta': {'object_name': 'Company'}, 'activities': ('django.db.models.fields.CharField', [], {'max_length':...
bendaf/diff_drive_entropy
EntropicRobot/main_race.py
Python
gpl-2.0
4,131
0.002905
import pygame import sys from PIL import Image # Python Imaging Library from vector_math import Vector2 pygame.init() # load map with PIL image_filename = "track_new_3.bmp" #image_filename = "empty.bmp" class Environment: def __init__(self): img = Image.open(image_filename) self.track = img.loa...
self.width, self.height def is_free(self, x, y): return self.track[x, y] == (255, 255, 255) def draw_pixel(self, r, g, b, x, y): global screen
draw_pixel(screen, r, g, b, x, y) class Goal: def __init__(self, x=100, y=100, size=10): self.pos = Vector2(x, y) self.size = size def draw(self): pygame.draw.rect(screen, (255, 0, 0), (self.pos.x, self.pos.y, self.size, self.size)) def draw_pixel(surface, r, g, b, x, y): ...
eamuntz/Django-Tut
myproject/myproject/settings.py
Python
mit
2,048
0
""" Django settings for myproject project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) ...
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'myproject.urls' WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { ...
ProstoKSI/distributed-queue
distributed_queue/tests/test_backends_init.py
Python
mit
1,313
0.002285
import unittest from distributed_queue import core, backends class TestBackend(unittest.TestCase): def test_list_backends(self): backend_list = core.BACKEND_LIST self.assertTrue('dummy' in backend_list) self.assertTrue('redis' in backend_list) def test_create_backend_fail(self): ...
: backend = core.create_backend('dummy') self.assertTrue(backend is not
None) self.assertTrue(isinstance(backend, backends.BaseBackend)) self.assertTrue(getattr(backend, 'send', None) is not None) self.assertTrue(getattr(backend, 'receive', None) is not None) test_data = 'test 1 2 3' backend.send('test', test_data) item = backend.receive(['t...
dohop/supervisor-logstash-notifier
setup.py
Python
apache-2.0
1,635
0
# # Copyright 2016 Dohop hf. # # 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, ...
description='Stream supervisor events to a logstash instance', long_description=open('README.rst').read(), entry_points={ 'console_scripts': [ 'logstash_notifier = logstash_notifier:main' ] }, install_requires=requi...
_requirements.read().splitlines(), )
SecHackLabs/WebHackSHL
modules/tplmap/burp_extension/config_tab.py
Python
gpl-3.0
4,466
0.027765
from burp import ITab from javax.swing import JPanel, GroupLayout, JLabel, JComboBox, JCheckBox from java.awt import Dimension from core.checks import plugins class ConfigTab( ITab, JPanel ): def __init__( self, callbacks ): self._callbacks = callbacks self._helpers = callbacks.getHelpers() ...
f._techTimebasedCheckBox, ), 'description': 'Techniques R(endered) T(ime-based blind). Default: RT.'
}, { 'label': 'Template Engines', 'components': self._pluginCheckBoxes, 'description': 'Force back-end template engine to this value(s).' }, { 'label': 'Payload position', 'components': ( self....
antani/cheapr
cheapr/app.py
Python
bsd-3-clause
1,780
0.002247
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template from cheapr.settings import ProdConfig from cheapr.assets import assets from cheapr.extensions import ( bcrypt, cache, db, login_manager, migrate, debug_toolbar, ) from ch...
fig): '''An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ :param config_object: The configuration object to use. ''' app = Flask(__name__) app.config.from_object(config_object) register_extensions(app) register_
blueprints(app) register_errorhandlers(app) app.secret_key = 'Google' app.images_cache='static/cache/images' #https://medium.com/@5hreyans/the-one-weird-trick-that-cut-our-flask-page-load-time-by-70-87145335f679 app.jinja_env.cache = {} images = Images(app) #resize = Resize(app) return ...
limix/glimix-core
version.py
Python
mit
411
0
import re from os.path import join from setuptools import find_packages def get(): pkgnames = find_packages() if len(pkgnames) == 0: return "unknown" pkgname = pkgnames[0] conte
nt = open(join(pkgname, "__init__.py")).read() c = re.compile(r"__version__ *= *('[^']+'|\"[^\"]+\")") m = c.search(content) if m is None: return "unknown" return m.gro
ups()[0][1:-1]
vileopratama/vitech
src/addons/l10n_in_hr_payroll/report/report_hr_salary_employee_bymonth.py
Python
mit
4,552
0.004174
#-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import datetime import time from openerp.osv import osv from openerp.report import report_sxw class report_hr_salary_employee_bymonth(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(r...
0.0 cnt = 0 for month in self.mnths: if month <> '': if len(month) != 7: month = '0' + str(month) if month in salary and salary[month]: emp_salary.append(salary[month]) total += salary[month] ...
else: emp_salary.append(0.00) else: emp_salary.append('') total_mnths[cnt] = '' cnt = cnt + 1 return emp_salary, total, total_mnths def get_employee(self, form): emp_salary = [] salary_list = [] ...
rvs/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/pg_twophase/switch_ckpt_serial/trigger_sql/test_triggersqls.py
Python
apache-2.0
1,237
0.001617
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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 ...
y 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 lan
guage governing permissions and limitations under the License. """ from mpp.models import SQLTestCase ''' Trigger sqls for create_tests ''' class TestTriggerSQLClass(SQLTestCase): ''' This class contains all the sqls that are part of the trigger phase The sqls in here will get suspended by one of the fault...
codelikeagirlcny/python-lessons-cny
code-exercises-etc/section_02_(strings)/z.ajm.str-format-phone-ex.20151024.py
Python
mit
169
0
phone = "315-555-2955"
prin
t "Area Code: {0}".format(phone[0:3]) print "Local: {0}".format(phone[4:]) print "Different format: ({0}) {1}".format(phone[0:3], phone[4:])
max0d41/ThugBrowser
src/DOM/Plugins.py
Python
gpl-2.0
1,544
0.002591
#!/usr/bin/env python # # Plugins.py # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; w...
nt(key) return self.item(key) except: return self.namedItem(key) def item(self, index): if index >= self.length: return Plugin() return list.__getitem__(self, index) def namedItem(self, name): index = 0 while index < self.length: ...
tswith(name): return p index += 1 print 'PLUGIN NOT FOUND:', name return Plugin() def refresh(self, reloadDocuments = False): pass
piton-package-manager/piton
piton/lib/inquirer/prompt.py
Python
mit
425
0
# -*- coding: utf-8 -*-
from .render.console import C
onsoleRender def prompt(questions, render=None, answers=None): render = render or ConsoleRender() answers = answers or {} try: for question in questions: answers[question.name] = render.render(question, answers) return answers except KeyboardInterrupt: print('') ...