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
amlyj/pythonStudy
2.7/data_analysis/study_numpy/numpy_functions/np_dot.py
Python
mit
3,856
0.000874
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17-9-7 下午3:07 # @Author : Tom.Lee # @File : np_dot.py # @Product : PyCharm # @Docs : # @Source : import numpy as np """ >>> import numpy as np Examples -------- >>> np.random.rand(3,2) array([[ 0.14022471, ...
2]] """ x1, y1 = 1, 2 x2, y2 = 3, 4 m1, n1 = 11, 22 m2, n2 = 33, 44 A = [[x1, y1], [x2, y2]] # 行 B = [[m1, n1], [m2, n2]] # 列 print np.dot(A, B) # [[ 77 110] # [165 242]] print '测试计算过程:' print x1 * m1 + y1 * m2, x1 * n1 + y1 * n2 # 77 110 print x2 * m1 + y2 * m2, x2 * n1 + y2 * n2 # 165 242 def my_dot_w2(...
st) and isinstance(b, list): assert len(a) == len(b) l1, l2 = a, b result = [] if isinstance(l1[0], list): # 判断是否为多维数组 size = len(l1) for index, value in enumerate(l1): start, cell = 0, [] while start < size: ...
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
Python
apache-2.0
14,371
0.008768
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
bundle(self, element=None): import tensorflow as tf self._session.close() tf.reset_default_graph() def process(self, element): """Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF
graph. """ import collections import apache_beam as beam num_in_batch = 0 try: assert self._session is not None feed_dict = collections.defaultdict(list) for line in element: # Remove trailing newline. if line.endswith('\n'): line = line[:-1] ...
frederica07/Dragon_Programming_Process
PyOpenGL-3.0.2/OpenGL/raw/GL/SGIX/texture_lod_bias.py
Python
bsd-2-clause
504
0.005952
'''Autogenerated by get_gl_extensions script, do not edit!''' from OpenGL import platform as _p from OpenGL.GL import glget EXTENSION_NAME = 'GL_SGIX_texture_lod_bias' _p.unpack_constants( """GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E GL_TEXTURE_LOD_BI
AS_T_SGIX 0x818F GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190""", globals()) def glInitTextureLodBiasSGIX(): '''Return boolean indicating whether this
extension is available''' from OpenGL import extensions return extensions.hasGLExtension( EXTENSION_NAME )
opencord/xos
lib/xos-api/xosapi/convenience/privilege.py
Python
apache-2.0
815
0
# Copyright 2017-present Open Networking Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI
CENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the L...
ce_wrapper class ORMWrapperPrivilege(ORMWrapper): pass register_convenience_wrapper("Privilege", ORMWrapperPrivilege)
globocom/database-as-a-service
dbaas/maintenance/async_jobs/base.py
Python
bsd-3-clause
5,453
0
from copy import copy from notification.models import TaskHistory from util import get_worker_name from workflow.workflow import steps_for_instances, rollback_for_instances_full __all__ = ('BaseJob',) class BaseJob(object): step_manger_class = None get_steps_method = None success_msg = '' error_msg...
manager.current_step self.auto_rollback = auto_rollback self.auto_cleanup = auto_cleanup self.scheduled_task = scheduled_task @property def steps(self): if self.get_steps_method is None: raise Exception(('You must set your
get_steps method name ' 'class in variable get_steps_method')) get_steps_func = getattr(self.database.infra, self.get_steps_method) return get_steps_func() @property def instances(self): raise NotImplementedError('You must override this method') def reg...
eduNEXT/edunext-platform
import_shims/lms/grades/rest_api/v1/tests/test_grading_policy_view.py
Python
agpl-3.0
470
0.008511
"""Deprecated import support. Auto-generated
by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('grades.rest_api.v1.tests.test_grading_policy_view', 'lms.djangoapps.grades.rest_api.v1.tests.t...
apps.grades.rest_api.v1.tests.test_grading_policy_view import *
mvpoland/django-press-links
press_links/datatranslation.py
Python
bsd-3-clause
323
0.006192
# Datatrans registry from datatrans.utils import register from press_links.models import Entry, Link class PressEntryTranslation(object): fields =
('title', 'excerpt', 'source') register(Entry, PressEntryTranslation) class LinkTrans
lation(object): fields = ('link', 'link_text') register(Link, LinkTranslation)
michaeljoseph/pane
pane/cli.py
Python
apache-2.0
569
0.001757
import logging import click import pane log = logging.getLogger(__name__)
@click.command() @click.option('--count', default=1, help='Number of greetings.') @click.option('--name', prompt='Your name', help='The person to greet.') @click.option('--debug', default=False, help='Debug mode.') def main(count, name, debug): """Simple program that greets NAME for a total of COUNT times.""" l...
click.echo('Hello %s!' % name) log.debug('Goodbye %s!' % name)
ThreatConnect-Inc/tcex
tcex/api/tc/v2/batch/group.py
Python
apache-2.0
21,524
0.001673
"""ThreatConnect Batch Import Module""" # standard library import json import uuid from typing import Any, Callable, Optional, Union # first-party from tcex.api.tc.v2.batch.attribute import Attribute from tcex.api.tc.v2.batch.security_label import SecurityLabel from tcex.api.tc.v2.batch.tag import Tag from tcex.utils ...
self._attributes: if attr.valid: self._group_data['attribute'].append(attr.data) # add security labels
if self._labels: self._group_data['securityLabel'] = [] for label in self._labels: self._group_data['securityLabel'].append(label.data) # add tags if self._tags: self._group_data['tag'] = [] for tag in self._tags: if ta...
Naoto-Imamachi/MIRAGE
scripts/module/analysis/thermo_calc.py
Python
mit
8,126
0.013537
#!/usr/bin/env python ''' thermo_calc.py: Calculate thermodynamic stability (minimum free energy (mfe) structures) <Energy> (1)miRNA seed region vs TargetRNA seed region -------- miRNA(8nt_seed) |||||||| -------- TargetRNA(8nt_seed) (2)mature miRNA vs candidate target site (the same length) -----------...
... return stdout, stderr #b'UUCAAGUA&UACUUGAA\n.(((((((&))))))). (-16.90)\n,(((((((&))))))), [-17.56]\n frequency of mfe structure in ensemble 0.342276 , delta G binding= -7.56\n' def regex_RNAcofold(seq): regex = r'.+\n(?P<str_mfe>\S+) \((?P<mfe>.+)\)\n(?P<str_ens>\S+)
\[(?P<ens>.+)\]\n frequency of mfe structure in ensemble (?P<ens_frequency>\S+) , delta G binding=(?P<delta_G>.+)\n' seq = seq.decode('utf-8') #print (seq) decoded_seq = re.match(regex, seq) str_mfe = decoded_seq.group('str_mfe') mfe = decoded_seq.group('mfe') str_ens = decoded_seq.group('...
palaxi00/palaxi00.github.io
Codeeval/bit_positions.py
Python
mit
295
0.010169
import sys with open(sys.argv[1], 'r') as test_cases: for test in test_cases: lista = (test.strip().split(',')) bin1 = bin(int(lista[0])) if bin1[-int(lista[1])] == bin1[-int(lista[2])]: print ('true'
)
else: print ('false')
edineicolli/daruma-exemplo-python
scripts/fiscal/ui_fiscal_icfencerrar.py
Python
gpl-2.0
6,436
0.003576
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_fiscal_icfencerrar.ui' # # Created: Mon Nov 24 22:25:43 2014 # 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 from PySide.QtGui import QMessage...
one, QtGui.QApplication.UnicodeUTF8)) self.pushButtonEnviar.setText(QtGui.QApplication.translate("ui_FISCAL_iCFEncerrar", "Enviar", None, QtGui.QApplication.UnicodeUTF8))
self.pushButtonCancelar.setText(QtGui.QApplication.translate("ui_FISCAL_iCFEncerrar", "Cancelar", None, QtGui.QApplication.UnicodeUTF8))
kerimlcr/ab2017-dpyo
ornek/moviepy/moviepy-0.2.2.12/moviepy/video/tools/drawing.py
Python
gpl-3.0
8,604
0.014179
""" This module deals with making images (np arrays). It provides drawing methods that are difficult to do with the existing Python libraries. """ import numpy as np def blit(im1, im2, pos=[0, 0], mask=None, ismask=False): """ Blit an image over another. Blits ``im1`` on ``im2`` as position ``pos=(x,y)``...
``p2`` is then defined as (p1 + vector). col1, col2 Either floats between 0 and 1 (for gradients used in masks) or [R,G,B] arrays (for colored gradients). shape 'linear', 'bilinear', or 'circular'. In a linear gradient the color
varies in one direction, from point ``p1`` to point ``p2``. In a bilinear gradient it also varies symetrically form ``p1`` in the other direction. In a circular gradient it goes from ``col1`` to ``col2`` in all directions. offset Real number between 0 and 1 indicating the fr...
naiyt/gem-spy
gem-spy.py
Python
mit
5,667
0.003882
import os import json import re import os.path import filecmp import pipes import fnmatch import subprocess import sublime import sublime_plugin import tempfile import hashlib from shutil import copyfile, rmtree class SpyOnGemsCommand(sublime_plugin.WindowCommand): def __init__(self, window): self.setting...
if not os.path.exists(cache_path): os.makedirs(cache_path) return cache_path # http://stackoverflow.com/a/3431838/1026980 def md5(self, fname): hash_
md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() # Utilities def run_bundle_command(self, command): try: current_path = self.window.folders()[0] ...
Reigel/kansha
kansha/user/user_cards.py
Python
bsd-3-clause
4,260
0.002817
# -*- coding:utf-8 -*- #-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- """ Trans-board view of user's cards """ from itertools import groupby from...
lse i18n._(u'n.c.'))
with h.div(class_='list-body'): for card in cards: if subgroup != sg_title(card): subgroup = sg_title(card) h << h.h4(subgroup) h << card.render(h, 'readonly') h << h.div(cl...
hack4impact/maps4all
app/contact/views.py
Python
mit
4,825
0.005596
import os from flask import render_template, redirect, url_for, abort, flash from flask.ext.login import login_required from flask.ext.rq import get_queue from wtforms.fields import SelectField from wtforms.validators import ( Optional ) from .. import db from ..models import EditableHTML, Resource, ContactCatego...
ute('/<int:category_id>', methods=['GET', 'POST']) @login_required def edit_category_name(category_id): """Edit a category""" category = ContactCategory.query.get(category_id) if category is None: abort(404) old_name = category.name form = EditCate
goryNameForm() if form.validate_on_submit(): if ContactCategory.query.filter(ContactCategory.name == form.name.data).first() is not None: flash('Category \"{}\" already exists.'.format(form.name.data), 'form-error') return render_template('contact/manage_category.html', ...
tseaver/google-cloud-python
spanner/google/cloud/spanner_v1/proto/spanner_pb2_grpc.py
Python
apache-2.0
22,552
0.003503
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.cloud.spanner_v1.proto import ( result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2, ) from google.cloud.spanner_v1.proto import ( spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_prot...
izer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString, ) self.PartitionRead = channel.unary_unary( "/google.spanner.v1.Spanner/PartitionRead", request_seria
lizer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString, ) class SpannerServicer(object): """Cloud Spanner API The Cloud Spanner A...
coreycb/charm-keystone
tests/charmhelpers/core/__init__.py
Python
apache-2.0
584
0
# Copyright 2014-2015 Canonical Limited. # # Licensed under the Apache License, Version 2.0 (t
he "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOU...
e License for the specific language governing permissions and # limitations under the License.
emilydolson/forestcat
pyrobot/plugins/worlds/Pyrobot/AndrewHallway.py
Python
agpl-3.0
1,447
0.000691
from pyrobot.simulators.pysim import * import math def INIT(): # (width, height), (offset x, offset y), scale: sim = TkSimulator((435, 850), (10, 835), 32) # x1, y1, x2, y2 in meters: sim.addBox(0, 25.7, 13, 25.9, "black") sim.addBox(0, 4.06, 2, 4.27, "black") sim.addBox(0, 4.27, 5.45, 4.72, "b...
6, 24.26, 13, 25.7, "black") sim.addBox(0, 21.34, 5, 25.7, "black") sim.addBox(5, 23.88, 6.39, 24.26, "black") # chair sim.addBox(10.2, 2.7, 11.1, 3.6, "blue", wallcolor="blue") # sofa sim.addBox(11.42, 3.55, 13, 4.45, "blue", wallcolor="blue")
# port, name, x, y, th, bounding Xs, bounding Ys, color # (optional TK color name): sim.addRobot(60000, TkPioneer("RedPioneer", 7, 21, -180 * math.pi / 180, ((0.225, 0.225, -0.225, -0.225), (0.175, -0.175...
librosa/librosa
docs/examples/plot_hprss.py
Python
isc
6,271
0.002232
# -*- coding: utf-8 -*- """ ===================================== Harmonic-percussive source separation ===================================== This notebook illustrates how to separate an audio signal into its harmonic and percussive components. We'll compare the original median-filtering based approach of `Fitzgerald...
bel='margin={:d}'.format(2**i))
ax[i, 0].label_outer() ax[i, 1].label_outer() ################################################################################ # In the plots above, it looks like margins of 4 or greater are sufficient to # produce strictly harmonic and percussive components. # # We can invert and play those components back just ...
fperez/sympy
doc/src/modules/mpmath/conf.py
Python
bsd-3-clause
4,392
0.004781
# -*- coding: utf-8 -*- # # mpmath documentation build configuration file, created by # sphinx-quickstart on Sun Apr 13 00:14:30 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't ...
rted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page.
#html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If tru...
gristlabs/asttokens
asttokens/asttokens.py
Python
apache-2.0
8,288
0.008808
# Copyright 2016 Grist Labs, 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 agreed to in writi...
xrange # pylint: disable=redefined-builtin from .line_numbers import LineNumbers from .util import Token, match_token, is_non_coding_token from .mark_tokens import MarkTokens class ASTTokens(object): """ ASTTokens maintains the text of Python code in several forms: as a string, as line numbers, and
as tokens, and is used to mark and access token and position information. ``source_text`` must be a unicode or UTF8-encoded string. If you pass in UTF8 bytes, remember that all offsets you'll get are to the unicode text, which is available as the ``.text`` property. If ``parse`` is set, the ``source_text``...
cr/fxos-certsuite
web-platform-tests/tests/tools/pywebsocket/src/mod_pywebsocket/msgutil.py
Python
mpl-2.0
7,598
0
# Copyright 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
sages: blocking, non-blocking, and via callback. Callback has the highest precedence. Note: This class should not be used with the standalone server for wss because pyOpenSSL used by the server raises a fatal error if the socket is accessed from multiple threads. """ def __init__(self, request...
a function to be called when a message is received. May be None. If not None, the function is called on another thread. In that case, MessageReceiver.receive and MessageReceiver.receive_nowait are useless because they will neve...
UManPychron/pychron
pychron/pipeline/plot/plotter/ideogram.py
Python
apache-2.0
35,999
0.001139
# =============================================================================== # Copyright 2013 Jake Ross # # 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...
verlay from chaco.array_data_source import ArrayDataSource from chaco.data_label import DataLabel from chaco.scatterplot import render_markers from chaco.tooltip import ToolTip from enable.colors import ColorTrait from numpy import array, arange, Inf, argmax from pyface.message_dialog import warning from traits.api imp...
es import nominal_value, std_dev from pychron.core.helpers.formatting import floatfmt from pychron.core.helpers.iterfuncs import groupby_key from pychron.core.stats.peak_detection import fast_find_peaks from pychron.core.stats.probability_curves import cumulative_probability, kernel_density from pychron.graph.explicit...
fandres/Monitor-heladas
Code/examples/Test.py
Python
gpl-3.0
244
0
import machine import time # 2+2 3*4.0 # 102**1023 print("Hi from ESP") pin = machine.Pin(2, machine.Pin.OUT) pin.high
() pin.low() def toggle(p): p.value(not p.value()) # toggle(pin) while True: to
ggle(pin) time.sleep_ms(500)
usoban/pylogenetics
pylogen/tree.py
Python
mit
2,030
0.049754
from abc import ABCMeta, abstractmethod class Edge: """ Phylogenetic tree edge. Connects start and end node with some given distance measure """ def __init__(self, startNode, endNode, distance): self.distance = distance self.setEndNode(endNode) self.setStartNode(startNode) def setStartNode(self, node...
connect it to its children, and a parent edge that connects it to its parent. Priting a node outputs subtree with root in the given node. """ __metaclass__ = ABCMeta def __init__(self, label): self.label = label self.children
= [] self.parentEdge = None def addChildEdge(self, childEdge): self.children.append(childEdge) def setParentEdge(self, parentEdge): self.parentEdge = parentEdge @abstractmethod def output(self): pass def __str__(self): return self.output() class NeighborJoiningNode(Node): """ Neighbor joinin...
fullfanta/mxnet
python/mxnet/gluon/parameter.py
Python
apache-2.0
31,399
0.003631
# 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...
type=mx_real_t, lr_mult=1.0, wd_mult=1.0, init=None, allow_deferred_init=False, dif
ferentiable=True): self._var = None self._data = None self._grad = None self._ctx_list = None self._ctx_map = None self._deferred_init = () self._differentiable = differentiable self._allow_deferred_init = allow_deferred_init self._grad_req = None ...
abshinn/backup
backup.py
Python
unlicense
11,146
0.008613
#!/usr/bin/env python3 # TODO # - grab file contents in update only if file has changed # - create methods for file access/information # - create methods for file writing/copying import os, sys, pickle, time, difflib #import pdb DEBUG class Backup(object): """Backup text files as binary strings. KEYWORD ...
ef __init__(self, new, changed, removed): self.new = new self.changed = changed self.removed = removed class stateCompare: """Store backup comparison objects in a simple object.""" def __init__(self, dirComparison, filComparison):
self.dirs = dirComparison self.files = filComparison def __init__(self, directories = [], backupdir = "", exts = ["py", "txt", "R", "tex"]): self.directories = directories self.exts = exts # define backup directory as current working directory if not specified ...
syci/domsense-agilebg-addons
account_vat_on_payment/__openerp__.py
Python
gpl-2.0
2,244
0.004011
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011-2012 Domsense s.r.l. (<http://www.domsense.com>). # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # # This progra...
it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied war...
General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "VAT on payment", "vers...
tarak/chef_django_app
user_profiles/apps.py
Python
gpl-3.0
141
0
from __future__ import unicode_literals from django.apps import AppConfig class UserProfiles
Config(AppConfig): na
me = 'user_profiles'
0k/oem
src/oem/db.py
Python
bsd-2-clause
5,051
0.002178
# -*- coding: utf-8 -*- import time import re import getpass import socket from kids.cache import cache from kids.cmd import msg from kids.ansi import aformat from . import ooop_utils _DEFAULT_NOT_SET = object() _DB_REGEX = re.compile('''^ (?P<dbname>[a-zA-Z0-9_]+) ## db_name ( @(?P<host>[a-zA-Z0-9\...
= True except socket.error as e: raise Exception( "Connection to %r: %s." % (db["host"], e.strerror)) except ooop_utils.LoginFailed as e:
if force_query is True: msg.err("Access Denied. Bad Credentials ? " "Trying to relog...") force_query = True except Exception as e: if (hasattr(e, 'faultCode') and re.search("^AccessDenied$", e.faultCode)):...
georgthegreat/dancebooks-bibtex
dancebooks/db.py
Python
gpl-3.0
1,449
0.018634
import contextlib import lo
gging import os.path import sqlalchemy from sqlalchemy import schema as sql_schema from sqlalchemy import types as sql_types from sqlalchemy.ext import declarative as sql_declarative from sqlalchemy.orm import session as sql_session from dancebooks.config import config _Base = sql_declarative.declarative_base() cla...
_tablename__ = "backups" __table_args__ = {"schema": "service"} id = sql_schema.Column(sql_types.BigInteger, primary_key=True) path = sql_schema.Column(sql_types.String, nullable=False) provenance = sql_schema.Column(sql_types.String, nullable=False) aspect_ratio_x = sql_schema.Column(sql_types.BigInteger, nullab...
ingenioustechie/zamboni
mkt/webpay/forms.py
Python
bsd-3-clause
877
0
from django import forms import happyforms from mkt.api.form
s import SluggableModelChoiceField from mkt.inapp.models import InAppProduct from mkt.webapps.models import Webapp class PrepareWebAppForm(happyforms.Form): app = SluggableModelChoiceField(queryset=Webapp.objects.valid(), sluggable_to_field_name='app_slug') class PrepareInApp...
eField(queryset=InAppProduct.objects.all(), to_field_name='guid') def clean_inapp(self): inapp = self.cleaned_data['inapp'] if not inapp.is_purchasable(): raise forms.ValidationError( 'Can not start a purchase on this inapp product.') ...
eufarn7sp/egads-gui
ui/Ui_filenamewindow.py
Python
gpl-3.0
8,132
0.007747
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'addfilename.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Addfilename(object): def setupUi(self, Addfilename): Addfi...
QtWidgets.QSizePolicy.Fixed) self.gridLayout.addItem(spacerItem5, 3, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.
setObjectName("horizontalLayout") spacerItem6 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem6) self.ac_cancelButton = QtWidgets.QToolButton(Addfilename) self.ac_cancelButton.setMinimumSize(QtCore.QSize(...
tetherless-world/satoru
whyis/test/test_case.py
Python
apache-2.0
3,045
0.006897
import flask_testing from flask import current_app from flask import Response from rdflib import URIRef from typing import Optional, Dict from depot.manager import DepotManager class TestCase(flask_testing.TestCase): def login_new_user(self, *, email: str = "[email protected]", password: str = "password", usernam...
pub_archive'] = { 'depot.backend' : 'depot.io.memory.MemoryFileStorage' } config.Test['DEFAULT_ANONYMOUS_R
EAD'] = False config.Test['file_archive'] = { 'depot.backend' : 'depot.io.memory.MemoryFileStorage' } # Default port is 5000 config.Test['LIVESERVER_PORT'] = 8943 # Default timeout is 5 seconds config.Test['LIVESERVER_TIMEOUT'] = 10 from whyis...
alphagov/notifications-admin
app/main/views/history.py
Python
mit
1,306
0
from collections import defaultdict from operator import attrgetter from flask import render_template, request from app import current_service, format_date_numeric from app.main import main from app.models.event import APIKeyEvent, APIKeyEvents, ServiceEvents from app.utils.user import user_has_permissions @main.ro...
e_service') def history(service_id): events = _get_events(current_service.id, request.args.get('selected')) return render_template( 'views/temp-history.html', days=_chunk_events_by_day(events), show_n
avigation=request.args.get('selected') or any( isinstance(event, APIKeyEvent) for event in events ), user_getter=current_service.active_users.get_name_from_id, ) def _get_events(service_id, selected): if selected == 'api': return APIKeyEvents(service_id) if selected == ...
inquisite/Inquisite-Core
lib/managers/SchemaManager.py
Python
gpl-3.0
25,915
0.004823
from lib.utils.Db import db import re from lib.exceptions.FindError import FindError from lib.exceptions.DbError import DbError from lib.exceptions.ValidationError import ValidationError from lib.exceptions.SettingsValidationError import SettingsValidationError from pluginbase import PluginBase from lib.decorators.Memo...
itory) WHERE ID(t) = {type_id} AND ID(r) = {repo_id} RETURN ID(f) as id, f.name as name, f.code as code, f.type as type, f.description as description, properties(f) as props", {"type_id": int(type_id), "repo_id": repo_id}) else: tres = db.run( "MATCH (...
epository)--(t:SchemaType) WHERE t.code = {code} AND ID(r) = {repo_id} RETURN ID(t) as id, t.name as name, t.code as code, t.description as description", {"code": type_id, "repo_id": repo_id}).peek() if tres is None: return None result = db.run( "...
amanda/twarkov
setup.py
Python
mit
533
0.0394
from
setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) setup( name = 'twarkov', version = '0.0.2', description = 'Markov generator built for generating Tweets from timelines', license = 'MIT', author = 'Amanda Pickering', author_ema...
words = 'twitter markov generator bots', packages = find_packages(), )
yannrouillard/weboob
modules/ganassurances/browser.py
Python
agpl-3.0
2,914
0.000686
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
.page.login(self.username, self.password) if not self.is_logged(): raise BrowserIncorrectPassword() def get_accounts_list(self): if not self.is_on_page(AccountsPage): self.location('/wps/myportal/TableauDeBord') return self.page.get_list() def get_account(self,...
list() for a in l: if a.id == id: return a return None def get_history(self, account): if account._link is None: return iter([]) self.location(account._link) assert self.is_on_page(TransactionsPage) return self.page.get_hist...
Bionetbook/bionetbook
bnbapp/bionetbook/_old/verbs/forms/suspend.py
Python
mit
159
0.006289
from verbs.baseform
s import forms class SuspendForm(forms.VerbForm): name = "Suspend" slug = "suspend" duration_min_tim
e = forms.IntegerField()
sgordon007/jcvi_062915
formats/sizes.py
Python
bsd-2-clause
4,608
0
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import os.path as op import sys import logging import numpy as np from jcvi.formats.base import LineFile from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \ get_abs_path, which class Sizes (LineFile): """ Two-colu...
_mapping: return None return self.cumsizes_mapping[ctg] + pos def get_breaks(self): for i in xrange(len(self)): y
ield self.ctgs[i], self.cumsizes[i], self.cumsizes[i + 1] @property def summary(self): from jcvi.assembly.base import calculate_A50 ctgsizes = self.sizes_mapping.values() a50, l50, n50 = calculate_A50(ctgsizes) return sum(ctgsizes), l50, n50 def main(): actions = ( ...
lahwaacz/qutebrowser
tests/test_conftest.py
Python
gpl-3.0
1,647
0.000607
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
TNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along
with qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Various meta-tests for conftest.py.""" import os import sys import warnings import pytest import qutebrowser def test_qapp_name(qapp): """Make sure the QApplication name is changed when we use qapp.""" assert qapp.applicationName() == 'qu...
andyclymer/ControlBoard
lib/modules/BreakfastSerial/examples/rgb_led.py
Python
mit
887
0.003382
#! /usr/bin/env python """ This is an examp
le tha
t demonstrates how to use an RGB led with BreakfastSerial. It assumes you have an RGB led wired up with red on pin 10, green on pin 9, and blue on pin 8. """ from BreakfastSerial import RGBLed, Arduino from time import sleep board = Arduino() led = RGBLed(board, { "red": 10, "green": 9, "blue": 8 }) # Red (R: on, G:...
persandstrom/home-assistant
tests/components/binary_sensor/test_sleepiq.py
Python
apache-2.0
1,835
0
"""The tests for SleepIQ binary sensor platform.""" import unittest from unittest.mock import MagicMock import requests_mock from homeassistant.setup import setup_component from homeassistant.components.binary_sensor import sleepiq from tests.components.test_sleepiq import mock_responses from tests.common import get...
"""Test for successfully setting up the SleepIQ platform.""" mock_responses(mock) setup_component(self.hass, 'sleepiq', {
'sleepiq': self.config}) sleepiq.setup_platform(self.hass, self.config, self.add_entities, MagicMock()) self.assertEqual(2, len(self.DEVICES)) left_side = self.DEVICES[1] self.assert...
kragniz/python-etcd3
etcd3/transactions.py
Python
apache-2.0
3,018
0
import etcd3.etcdrpc as etcdrpc import etcd3.utils as utils _OPERATORS = { etcdrpc.Compare.EQUAL: "==", etcdrpc.Compare.NOT_EQUAL: "!=", etcdrpc.Compare.LESS: "<", etcdrpc.Compare.GREATER: ">" } class BaseCompare(object): def __init__(self, key, range_end=None): self.key = key sel...
ER return self def __repr__(self): if self.range_end is None: keys = self.key else: keys = "[{}, {})".format(self.key, self.range_end) return "{}: {} {} '{}'".format(self.__class__, keys, _OPERATORS.get(self.op), ...
nd is not None: compare.range_end = utils.to_bytes(self.range_end) if self.op is None: raise ValueError('op must be one of =, !=, < or >') compare.result = self.op self.build_compare(compare) return compare class Value(BaseCompare): def build_compare(self...
mattn/ccat
Godeps/_workspace/src/sourcegraph.com/sourcegraph/srclib/docs/buildsite.py
Python
mit
3,663
0.019929
#!/usr/bin/env python import jinja2 import os import re import shlex import sys import mkdocs.build from mkdocs.build import build from mkdocs.config import load_config from urllib2 import urlopen import subprocess def line_containing(lines, text): for i in range(len(lines)): if text.lower() in lines[i].lower(...
nes) # No matching logic else: return match.group(0) # Process an aritrary number of expansions. oldSource = "" while source != oldSource: oldSource = source source = re.sub("\[\[(.*)\]\]", expand, oldSource) return convert_markdown_o
riginal(source) # Hotpatch in the markdown conversion wrapper mkdocs.build.convert_markdown = convert_markdown_new if __name__ == "__main__": # Build documentation config = load_config(options=None) build(config) # Load templates template_env = jinja2.Environment(loader = jinja2.FileSystemLoader(os.path...
softwaresaved/fat
lowfat/jobs/daily/report.py
Python
bsd-3-clause
1,861
0.004299
import os from django_extensions.management.jobs import DailyJob import nbformat from nbconvert.preprocessors import ExecutePreprocessor from nbconvert import HTMLExporter class Job(DailyJob): help = "Convert Jupyter Notebook in lowfat/reports to HTML page in lowfat/reports/html." def execute(self): ...
with open("lowfat/reports/{}".format(notebook_filename)) as file_: notebook = nbformat.read(file_, as_version=4) # Kernel is provided by https://github.com/django-extensions/django-extensions/ execute_preprocessor = ExecutePreprocessor(timeout=600, kernel_name='dj...
ter.template_file = 'basic' (body, dummy_resources) = html_exporter.from_notebook_node(notebook) with open('lowfat/reports/html/{}.html'.format(notebook_filename), 'wt') as file_: file_.write(body)
tejesh95/Zubio.in
zubio/allauth/socialaccount/models.py
Python
mit
11,718
0.000085
from __future__ import absolute_import from django.core.exceptions import PermissionDenied from django.db import models from django.contrib.auth import authenticate from django.contrib.sites.models import Site from django.utils.encoding import python_2_unicode_compatible from django.utils.crypto import get_random_stri...
'uid': # # Ideally, URLField(max_length=1024, unique=True) would be used # for identity. However, MySQL has a max_length limitation of 255 # for URLField. How about models.TextField(unique=True) then? # Well, that won't work
either for MySQL due to another bug[1]. So # the only way out would be to drop the unique constraint, or # switch to shorter identity URLs. Opted for the latter, as [2] # suggests that identity URLs are supposed to be short anyway, at # least for the old spec. # # [1] http://code.djangoproject....
landonb/hamster-applet
wafadmin/Logs.py
Python
gpl-3.0
2,570
0.077432
#! /usr/bin/env python # encoding: utf-8 import ansiterm import os,re,logging,traceba
ck,sys from Constants import* zones='' verbose=0 colors_lst={'USE':True,'BOLD':'\x1b[01;1m','RED':'\x1b[01;31m','GREEN':'\x1b[32m','YELLOW':'\x1b[33m','PINK':'\x1b[35m','BLUE':'\x1b[01;34m','CYAN':'\x1b[36m','NORMAL':'\x1b[0m','cursor_on':'\x1b[?25h','cursor_off':'\x1b[?25l',} got_tty=False term=os.environ.get('TERM','...
Error: pass import Utils if not got_tty or'NOCOLOR'in os.environ: colors_lst['USE']=False def get_color(cl): if not colors_lst['USE']:return'' return colors_lst.get(cl,'') class foo(object): def __getattr__(self,a): return get_color(a) def __call__(self,a): return get_color(a) colors=foo() re_log=re.compile(...
astagi/taiga-back
tests/integration/test_projects.py
Python
agpl-3.0
13,485
0.00178
from django.core.urlresolvers import reverse from taiga.base.utils import json from taiga.projects.services import stats as stats_services from taiga.projects.history.services import take_snapshot from taiga.permissions.permissions import ANON_PERMISSIONS from taiga.projects.models import Project from .. import factor...
ervices.get_member_stats_for_project(project) assert stats["closed_bugs"][membership_1.user.id] == 1 assert stats["closed_bugs"][membership_2.user.id] == 0 assert stats["iocaine_tasks"][membership_1.user.id] == 0 assert stats["iocaine_tasks"][membership_2.user.id] == 1 assert stats["wiki_changes"...
assert stats["created_bugs"][membership_2.user.id] == 1 assert stats["closed_tasks"][membership_1.user.id] == 1 assert stats["closed_tasks"][membership_2.user.id] == 0 def test_leave_project_valid_membership(client): user = f.UserFactory.create() project = f.ProjectFactory.create() role = f.Role...
mathom/xrayvision
xrayvision/patches/sqlite3/__init__.py
Python
mit
202
0
''' Wrap some important functions in sqlite3 so we can instrument them. ''' from xrayvision.monkeypatch import mark_patched, is_patched _old_connect =
sqlite3.conne
ct def patch(module): module
mic4ael/indico
indico/modules/events/persons/operations.py
Python
mit
843
0.001186
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import session from indico.core import signals from i...
, EventLogRealm from indico.modules.events.persons import logger def update_person(person, data): person.populate_from_dict(data) db.session.flush() signals.event.person_updated.send(person) logger.info('Person %s updated by %s', person, session.user) person.event.log(EventLogRealm.management, Eve...
r)
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_isis_act.py
Python
apache-2.0
15,069
0.017918
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI...
, None, [], [], ''' IS-IS process instance identifier ''', 'instance_identifier', 'Cisco-IOS-XR-isis-act
', False), ], 'Cisco-IOS-XR-isis-act', 'instance', _yang_ns._namespaces['Cisco-IOS-XR-isis-act'], 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_isis_act' ), }, 'ClearIsisProcessRpc.Input' : { 'meta_info' : _MetaInfoClass('ClearIsisProcessRpc.Input'...
spiralx/mypy
mypy/spiralx/fileproc/__test.py
Python
mit
358
0.005587
impor
t unittest import doctest import spiralx.fileproc # ----------------------------------------------------------------------------- def load_tests(loader, tests, ignore): fileprocTestSuite = unittest.TestSuite() fileprocTestSuite.addTests(doctest.DocTest
Suite(spiralx.fileproc)) return fileprocTestSuite #suite = get_tests() #suite.run()
jeffschenck/rest-roles
rest_roles/roles.py
Python
mit
5,031
0
from __future__ import relative_imports from . import ALL_ACTIONS, ALL_VIEWS, RoleConfigurationError class RoleMeta(object): """Metaclass to register role classes.""" registry = [] def __new__(cls, name, bases, dct): """Register all roles created in the system.""" role_cls = super(RoleMe...
392043 pass def _enforce_restrictions(self, request, view, restrictions): """Ensure only valid objects are created or modified.""" # For creates, this will require validating that the object about to be # created *would* match the queries being described by the Q object # (o...
sion of this is massive and kind of gross, since # we'd need to implement Python-side calculations to mirror all Q # functionality: # - & and | and ~ operations between Q nodes # - __ foreign key traversal syntax # - all the field lookup types (__gte, __in, etc.) # For o...
ActiveState/code
recipes/Python/577084_shell_sort/recipe-577084.py
Python
mit
411
0
def ShellSort(A): def GetCols(n): cols = [1] val = 1 while val < n: val = int(val * 2.2) cols.insert(0, val) return cols for h in GetCols(len(A)): for i in range(h, len(A)): cur = A[i] j = i while j >= h and A[j...
A
[j] = cur
damianolombardo/fauxmo
fauxmo.py
Python
mit
17,632
0.001475
#!/usr/bin/env python """ The MIT License (MIT) Copyright (c) 2015 Maker Musings 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...
if self.use_poll: self.poller.register(fileno, select.POLLIN) self.targets[fileno] = target def remove(self, target, fileno=None): if not fileno: fileno = target.fileno() if self.us
e_poll: self.poller.unregister(fileno) del (self.targets[fileno]) def poll(self, timeout=0): if self.use_poll: ready = self.poller.poll(timeout) else: ready = [] if len(self.targets) > 0: (rlist, wlist, xlist) = select.select(s...
ramcn/demo3
venv/lib/python3.4/site-packages/oauth2_provider/exceptions.py
Python
mit
441
0
class OAuthToolkitError(Exception): """ Base class for exceptions """ def __init__(self, error=None, redirect_uri=None
, *args, **kwargs): super(OAuthToolkitError, self).__init__(*args, **kwargs) self.oauthlib_error = error if redirect_uri: self.oauthlib_error.redirect_uri = redirect_uri class FatalClientError(OAuthToolkitError): """ Class for critical errors """ pass
m8ttyB/socorro
socorro/unittest/processor/test_support_classifiers.py
Python
mpl-2.0
11,339
0.000088
# 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/. import copy from nose.tools import eq_, ok_ from sys import maxint from socorro.lib.util import DotDict from socorro....
), (5, ) ) def test_windows_action(self): jd = copy.deepcopy(cannonical_json_dump) processed_crash = DotDict() processed_crash.json_dump = jd raw_crash = DotDict() raw_crash.ProductName = 'Firefox' raw_cras
h.Version = '16' raw_dumps = {} fake_processor = create_basic_fake_processor() classifier = OutOfDateClassifier() classifier.out_of_date_threshold = ('17',) processed_crash.json_dump['system_info']['os'] = 'Windows NT' processed_crash.json_dump['system_info']['os_ver'] ...
Ircam-Web/mezzanine-organization
organization/utils/context_processors.py
Python
agpl-3.0
237
0
# -*- coding: utf-8
-*- from django.conf import settings def static_hash(request): """ Context processor to set archiprod to True for the main ressource menu """ return {"static_hash": settings.STATIC_HA
SH}
marsch/camlistore
lib/python/camli/op.py
Python
apache-2.0
12,883
0.006443
#!/usr/bin/env python # # Camlistore uploader client for Python. # # Copyright 2010 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-...
present this set will be empty. Raises: ServerError if the server response is bad. PayloadError if the server response is not in the right format. OSError or IOError if reading any blobs breaks. """ if isinstance(blobs, dict): raise TypeError('Must pass iterable of tuples, open ...
or item in blobs: if isinstance(item, tuple): blob, blobref = item else: blob, blobref = item, None if blobref is None: blobref = 'sha1-' + buffered_sha1(blob, buffer_size=self.buffer_size) blobref_dict[blobref] = blob preupload = {'camliversion': '1'} for index,...
okolisny/integration_tests
cfme/utils/tests/test_ipappliance.py
Python
gpl-2.0
1,553
0.000644
# -*- coding: utf-8 -*- from urlparse import urlparse import pytest from fixtures.pytest_store import store from cfme.utils.appliance import IPAppliance, DummyAppliance def test_ipappliance_from_address(): address = '1.2.3.4' ip_a = IPAppliance(address) assert ip_a.address == address assert ip_a.url ...
_a = IPAppliance() assert infra_provider in ip_a.managed_known_providers def test_context_hack(monkeypatch): ip_a = IPAppliance.from_url('http://127.0.0.2/') def not_good(*k): raise Run
timeError() monkeypatch.setattr(ip_a, '_screenshot_capture_at_context_leave', not_good) with pytest.raises(ValueError): with ip_a: raise ValueError("test")
donlee888/JsObjects
Python/Prog282SimpleDb/scripts/simpledb.py
Python
mit
1,593
0.000628
#!/usr/bin/python ''' Created on May 14, 2012 @author: Charlie ''' import ConfigParser import boto import cgitb cgitb.enable() class MyClass(object): def __init__(self, domain): config = ConfigParser.RawConfigParser() config.read('.boto') key = config.get('Credentials', 'aws_access_key_i...
): self.conn.creat
e_domain(self.domain) def addData(self, itemName, itemAttrs): dom = self.conn.get_domain(self.domain) item_name = itemName dom.put_attributes(item_name, itemAttrs) def startXml(self): xml = "Content-Type: text/xml\n\n" xml += "<?xml version='1.0'?>\n" xml += '<t...
ionelmc/python-hunter
tests/utils.py
Python
bsd-2-clause
615
0
import os from hunter import CallPrinter TIMEOUT = int(os.getenv('HUNTER_TEST_TIMEOUT', 60)) class DebugCallPrinter(CallPrinter): def __init__(self, suffix='', **kwargs): self.s
uffix = suffix super(DebugCallPrinter, self).__init__(**kwargs) def __call__(self, event): self.output("depth={} calls={:<4}", event.depth, event.calls) super(DebugCallPrinter, self).__call__(event)
def output(self, format_str, *args, **kwargs): format_str = format_str.replace('\n', '%s\n' % self.suffix) super(DebugCallPrinter, self).output(format_str, *args, **kwargs)
lukaszb/monolith
monolith/tests/test_cli.py
Python
bsd-2-clause
11,047
0.000815
import io import sys import mock import argparse from monolith.compat import unittest from monolith.cli.base import arg from monolith.cli.base import ExecutionManager from monolith.cli.base import SimpleExecutionManager from monolith.cli.base import BaseCommand from monolith.cli.base import CommandError from monolith.c...
elf.manager.call_command('add',
'-f') self.assertTrue(Command.handle.called) namespace = Command.handle.call_args[0][0] self.assertTrue(namespace.force) @mock.patch('monolith.cli.base.sys.stderr') def test_call_command_fails(self, stderr): class Command(BaseCommand): args = [ arg('...
MartinHowarth/microservice
microservice/examples/hello_world.py
Python
mit
219
0
from microservi
ce.core.decorator import microservice @microservice def hello_world(*args, **kwargs): return "Hello, world!" @microservice def hello_other_world(*args, **kwargs): r
eturn "Hello, other world!"
sergeyfarin/pyqt-fit
setup.py
Python
gpl-3.0
2,412
0.003317
#!/usr/bin/env python from setuptools import setup #from path import path #with (path(__file__).dirname() / 'pyqt_fit' / 'version.txt').open() as f: #__version__ = f.read().strip() import os.path version_filename = os.path.join(os.path.dirname(__file__), 'pyqt_fit', 'version.txt') with open(version_filename, "...
author_email='[email protected]', url=['https://code.google.com/p/pyqt-fit/'], packages=['pyqt_fit', 'pyqt_fit.functions', 'pyqt_fit.residuals', 'pyqt_fit.test'], package_data={'pyqt_fit': ['
qt_fit.ui', 'version.txt', 'cy_local_linear.pyx', '_kernels.pyx', '_kde.pyx', 'cy_binning.pyx', 'math.pxd' ...
takeshineshiro/nova
nova/tests/functional/v3/test_suspend_server.py
Python
apache-2.0
2,309
0
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
# License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from nova.tests.functional.v3 import test_servers CONF = cfg.CONF CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.legacy_v2.extensions') class SuspendServerSamplesJsonTest(test_servers.ServersSampleBase): extension_name = "os-suspend-server" ctype = 'json' extra_extensions_to_load = ["os-access-ips"] # TODO(park): Overriding '_api_version' till all functional tests # are merged...
benhunter/py-stuff
bhp/rforward.py
Python
mit
6,044
0.002647
#!/usr/bin/env python # Copyright (C) 2008 Robey Pointer <[email protected]> # # This file is part of paramiko. # # Paramiko 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 ...
t sys import threading from optparse import OptionParser import paramiko SSH_PORT = 22 DEFAULT_PORT = 4000 g_verbose = True def handler(chan, host, port): sock = socket.socket() try: sock.conne
ct((host, port)) except Exception as e: verbose('Forwarding request to %s:%d failed: %r' % (host, port, e)) return verbose('Connected! Tunnel open %r -> %r -> %r' % (chan.origin_addr, chan.getpeername(), (host, port))) while True: ...
priyaganti/rockstor-core
src/rockstor/storageadmin/views/network.py
Python
gpl-3.0
16,309
0
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la...
undrobin
"}}', 'activebackup': '{ "runner": {"name": "activebackup"}}', 'loadbalance': '{ "runner": {"name": "loadbalance"}}', 'lacp': '{ "runner": {"name": "lacp"}}', } team_profiles = ('broadcast', 'roundrobin', 'activebackup', 'loadbalance', 'lacp') bond_profiles = ('b...
eduNEXT/edx-platform
lms/djangoapps/program_enrollments/apps.py
Python
agpl-3.0
926
0.00216
""" ProgramEnrollments Application Configuration """ from django.apps import AppConfig from edx_django_utils.plugins import PluginURLs from openedx.core.djangoapps.plugins.constants import ProjectType class ProgramEnrollmentsConfig(AppConfig): """ Application conf
iguration for ProgramEnrollment """ name = 'lms.djangoapps.program_enrollments' plugin_app = { PluginURLs.CONFIG: { ProjectType.LMS: { PluginURLs.NAM
ESPACE: 'programs_api', PluginURLs.REGEX: 'api/program_enrollments/', PluginURLs.RELATIVE_PATH: 'rest_api.urls', } }, } def ready(self): """ Connect handlers to signals. """ from lms.djangoapps.program_enrollments import signal...
anirudhr/neural
bam_bias.py
Python
gpl-2.0
4,551
0.006152
#!/usr/bin/python2 #:indentSize=4:tabSize=4:noTabs=true:wrap=soft: import numpy as np import re def simple_transfer(xin, x): return (xin/abs(xin)) if xin else x class BAM: def __init__(self, s_mat_list, t_mat_list): #s_mat_list, t_mat_list = list of np.matrix self.transfer = np.vectorize(simple_trans...
#print 'Not converged' return y
def inp_right(self, y_mat): firstrun_flag = True convergence_flag = False while not convergence_flag: xin = y_mat * self.w_mat.getT() + self.biasX if firstrun_flag: x = np.matrix(np.zeros([xin.shape[1]])) xold = x x = self.transf...
anhstudios/swganh
data/scripts/templates/object/draft_schematic/clothing/shared_clothing_armor_mandalorian_bracer_r.py
Python
mit
473
0.046512
#### NOTICE: THIS FILE IS
AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swg
py.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/clothing/shared_clothing_armor_mandalorian_bracer_r.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
rdqw/sscoin
qa/rpc-tests/test_framework/mininode.py
Python
mit
39,022
0.000948
# mininode.py - Sscoin P2P network half-a-node # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # This python code was modified from ArtForz' public domain half-a-node, as # found in the mini-node branch of http://github.co...
ket_map = dict() # One lock for synchronizing all data access between the networking thread (see # NetworkThread below) and the thread running the test logic. For simplicity, # NodeConn acquires this lock whenever delivering a message to to a NodeConnCB, # and whenever adding anything to the send buffer (in send_mes
sage()). This # lock should be acquired in the thread running the test logic to synchronize # access to any data shared with the NodeConnCB or NodeConn. mininode_lock = RLock() # Serialization/deserialization tools def sha256(s): return hashlib.new('sha256', s).digest() def hash256(s): return sha256(sha256(...
kohr-h/odl
odl/test/trafos/backends/pyfftw_bindings_test.py
Python
mpl-2.0
13,174
0
# Copyright 2014-2017 The ODL contributors # # This file is part of ODL. # # 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 https://mozilla.org/MPL/2.0/. from __future__ import division import numpy...
(3, 4, 3), (3, 4, 3)] always_bad_shapes = [(3, 4), (3, 4, 5)] for bad_shape, axes in zip(bad_sha
pes_out, axes_list): for always_bad_shape in always_bad_shapes: arr_out = np.empty(always_bad_shape, dtype='complex128') with pytest.raises(ValueError): if direction == 'forward': pyfftw_call(arr_in, arr_out, axes=axes, halfcomplex=True, ...
verma-varsha/zulip
zerver/lib/cache_helpers.py
Python
apache-2.0
5,384
0.006129
from __future__ import absolute_import from six import binary_type from typing import Any, Callable, Dict, List, Tuple, Text # This file needs to be different from cache.py because cache.py # cannot import anything from zerver.models or we'd have an import # loop from django.conf import settings from zerver.models im...
e)] = (client,) def huddle_cache_items(items_for_remote_cache, huddle): # type: (Dict[Text, Tuple[Huddle]], Huddle) -> None items_for_remote_cache[huddle_hash_cache_key(huddle.huddle_hash)] = (huddle,) def recipient_cache_items(items_for_remote_cache, recipient): # type: (Dict[Text, Tuple[Recipient]], Rec...
e, recipient.type_id)] = (recipient,) session_engine = import_module(settings.SESSION_ENGINE) def session_cache_items(items_for_remote_cache, session): # type: (Dict[Text, Text], Session) -> None store = session_engine.SessionStore(session_key=session.session_key) # type: ignore # import_module items_for_...
hlzz/dotfiles
graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/trial/_dist/test/test_worker.py
Python
bsd-3-clause
15,115
0.002183
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Test for distributed trial worker side. """ import os from cStringIO import StringIO from zope.interface.verify import verifyObject from twisted.trial.reporter import TestResult from twisted.trial.unittest import TestCase from...
d = self.worker.callRemote(managercommands.AddSkip, testName=self.testName, reason='reason') d.addCallback(lambda result: results.append(result['success'])) self.pumpTranspor
ts() self.assertEqual(self.testCase, self.result.skips[0][0]) self.assertTrue(results) def test_runUnexpectedSuccesses(self): """ Run a test, and succeed unexpectedly. """ results = [] d = self.worker.callRemote(managercommands.AddUnexpectedSuc...
tseaver/gcloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/transports/bigtable_instance_admin_grpc_transport.py
Python
apache-2.0
12,786
0.000313
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
sed to take advantage of advanced features of gRPC. """ # The scopes needed to make gRPC calls to all of the methods defined # in this service. _OAUTH_SCOPES = ( 'https://www.googleapis.com/auth/bigtable.admin', 'https://www.googleapis.com/auth/bigtable.admin.cluster',
'https://www.googleapis.com/auth/bigtable.admin.instance', 'https://www.googleapis.com/auth/bigtable.admin.table', 'https://www.googleapis.com/auth/cloud-bigtable.admin', 'https://www.googleapis.com/auth/cloud-bigtable.admin.cluster', 'https://www.googleapis.com/auth/cloud-bigtab...
WALR/taiga-back
taiga/projects/services/bulk_update_order.py
Python
agpl-3.0
5,428
0.000921
# Copyright (C) 2014 Andrey Antukh <[email protected]> # Copyright (C) 2014 Jesús Espino <[email protected]> # Copyright (C) 2014 David Barragán <[email protected]> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the F...
r = connection.cursor() sql = """ prepare bulk_update_order as update projects_taskstatus set "order" = $1 where projects_taskstatus.id = $2 and projects_taskstatus.project_id = $3; """ cursor.execute(sql) for id, order in data: cursor.execute("EXECUTE bulk_update_ord...
r.execute("DEALLOCATE bulk_update_order") cursor.close() @transaction.atomic def bulk_update_issue_status_order(project, user, data): cursor = connection.cursor() sql = """ prepare bulk_update_order as update projects_issuestatus set "order" = $1 where projects_issuestatus.id = $2 and ...
jamesmishra/nlp-playground
nlp_playground/lib/gensim/__init__.py
Python
mit
44
0
"""Tools for working with Gensim models.""
"
electronics45/pyapplaunch
pyapplaunch/RadioManagement.py
Python
mit
6,893
0.03888
from PyQt4.QtCore import * from PyQt4 import QtGui class RadioManagement (): def __init__ (self, radioCol, gridLayout): self.radioGroup = QtGui.QButtonGroup() # To store radio buttons. self.radioCol = radioCol self.gridLayout = gridLayout def initDelAndMovButtons (self, vLayout): # Add hbox for edit button...
idget (button) self.connect (button, SIGNA
L ("clicked()"), self.deleteButtonClicked) button = QtGui.QPushButton ("Move &Up", self) self.editHBox.addWidget (button) self.connect (button, SIGNAL ("clicked()"), self.moveUpButtonClicked) button = QtGui.QPushButton ("Move Do&wn", self) self.editHBox.addWidget (button) self.connect (button, SIGNAL ("cl...
GhostshipSoftware/avaloria
src/tests/test_utils_batchprocessors.py
Python
bsd-3-clause
1,416
0.010593
import unittest class TestReadBatchfile(unittest.TestCase): def test_read_batchfile(self): # self.assertEqual(expected, read_batchfile(pythonpath, file_ending)) assert True # TODO: implement your test here class TestBatchCommandProcessor(unittest.TestCase): def test_parse_file(self): #...
.parse_file(pythonpath)) assert True # TODO: implement your test here class TestTbFilename(unittest.TestCase): def test_tb_filename(self): # self.assertEqual(expected, tb_filename(tb)) assert True # TODO: implement your test here class TestTbIter(unittest.TestCase):
def test_tb_iter(self): # self.assertEqual(expected, tb_iter(tb)) assert True # TODO: implement your test here class TestBatchCodeProcessor(unittest.TestCase): def test_code_exec(self): # batch_code_processor = BatchCodeProcessor() # self.assertEqual(expected, batch_code_processor...
suzukaze/mycli
setup.py
Python
bsd-3-clause
1,852
0.00054
import re import ast from setuptools import setup, find_packages _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('mycli/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) description = 'CLI for MySQL Database. With auto-completi...
be Capitalcased. WTF? 'prompt_toolkit==0.46', 'PyMySQL >= 0.6.6', 'sqlparse >= 0.1.16', 'configobj >= 5.0.6', ], entry_points=''' [console_scripts] mycli=mycli.main:cli ''', classifiers=[ 'Intended Au...
'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: SQL', 'Topic ::...
Ninjakow/TrueSkill
ranking.py
Python
gpl-3.0
5,051
0.005939
from trueskill import TrueSkill, Rating, rate import argparse from pytba import api as tba import math class FrcTrueSkill: def __init__(self): self.env = TrueSkill(draw_probability=0.02) self.trueskills = {} self.events = {} def update(self, red_alliance, red_score, blue_alliance, blu...
ill', '1.0') parser = argparse.ArgumentParser(description='Run TrueSkill algorithm on event results.') parser.add_argument('--predict', help='Predict unplayed matches', dest='predict', action='store_true') parser.add_argument('--year', help='All matches in all events in specified year', type=str, default=st...
# Set the draw probability based on previous data - around 3% env = TrueSkill(draw_probability=0.025) # Try tweaking tau and beta too matches = get_all_matches(args.year) results = parse_matches(matches, env) results = sort_by_trueskill(results, env) #results = sort_by_name(results) print_tru...
AriMartti/sikteeri
sikteeri/views.py
Python
mit
1,066
0.009381
# -*- coding: utf-8 -*- import logging logger = logging.getLogger("sikte
eri.views") from django.conf import se
ttings from django.shortcuts import render_to_response, redirect from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ from sikteeri.version import VERSION def frontpage(request): if settings.MAINTENANCE_MESSAGE == None: if not request.user.is_authenticated(): ...
SinnerSchraderMobileMirrors/django-cms
cms/admin/placeholderadmin.py
Python
bsd-3-clause
25,921
0.003472
# -*- coding: utf-8 -*- import sys from django.contrib.admin.helpers import AdminForm from django.utils.decorators import method_decorator from django.db import transaction from django.utils import simplejson from django.views.decorators.clickjacking import xframe_options_sameorigin from cms.constants import PLUGIN_CO...
rm.media context = { 'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'), 'title': opts.verbose_name, 'plugin': None, 'plugin_id': None, 'adminform': admin_form, 'add': False, 'is_popup': True, 'media':
media, 'opts': opts, 'change': True, 'save_as': False, 'has_add_permission': False, 'window_close_timeout': 10, } if cancel_clicked: # cancel button was clicked context.update({ 'cancel': True, ...
soybean217/lora-python
UServer/admin_run.py
Python
mit
632
0.001582
import sys from utils.log import Logger if __name__ == '__main__': input_argv = sy
s.argv try: server_name = input_argv[1] if server_name == 'http_server': from admin_server import http_server Logger.info('Admin Http Server Begin to run') http_server() elif server_name == 'data_server': from admin_server import data_server ...
o run') data_server() else: print('do not understand the command:%s.' % server_name) except IndexError as e: print('need input argv')
dora71/pyrigcontrol
sercomm.py
Python
agpl-3.0
1,642
0.052407
#!/usr/bin/env python # -*- coding: utf-8 -*- import serial import time import Queue import thread class Sercomm(object): def __init__(self): try: self.ser = serial.Serial( port='/dev/ttyUSB0', baudrate=19200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_O...
check if check == ";": break self.warteschlange.task_done() self.lock.release() if out == '': out = 'Leere Antwort' return out def schliessen(self): self.ser.close() def main(): doit = Sercomm() # print ("Schalte 1 Band hoch") # doit.schreiben("BU...
Eingegebener Befehl: "+seq+"\n" print "Antwort des Transceivers: "+doit.lesen(seq)+"\n" doit.schliessen() if __name__ == "__main__": main()
rmatsuda/invesalius3
invesalius/gui/dialogs.py
Python
gpl-2.0
189,985
0.004895
# -*- coding: UTF-8 -*- #-------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: [email protected]...
umberDialog(message, value) dlg.SetValue(value) if dlg.ShowModal() == wx.ID_OK: return dlg.GetValue() dlg.Destroy() return 0 class ProgressDialog(object): def __init__(self, parent, maximum, abort=False): self.title = "InVesalius 3" self.msg = _("Loading DICOM files") ...
DAL | wx.PD_CAN_ABORT self.dlg = wx.ProgressDialog(self.title, self.msg, maximum = self.maximum, parent = parent, style = self.style) self.dlg.Bind(wx.EV...
gylian/sickrage
sickbeard/providers/generic.py
Python
gpl-3.0
20,287
0.003648
# coding=utf-8 # Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
if helpers.download_file(url, filename, session=self.session): logger.log(u"Downloading a result from " + self.name + " at " + url) if self.providerType == GenericProvider.TORRENT: logger.log(u"Saved magnet link to " + filename, logger.INFO) el...
True logger.log(u"Failed to download result", logger.WARNING) return False def _verify_download(self, file_name=None): """ Checks the saved file to see if it was actually valid, if not then consider the download a failure. """ # primitive verification of torrents, ...
otger/gfa_thermal_entropySys
gfa_thermal/monitor_system.py
Python
lgpl-3.0
1,028
0.001946
#!/usr/bin/python # -*- coding: utf-8 -*- from entropyfw import System from s_pico_tc08.module import EntropyPicoTc08 from s_tti_cpx.module import EntropyTTiCPX from s_laird_optotec_ot15.module import EntropyLairdOT15ConstantQc from .s_controller.module import Entro
pyController as GFAEntropyController from s_eventlogger.module import EntropyEventLogger from . import config from . import system_names __author__ = 'otger' class SystemMonitorGFAThermal(System): def __init__(self, flask_app):
System.__init__(self, flask_app) self.pico = EntropyPicoTc08(name=system_names.TC08_MOD, channels=[]) self.add_module(self.pico) # self.tticpx = EntropyTTiCPX(name=system_names.TTiCPX_MOD) # self.add_module(self.tticpx) self.elogger = EntropyEventLogger(name=system_names.LOGGER_M...
satybald/twitter-modeling-lda
source code/preprocess.py
Python
mit
5,802
0.027232
#!/usr/bin/python import re, csv, sys from urlparse import urlparse from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, sent_tokenize from nltk.text import TextCollection #process command line arguments if len(sys.argv) < 2: print "ERROR: arg1: must specify the input file" print " ...
'=\'(', '=\'[', 'D;', 'D\':', 'D:<', 'D8', 'D-\':', '):', ']:', ')-:', ']-:', ')=', ']=', ']:<', '>-:'] emots_neg = [emot.lower() for emot in emots_neg] gaz_pos = [] gaz_neg = [] tweets = [] sentiments = [] emots_count = [] punct_count = [] gaz_count = [] words = [] #will contain all non-stop w...
e in gaz_file: line = line.strip() if line != '' and line[0] != ';': gaz_pos.append(line) gaz_file.close() gaz_file = open('negative-words.txt', 'r') for line in gaz_file: line = line.strip() if line != '' and line[0] != ';': gaz_neg.append(line) gaz_file.close() # print some information print '...
ignamv/PlanarProcess
test.py
Python
gpl-3.0
2,927
0.006833
from planarprocess import * from gds_helpers
import * from itertools import cycle xmin, xmax = -5, 5 layers = gds_cross_section('mypmos.gds', [(0,xmin), (0, xmax)], 'gdsmap.map') ['P-Active-We
ll', 'Active-Cut', 'N-Well', 'Metal-2', 'Metal-1', 'P-Select', 'N-Select', 'Transistor-Poly', 'Via1'] wafer = Wafer(1., 5., 0, xmax - xmin) # N-Well nw = layers['N-Well'] wafer.implant(.7, nw, outdiffusion=5., label='N-Well') # Field and gate oxides de = layers['P-Active-Well'] # TODO: channel stop under field oxide...
jonparrott/botocore
tests/unit/test_sns_operations.py
Python
mit
3,318
0.000301
#!/usr/bin/env python # Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights
Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, a...
itions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICU...
maurizi/otm-core
opentreemap/manage_treemap/templatetags/roles.py
Python
agpl-3.0
594
0
from django import template from manage_treemap.views.roles
import options_for_permission from treemap.audit import FieldPermission from treemap.lib.object_caches import role_field_permissions register = template.Library() @register.filter def photo_permission_level(role): photo_perms = role_field_permissions(role, None, 'TreePhoto') if photo_perms: perm =...
else: perm = FieldPermission.READ_ONLY label = dict(FieldPermission.choices)[perm] return perm, label register.filter(options_for_permission)
prologic/spyda
spyda/processors.py
Python
mit
385
0.002597
try: from calais import Calais except ImportError: # pragma: no cover Calais = None # NOQA if Calais is not None: def process_calai
s(content, key): calais = Calais(key) response = calais.analyze(content) people = [entity["name"] for entity in getattr(response, "entities", []) if entity["_type
"] == "Person"] return {"people": people}
benzkji/django-cms
cms/utils/decorators.py
Python
bsd-3-clause
1,191
0.00084
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.utils.http import urlquote from cms.page_rendering import _handle_no_page from cms.utils import get_current_site from cms.utils.page_permissions import user_can
_view_page def cms_perms(func): def inner(request, *args, **kwargs): page = request.current_page
if page: if page.login_required and not request.user.is_authenticated: return redirect_to_login(urlquote(request.get_full_path()), settings.LOGIN_URL) site = get_current_site() if not user_can_view_page(request.user, page, site): return _handle_no_p...
orlenko/bccf
src/pybb/defaults.py
Python
unlicense
3,811
0.00761
# -*- coding: utf-8 -*- import os.path from django.conf import settings from pybb.util import filter_blanks, rstrip_str PYBB_TOPIC_PAGE_SIZE = getattr(settings, 'PYBB_TOPIC_PAGE_SIZE', 10) PYBB_FORUM_PAGE_SIZE = getattr(settings, 'PYBB_FORUM_PAGE_SIZE', 20) PYBB_AVATAR_WIDTH = getattr(settings, 'PYBB_AVATAR_WIDTH'...
pybb.permissions.DefaultPermissionHandler') PYBB_PROFILE_RELATED_N
AME = getattr(settings, 'PYBB_PROFILE_RELATED_NAME', 'pybb_profile')
placiflury/gridmonitor-infocache
infocache/errors/stats.py
Python
bsd-3-clause
593
0.008432
# last modified 10.3.2009 class StatsError(Exception): """ Exception raised for errors resulting from collection of statistical information about the grid. Attributes: expression -- input expression in which error occurr
ed message -- explanation of error """ def __init__(self, expression, message): self.expression = expression self.message = message def desc(self): return self.message class TYPE_ERROR(StatsError): """
Exception raised if type of statistical container is not known.. """ pass
tethysplatform/tethys
tests/unit_tests/test_tethys_apps/test_static_finders.py
Python
bsd-2-clause
2,361
0.001271
import os import unittest from tethys_apps.static_finders import TethysStaticFinder class TestTethysStaticFinder(unittest.TestCase): def setUp(self): self.src_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) self.root = os.path.join(self.src_dir, 'tests', 'apps', ...
self.root, path), ret) def test_find_location_with_prefix_not_in_path(self): prefix = 'tethys_app' path = 'css/main.css' tethys_static_finder = TethysStaticFinder() ret = tethys_static_finder.find_location(self.root, path, prefix) self.assertIsNone(ret) def test_find_...
ss/main.css' tethys_static_finder = TethysStaticFinder() ret = tethys_static_finder.find_location(self.root, path, prefix) self.assertEqual(os.path.join(self.root, 'css/main.css'), ret) def test_list(self): tethys_static_finder = TethysStaticFinder() expected_ignore_patter...