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 |
|---|---|---|---|---|---|---|---|---|
alexis-roche/nipy | nipy/labs/statistical_mapping.py | Python | bsd-3-clause | 15,304 | 0.000915 | from __future__ import absolute_import
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import numpy as np
import scipy.stats as sp_stats
# Use the nibabel image object
from nibabel import Nifti1Image as Image
from nibabel.affines import apply_affine
fr... | luster-level p-values (corrected)
p = None
if isinstance(nulls['smax'], np.ndarray):
p = simulated_pvalue(c['size'], nulls['sm | ax'])
c['cluster_fwer_pvalue'] = p
# Cluster-level p-values (uncorrected)
p = None
if isinstance(nulls['s'], np.ndarray):
p = simulated_pvalue(c['size'], nulls['s'])
c['cluster_pvalue'] = p
# General info
info = {'nvoxels': nvoxels,
'threshold_z'... |
rodrigofaccioli/drugdesign | virtualscreening/vina/spark/prepare_receptor.py | Python | apache-2.0 | 2,232 | 0.002688 | import ConfigParser as configparser
import os
import sys
from pyspark import SparkContext, SparkConf, SparkFiles
from pyspark.sql import SQLContext, Row
from datetime import datetime
from os_utils import make_directory, preparing_path, time_execution_log, check_file_exists
from subprocess import Popen, PIPE
from vina_u... | .path.join(path_spark_drugdesign, "vina_utils.py"))
sc.addPyFile(os.path.join(path_spark_drugdesign, "json_utils.py"))
sc.addPyFile(os.path.join(path_spark_drugdesign, "os_utils.py"))
# Broadcast
pythonsh = sc.broadcast(pythonsh)
script_receptor4 = sc.broadcast(script_receptor4)
pdbqt_receptor_... | ceptor_path)
def run_prepare_receptor_spark(receptor):
receptor_pdbqt = os.path.join(pdbqt_receptor_path.value,
get_name_model_pdb(receptor))
command = ''.join([pythonsh.value,
' ',
script_receptor4.valu... |
doubleDragon/QuantBot | quant/observers/t_bithumb.py | Python | mit | 40,197 | 0.004183 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import division
import logging
import time
from quant import config
from quant.brokers import broker_factory
from .basicbot import BasicBot
from quant.common import log
MESSAGE_TRY_AGAIN = 'Please try again'
class T_Bithumb(BasicBot):
"""
bch:
... | self.brokers[
self.base_pair].krw_available / base_pair_ask_price_real),
8)
hedge_mid_amount_balance = round(min(self.brokers[self.pair_2].btc_available,
... | s[self.pair_1].bch_available * pair1_bid_price_real), 8)
"""取市场和余额共同限制的amount"""
hedge_quote_amount = min(hedge_quote_amount_market, hedge_quote_amount_balance, self.min_trade_amount)
hedge_mid_amount = hedge_quote_amount * pair1_bid_price
logging.debug("forward======>b... |
mozilla-it/autocert | autocert/api/destination/factory.py | Python | mit | 854 | 0.003513 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
destination.factory
'''
from destination.zeus import ZeusDestination
from destination.aws import AwsDestination
from exceptions | import AutocertError
from config import CFG
from app import app
class DestinationFactoryError(AutocertError):
def __init__(self, destination):
msg = f'destination factory error with {destination}'
super(DestinationFactoryError, self).__init__(msg)
def create_destination(destination, ar, cfg, timeo... | None
if destination == 'aws':
d = AwsDestination(ar, cfg, verbosity)
elif destination == 'zeus':
d = ZeusDestination(ar, cfg, verbosity)
else:
raise DestinationFactoryError(destination)
dests = list(CFG.destinations.zeus.keys())
if d.has_connectivity(timeout, dests):
... |
bradleyayers/django-revisionfield | django_revisionfield/models.py | Python | bsd-2-clause | 828 | 0.001208 | # -*- coding: utf8 -*-
from django.db import models
from django.db.models import F
class Revision(models.Model):
"""
A blank model (except for ``id``) that is merely an implementation detail
of django | -revisionfield.
"""
number = models.PositiveIntegerField()
@staticmethod
def next():
"""
Returns the next revision.
:returns: next available revision
| :rtype: ``int``
"""
try:
current = Revision.objects.get().number
except Revision.DoesNotExist:
revision, created = Revision.objects.get_or_create(number=1)
current = revision.number
while Revision.objects.filter(number=current).update(number=F('nu... |
klmitch/nova | nova/tests/unit/compute/test_provider_config.py | Python | apache-2.0 | 17,242 | 0.000058 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
need to be placed in the subclass. This is why there are test_ functions in
the subclass that call the run_test_ methods in this class. This should
keep things simple as more schema versions are added.
"""
def setUp(self):
super(SchemaValidationMixin, self).setUp()
self.mock_load_ya... | self.mock_LOG = self.useFixture(
fixtures.MockPatchObject(
provider_config, 'LOG')).mock
def set_config(self, config=None):
data = config or {}
self.mock_load_yaml.return_value = data
return data
def run_test_validation_errors(self, config, expected_messag... |
EmreAtes/spack | lib/spack/spack/test/cmd/url.py | Python | lgpl-2.1 | 5,856 | 0.000342 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Les... | License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import re
import pytest
from spack.url import UndetectableVersionError
from spack.main import Spac... |
henniggroup/MPInterfaces | mpinterfaces/mat2d/intercalation/startup.py | Python | mit | 3,088 | 0.000648 | from __future__ import print_function, division, unicode_literals
import operator
from pymatgen.core.periodic_table import Element
from pymatgen.core.structure import Structure
from mpinterfaces.mat2d.intercalation.analysis import get_interstitial_sites
__author__ = "Michael Ashton"
__copyright__ = "Copyright 2017... | specie = Element(ion)
# If the structure isn't big enough to accomodate such a small
# atomic fraction, multiply it into a supercell.
n_ions = 1.
while not n_ions / (structure.num_sites+n_ions) <= atomic_fraction:
# A supercell in all 3 dimenions is not usually necessary,
# but is t... | ble for finding interstitial sites.
# Flat or narrow supercells give a poor triangulation.
structure.make_supercell(2)
if structure.num_sites * atomic_fraction > 3:
print("The algorithm is working, but may take several minutes "
"due to the relatively large number of ions to "... |
volpino/Yeps-EURAC | tools/filters/axt_to_lav_code.py | Python | mit | 306 | 0.01634 |
def exec_after_process(app, inp_data, out_data, param | _dict, tool, stdout, stderr):
for name,data in out_data.items():
if name == "seq_file2":
data.dbkey = param_dict['dbkey_2']
app.model.context.add( data )
app.model.context.flush() |
break |
crakensio/djph2 | craken_project/manage.py | Python | mit | 263 | 0.003802 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "craken_pr | oject.settings.local")
from django.co | re.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
MISP/misp-modules | tests/test.py | Python | agpl-3.0 | 34,783 | 0.002048 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
import requests
import base64
import json
import os
import io
import re
import zipfile
from hashlib import sha256
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from em... | })
response = requests.post(se | lf.url + "query", data=data).json()
print(response)
print("OpenIOC :: {}".format(response))
values = [x["values"][0] for x in response["results"]]
assert("mrxcls.sys" in values)
assert("mdmcpq3.PNF" in values)
@unittest.skip("Need Rewrite")
def test_... |
jyi/ITSP | prophet-gpl/tools/rev-test.py | Python | mit | 2,304 | 0.027344 | #!/usr/bin/env python
from sys import argv
from os import system
from php_tester import php_tester
if __name__ == "__main__":
assert(len(argv) > 3);
repo_src = argv[1];
repo_test = argv[2];
revision = argv[3];
if (len(argv) == 4):
out_file = "revlog" + revision + ".txt";
revision2 =... | outdiff.append(i);
print >>fout, "Diff Cases: Tot", len(outdiff);
for i in outdiff:
print >>fout, i,
print >>fout;
print >>fout, "Positive Cases: Tot", len(common);
for i in common:
print >>fout, i,
| print >>fout;
print >>fout, "Regression Cases: Tot", len(diff21);
for i in diff21:
print >>fout, i,
print >>fout;
fout.close();
system("rm -rf " + workdir);
|
unioslo/cerebrum | Cerebrum/modules/no/uio/PostmasterCommands.py | Python | gpl-2.0 | 4,574 | 0.001968 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011, 2012 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 ... | . 'STUDENT', 'STUDENT/aktiv' and
'ANSATT/vitenskapelig'. Returned in two lists, affs and statuses.
"""
affs = list()
| stats = list()
for string in input:
try:
aff, status = string.split('/', 1)
except ValueError:
affs.append(self.co.PersonAffiliation(string))
else:
stats.append(self.co.PersonAffStatus(self.co.PersonAffiliation(aff), status))
... |
miurahr/translate | translate/tools/test_phppo2pypo.py | Python | gpl-2.0 | 1,682 | 0 | # phppo2pypo unit tests
# Author: Wil Clouser <wclouser@mozilla.com>
# Date: 2009-12-03
from io import BytesIO
from translate.convert import test_convert
from translate.tools import phppo2pypo
class TestPhpPo2PyPo:
| def test_single_po(self):
inputfile = b"""
# This user comment refers to: %1$s
#. This developer comment does too: %1$s
#: some/path.php:111
#, php-format
msgid "I have %2$s apples and %1$s oranges"
msgstr "I have %2$s apples and %1$s oranges"
"""
outputfile = BytesIO()
phppo2pypo.conver... | 'msgid "I have {1} apples and {0} oranges"' in output
assert 'msgstr "I have {1} apples and {0} oranges"' in output
def test_plural_po(self):
inputfile = b"""
#. This developer comment refers to %1$s
#: some/path.php:111
#, php-format
msgid "I have %1$s apple"
msgid_plural "I have %1$s apples"
msgs... |
lalinsky/acute-dbapi | setup.py | Python | mit | 1,836 | 0.014161 | #
# acute-dbapi setup
# Ken Kuhlman (acute at redlagoon dot net), 2007
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Extension
import sys
import os
setup(
name="acute-dbapi",
version="0.1.0",
description="Python DB-API testsuite",
author="Ken Kuhlma... | o the home page for acute-dbapi, a DB-API compliance test suite. Acute is still in it's infancy, but it's reached th | e level of maturity that it would benefit from community input. It currently contains 71 tests, and many more will be added soon.
Comments, suggestions, and patches are all warmly welcome. There are several TODOs listed in the [TODO] file, and many more generously sprinkled throughout the code; if you'd like to help... |
commshare/etna_viv | tools/etnaviv/parse_fdr.py | Python | gpl-3.0 | 9,109 | 0.004611 | '''
Parse execution data log stream.
Allows access to selected parts of program memory at the time of recorded events.
'''
# Copyright (c) 2012-2013 Wladimir J. van der Laan
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Softw... | sys, | struct
from collections import namedtuple
from bisect import bisect_right
from binascii import b2a_hex
LITTLE_ENDIAN = b'<'
BIG_ENDIAN = b'>'
# target architecture description
ENDIAN = LITTLE_ENDIAN
DEBUG = False
RECTYPE_CHAR = b'B' # always 8 bit
MAGIC_CHAR = b'I' # always 32 bit
WORD_CHAR = b'I' # 32 bit
ADDR_CHAR... |
derivationBud/prez | source/greenparadise.py | Python | mit | 548 | 0.032847 | import re,json
def isValid(number):
match=re.match(r | '[456]\d{3}-?\d{4}-?\d{4}-?\d{4}$',number)
if not match: return False
else:
digits=number.rep | lace("-","")
result=re.search(r'(\d)\1\1\1',digits)
if result: return False
return True
records=json.load(open("greenparadise.json"))
for record in records:
valid=isValid(record["card"])
if not valid:
print("Invalid card:",record["card"])
if valid != record["valid"]:
prin... |
wangyangjun/RealtimeStreamBenchmark | script/pull-updates.py | Python | apache-2.0 | 715 | 0.018182 | #!/bin/python
from __future__ import print_function
import subprocess
import sys
import os
import json
from util import appendline, get_ip_address
if __name__ == "__main__":
path = os.path.dirname(os.path.realpath(__file__))
config = json.load(open(path+'/cluster-config.json'));
for node in config['nodes']:
files... | s.Popen('ssh c | loud-user@'+node['ip']+' "git clone https://github.com/wangyangjun/StreamBench.git"', shell=True)
else:
p = subprocess.Popen('ssh cloud-user@'+node['ip']+' "cd /home/cloud-user/StreamBench;git checkout .;git pull;"', shell=True)
|
Reimilia/Privacy_Server | resources/common/json_parser.py | Python | mit | 8,021 | 0.012093 | import json
import copy
formtable = {"name":[u'name'],
"gender":[u'gender'],
"contact":[u'contact'],
"address":[u'address']}
def is_reserved_layer(dict,reserved_word):
for key in dict:
if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]:
... | rd):
'''
:param source: a list of list
:return: a dict which can be converted into json str use json.dumps()
'''
dest = jso | n_gene(source,reserved_word)
json_reduce_layer(dest,reserved_word)
json_reduce_structure(dest)
return dest
def json_gene(list,reserved_word):
proto = {}
for item in list:
if not proto.has_key(item[0]):
proto[item[0]] = []
json_write(item[1:],proto[item[0]],reserved_wor... |
tensorflow/tensorflow | tensorflow/python/tools/optimize_for_inference.py | Python | apache-2.0 | 5,141 | 0.005057 | # pylint: disable=g-bad-file-header
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | gument(
"--input_names",
type=str,
default="",
help="Input node names, comma separated.")
parser.add_argument(
"--output_names",
type=str,
default="",
help="Output node names, comma separated.")
parser.add_argument(
"--frozen_graph",
nargs="?",
const... | o file.\
""")
parser.add_argument(
"--placeholder_type_enum",
type=str,
default=str(dtypes.float32.as_datatype_enum),
help="""\
The AttrValue enum to use for placeholders.
Or a comma separated list, one value for each placeholder.\
""")
parser.add_argument(
"--t... |
lukehsiao/RobotSoccer | MotionControl/scripts/kalman_filter/Sample.py | Python | mit | 2,688 | 0.011161 | import math
from param import *
class Sample:
def __init__(self):
self.time = 0
self.home1_x = 0.0
self.home1_y = 0.0
self.home1_theta = 0.0
self.home2_x = 0.0
self.home2_y = 0.0
self.home2_theta = 0.0
self.away1_x = 0.0
self.away1_y = 0.0
... | ixelToMeter(data.away2_y)
self.away2_theta = degreeToRadian(data.away2_theta)
self.ball_x = pixelToMeter(data.ball_x)
self.ball_y = pixelToMeter(data.ball_y)
def getDiscreteSample(self):
home1_x = meterToPixel(self.home1_x);
home1_y = meterToPixel(self.home1_y)... | ome1_theta = radianToDegree(self.home1_theta);
home2_x = meterToPixel(self.home2_x);
home2_y = meterToPixel(self.home2_y);
home2_theta = radianToDegree(self.home2_theta);
away1_x = meterToPixel(self.away1_x);
away1_y = meterToPixel(self.away1_y);
away1_theta = radianToDeg... |
pymelibre/ecolepo | agrostore/stores/admin.py | Python | gpl-3.0 | 135 | 0 | from django.co | ntrib import admin
from .models import (
Store,
Seller
)
admin.si | te.register(Store)
admin.site.register(Seller)
|
HamsterHuey/py_matlab_funcs | histfit.py | Python | mit | 2,005 | 0.009476 | # -*- coding: utf-8 | -*-
"""
Created on Mon May 05 23:10:12 2014
@author: Sudeep Mandal
"""
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def histfit(data, ax=None, **kwargs):
"""
Emulates MATLAB histfit | () function. Plots histogram & Gaussian fit to data
Currently only implements Gaussian fit
Parameters:
-----------
data : 1D array data to be plotted as histogram
ax : axes handle to use for plotting (eg: pass handle for using histfit
to plot in a subplot of an existing... |
liosha2007/plone-groupdocs-signature-source | src/groupdocs/signature/portlets/__init__.py | Python | apache-2.0 | 294 | 0.006803 | from zope.i18nmessageid import MessageFactory
PloneMessageFactory = MessageFac | tory('plone')
from Products.CMFCore.permissions import setDefaultRoles
setDefaultRoles('signature.portlets.gdsignature: Add GroupDocs Signature portlet',
| ('Manager', 'Site Administrator', 'Owner',))
|
justusc/Elemental | examples/interface/SOC.py | Python | bsd-3-clause | 4,486 | 0.041685 | #
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El, math, time
m = 10
cutoff = 1000
output = Tru... | _NT" )
El.Print( zNT, "z_NT" )
# Compute the minimum non-negative step length, alpha, such that s + alpha y
# touches the boundary of the product cone
y = El.DistMultiVec()
El.Uniform( y, n, 1 )
upperBound = 100.
alpha = El.MaxStepInSOC( s, y, orders, firstInds, upperBound, cutoff )
p = El.DistMultiVec()
El.Copy( s... | p )
pDets = El.SOCDets( p, orders, firstInds, cutoff )
if output:
El.Print( y, "y" )
if worldRank == 0:
print "maximum step in cone is:", alpha
El.Print( p, "s + alpha y" )
El.Print( pDets, "det(s + alpha y)" )
# Require the user to press a button before the figures are closed
El.Finalize()
if worldSize ... |
mariosky/evo-drawings | venv/lib/python2.7/site-packages/py2neo/packages/httpstream/__init__.py | Python | agpl-3.0 | 842 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2013-2014, Nigel Small
#
# Licensed under the Apache License, Version 2.0 (the "License");
# y | ou 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,
# WITHOUT WARRANTIES OR... | __ = "Nigel Small"
__copyright__ = "2013-2014, Nigel Small"
__email__ = "nigel@nigelsmall.com"
__license__ = "Apache License, Version 2.0"
__version__ = "1.2.0"
from .http import *
|
chiara-paci/baskerville | baskervilleweb/bibliography/apps.py | Python | gpl-3.0 | 177 | 0.011299 | # rock_n_roll/apps.py
from | django.apps import AppConfig
class BibliographyConfig(AppConfig):
name = 'bibliography'
| verbose_name = "bibliography"
#pippio = "pippo"
|
keisetsu/joblist | indeed.py | Python | mit | 5,528 | 0.000543 | #!/usr/bin/env python
import dateutil.parser
import dateutil.tz
import feedparser
import re
from datetime import datetime, timedelta
from joblist import JobList
class FilterException(Exception):
pass
class IndeedJobList(JobList):
'''Joblist class for Indeed
This joblist is for the indeed.com rss feed. I... | d < max_results:
# Get a page of feed results (sorted by date), and process
# it until either a date older than *oldest_cutoff*
# appears or all the entries have been processed
offset = pages * self.page_size
feed = feedparser.parse(
self.base_... | (domain=domain,
keywords=keywords,
location=location,
radius=radius,
offset=offset)
)
new = []
for entry in feed['entries']:
... |
marco-lilek/musiClr | src/utils/runner.py | Python | mit | 1,645 | 0.021884 | import ntpath
import mp3parser
from modifyTag import TagWrapper
from glob import glob
from os.path import join
def pathLeaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
class Runner():
def __init__(self, configs):
# We do this here to make it clear what data we need
... | elif not self.overwriteTags and tag.hasTags():
mp3parser.addToArtistList(tag.tag.artist)
self.results.append(["Skipped", raw, tag.tag.artist, tag.tag.name, fileName])
else:
artist, name = mp3parser.parse(raw, self.useLastFm)
if artist is N... | ad", raw, "", "", fileName])
else:
tag.modify(artist, name)
self.results.append(["Good", raw, artist, name, fileName])
|
appop/bitcoin | qa/rpc-tests/rpcbind_test.py | Python | mit | 4,449 | 0.004271 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The nealcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test running nealcoind with the -rpcbind and -rpcallowip options."""
from test_framework.test_framewo... | , defaultport)])
# check only IPv4 localhost (explicit)
self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1' | ],
[('127.0.0.1', defaultport)])
# check only IPv4 localhost (explicit) with alternative port
self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],
[('127.0.0.1', 32171)])
# check only IPv4 localhost (explicit) with multiple alternative ports on same h... |
bfontaine/jinja2_maps | tests/test_base.py | Python | mit | 718 | 0.005571 | # -*- coding: UTF-8 -*-
from base import TestCase
from jinja2_maps.base import _nor | malize_location
class Location(object):
def __init__(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
class TestBase(TestCase):
def test_normalize_location_dict(self):
d = {"latitude": 42.0, "longitude": 17.0}
self.assertEquals(d, _normalize_location(d))
def t... | itude=17.1)))
self.assertEquals({"latitude": 41.3, "longitude": 16.1},
_normalize_location(Location(lat=41.3, lng=16.1)))
|
pez2001/sVimPy | test_scripts/test_nested_function.py | Python | gpl-2.0 | 46 | 0.086957 | def | f2():
def f3 | ():
print("f3")
f3()
f2()
|
BNBLORD/bookingsynclord | bookingsynclord/data_store/ChangeOverStore.py | Python | gpl-3.0 | 346 | 0.008671 | fr | om GenericStore import GenericStore
class ChangeOverStore(GenericStore):
"""Store used to manage Source entities.
BookingSync doc : http://developers.bookingsync.com/reference/endpoints/change_overs/
"""
def __init__(self,credential_manager):
| super(ChangeOverStore, self).__init__(credential_manager, "change_overs")
|
littlecodersh/EasierLife | Scripts/LogInput&Output/py3.py | Python | mit | 642 | 0.012461 | import sys
class outPip(object):
def __init__(self, fileDir):
self.fileDir = fileDir
self.console = sys.stdout
def write(self, s):
self.console.write(s)
with open(s | elf.fileDir, 'a') as f: f.write(s)
def flush(self):
self.console.flush()
new_input = input
def inPip(fileDir):
def _input(hint):
s = new_input(hint)
with open(fileDir, 'a') as f: f.write(s)
return s
return _input
sys.stdout = outPip('out.log')
i | nput = inPip('out.log')
print('This will appear on your console and your file.')
print('So is this line.')
input('yo')
|
cgalleguillosm/accasim | accasim/base/scheduler_class.py | Python | mit | 26,009 | 0.009574 | """
MIT License
Copyright (c) 2017 cgalleguillosm, AlessioNetti
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, ... | Verification.CHECK_REQUEST, **kwargs):
"""
Construct a scheduler
:param seed: Seed for the random state
:param resource_manager: A Resource Manager object for dealing with system resources.
:param allocator: Allocator object to be used by the schedule... | an allocator isn't defined, the scheduler class must generate the entire dispatching plan.
:param job_check: A job may be rejected if it doesnt comply with:
- JobVerification.REJECT: Any job is rejected
- JobVerification.NO_CHECK: All jobs are accepted
... |
shoopio/shoop | shuup_tests/simple_cms/test_custom_templates.py | Python | agpl-3.0 | 1,062 | 0.000942 | # This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import pytest
from shuup.simple_cms.models import Page
from shuup.simple_... | o_db
@pytest.mark.parametrize("template_name", ["page.jinja", "page_sidebar.jinja"])
def test_superuser_can_see_invisible_page(rf, template_name):
template_path = "shuup/simple_cms/" + template_name
page = create_page(template_name=template_path, available_from=datetime.date(1988, 1, 1), shop=get_default_shop()... | unc = PageView.as_view()
request = apply_request_middleware(rf.get("/"))
response = view_func(request, url=page.url)
response.render()
assert response.template_name[0] == template_path
|
Zincr0/pyscrap | setup.py | Python | apache-2.0 | 1,541 | 0.012979 | # -*- coding=utf-8 -*-
#Copyright 2012 Daniel Osvaldo Mondaca Seguel
#
#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... | ap"],
install_requires = ["lxml", "simplejson"],
long_description=read("README.txt"),
package_data = { | "package": files},
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Software Development",
"License :: OSI Approved :: Apache Software License",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
],
)
|
alexhayes/django-psi | psi/__init__.py | Python | mit | 22 | 0 | __version__ = '0 | .3.0'
| |
andb0t/Fuxenpruefung | src/i18n.py | Python | gpl-3.0 | 9,386 | 0.003525 | import files
CURRENT_LANGUAGE = 'ger'
class dictionary:
def __init__(self):
pass
score = {'ger': 'Punkte',
'bay': 'Punkte',
}
rank = {'ger': 'Platz',
'bay': 'Bloz',
}
time = {'ger': 'Datum',
'bay': 'Datum',
}
usern... | return getattr(dictionary, word.lower())[lang()]
except KeyError:
return word
def lang_button_image():
return files.resource_path('', 'images\\' + lang() + '_' + switch_language(False) + '.png')
def switch_language(doSwitch=True):
global CURRENT_LANGUAGE
if CURRENT_LANGUAGE == 'ger' | :
if doSwitch:
CURRENT_LANGUAGE = 'eng'
return 'eng'
elif CURRENT_LANGUAGE == 'eng':
if doSwitch:
CURRENT_LANGUAGE = 'bay'
return 'bay'
elif CURRENT_LANGUAGE == 'bay':
if doSwitch:
CURRENT_LANGUAGE = 'ger'
return 'ger'
longNam... |
VulcanTechnologies/oauth2lib | oauth2lib/utils.py | Python | mit | 2,411 | 0.005807 | from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlpars... | nparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
| url.fragment))
|
namccart/pybombs | pybombs/utils/sysutils.py | Python | gpl-3.0 | 4,522 | 0.002654 | #
# Copyright 2015 Free Software Foundation, Inc.
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# PyB... | #
# You should have received a copy of the GNU General Public License
# along with PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA | .
#
"""
System Utils
"""
from __future__ import print_function
import re
import os
import os.path as op
from pybombs.pb_exception import PBException
def which(program, env=None):
"""
Equivalent to Unix' `which` command.
Returns None if the executable `program` can't be found.
If a full path is given ... |
danstoner/python_experiments | pgu/examples/gui5.py | Python | gpl-2.0 | 1,996 | 0.021042 | """Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
# the following line is not needed if pgu is installed
import sys; sys.path.insert(0, "..")
from pgu import gui
# Load an alternate theme to show how it is done. You can also
# speci... | )
c.td(gui.Checkbox(g,value=2))
c.td(gui.Checkbox(g,value=3))
##
c.tr()
c.td(gui.Label("Radio"))
g = gui.Group()
c.td(gui.Radio(g,value=1))
c.td(gui.Radio(g,value=2))
c.td(gui.Radio(g,value=3))
c.tr()
c.td(gui.Label("Select"))
e = gui.Select()
e.add("Goat",'goat')
e.add("Horse",'hor | se')
e.add("Dog",'dog')
e.add("Pig",'pig')
c.td(e,colspan=3)
c.tr()
c.td(gui.Label("Tool"))
g = gui.Group(value='b')
c.td(gui.Tool(g,gui.Label('A'),value='a'))
c.td(gui.Tool(g,gui.Label('B'),value='b'))
c.td(gui.Tool(g,gui.Label('C'),value='c'))
c.tr()
c.td(gui.Label("Input"))
def cb():
print("Input received")
w ... |
maweis1981/hey001 | mayversion/mayversion/accounts/models.py | Python | lgpl-3.0 | 4,215 | 0.024061 | #!/usr/bin/env python
# encoding: utf-8
from django.db import models,connection
from django.contrib.auth.models import User,UserManager
class UserProfile(models.Model):
GENDER_CHOICES = (
(1, '男'),
(2, '女'),
)
PROVINCE_CHOICES = (
('JiangSu','江苏'),
('ShangHai','上海'),
('ShangHai','上海... | efault=1)
drinking = models.CharField("喝酒", max_length=10, choices = DEGREE_CHOICES,default=1)
family = models.CharField("家庭情况", max_length=10)
language = models.Cha | rField("语言", max_length=10)
hobby = models.CharField("兴趣", max_length=10)
short = models.SlugField("座右铭")
def set_user_id(self,raw_user_id):
raw_user = UserProfile.objects.get(pk = raw_user_id)
if raw_user:
self.user = raw_user
else:
raise Exception('no user ... |
ostravaTokyo/hfls | python/readFetiData.py | Python | unlicense | 14,274 | 0.027533 | import numpy as np
from scipy import sparse
import scipy.sparse.linalg as spla
import pylab as plt
from scipy.linalg import block_diag
#
#
nSub = 2
def load_matrix_basic(pathToFile,makeSparse,makeSymmetric, offset):
f0 = open(pathToFile).readlines()
firstLine = f0.pop(0) #removes the first line
tmp = np.z... | KplusBcT_p = []
Bc_nonzRow = []
|
KplusBcT = []
BcKplus_tmp = []
# BcK_dense = []
K_UT = []
# x_out = []
# x_out_p = []
# Lumped = []
# Lumped = []
for i in range(nSub):
K.append(load_matrix(path0,"dump_K_","",str(i),False,True,1))
K_UT.append(load_matrix(path0,"dump_K_","",str(i),False,False,1... |
tundish/volcasample | volcasample/project.py | Python | gpl-3.0 | 8,341 | 0.000959 | #!/usr/bin/env python3
# encoding: UTF-8
# This file is part of volcasample.
#
# volcasample is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | )
metadata = os. | path.join(path, "{0:02}".format(n), "metadata.json")
with open(metadata, "w") as new:
json.dump(tgt, new, indent=0, sort_keys=True)
yield tgt
@staticmethod
def check(path, start=0, span=None, quiet=False):
stop = min(100, (start + span) if span is not None else ... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/cronscripts/rosetta-approve-imports.py | Python | agpl-3.0 | 523 | 0 | #!/usr/bin/python -S
#
# Copyright 2009 Canonical Ltd. This software is licensed under the
# GNU | Affero General Public License version 3 (see the file LICENSE).
"""Perform auto-approvals and auto-blocks on translation import queue"""
import _pythonpath
from lp.translations.scripts.import_queue_ga | rdener import ImportQueueGardener
if __name__ == '__main__':
script = ImportQueueGardener(
'translations-import-queue-gardener',
dbuser='translations_import_queue_gardener')
script.lock_and_run()
|
marioharper182/OptionsPricing | Accelerate/pnlEuropean.py | Python | apache-2.0 | 3,084 | 0.027562 | __author__ = 'Mario'
import wx
import wx.xrc
###########################################################################
## Class MainPanel
###########################################################################
class MainPanel ( wx.Panel ):
def __init__( self, parent ):
wx.Panel.__init__ ( self, pa... | g, wx.DefaultPosition, wx.DefaultSize, 0 )
txtCtrlSizer.Add( self.OptionYears, 0, wx.ALL, 5 )
self.OptionYearsText = wx.StaticText(self, -1, 'Option | Time Length', pos = wx.Point(125, 75))
self.RiskFree = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
txtCtrlSizer.Add( self.RiskFree, 0, wx.ALL, 5 )
self.RiskFreeText = wx.StaticText(self, -1, 'Risk Free Rate', pos = wx.Point(125, 110))
self.Vol... |
citrix-openstack-build/debtcollector | debtcollector/removals.py | Python | apache-2.0 | 3,792 | 0 | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 requir... | efix_pre = "Using function/method"
except AttributeError:
f_name = f.__name__
qualified = False
if not qualified:
_prefix_pre = "Using function/method"
if instance is None:
# Decorator was used on a class
if inspect.isclass... | ).__name__
if module_name == '__main__':
f_name = reflection.get_class_name(
f, fully_qualified=False)
else:
f_name = reflection.get_class_name(
f, fully_qualified=True)
... |
F5Networks/f5-common-python | f5/bigip/tm/sys/test/functional/test_folder.py | Python | apache-2.0 | 3,258 | 0 | # Copyright 2016 F5 Networks 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... | assert f.fullPath == '/'
def test_load_root_folder_by_partition(self, mgmt_root):
fc = mgmt_root.tm.sys.folders
f = fc.folder.load(partition='/')
assert f.name == '/'
assert f.fullPath == '/'
def test_load_root_no_attributes(self, mgmt_root):
fc = mgmt_root.tm.sys.fo... | rt f.name == '/'
assert f.fullPath == '/'
class TestFolderCollection(object):
def test_get_collection(self, request, mgmt_root):
setup_folder_test(request, mgmt_root, 'testfolder', '/')
fc = mgmt_root.tm.sys.folders
folders = fc.get_collection()
assert len(folders)
... |
mluo613/osf.io | osf/migrations/0026_preprintservice_license.py | Python | apache-2.0 | 583 | 0.001715 | # -*- coding: utf-8 -*-
# Generated by | Django 1.9 on 2016-12-09 21:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('osf', '0025_preprintprovider_social_instagram'),
]
operations = [
migrations.AddFie... | name='license',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='osf.NodeLicenseRecord'),
),
]
|
huntxu/neutron | neutron/tests/functional/agent/test_dhcp_agent.py | Python | apache-2.0 | 17,256 | 0.000174 | # Copyright (c) 2015 Red Hat, 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 require... | 4: {'addr': '192.168.10.11',
'cidr': '192.168.10.0/24',
'gateway': '192.168.10.1'},
6: {'addr': '2001:db8:0:1::c0a8:a0b',
'cidr': '20 | 01:db8:0:1::c0a8:a00/120',
'gateway': '2001:db8:0:1::c0a8:a01'}, }
def setUp(self):
super(DHCPAgentOVSTestFramework, self).setUp()
config.setup_logging()
self.conf_fixture = self.useFixture(fixture_config.Config())
self.conf = self.conf_fixture.conf
dhcp_agent.re... |
DedMemez/ODS-August-2017 | building/DistributedSuitInterior.py | Python | apache-2.0 | 16,068 | 0.004232 | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.building.DistributedSuitInterior
from panda3d.core import Point3, Vec3, headsUp
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from ElevatorConstants import *
import ElevatorUtils
from toontown.toonbase i... | elIn != None:
| self.elevatorModelIn.removeNode()
if self.elevatorModelOut != None:
self.elevatorModelOut.removeNode()
if self.floorModel != None:
self.floorModel.removeNode()
self.leftDoorIn = None
self.rightDoorIn = None
self.leftDoorOut = None
self.rig... |
Xobb/fabric-bolt | src/fabric_bolt/projects/views.py | Python | mit | 17,972 | 0.003561 | """
Views for the Projects App
"""
import datetime
import subprocess
import sys
from django.http import StreamingHttpResponse, HttpResponseRedirect
from django.db.models.aggregates import Count
from django.contrib import messages
from django.views.generic import CreateView, UpdateView, DetailView, View, DeleteView, R... | .Project.objects.get(pk=project_id)
return super(BaseGetProjectCreateView, self).dispatch(request, *args, **kwargs)
class ProjectList(SingleTableView):
"""
Project List page
"""
table_class = tables.ProjectTable
model = models.Project
queryset = models.Project.active_records.all()
... | s ProjectCreate(CreateView):
"""
Create a new project
"""
model = models.Project
form_class = forms.ProjectCreateForm
template_name_suffix = '_create'
def form_valid(self, form):
"""After the form is valid lets let people know"""
ret = super(ProjectCreate, self).form_valid... |
coxmediagroup/django-shorturls | src/shorturls/urls.py | Python | bsd-3-clause | 255 | 0.039216 | from django.conf import s | ettings
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(
regex = '^(?P<prefix>%s)(?P<tiny>\w+)$' % '|'.join(settings.SHORTEN_MODELS. | keys()),
view = 'shorturls.views.redirect',
),
) |
the-blue-alliance/the-blue-alliance | src/backend/common/helpers/rankings_helper.py | Python | mit | 1,985 | 0.001008 | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys... | }
if year not in cls.QUAL_AVERAGE_YEARS:
qual_average = None
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return... | "team_key": team_key,
"record": record, # None if record doesn't affect rank (e.g. 2010, 2015)
"qual_average": qual_average, # None if qual_average doesn't affect rank (all years except 2015)
"matches_played": int(matches_played),
"dq": int(dq),
"sort_orders... |
d53dave/cgopt | csaopt/instancemanager/awstools.py | Python | mit | 13,839 | 0.004119 | import boto3
import logging
import time
from string import Template
from pyhocon import ConfigTree
from botocore.exceptions import ClientError
from typing import List, Any, Tuple, Dict
from . import Instance
from .instancemanager import InstanceManager
from ..utils import random_str, random_int
log = logging.getLogg... | interpolate_userscript_template_vals(script: bytes, **kwargs: str) -> bytes:
return Template(script.decode('utf-8')).substitute(kwargs).encode()
def _has_exit_status(instance) -> bool:
instance.reload()
return instance.state['Name'] == 'shutting-down' or instance.state['Name'] == 'terminated'
class AWST... | tes required instances on `__enter__()`, disposing of the managed instances in
`__exit__()`. These two methods as well as :meth:`instancemanager.awstools.AWSTools.get_running_instances` are the
only methods called by the Runner (i.e. the only public methods).
This class will use boto3 to (1) create a secur... |
SUSE/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/version.py | Python | mit | 494 | 0 | # 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 co... | # regenerated.
# --------------------------------------------------------------------------
VERSION = "5.6.130"
|
rdmilligan/SaltwashAR | scripts/robot.py | Python | gpl-3.0 | 3,499 | 0.003715 | # Copyright (C) 2015 Ross D Milligan
# GNU GENERAL PUBLIC LICENSE Version 3 (full notice can be found at https://github.com/rdmilligan/SaltwashAR)
from rockyrobotframes import *
from sportyrobotframes import *
from constants import *
class Robot:
def __init__(self):
self.body_frame = None
self.he... | self.head_angry_frames)
else:
self._render_head(self.head_passive_frames)
# render the robot's head
def _render_head(self, frames):
self.head_frame_index += 1
if self.head_frame_index >= len(frames):
sel | f.head_frame_index = 0
glCallList(frames[self.head_frame_index])
class RockyRobot(Robot):
# load frames
def load_frames(self, is_animated):
self.body_frame = rocky_robot_body_frame()
self.head_passive_frames = rocky_robot_head_passive_frames(is_animated)
self.head_speaking... |
arsenovic/clifford | clifford/g3c.py | Python | bsd-3-clause | 240 | 0 | from . import Cl, conformalize
layout_orig, blades_orig = Cl(3)
layout, bla | des, stuff = conformalize(layout_orig)
locals().update(blades)
locals().update(stuff)
# for shorter reprs
layout.__name__ = 'layout'
layout.__module__ = | __name__
|
ahtn/keyplus | host-software/keyplus/constants/settings.py | Python | mit | 3,115 | 0.004815 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 jem@seethis.link
# Licensed under the MIT license (http://opensource.org/licenses/MIT)
from keyplus.utility import inverse_map
AES_KEY_LEN = 16
EP_VENDOR_SIZE = 64
VENDOR_REPORT_LEN = 64
FLASH_WRITE_PACKET_LEN = EP_VENDOR_SIZE - 5
SETTINGS_RF_INFO_SIZE =... | ##
SUPPORT_SCANNING_MASK = 0x01
SUPPORT_SCANNING_COL_ROW_MASK = 0x02
SUPPORT_SCANNING_ROW_COL_MASK = 0x04
SUPPORT_SCANNING_PINS_MASK = 0x08
SUPPORT_SCANNING_ARBITRARY_MASK = 0x10
SUPPORT_SCANNING_BUILT_IN_MASK = 0x20
SUPPORT_KEY_MEDIA = 0x01
SUPPORT_KEY_MOUSE = 0x02
SUPPORT_KEY_LAYERS = 0x04
SUPPORT_KEY_STICKY = 0x08... | RT_KRO_6 = 0x02;
SUPPORT_LED_INDICATORS = 0x01
SUPPORT_LED_BACKLIGHTING = 0x02
SUPPORT_LED_WS2812 = 0x04
SUPPORT_NRF24 = 0x01
SUPPORT_I2C = 0x02
SUPPORT_UNIFYING = 0x04
SUPPORT_USB = 0x08
SUPPORT_BT = 0x10
VERSION_IS_STABLE = 0x01
VERSION_RESERVED_1 = 0x02
VERSION_RESERVED_2 = 0x04
VERSION_RESERVED_3 = 0x08
SUPPOR... |
mozilla/captain | captain/wsgi.py | Python | mpl-2.0 | 1,653 | 0.00121 | """
WSGI config for captain project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... | . For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import site
# We defer to a DJANGO_SETTINGS_MOD | ULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "captain.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "captain.settings")
... |
ANR-kamoulox/Telemeta | telemeta/models/corpus.py | Python | agpl-3.0 | 2,752 | 0.002544 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Samalyse SARL
# Copyright (C) 2010-2014 Parisson SARL
# This file is part of Telemeta.
# 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 Free Software Foundation, eithe... |
from telemeta.models.collection import *
class MediaCorpus(MediaBaseResource):
"Describe a corpus"
element_type = 'corpus'
children_type = 'collections | '
children = models.ManyToManyField(MediaCollection, related_name="corpus",
verbose_name=_('collections'), blank=True)
recorded_from_year = IntegerField(_('recording year (from)'), help_text=_('YYYY'))
recorded_to_year = ... |
mhotwagner/backstage | foti/serializers.py | Python | mit | 343 | 0 | from r | est_framework import serializers
from .models import Foto
class FotoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Foto
fields = (
'id',
'name',
'location',
'date',
'image',
'created',
'up... | )
|
krafczyk/spack | var/spack/repos/builtin/packages/leveldb/package.py | Python | lgpl-2.1 | 2,768 | 0.000723 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | the GNU Lesse | r General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import glob
from spack import *
class Leveldb(MakefilePackage):
"""LevelDB... |
1ukash/horizon | horizon/dashboards/project/networks/forms.py | Python | apache-2.0 | 2,056 | 0.000486 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# ... | 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, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License f... | the License.
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import api
from horizon import exceptions
from horizon import forms
from horizon import messages
LOG = logging.getLogger(__name__)
class UpdateNetwork(forms.SelfHandlingFo... |
microsoft/task_oriented_dialogue_as_dataflow_synthesis | tests/test_dataflow/multiwoz/test_create_programs.py | Python | mit | 10,600 | 0.002075 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import json
import os
from typing import Any, Dict, Iterator, List
from dataflow.core.utterance_tokenizer import UtteranceTokenizer
from dataflow.multiwoz.create_programs import create_programs_for_trade_dialogue
from dataflow.multiwoz.salience... | Dict[ | str, Any]):
utterance_tokenizer = UtteranceTokenizer()
salience_model = VanillaSalienceModel()
expected_plans: List[str] = [
# turn 1
"""(find (Constraint[Hotel] :area (?= "none") :book-day (?= "none") :book-people (?= "none") :book-stay (?= "none") :internet (?= "none") :name (?= "none") :... |
RoyalTS/econ-python-environment | waf.py | Python | bsd-3-clause | 1,785 | 0 | #!/usr/bin/env python
# Thomas Nagy, 2005-2013
# Modifications by Hans-Martin von Gaudecker for econ-project-templates
"""
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 ab... | ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXE | MPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT ... |
jwesstrom/cleverMirror | main.py | Python | gpl-3.0 | 1,864 | 0.004299 | # -*- coding: utf-8 -*-
import datetime
from kivy.app import App
from kivy.uix.widget import Widget
import random
from kivy.clock import Clock
from kivy.properties import StringProperty, NumericProperty
from webScrape import webScraper
class MirrorWindow(Widget):
dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', ... | NumericProperty(0)
time = StringProperty('')
day = StringProperty('')
date = StringProperty('')
weather1 = StringProperty('')
weather2 = Strin | gProperty('')
weather3 = StringProperty('')
seconds = StringProperty('')
def update(self, dt):
self.time = datetime.datetime.today().strftime("%H:%M")
self.day = self.dayPrint[int(datetime.date.today().strftime('%w'))]
self.date = datetime.date.today().strftime('%y%m%d')
#se... |
fp7-ofelia/pypelib | src/pypelib/persistence/backends/django/RuleTableModel.py | Python | lgpl-3.0 | 1,069 | 0.034612 | import os
import sys
import time
from django.db import models
'''
@author: lbergesio,omoya,CarolinaFernandez
@organization: i2CAT, OFELIA FP7
Django RuleTable Model class
'''
#Django is required to run this model
class PolicyRuleTableModel(models.Model):
class Meta:
"""Rul... | .CharField(max_length = 64, default="", blank =True, null =True)
defaultPersistence = models.CharField(max_length = 64, default="", blank =True, | null =True)
defaultPersistenceFlag = models.BooleanField()
|
pinterest/teletraan | deploy-agent/tests/unit/deploy/utils/test_exec.py | Python | apache-2.0 | 5,911 | 0.001184 | # Copyright 2016 Pinterest, 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... | RETRY | = 3
executor.PROCESS_POLL_INTERVAL = 2
executor.BACK_OFF = 2
executor.MAX_SLEEP_INTERVAL = 60
executor.MAX_TAIL_BYTES = 10240
deploy_report = executor.run_cmd(cmd=cmd)
self.assertTrue(ping_server.called)
self.assertEqual(deploy_report.status_code, AgentStatus.SCRI... |
abathur/dbg_census | dbg_census/eq2.py | Python | apache-2.0 | 128 | 0.03125 | from . import census
class Stat | s(census.Stats):
namespace = "eq2"
def __str__(self):
return | "EVERQUST 2 STATS API"
|
PascualArroyo/Domotics | Server/myconfig.py | Python | gpl-2.0 | 9,785 | 0.006847 | #Es necesario cambiar estos datos por los parametros de nuestro servidor, usuarios, password
userDb = "userDb"
passDb = "passDb"
mail = "*********@gmail.com"
passMail = "passMail"
nameDb = "domotics_db"
urlDb = "urlDb"
serverPort = 8080
#Security Code Device
updateCode = "UPDATE device SET code = '%s' WHERE id = '%s... | e.timeStamp = NOW() WHERE id = '%s' AND code = '%s'"
#Check Device Remote for Delete
checkDeviceRemote = "SELECT id FROM de | vice WHERE idDevice = '%s'"
#Delete devices
deleteTimerDevice = "DELETE FROM timer WHERE idDevice = '%s'"
deleteAlertDevice = "DELETE FROM alert WHERE idDevice = '%s'"
deleteSensorsData = "DELETE FROM sensors WHERE idDevice = '%s'"
deleteLocationDevice = "DELETE FROM locationDevice WHERE idDevice = '%s'"
deleteDevice ... |
Yelp/paasta | paasta_tools/check_services_replication_tools.py | Python | apache-2.0 | 8,925 | 0.000896 | # Copyright 2015-2019 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | import Optional
from typing import Sequence
from typing import Tuple
from typing | import Type
from typing import Union
import a_sync
from marathon import MarathonClient
from marathon.models.task import MarathonTask
from mypy_extensions import Arg
from mypy_extensions import NamedArg
from paasta_tools.kubernetes_tools import get_all_nodes
from paasta_tools.kubernetes_tools import get_all_pods
from... |
edsfault/Edsfault-processing.js | tools/packer.py | Python | mit | 1,163 | 0.009458 | #!/usr/bin/env python
import sys, os, os.p | ath, signal
import jsshellhelper
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
# Uses jsshell https://developer.mozilla.org/en/Introduction_to_the_JavaScript_shell
class Pa | cker(object):
toolsdir = os.path.dirname(os.path.abspath(__file__))
def run(self, jsshell, filename):
tmpFile = jsshellhelper.createEscapedFile(filename)
cmd = [jsshell,
'-f', os.path.join(self.toolsdir, 'packer.js'),
'-f', os.path.join(self.toolsdir, 'cleaner.js'),
'-f', ... |
antmicro/distant-rec | tools/shebang-replace.py | Python | apache-2.0 | 1,211 | 0.004129 | #!/usr/bin/env python3
import sys
from os import listdir, chdir
from os.path import isfile, abspath
UNTIL = '/build/'
REPLACE_WITH = '/b/f/w'
def bangchange(file_path):
script = File(file_path)
if script.flist[0].find("#!") == 0:
if script.flist[0].find(UNTIL) > 0:
print("\033[92m" + "[M... | __init__(self, path):
self.fh = open(path, "r+")
try:
self.fstring = self.fh.read()
except UnicodeDecodeError:
print("\033[94m" + "[SKP] {}".format(path))
self.fstring = ""
se | lf.flist = self.fstring.split("\n")
def flush(self):
self.fstring = "\n".join(self.flist)
self.fh.seek(0)
self.fh.write(self.fstring)
self.fh.close()
def main():
if len(sys.argv) != 2:
print("\033[91m"+"[FAIL] Invalid arguments")
return 1
chdir(sys.argv[1])... |
MyRobotLab/myrobotlab | src/main/resources/resource/Clock/clock_6_clock_stopped.py | Python | apache-2.0 | 122 | 0.016393 | clock.addListener("clockStopped", "python", "clock_stopped")
| def clock_stopped():
print("The clock | has been stopped") |
n0mjs710/DMRlink | ipsc/dmrlink_config.py | Python | gpl-3.0 | 11,481 | 0.004703 | #!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2018 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe... | 'IPSC_MODE': config.get(section, 'IPSC_MODE'),
'TS1_LINK': config.getboolean(section, 'TS1_LINK'),
'TS2_LINK': config.getboolean(section, 'TS2_LINK'),
'MODE': '',
# These items are used to create the multi-byte... | LL'),
'RCM': config.getboolean(section, 'RCM'),
'CON_APP': config.getboolean(section, 'CON_APP'),
'XNL_CALL': config.getboolean(section, 'XNL_CALL'),
'XNL_MASTER': config.getboolean(section, 'XNL_MASTER'),
... |
pluradj/incubator-tinkerpop | gremlin-python/src/main/jython/gremlin_python/process/strategies.py | Python | apache-2.0 | 5,953 | 0.001008 | '''
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 use this ... | TraversalStrategy.__init__(self)
class MatchPredicateStrategy(TraversalStrategy):
def __init__(self):
TraversalStrategy.__init__(self)
class OrderLimitStrategy(TraversalStrategy):
def __init__(self):
TraversalStrategy.__init__(self)
class PathProcessorStrategy(TraversalStrategy):
d... | ategy(TraversalStrategy):
def __init__(self):
TraversalStrategy.__init__(self)
class CountStrategy(TraversalStrategy):
def __init__(self):
TraversalStrategy.__init__(self)
class RepeatUnrollStrategy(TraversalStrategy):
def __init__(self):
TraversalStrategy.__init__(self)
class ... |
fr34k8/Archipel | ArchipelAgent/archipel-agent-hypervisor-geolocalization/archipelagenthypervisorgeolocalization/geoloc.py | Python | agpl-3.0 | 7,356 | 0.006661 | # -*- coding: utf-8 -*-
#
# geoloc.py
#
# Copyright (C) 2010 Antoine Mercadal <antoine.mercadal@inframonde.eu>
# Copyright, 2011 - Franck Villaume <franck.villaume@trivialdev.com>
# This file is part of ArchipelProject
# http://archipelproject.org
#
# This program is free software: you can redistribute it and/or modify... | s(self):
"""
This method will be called by the plugin user when it will be
necessary to register module for listening to stanza.
"""
if self.plugin_deactivated:
return
self.entity.xmppclient.RegisterHandler('iq', self.process_iq, ns=ARCHIPEL_NS_HYPERVISOR_GEOL... | if self.plugin_deactivated:
return
self.entity.xmppclient.UnregisterHandler('iq', self.process_iq, ns=ARCHIPEL_NS_HYPERVISOR_GEOLOC)
@staticmethod
def plugin_info():
"""
Return informations about the plugin.
@rtype: dict
@return: dictionary contaning ... |
jorgehog/Deux-kMC | scripts/autocorr/run.py | Python | gpl-3.0 | 881 | 0.014756 | import sys
import os
import numpy as np
sys.path.append(os.path.join(os.getcwd(), ".."))
from run_utils import run_kmc, parse_input
from ParameterJuggler import ParameterSet
def main():
controller, path, app, cfg, n_procs = parse_input(sys.argv)
alpha_values = ParameterSet(cfg, "alpha\s*=\s*(.*)\;")
a... | 20)
controller.run(run_kmc, path | , app, cfg, ask=False, n_procs=n_procs, shuffle=True)
if __name__ == "__main__":
main()
|
kustomzone/Rusthon | regtests/c++/try_except_finally.py | Python | bsd-3-clause | 301 | 0.059801 | '''
c++ finally
'' | '
def myfunc():
b = False
try:
print('trying something that will fail...')
print('some call that fails at runtime')
f = open('/tmp/nosuchfile')
except:
print('got exception')
finally:
print('finally cleanup')
b = True
TestError( b == True )
def main():
myfun | c()
|
xiaoyuanW/gem5 | configs/common/MemConfig.py | Python | bsd-3-clause | 8,019 | 0.00212 | # Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | n the options and attach them.
If requested, we make a multi-channel configuration of the
selected memory controller class by creating multiple instances of
the specific class. The individual controllers have their
parameters set such that the address range is interleaved between
them.
"""
... | = int(math.log(nbr_mem_ctrls, 2))
if 2 ** intlv_bits != nbr_mem_ctrls:
fatal("Number of memory channels must be a power of 2")
cls = get(options.mem_type)
mem_ctrls = []
# For every range (most systems will only have one), create an
# array of controllers and set their parameters to match ... |
mredar/ucldc_oai_harvest | oai_harvester/read_sqs_queue.py | Python | bsd-3-clause | 1,363 | 0.007337 | #!/usr/bin/env python
'''Check a queue and get times and info for messages in q'''
import sys
import os
import logging
import json
import datetime
import boto.sqs as sqs
QUEUE_OAI_HARVEST = os.environ.get('QUEUE_OAI_HARVEST', 'OAI_harvest')
QUEUE_OAI_HARVEST_ERR = os.environ.get('QUEUE_OAI_HARVEST_ERR', 'OAI_harvest_e... | _":
if len(sys.argv) < 2:
print ' | Usage: read_sqs_queue.py <queue_name>'
main(sys.argv)
|
sihrc/tornado-boilerplate | indico/routes/auth.py | Python | mit | 1,532 | 0.001305 | """
IndicoService Authentication Route
Creating and Maintaining Users
"""
from indico.utils.auth.auth_utils import auth, user_hash
from indico.utils.auth.facebook_utils import check_access_token
from indico.error import FacebookTokenError
from indico.utils import unpack, mongo_callback, type_check
from indico.routes.ha... | # Create User if doesn't exist
@unpack("access_tok | en", "oauth_id", "user")
@type_check(str, str, dict)
def login(self, access_token, oauth_id, user):
if not check_access_token(access_token):
raise FacebookTokenError()
@mongo_callback(self)
def sync_callback(result):
self.respond({
"user": result,... |
ifduyue/sentry | src/sentry/south_migrations/0373_backfill_projectteam.py | Python | bsd-3-clause | 95,648 | 0.007935 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import IntegrityError, models, transaction
from sentry.utils.query import RangeQuerySetWrapperWithProgressBar
class Migration(DataMigration):
# Flag to indicate if ... | "'315c19be5328426e81e059c18e6064b1'", 'max_length': '64', 'db_index': 'True'}),
'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2018, 1, 4, 0, 0)', 'db_index': 'True'}),
'id': ('sentry.db.models.fie | lds.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'redirect_uri': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'scope_list': ('sentry.db.models.fields.array.ArrayField', [], {'of': ('django.db.models.fields.TextField', [], {})}),
'scopes': ('django.... |
fperignon/siconos | CI/machinery/ci_task.py | Python | apache-2.0 | 11,193 | 0.000893 | """CI task management
Note : this should remain independant of siconos.
"""
import os
import shutil
from subprocess import check_call, CalledProcessError
import time
import multiprocessing
class TimeoutException(Exception):
pass
class RunableProcessing(multiprocessing.Process):
def __init__(self, func, *a... | e_kill=True):
if seconds == 0:
def wrapper(function):
return function
return wrapper
else:
def wrapper(function):
def inner(*args, **kwargs):
now = time.time()
proc = RunableProcessing(function, *args, **kwargs)
proc... | t(time.time() - now)
raise TimeoutException(
'timed out after {0} seconds'.format(runtime))
if not proc.done():
proc.terminate()
assert proc.done()
success, result = proc.result()
if success:
... |
ubuntu-core/snapcraft | tests/unit/plugins/v2/test_meson.py | Python | gpl-3.0 | 3,544 | 0.000847 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | "meson-parameters": {
"default": [],
"items": {"type": "string"},
"type": "array",
"uniqueItems": True,
},
"meson-version": {"default": "", "type": "string"},
... | "required": ["source"],
"type": "object",
}
),
)
def test_get_build_packages(self):
plugin = MesonPlugin(part_name="my-part", options=lambda: None)
self.assertThat(
plugin.get_build_packages(),
Equals(
... |
ajhalme/kbsim | lib/Vec2d.py | Python | gpl-3.0 | 10,798 | 0.007409 | import operator
import math
class Vec2d(object):
"""2d vector class, supports vector and scalar operators,
and also provides a bunch of high level functions
"""
__slots__ = ['x', 'y']
def __init__(self, x_or_pair, y = None):
if y == None:
self.x = x_or_pair[0... | .floordiv)
def __truediv__(self, other):
return self._o2(other, operator.truediv)
def __rtruediv__(self, other):
return self._r_o2(other, operator.truediv)
def __itruediv__(self, other):
return self._io(other, operator.floordiv)
# Modulo
def __mod__(self, o | ther):
return self._o2(other, operator.mod)
def __rmod__(self, other):
return self._r_o2(other, operator.mod)
def __divmod__(self, other):
return self._o2(other, operator.divmod)
def __rdivmod__(self, other):
return self._r_o2(other, operator.divmod)
# Expon... |
suutari-ai/shoop | shuup_tests/simple_cms/test_plugins.py | Python | agpl-3.0 | 2,133 | 0.000469 | # This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from shuup.simple_cms.plugins import PageLinksPlugin
from shuup_tests.front... | gin.get_context_data(context)["pages"]
plugin = PageLinksPlugin({"show_all_pages": True})
assert page in plugin.get_context_data(context)["pages"]
@pytest.mark.django_db
def test_plugin_renders_absolute_links():
"""
Test that the plugin renders only absolute links.
"""
context = get_jinja_con... | visible_in_menu=True)
absolute_link = "/%s" % page.url
plugin = PageLinksPlugin({"show_all_pages": True})
assert absolute_link in plugin.render(context)
|
Matt-Stammers/Python-Foundations | Simple Functions/Reversing_split_words.py | Python | gpl-3.0 | 450 | 0.011111 | # What if you j | ust wanted to split a word in half and return each half on its own:
# You could do the following:
def reverse(st):
words = list(st.split(' '))
print(words)
rev_word = words[::-1]
print(rev_word)
return ' '.join(rev_word)
# but this can be condensed to one sentence:
def reverse(st):
return... | (st.split(' ')))
|
jllivermont/hotjar-task | survey/notifier.py | Python | apache-2.0 | 457 | 0 | import os
import pusher
CHANNEL = | "response-updates"
client = pusher.Pusher(
app_id=os.environ.get("PUSHER_APP_ID"),
key=os.environ.get("PUSHER_KEY"),
secret=os.environ.get("PUSHER_SECRET"),
cluster='eu',
ssl=True
) if "IS_PROD" in os.environ else None
def notify(msg_type, payload):
"""Notifies that a SurveyResponse has been ... | d or modified"""
if client is not None:
client.trigger(CHANNEL, msg_type, payload)
|
ccc-ffm/christian | modules/hq.py | Python | gpl-3.0 | 3,293 | 0.00334 | import os
from datetime import datetime
class HQ(object):
def __init__(self, fpath, kpath):
self.people_in_hq = 0
self.keys_in_hq = 0
self.joined_users = []
self.hq_status = 'unknown'
self.status_since = datetime.now().strftime('%Y-%m-%d %H:%M')
self.is_clean = True... | an = True
self.savestates()
def hq_dirty(self):
self.is_clean = False
self.savestates()
def hq_join(self,user):
self.people_in_hq += 1
self.joined_users.append(user)
self.savestates()
def hq_leave(self,user):
if user in self.joined_users:
... | sers.remove(user)
self.savestates()
def hq_keyjoin(self,user):
self.keys_in_hq +=1
self.joined_keys.append(user)
self.hq_join(user)
def hq_keyleave(self,user):
if user in self.joined_keys:
self.keys_in_hq -=1
self.joined_keys.remove(user)
... |
felinx/poweredsites | poweredsites/libs/decorators.py | Python | apache-2.0 | 3,016 | 0.002984 | # -*- coding: utf-8 -*-
#
# Copyright(c) 2010 poweredsites.org
#
# 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... | do.web import HTTPError
from tornado.options import options
from poweredsites.libs import cache # cache decorator alias
def admin(method):
"""Decorate with this method to restrict to site admins."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if no | t self.current_user:
if self.request.method == "GET":
url = self.get_login_url()
if "?" not in url:
url += "?" + urllib.urlencode(dict(next=self.request.full_url()))
self.redirect(url)
return
raise HTTPErr... |
mpetyx/pyrif | 3rdPartyLibraries/FuXi-master/test/additionalDLPTests.py | Python | mit | 8,179 | 0.002078 | # import copy
# import sys
import unittest
from rdflib.graph import Graph
# from rdflib.namespace import NamespaceManager
from rdflib import (
# RDF,
# RDFS,
Namespace,
# Variable,
# Literal,
# URIRef,
# BNode
)
from rdflib.util import first
from FuXi.Rete.RuleStore import (
# N3RuleStore,
Setup... | pDescriptionLogicProgramming(
self.ontGraph,
addPDSemantics=False,
constructNetwork=False)
self.assertEqual(
repr(rules),
"set([Forall ?X ( ex:Foo(?X) :- " + \
"And( ex:someProp(?X ex | :fish) ex:Bar(?X) ) )])")
def testNestedConjunct(self):
nestedConj = (EX.Foo & EX.Bar) & EX.Baz
(EX.Omega) += nestedConj
ruleStore, ruleGraph, network = SetupRuleStore(makeNetwork=True)
rules = network.setupDescriptionLogicProgramming(
self.ontGraph,
... |
ooovector/qtlab_replacement | plotting_scripts/gain_compression_upd.py | Python | gpl-3.0 | 892 | 0.045964 | import tables
from numpy import *
from matplotlib.pyplot import *
from matplotlib.widgets import Button
#Open HDF5 data file
db = lambda x: 20*log10(x)
ax1 = sub | plot(2,2,1)
ax2 = subplot(2,2,2)
ax3 = subplot(2,2,3)
def update(event):
f = tables.open_file('data.h5', mode='r')
data_2d = array(f.root.data)
c | _coord = array(f.root.column_coordinate)
r_coord = array(f.root.row_coordinate)
ind = int(len(c_coord)/2)+2
ref = array(f.root.ref)
data_2d = data_2d/ref
ax1.clear()
m1=ax1.pcolormesh( c_coord, r_coord, db(abs(data_2d)) )
ax2.clear()
m2 = ax2.plot( c_coord, db(abs(data_2d[0])) )
ax2.grid()
ax3.clear()
m3 =... |
arborh/tensorflow | tensorflow/python/keras/mixed_precision/experimental/layer_correctness_test.py | Python | apache-2.0 | 5,874 | 0.003745 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | rgs:
f32_layer: A float32 layer. The other three layers will automatically
be created | from this
input_shape: The shape of the inputs to the layer, including the batch
dimension.
"""
strategy = create_mirrored_strategy()
# Create the layers
assert f32_layer.dtype == f32_layer._compute_dtype == 'float32'
config = f32_layer.get_config()
distributed_f32_layer = f32_la... |
foxmask/orotangi | setup.py | Python | bsd-3-clause | 1,297 | 0 | from setuptools import setup, find_packages
from orotangi import __version__ as version
install_requires = [
'Django==1.11.18',
'djangorestframework==3.6.2',
'django-cors-headers==2.0.2',
'django-filter==1.0.2',
'python-dateutil==2.6.0'
]
setup(
name='orotangi',
version=version,
descri... | oxmask/orotangi/"
"archive/orotangi-" + version + ".zip",
packages | =find_packages(exclude=['orotangi/local_settings']),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.11',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
... |
roadmapper/ansible | test/units/modules/cloud/amazon/test_aws_acm.py | Python | gpl-3.0 | 4,581 | 0.000873 | # (c) 2019 Telstra Corporation Limited
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... | st chain split fun | ction on super simple (invalid) certs
expected = ['aaa', 'bbb', 'ccc']
for fname in ['simple-chain-a.cert', 'simple-chain-b.cert']:
path = fixture_suffix + '/' + fname
with open(path, 'r') as f:
pem = to_text(f.read())
actual = pem_chain_split(module, pem)
actual = [... |
uvbs/steam-limiter | updateapp/main.py | Python | bsd-2-clause | 18,251 | 0.011506 | #!/usr/bin/env python
#
# Copyright (C) 2011 Nigel Bree
# 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 co... | larly to iPrimus, these small regional ISPs don't document what they
# do and so | me of this data may be out of data due to acquisitions, since the
# iiNet group has acquired a lot of regional ISPs.
15: { 'name': 'Westnet Internet Services (Perth, WA)',
'filter': 'content*.steampowered.com=valve217.cs.steampowered.com,files-oc-syd.games.on.net',
'allow': '//steam.cdn.on.... |
stianvi/ansible-modules-core | cloud/openstack/_quantum_router.py | Python | gpl-3.0 | 7,042 | 0.007242 | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, Benno Joy <benno@ansible.com>
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ... |
try:
routers = neutron.list_routers(**kwargs)
except Exception as e:
module.fail_json(msg = "Error in getting the router list: %s " % e.message)
if not routers['routers']:
return None
return routers['routers'][0]['id']
def _create_router(module, neutron):
router = {
... | create_router(dict(router=router))
except Exception as e:
module.fail_json( msg = "Error in creating router: %s" % e.message)
return new_router['router']['id']
def _delete_router(module, neutron, router_id):
try:
neutron.delete_router(router_id)
except:
module.fail_json("Error i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.