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 |
|---|---|---|---|---|---|---|---|---|
xkong/baniugui | dict4ini/p3.py | Python | mit | 5,024 | 0.014928 | # $Id: p3.py,v 1.2 2003/11/18 19:04:03 phr Exp phr $
# Simple p3 encryption "algorithm": it's just SHA used as a stream
# cipher in output feedback mode.
# Author: Paul Rubin, Fort GNOX Cryptography, <phr-crypto at nightsong.com>.
# Algorithmic advice from David Wagner, Richard Parker, Bryan
# Olson, and Paul Crowley... | 5.2).
from string import translate
def _hmac_setup():
global _ipad, _opad, _itrans, _otrans
_itrans = a | rray('B',[0]*256)
_otrans = array('B',[0]*256)
for i in xrange(256):
_itrans[i] = i ^ 0x36
_otrans[i] = i ^ 0x5c
_itrans = _itrans.tostring()
_otrans = _otrans.tostring()
_ipad = '\x36'*64
_opad = '\x5c'*64
def _hmac(msg, key):
if len(key)>64:
key=sha.new(key).diges... |
rspavel/spack | var/spack/repos/builtin/packages/py-pygobject/package.py | Python | lgpl-2.1 | 2,511 | 0.001991 | # Copyright 2013-2020 Lawrence Livermore 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 PyPygobject(PythonPackage):
"""bindings for the GLib, and GObject,
to be used in Py... | =('build', 'run'), when='@3:')
depends_on('py-py2cairo', type=('build', 'run'), when='@2:2.99')
depends_on('gobject-introspection')
depends_on('gtkplus', w | hen='@3:')
patch('pygobject-2.28.6-introspection-1.patch', when='@2.28.3:2.28.6')
# patch from https://raw.githubusercontent.com/NixOS/nixpkgs/master/pkgs/development/python-modules/pygobject/pygobject-2.28.6-gio-types-2.32.patch
# for https://bugzilla.gnome.org/show_bug.cgi?id=668522
patch('pygobject... |
EnigmaCurry/ccm | tests/test_lib.py | Python | apache-2.0 | 1,241 | 0.002417 | impor | t sys
sys.path = [".."] + sys.path
from . import TEST_DIR
from ccmlib.cluster import Cluster
CLUSTER_PATH = TEST_DIR
def test1():
cluster = Cluster(CLUSTER_PATH, "test1", cassandra_version='2.0.3')
cl | uster.show(False)
cluster.populate(2)
cluster.set_partitioner("Murmur3")
cluster.start()
cluster.set_configuration_options(None, None)
cluster.set_configuration_options({}, True)
cluster.set_configuration_options({"a": "b"}, False)
[node1, node2] = cluster.nodelist()
node2.compact()
... |
google/vulkan_test_applications | gapid_tests/synchronization_tests/vkDeviceWaitIdle_test/vkDeviceWaitIdle_test.py | Python | apache-2.0 | 1,043 | 0 | # Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, softwa... | ual
from gapit_test_framework import GapitTest, require_not_equal
from vulkan_constants import VK_SUCCESS
@gapit_test("vkDeviceWaitIdle_test")
class WaitForSingleQueue(GapitTest):
def expect(self):
device_wait_idle = require(self.nth_call_of("vkDeviceWaitIdle", 1))
require_not_equal(0, device_w... | int(device_wait_idle.return_val))
|
lnielsen/invenio3 | setup.py | Python | gpl-2.0 | 4,365 | 0.000229 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Invenio Digital Library Framework."""
import os
import sys
... | ests_require = [
'check-manifest>=0.25',
'coverage>=4.0',
'isort>=4.2.2',
'pep257>=0.6.0',
'pytest-cache>=1.0',
'pytest-cov>=1.8.0',
'pytest-pep8>=1.0.6',
'pytest>=2.8.0',
]
extras_require = {
'minimal': [
'invenio-base>=0.1.0.dev20150000',
],
'core': [
'inve... |
rocco8773/bapsflib | bapsflib/_hdf/maps/controls/sixk.py | Python | bsd-3-clause | 16,445 | 0.000426 | # This file is part of the bapsflib package, a Python toolkit for the
# BaPSF group at UCLA.
#
# http://plasma.physics.ucla.edu/
#
# Copyright 2017-2018 Erik T. Everson and contributors
#
# License: Standard 3-clause BSD; see "LICENSES/LICENSE.txt" for full
# license terms and contributor agreement.
#
"""
Module for ... | igs[config_name]["probe"] = _probe_lists[pname]
# add 'receptacle'
self._configs[config_name]["receptacle"] = self._configs[config_name][
"probe"
]["receptacle"]
| # ---- get configuration dataset ----
try:
dset_name = self.construct_dataset_name(config_name)
dset = self.group[dset_name]
except (KeyError, ValueError):
# KeyError: the dataset was not found
# ValueError:... |
plaid/plaid-python | plaid/model/link_token_account_filters.py | Python | mit | 7,714 | 0.000519 | """
The Plaid API
The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from plaid.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal... | 'd | epository': (DepositoryFilter,), # noqa: E501
'credit': (CreditFilter,), # noqa: E501
'loan': (LoanFilter,), # noqa: E501
'investment': (InvestmentFilter,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'... |
openstack/freezer-api | freezer_api/tests/unit/sqlalchemy/test_migrations.py | Python | apache-2.0 | 12,143 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | self.assertIsInstance(columns.deleted_at.type, self.TIME_TYPE)
self.assertIsInstance( | columns.deleted.type, self.BOOL_TYPE)
def _check_001(self, engine, data):
clients_columns = [
'created_at',
'updated_at',
'deleted_at',
'deleted',
'user_id',
'id',
'project_id',
'client_id',
'hostnam... |
biancini/met | met/metadataparser/entity_export.py | Python | bsd-2-clause | 4,400 | 0.001364 | #################################################################
# MET v2 Metadate Explorer Tool
#
# This Software is Open Source. See License: https://github.com/TERENA/met/blob/master/LICENSE.md
# Copyright (c) 2012, TERENA All rights reserved.
#
# This Software is based on MET v1 developed for TERENA by Yaco Sistem... | y-to-xml """
doc = Document()
def __init__(self, | structure):
if len(structure) == 1:
root_name = str(structure.keys()[0])
self.root = self.doc.createElement(root_name)
self.doc.appendChild(self.root)
self.build(self.root, structure[root_name])
def build(self, father, structure):
if type(structure) ... |
NeotomaDB/Neotoma_SQL | tilia_check.py | Python | mit | 2,487 | 0.002413 | """ Check all newly written functions for the Neotoma postgres DB against
the old functions written in SQL Server T-SQL.
by: Simon Goring """
from sys import argv
from re import sub
from colorama import Fore
from colorama import Style
import requests
tilia_uri = 'http://tilia.neotomadb.org/Retrieve/'
dev_uri... | t(f"{Fore.RED}Missing{Style.RESET_ALL}: " + i["name"].lower())
missing = missing + 1
print(f"\n{Fore.GREEN}Total Matched:{Style.RESET_ALL}:" + str(matched))
print(f"{Fore.YELLOW}Matched with wrong parameters:{Style.RESET_ALL}:" + str(wrong_param))
print(f"{Fore.RED}Total Missed: | {Style.RESET_ALL}:" + str(missing))
|
tgquintela/Mscthesis | FirmsLocations/Preprocess/geo_filters.py | Python | mit | 7,868 | 0.001652 |
"""
Geofilters
----------
Filters coded oriented to filter and detect uncorrect data.
"""
import os
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.neighbors import KDTree
from pySpatialTools.Preprocess.Transformations.Transformation_2d.geo_filters\
import check_in_square_area... | es-y': new2_locs[:, 1]})
df_null_both.to_csv(os.path.join(pathdata, 'nulllocsandcps'), sep=';')
# df['cp'][null_both] = new2_cps
# df['es-x'][null_both] = new2_locs[:, 0]
# df['es-y'][null_both] = new2_locs[:, 1]
# print df.shape, null_neither.sum()
df = df[null_neither]
return df
def create... | for i in idxs:
reg = regions[i]
i_reg = np.where(u_regs == reg)[0][0]
# Random creation
loc = np.random.random(2)*std_locs[i_reg] + mean_locs[i_reg]
new_locs.append(loc)
new_locs = np.array(new_locs)
return new_locs
def create_locs2cp(locs, null_locs2cps, raw_locs, ... |
renanvicente/threadurl | setup.py | Python | apache-2.0 | 332 | 0.084337 | from distutils.core import setup
setup(
name | = 'threadurl',
version = '0.0.1',
py_modules = ['threadurl'],
author = 'renanvicente',
author | _email = '[email protected]',
url = 'http://github.com/renanvicente/threadurl',
description = 'A simple way to send a lot of requests using thread',
)
|
cheery/essence | essence3/layout.py | Python | gpl-3.0 | 11,955 | 0.007779 | from essence3.util import clamp
class Align(object):
def __init__(self, h, v = None):
self.h = h
self.v = h if v is None else v
def __call__(self, node, edge):
if edge in ('top', 'bottom'):
return node.width * self.h
if edge in ('left', 'right'):
return... | height), style):
Box.__init__(self, (0, 0, width, height), style)
class Label(Box):
def __init__(self, source, style):
self.source = source
Box.__init__(self, (0, 0, 0, 0), style)
self.offsets = None
def flowline(se | lf, edge, which):
left, top, right, bottom = self.style['padding']
if edge in ('top', 'bottom'):
return self.width * (0.0, 0.5, 1.0)[which] + left
if edge in ('left', 'right'):
if which == 0:
return top
if which == 1:
return to... |
ros2/system_tests | test_cli_remapping/test/test_cli_remapping.py | Python | apache-2.0 | 6,164 | 0.000649 | # Copyright 2018 Open Source Robotics Foundation, 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... | n(
ExecuteProcess(
cmd=command + ['--ros-args', '--remap', cli_argument.format(**locals())],
name='name_maker_' + replacement_name, env=env
)
)
test_context[replacement_name] = replacement_value.format(random_string=random_string)
launch_descr... | (unittest.TestCase):
ATTEMPTS = 10
TIME_BETWEEN_ATTEMPTS = 1
@classmethod
def setUpClass(cls):
rclpy.init()
cls.node = rclpy.create_node('test_cli_remapping')
@classmethod
def tearDownClass(cls):
cls.node.destroy_node()
rclpy.shutdown()
def get_topics(self... |
stetie/postpic | postpic/datareader/dummy.py | Python | gpl-3.0 | 7,561 | 0.000794 | #
# This file is part of postpic.
#
# postpic 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.
#
# postpic is distributed in the hope th... | s output (for example it
will pretend to have dumpid many particles).
'''
def __init__(self, dumpid, dimensions=2, randfunc=np.random.normal, seed=0, **kwargs):
super(self.__class__, self).__init__(d | umpid, **kwargs)
self._dimensions = dimensions
self._seed = seed
self._randfunc = randfunc
# initialize fake data
if seed is not None:
np.random.seed(seed)
self._xdata = randfunc(size=int(dumpid))
if dimensions > 1:
self._ydata = randfunc(s... |
streed/antZoo | test_server.py | Python | mit | 126 | 0.015873 | import sys
from antZoo.gossip import GossipServiceHandler
server = GossipServiceHandler.Server( sys. | argv[1] )
server.serve()
| |
corumcorp/redsentir | redsentir/seguridad/views.py | Python | gpl-3.0 | 3,382 | 0.015671 | from django.shortcuts import render
from django.contrib.auth.models import User
from .models import *
from django.contrib.auth.views import login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import csv
from djqscsv import render_to_csv_response
from django.contrib.auth.decor... | cts.filter(usuario_i | d=usuario.pk).order_by('id').reverse()[:20]
return render(request, 'sitio/perfil/perfil.html', {'usuario':usuario,'publicaciones':publicaciones})
|
satdav/mozillians | manage.py | Python | bsd-3-clause | 590 | 0.001695 | #!/usr/bin/env python
import os
import sys
try:
# For local development in a virtualenv:
from funfactory import manage
except ImportError:
# Production:
# Add a temporary path so that we can import the funfactory
tmp_path = os.path.join(os.path. | dirname(os.path.abspath(__ | file__)),
'vendor', 'src', 'funfactory')
sys.path.append(tmp_path)
from funfactory import manage
# Let the path magic happen in setup_environ() !
sys.path.remove(tmp_path)
manage.setup_environ(__file__)
if __name__ == "__main__":
manage.main()
|
skywalka/splunk-for-nagios | bin/liveservicestate.py | Python | gpl-3.0 | 2,474 | 0.031124 | # Script to list remote services in Nagios by accessing MK Livestatus
# Required field to be passed to this script from Splunk: status (eg. 0, 1, 2, 3, 666, 9999)
# where 666 is any non-zero status | , and 9999 is any status
import socket,string,sys,re,mklivestatus
import splunk.Intersplunk
results = []
if len(sys.argv) != 3:
print "Usage: %s [status] [host_name]" % sys.argv[0]
sys.exit(1) ... |
status_zero = 0
status2 = int(sys.argv[1])
host_name3 = sys.argv[2]
host_name2 = host_name3.lower()
if status2 == 666:
mkl_filter = ">"
status3 = status_zero
elif status2 == 9999:
mkl_filter = "!="
status3 = status2
else:
mkl_filter = "="
status3 = status2
status = "%s %d" % (mkl_f... |
jrief/django-shop-productvariations | shop_textoptions/views.py | Python | bsd-3-clause | 932 | 0.003219 | # -*- coding: utf-8 -*-
class ProductTextOptionsViewMixin | (object):
"""
DetailView Mixin class when using ProductTextOptionsMixin
"""
def get_variation(self):
"""
The post request contains information a | bout the chosen variation.
Recombine this with the information extracted from the OptionGroup
for the given product
"""
variation = super(ProductTextOptionsViewMixin, self).get_variation()
variation.update({ 'text_options': {} })
product = self.get_object()
for te... |
DzikuVx/PowerCutter | power_cutter.py | Python | gpl-2.0 | 300 | 0.043333 | #!/usr/bin/en | v python
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
def main():
# GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output( | 18, GPIO.HIGH)
time.sleep(5);
GPIO.output(18, GPIO.LOW)
GPIO.cleanup()
if __name__ == "__main__":
main()
|
akesandgren/easybuild-easyblocks | easybuild/easyblocks/n/ncurses.py | Python | gpl-2.0 | 1,919 | 0.003648 | ##
# This file is an EasyBuild reciPY as per https://github.com/easybuilders/easybuild
#
# Copyright:: Copyright 2012-2019 Uni.Lu/LCSB, NTUA
# Authors:: Cedri | c Laczny <[email protected]>, Fotis Georgatos <[email protected]>, Kenneth Hoste
# License:: MIT/GPL
# $Id$
#
# This work implements a part of the HPCBIOS project and is a component of the policy:
# http://hpcbios.readthedocs.org/en/latest/HPCBIOS_2012-90.html
##
"""
Easybuild support for building ncurses, implemented... | syblock
@author: Cedric Laczny (Uni.Lu)
@author: Fotis Georgatos (Uni.Lu)
@author: Kenneth Hoste (Ghent University)
"""
import os
from easybuild.easyblocks.generic.configuremake import ConfigureMake
class EB_ncurses(ConfigureMake):
"""
Support for building ncurses
"""
def configure_step(self):
... |
sulantha2006/Processing_Pipeline | ExecutePipeline/ExecutePipeline.py | Python | apache-2.0 | 5,465 | 0.010064 | __author__ = 'Sulantha'
import sys, argparse
sys.path.extend(['/home/sulantha/PycharmProjects/Processing_Pipeline'])
from Config import StudyConfig
from Manager.PipelineManager import PipelineManager
import logging.config
from Utils.PipelineLogger import PipelineLogger
import Config.EmailConfig as ec
from Utils.EmailCl... | nager(studyList, version)
####ToDo: Process steps sequence.
## Recurse for new data
PipelineLogger.log('root', 'info', 'Recursing for new data started ...')
pipeline.recurseForNewData()
PipelineLogger.log('root', 'info', 'Recursing for new | data done ...############')
## Add data to Sorting table.
pipeline.addNewDatatoDB()
##Get Unmoved Raw File List
pipeline.getUnmovedRawDataList()
PipelineLogger.log('root', 'info', 'Moving new data started ...')
pipeline.moveRawData()
PipelineLogger.log('root', 'i... |
vabs22/zulip | tools/linter_lib/custom_check.py | Python | apache-2.0 | 24,509 | 0.006651 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import re
import traceback
from .printer import print_err, colors
from typing import cast, Any, Callable, Dict, List, Optional, Tuple
def build_custom_checkers(by_lang):
# type: (Dict[str, List[str]])... | one space t | railing a non-space, three or more trailing spaces, and
# spaces on an empty line.
{'pattern': '((?<!\s)\s$)|(\s\s\s+$)|(^\s+$)',
'strip': '\n',
'description': 'Fix trailing whitespace'},
{'pattern': '^#+[A-Za-z0-9]',
'strip': '\n',
'description': 'Missing spa... |
dirtycoder/opbeat_python | tests/events/tests.py | Python | bsd-3-clause | 676 | 0.001479 | # | -*- coding: utf-8 -*-
from mock import Mock
from django.test import TestCase
from opbeat.events import Message
class MessageTest(TestCase):
def test_to_string(self):
unformatted_message = 'My message from %s about %s'
client = Mock()
message = Message(client)
message.logger =... | self.assertEqual(message.to_string(data), unformatted_message)
data['param_message']['params'] = (1, 2)
self.assertEqual(message.to_string(data),
unformatted_message % (1, 2))
|
tadek-project/tadek-common | tadek/engine/contexts.py | Python | gpl-3.0 | 11,158 | 0.006363 | ################################################################################
## ##
## This file is a part of TADEK. ##
## ... | raise testexec.TestAbortError("Keyboard interrupt")
except Exception, err:
execResult.errors.ap | pend(testexec.errorInfo(err))
execResult.status = testexec.STATUS_ERROR
# FIXME
# Shouldn't some exception be passed higher?
else:
execResult.status = testexec.STATUS_PASSED
finally:
result.stopTest(self.task.result, device)... |
ArdanaCLM/ardana-service | ardana_service/admin.py | Python | apache-2.0 | 8,071 | 0 | # (c) Copyright 2017-2019 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | object indicating whether the servic | e is configured to
enforce authentication
.. :quickref: Model; Returns whether authentication is required
**Example Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"isSecured": false
}
:status 200: success
"""
ret... |
shamitb/Tantal | bot/backup01.py | Python | mit | 9,157 | 0.006443 | import json
import logging
import random
import Algorithmia
import nltk
from textblob import TextBlob
from text_corpus import TextCorpus
from aylienapiclient import textapi
logger = logging.getLogger(__name__)
class RtmEventHandler(object):
def __init__(self, slack_clients, msg_writer):
self.clients = s... | confidence']
str += str2
self.msg_writer.send_message(event['channel'], str)
elif 'tag' in msg_txt:
count = 0;
client = Algorithmia.client('sim3x6PzEv6m2icRR+23rqTTcOo1') |
algo = client.algo('nlp/AutoTag/1.0.0')
tags = algo.pipe(msg_txt)
str_final = ""
#print entities.result
for item in tags.result:
if count == 0:
pass
else:
... |
bt3gl/NetAna-Complex-Network-Analysis | src/calculate_features_advanced/auto.py | Python | mit | 604 | 0.006623 | #!/usr/bin/env python
__author__ = "Mari Wahl"
__copyright__ = "Copyright 2014, The Cogent Project" |
__credits__ = ["Mari Wahl"]
__license__ = "GPL"
__version__ = "4.1"
__maintainer__ = "Mari Wahl"
__email__ = "[email protected]"
from helpers import running, constants
# change here for type of net:
NETWORK_FILES = constants.NETWORK_FILES_UN_AUTO + constants.NETWORK_FILES_DIR_AUTO
TYPE_NET_DIR = "auto/"
def... | = '__main__':
main()
|
m-vdb/ourplaylists | ourplaylists/app/migrations/0009_playlistitem_created_at.py | Python | mit | 527 | 0.001898 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('app', ' | 0008_playlistitem_network'),
]
operations = [
migrations.AddField(
model_name='playlistitem',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2014, 1 | 0, 6, 10, 0, 29, 893833), auto_now_add=True),
preserve_default=False,
),
]
|
mec07/PyLATO | tests/pylato/test_electronic.py | Python | gpl-2.0 | 17,499 | 0.000971 | import json
import numpy as np
import pytest
from pylato.electronic import Electronic, num_swaps_to_sort
from pylato.exceptions import UnimplementedMethodError
from pylato.init_job import InitJob
from pylato.main import execute_job
from tests.conftest import load_json_file
@pytest.mark.parametrize(
("array", "e... | singlet", [
[0.5, 0.5, 0.0, 0.0],
[0.5, 0.5, 0.0, 0.0],
[0.0, 0.0, 0.5, 0.5],
[0.0, 0.0, 0.5, 0.5],
], 0),
("triplet up", [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.0, ... | [0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]
], 1),
]
)
def test_quantum_number_S(self, name, rho, expected_S):
# Setup
Job = InitJob("test_data/JobDef_scase.json")
# Spin 0 density matrix
Job.Electron.rho = np.matrix(rho)
# Ac... |
angelverde/evadoc | models/menu.py | Python | gpl-3.0 | 1,321 | 0.004549 | # -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
response.KEY = KEY = 'youshallnotpass' |
#########################################################################
## this is the m | ain application menu add/remove items as required
#########################################################################
response.menu = [
]
es_nuevo = not auth.is_logged_in() and not session.id_facultad
response.nav = auth.navbar(mode="dropdown")
if es_nuevo:
# si no esta logueado y no tiene facultad como an... |
s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/test/ispy/server/debug_view_handler.py | Python | gpl-3.0 | 1,348 | 0.002967 | # 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.
"""Request handler to display the debug view for a Failure."""
import jinja2
import os
import sys
import webapp2
from common import ispy_utils
import view... | =jinja2.FileSystemLoader(os.path.dirname(views.__file__)),
extensions=['jinja2.ext.autoescape'])
class DebugViewHandler(webapp2.RequestHandler):
"""Request handler to display the debug view for a failure."""
def get(self):
"""Handles get requests to the /debug_view page.
GET Parameters:
test_r... | name.
"""
test_run = self.request.get('test_run')
expectation = self.request.get('expectation')
expected_path = ispy_utils.GetExpectationPath(expectation, 'expected.png')
actual_path = ispy_utils.GetFailurePath(test_run, expectation, 'actual.png')
data = {}
def _ImagePath(url):
retur... |
yapdns/yapdns-app | web/core/views.py | Python | mit | 3,697 | 0.001352 | from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from .search import DnsRecord
from .models import Client
from functools import wraps
from elasticsearch.helpers import bulk
from elasticsearch_dsl.connections import connections
import json
res... | nt_fields = ('service_type', 'ip')
if no | t all(k in client for k in client_fields):
raise InvalidDnsRecord('Required fields {} not present in client'.format(client_fields))
dns_record = DnsRecord(**body)
return dns_record
@csrf_exempt
@client_auth
def create_record(request):
if request.method != 'POST':
return response_from_code... |
klmitch/nova | nova/policies/assisted_volume_snapshots.py | Python | apache-2.0 | 1,590 | 0 | # Copyright 2016 Cloudbase Solutions Srl
# 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 r... | s:%s | '
assisted_volume_snapshots_policies = [
policy.DocumentedRuleDefault(
name=POLICY_ROOT % 'create',
check_str=base.SYSTEM_ADMIN,
description="Create an assisted volume snapshot",
operations=[
{
'path': '/os-assisted-volume-snapshots',
'me... |
jarretraim/py-docstack | docstack/config.py | Python | apache-2.0 | 2,382 | 0 | import logging
import random
import string
import sys
from oslo.config import cfg
# Logging setup
logger = logging.getLogger(__name__)
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(logging.DEBUG)
logger.addHandler(stdout)
logger.setLevel(logging.DEBUG)
default_opts = [
cfg.StrOpt('working_dir',
... | ture
infrastructure_group = cfg.OptGroup(name="infrastructure",
title="Infrastructure Services")
conf.register_group(infrastructure_group)
conf.register_opts(infrastructure_opts, infrastructure_group)
conf.set_default('sql_password', generate_password(12), 'infras... | gger, logging.INFO)
return conf
|
Inveracity/jinjabread | jinjabread/functions/salt/saltexceptions.py | Python | mit | 12,746 | 0.000628 | # -*- coding: utf-8 -*-
'''
This module is a central location for all salt exceptions
'''
from __future__ import absolute_import
# Import python libs
import copy
import logging
import time
# Import Salt libs
from .six import six
log = logging.getLogger(__name__)
'''
Classification of Salt exit code... | ):
'''
Used when a module runs a command which returns an error and wants
to show the user the output gracefully instead of dying
'''
def __init__(self, message='', info=None):
self.error = exc_str_prefix = message
self.info = info
if self.info:
try:
... | ix[-1] not in '.?!':
exc_str_prefix += '.'
except IndexError:
pass
exc_str_prefix += ' Additional info follows:\n\n'
# Get rid of leading space if the exception was raised with an
# empty message.
exc_str_prefix = exc... |
suutari-ai/shoop | shuup_tests/notify/fixtures.py | Python | agpl-3.0 | 3,614 | 0 | # -*- coding: utf-8 -*-
# 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.
from __future__ import unicode_literals
from django import forms
... | ä on a test",
"content_type": "plain"
}
}
TEST_TEMPLATE_LANGUAGES = ("sw", "ja", "en")
class ATestEvent(Event):
identifier = "test_event"
log_target_variable = "order"
order_language = Variable(name="Order Language", | type=Language)
just_some_text = Variable(name="Just Some Text", type=Text)
order = Variable(name="Order", type=Model("shuup.Order"))
class ATestTemplateUsingAction(Action):
identifier = "test_template_action"
template_use = TemplateUse.MULTILINGUAL
template_fields = {
"subject": forms.Char... |
cykl/codespeed | tools/migrate_script.py | Python | lgpl-2.1 | 1,602 | 0.003121 | # -*- coding: utf-8 -*-
"""Adds the default branch to all existing revisions
Note: This file is assumed to be in the same directory
as the project settings.py. Otherwise you have to set the
shell environment DJANGO_SETTINGS_MODULE
"""
import sys
import os
## Setup to import models from Django app ##
def import_from_... | Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write(
"Error: Can't find the file 'settings.py' in the directory "
"containing %r. It appears you've customized | things.\nYou'll have "
"to run django-admin.py, passing it your settings module.\n(If the"
" file settings.py does indeed exist, it's causing an ImportError "
"somehow.)\n" % __file__)
sys.exit(1)
from django.core.management import setup_environ
setup_environ(settings)
from... |
hgrimelid/feincms | example/admin.py | Python | bsd-3-clause | 323 | 0.003096 | from django.contrib import admin
from feincms.admin import editor
fr | om example.models import Cate | gory
class CategoryAdmin(editor.TreeEditor):
list_display = ('name', 'slug')
list_filter = ('parent',)
prepopulated_fields = {
'slug': ('name',),
}
admin.site.register(Category, CategoryAdmin)
|
ivanlyon/exercises | general/state_machine_process.py | Python | mit | 6,277 | 0.002708 | '''
Finite State Machine algorithm used to assess score of Python found in
statements of the form 'Python is ___'. The 2 possible scores are
'positive' and 'negative'.
Reference: http://www.python-course.eu/finite_state_machine.php
+--------------+-------------+--------------+
| From State | Input | To State... | general import state_machine
POSITIVE_ADJECTIVES = []
NEGATIVE_ADJECTIVES = []
IS_STATE = 'is_state'
PYTHON_STATE = 'Python_state'
START_STATE = 'Start'
ERROR_STATE = 'error_state'
NOT_STATE = 'not_state'
POS_STATE = 'pos_state'
NEG_STATE = 'neg_state'
END_STATE = 'End'
SENTIMENT = ''
##############################... | ''
splitted_text = text.split(None, 1)
word, text = splitted_text if len(splitted_text) > 1 else (text,'')
if word == "Python":
newState = PYTHON_STATE
else:
newState = ERROR_STATE
global SENTIMENT
SENTIMENT = process_sentiment(ERROR_STATE)
return (newState, text)
#... |
Bakkes/Slick2DRPG | res/scripts/pokemon/pokemon.py | Python | gpl-2.0 | 2,539 | 0.054746 | from org.bakkes.game.scripting.interfaces import IPokemon
from org.bakkes.game.scripting.interfaces import PokemonType
#from org.bakkes.fuzzy import *
#from org.bakkes.fuzzy.hedges import *
#from org.bakkes.fuzzy.operators import *
#from org.bakkes.fuzzy.sets import *
class Pokemon(IPokemon):
def __init__(s... | plemented"
def initialize_fuzzy(self):
raise "Fuzzymodule not initialized"
def set_earth_strength(self, newVal):
if(newVal > 0):
self.earth_strength = newVal
els | e:
self.earth_strength = 0
def set_water_strength(self, newVal):
if(newVal > 0):
self.water_strength = newVal
else:
self.water_strength = 0
def set_fire_strength(self, newVal):
if(newVal > 0):
self.fire_strength = newVal
else:
self.fire_strength = 0
class pokemon_0(Pokemo... |
hgn/bcc | examples/simple_tc.py | Python | apache-2.0 | 804 | 0.001244 | #!/usr/b | in/env python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bpf import BPF
from pyroute2 import IPRoute
ipr = IPRoute()
text = """
int hello(struct __sk_buff *skb) {
return 1;
}
"""
try:
b = BPF(text=text, debug=0)
fn = b.load_func("hello", BPF.SCHED_... | nk_lookup(ifname="t1a")[0]
ipr.tc("add", "ingress", idx, "ffff:")
ipr.tc("add-filter", "bpf", idx, ":1", fd=fn.fd,
name=fn.name, parent="ffff:", action="ok", classid=1)
ipr.tc("add", "sfq", idx, "1:")
ipr.tc("add-filter", "bpf", idx, ":1", fd=fn.fd,
name=fn.name, parent="1:", acti... |
nicolasm/lastfm-export | import.py | Python | mit | 2,386 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import logging
import sys
from lfmconf.lfmconf import get_lastfm_conf
from lfmdb import lfmdb
from stats.stats import process_track, retrieve_total_plays_from_db, \
retrieve_total_json_tracks_from_db
from queries.inserts import get_query_insert_play
logg... | ters = []
for (track_id, json_track) in new_plays:
logging.info('Track %s' % track_id)
track = json.loads(json_track)
transformed_track = process_track(track)
| artist_name = transformed_track['artist_text']
album_name = transformed_track['album_text']
track_name = transformed_track['name']
# Cut artist name if too long.
if len(artist_name) > 512:
artist_name = artist_name[:512]
# Cut track name if too long.
if len(track_name) > 512:
... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/lib/galaxy/model/migrate/versions/0121_workflow_uuids.py | Python | gpl-3.0 | 1,498 | 0.018692 | """
Add UUIDs to workflows
"""
from sqlalchemy import *
from sqlalchemy.orm import *
from migrate import *
from migrate.changeset import *
from galaxy.model.custom_types import UUIDType, TrimmedString
import logging
log = logging.getLogger( __name__ )
metadata = MetaData()
"""
Because both workflow and job reques... | pgrade(migrate_engine):
print __doc__
metadata.bind = migrate_engine
metadata.reflect()
# Add the uuid colum to the workflow table
try:
workflow_table = Table( "workflow", metadata, autoload=True )
workflow_uuid_column.create( workflow_table )
assert workflow_uuid_column is ... | low table failed: %s" % str( e ) )
return
def downgrade(migrate_engine):
metadata.bind = migrate_engine
metadata.reflect()
# Drop the workflow table's uuid column.
try:
workflow_table = Table( "workflow", metadata, autoload=True )
workflow_uuid = workflow_table.c.uuid
w... |
crate/crate-python | src/crate/client/sqlalchemy/tests/connection_test.py | Python | apache-2.0 | 2,183 | 0 | # -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate licenses
# this file to you under the Apache License, Version 2.0 (the "License"... | self.assertEqual("<Connection <Client ['http://127.0.0.1:4200']>>",
repr(conn.connection))
def test_connection_server(self):
engine = sa.create_engine(
"crate://otherhost:19201")
conn = engine.raw_connection()
self.assertEqual("<Connection <Client... | e://", connect_args={
'servers': ['localhost:4201', 'localhost:4202']
}
)
conn = engine.raw_connection()
self.assertEqual(
"<Connection <Client ['http://localhost:4201', " +
"'http://localhost:4202']>>",
repr(conn.connection))
|
l33tdaima/l33tdaima | p713m/subarray_product_less_than_k.py | Python | mit | 707 | 0.002829 | from typing import List
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 0:
return 0
l, r, prod, ans = 0, 0, 1, 0
while r < len(nums):
prod *= nums[r]
while l <= r and prod >= k:
prod /= nums[... | - l + 1
r += 1
return ans
# TESTS
tests = [
([10, 5, 2, 6], 0, 0),
([10, 5, 2, 6], 100, 8),
]
for nums, k, expected in tests:
sol = Solution()
actual = sol.numSubarrayProductLessThanK(nums, k)
print("# of subarray in", nums, "with product less than", k, "->", actual)
assert... | d
|
ckwatson/kernel | tests/quick_test.py | Python | gpl-3.0 | 893 | 0.022396 | import sys
import os
from ..data.molecular_species import molecular_species
from ..data.reaction_mechanism_class import reaction_mechanism
from ..data.condition_class import condition
from ..data.re | agent import reagent
from ..data.puzzle_class import puzzle
from ..data.solution_class import solution
def name(class_obj):
return class_obj.__name__
# depends on JSON base class
for class_being_tested in [molecular_species, condition, reaction_mechanism, reagent, puzzle, solution]:
system_output = sys.stdout # sto... | ing_tested.test()
sys.stdout.close() # close file
sys.stdout = system_output #replace stdout
if test_result:
print("PASSED", name(class_being_tested), sep=" ")
else:
print("FAILED", name(class_being_tested), sep=" ")
|
jeremiah-c-leary/vhdl-style-guide | vsg/rules/attribute_declaration/__init__.py | Python | gpl-3.0 | 189 | 0 |
from .rule_100 import rule_100
from .rule_101 import rule_101
from .rule_300 import rule_300
from .rule_500 import rule_500
from .rule_501 import rule_501
from .rule_502 import ru | le_502
| |
NixaSoftware/CVis | venv/bin/tools/build/v2/test/core_parallel_multifile_actions_1.py | Python | apache-2.0 | 1,606 | 0.000623 | #!/usr/bin/python
# Copyright 2007 Rene Rivera.
# Copyright 2011 Steven Watanabe
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# Added to guard against a bug causing targets to be used before they
# themselves have fini... | ass_d0=False)
t.write("sleep.bat", """\
::@timeout /T %1 /NOBREAK >nul
@ping 127.0.0.1 -n 2 -w 1000 >nul
@ping 127.0.0.1 -n %1 -w 1000 >nul
@exit /B 0
""")
t.write("file.jam", """\
if $(NT)
{
SLEEP = @call sleep.bat ;
}
else
{
SLEEP = sleep ;
}
actions .gen.
{
echo 001
$(SLEEP) 4
echo 002
}
rule ... | ; }
actions .use.1
{
echo 003
}
rule .use.2 { DEPENDS $(<) : $(>) ; }
actions .use.2
{
$(SLEEP) 1
echo 004
}
.gen. g1.generated g2.generated ;
.use.1 u1.user : g1.generated ;
.use.2 u2.user : g2.generated ;
DEPENDS all : u1.user u2.user ;
""")
t.run_build_system(["-ffile.jam", "-j2"], stdout="""\
...fou... |
thomastu/django-wiki | wiki/plugins/notifications/models.py | Python | gpl-3.0 | 4,121 | 0.000243 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from django.db im... | ption', 'articleplugin_ptr')
# Matches label of upcoming 0.1 release
db_table = 'wiki_notifications_articlesubscription'
if settings.APP_LABEL:
app_label = settings.APP_LABEL
def default_url(article, urlpath=None):
if urlpath:
return reverse('wiki:get', kwargs={'path': ... | rgs.get('created', False):
url = default_url(instance.article)
filter_exclude = {'settings__user': instance.user}
if instance.deleted:
notify(
_('Article deleted: %s') %
get_title(instance),
settings.ARTICLE_EDIT,
target... |
vollib/vollib | vollib/helper/numerical_greeks.py | Python | mit | 7,763 | 0.005541 | # -*- coding: utf-8 -*-
"""
vollib.helper.numerical_greeks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A library for option pricing, implied volatility, and
greek calculation. vollib is based on lets_be_rational,
a Python wrapper for LetsBeRational by Peter Jaeckel as
described below.
... | --------------------+
| b = r | gives the Black and Scholes (1973) stock option |
| | model |
+-----------+------------------------------------------------------+
| b = r -q | gives the Merton (1973) stock option model with ... | --------------+
| b = 0 | gives the Black (1976) futures option model |
+-----------+------------------------------------------------------+
| b = 0 and | gives the Asay (1982) margined futures option model |
| r = 0 | |
... |
feranick/SpectralMachine | Utilities/PlotRruffSpectraRound.py | Python | gpl-3.0 | 3,466 | 0.014426 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
*********************************************
*
* PlotRruffSpectraRound
* Plot Rruff spectra
* Files must be in RRuFF
* version: 20171208c
*
* By: Nicola Ferralis <feranick@hotm | ail.com>
*
***********************************************
'''
print(__doc__)
import numpy as np
import sys, os.path, getopt, | glob, csv, re
from datetime import datetime, date
import matplotlib.pyplot as plt
def main():
if len(sys.argv) < 4:
print(' Usage:\n python3 PlotRruffSpectraRound.py <EnIn> <EnFin> <EnStep> <decimals>\n')
print(' Requires python 3.x. Not compatible with python 2.x\n')
return
else:
... |
UManPychron/pychron | pychron/pipeline/plot/plotter/arar_figure.py | Python | apache-2.0 | 24,577 | 0.000814 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may | not us | e 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 CONDITIONS OF AN... |
OCA/bank-statement-reconcile | account_mass_reconcile_ref_deep_search/models/__init__.py | Python | agpl-3.0 | 171 | 0 | # Copyri | ght 2015-2018 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl. | html)
from . import mass_reconcile
from . import advanced_reconciliation
|
Gu1/ansible-lxc-remote | _ssh.py | Python | gpl-3.0 | 21,418 | 0.003829 | # (c) 2012, Michael DeHaan <[email protected]>
#
# 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 lat... | PIPE,
| stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdin = p.stdin
return (p, stdin)
def _password_cmd(self):
if self.password:
try:
p = subprocess.Popen(["sshpass"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIP... |
ruibarreira/linuxtrail | usr/lib/virtualbox/sdk/bindings/xpcom/python/xpcom/file.py | Python | gpl-3.0 | 11,962 | 0.006855 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | lines = lines[:-1]
return [s+"\n" for s in | lines ]
def write(self, data):
assert self.outputStream is not None, "Not setup for write!"
self._lock()
try:
self.outputStream.write(data, len(data))
finally:
self._release()
def close(self):
self._lock()
try:
if self.inputS... |
aaronprunty/starfish | vezda/examples/starfish-tutorial/data/extractData.py | Python | apache-2.0 | 609 | 0 | import numpy as np
import scipy.io as io
dataStructure = io.loadmat('starfish.mat')
r | eceiverPoints = dataStructure['receivers']
sourcePoints = dataStructure['receivers']
scattererPoints = dataStructure['scatterer']
scatteredData = dataStructure['scatteredData']
recordingTimes = dataStructure['recordTimes']
recordingTimes = np.reshape(recordingTimes, (recordingTimes.shape[1],))
np.save('receiverPoints.... | s.npy', recordingTimes)
|
anomaly/vishnu | vishnu/session.py | Python | apache-2.0 | 10,835 | 0.001292 | """
Vishnu session.
"""
from __future__ import absolute_import
from http.cookies import Morsel
from http.cookies import SimpleCookie
from datetime import datetime, timedelta
import hashlib
import hmac
import logging
import sys
import uuid
from vishnu.cipher import AESCipher
from vishnu.backend.config import Base as... | dConfig):
raise TypeError("unknown backend configuration received %s" % backend)
self._backend = backend
@property
def secret(self):
"""
:return: secret used for HMAC signature
:rtype: string
"""
return self._secret
@property
def cookie_name(... | _key(self):
"""
:return: key to use for encryption
:rtype: string
"""
return self._encrypt_key
@property
def secure(self):
"""
:return: whether the cookie can only be transmitted over HTTPS
:rtype: boolean
"""
return self._secure
... |
edbgon/rpipin | hmc5883l.py | Python | mit | 1,591 | 0.010685 | #!/usr/bin/python3
class hmc5883l:
def __init__(self, i2cbus, addr, tilt_magnitude):
self.addr = addr
self.i2cbus = i2cbus
try:
self.i2cbus.write_byte_data(addr, 0x00, 0xF8) # CRA 75Hz.
self.i2cbus.write_byte_d | ata(addr, 0x02, 0x00) # Mode continuous reads.
except OSError:
pass
| self.valX = 0
self.valY = 0
self.valZ = 0
self.iX = 0
self.iY = 0
self.iZ = 0
self.tilt_magnitude = tilt_magnitude
self.tilt_delta = 0
self.tilted = False
def update(self):
try:
X = (self.i2cbus.read_byte_data(self.addr, 0x03) << 8) | self.i2cbus.r... |
RodericDay/MKS | setup.py | Python | mit | 375 | 0 | #!/usr/bin/env | python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='MKS',
version='0.1.0',
description="A unit system based on meter, kilo, and second",
author='Roderic Day',
author_email='[email protected]',
url='www.pe... | |
jachym/PyWPS-SVN | tests/processes/dummyprocess.py | Python | gpl-2.0 | 1,590 | 0.030818 | """
DummyProcess to check the WPS structure
Author: Jorge de Jesus ([email protected]) as suggested by Kor de Jong
"""
from pywps.Process import WPSProcess
class Process(WPSProcess):
def __init__(self):
# init process
WPSProcess.__init__(self,
i... | d one an | d subtract one operation",
grassLocation =False)
self.Input1 = self.addLiteralInput(identifier = "input1",
title = "Input1 number",
default=100)
self.Input2= self.addLiteralInput(ident... |
weinbe58/QuSpin | tests/mean_level_spacing_test.py | Python | bsd-3-clause | 1,223 | 0.044154 | from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
#
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import spin_basis_1d # Hilbert space spin basis
from quspin.tools.measurements import mean_l... | ]
z_field=[[g,i] for i in range(L)]
# create static and dynamic lists
static_2=[["zz",J_zz],["x",x_field],["z",z_field]]
dynamic=[]
# create spin-1/ | 2 basis
basis=spin_basis_1d(L,kblock=0,pblock=1)
# set up Hamiltonian
H2=hamiltonian(static_2,dynamic,basis=basis,dtype=np.float64)
# compute eigensystem of H2
E2=H2.eigvalsh()
# calculate mean level spacing of spectrum E2
r=mean_level_spacing(E2)
print("mean level spacing is", r)
E2=np.insert(E2,-1,E2[-1])
r=mean_lev... |
fabiocaccamo/django-freeze | freeze/settings.py | Python | mit | 3,077 | 0.006825 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
import os
FREEZE_ROOT | = get | attr(settings, 'FREEZE_ROOT', os.path.abspath(os.path.join(settings.MEDIA_ROOT, '../freeze/')) )
if not os.path.isabs(FREEZE_ROOT):
raise ImproperlyConfigured('settings.FREEZE_ROOT should be an absolute path')
if settings.MEDIA_ROOT.find(FREEZE_ROOT) == 0 or settings.STATIC_ROOT.find(FREEZE_ROOT) == 0:
raise ... |
beni55/networkx | networkx/generators/tests/test_random_graphs.py | Python | bsd-3-clause | 4,826 | 0.019892 | #!/usr/bin/env python
from nose.tools import *
from networkx import *
from networkx.generators.random_graphs import *
class TestGeneratorsRandom():
def smoke_test_random_graph(self):
seed = 42
G=gnp_random_graph(100,0.25,seed)
G=binomial_graph(100,0.25,seed)
G=erdos_renyi_graph(100,... | assert_equal(sum(1 for _ in G.edges()), 45)
| G=gnm_random_graph(10,100,directed=True)
assert_equal(len(G),10)
assert_equal(sum(1 for _ in G.edges()),90)
G=gnm_random_graph(10,-1.1)
assert_equal(len(G),10)
assert_equal(sum(1 for _ in G.edges()),0)
def test_watts_strogatz_big_k(self):
assert_raises(networkx.exce... |
rsmith-nl/scripts | git-origdate.py | Python | mit | 1,260 | 0.000794 | #!/usr/bin/env python
# file: git-origdate.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Copyright © 2015-2018 R.F. Smith <[email protected]>.
# SPDX-License-Identifier: MIT
# Created: 2015-01-03T16:31:09+01:00
# Last modified: 2020-12-16T00:25:34+0100
"""Report when arguments were checked into git."""
import os... | nt(f"Usage: {binary} [file ...]", file=sys.stderr)
sys.exit(0)
try:
for fn in sys.argv[1:]:
args = [
"git",
"--no-pager",
"log",
"--diff-filter=A",
"--format=%ai",
"--",
fn,
]
cp = | sp.run(args, stdout=sp.PIPE, stderr=sp.DEVNULL, text=True, check=True)
# Sometimes this git command will return *multiple dates*!
# In that case, select the oldest.
date = cp.stdout.strip().splitlines()[-1]
print(f'"{fn}": {date}')
except sp.CalledProcessError as e:
if e.returncode ... |
jnayak1/osf.io | scripts/osfstorage/files_audit.py | Python | apache-2.0 | 7,198 | 0.001667 | #!/usr/bin/env python
# encoding: utf-8
"""Verify that all OSF Storage files have Glacier backups and parity files,
creating any missing backups.
TODO: Add check against Glacier inventory
Note: Must have par2 installed to run
"""
from __future__ import division
import gc
import os
import math
import hashlib
import ... | (audit_temp_path)
except OSError:
pass
if glacier:
logger.info('glacier audit start')
audit(glacier_targets(), num_of_workers, worker_id, dry_run)
logger.info('glacier audit complete')
if parity:
logger.info('parity audit star... | ger.error('=== Unexpected Error ===')
logger.exception(err)
raise err
if __name__ == '__main__':
import sys
arg_num_of_workers = int(sys.argv[1])
arg_worker_id = int(sys.argv[2])
arg_glacier = 'glacier' in sys.argv
arg_parity = 'parity' in sys.argv
arg_dry_run = 'dry' in sys.ar... |
Ricyteach/candemaker | src/candemaker/filemaker.py | Python | bsd-2-clause | 1,977 | 0.011128 | class FileOut():
'''Provides a file exporting interface compatible with the pathlib.Path API
for any iterable object.'''
def __init__(self, obj, path = None, *, mode = 'w', obj_iter = None):
self.obj = obj
self.path = path
self.mode = mode
try:
self._iter = obj._... | raise TypeError('The obj is not iterable.') from None
def to_str(self):
'''Export the object to a string.'''
return '\n'.join(self._iter())
def to_stream(self, fstream):
'''Export the object to provided stream.'''
fstream.write(self.to_str())
def __ent | er__(self):
try:
# do not override an existing stream
self.fstream
except AttributeError:
# convert self.path to str to allow for pathlib.Path objects
self.fstream = open(str(self.path), mode = self.mode)
return self
def __exit__(self, exc_t, e... |
david-cattermole/qt-learning | python/qtLearn/widgets/ui_floatAttr.py | Python | bsd-3-clause | 1,458 | 0.004115 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/data/Public/qt-learning/ui/widgets/floatAttr.ui'
#
# Created: Tue Nov 14 18:49:58 2017
# by: PyQt4 UI code generator 4.6.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Widget(objec... | Margin(3)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtGui.QLabel(Widget)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.doubleSpinBox = QtGui.QDoubleSpinBox(Widget)
self.doubleSpinBox.setObjectName("doubleSpin... | Layout.addWidget(self.doubleSpinBox)
spacerItem = QtGui.QSpacerItem(250, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.retranslateUi(Widget)
QtCore.QMetaObject.connectSlotsByName(Widget)
def retranslateUi(self, Widget):
... |
piotrdrag/guake | guake/main.py | Python | gpl-2.0 | 11,423 | 0.001401 | # -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This progra... | ument generation on readthedocs, we do not have paths.py generated
try:
from guake.paths import LOCALE_DIR
bindtextdomain(NAME, LOCALE_DIR)
except: # pylint: disable=bare-except
pass
def main():
"""Parses the command line parameters and decide if dbus methods
should be c | alled or not. If there is already a guake instance
running it will be used and a True value will be returned,
otherwise, false will be returned.
"""
# Force to xterm-256 colors for compatibility with some old command line programs
os.environ["TERM"] = "xterm-256color"
# Force use X11 backend un... |
wateraccounting/SEBAL | Processing_Scripts/METEO/CalcHumidityGLDASdata.py | Python | apache-2.0 | 978 | 0.018405 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 19 10:09:38 2017
@author: tih
"""
Tfile = r"J:\Tyler\Input\Meteo\daily\avgsurft_inst\mean\T_GLDA | S-NOAH_C_daily_2016.06.15.tif"
Pfile = r"J:\Tyler\Input\Meteo\daily\psurf_f_inst\mean\P_GLDAS-NOAH_kpa_daily_2016.06.15.tif"
Hfile = r"J:\Tyler\Input\Meteo\daily\qair_f_inst\mean\Hum_GLDAS-NOAH_kg-kg_daily_2016.06.15.tif"
Outfilename = r"J:\Tyler\Input\Meteo\daily | \Hum_Calculated\Humidity_percentage_Calculated_daily.tif"
import gdal
import os
import wa.General.raster_conversions as RC
import wa.General.data_conversions as DC
import numpy as np
geo_out, proj, size_X, size_Y = RC.Open_array_info(Tfile)
Tdata = RC.Open_tiff_array(Tfile)
Tdata[Tdata<-900]=np.nan
Pdata = RC.Open_t... |
Ingenico-ePayments/connect-sdk-python2 | ingenico/connect/sdk/domain/payment/definitions/non_sepa_direct_debit_payment_method_specific_input.py | Python | mit | 8,060 | 0.004591 | # -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.domain.definitions.abstract_payment_method_specific_input import AbstractPaymentMethodSpecificInput
from ingenico.connect.sdk.domain.payment.de... | entProduct730SpecificInput'])
if 'recurringPaymentSequenceIndicator' in dictionary:
self.recurring_payment_sequence_indicator = dictionary['recurringPaymentSequenceIndicator']
if 'requiresApproval' | in dictionary:
self.requires_approval = dictionary['requiresApproval']
if 'token' in dictionary:
self.token = dictionary['token']
if 'tokenize' in dictionary:
self.tokenize = dictionary['tokenize']
return self
|
Manolaru/Python_train | Les_3/Task_9/test/test_modify_group.py | Python | apache-2.0 | 554 | 0.001805 | from model.group import Group
def test_modify_group_name(app):
if app.group.count() == 0:
app.group.create(Group(name="testing"))
app.group.modify_first_group(Group(name= | "NewGroup"))
def test_modify_group_header(app):
if app.group.count() == 0:
app.group.create(Group(name="testing"))
app.group.modify_first_group(Group(header="New header"))
def test_modify_group_footer(app):
if app.group.count() == 0:
app.group.create(Group(name="testing"))
app.group.... | er="New footer"))
|
dashpay/dash | test/functional/feature_llmq_is_cl_conflicts.py | Python | mit | 13,986 | 0.003075 | #!/usr/bin/env python3
# Copyright (c) 2015-2021 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import time
from decimal import Decimal
from test_framework.blocktools import get_masternode_payment, create... | id, node)
self.wait_for_instantlock(rawtx4_txid, node)
block = self.create_block(self.nodes[0], [rawtx2_obj])
if t | est_block_conflict:
# The block shouldn't be accepted/connected but it should be known to node 0 now
submit_result = self.nodes[0].submitblock(ToHex(block))
assert(submit_result == "conflict-tx-lock")
cl = self.create_chainlock(self.nodes[0].getblockcount() + 1, block)
... |
jimi-c/ansible | lib/ansible/plugins/connection/httpapi.py | Python | gpl-3.0 | 9,898 | 0.002223 | # (c) 2018 Red Hat Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
---
author: Ansible Networking Team
connection: httpapi
short_description: Use httpapi to run... | be defined as other values.
default: sudo
ini:
section: privilege_escalation
key: become_method
env:
- name: ANSIBLE_BECOME_METHOD
vars:
- name: ansible_become_method
persistent_connect_timeout:
type: int
description:
- Configures, in seconds, the amount of time ... | a persistent connection. If this value expires
before the connection to the remote device is completed, the connection
will fail
default: 30
ini:
- section: persistent_connection
key: connect_timeout
env:
- name: ANSIBLE_PERSISTENT_CONNECT_TIMEOUT
persistent_command_ti... |
aspiringguru/sentexTuts | PracMachLrng/sentex_ML_demo12.py | Python | mit | 692 | 0.011561 | '''
Euclidean Distance - Practical Machine Learning Tutorial with Python p.15
https://youtu.be/hl3bQySs8sM?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
https://en.wikipedia.org/wiki/Euclidean_distance
The distance (d) from p to q, or fro | m q to p is given by the Pythagorean formula:
d(q,p) = d(p,q) = sqrt( (q1-p1)^2 + (q2-p2)^2 + .... + (qn-pn)^2)
[recall hyptoneuse of 90 deg triangle formula h = sqrt(x^2 + y^2) where x & y are the square sides.]
euclidian distance = sqrt(Sum [i=1 to n] (qi - pi)^2)
'''
from math import sqrt
plot1 = [1,3]
plot2 = [2,... | ("euclidian_distance={}".format(euclidian_distance)) |
brenton/openshift-ansible | roles/lib_openshift/src/test/unit/test_oc_route.py | Python | apache-2.0 | 12,042 | 0.000747 | '''
Unit tests for oc route
'''
import os
import six
import sys
import unittest
import mock
# Removing invalid variable names for tests so that I can
# keep them brief
# pylint: disable=invalid-name,no-name-in-module
# Disable import-error b/c our libraries aren't loaded in jenk | ins
# pylint: disable=import-error,wrong-import-position
# place class in our pyt | hon path
module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501
sys.path.insert(0, module_path)
from oc_route import OCRoute, locate_oc_binary # noqa: E402
class OCRouteTest(unittest.TestCase):
'''
Test class for OCServiceAccount
'''
@mock.patch('o... |
ryfeus/lambda-packs | pytorch/source/caffe2/python/attention.py | Python | mit | 12,504 | 0.00008 | ## @package attention
# Module caffe2.python.attention
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import brew
class AttentionType:
Regular, Recurrent, Dot, SoftCoverage = tuple(range(4))
... | t_old_shape'),
],
shape=[1, -1, encoder_output_dim],
)
return attention_weighted_encoder_context
# Calculate a softmax over the passed in attention energy logits
def _calc_attention_weights(
model,
attention_logits_transposed,
scope,
encoder_lengths=None,
):
if encoder_leng... | der_lengths],
['masked_attention_logits'],
mode='sequence',
)
# [batch_size, encoder_length, 1]
attention_weights_3d = brew.softmax(
model,
attention_logits_transposed,
s(scope, 'attention_weights_3d'),
engine='CUDNN',
axis=1,
)
re... |
rmariotti/py_cli_rpg | test.py | Python | gpl-3.0 | 598 | 0.040201 | #!/usr/bin/env python3
import rooms
imp | ort entity
''' creazione delle stanze da creare durante il gioco '''
def rand_room(sub_rooms=1, name=1):
room_list = []
name_sub = name
while sub_rooms > 0:
name_sub = name_sub + 1
sub_rooms = sub_rooms - 1
room_list.append(rand_r | oom(sub_rooms, name_sub))
return rooms.Room(doors=room_list, description=("Door n°"+str(name)))
''' creazione di alcuni mostri '''
space_police = entity.Entity(name="space policeman",
hp=12, velocity=7,
strenght=7,
intelligence=2
hand=None
items=[]
lvl=1) |
wwu-numerik/scripts | python/paraview/paraview_metafile.py | Python | bsd-2-clause | 1,481 | 0.006752 | #!/usr/bin/env python
# - | *- coding: utf-8 -*-
import os
import sys
default_prefixes = ( 'computed__velocity', 'computed__pressure' )
ext = '.vtu'
path = os.getcwd()
pvd_header = '''<?xml version="1.0"?>
<VTKFile type="Collection" version="0.1" byte_order="LittleEndian">
<Collection>
'''
pvd_footer = '''
</Collection>
</VTKFile>'''
def w... | xcept:
cutoff = None
fn = '%s.pvd' % pref
print
fn
if cutoff:
print
'\t\tcutoff: %d' % cutoff
files = filter(lambda p: p.startswith(pref) and p.endswith(ext), os.listdir(path))
files.sort()
with open(fn, 'wb') as pvd:
... |
kubeflow/kfp-tekton-backend | sdk/python/kfp/components/_component_store.py | Python | apache-2.0 | 6,197 | 0.005164 | __all__ = [
'ComponentStore',
]
from pathlib import Path
import copy
import requests
from typing import Callable
from . import _components as comp
from .structures import ComponentReference
class ComponentStore:
def __init__(self, local_search_paths=None, url_search_prefixes=None):
self.local_search_p... | locations are:
<local-search-path>/<name>/versions/tags/<digest>
<url-search-prefix>/<name>/versio | ns/tags/<digest>
Args:
name: Component name used to search and load the component artifact containing the component definition.
Component name usually has the following form: group/subgroup/component
digest: Strict component version. SHA256 hash digest of the compo... |
NegativeMjark/mockingmirror | mockingmirror.py | Python | apache-2.0 | 4,974 | 0.000201 | # Copyright 2015 Mark Haines
#
# 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, soft... | = mirrors
self._ | mirrors.append(self)
self._is_callable = False
self._path = path
# Replace our mock and spec objects.
self._mock = NonCallableMock(name=path)
self._mock.mock_add_spec([], True)
self._spec = set()
if name is not None:
setattr(self._parent._mock, self._n... |
atados/api | atados_core/migrations/0054_auto_20160731_1811.py | Python | mit | 1,722 | 0.002904 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import atados_core.models.uploads
import django_resized.forms
class Migration(migrations.Migration):
dependencies = [
('atados_core', '0053_auto_20160728_1309'),
]
operations = [
mig... | model_name='uploadedimage',
name='image_large',
field=django_resized.forms.ResizedImageField(default=None, null=True, upload_to=atados_core.models.uploads.ImageName(b'-large'), blank=True),
preserve_default=True,
),
migrations.AlterField(
| model_name='uploadedimage',
name='image_medium',
field=django_resized.forms.ResizedImageField(default=None, null=True, upload_to=atados_core.models.uploads.ImageName(b'-medium'), blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='... |
andrius-momzyakov/grade | web/migrations/0002_auto_20170604_1403.py | Python | gpl-3.0 | 593 | 0.001704 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-04 14:03
from __future__ import unicode_literals
from django.db impor | t migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='worker',
name='jobcategories',
),
migrations.AddField(
model_name='worker',
... | ', verbose_name='Услуги'),
),
]
|
Anaconda-Platform/anaconda-client | binstar_client/commands/config.py | Python | bsd-3-clause | 6,043 | 0.001158 | '''
anaconda-client configuration
Get, Set, Remove or Show the anaconda-client configuration.
###### anaconda-client sites
anaconda-client sites are a mechanism to allow users to quickly switch
between Anaconda repository instances. This is primarily used for testing
the anaconda alpha site. But also has application... | help=description,
description=description,
epilog=__doc__,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('--type', default=safe_load,
help='... | on='append', default=[],
help='sets a new variable: name value', metavar=('name', 'value'))
agroup.add_argument('--get', metavar='name',
help='get value: name')
agroup.add_argument('--remove', action='append', default=[],
help='removes a va... |
rdkit/rdkit-orig | Contrib/LEF/ClusterFps.py | Python | bsd-3-clause | 2,812 | 0.014225 | #
# Copyright (c) 2009, Novartis Institutes for BioMedical Research Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyri... | eated by Greg Landrum and Anna Vulpetti, March 2009
from rdkit.ML.Cluster import Butina
from rdkit import DataStructs
import sys,cPickle
# sims is the list of similarity thresholds used to generate clusters
sims=[.9,.8,.7,.6]
smis=[]
uniq=[]
uFps=[]
for fileN in sys.argv[1:]:
inF = file(sys.argv[1],'r')
cols... | :
try:
fpIdx = uFps.index(fp)
except ValueError:
fpIdx=len(uFps)
uFps.append(fp)
uniq.append([fp,nm,smi,'FP_%d'%fpIdx]+row[3:])
smis.append(smi)
def distFunc(a,b):
return 1.-DataStructs.DiceSimilarity(a[0],... |
ecs28/pyoverview | pyoverview/basic/variables.py | Python | apache-2.0 | 835 | 0.005988 | """
Basic variables overview:
All variable in Python are objects and the types are defined on the fly
"""
# function
def functionexample(param):
print(param)
# variables
# String
letter = "hello"
letter2 = 'ab"c'
# concat using +
letter3 = letter + ' ' + letter2
# ** mixing concat numers + letters is no sup... | call function
functionexample(letter4)
# multiple assigns
a,b = 3,4
mystring = letter
''' Check the object type to use the co | rrect output format '''
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat1, float) and myfloat1 == 10.0:
print("Float: %f" % myfloat1)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
|
egorsmkv/wmsigner | setup.py | Python | mit | 848 | 0 | import os
from distutils.core import setup
ROOT = os.path.dirname(os.path.realpath(__file__))
setup(
name='wmsigner',
version='0.1.1',
url='https://github.com/egorsmkv/wmsigner',
description='WebMoney Signer',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Egor Smo | lyakov',
author_e | mail='[email protected]',
license='MIT',
keywords='webmoney singer security wmsigner WMXI',
packages=['wmsigner'],
data_files=[('', ['README.rst'])],
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: Financial and Insurance Industry',
'Programming Langua... |
j-5/zask | zask/ext/sqlalchemy/__init__.py | Python | bsd-3-clause | 18,665 | 0 | # -*- coding: utf-8 -*-
"""
zask.ext.sqlalchemy
~~~~~~~~~~~~~~~~~~~
Adds basic SQLAlchemy support to your application.
I have not add all the feature, bacause zask is not for web,
The other reason is i can't handle all the features right now :P
Differents between Flask-SQLAlchemy:
1. No de... | echo:
options['echo'] = True
self._engine = rv = sqlalchemy.cr | eate_engine(info, **options)
self._connected_for = (uri, echo)
return rv
class Model(object):
"""Baseclass for custom user models."""
#: the query class used. The :attr: |
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot | decksite/views/kickoff.py | Python | gpl-3.0 | 842 | 0.003563 | from flask import url_for
from decksite.view import View
from magic import tournaments
from shared import dtutil
# pylint: disable=no-self-use
class KickOff(View):
def __init__(self) -> None:
super().__init__()
kick_off_date = tournaments.kick_off_date()
if dtutil.now() > kick_off_date:
... | aqs')
self.cardhoarder_loan_url = 'https://www.cardhoarder.com/free-loan-program-faq'
self.tournaments_url = url_for('tournaments | ')
self.discord_url = url_for('discord')
def page_title(self) -> str:
return 'The Season Kick Off'
|
akshaynathr/mailman | src/mailman/chains/owner.py | Python | gpl-3.0 | 1,754 | 0.00114 | # Copyright (C) 2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman 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 opt... | TerminalChainBase
from mailman.config i | mport config
from mailman.core.i18n import _
log = logging.getLogger('mailman.vette')
class OwnerNotification(ChainNotification):
"""An event signaling that a message is accepted to the -owner address."""
class BuiltInOwnerChain(TerminalChainBase):
"""Default built-in -owner address chain."""
nam... |
hayalasalah/hayalasalah | web/cloud/cloud/profiles/__init__.py | Python | mpl-2.0 | 283 | 0.003534 | """
profiles - Django application for managing users, mosques, and their membership.
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 c | an obtain one at http://mozilla.org/MPL/2.0/.
"""
|
camptocamp/mapproxy | mapproxy/test/unit/test_util_conf_utils.py | Python | apache-2.0 | 2,557 | 0.001173 | # -:- encoding: utf-8 -:-
# This file is part of the MapProxy project.
# Copyright (C) 2013 Omniscale <http://omniscale.de>
#
# 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.a... | = {"__all__": {"ba": 1}}
assert update_config(a, b) == {"a": {"ba": 1}, "b": {"ba": 1, "bb": {}}}
def test_extend(self):
a = {"a": "foo", "b": ["ba"]}
b = {"b__extend__": ["bb", "bc"]}
assert update_config(a, | b) == {"a": "foo", "b": ["ba", "bb", "bc"]}
def test_prefix_wildcard(self):
a = {"test_foo": "foo", "test_bar": "ba", "test2_foo": "test2", "nounderfoo": 1}
b = {"____foo": 42}
assert update_config(a, b) == {
"test_foo": 42,
"test_bar": "ba",
"test2_foo"... |
citrix-openstack-build/oslo.log | oslo/log/openstack/common/rpc/matchmaker.py | Python | apache-2.0 | 9,429 | 0 | # Copyright 2011 Cloudscaling Group, 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 applicabl... | to-live.'),
]
CONF = cfg.CONF
CONF.register_opts(matchmaker_opts)
LOG = logging.getLogger(__name__)
contextmanager = contextlib.contex | tmanager
class MatchMakerException(Exception):
"""Signified a match could not be found."""
message = _("Match not found by MatchMaker.")
class Exchange(object):
"""Implements lookups.
Subclass this to support hashtables, dns, etc.
"""
def __init__(self):
pass
def run(self, key)... |
tschutter/homefiles | install.py | Python | bsd-2-clause | 27,678 | 0 | #!/usr/bin/env python3
"""
Configure user settings.
- Install files in tschutter/homefiles using symbolic links.
- Configure window manager keybindings.
- Install fonts.
"""
import argparse
import glob
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import time
try:
# pylint: dis... | """
# pylint: disable=too-many-branches
if l | inkname is None:
if os.path.isabs(filename):
raise ValueError(
"default linkname cannot be used with absolute filename"
)
linkname = filename
# Determine the source and destination pathnames.
if os.path.isabs(filename):
file_pathname = filename
... |
OuHangKresnik/Ninja | raspberry/ledplay/ledstart.py | Python | mit | 612 | 0.022876 | import RPi.GPIO as GPIO
import time
led = 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led,GPIO.OUT)
#for x in range(0,100):
GPIO.output(led,True)
time.sle | ep(0.5)
GPIO.output(led,False)
time.sleep(0.5)
GPIO.output(led,True)
time.sleep(0.5)
GPIO.output(led,False)
time.sleep(0.5)
GPIO.output(led,True)
time.sleep(0.2)
GPIO.output(led,False)
time.sleep(0.2)
GPIO.output(led,True)
time.sleep(0.2)
GPIO.output(led,False)
| time.sleep(0.2)
GPIO.output(led,True)
time.sleep(0.2)
GPIO.output(led,False)
time.sleep(0.2)
# time.sleep(1)
# GPIO.output(led,False)
# time.sleep(1)
#GPIO.cleanup()
#GPIO.output(led,False)
|
deepmind/dd_two_player_games | dd_two_player_games/drift_utils_test.py | Python | apache-2.0 | 3,547 | 0.002255 | # Copyright 2021 DeepMind Technologies Limited and Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | ess or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Drift utils test."""
from absl.testing import absltest
from absl.testing import parameterized
from dd_two_player_games import drift_utils
from dd_two_player_games import gan
LEARNING_RATE_TUPL... | (0.0001, 0.5)]
class DriftUtilsTest(parameterized.TestCase):
"""Test class to ensure drift coefficients are computed correctly.
Ensures that the drift coefficients in two-player games are
computed as for the math for:
* simultaneous updates.
* alternating updates (for both player orders).
"""
@p... |
iw3hxn/LibrERP | export_teamsystem/test_data.py | Python | agpl-3.0 | 8,152 | 0.002454 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2016 Didotech srl (http://www.didotech.com)
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free ... | payment_subtype': '', # Sottotipo rimessa diretta
'agent_code': 0, # Codice agente
'paused_payment': '', # Effetto sospeso
'cig': '',
'cup': '',
# Movimenti INTRASTAT BENI dati aggiuntivi...
}
def get_accounting_data():
empty_accounting = {
'val_0': 0,
'empty': '',
... | tt vendita = 001
# Fatt acquisto = 002
'account': 0, # ??? Conto cont. Industriale
# 1 = sistemi
# 2 = Noleggi
# 3 = domotica
'account_proceeds': 0, # ??? Voce di spesa / ricavo (uguale ai conti di ricavo con... |
kubestack/kubestack | app/kubestack/setup.py | Python | gpl-2.0 | 1,536 | 0.000651 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read() | .replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='kubestack',
version='0.1.0',
description="Python app to manage dynamic Jenkins slaves with Kubernetes",
long_description=read... | ,
packages=[
'kubestack',
],
package_dir={'kubestack':
'kubestack'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='kubestack',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended ... |
giantas/minor-python-tests | Operate List/operate_list.py | Python | mit | 1,301 | 0.018447 | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the nu | mbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is None:
return False
if len(num_list) == 0:
return False
new_list = []
... | return True
def sum(num_list):
"""Compute sum of list values"""
if check_list(num_list):
final_sum = 0
for i in num_list:
final_sum = final_sum + i
return final_sum
else:
return False
def multiply(num_list):
"""Multiply list values""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.