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 |
|---|---|---|---|---|---|---|---|---|
analytics-pros/mozilla-bedrock | bedrock/settings/base.py | Python | mpl-2.0 | 33,383 | 0.000899 | # 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 json
import logging
import platform
from os.path import abspath
from django.utils.functional import lazy
import... | lla-l10n/{}'.format(default_locales_repo)
LOCALES_REPO = config('LOCALES_REPO', default=default_locales_repo)
def get_dev_languages():
try:
return [lang.name for lang in LOCALES_PATH.iterdir()
if lang.is_dir() and lang.name != 'templates']
except OSError:
| # no locale dir
return list(PROD_LANGUAGES)
DEV_LANGUAGES = get_dev_languages()
DEV_LANGUAGES.append('en-US')
# Map short locale names to long, preferred locale names. This
# will be used in urlresolvers to determine the
# best-matching locale from the user's Accept-Language header.
CANONICAL_LOCALES ... |
pigay/COMDIRAC | Interfaces/scripts/dmkdir.py | Python | gpl-3.0 | 1,488 | 0.024866 | #!/usr/bin/env | python
"""
create a directory in the FileCatalog
"""
import os
import DIRAC
from DIRAC.Core.Base import Script
from COMDIRAC.Interfaces import critical
from COMDIRAC.Interfaces import DSession
from COMDIRAC.Interfaces import createCatalog
from COMDIRAC.Interfaces import pathFromArgum | ents
if __name__ == "__main__":
import sys
from DIRAC.Core.Base import Script
Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1],
'Usage:',
' %s Path...' % Script.scriptName,
'Argume... |
RCOS-Grading-Server/HWserver | migration/run_migrator.py | Python | bsd-3-clause | 331 | 0.003021 | """Run the migrator tool thro | ugh its CLI."""
from pathlib import Path
import sys
from migrator import cli
if __name__ == '__main__':
config_path = Path(Path(__file__).parent.resolve(), '..', '..', '..', 'config')
config_path = config_path.resolve() if config_path.exists() else None
cli.run(sys.argv[1 | :], config_path)
|
will-iam/Variant | casepy/eulerRuO2/nNoh131072x1/chars.py | Python | mit | 472 | 0.012712 | import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '../../../'))
import script.rio as io
import script.initial_condition.noh1D as noh1D
# Domain properties
lx = 1.0
ly = 1.0
Nx = 131072
Ny = 1
# S | cheme execution options
T = 0.6
CFL | = 0.5
gamma = 5./3.
BClayer = 1
quantityList = ['rho', 'rhou_x', 'rhou_y', 'rhoE']
def buildme(quantityDict, coords_to_uid, coords_to_bc):
noh1D.build(quantityDict, coords_to_uid, coords_to_bc, Nx, Ny, lx, ly, BClayer)
|
SalesforceFoundation/CumulusCI | cumulusci/tasks/salesforce/Deploy.py | Python | bsd-3-clause | 5,848 | 0.002394 | import pathlib
from typing import Optional
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.utils import process_bool_arg, process_list_arg
from cumulusci.salesforce_api.metadata import ApiDeploy
from cumulusci.salesforce_api.package_zip import MetadataPackageZipBuilder
from cumulusci.tasks.s... | kageVersions/> element from all meta.xml files. The packageVersion element gets added automatically by the target org and is set to whatever version is installed in the org. To disable this, set this option to False"
},
}
name | spaces = {"sf": "http://soap.sforce.com/2006/04/metadata"}
def _init_options(self, kwargs):
super(Deploy, self)._init_options(kwargs)
self.check_only = process_bool_arg(self.options.get("check_only", False))
self.test_level = self.options.get("test_level")
if self.test_level and se... |
jcshen007/cloudstack | test/integration/smoke/misc/test_escalations_templates.py | Python | apache-2.0 | 8,699 | 0.002299 | # 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... | cls.storagetype = 'local'
cls.services["service_offerings"][
"tiny"]["storagetype"] = 'local'
cls.services["disk_offering"]["storagetype"] = 'local'
else:
cls.storagetype = 'shared'
cls.services["service_offerings... | "]["storagetype"] = 'shared'
cls.services["disk_offering"]["storagetype"] = 'shared'
cls.services['mode'] = cls.zone.networktype
cls.services["virtual_machine"][
"hypervisor"] = cls.testClient.getHypervisorInfo()
cls.services["virtual_machine"]["zonei... |
futurice/sforce2flowdock | sforce-show-api-versions.py | Python | gpl-3.0 | 362 | 0 | #! /usr/bin/env python3
import json
from s2f.sforce | import SClient
from s2f import util
"""
Print SalesForce API versions.
Use this to set the version in the config file JSON.
"""
if __name__ == '__main__':
util.setupLogging()
client = SClient(util.SForceCfgFileName, util.SForceTokenFileName)
print(json.dumps(client.getAPIVersi | ons(), indent=2))
|
orian/umo | pdf_scraping.py | Python | mit | 12,546 | 0.012195 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
a='51.01 633.55 Td\n'
b='(LICZBA UPRAWNIONYCH) Tj\n'
re.compile(r'() () Td\\n')
m = re.match(r'(?P<x>[\d\.]+) (?P<y>[\d\.]+) Td\n', a)
print(m.groupdict())
t = re.match(r'\((?P<t>.*)\) Tj\n', b)
print(t.groupdict())
# <codecell>
import json
import re
... | prev = self._prev
if cond != None and not cond(curr._text):
return False
r_val = True
if self._prev:
if move_x>0:
r_val = float(curr._x) >= float(prev._x)+self._d_x
if move_y>0:
r | _val = float(curr._y) <= float(prev._y)-self._d_y
self._prev = curr
self._idx += 1
if not r_val:
return False
val = curr._text
if parser != None:
try:
val = parser(val)
|
turbulenz/turbulenz_local | turbulenz_local/lib/deploy.py | Python | mit | 37,875 | 0.002139 | # Copyright (c) 2010-2014 Turbulenz Limited
"""
Controller class for deploying a game
"""
from urllib3.exceptions import HTTPError, SSLError
from simplejson import dump as json_dump, load as json_load, loads as json_loads, JSONDecodeError
from os import stat, sep, error, rename, remove, makedirs, utime, access, R_OK, ... | edirect=False,
retries=5,
timeout=self.hub_timeout)
else:
self.hub_pool.request('POST',
'/dynami | c/upload/cancel',
fields=fields,
headers=headers,
redirect=False,
retries=5,
timeout=self.hub_timeout)
... |
Kobzol/debug-visualizer | gui/config.py | Python | gpl-3.0 | 2,272 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Jakub Beranek
#
# This file is part of Devi.
#
# Devi 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, version 3 of the License, or
# (at yo... | License
# along with Devi. If not, see <http://www.gnu.org/licenses/>.
#
import os
import paths
from gi.repository import Gtk
from gi.repository import Gdk
class Config(object):
UI_DIR = os.path.join(paths.DIR_ROOT, paths.DIR_RES, "gui")
GUI_MAIN_WINDOW_MENU = None
GUI_MAIN_WINDOW_TOOLBAR = None
... | _MEMORY_CANVAS_TOOLBAR = None
GUI_STARTUP_INFO_DIALOG = None
@staticmethod
def get_gui_builder(path):
return Gtk.Builder.new_from_file(os.path.join(Config.UI_DIR,
path + ".glade"))
@staticmethod
def preload():
Config.UI_DIR = os... |
clejeu03/EWP | core/sessionManager/Project.py | Python | mit | 3,334 | 0.007199 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from core.sessionManager.Video import Video
class Project(object):
def __init__(self, name, path):
super(Project, self).__init__()
self._name = name
self._path = path
self._videos = []
self._sketchBoardVideos = [] #/!\ Unique ... | view after. """
if video in self._sketchBoardVideos:
self._sketchBoardVideos.remove(video)
else :
raise Exception("Can't find the video")
# ---------------------- BUILT-IN FUNCTIONS ------------------------- #
def __str__(self):
#String representation of the cl... | e) + ' / path : ' + str(self._path) + ' / videos : ' + str(len(self._videos))
video = str(self._videos[0])
sketchBoardVideo = str(self._sketchBoardVideos[0])
return describe + video + sketchBoardVideo
def __eq__(self, other):
#Stands for the == compare
if self._name == other... |
spaceone/tehbot | tehbot/plugins/wolframalpha/__init__.py | Python | mit | 2,727 | 0.002567 | from tehbot.plugins import *
import tehbot.plugins as plugins
import wolframalpha
import prettytable
class WolframAlphaPlugin(StandardPlugin):
def __init__(self):
StandardPlugin.__init__(self)
self.parser.add_argument("query", nargs="+")
def initialize(self, dbconn):
StandardPlugin.ini... | mpty_columns(table, nr_cols)
if len(table) < 2:
s2 = " | ".join(table[0])
return s2
pt = prettytable.PrettyTable()
pt.header = False
for line in table:
pt.add_row(line)
s = pt.get_string()
return s
def execute(self, connection, ... | ted:
return self.parser.format_help().strip()
except Exception as e:
return u"Error: %s" % str(e)
txt = "\x0303[Wolfram|Alpha]\x03 "
try:
res = None
misc = []
for p in self.client.query(" ".join(pargs.query)).pods:
... |
Outernet-Project/librarian-analytics | librarian_analytics/data.py | Python | gpl-3.0 | 4,521 | 0 | import calendar
import datetime
import functools
import hashlib
import logging
import uuid
import user_agents
from bitpack import BitStream, BitField, register_data_type
from bitpack.utils import pack, unpack
from bottle_utils.common import to_bytes
from pytz import utc
FIELD_SEPARATOR = '$'
DESKTOP = 1
PHONE = 2
... | o=utc)
def to_utc_timestamp(dt):
"""Converts the passed-in datetime object into a unix UTC timestamp."""
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
msg = "Naive datetime object passed. It is assumed that it's in UTC."
logging.warning(msg)
elif dt.tzinfo != utc:
# loca... | le()))
register_data_type('timestamp', to_utc_timestamp, from_utc_timestamp)
def generate_device_id():
return uuid.uuid4().hex
def generate_user_id():
return uuid.uuid4().hex[:8]
def characterize_agent(ua_string):
ua = user_agents.parse(ua_string)
os_fam = ua.os.family
if ua.is_pc:
r... |
karies/root | tutorials/dataframe/df103_NanoAODHiggsAnalysis.py | Python | lgpl-2.1 | 17,701 | 0.00661 | ## \file
## \ingroup tutorial_dataframe
## \notebook -draw
## \brief An example of complex analysis with RDataFrame: reconstructing the Higgs boson.
##
## This tutorial is a simplified but yet complex example of an analysis reconstructing the Higgs boson decaying to two Z
## bosons from events with four leptons. The da... | Select interesting events with multiple cuts on event properties, e.g., number of leptons, kinematics of the
## leptons and quality of the t | racks.
## 2. Reconstruct two Z bosons of which only one on the mass shell from the selected events and apply additional cuts on
## the reconstructed objects.
## 3. Reconstruct the Higgs boson from the remaining Z boson candidates and calculate its invariant mass.
##
## Another aim of this version of the tutorial is ... |
alkamid/lab-scripts | matplotlib-scripts/matplotFF.py | Python | gpl-2.0 | 9,814 | 0.005199 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import scipy.interpolate
from PIL import Image
matplotlib.use('Qt5Agg')
class matplotFF():
"""A class for plotting far-field measurements of lasers. It requires
the 'x z signal' format, but supports stitched measurements — the data
can b... | rted(z_unique_vals)):
for ix, x in enumerate(sorted(x_unique_vals)):
self.x[iz][ix] = x
self.z[iz][ix] = z
for i in zip(self.xRaw, self.zRaw, self.sigRaw):
if (abs(i[0]-x) < stage_tolerance) and (abs(i[1]-z) < stage_tole... | gnal[iz][ix] = i[2]
break
else:
self.x = self.xRaw.reshape((self.zLen,self.xLen))
self.z = self.zRaw.reshape((self.zLen,self.xLen))
self.signal = self.sigRaw.reshape((self.zLen,self.xLen))
# normalise the signal to [0, 1]
self.sig... |
hayd/pattern | pattern/text/nl/__main__.py | Python | bsd-3-clause | 521 | 0.001919 | #### PATTERN | NL | PARSER COMMAND-LINE ##################################
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
##############################################################... | m .__init__ import co | mmandline, parse
commandline(parse)
|
mbouchar/xc2424scan | src/xc2424scan/utils/test.py | Python | gpl-2.0 | 620 | 0.003226 | #!/usr/bin/python
import socket
HOST = raw_input("enter scanner ip : ")
PORT = 14882
if __name__ == "__main__":
socks = socket.socket()
socks.connect((HOST, PORT))
socks.settimeout(1)
try:
while T | rue:
command = ra | w_input("# ")
if command != "":
socks.send("%s\n" % command)
try:
data = socks.recv(1024)
print "Received", repr(data)
except socket.timeout:
pass
except KeyboardInterrupt:
pass
except Exception, e:
... |
ppizarror/korektor | bin/langeditor/_import.py | Python | gpl-2.0 | 1,200 | 0.003342 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IMPORT
Permite adaptar | un exportado traducido a uno válido para hoa
|
Autor: PABLO PIZARRO @ github.com/ppizarror
Fecha: 2014-2015
Licencia: GPLv2
"""
__author__ = "ppizarror"
# Importación de librerías
import os
import sys
reload(sys)
# noinspection PyUnresolvedReferences
sys.setdefaultencoding('UTF8') # @UndefinedVariable
try:
namearchive = raw_input("Ingrese el... |
merelcoin/merelcoin | test/functional/rpc_fundrawtransaction.py | Python | mit | 34,177 | 0.009509 | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from decimal import Decimal
from test_framework.test_framework imp... | #
# simple test with two coins #
##############################
inputs = [ ]
outputs = { self.nodes[0].getnewaddress() : 2.6 }
rawtx = self.nodes[2] | .createrawtransaction(inputs, outputs)
dec_tx = self.nodes[2].decoderawtransaction(rawtx)
rawtxfund = self.nodes[2].fundrawtransaction(rawtx)
fee = rawtxfund['fee']
dec_tx = self.nodes[2].decoderawtransaction(rawtxfund['hex'])
assert(len(dec_tx['vin']) > 0)
assert_equa... |
icomms/wqmanager | apps/receiver/__init__.py | Python | bsd-3-clause | 1,031 | 0.007759 | import logging
from django.http import HttpResponse
from receiver.submitresponse import SubmitResponse
def duplicate_attachment(way_handled, additional_params):
'''Return a custom http response associated the handling
of the xform. In this case, telling the sender that
they sub... | tatus="Duplicate Submission.",
submit_id=way_handled.submission.id,
**additional_params)
return response.to_response()
except Exception, e:
logging.error("Problem in properly responding to | instance data handling of %s" %
way_handled)
|
snegovick/dswarm_simulator | path_finding/smoothing_algorithms.py | Python | gpl-3.0 | 6,317 | 0.008073 | import math
from map_utils import *
def calc_field_grad(m, pt):
w = len(m[0])
h = len(m)
if pt[0]>=w or pt[0]<0:
return None
if pt[1]>=h or pt[1]<0:
return None
px_s = pt[0]-1
px_e = pt[0]+1
if px_s>=w or px_s<0:
px_s = pt[0]
if px_e>=w or px_e<0:
... |
if __name__=="__main__":
m = [[ 0, 0.1, 0.2, 0.3],
[ 0.1, 0.2, 0.3, 0.4],
[ 0.2, 0.3, 0.4, 0.5],
[ 0.3, 0.4, 0.5, 0.6]]
path = [(0, 3), (1,3), (2, 3), (2, 2), (2, 1), (2, 0), (3, 0)]
pri | nt "field gradient:", calc_field_grad(m, (1, 1))
orig_path = path[:]
path = smooth_path_with_field(path, m, 1)
print "after:"
for p in path:
print p
import Image, ImageDraw
scale = 50
size = 2000
offset = 10
im = Image.new('RGBA', (size, size), (255, 255, 255, ... |
crf1111/Bio-Informatics-Learning | Bio-StrongHold/src/Enumerating_Unrooted_Binary_Trees.py | Python | mit | 3,854 | 0.003114 | class Node():
def __init__(self, name):
self.name = name
def __str__(self):
if self.name is not None:
return self.name
else:
return "internal_{}".format(id(self))
class Edge():
def __init__(self, node1, node2):
self.nodes = [node1, node2]
def __... | des[0]], node_conversion[edge.nodes[1]]) for edge in self.edges]
new_tree = Tree(new_nodes, new_edges)
return new_tree
def enumerate_trees(leaves):
assert(len(leaves) > 1)
if len(leaves) == 2:
n1, | n2 = leaves
t = Tree()
t.nodes = [Node(n1), Node(n2)]
t.edges = [Edge(t.nodes[0], t.nodes[1])]
return [t]
elif len(leaves) > 2:
# get the smaller tree first
old_trees = enumerate_trees(leaves[:-1])
new_leaf_name = leaves[-1]
new_trees = []
# f... |
yeyanchao/calibre | src/calibre/gui2/preferences/look_feel_ui.py | Python | gpl-3.0 | 19,303 | 0.004403 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yc/code/calibre/calibre/src/calibre/gui2/preferences/look_feel.ui'
#
# Created: Thu Oct 25 16:54:55 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui... | ist"))
self.opt_book_list_tooltips.setObjectName(_fromUtf8("opt_book_list_tooltips"))
self.gridLayout_9.addWidget(self.opt_book_list_tooltips, 5, 0, 1, 1)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(I("lt.p | ng"))), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.tabWidget.addTab(self.tab, icon, _fromUtf8(""))
self.tab_4 = QtGui.QWidget()
self.tab_4.setObjectName(_fromUtf8("tab_4"))
self.gridLayout_12 = QtGui.QGridLayout(self.tab_4)
self.gridLayout_12.setObjectName(_fromUtf8("gridLayout_12... |
AlphaCluster/NewsBlur | vendor/readability/encoding.py | Python | mit | 2,034 | 0.004916 | import re
import chardet
import sys
RE_CHARSET = re.compile(br'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
RE_PRAGMA = re.compile(br'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
RE_XML = re.compile(br'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
CHARSETS = {
'big5': 'big5hkscs',
'gb2312': 'gb18030... | d encodings
for declared_encoding in declared_encodings:
try:
if sys.version_info[0] == 3:
# declared_encoding will actually be bytes but .decode() only
# accepts `str` type. Decode blindly with ascii because no one should
# ever use non-ascii char... | ed_encoding.decode('ascii', 'replace')
encoding = fix_charset(declared_encoding)
# Now let's decode the page
page.decode()
# It worked!
return encoding
except UnicodeDecodeError:
pass
# Fallback to chardet if declared encodings fail
... |
lucienimmink/scanner.py | scanner/_utils.py | Python | mit | 1,322 | 0 | #!/usr/bin/env python
# -*- coding: utf8 -*-
class Time:
def ums(i, ignoreZero=True):
i = float(i)
hours = int(i / 3600)
rest = i % 3600
minutes = int(rest / 60)
seconds = int(rest % 60)
if hours < 10:
hours = "0" + str(hours)
if minutes < 10:
... | 8859-1']
encodings = [encoding] + fallback_encodings
for enc in encodings:
try:
return bstr.decode(enc)
except UnicodeDecodeError:
pas | s
except AttributeError:
pass
# Finally, force the unicode
return bstr.decode(encoding, 'ignore')
|
Chilledheart/chromium | content/test/gpu/gpu_tests/webgl_robustness.py | Python | bsd-3-clause | 2,628 | 0.003044 | # 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.
from telemetry import benchmark
from telemetry.page import page
from telemetry.page import page_test
from telemetry.story import story_set as story_set_module... | robustnessTestHarness.notifyFinished();
}
robustnessTestHarness.notifyFinished = function() {
// The test may fail in unpredictable ways depending on when the context is
// lost. We ignore such errors and only require that the browser doesn't
// crash.
webglTestHarness._allTestSucc | eeded = true;
// Notify test completion after a delay to make sure the browser is able to
// recover from the lost context.
setTimeout(webglTestHarness.notifyFinished, 3000);
}
window.confirm = function() {
robustnessTestHarness.initialize();
robustnessTestHarness.runTestLoop();
return fals... |
ndim/weight-calendar-grid | weight_cal_grid/log.py | Python | mit | 5,614 | 0.004453 | ########################################################################
"""Generic and custom log message infrastructure"""
########################################################################
"""\
log - simple logging module
This is so much simpler than Python's stock 'logging' module and thus
much less error... | xc_info = sys.exc_info()
traceback.print_exception(
exc_info[0], exc_info[1], exc_info[2],
None, sy | s.stderr)
if msg:
p = {}
if args:
p['message'] = msg % args
else:
p['message'] = msg
p['prog'] = prog
p['catmsg'] = {
DATA: 'DATA: ',
DEBUG: 'DEBUG: ',
VERBOSE: '... |
public/flake8-import-order | tests/test_cases/missing_newline.py | Python | lgpl-3.0 | 184 | 0.01087 | # appnexus cryptography edited google pep8 smarkets
import ast
# This comment should not prevent | the I201 below, it is not a newline.
import X # I201
import flake8_im | port_order # I201
|
Khroki/MCEdit-Unified | pymclevel/pocket.py | Python | isc | 15,372 | 0.001821 | from level import FakeChunk
import logging
from materials import pocketMaterials
from mclevelbase import ChunkNotPresent, notclosing
from nbt import TAG_List
from numpy import array, fromstring, zeros
import os
import struct
# values are usually little-endian, unlike Minecraft PC
logger = logging.getLogger(__name__)
... | rmat()
# start=sectorStart, end=sectorStart + sectorCount, index=index, offset=offset)
#
# compressedData = self._readChunk(cx, cz)
# if compressedData is None:
# | raise RegionMalformed("Failed to read chunk data for {0}".format((cx, cz)))
#
# format, data = self.decompressSectors(compressedData)
# chunkTag = nbt.load(buf=data)
# lev = chunkTag["Level"]
# xPos = lev["xPos"].value... |
robmcmullen/peppy | peppy/hsi/plotters.py | Python | gpl-2.0 | 9,351 | 0.008662 | # peppy Copyright (c) 2006-2010 Rob McMullen
# Licenced under the GPLv2; see http://peppy.flipturn.org for more info
"""Plotting minor modes for HSI major mode
"""
import os, struct, mmap
from cStringIO import StringIO
import wx
from peppy.actions.minibuffer import *
from peppy.actions import *
from peppy.minor imp... | traceback
dprint(traceback.format_exc())
self.last_coords = coords
def redisplayProxies(self):
self.updateProxies(*self.last_coords)
class SpectrumXLabelAction(HSIActionMixin, RadioAction):
"""Change the X axis label of the | spectrum plot"""
name = "X Axis Label"
def getIndex(self):
cubeview = self.mode.cubeview
labels = cubeview.getAvailableXAxisLabels()
minor = self.popup_options['minor_mode']
current = minor.xlabel
return labels.index(current)
def getItems(self):
cubeview = ... |
histograph/aws | staging/scripts/register_staging.py | Python | mit | 947 | 0.026399 | from boto.connection import AWSAuthConnection
import os
class ESConnection(AWSAuthConnection):
def __init__(self, region, **kwargs):
super(ESConnection, self).__init__(**kwargs)
self._set_auth_region_name(region)
self._set_auth_service_name("es")
def _required_auth_capability(self):
return ['hmac-v4']
if ... | access_key=os.environ['AWS_SECRET_ACCESS_KEY'],
is_secure=False)
print('Registering Snapshot Repository')
resp = client.make_request(method='POST',
path='/_snapshot/histograph-dump',
data='{"type": "s3","settings": { "bucket": "histograph-es-dump","region": "eu-central-1","role_arn": "arn:aws:iam::44191550... | )
|
jaredkoontz/leetcode | Python/random-pick-index.py | Python | mit | 1,340 | 0.001493 | # Time: O(n)
# Space: O(1)
# Given an array of integers with possible duplicates,
# randomly output the index of a given target number.
# You can assume that the given target number must exist in the array.
#
# Note:
# The array | size can be very large.
# Solution that uses too much extra space will not pass the judge.
#
# Example:
#
# int[] nums = new int[] {1,2,3,3,3};
# Solution solution = new Solution(nums);
#
# // pick(3) should return either index 2, 3, or 4 randomly.
# Each index should have equal probability of returning.
# solution.pic... | 1);
from random import randint
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.__nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
reservo... |
tboyce021/home-assistant | tests/components/bayesian/test_binary_sensor.py | Python | apache-2.0 | 24,735 | 0.000323 | """The test for the bayesian sensor platform."""
import json
from os import path
from homeassistant import config as hass_config
from homeassistant.components.bayesian import DOMAIN, binary_sensor as bayesian
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
fro... | et("observations")
assert 0.2 == state.attributes.get("p | robability")
assert state.state == "off"
hass.states.async_set("sensor.test_monitored", "off")
await hass.async_block_til |
bcrochet/eve | eve/tests/io/mongo.py | Python | bsd-3-clause | 14,202 | 0 | # -*- coding: utf-8 -*-
from datetime import datetime
import simplejson as json
from bson import ObjectId
from bson.dbref import DBRef
from cerberus import SchemaError
from unittest import TestCase
from eve.io.mongo import Validator, Mongo, MongoJSONEncoder
from eve.io.mongo.parser import parse, ParseError
from eve.t... | ParseError, parse, 'a | 2')
class TestMongoValidator(TestCase):
def test_unique_fail(self):
""" relying on POST and PATCH tests since we don't have an active
app_context running here """
pass
def test_unique_success(self):
""" relying on POST and PATCH tests since we don't hav... | pass
def test_objectid_fail(self):
schema = {'id': {'type': 'objectid'}}
doc = {'id': 'not_an_object_id'}
v = Validator(schema, None)
self.assertFalse(v.validate(doc))
self.assertTrue('id' in v.errors)
self.assertTrue('ObjectId' in v.errors['id'])
def te... |
tgbugs/pyontutils | neurondm/neurondm/models/phenotype_direct.py | Python | mit | 4,341 | 0.008754 | #!/usr/bin/env python3
from pathlib import Path
import rdflib
from pyontutils.core import makeGraph
from pyontutils.utils import relative_path
from pyontutils.namespaces import makePrefixes, TEMP
from pyontutils.namespaces import rdf, rdfs, owl
from neurondm import *
from neurondm.lang import *
from neurondm.core impor... | e_path(__file__))
#Neuron.out_graph = graphBase.out_graph # each subclass of graphBase has a distinct out graph IF it was set manually
#Neuron.out_graph | = rdflib.Graph()
#ng = makeGraph('', prefixes={}, graph=Neuron.out_graph)
#ng.filename = Neuron.ng.filename
Neuron.mro()[1].existing_pes = {} # wow, new adventures in evil python patterns mro()[1]
dns = [Neuron(*d.pes) for d in set(dns)] # TODO remove the set and use this to test existing bags?
#f... |
undertherain/benchmarker | benchmarker/kernels/dimenet/pytorch.py | Python | mpl-2.0 | 528 | 0 | from benchmarker.kernels.helpers_torch | import Regression
from torch_geometric.nn import DimeNet
def get_kernel(params):
# TODO: make these parameters
net = DimeNet(
hidden_channels=params["problem"]["hidden_channels"],
out_channels=1,
num_blocks=6,
num_bilinear=8,
num_spherical=7,
num_radial=6,
... | ession(params["mode"], net)
|
bearicc/python-wavelet-transform | cwt_demo.py | Python | agpl-3.0 | 380 | 0 | import scipy as sp
from mycwt | import cwt
pi = sp.pi
mu = [100.0, 500.0, 900.0]
sigma = [5.0, 10.0, 20.0]
a = [3.0, 1.0, 0.5]
t = sp.arange(0, 1000)*1.0
x = sp.zeros(t.shape)
for i in range(0, len(mu)):
x += 1/sp.sqrt(2*pi)/sigma[i]*sp.exp(-0.5*((t-mu[i])/sigma[i])**2)
smax = 128
wname = 'bior2.6'
scale | s = sp.arange(1, smax+1)*1.0
coefs = cwt(x, scales, wname, bplot=True)
|
nekohayo/snowy | lib/django_openid_auth/models.py | Python | agpl-3.0 | 2,355 | 0.000425 | # django-openid-auth - OpenID integration for django.contrib.auth
#
# Copyright (C) 2007 Simon Willison
# Copyright (C) 2008-2010 Canonical Ltd.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions o... | OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from django.contrib.auth.models import User
from django.db impor | t models
class Nonce(models.Model):
server_url = models.CharField(max_length=2047)
timestamp = models.IntegerField()
salt = models.CharField(max_length=40)
def __unicode__(self):
return u"Nonce: %s, %s" % (self.server_url, self.salt)
class Association(models.Model):
server_url = models.... |
PeachstoneIO/peachbox | tutorials/tutorial_movie_reviews/tasks/importer.py | Python | apache-2.0 | 1,848 | 0.010823 | # general
import time
# peachbox imports
from peachbox.task import Task
from peachbox.connector import sink, source
from peachbox.pipeline import Chain, Validator
# tutorial
from pipelines.importer import UserReviewEdge, ProductReviewEdge, ReviewProperties
import model.master
class ImportMovieReviews(ScheduledTask):
... | ges, 'model':model.master.UserReviewEdge},
{'data':product_review_edges, 'model':model.master.ProductReviewEdge},
{'data':review_prop | erties, 'model':model.master.ReviewProperties}])
# Payload is sent with 'Finished Event'
self.payload = {'import_finished':int(time.time()), 'latest_kafka_offset':self.source.latest_offset}
|
ThomasBrouwer/BNMTF | data_toy/bnmf/generate_bnmf.py | Python | apache-2.0 | 3,430 | 0.032362 | """
Generate a toy dataset for the matrix factorisation case, and store it.
We use dimensions 100 by 50 for the dataset, and 10 latent factors.
As the prior for U and V we take value 1 for all entries (so exp 1).
As a result, each value in R has a value of around 20, and a variance of 100-120.
For contrast, the San... | u)
# Try to generate M
M = try_generate_M(I,J,fraction_unknown,attempts=1000)
# Store all matrices in text files
numpy.savetxt(open(output_folder+"U.txt",'w'),U)
numpy.savetxt(open(output_folder+"V.txt",'w'),V)
numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R)
numpy.savetx... | Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max())
fig = plt.figure()
plt.hist(R.flatten(),bins=range(0,int(R.max())+1))
plt.show() |
portfors-lab/sparkle | test/tests/gui/plotting/test_protocol_display.py | Python | gpl-3.0 | 3,063 | 0.001306 | import sys
import time
import numpy as np
from sparkle.QtWrapper.QtGui import QApplication
from sparkle.gui.plotting.protocoldisplay import ProtocolDisplay
from test.sample import samplewav
PAUSE = 0
class TestProtocolDisplay():
def setUp(self):
self.t = np.arange(200)
def data_func(self, f):... | '].viewRange()[0], display.responsePlots['chan2'].viewRange()[0], display.specPlot.viewRange()[0]
assert lims == display.responsePlots['chan0'].viewRange()[0] \
== display.responsePlots['chan2'].viewRange()[0] \
== display.specPlot.viewRange()[0]
def test_add_remove_... | ponsePlot('chan1', 'chan2')
assert display.responsePlotCount() == 3
display.removeResponsePlot('chan1', 'chan2')
assert display.responsePlotCount() == 1
display.addResponsePlot('chan1')
assert display.responsePlotCount() == 2
display.removeResponsePlot('chan0', 'chan1'... |
Ninad998/FinalYearProject | django_app/migrations/0001_initial.py | Python | mit | 1,051 | 0.003806 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-21 07:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import m | igrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
|
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=... |
Timdawson264/acd_cli | acdcli/cache/__init__.py | Python | gpl-2.0 | 43 | 0.023256 | __al | l__ = | ('db', 'format', 'query', 'sync') |
Elhodred/python-digitaloceanmanager | doma.py | Python | lgpl-3.0 | 4,258 | 0.005402 | #!/usr/bin/env python
import argparse
import ConfigParser
import os.path
import digitaloceanmanager
import getpass
from passlib.hash import sha512_crypt
token = None
user = None
passwd = None
ssh_port = None
if __name__ == "__main__":
config = ConfigParser.RawConfigParser()
if (os.path.isfile('doma.cfg')):
... | parsers.add_parse | r('shutdown', help='shutdown a droplet')
parser_shutdown.add_argument('id', help='id of the droplet to shutdown')
parser_shutdown.set_defaults(func=manager.shutdown_droplet)
# List available images
parser_images = subparsers.add_parser('images', help='list all images')
parser_images.set_defaults(fu... |
jeongyoonlee/Kaggler | tests/conftest.py | Python | mit | 1,121 | 0.000892 | import numpy as np
import pandas as pd
import pytest
from .const import RANDOM_SEED, TARGET_COL
N_CATEGORY = 50
N_OBS = 10000
N_CAT_FEATURE = 10
N_NUM_FEATURE = 5
@pytest.fixture(scope="module")
def generate_data():
generated = False
def _generate_data():
if not generated:
assert N_C... | num[:, 1]
- np.log1p(np.exp(X_num[:, 1] + X_num[:, 2]))
+ 10 | * (X_cat[:, 0] == 0).astype(int)
+ np.random.normal(scale=0.01, size=N_OBS)
)
return df
yield _generate_data
|
BackupTheBerlios/tops | totalopenstation/output/tops_sql.py | Python | gpl-3.0 | 2,442 | 0.00041 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# filename: tops_sql.py
# Copyright 2008-2010 Stefano Costa <steko@iosa.it>
#
# This file is part of Total Open Station.
#
# Total Open Station is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by ... | e input point.
At this moment the column names are fixed, but they could change in the
future. The default names are reasonable.'''
params = {
'wkt': to_wkt(point),
'tablename': tablename,
'pid': point[0],
| 'text': point[4]}
sql_string = "INSERT INTO %(tablename)s" % params
sql_string += "(point_id, point_geom, point_text) VALUES"
sql_string += "(%(pid)s,GeomFromText('%(wkt)s'),'%(text)s');\n" % params
return sql_string
def to_wkt(point):
pid, x, y, z, text = point
wkt_representation = 'POINT(%... |
wizardofozzie/simpybtc | btc/mnemonic.py | Python | mit | 7,793 | 0.011549 | #!/usr/bin/python
from btc.main import *
#from btc.pyspecials import *
# get wordlists
def open_wordlist(wordlist):
try:
if wordlist in ('Electrum1', 'electrum1', 'electrum'):
from btc._electrum1wordlist import ELECTRUM1_WORDLIST
assert len(ELECTRUM1_WORDLIST) == 1626
r... | ks, each indexing a 2048 (=2**11)
word list (in BIP39WORDS)
hexseed: hexadecimal bytes or bytearray object
>>> bip | 39_hex_to_mnemonic('eaebabb2383351fd31d703840b32e9e2')
'turtle front uncle idea crush write shrug there lottery flower risk shell'
"""
try: BIP39WORDS = open_wordlist('bip39')
except: BIP39WORDS = download_wordlist('bip39')
if isinstance(hexvalue, string_or_bytes_types) and re.match('^[0-9a-fA-F]... |
savoirfairelinux/num2words | tests/test_ko.py | Python | lgpl-2.1 | 4,547 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2003, Taro Ogawa. All Rights Reserved.
# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved.
# This library is free software; you can redistribute it and/or
# modify it under the terms | of the GNU Lesser General Public
# Lice | nse as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ... |
rtts/qqq | qqq/collections/urls.py | Python | gpl-3.0 | 730 | 0.005479 | from django.conf.urls.defaults import *
from django.utils.translation import ugettext as _
urlpatterns = patterns('qqq.collections.views',
(r'^%s/$' % _('collecti | ons'), 'collections'),
(r'^%s/(\d+)/$' % _('collection'), 'saved_collection'),
(r'^%s/(\d+)/([^/]+)/$' % _('collection'), 'saved_collection'),
(r'^%s/$' % _('vote-for-collection'), 'vote_for_collection'),
(r'^%s/$' % _('add-collection'), 'add_collection'),
(r'^%s/$' % _('collection'), 'collection'),
(r'^%s/... | s/%s\.(\w{3})$' % (_('collection'), _('download')), 'download'),
(r'^%s/(\d+)/%s\.(\w{3})$' % (_('collection'), _('download')), 'download_saved_collection'),
)
|
fugwenna/bunkbot | src/core/event_hook.py | Python | mit | 537 | 0.001862 | class EventHook(object):
"""
Basi | c "event system" from:
http://www.voidspace.org.uk/python/weblog/arch_d7_2007_02_03.shtml#e616
"""
def __init__(self):
self.__handlers = []
def __iadd__(self, handler):
self.__handlers.append(handler)
return self
def __isub__(self, handler):
self.__handle... | await handler(*args, **keywargs) |
nburn42/tensorflow | tensorflow/contrib/boosted_trees/examples/boston.py | Python | apache-2.0 | 6,159 | 0.006495 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | er.add_argument(
"--l2", type=float, default=1.0, help="l2 regularization per batch.")
parser.add_argument(
"--learning_rate",
type=float,
default=0.1,
help="Learning rate (shrinkage weight) with which each new tree is added."
)
| parser.add_argument(
"--num_trees",
type=int,
default=None,
required=True,
help="Number of trees to grow before stopping.")
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
|
Arcanemagus/SickRage | sickbeard/providers/speedcd.py | Python | gpl-3.0 | 7,229 | 0.003182 | # coding=utf-8
# Author: Dustyn Gibson <miigotu@gmail.com>
#
# URL: https://sick-rage.github.io
#
# 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 ... | 'c49': 1, # TV | /HD
'c50': 1, # TV/Sports
'c52': 1, # TV/B-Ray
'c55': 1, # TV/Kids
'search': '',
}
# Units
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def process_column_header(td):
result = ''
img = td.find('img')
... |
tadgh/ArgoRevisit | third_party/nltk/sourcedstring.py | Python | apache-2.0 | 54,572 | 0.00317 | # Nat | ural Language Toolkit: Sourced Strings
#
# Copyrigh | t (C) 2001-2009 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
X{Sourced strings} are strings that are annotated with information
about the location in a document where they were originally found.
Sourced strings are subclassed from ... |
hongzhouye/frankenstein | sgscf/sgopt.py | Python | bsd-3-clause | 6,925 | 0.002455 | """Gradient descent
"""
import numpy as np
from frankenstein.tools.perf_utils import TIMER
from pyscf.lib import logger
""" Helper functions
"""
def get_gHp_fd(get_grad, p, order=1, eps=1.E-4):
""" Compute gradient-Hessian product using finite difference
Inps:
get_grad (callable):
gra... | mf.back_to_origin()
mf.ov = np.zeros([mf.ov_size])
| mf.ov[i] = eps
mf.update_all()
mf.ov[i] = 0.
return mf.get_grad_gdm()
self.timer.start(0)
mf.save_new_origin()
H = np.zeros([mf.ov_size]*2)
for i in range(mf.ov_size):
if self.fd == 1:
H[i] = (dphi(i,self.eps) - g) / sel... |
mercycorps/TolaActivity | tola/forms.py | Python | apache-2.0 | 3,887 | 0.004116 | from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.bootstrap import *
from crispy_forms.layout import Layout, Submit, Reset, Div
from django import forms
from django.contrib.auth.forms import UserCreationForm
from workflow.models import TolaUser
from django.contrib.auth.model... | 'last_name','email','username']
def __init__(self, *args, **kwargs):
super(NewUserRegistrationForm, self).__init__(*args, **kwargs)
helper = FormHelper()
helper.form_method = 'post'
helper.form_class = 'form-ho | rizontal'
helper.label_class = 'col-sm-2'
helper.field_class = 'col-sm-6'
helper.form_error_title = 'Form Errors'
helper.error_text_inline = True
helper.help_text_inline = True
helper.html5_required = True
helper.form_tag = False
class NewTolaUserRegistrationForm(forms.ModelForm):
"""
... |
joergdietrich/astropy | astropy/vo/validator/tests/test_validate.py | Python | bsd-3-clause | 3,067 | 0.000652 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for `astropy.vo.validator.validate`.
.. note::
This test will fail if external URL query status
changes. This is beyond the control of AstroPy.
When this happens, rerun or update the test.
"""
from __future__ import absolute_import,... | Database.from_json(fname2)
assert db1.list_catalogs() == db2.list_catalogs()
@pytest.mark.parametrize(('parallel'), [True, False])
def test_validation(self, parallel):
if os.path.exists(self.out_dir):
shutil.rmtree(self.out_dir)
validate.check_c | onesearch_sites(
destdir=self.out_dir, parallel=parallel, url_list=None)
for val in self.filenames.values():
self._compare_catnames(get_pkg_data_filename(
os.path.join(self.datadir, val)),
os.path.join(self.out_dir, val))
@pytest.mark.parametrize(('p... |
yantrabuddhi/FreeCAD | src/Mod/OpenSCAD/OpenSCADUtils.py | Python | lgpl-2.1 | 24,151 | 0.02385 | #***************************************************************************
#* *
#* Copyright (c) 2012 Sebastian Hoogen <github@sebastianhoogen.de> *
#* *
#* This pr... | if stdoutd.strip():
FreeCAD.Console.PrintMessage(stdoutd+u'\n')
| return stdoutd
osfilename = FreeCAD.ParamGet(\
"User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
GetString('openscadexecutable')
if osfilename and os.path.isfile(osfilename):
if not outputfilename:
dir1=tempfile.gettempdir()
if keepname:
outp... |
kailIII/emaresa | trunk.pe.bk/l10n_pe_vat/__init__.py | Python | agpl-3.0 | 1,401 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com).
#
# WARNING: This program as such is intended to be used by professional
# programmers who take t... | ces resulting from its eventual inadequacies and bugs
# En | d users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Softwa... |
Joergen/olympia | sites/identitystage/settings_base.py | Python | bsd-3-clause | 5,553 | 0.00036 | """private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.s | ettings_base import (
CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING, CSP_SCRIPT_SRC,
CSP_FRAME_SRC)
from .. import splitstrip
import private_base as private
ENGAGE_ROBOTS = False
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = private.EMAIL_HOST
DEBUG = False
TEMPLATE_DEBUG = D... | KEY
ADMINS = ()
DATABASES = {}
DATABASES['default'] = dj_database_url.parse(private.DATABASES_DEFAULT_URL)
DATABASES['default']['ENGINE'] = 'mysql_pool'
DATABASES['default']['OPTIONS'] = {'init_command': 'SET storage_engine=InnoDB'}
DATABASES['slave'] = dj_database_url.parse(private.DATABASES_SLAVE_URL)
DATABASES['s... |
DXCanas/kolibri | kolibri/core/content/apps.py | Python | mit | 410 | 0 | from __future__ import absolut | e_import
from __future__ import print_function
from __future__ import unicode_literals
from django.apps import | AppConfig
class KolibriContentConfig(AppConfig):
name = 'kolibri.core.content'
label = 'content'
verbose_name = 'Kolibri Content'
def ready(self):
from kolibri.core.content.utils.sqlalchemybridge import prepare_bases
prepare_bases()
|
mzdaniel/oh-mainline | vendor/packages/twisted/doc/core/howto/listings/TwistedQuotes/pbquote.py | Python | agpl-3.0 | 193 | 0.010363 | from twisted.spread import pb
class QuoteReader(pb.Root):
|
def __init__(self, quoter):
self.quoter = quoter
def remote_nextQuote(self):
return self.quoter.getQuote()
| |
FedeMPouzols/Savu | doc/source/files_and_images/example_test.py | Python | gpl-3.0 | 1,241 | 0 | # - | *- coding: utf-8 -*-
# Copyright 2014 Diamond Light Source Ltd.
#
# 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 appli... | ess or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. module:: r1
:platform: r2
:synopsis: r3
.. moduleauthor:: r4
"""
import unittest
import tempfile
import savu.test.test_utils as tu
from savu.test.plugin_runner_test import run_protec... |
ops-org/sistema-ops-backend | parlamentar/models.py | Python | gpl-3.0 | 772 | 0.001295 | fr | om django.db import models
class Profissao(models.Model):
nome = models.CharField(max_length=128)
class Partido(models.Model):
nome = models.CharField(max_length=128)
sigla = models.CharField(max_length=32)
class Deputado(models.Model):
DEPUTADO_SEXO_CHOICES = | (
('m', 'Masculino'),
('f', 'Feminino')
)
nome = models.CharField(max_length=1024)
nome_civil = models.CharField(max_length=254, null=True, blank=True)
email = models.EmailField()
profissao = models.ForeignKey(Profissao, related_name='deputados')
sexo = models.CharField(max_leng... |
mpihlak/skytools-dev | setup_skytools.py | Python | isc | 1,526 | 0.017038 | #! /usr/bin/env python
# this script does not perform full installation,
# it is meant for use from Makefile
import sys, os.path, re
from distutils.core import setup
from distutils.extension import Extension
# check if configure has run
if not os.path.isfile('config.mak'):
print "please run ./configure && make f... | are_dup_files.append('sql/txid/txid.sql')
# run actual setup
setup(
name = "skytools",
license = "BSD",
version = ac_ver,
maintainer = "Marko Kreen",
maintainer_email = "markokr@gmail.com",
url = "http://pgfoundry.org/projects/skytools/",
package_dir = {'': 'python'},
packages = ['skyto... | hon/conf/wal-master.ini',
'python/conf/wal-slave.ini',
]),
('share/skytools' + sfx, share_dup_files)],
ext_modules=[Extension("skytools._cquoting", ['python/modules/cquoting.c'])],
)
|
dturner-tw/pants | src/python/pants/fs/archive.py | Python | apache-2.0 | 5,886 | 0.009004 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from abc i... | es as regular files.
# This method should work on for python 2.6-3.x.
# TODO(Eric Ayers) Pants no longer builds with python 2.6. Can this be removed?
if not name.endswith(b'/'):
if (not filter_func or filter_func(name)):
archive_file.extract(name, outdir)
def __init__(se... | lf, basedir, outdir, name, prefix=None):
zippath = os.path.join(outdir, '{}.{}'.format(name, self.extension))
with open_zip(zippath, 'w', compression=self.compression) as zip:
# For symlinks, we want to archive the actual content of linked files but
# under the relpath derived from symlink.
fo... |
BelgianBiodiversityPlatform/Astapor | website/specimens/management/commands/full_import.py | Python | bsd-2-clause | 792 | 0.005051 | from django. | core import management
from ._utils | import AstaporCommand
class Command(AstaporCommand):
help = 'Call other commands in sequence to perform the full data import and initial processing.'
def add_arguments(self, parser):
parser.add_argument('specimen_csv_file')
parser.add_argument('taxonomy_csv_file')
def handle(self, *args,... |
praekelt/molo | molo/core/migrations/0004_configure_root_page.py | Python | bsd-2-clause | 1,214 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def configure_root_page(apps, schema_editor):
# Get models
ContentType = apps.get_model('conte | nttypes.ContentType')
Site = apps.get_model('wagtailcore.Site')
Main = apps.get_model('core.Main')
HomePage = apps.get_model('core.HomePage')
# Delete the default homepage
HomePage.objects.all().delete()
# Create content type for main model
main_content_type, created = ContentType.objects.... | ",
slug='main',
content_type=main_content_type,
path='00010001',
depth=2,
numchild=0,
url_path='/home/',
)
# Create a site with the new homepage set as the root
Site.objects.all().delete()
Site.objects.create(
hostname='localhost', root_page=main,... |
jcurry/ZenPacks.community.PredictiveThreshold | ZenPacks/community/PredictiveThreshold/interfaces.py | Python | gpl-2.0 | 2,440 | 0.004098 | ##########################################################################
# Author: Jane Curry, jane.curry@skills-1st.co.uk
# Date: April 19th, 2011
# Revised:
#
# interfaces.py for Predictive Threshold ZenPack
#
# This program can be used under the GNU General Public License version 2
#... | Count'))
# alpha = schema.Text(title=_t(u'Alpha'))
# beta = schema.Text(tit | le=_t(u'Beta'))
# gamma = schema.Text(title=_t(u'Gamma'))
# rows = schema.Text(title=_t(u'Rows'))
# season = schema.Text(title=_t(u'Season'))
# window = schema.Text(title=_t(u'Window'))
# threshold = schema.Text(title=_t(u'Threshold'))
# delta = schema.Text(title=_t(u'Delta'))
# predcolor = schema.... |
jai1/pulsar | pulsar-functions/instance/src/main/python/util.py | Python | apache-2.0 | 2,346 | 0.008951 | #!/usr/bin/env python
#
# 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
# "... |
api_dir = os.path.join(our_dir, PULSAR_API_ROOT, PULSAR_FUNCTIONS_API_ROOT)
try:
return import_class_from_path(api_dir, full_class_name)
except Exception as e:
Log.info("Failed to import class %s from path %s" % (full_class_name, from_path))
Log.info(e, exc_i | nfo=True)
return None
def import_class_from_path(from_path, full_class_name):
Log.debug('Trying to import %s from path %s' % (full_class_name, from_path))
split = full_class_name.split('.')
classname_path = '.'.join(split[:-1])
class_name = full_class_name.split('.')[-1]
if from_path not in sys.path:
... |
sergeyfarin/pyqt-fit | pyqt_fit/loader.py | Python | gpl-3.0 | 3,942 | 0.001776 | from __future__ import print_function, absolute_import
import inspect
from path import path
import imp
import sys
import re
bad_chars = re.compile(u'\W')
python_version = sys.version_info
if python_version.major == 2 and python_version.minor == 7:
if sys.platform == 'win32' or sys.platform == 'cygwin':
... | def create_module(loader):
" Version for Python 3.4 or later "
mod = ModuleType(loader.name)
loader.exec_module(mod)
return mod
module_loaders = [ (ilm.EXTENSION_SUFFIXES, ilm.ExtensionFileLoader),
(ilm.SOURCE_SUFFIXES, ilm.SourceFileLoader),
... | f load_module(pack_name, module_name, search_path):
pth = path(search_path) / module_name
for exts, loader_cls in module_loaders:
for ext in exts:
filename = pth + ext
if filename.exists():
loader = loader_cls(pack_name, str(filename))
... |
PearsonIOKI/compose-forum | askbot/bin/rebuildlocales.py | Python | gpl-3.0 | 365 | 0.005479 | import os
import subprocess
locales = os.listdir('locale')
de | f call_command(command):
print command
subprocess.call(command.split())
for locale in locales:
call_command(
'python ../manage.py jinja2_makemessages -l | %s -e html,py,txt' % locale
)
call_command(
'python ../manage.py makemessages -l %s -d djangojs' % locale
)
|
saltastro/salt-data-quality-site | test_bokeh_model.py | Python | mit | 2,995 | 0.004341 | import argparse
import importlib
import inspect
import os
import sys
import traceback
from bokeh.plotting import output_file, show
from fabulous.color import bold, red
from app import create_app
def error(msg, stacktrace=None):
"""Print an error message and exit.
Params:
-------
msg: str
Er... | ce: str
Stacktrace.
"""
if stacktrace:
print(stacktrace)
print(bold(red(msg)))
sys.exit(1)
# get command line arguments
parser = argparse.ArgumentParser(description='Test a Bokeh model.')
parser.add_argument('module_file',
type=str,
h | elp='Python file containing the Bokeh model')
parser.add_argument('model_function',
type=str,
help='Function returning the Bokeh model')
parser.add_argument('func_args',
type=str,
nargs='*',
help='Arguments to pass to th... |
harshadyeola/easyengine | tests/cli/a_test_site_disable.py | Python | mit | 394 | 0 | from | ee.utils import test
from ee.cli.main import get_test_app
class CliTestCaseSite(test.EETestCase):
def test_ee_cli(self):
self.app.setup()
self.app.run()
self.app.close()
def test_ee_cli_site_disable(self):
self.app = get_test_app(argv=['site', 'disable', 'example2.com'])
... | lose()
|
pyblish/pyblish-mindbender | run_maya_tests.py | Python | mit | 1,052 | 0 | """Use Mayapy for testing
Usage:
$ mayapy run_maya_tests.py
"""
import sys
import nose
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
stan | dalone.initialize()
argv = sys.argv[:]
argv.extend([ |
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
... |
SANBI-SA/tools-iuc | tools/kraken_taxonomy_report/kraken_taxonomy_report.py | Python | mit | 12,936 | 0.022727 | #!/usr/bin/env python
# Reports a summary of Kraken's results
# and optionally creates a newick Tree
# Copyright (c) 2016 Daniel Blankenberg
# Licensed under the Academic Free License version 3.0
# https://github.com/blankenberg/Kraken-Taxonomy-Report
from __future__ import print_function
import optparse
import os
i... | nrecognized rank: Node "%s" is "%s", setting to "%s"' % ( node_id, fields[2], NO_RANK_NAME ), file=sys.stderr )
rank = NO_RANK_INT
if node_id == '1':
| parent_id = '0'
if parent_id not in child_lists:
child_lists[ parent_id ] = []
child_lists[ parent_id ].append( node_id )
rank_map[node_id] = rank
return ( child_lists, name_map, rank_map )
def dfs_summation( node, counts, child_lists ):
children =... |
probml/pyprobml | scripts/bayes_change_of_var.py | Python | mit | 1,657 | 0.006035 | # Based on https://github.com/probml/pmtk3/blob/master/demos/bayesChangeOfVar.m
# MC on change of variables and empirical distribution, highlighting that
# modes are not, in general, preserved.
import superimport
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import os
from pyprobml_u... | he mapping function, and an indication of how
# the x-distribution's mean maps to y-space.
linewidth = 5
plt.bar(bin_edges_x[:-1], hist_x, color='red', align='edge', width=bin_ | edges_x[1] - bin_edges_x[0])
plt.barh(bin_edges_y[:-1], hist_y, color='green', align='edge', height=bin_edges_y[1] - bin_edges_y[0])
x_range = np.arange(0, 10, 0.01)
plt.plot(x_range, ginv(x_range), 'blue', linewidth=linewidth)
plt.vlines(mu, ymin=0, ymax=ginv(mu), color='yellow', linewidth=linewidth)
plt.hlines(ginv(m... |
hasadna/knesset-data-pipelines | votes/join_kmmbr_mk_individuals.py | Python | mit | 4,076 | 0.002699 | from datapackage_pipelines.wrapper import ingest, spew
# this members have a problem with their names
# we can match them directly
KMMBR_IDS_DIRECT_MATCH_TO_PERSON_ID = {'000000431': 431}
def get_mk_individuals(resource, data):
data['mks'] = []
for mk in resource:
yield mk
knesset_nums = set... |
def get_vote_rslts(resource, data):
kmmbr = None
for vote_rslt in resource:
if not kmmbr or kmmbr['id'] != vote_rslt['kmmbr_id']:
if | kmmbr:
yield from get_kmmbr_results(kmmbr, data)
kmmbr = {'id': vote_rslt['kmmbr_id'],
'names': set(),
'vote_rslts': []}
kmmbr['names'].add(vote_rslt['kmmbr_name'].strip())
kmmbr['names'].add(vote_rslt['kmmbr_name'].strip().replace('`... |
kmoocdev2/edx-platform | cms/djangoapps/contentstore/features/html-editor.py | Python | agpl-3.0 | 9,937 | 0.001409 | # disable missing docstring
# pylint: disable=missing-docstring
from collections import OrderedDict
from lettuce import step, world
from nose.tools import assert_equal, assert_false, assert_in, assert_true
from common import get_codemirror_value, type_in_codemirror
CODEMIRROR_SELECTOR_PREFIX = "$('iframe').contents... | expected font family')
def default_options_sets_expected_font_family(step): # pylint: disable=unused-argument, redefined-outer-name
fonts = get_available_fonts(get_fonts_list_panel(world))
fonts_found = fonts.get("Default", None)
expected_font_family = CUSTOM_FONTS.get('Default')
for expected_font in e... | eck_standard_tinyMCE_fonts(step):
fonts = get_available_fonts(get_fonts_list_panel(world))
for label, expected_fonts in TINYMCE_FONTS.items():
for expected_font in expected_fonts:
assert_in(expected_font, fonts.get(label, None))
TINYMCE_FONTS = OrderedDict([
("Andale Mono", ['andale mon... |
athoune/aiohttp_security | setup.py | Python | apache-2.0 | 2,105 | 0.00095 | import codecs
from setuptools import setup, find_packages
import os
import re
import sys
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_opti... | ohttp.web"),
long_description='\n\n'.join((read('README.rst'), read('CHANGES.txt'))),
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
... | uage :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP'],
author='Andrew Svetlov',
author_email='andrew.svetlov@gmail.com',
url='https://github.com/aio-libs/aiohttp_security/',
license='Apache 2',
packages=find_packages(),
install_requires=install_requires,
tests_requ... |
alephu5/Soundbyte | environment/lib/python3.3/site-packages/scipy/ndimage/measurements.py | Python | gpl-3.0 | 47,436 | 0.000358 | # Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following d... | objects); useful for finding features' position or
dimensions
Examples
--------
Create an image with some features, then label it using the | default
(cross-shaped) structuring element:
>>> a = np.array([[0,0,1,1,0,0],
... [0,0,0,1,0,0],
... [1,1,0,0,1,0],
... [0,0,0,1,0,0]])
>>> labeled_array, num_features = label(a)
Each of the 4 features are labeled with a different integer:
>>> ... |
tidus747/Tutoriales_juegos_Python | Ataca a los orcos V0.0.5/Ataca_a_los_orcos_V0.0.5.py | Python | gpl-3.0 | 4,736 | 0.011467 | # -*- coding: utf-8 -*-
import random
import textwrap
def print_bold(msg):
#Funcion para mostrar por pantalla un string en negrita
print("\033[1m"+msg+"\033[0m")
def print_linea_punteada(width=72):
print('-'*width)
def ocupar_chozas():
ocupantes = ['enemigo','amigo','no ocupada']
chozas = []
... | int(10,15)
medidor_salud[unidad_herida] = max(puntos_vida- herida,0)
print("¡Ataque!")
mostrar_salud(medidor_salud,bold=False)
def revelar_ocupa | ntes(idx, chozas):
msg=""
print("Revelando los ocupantes...")
for i in range(len(chozas)):
ocupantes_info = "<%d:%s>"%(i+1, chozas[i])
if i+1 == idx:
ocupantes_info = "\033[1m" + ocupantes_info + "\033[0m"
msg += ocupantes_info + " "
print("\t" + msg)
print_linea_... |
joopert/home-assistant | homeassistant/scripts/credstash.py | Python | apache-2.0 | 2,373 | 0.001686 | """Script to get, put and delete secrets stored in credstash."""
import argparse
import getpass
from homeassistant.util.yaml import _SECRET_NAMESPACE
# mypy: allow-untyped-defs
REQUIREMENTS = ["credstash==1.15.0"]
def run(args):
"""Handle credstash script."""
parser = argparse.ArgumentParser(
desc... | )
| print(f"Secret {args.name} put successfully")
elif args.action == "get":
the_secret = credstash.getSecret(args.name, table=table)
if the_secret is None:
print(f"Secret {args.name} not found")
else:
print(f"Secret {args.name}={the_secret}")
elif args.action ==... |
tripatheea/Riemann-Zeta | python/dirichlet.py | Python | mit | 1,897 | 0.038482 | from __future__ import division
import math
import numpy as np
from time import time
import sympy as sp
import mpmath as mp
from mpmath.ctx_mp_python import mpf
from scipy.misc import factorial
from scipy.special import gamma
precision = 53
mp.prec = precision
mp.pretty = True
def calculate_factorial_ratio(n,... | mp.dps = 50
k = (n - i)
result = 1
for j in range(k + 2*i - 1, k, -1):
result = mp.fmul(result, j)
return result
def n_choose_k(n, k):
j = n - k
numerator = 1
for i in range(1, k + 1):
numerator *= (j + i)
denominator = factorial(k)
return | numerator / denominator
def dirichlet_eta(s, N):
def calculate_d_n(n):
total = 0.0
for k in range(n + 1):
if k % 2 == 0:
alternating_factor = 1
else:
alternating_factor = -1
total += alternating_factor * n_choose_k(n, k) / ( k + 1)**s
return total
eta = 0.0
for n in range(N + 1):
d_n = c... |
stelfrich/bioformats | tools/bump_maven_version.py | Python | gpl-2.0 | 3,006 | 0.001331 | #! /usr/bin/python
# Script for increasing versions numbers across the code
import sys
import glob
import re
import argparse
def check_version_format(version):
"""Check format of version number"""
pattern = '^[0-9]+[\.][0-9]+[\.][0-9]+(\-.+)*$'
return re.match(pattern, version) is not None
BIO_FORMATS_... | ile(
self.upgradecheck, self.stableversion_pattern, version)
if __name__ == "__main__":
# Input check
parser = argparse.ArgumentParser()
parser.add_argument("--old-group", type=str, default="ome")
parser.add_argument("--new-group", type=str, default="ome")
parser.add_argument("version"... | d_group, new_group=ns.new_group)
replacer.bump_pom_versions(ns.version)
if not ns.version.endswith('SNAPSHOT'):
replacer.bump_stable_version(ns.version)
|
kuraha4/roguelike-tutorial-python | src/data/status_effect.py | Python | mit | 1,577 | 0.000634 | # -*- coding: utf-8 -*-
"""Status effect data."""
from components.status_effect i | mport StatusEffect
from status_effect_functions import damage_of_time
# todo: generate new object not copy
STATUS_EFFECT_CATALOG = {
'POISONED':
{
'name': 'poisoned',
'tile_path': 'status_effect/poisoned.png',
'color': 'green',
'tick_function': damage_of_time,
'duration'... | 'OFF_BALANCED':
{
'name': 'off-balanced',
'tile_path': 'status_effect/off_balanced.png',
'color': 'gray',
'duration': 4,
'stats': {'phys_pow': -1,
'defense': -2}
},
'VIGILANT':
{
'name': 'vigilant',
'tile_path': 'status_effec... |
bmihelac/django-import-export | import_export/templatetags/import_export_tags.py | Python | bsd-2-clause | 323 | 0 | from diff_match_patch import diff_match_patch
from django import template
register = template.Library()
@register.simple_tag
def compare_values(value1, value2):
dmp = diff_match_patch()
diff = dmp.diff_main(value1, value2)
dmp.diff_cleanupSemantic(diff)
| html = dmp.diff_prettyHtml(diff)
r | eturn html
|
eunchong/build | scripts/slave/recipe_modules/auto_bisect/resources/fetch_revision_info.py | Python | bsd-3-clause | 1,529 | 0.011772 | #!/usr/bin/python
# Copyright 2015 The Chro | mium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LIC | ENSE file.
"""Gets information about one commit from gitiles.
Example usage:
./fetch_revision_info.py 343b531d31 chromium
./fetch_revision_info.py 17b4e7450d v8
"""
import argparse
import json
import urllib2
import depot_map # pylint: disable=relative-import
_GITILES_PADDING = ')]}\'\n'
_URL_TEMPLATE = 'https... |
mozilla/ChangeDetector | pyLibrary/queries/containers/__init__.py | Python | mpl-2.0 | 4,498 | 0.001556 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __... | having(self, having):
_ = having
Log.error("not implemented")
def format(self, format):
_ = format
Log.error("not implemented")
def get_columns(self, table):
"""
USE THE frum | TO DETERMINE THE COLUMNS
"""
Log.error("Not implemented")
|
PicoCentauri/GromacsWrapper | gromacs/fileformats/ndx.py | Python | gpl-3.0 | 7,868 | 0.003177 | # GromacsWrapper: formats.py
# Copyright (c) 2009-2011 Oliver Beckstein <orbeckst@gmail.com>
# Released under the GNU Public License 3 (or higher, your choice)
# See the file COPYING for details.
"""
Gromacs NDX index file format
=============================
The `.ndx file`_ contains lists of atom indices that are g... | file ``system.ndx``)::
ndx = NDX('system') # suffix .ndx is | automatically added
ndx['chi1'] = [2, 7, 8, 10]
ndx.write()
"""
default_extension = "ndx"
# match: [ index_groupname ]
SECTION = re.compile("""\s*\[\s*(?P<name>\S.*\S)\s*\]\s*""")
#: standard ndx file format: 15 columns
ncol = 15
#: standard ndx file format: '%6d'
fo... |
sbg/sevenbridges-python | sevenbridges/meta/comp_mutable_dict.py | Python | apache-2.0 | 1,715 | 0 | # noinspection PyProtectedMember,PyUnresolvedReferences
class CompoundMutableDict(dict):
"""
Resource used for mutable compound dictionaries.
"""
# noinspection PyMissingConstructor
def __init__(self, **kwargs):
self._parent = kwargs.pop('_parent')
self._api = kwargs.pop('api')
... | lf._parent._data[self._name]:
if self._parent._data[self._name][key] != value:
self._parent._dirty[self._name][key] = value
self._parent._data[self._name][key] = value
else:
self._parent._data[self._name][key] = value
self._parent._dirty[self._... | def __repr__(self):
values = {}
for k, _ in self.items():
values[k] = self[k]
return str(values)
__str__ = __repr__
def update(self, e=None, **f):
other = {}
if e:
other.update(e, **f)
else:
other.update(**f)
for k... |
hurricanerix/swift | test/unit/common/middleware/test_staticweb.py | Python | apache-2.0 | 41,893 | 0 | # Copyright (c) 2010 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | elif env['PATH_INFO'] == '/v1/a/c1':
return Response(status='401 Unauthorized')(env, start_response)
elif env['PATH_INFO'] == '/v1/a/c2':
return self.listing(env, start_response)
elif env['PATH_INFO'] == '/v1/a/c2/one.txt':
return Response(status='404 Not Found')(e... | ng(env, start_response)
elif env['PATH_INFO'] == '/v1/a/c3/index.html':
return Response(status='200 Ok', body='''
<html>
<body>
<h1>Test main index.html file.</h1>
<p>Visit <a href="subdir">subdir</a>.</p>
<p>Don't visit <a href="subdir2/">subdir2</a> because it doesn't r... |
oliviamillard/CS141 | ChaosSierpinskiTriangle.py | Python | mit | 2,806 | 0.015324 | #Olivia Millard - Homework 3
#This program will generate a Sierpinski Triangle.
import pygame, random, math
## PRE- user-inputted width/height to generate the size of the image
## POST- Creates a list with (len(length[0])); each list item is a list with (len(size[1]))
## Points = ima... | w = newImage((width, height))
for X in range(width):
for Y in range(height):
wind | ow[X][Y] = (255,255,255)
p = 1
p = random_point(width, height)
i = 0
for i in range(4444444):
img_corners = [(width, height),(0, height),(width // 2, 0)]
c = random.choice(img_corners)
m = midpoint(p[0], p[1], c[0], c[1])
color = color_point((m[0]), (m[1]), width, height)
if i > 20:
window... |
pombreda/omnipy | omnipy/reader/_reader.py | Python | gpl-3.0 | 1,755 | 0.034758 | """
The basic module about log readers
"""
import os
import re
from ..utils.gzip2 import GzipFile
__author__ = 'chenxm'
__all__ = ["FileReader"]
class FileReader(object):
@staticmethod
def open_file(filename, mode='rb'):
""" open plain or compressed file
@return file handler
"""
parts = os.path.basename(f... | return self.data[property]
def __setitem__(self, property, value):
self.data[property] = value
def __str__(self):
return str(self.data)
class LogReader(object):
def __init__(s | elf, filename):
self.filename = filename
self.filehandler = FileReader.open_file(filename)
def __iter__(self):
return self
def next(self):
try:
new_line = self.filehandler.next()
return new_line
except StopIteration:
self.filehandler.close()
raise StopIteration |
patricklaw/pants | src/python/pants/backend/python/register.py | Python | apache-2.0 | 2,773 | 0.001082 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Support for Python.
See https://www.pantsbuild.org/docs/python-backend.
"""
from pants.backend.python import target_types_rules
from pants.backend.python.dependency_inference import r... | coverage_py,
lockfile,
package_pex_binary,
pytest_runner,
repl,
run_pex_binary,
setup_py,
tailor,
)
from pants.backend.python.macros.pants_requirement import PantsRequirement
from pants.backend.python.macros.pipenv_requirements import PipenvRequirements
from pants.backend.python.macros.poe... | PythonRequirements
from pants.backend.python.subsystems import ipython, pytest, python_native_code, setuptools
from pants.backend.python.target_types import (
PexBinary,
PythonDistribution,
PythonRequirementsFile,
PythonRequirementTarget,
PythonSourcesGeneratorTarget,
PythonTestsGeneratorTarget,... |
nabla-c0d3/nassl | nassl/cert_chain_verifier.py | Python | agpl-3.0 | 3,020 | 0.00298 | from pathlib import Path
from typing import List
from nassl._nassl import X509, X509_STORE_CTX
class CertificateChainVerificationFailed(Exception):
def | __init__(self, openssl_error_code: int) -> None:
self.openssl_error_code = openssl_error_code
self.openssl_error_str | ing = X509.verify_cert_error_string(self.openssl_error_code)
super().__init__(
f'Verification failed with OpenSSL error code {self.openssl_error_code}: "{self.openssl_error_string}"'
)
class CertificateChainVerifier:
def __init__(self, trusted_certificates: List[X509]) -> None:
... |
iulian787/spack | var/spack/repos/builtin/packages/prokka/package.py | Python | lgpl-2.1 | 1,155 | 0.001732 | # Copyright 2013-2020 Lawrence Live | rmore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Prokka(Package):
"""Prokka is a software tool to annotate bacterial, archaeal and viral
genomes quickly and produce st... | hub.com/tseemann/prokka"
url = "https://github.com/tseemann/prokka/archive/v1.14.5.tar.gz"
version('1.14.6', sha256='f730b5400ea9e507bfe6c5f3d22ce61960a897195c11571c2e1308ce2533faf8')
depends_on('perl', type='run')
depends_on('perl-bioperl', type='run')
depends_on('perl-xml-simple', type='run... |
BLuu13/ISSAMemberManager | tests/test_delete.py | Python | mpl-2.0 | 278 | 0.02518 | import unittest
from ISSA.MemberMailer.Objects.database | imp | ort Database
class TestDelete(unittest.TestCase):
def test_delete_mem(self):
test_member = Database()
test = test_member.delete(8)
self.assertEqual(test, "Success!")
if __name__ == '__main__':
unittest.main()
|
michellab/SireUnitTests | unittests/SireIO/test_mol2.py | Python | gpl-3.0 | 5,051 | 0.008513 | from Sire.Base import *
from Sire.IO import *
from Sire.Mol import *
from glob import glob
from nose.tools import assert_equal, assert_almost_equal
# Check that we have Mol2 support in this version of Sire.
has_mol2 = True
try:
p = Mol2()
except:
# No Mol2 support.
has_mol2 = False
# General test of abi... | llowing this, we then c | heck that the
# parser can convert the molecule back into the correct data format, ready to
# be written to file.
def test_read_write(verbose=False):
if not has_mol2:
return
# Glob all of the Mol2 files in the example file directory.
mol2files = glob('../io/*mol2')
# Loop over all test files.
... |
AutorestCI/azure-sdk-for-python | azure-batch/azure/batch/models/job_get_all_lifetime_statistics_options.py | Python | mit | 1,726 | 0.000579 | # 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 cause incorrect behavior | and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class JobGetAllLifetimeStatisticsOptions(Model):
"""Additional parameters for get_all_lifetime_statistics operation.
:param timeout: The maximum... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_corvette_rebel_crowley.py | Python | mit | 458 | 0.045852 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shar | ed_dressed_corvette_rebel_crowley.iff"
result.attribute_template_id = 9
result.stfName("npc_name","twilek_ | base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.