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 |
|---|---|---|---|---|---|---|---|---|
corredD/upy | blender/v280/__init__.py | Python | gpl-3.0 | 755 | 0.001325 |
"""
Copyright (C) <2010> Autin L. TSRI
This file git_upy/blender/v271/__init__.py is part of upy.
upy is free software: you can redistribute it and/or modify
it under the t | erms 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.
upy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNE... | ould have received a copy of the GNU General Public License
along with upy. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>.
"""
|
pizzapanther/Getting-Paid-With-Python | paypal_demo/paypal_demo/settings.py | Python | mit | 2,758 | 0.000725 | """
Django settings for paypal_demo project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full li | st of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( | __file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gt^xy(p!5wcff5@zy#^cnvuz9ry#-#g$59du41x@a!l=#)3q6+'
# SECURITY WARNING: don't run with d... |
liukaijv/XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels23.py | Python | bsd-2-clause | 1,849 | 0.000541 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | t({'type': 'column'})
chart.axis_ids = [45705856, 45740416]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column( | 'A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({
'values': '=Sheet1!$A$1:$A$5',
'data_labels': {
'value': 1,
'font': {'name': 'Consolas', 'baseline': 1 * -1, 'pitch_family': 49, ... |
janmtl/pypsych | pypsych/data_sources/hrvstitcher.py | Python | bsd-3-clause | 10,502 | 0.000286 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Includes the HRV stitcher data source class
"""
import pandas as pd
import numpy as np
from scipy.io import loadmat
from scipy.interpolate import UnivariateSpline
from data_source import DataSource
from schema import Schema, Or, Optional
def _val(x, pos, label_bin):
... | 'Condition', 'Bin_Order',
'Start_Time', 'End_Time',
'Bin_Index'],
| index=np.arange(0, total_bins))
idx = 0
for _, label in labels.iterrows():
n_bins = label['N_Bins']
cuts = np.linspace(start=label['Start_Time'] + label['Left_Trim'],
stop=(label['Start_Time']
... |
AjayMT/nodenet | setup.py | Python | mit | 787 | 0 | #!/usr/bin/env python
from setuptools import setup
setup(
name='nodenet',
version='0.1.0',
| description='an asynchronous node-based UDP networking library',
author='Ajay MT',
author_email='ajaymt@icloud.com',
url='http://github.com/AjayMT/nodenet',
download_url='https://github.com/AjayMT/nodenet/tarball/v0.1.0',
keywords='node network UDP asynchronous',
py_modules=['nodenet'],
req... | velopers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
]
)
|
opensvn/test | src/study/python/cpp/ch13/roundFloat2.py | Python | gpl-2.0 | 280 | 0 | #!/usr/bin/env python
class RoundFloatManual(object):
def __init__(self, val):
assert isinstance(val, float), \
"Value must be a float!"
self.value = round(val, 2 | )
def __str__(self):
return '%.2 | f' % self.value
__repr__ = __str__
|
mpclemens/python-explore | turtle/bloom.py | Python | gpl-3.0 | 728 | 0.002747 | #!/usr/bin/env python
import turtle
import random
def bloom(radius):
turtle.colormode(255)
for rad in range(40, 10, -5):
for looper in range(360//rad):
turtle.up()
turtle.circle(radius+rad, rad)
turtle.begin_fill()
turtle.fillcolor((200+random.randint(0,... | om(5)
turtle.exitonclick()
###
if __name__ == "__main__":
main()
| |
satyamz/Tests | pyftpdlib/log.py | Python | gpl-2.0 | 6,094 | 0.000164 | #!/usr/bin/env python
# ======================================================================
# Copyright (C) 2007-2014 Giampaolo Rodola' <g.rodola@gmail.com>
#
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and assoc... | icode strings. The explicit calls to
# unicode() below are harmless in python2 b | ut will do the
# right conversion in python 3.
fg_color = (curses.tigetstr("setaf") or curses.tigetstr("setf")
or "")
if (3, 0) < sys.version_info < (3, 2, 3):
fg_color = unicode(fg_color, "ascii")
self._colors = {
#... |
NINAnor/sentinel4nature | Tree canopy cover/regression/GBRT_Luroeykalven_manual_FCLS.py | Python | gpl-2.0 | 8,821 | 0.006122 | # GBRT for Luroeykalven case study site
# Training data: manually digitized training areas, including water pixels
# Predictors: results of FCLS spectral unmixing
# Authors: Stefan Blumentrath
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble
from sklearn import datasets
from sklearn.uti... | #plt.subplot(1, 2, 2)
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, np.array(cols)[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Variable Importance')
plt.savefig(featureimportance)
if partialdependence:
if spatial_term:
cols = ['x', 'y'] ... | axs = plot_partial_dependence(clf, X_train, cols, n_jobs=cores, n_cols=2,
feature_names=cols, figsize=(len(cols), len(cols)*2))
fig.savefig(partialdependence)
sorted_idx = np.argsort(clf.feature_importances_)
twoway = list(combinations(list(reversed(sorted_idx[-6:])),... |
0asa/gittle | examples/diff.py | Python | apache-2.0 | 227 | 0 | from gittle import Gittle
repo = Gittle('.')
lastest = [
info['sha']
| for info in repo.commit_info()[1:3]
]
pr | int(repo.diff(*lastest, diff_type='classic'))
print("""
Last Diff
""")
print(list(repo.diff('HEAD')))
|
chippey/gaffer | python/GafferSceneTest/__init__.py | Python | bsd-3-clause | 5,457 | 0.00055 | ##########################################################################
#
# Copyright (c) 2012-2014, John Haddon. All rights reserved.
# Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | ptionsTest
from DeleteOptionsTest import DeleteOptionsTest
from CopyOptionsTest import CopyOp | tionsTest
from SceneNodeTest import SceneNodeTest
from PathMatcherTest import PathMatcherTest
from PathFilterTest import PathFilterTest
from ShaderAssignmentTest import ShaderAssignmentTest
from CustomAttributesTest import CustomAttributesTest
from AlembicSourceTest import AlembicSourceTest
from DeletePrimitiveVariable... |
seankelly/buildbot | master/buildbot/reporters/http.py | Python | gpl-2.0 | 4,489 | 0.001337 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | yield service.BuildbotService.reconfigService(self)
self.debug = | debug
self.verify = verify
self.builders = builders
self.neededDetails = copy.copy(self.neededDetails)
for k, v in iteritems(kwargs):
if k.startswith("want"):
self.neededDetails[k] = v
@defer.inlineCallbacks
def startService(self):
yield serv... |
davelab6/pyfontaine | fontaine/charsets/noto_chars/notosanstamil_regular.py | Python | gpl-3.0 | 7,479 | 0.017917 | # -*- coding: utf-8 -*-
class Charset(object):
common_name = 'NotoSansTamil-Regular'
native_name = ''
def glyphs(self):
chars = []
chars.append(0x0000) #uni0000 ????
chars.append(0x200B) #uniFEFF ZERO WIDTH SPACE
chars.append(0x200C) #uni200C ZERO WIDTH NON-JOINER
... | F0) #uni0BF0 TAMIL NUM | BER TEN
chars.append(0x0BF1) #uni0BF1 TAMIL NUMBER ONE HUNDRED
chars.append(0x0BF2) #uni0BF2 TAMIL NUMBER ONE THOUSAND
chars.append(0x0BF3) #uni0BF3 TAMIL DAY SIGN
chars.append(0x0BF4) #uni0BF4 TAMIL MONTH SIGN
chars.append(0x0BF5) #uni0BF5 TAMIL YEAR SIGN
chars.appe... |
nickhand/nbodykit | nbodykit/source/catalog/file.py | Python | gpl-3.0 | 7,330 | 0.004093 | from nbodykit.base.catalog import CatalogSource
from nbodykit.io.stack import FileStack
from nbodykit import CurrentMPIComm
from nbodykit import io
from nbodykit.extern import docrep
from six import string_types
import textwrap
import os
__all__ = ['FileCatalogFactory', 'FileCatalogBase',
'CSVCatalog', 'Bi... | omm.bcast(self._source)
# compute the size; start with full file.
lstart = self.comm.rank * self._source.size // self.comm.size
lend = (self.comm.rank + 1) * self._source.size // self.comm.size
self._size = lend - lstart
self.start = 0
| self.end = self._source.size
self._lstart = lstart # offset in the file for this rank
self._lend = lend # offset in the file for this rank
# update the meta-data
self.attrs.update(self._source.attrs)
if self.comm.rank == 0:
self.logger.info("Extra arguments to... |
algolia/algoliasearch-client-python | tests/unit/test_insights_client.py | Python | mit | 883 | 0.001133 | import unittest
from algoliasearch.configs import InsightsConfig
from algoliasearch.exceptions import AlgoliaException
from algoliasearch.insights_client import InsightsClient
class TestInsightsClient(unittest.TestCase):
def test_create(self):
client = InsightsCli | ent.create("foo", "bar")
self.assertIsInstance(client, InsightsClient)
with self.assertRaises(AssertionError) as _:
InsightsClient.create("", "")
def test_create_with_config(self):
config = InsightsConfig("foo", "bar")
self.assertIsInstance(InsightsClient.create_with_c... | self.assertEqual(client._config._region, "us")
client = InsightsClient.create("foo", "bar", "fr")
self.assertEqual(client._config._region, "fr")
|
KhronosGroup/COLLADA-CTS | StandardDataSets/1_5/collada/library_materials/material/extra/technique_sid_target/technique_sid_target.py | Python | mit | 4,063 | 0.007384 |
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ... | self.status_baseline
return self.status_superior
if ( self.__assistant.CompareRenderedImages(context) ):
self.__assistant.CompareImagesAgainst(context, "_reference_material_extra_element_names")
# Check for preservation of element data
self.__assistant.... | self.status_superior = self.__assistant.DeferJudgement(context)
return self.status_superior
# To pass advanced you need to pass intermediate, this object could also include additional
# tests that were specific to the advanced badge
def JudgeExemplary(self, context):
... |
anush7/django-article-project | article/urls.py | Python | mit | 197 | 0.005076 | from django.conf.urls import include, url
from article import views
urlpatterns = [
url(r'^$', views.articles, name= | 'articles'),
url(r'^add/?$', views.add_articles, name='add-articles'),
| ] |
texastribune/armstrong.base | fabfile/_utils.py | Python | bsd-3-clause | 342 | 0.008772 | from fabric.api import *
from fabric.decorators import task
import os, sys
sys.path[0:0] = [os.path.join(os.path.realpath('.'), '..'), ]
try:
from d51.django.virtualenv.test_runner import run_tests
except ImportError, e:
import sys
sys.stderr.write("This project requires d5 | 1.django.virtualenv.test_runne | r\n")
sys.exit(-1)
|
Tehnix/PyIRCb | src/irc/botDispatcher.py | Python | bsd-3-clause | 2,303 | 0.005211 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IRC bot...
"""
import threading
import src.utilities as util
import src.settings
import src.irc.botObject
class BotDispatcher(threading.Thread):
"""
The BotDispatcher object handles the delegation of the various bots on
the various specified servers.
... | ngsInstance = src.settings.Settings()
self.dispatch()
def dispatch(self):
"""Create one Bot object for each server and start it in threads."""
servers = self.settingsInstance.settings['servers']
f | or name, info in servers.items():
self.botObjects[name] = src.irc.botObject.BotObject(
self.settingsInstance.settings,
info
)
thread = threading.Thread(
target=self.botObjects[name].connectToServer
)
thread.start... |
rtqichen/torchdiffeq | examples/ode_demo.py | Python | mit | 5,643 | 0.002304 | import os
import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
parser = argparse.ArgumentParser('ODE demo')
parser.add_argument('--method', type=str, choices=['dopri5', 'adams'], default='dopri5')
parser.add_argument('--data_size', type=int, default=1000)
parse... | label('x')
ax_vecfield.set_ylabel('y')
y, x = np.mgrid[-2:2:21j, -2:2:21j]
dydt = odefunc(0, torch.Tensor(np.stack([x, y], -1).reshape(21 * 21, 2)).to(device)).cpu().detach().numpy()
mag = np.sqrt(dydt[:, 0]**2 + dydt[:, 1]**2).reshape(-1, 1)
dydt = (dydt / mag)
dydt = d... | , 1], color="black")
ax_vecfield.set_xlim(-2, 2)
ax_vecfield.set_ylim(-2, 2)
fig.tight_layout()
plt.savefig('png/{:03d}'.format(itr))
plt.draw()
plt.pause(0.001)
class ODEFunc(nn.Module):
def __init__(self):
super(ODEFunc, self).__init__()
self.ne... |
Resmin/Resmin | resmin/apps/comment/views.py | Python | gpl-3.0 | 1,460 | 0 | from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import get_object_or_404, render
from .models import Comment
from .forms import UpdateCommentForm
from django.http.response import JsonResponse
from django.views.decorators.http import require_http_methods
def update_comment(request, cid):
... | n you have time.
"""
comment = get_object_or_404(Comment, id=cid, owner=request.user)
if request.method == 'POST':
update_comment_form = UpdateCommentForm(
request.POST, comment=comment)
if update_comment_form.is_valid():
update_comment_form.save()
return rend... | t_form = UpdateCommentForm(comment=comment)
return render(request, 'comments/update_form.html', {
'update_comment_form': update_comment_form})
def get_comment(request, cid):
comment = get_object_or_404(Comment, id=cid, owner=request.user)
return render(request, 'comments/comment.html', {
'... |
lpe234/sanicDemo | controller/__init__.py | Python | gpl-3.0 | 137 | 0 | # -*- coding: UTF-8 -*-
# bp_v1
from .api_v1 import bp_v1
# bp_v2
from .api_v2 i | mport bp_v2
| __author__ = 'lpe234'
"""
Controller
"""
|
zydiig/CKAN.py | libckan/fs.py | Python | gpl-3.0 | 1,487 | 0 | import logging
import re
from pathlib import Path
def find_by_name(path, name):
if type(path) is str:
path = Path(path)
for child in path.iterdir():
if | child.name == name:
return child
elif child.is_d | ir():
ret = find_by_name(child, name)
if ret:
return ret
return None
def find_by_regexp(path, regexp):
if type(path) is str:
path = Path(path)
for child in path.iterdir():
if re.fullmatch(regexp, str(child)):
return child
elif chi... |
aerval/de.rki.proteomic_virus_detection | plugin_source/SixFrameTranslation.py | Python | gpl-2.0 | 2,361 | 0.011012 | from Bio import SeqIO
from Bio.Alphabet import IUPAC, ProteinAlphabet
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from optparse import OptionParser
def translate_to_six_frame(dnaRecord, translationTable):
'''
translate a Bio.SeqRecord of a DNA sequence via the given translation table in... | slation %s frame %i' % (aaRecord.description, direction, frame)
translations.append(aaRecord)
| return translations
if __name__ == '__main__':
op = OptionParser()
op.add_option('-g','--genomes', dest='genomeFilenames', action='append', default=None, help='the input genome in fasta format')
op.add_option('-o','--outputs', dest='outputFilenames', action='append', default=None, help='the ... |
davek44/Scimm | bin/scimm.py | Python | artistic-2.0 | 9,432 | 0.004983 | #!/usr/bin/env python
from optparse import OptionParser, SUPPRESS_HELP
import os, glob, subprocess, sys, math, shutil
import imm_cluster, util
############################################################
# scimm.py
#
# Sequence Clustering with Interpolated Markov Models
#
# Author: David Kelley
#######################... | ons.proc:
# make a temp dir to compute in and cd to it
temp_dir('tmp.start%d' % i)
p.append(subprocess.Popen('%s/cb_init.py -r %s -n %d -k %d -m %d -p %d %s' % (bin_dir, options.readsf, options.cb_numreads, options.k, options.cb_mers, options.cb_threads, em), ... | exit()
j += options.lb_threads # even if not true, just move things along
# wait for processes to finish
for j in range(len(p)):
os.waitpid(p[j].pid, 0)
# choose best start
#maxlike_clusters(total_starts, options.readsf, options.k, o... |
yosuke/OpenHRIVoice | openhrivoice/parsecmudict.py | Python | epl-1.0 | 1,210 | 0.004959 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''CMU dict file parser
Copyright (C) 2010
Yosuke Matsusaka
Intelligent Systems Research Institute,
National Institute of Advanced Industrial Science and Technology (AIST),
Japan
All rights reserved.
Licensed under the Eclipse Public License -v 1.0 (EP... | f.readline()
for l in f:
| t = l.strip().split(' ', 2)
w = t[0].strip('()"')
v = t[2].replace('(', '').replace(')', '').replace(' 0', '').replace(' 1', '')
try:
self._dict[w].append(v)
except KeyError:
self._dict[w] = [v,]
def lookup(self, w):
try... |
rosenvladimirov/addons | l10n_bg_uic/hooks.py | Python | agpl-3.0 | 521 | 0.001931 | # - | *- coding: utf-8 -*-
# © 2015 Roberto Lizana (Trey)
# © 2016 Pedro M. Baeza
# © 2017 Rosen Vladimirov
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, SUPERUSER_ID
def post_init_hook(cr, registry):
cr.execute("""
INSER | T INTO res_partner_id_number
(partner_id, name, category_id, status, active)
SELECT id, company_registry, 1, 'open', TRUE
FROM res_partner
WHERE company_registry IS NOT NULL""")
env = api.Environment(cr, SUPERUSER_ID, {})
|
vlegoff/tsunami | src/secondaires/navigation/commandes/debarquer/__init__.py | Python | bsd-3-clause | 4,221 | 0.000951 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | onnage.agir("bouger")
# On va chercher la salle la plus proche
etendue = navire.etendue
| # On cherche la salle de nagvire la plus proche
d_salle = None # la salle de destination
distance = 2
x, y, z = salle.coords.tuple()
for t_salle in etendue.cotes.values():
if t_salle.coords.z == z:
t_x, t_y, t_z = t_salle.coords.tuple()
... |
pragmatux/systemd | src/python-systemd/journal.py | Python | gpl-2.0 | 20,273 | 0.002318 | # -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
#
# This file is part of systemd.
#
# Copyright 2012 David Strauss <david@davidstrauss.net>
# Copyright 2012 Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
# Copyright 2012 Marti Raudsepp <marti@juffo.org>
#
# systemd is free software; you can redist... | onvert_uuid = _uuid.UUID
DEFAULT_CONVERTERS = {
'MESSAGE_ID': _convert_uuid,
'_MACHINE_ID': _convert_uuid,
'_BOOT_ID': _convert_uuid,
'PR | IORITY': int,
'LEADER': int,
'SESSION_ID': int,
'USERSPACE_USEC': int,
'INITRD_USEC': int,
'KERNEL_USEC': int,
'_UID': int,
'_GID': int,
'_PID': int,
'SYSLOG_FACILITY': int,
'SYSLOG_PID': int,
'_AUDIT_SESSION': int,
'_AUDIT_LOGINUID': int,
'_SYSTEMD_SESSION': int,
... |
LighthouseUK/jerboa | setup.py | Python | lgpl-3.0 | 659 | 0.004552 | from distutils.core import setup
setup(
name='jerboa',
packages=['jerboa'], # this must be the same as the name above
version='0.2.1-alpha',
description='',
author='Matt Badger',
author_email='foss@lighthouseuk.net',
url='https://github.com/LighthouseUK/jerboa', # use the URL to the githu | b repo
download_url='https://github.com/LighthouseUK/jerboa/tarball/0.2.1-alpha', # I'll explain this in a second
keywords=['gae', 'lighthouse', 'jerboa', 'webapp2'], # arbitrary keywords
classifiers=[],
requires=['web | app2', 'blinker', 'wtforms', 'jinja2', 'pytz', 'babel', 'pycrypto'],
# tests_require=['WebTest']
)
|
elysiumd/windows-wallet-13.2 | qa/rpc-tests/fundrawtransaction.py | Python | mit | 28,411 | 0.010137 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
def ge... | work_split=False
self.sync_all()
def run_test(self):
print("Mining blocks...")
min_relay_tx_fee = self.nodes[0].getnetworkinfo()['relayfee']
# This test is not meant to test fee estimation a | nd we'd like
# to be sure all txs are sent at a consistent desired feerate
for node in self.nodes:
node.settxfee(min_relay_tx_fee)
# if the fee's positive delta is higher than this value tests will fail,
# neg. delta always fail the tests.
# The size of the signature... |
lycantropos/VKApp | manage.py | Python | gpl-3.0 | 882 | 0 | import unittest
import click
from tests.test_app import TestApp |
from tests.test_models import TestModels
from tests.test_utils import TestUtils
@click.group(name='tests', invoke_without_command=False)
def test():
pass
@test.command(name='test_ | models')
def test_models():
"""Tests implemented models"""
suite = unittest.TestLoader().loadTestsFromTestCase(TestModels)
unittest.TextTestRunner(verbosity=2).run(suite)
@test.command(name='test_utils')
def test_utils():
"""Tests utility functions"""
suite = unittest.TestLoader().loadTestsFromTes... |
Infinidat/pyvmomi | pyVim/connect.py | Python | apache-2.0 | 29,885 | 0.012682 | # VMware vSphere Python SDK
# Copyright (c) 2008-2016 VMware, 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
#
# ... | key)
si = vim.ServiceInstance("ServiceInstance", soapStub)
sm | = si.content.sessionManager
if not sm.currentSession:
try:
soapStub.samlToken = samlAssertion
si.content.sessionManager.LoginByToken()
finally:
soapStub.samlToken = None
return _doLogin
def Connect(host='localhost', port=443, user='r... |
jakirkham/dask | dask/dataframe/io/tests/test_parquet.py | Python | bsd-3-clause | 129,660 | 0.001057 | import glob
import math
import os
import sys
import warnings
from decimal import Decimal
import numpy as np
import pandas as pd
import pytest
from packaging.version import parse as parse_version
import dask
import dask.dataframe as dd
import dask.multiprocessing
from dask.blockwise import Blockwise, optimize_blockwis... | r(tmp)
assert "_common_metadata" in files
assert "_metadata" in files
assert "part.0.parquet" in files
df2 = dd.read_parquet(tmp, index=False, engine=read_engine)
assert len(df2.divis | ions) > 1
out = df2.compute(scheduler="sync").reset_index()
for column in df.columns:
assert (data[column] == out[column]).all()
@pytest.mark.parametrize("index", [False, True])
@write_read_engines_xfail
def test_empty(tmpdir, write_engine, read_engine, index):
fn = str(tmpdir)
df = pd.DataF... |
smerritt/swift | swift/common/ring/utils.py | Python | apache-2.0 | 26,082 | 0.000038 | # Copyright (c) 2010-2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | +---- device id 16
|
+---- device id 17
The | tier tree would look like:
{
(): [(1,), (2,)],
(1,): [(1, 1), (1, 2)],
(2,): [(2, 1)],
(1, 1): [(1, 1, 192.168.101.1),
(1, 1, 192.168.101.2)],
(1, 2): [(1, 2, 192.168.102.1),
(1, 2, 192.168.102.2)],
(2, 1): [(2, 1, 192.168.201.1),
(2... |
cfagiani/crowdcloud | build_cloud.py | Python | apache-2.0 | 7,232 | 0.013689 | """
__author__ = 'Christopher Fagiani'
"""
import sys, argparse, json, string, collections
from datetime import datetime
SummaryData = collections.namedtuple('SummaryData', 'wordCounts articles commentCount authors anonCount')
def main(args):
"""This program will output a word cloud as html based on the freque... | \n")
out_file.write("var authorCount='"+str(len(summary_data.authors))+"';\n")
out_file.write("var anonCount='"+str(summary_data.anonCount)+"';\n")
if interval is not None:
| out_file.write("var intervalHrs='"+interval+"';\n")
else:
out_file.write("var intervalHrs='unknown';\n")
out_file.write("var words = [")
else:
out_file.write("[")
for item in sorted_data:
if(item[1]['count']<threshold):
... |
coberger/DIRAC | DataManagementSystem/Client/FailoverTransfer.py | Python | gpl-3.0 | 11,229 | 0.027518 | """ Failover Transfer
The failover transfer client exposes the following methods:
- transferAndRegisterFile()
- transferAndRegisterFileFailover()
Initially these methods were developed inside workflow modules but
have evolved to a generic 'transfer file with failover' client.
The transferAndR... | licaRemovalRequest( lfn, failoverSE )
if not result['OK']:
self.log.error( 'Could not set removal request', result['Message'] )
return result
return S_OK( {'uploadedSE':failoverSE, 'lfn':lfn} )
def getRequest( self ):
""" get the accumulated request object
"""
return self.request
... | equest Management Service
"""
if self.request.isEmpty():
return S_OK()
isValid = RequestValidator().validate( self.request )
if not isValid["OK"]:
return S_ERROR( "Failover request is not valid: %s" % isValid["Message"] )
else:
requestClient = ReqClient()
result = requestCli... |
NERC-CEH/jules-jasmin | majic/joj/crowd/client.py | Python | gpl-2.0 | 12,041 | 0.00108 | """
#header
"""
import base64
import datetime
import logging
from joj.crowd.models import UserRequest
import urllib2
import simplejson
from simplejson import JSONDecodeError
log = logging.getLogger(__name__)
class ClientException(Exception):
""" Base exception for Crowd-based errors """
def __init__(self):
... | icationFailedException,
'INVALID_USER': UserException,
'USER_NOT_FOUND': UserException
| }
_token_cache = {}
crowd_user = None
crowd_password = None
def __init__(self, api_url=None, app_name=None, app_pwd=None):
"""Constructor function
Params:
api_url: The URL to the Crowd API
app_name: Application login name for Crowd server
app_pwd... |
chelnak/BotStats | app/__init__.py | Python | mit | 466 | 0.01073 | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import flask.ext.restless
app = Flask(__name | __)
app.config.from_object('config')
#flask-sqlalchemy
db = SQLAlchemy(app)
from app import models, views
from app.models import Fact, Log
#API
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
ma | nager.create_api(Fact, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Log, methods=['GET', 'POST', 'PUT', 'DELETE'])
|
alsrgv/tensorflow | tensorflow/python/keras/layers/recurrent_test.py | Python | apache-2.0 | 54,154 | 0.003638 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | andom((6, 5, 5))
y_np = model.predict(x_np)
weights = model.get_weights()
config = layer.get_config()
with keras.utils.CustomObjectScope({'MinimalRNNCell': MinimalRNNCell}):
layer = keras.layers.RNN.from_config(config)
y = layer(x)
model = keras.models.Model(x, y)
model.set_weights(wei... | king.
cells = [MinimalRNNCell(8),
MinimalRNNCell(12),
MinimalRNNCell(32)]
layer = keras.layers.RNN(cells)
y = layer(x)
model = keras.models.Model(x, y)
model.compile(
optimizer='rmsprop',
loss='mse',
run_eagerly=testing_utils.should_run_eagerly())
... |
w1z2g3/crossbar | crossbar/controller/test/test_cli.py | Python | agpl-3.0 | 10,540 | 0.001328 | #####################################################################################
#
# Copyright (C) Tavendo GmbH
#
# Unless a separate license agreement exists between you and Tavendo GmbH (e.g. you
# have purchased a commercial license), the license terms below apply.
#
# Should you enter into a separate licen... | #############################
from __future__ import absolute_import, division, print_function
from six import StringIO as NativeStringIO
from twisted.internet.selectreactor import SelectReactor
from crossbar.test import TestCase
from crossbar.controller import cli
from crossbar import _logging
from weakref import... | t twisted
class CLITestBase(TestCase):
# the tests here a mostly bogus, as they test for log message content,
# not actual functionality
skip = True
def setUp(self):
self._subprocess_timeout = 15
if platform.python_implementation() == 'PyPy':
self._subprocess_timeout = ... |
KevinJMcGrath/Symphony-Ares | modules/plugins/PABot/logging.py | Python | mit | 796 | 0.002513 | import logging.handlers
import os
_pabotlog = logging.getLogger('PABot')
_pabotlog.setLevel(logging.DEBUG)
_log | Path = os.path.abspath("./logging/pabot.log")
_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
_consoleStreamHandler = logging.StreamHandler()
_consoleStreamHandler.setLevel(logging.DEBUG)
_consoleStreamHandler.setFormatter(_formatter)
_symLogRotFileHandler = logging.handlers.Ro... | ging.DEBUG)
_symLogRotFileHandler.setFormatter(_formatter)
_pabotlog.addHandler(_consoleStreamHandler)
_pabotlog.addHandler(_symLogRotFileHandler)
def LogPABotMessage(message):
_pabotlog.info(message)
def LogPABotError(message):
_pabotlog.error(message)
|
nanchenchen/emoticon-analysis | emoticonvis/apps/api/serializers.py | Python | mit | 4,406 | 0.004766 | """
This module defines serializers for the main API data objects:
.. autosummary::
:nosignatures:
DimensionSerializer
FilterSerializer
MessageSerializer
QuestionSerializer
"""
from django.core.paginator import Paginator
from rest_framework import serializers, pagination
import emoticonvis.apps... | r()
tokens = serializers.ListField()
feature_vector = serializers.ListField(child=serializers.DictField())
class FeatureCodeDistributionSerializer(serializers.Serializer):
feature_index = serializers.IntegerField()
feature_text = serializers.CharField()
| distribution = serializers.ListField(child=serializers.DictField())
class SVMResultSerializer(serializers.Serializer):
results = serializers.DictField()
messages = serializers.ListField(child=FeatureVectorSerializer(), required=True)
class FeatureSerializer(serializers.ModelSerializer):
token_list = ser... |
FederatedAI/FATE | examples/pipeline/data_transform/pipeline-data-transform-dense.py | Python | apache-2.0 | 2,334 | 0.003428 | #
# Copyright 2019 The FATE 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 appli... | est_train_data)
reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)
data_transform_0 = DataTransform(name="data_transform_0")
data_transform_0.get_party_instance(role='guest', party_id=guest).component_para | m(with_label=True)
data_transform_0.get_party_instance(role='host', party_id=host).component_param(with_label=False)
pipeline.add_component(reader_0)
pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
pipeline.compile()
pipeline.fit()
if __name__ == "__main__":
p... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/desktop/core/ext-py/lxml/src/lxml/tests/test_xpathevaluator.py | Python | gpl-2.0 | 23,244 | 0.00271 | # -*- coding: utf-8 -*-
"""
Test cases related to XPath evaluation and the XPath class
"""
import unittest, sys, os.path
this_dir = os.path.dirname(__file__)
if this_dir not in sys.path:
sys.path.insert(0, this_dir) # needed for Py3
from common_imports import etree, HelperTestCase, _bytes, BytesIO
from common_i... | elf.assertEquals(['FooBar', 'BarFoo'],
tree.xpath('/a/b/text()', smart_strings=True))
self.assertEquals([root[0], root[1]],
[r.getparent() for r in
tree.xpath('/ | a/b/text()', smart_strings=True)])
self.assertEquals(['FooBar', 'BarFoo'],
tree.xpath('/a/b/text()', smart_strings=False))
self.assertEquals([False, False],
[hasattr(r, 'getparent') for r in
tree.xpath('/a/b/text()', smart_s... |
keepkey/python-keepkey | tests/test_msg_verifymessage_segwit_native.py | Python | lgpl-3.0 | 4,324 | 0.002313 | # This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | def test_verify_utf(self):
self.setup_mnemonic_nopin_nopassphrase()
words_nfkd = u'Pr\u030ci\u0301s\u030cerne\u030c z\u030clut\u030couc\u030cky\u0301 ku\u030an\u030c u\u0301pe\u030cl d\u030ca\u0301belske\u0301 o\u0301dy za\u0301ker\u030cny\u0301 uc\u030cen\u030c be\u030cz\u030ci\u0301 pode\ | u0301l zo\u0301ny u\u0301lu\u030a'
words_nfc = u'P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy z\xe1ke\u0159n\xfd u\u010de\u0148 b\u011b\u017e\xed pod\xe9l z\xf3ny \xfal\u016f'
res_nfkd = self.client.verify_message(
'Bitcoin',
... |
uc-cdis/cdis-python-utils | cdispyutils/auth/errors.py | Python | apache-2.0 | 101 | 0 | class JWTValid | ationError(Exception):
| pass
class JWTAudienceError(JWTValidationError):
pass
|
Lukasa/cryptography | tests/utils.py | Python | apache-2.0 | 14,122 | 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
# distributed under the... | anguage governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import collections
from contextlib import contextmanager
import pytest
import six
from cryptography.exceptions import UnsupportedAlgorithm
import c | ryptography_vectors
HashVector = collections.namedtuple("HashVector", ["message", "digest"])
KeyedHashVector = collections.namedtuple(
"KeyedHashVector", ["message", "digest", "key"]
)
def select_backends(names, backend_list):
if names is None:
return backend_list
split_names = [x.strip() for x ... |
svetlyak40wt/django-dzenlog | example/blog/models.py | Python | bsd-3-clause | 621 | 0.004831 | from django.db import mod | els
from django.utils.translation import ugettext_lazy as _
from django_dzenlog.models import GeneralPost
class TextPost(GeneralPost):
body_detail_template = 'blog/text_post.html'
feed_description_template = 'blog/text_feed_detail.html'
body = models.TextField(_('Post\'s body'))
class LinkPost(GeneralPo... | url = models.URLField(_('URL'), default='http://example.com', verify_exists=False)
description = models.TextField(_('URL\'s description'), blank=True)
|
mkobos/tree_crawler | concurrent_tree_crawler/test/subtrees_comparer.py | Python | mit | 650 | 0.026154 | def subtrees_equal(expected_schema_node, actual_node):
if expected_schema_node[0] != actual_node.get_name():
return False
if expected_schema_node[1] != actual_node.get_state():
return False
expected_children = expected_schema_node[2]
actual_children = actual_node.get_children()
actual_children_names = [child.g... | ed_children) != len(actual_children_nam | es):
return False
for (expected_child, actual_child_name) in \
zip(expected_children, actual_children_names):
subtrees_equal(
expected_child, actual_node.get_child(actual_child_name))
return True |
amolkahat/pandas | pandas/tests/arrays/categorical/test_algos.py | Python | bsd-3-clause | 5,452 | 0 | import pytest
import numpy as np
import pandas as pd
import pandas.util.testing as tm
@pytest.mark.parametrize('ordered', [True, False])
@pytest.mark.parametrize('categories', [
['b', 'a', 'c'],
['a', 'b', 'c', 'd'],
])
def test_factorize(categories, ordered):
cat = pd.Categorical(['b', 'b', 'a', 'c', No... | w_fill=True, fill_value=-1)
expected = pd.Categorical([-1, -1, 0], categories=[-1, 0, 1])
tm.assert_categorical_equal(result, expected)
def test_take_fill_value(self):
# https://github.com/pandas-dev/pandas/issues/23296
cat = pd.Categorical(['a', 'b', 'c'])
result = cat.take... | ategorical_equal(result, expected)
def test_take_fill_value_new_raises(self):
# https://github.com/pandas-dev/pandas/issues/23296
cat = pd.Categorical(['a', 'b', 'c'])
xpr = r"'fill_value' \('d'\) is not in this Categorical's categories."
with tm.assert_raises_regex(TypeError, xpr):... |
nathanielvarona/airflow | tests/providers/apache/cassandra/hooks/test_cassandra.py | Python | apache-2.0 | 8,538 | 0.00164 | #
# 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... | n("cassandra")
class TestCassandraHook(unittest.TestCase):
def setUp(self):
db.merge_conn(
Connection(
conn_id='cassandra_test',
conn_type='cassandra',
host='hos | t-1,host-2',
port='9042',
schema='test_keyspace',
extra='{"load_balancing_policy":"TokenAwarePolicy","protocol_version":4}',
)
)
db.merge_conn(
Connection(
conn_id='cassandra_default_with_schema',
con... |
hasadna/knesset-data-pipelines | people/plenum_session_voters.py | Python | mit | 2,135 | 0.000468 | from datapackage_pipelines.wrapper import ingest, spew
def get_votes(resource, data, stats):
data['session_voters'] = {}
stats['num_votes'] = 0
stats['num_vote_mks'] = 0
for vote in resource:
voters = data['session_voters'].setdefault(vote['session_id'], set())
for attr in ['mk_ids_pro... | ats['num_votes'] += 1
def get_plenum(resource, data, stats):
stats.update(known_sessions=0, unknown_sessions=0)
for session in resource:
if session['PlenumSessionID'] in data['session_voters']:
stats['known_sessions'] += 1
session['voter_mk_ids'] = list(data['session_voters'][s... | stats['unknown_sessions'] += 1
if not session['voter_mk_ids']:
session['voter_mk_ids'] = None
yield session
def get_resources(resources, stats, data):
for i, resource in enumerate(resources):
if i == data['votes_index']:
get_votes(resource, data, stats)
el... |
mostafa-mahmoud/sahwaka | lib/evaluator.py | Python | apache-2.0 | 13,538 | 0.002955 | #!/usr/bin/env python
"""
A module that provides functionalities for calculating error metrics
and evaluates the given recommender.
"""
import numpy
from util.top_recommendations import TopRecommendations
class Evaluator(object):
"""
A class for computing evaluation metrics and splitting the input data.
"... | data for every user.
:returns: a tuple of train and test data.
:rtype: tuple
"""
if self.random_see | d is False:
numpy.random.seed(42)
test = numpy.zeros(self.ratings.shape)
train = self.ratings.copy()
for user in range(self.ratings.shape[0]):
non_zeros = self.ratings[user, :].nonzero()[0]
test_ratings = numpy.random.choice(non_zeros,
... |
MediaMath/t1-python | terminalone/models/concept.py | Python | apache-2.0 | 729 | 0 | # -*- coding: utf-8 -*-
"""Provides concept object."""
from __future__ import absolute_import
from .. import t1types
from ..entity import Entity
class Concept(Entity):
"""Concept entity."""
collection = 'concepts'
resource = 'concept'
_relations = {
'advertiser',
}
_pull = {
'... | us': t1types.int_to_bool,
'updated_on': t1types.strpt,
'version': int,
}
_push = _pull.copy()
_push.update({
'status': int,
})
def __init__(self, session, properties=None, **kwargs):
super(Con | cept, self).__init__(session, properties, **kwargs)
|
bd4/monster-hunter-scripts | db/_pathfix.py | Python | mit | 251 | 0 | """
Hack to get scripts to run from source checkout without having to set
PYTHONPATH.
"""
import sys
from | os.path import dirname, join, abspath
db_path = dirname(__file__)
project_path = abspath(join(db_path, "..")) |
sys.path.insert(0, project_path)
|
mfalaize/homelab | compta/management/commands/check_operations.py | Python | gpl-3.0 | 3,142 | 0.003196 | import calendar
from datetime import date
from django.conf import settings
from django.core.mail import send_mail
from django.core.management import BaseCommand
from django.template.loader import get_template
from compta.bank import get_bank_class
from compta.models import Compte
def generate_mail():
# Dernier ... | érations bancaires en ligne, inscrit les nouvelles en base et les envoie par mail"""
comptes = Compte.objects.all()
| for compte in comptes:
operations = compte.operation_set.all()
bank_class = get_bank_class(compte.identifiant.banque)
has_changed = False
with bank_class(compte.identifiant.login, compte.identifiant.mot_de_passe, compte.numero_compte) as bank:
new_operations = bank.fetch_las... |
scikit-learn-contrib/categorical-encoding | category_encoders/leave_one_out.py | Python | bsd-3-clause | 11,063 | 0.002983 | """Leave one out coding"""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
import category_encoders.utils as util
from sklearn.utils.random import check_random_state
__author__ = 'hbghhy'
class LeaveOneOutEncoder(BaseEstimator, util.TransformerWithTargetMixin):
"""Leave one out codi... | ols = X.columns.values
self._mean = y.mean()
return {col: self.fit_column_map(X[col], y) for col in cols}
def fit_column_map(self, series, y):
category = pd.Categorical(series)
categories = category.categories
codes = category.codes.copy()
codes[codes == -1] = le... | [(code, category) for code, category in enumerate(categories)]))
result = y.groupby(codes).agg(['sum', 'count'])
return result.rename(return_map)
def transform_leave_one_out(self, X_in, y |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.2/Lib/test/test_zlib.py | Python | mit | 6,045 | 0.00397 | import zlib
from test_support import TestFailed
import sys
import imp
try:
t = imp.find_module('test_zlib')
file = t[0]
except ImportError:
file = open(__file__)
buf = file.read() * 8
file.close()
# test the checksums (hex so the test doesn't break on 64-bit machines)
print hex(zlib.crc32('penguin')), hex... | decompressobj(-12)
cb = combuf
bufs = []
while cb:
max_length = 1 + len(cb)/10
chunk = deco.decompress(cb, max_length)
if len(chunk) > max_length:
print 'chunk too big (%d>%d)' % (len(chunk),max_length)
bufs.append(chunk | )
cb = deco.unconsumed_tail
bufs.append(deco.flush())
decomp2 = ''.join(buf)
if decomp2 != buf:
print "max_length decompressobj failed"
else:
print "max_length decompressobj succeeded"
# Misc tests of max_length
deco = zlib.decompressobj(-12)
try:
deco.decompress("", -1)
except ValueError:
pass
els... |
Purg/SMQTK | bin/memex/hackathon_2016_07/cp1/ad_image_classification/cnn_finetuning/score_eval_data.py | Python | bsd-3-clause | 5,443 | 0.003858 | import csv
import collections
import json
import numpy
from smqtk.utils.bin_utils import logging, initialize_logging
from smqtk.representation.data_set.memory_set import DataMemorySet
from smqtk.algorithms.descriptor_generator.caffe_descriptor import CaffeDescriptorGenerator
from smqtk.algorithms.classifier.index_labe... | f.write( json.dumps({"cluster_id": c, "score": float(cluster2score_max[c])}) + '\n' )
else:
# Due to a cluster having no child ads with imagery
print "No childred with images for cluster '%s'" % c
f.write( json.dumps({"cluster_id": c, "score": 0.5}) + '\n' )
with open(OUTP... | ": float(cluster2score_avg[c])}) + '\n' )
else:
# Due to a cluster having no child ads with imagery
print "No childred with images for cluster '%s'" % c
f.write( json.dumps({"cluster_id": c, "score": 0.5}) + '\n' )
|
Elico-Corp/openerp-7.0 | balance_sheet_extended/__init__.py | Python | agpl-3.0 | 170 | 0 | # -*- coding: | utf-8 -*-
# | © 2014 Elico Corp (https://www.elico-corp.com)
# Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
import report
import wizard
|
googleapis/python-bigquery-storage | samples/snippets/__init__.py | Python | apache-2.0 | 601 | 0 | # -*- coding: utf-8 -*-
#
# Copy | right 2021 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 requir | ed by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
acockburn/appdaemon | appdaemon/sequences.py | Python | mit | 4,617 | 0.002816 | import uuid
import asyncio
from appdaemon.appdaemon import AppDaemon
class Sequences:
def __init__(self, ad: AppDaemon):
self.AD = ad
self.logger = ad.logging.get_child("_sequences")
async def run_sequence_service(self, namespace, domain, service, kwargs):
if "entity_id" not in kwar... | uence):
coro = self.prep_sequence(_name, namespace, sequence)
#
# OK, lets run it
#
future = asyncio.ensure_future(coro)
self.AD.futures.add_future(_name, future)
return future
async def prep_sequence(self, _name, namespace, sequence):
| ephemeral_entity = False
loop = False
if isinstance(sequence, str):
entity_id = sequence
if await self.AD.state.entity_exists("rules", entity_id) is False:
self.logger.warning('Unknown sequence "%s" in run_sequence()', sequence)
return None... |
jonocodes/gedit-code-assistance | backends/xml/gcpbackendxml/backend.py | Python | gpl-3.0 | 1,683 | 0.001783 | # gcp xml backend
# Copyright (C) 2012 Jesse van den Kieboom <jessevdk@gnome.org>
#
# 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 la... | have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from gi.repository import GObject, Gcp
from document import Document
class Backend(GObject.Object, Gcp.Backend):
| size = GObject.property(type=int, flags = GObject.PARAM_READABLE)
def __init__(self):
GObject.Object.__init__(self)
self.documents = []
def do_get_property(self, spec):
if spec.name == 'size':
return len(self.documents)
GObject.Object.do_get_property(self, spec)... |
emoitzi/django-excel-viewer | users/__init__.py | Python | gpl-3.0 | 44 | 0.022727 | defa | ult_app_config = 'users.apps.UserCon | fig' |
ikvk/imap_tools | examples/fetch_by_pages.py | Python | apache-2.0 | 605 | 0.003306 | from imap_tools import MailBox
with MailBox('imap.mail.com').login( | 'test@mail.com', 'pwd', 'INBOX') as mailbox:
criteria = 'ALL'
found_nums = mailbox.numbers(criteria)
page_len = 3
pages = int(len(found_nums) // page_len) + 1 if len(found_nums) % page_len else int(len(found_nums) // page_len)
for page in range(pages):
print('page {}'.format(page))
p... | print(page_limit)
for msg in mailbox.fetch(criteria, bulk=True, limit=page_limit):
print(' ', msg.date, msg.uid, msg.subject)
|
konstantinKim/vd-backend | app/materials/models.py | Python | mit | 2,427 | 0.021426 | from marshmallow_jsonapi import Schema, fields
from marshmallow import validate
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError
db = SQLAlchemy(session_options={"autoflush": False})
class CRUD():
def add(self, resource):
db.session.add(resource)
return db... |
#self links
def get_top_level_links(self, data, many):
self_link = ''
if many:
self_link = "/materials/"
else:
if 'attributes' in data:
self_link = "/materials/{}".forma | t(data['attributes']['MATERIAL_ID'])
return {'self': self_link}
class Meta:
type_ = 'materials'
class MaterialsSalvage(db.Model, CRUD):
__tablename__ = 'materials_salvage'
MATERIAL_SALVAGE_ID = db.Column(db.Integer, primary_key=True)
name = db.Colu... |
marwoodandrew/superdesk-aap | server/aap/data_consistency/compare_repositories.py | Python | agpl-3.0 | 9,289 | 0.002153 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import super... | et_mongo_items(self, consistency_record):
# get the records from mongo in chunks
projection = dict(superdesk.resources[self.resource_name].endpoint_schema['datasource']['projection'])
superdesk.resources[self.resource_name].endpoint_schema['datasource']['proj | ection'] = None
service = superdesk.get_resource_service(self.resource_name)
cursor = service.get_from_mongo(None, {})
count = cursor.count()
no_of_buckets = len(range(0, count, self.default_page_size))
mongo_items = []
updated_mongo_items = []
request = ParsedReq... |
Johnetordoff/osf.io | osf/migrations/0239_auto_20211110_1921.py | Python | apache-2.0 | 497 | 0.002012 | # -*- coding: utf-8 -*-
| # Generated by Django 1.11.28 on 2021-11-10 19:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('osf', '0238_abstractprovider_allow_updates'),
]
operations = [
migrations.AddIndex(
mo... | e='osf_schemar_object__8cc95e_idx'),
),
]
|
Karaage-Cluster/karaage-applications | kgapplications/south_migrations/0001_initial.py | Python | gpl-3.0 | 21,468 | 0.007965 | # -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
('applications', '0028_auto__chg_field_applicant_username'),
)
def forwards(self, orm):
if not db.dry_run:
orm['co... | ', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['kgapplications.Application'], unique=True, primary_key=True)),
('needs_account', self.gf('django.db.models.fields.BooleanField')(default=True)),
('make_leader', self.gf('django.db.models.fields.BooleanField')(default=False)),
... | ('institute', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['karaage.Institute'], null=True, blank=True)),
('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('additional_req', self.gf('django.db.models.fields.TextField')(null=True, blank=True))... |
r-kitaev/lucid-python-werkzeug | tests/contrib/test_wrappers.py | Python | bsd-3-clause | 2,682 | 0 | # -*- coding: utf-8 -*-
from werkzeug.contrib import wrappers
from werkzeug import routing
from werkzeug.wrappers import Request, Response
def test_reverse_slash_behavior():
"""Test ReverseSlashBehaviorRequestMixin"""
class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
pass
req =... | html')
assert resp.charset == 'utf-7'
resp.charset = 'utf-8'
assert resp.charset == 'utf-8'
assert resp.mimetype == 'text/html'
assert resp.mimetype_params == {'charset': 'utf-8'}
resp.mimetype_params['charset'] = 'iso-8859-15'
assert resp.charset == 'iso-8859-15'
resp.data = u'Hällo Wör... | rs['content-type']
try:
resp.charset = 'utf-8'
except TypeError, e:
pass
else:
assert False, 'expected type error on charset setting without ct'
|
jcalbert/TextBlob | docs/conf.py | Python | mit | 2,936 | 0.003406 | # -*- coding: utf-8 -*-
import datetime as dt
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.inser... | l section).
man_pages = [
('index', 'textblob', u'textblob Documenta | tion',
[u'Steven Loria'], 1)
]
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'textblob'... |
nisavid/testbed | testbed/tests/redirect.py | Python | lgpl-3.0 | 4,763 | 0 | #!/usr/bin/env python
""":mod:`Redirection <testbed.resources._redirect>` tests."""
__copyright__ = "Copyright (C) 2014 Ivan D Vasin"
__docformat__ = "restructuredtext"
import json as _json
import unittest as _unittest
from urllib import quote as _percent_encode
import napper as _napper
import spruce.logging as _lo... | nse(response,
loc=self._redirect_loc)
def test_postget_response_redirect_as_html(self):
response = self.request('postget',
self._redirect_path,
accept_mediaranges=('text/html',
... | ,
loc=self._redirect_loc,
contenttype='text/html')
@property
def _redirect_loc(self):
return 'aoeu'
@property
def _redirect_path(self):
return 'response;loc={}'\
.format(_perce... |
DasIch/relief | tests/schema/test_mappings.py | Python | bsd-3-clause | 12,224 | 0.000736 | # coding: utf-8
"""
tests.schema.test_mappings
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2013 by Daniel Neuhäuser
:license: BSD, see LICENSE.rst for details
"""
import pytest
from relief import (
Dict, OrderedDict, Unicode, Integer, NotUnserializable, Form, Element,
_compat
)
from tests.conftest... | u"bar").value is NotUnserializable
assert element.get(u"bar").raw_value is None
def test_iter(self, element_cls):
keys = list(element_cls({u"foo": 1}))
assert len(keys) == 1
assert keys[0].value = | = u"foo"
@python2_only
def test_iterkeys(self, element_cls):
keys = list(element_cls({u"foo": 1}).iterkeys())
assert len(keys) == 1
assert keys[0].value == u"foo"
@python2_only
def test_viewkeys(self, element_cls):
keys = list(element_cls({u"foo": 1}).viewkeys())
... |
EmanueleCannizzaro/scons | test/CC/SHCC.py | Python | mit | 2,436 | 0.002463 | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... | sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS... | NT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/CC/SHCC.py rel_2.5.1:3735:9... |
kblin/supybot-gsoc | src/commands.py | Python | bsd-3-clause | 30,909 | 0.0033 | ###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2009, James Vega
# 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... | pt
import inspect
import threading
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
import supybot.ircdb as ircdb
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbac | ks
###
# Non-arg wrappers -- these just change the behavior of a command without
# changing the arguments given to it.
###
# Thread has to be a non-arg wrapper because by the time we're parsing and
# validating arguments, we're inside the function we'd want to thread.
def thread(f):
"""Makes sure a command spawn... |
KaranKamath/SequiturG2P | symbols.py | Python | gpl-2.0 | 2,130 | 0.018779 | __author__ = 'Maximilian Bisani'
__version__ = '$LastChangedRevision: 1691 $'
__date__ = '$LastChangedDate: 2011-08-03 15:38:08 +0200 (Wed, 03 Aug 2011) $'
__copyright__ = 'Copyright (c) 2004-2005 RWTH Aachen University'
__license__ = """
This program is free software; you can redistribute it and/or modify... | even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, you will find it at
http://www.gnu.org/licenses/gpl.html, or write to the Free Softw... | or become invalid, a valid provision is deemed to have been
agreed upon which comes closest to what the parties intended
commercially. In any case guarantee/warranty shall be limited to gross
negligent actions or intended actions or fraudulent concealment.
"""
class SymbolInventory:
"""
0 (zero) is __void__ wh... |
nttcom/eclcli | eclcli/bare/bareclient/ecl/common/apiclient/utils.py | Python | apache-2.0 | 2,975 | 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
# ... | "name": manager.resource_class.__name__.lower(),
"name_or_id": name_or_id
}
raise exceptions.CommandError(msg)
except exceptions.NoUniqueMatch:
msg = _("Multiple %(name)s matches found for "
"'%(name_or_id)s', use an ID to b... |
"name": manager.resource_class.__name__.lower(),
"name_or_id": name_or_id
}
raise exceptions.CommandError(msg)
|
jpschnel/maze-vision | maze_vision.py | Python | apache-2.0 | 2,411 | 0.072999 | # 0 = open space, 1=boundary , 2= the robot, 3= finish
def maze_vision():
path= ''
maze=[]
maze.append(list('000000002000000'))
maze.append(list('000000003001100'))
maze.append(list('000000000000000'))
maze.append(list('000000000000000'))
maze.append(list('000000000000000'))
maze.append(list('000... | dist=4444444
if maze[sy][sx]=='3': #reached finish
print(hit)
return 0 #return
#up
# if up >-1:
# if maze[sy][up]=='0': #if this direction is open
# maze[sy][up]='4' #mark it as traveled to
# path= path +'u' | #add that direction to final path
# updist= 1+ distance(maze,up,sy,fx,fy,path) #calculate shortest dist from there
#if it makes it past here, that was not the shortest distance
#path= path[:-1] #remove that direction from final path
#maze[sy][up]=0 #mark that direction as not traveled
... |
eharney/nova | nova/db/sqlalchemy/migration.py | Python | apache-2.0 | 2,918 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | return versioning_api.upgrade(get_engine(), repositor | y, version)
else:
return versioning_api.downgrade(get_engine(), repository,
version)
def db_version():
repository = _find_migrate_repo()
try:
return versioning_api.db_version(get_engine(), repository)
except versioning_exceptions.DatabaseNotContr... |
dominikkowalski/django-powerdns-dnssec | powerdns/routers.py | Python | bsd-2-clause | 959 | 0 | class PowerDNSRouter(object):
"""Route all operations on powerdns models to the powerdns database."""
db_name = 'powerdns'
app_name = 'powerdns'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_name:
return self.db_name
return None
def db_for... | nts):
if model._meta.app_label == self.app_name:
return self.db_name
return None
def allow_relation(self, obj1, obj2, **hints):
if (obj1._meta.app_label == self.app_name and
obj2._meta.app_label == self.app_name):
return True
return None
... | ef allow_syncdb(self, db, model):
if model._meta.app_label == self.app_name:
return db == self.db_name
elif db == self.db_name:
# workaround for http://south.aeracode.org/ticket/370
return model._meta.app_label == 'south'
return None
|
smitchell556/cuttle | tests/test_cuttle_class.py | Python | mit | 6,111 | 0.000327 | # -*- coding: utf-8
"""
Tests related to the Cuttle class.
"""
import os
import unittest
import warnings
import time
from cuttle.reef import Cuttle, Column
from cuttlepool import CuttlePool
from cuttlepool.cuttlepool import PoolConnection
DB = '_cuttle_test_db'
DB2 = '_cuttle_test_db2'
HOST = 'localhost'
class Bas... | ials)
con1 = pool1.get_connection()
cur1 = con1.cursor()
con2 = pool2.get_connection()
cur2 = con2.cursor()
# get databases
cur1.execute('SHOW DATABASES')
dbs = cur1.fetchall()
self.assertIn((DB,), dbs)
self. | assertIn((DB2,), dbs)
# get tables
cur1.execute('SHOW TABLES')
tbls1 = cur1.fetchall()
cur2.execute('SHOW TABLES')
tbls2 = cur2.fetchall()
self.assertIn((self.testtable1().name,), tbls1)
self.assertNotIn((self.testtable2().name,), tbls1)
self.assertIn((... |
pavelpat/yased | src/tests/__init__.py | Python | apache-2.0 | 1,664 | 0.000601 | # coding: utf-8
from unittest import TestCase
from yased import EventsDispatcher, Event
class AnyEvent(Event): |
"""Represents any event."""
class EventsDispatcherTestCase(TestCase):
def setUp(self):
self.ed = EventsDispatcher()
def te | st_send(self):
calls = []
def handler(*args, **kwargs):
calls.append(True)
self.ed.connect(handler, AnyEvent)
self.ed.send(AnyEvent())
self.assertEqual(len(calls), 1)
self.ed.disconnect(handler, AnyEvent)
self.ed.send(AnyEvent())
self.assert... |
themotleyfool/django-offline-messages | tests/settings.py | Python | bsd-3-clause | 361 | 0 | # django-offline-messages Test Settings
| DATABASES = {'default': {'ENGINE': 'django. | db.backends.sqlite3'}}
INSTALLED_APPS = (
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'offline_messages',
'tests'
)
ROOT_URLCONF = ''
COVERAGE_ADDITIONAL_MODULES = ('offline_messages',)
|
vitaly-krugl/nupic | examples/opf/experiments/multistep/hotgym_best_sp/description.py | Python | agpl-3.0 | 2,842 | 0.007389 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ll be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/lice... | ------------------------------------------
## This file defines parameters for a prediction experiment.
import os
from nupic.frameworks.opf.exp_description_helpers import importBaseDescription
# the sub-experiment configuration
config = \
{ 'modelParams': { 'clParams': { 'verbosity': 0},
'inferenc... |
lnls-sirius/dev-packages | siriuspy/siriuspy/clientarch/__init__.py | Python | gpl-3.0 | 306 | 0 | """Subpackage for the Archiver server."""
fr | om ..envars import SRVURL_ARCHIVER as SERVER_URL
from .client import ClientArchiver
from .pvarch import PVDetails, PVData, PVDataSet
from .devices import Orbit, Correctors, TrimQuads
from .time import Time
from . import exceptions
del client, | pvarch, devices
|
openqt/algorithms | leetcode/python/lc754-reach-a-number.py | Python | gpl-3.0 | 1,163 | 0.009458 | # coding=utf-8
import unittest
"""754. Reach a Number
https://leetcode.com/problems/reach-a-number/description/
You are standing at position `0` on an infinite number line. There is a goal
at position `target`.
On each move, you can either go left or right. During the _n_ -th move
(starting from 1), you take _n_ ste... | rst move we step from 0 to 1.
On the second move we step from 1 to -1.
On the third move we step from -1 to 2.
**Note:**
* `target` will be a non-zero integer in the range `[-10^9, 10^9]`.
Similar Questions:
"""
class Solution(object):
def reachNumber(self, target):
"""
... | ype target: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
|
danstoner/python_experiments | playing_with_kivy/kivi-examples/widgets/lists/list_reset_data.py | Python | gpl-2.0 | 2,398 | 0.000834 | # -*- coding: utf-8 -*-
from kivy.uix.listview import ListView
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from kivy.adapters.listadapter import ListAdapter
from kivy.adapters.models import SelectableDataItem
from kivy.uix.listview import ListItemButton
from random import choice
from str... | lass DataItem(SelectableDataItem):
def __init__(self, **kwargs):
super(DataItem, self).__init__(**kwargs)
self.name = ''.join(choice(ascii_uppercase + digits) for x in range(6))
class MainView(FloatLayout):
"""
Implementation of a ListView using the kv language.
"""
def __init__(s... | View, self).__init__(**kwargs)
data_items = []
data_items.append(DataItem())
data_items.append(DataItem())
data_items.append(DataItem())
list_item_args_converter = lambda row_index, obj: {'text': obj.name,
'size_hint_y'... |
hpk42/pluggy | testing/benchmark.py | Python | mit | 2,435 | 0 | """
Benchmarking and performance tests.
"""
import pytest
from pluggy import HookspecMarker, HookimplMarker, PluginManager
from pluggy._hooks import HookImpl
from pluggy._callers import _multicall
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
@hookimpl
def hook(arg1, arg2, arg3): |
return arg1, arg2, arg3
@hookimpl(hookwrapper=True)
def wrapper(arg1, arg2, arg3):
yield
@pytest.fixture(params=[10, 100], ids="hooks={}".format)
def hooks(request):
return [hook for i in range(request.param)]
@pytest.fixture(params=[10, 100], ids="wrappers={}".format)
def wrappers(request):
retu... | [wrapper for i in range(request.param)]
def test_hook_and_wrappers_speed(benchmark, hooks, wrappers):
def setup():
hook_name = "foo"
hook_impls = []
for method in hooks + wrappers:
f = HookImpl(None, "<temp>", method, method.example_impl)
hook_impls.append(f)
... |
DarthGeek01/PopulationSimulator | Genetics/Allele.py | Python | gpl-2.0 | 6,542 | 0.003363 | __author__ = 'ariel'
"""
Python Population Simulator
Copyright (C) 2015 Ariel Young
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 yo... | = trait
if alleles:
if letter_one != None:
self.letterOne = letter_one
if letter_two != None:
self.letterTwo = letter_two
if self.letterOne and self.letterTwo:
if self.letterOne.isupper() and self.letterTwo.isupper():
... | ressions.HOMOZYGOUS_DOMINANT
self.genotype = Genotypes.DOMINANT
elif self.letterOne.isupper() and not self.letterTwo.isupper():
self.expression = Expressions.HETEROZYGOUS_DOMINANT
self.genotype = Genotypes.DOMINANT
elif not self... |
GaelVaroquaux/diffusion-segmentation | spectral_embedding.py | Python | bsd-3-clause | 11,610 | 0.006202 | import numpy as np
import scipy
from scipy import linalg
from scipy import sparse
from scipy import ndimage
import scipy.sparse.linalg.eigen.arpack
from scipy.sparse.linalg.eigen.arpack import eigen, eigen_symmetric
#from pyamg.graph import lloyd_cluster
import pyamg
from pyamg import smoothed_aggregation_solver
from s... | [diag_mask] = 1
d = np.sign(diag_weights)/np.sqrt(np.abs( | diag_weights))
lap = abs_adjacency*d[:, np.newaxis]*d[np.newaxis, :]
lambdas, diffusion_map = linalg.eigh(lap)
return lambdas, diffusion_map.T[-2::-1]*d
def spectral_embedding_sparse(adjacency, k_max=14, mode='amg', take_first=True):
""" A diffusion reordering, but that works for negative values.
"... |
googleapis/python-retail | google/cloud/retail_v2/services/search_service/__init__.py | Python | apache-2.0 | 765 | 0 | # -*- coding: | utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop | y 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 for the specific... |
StackStorm/mistral | mistral/tests/unit/engine/test_action_defaults.py | Python | apache-2.0 | 6,915 | 0 | # Copyright 2015 - StackStorm, 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 ... | est cases
# the change in value is not perma | nent.
cfg.CONF.set_default('auth_enable', False, group='pecan')
ENV = {
'__actions': {
'std.http': {
'auth': 'librarian:password123',
'timeout': 30,
}
}
}
EXPECTED_ENV_AUTH = ('librarian', 'password123')
WORKFLOW1 = """
---
version: "2.0"
wf1:
type: direct
tasks:
... |
rodxavier/open-pse-initiative | django_project/companies/models.py | Python | mit | 2,705 | 0.004806 | from datetime import datetime, timedelta
from django.db import models
from django.db.models import Max, Min
from tinymce.models import HTMLField
class Company(models.Model):
name = models.CharField(max_length=75, blank=True, null=True)
symbol = models.CharField(max_length=10, blank=True, null=True)
descr... | y
def readable_name(self):
if self.is_index:
return self.name[1:]
else:
return self.name
@property
def year_high(self):
today = datetime.now()
one_year = timedelta(days=52*7)
if today.isoweekday() == 6:
today = today - time... | edelta(days=2)
last_year = today - one_year
quotes = self.quote_set.filter(quote_date__gt=last_year)
if quotes.count() == 0:
return 0.0
year_high = quotes.aggregate(Max('price_high'))
return ('%f' % year_high['price_high__max']).rstrip('0').rstrip('.')
@p... |
springload/draftjs_exporter | draftjs_exporter/defaults.py | Python | mit | 1,811 | 0 | from draftjs_exporter.constants import BLOCK_TYPE | S, INLINE_STYLES
from draftjs_exporter.dom import DOM
from draftjs_exporter.types import Element, Props
def render_children(props: Props) -> Element:
"""
Renders the children of a component w | ithout any specific
markup for the component itself.
"""
return props["children"]
def code_block(props: Props) -> Element:
return DOM.create_element(
"pre", {}, DOM.create_element("code", {}, props["children"])
)
# Default block map to extend.
BLOCK_MAP = {
BLOCK_TYPES.UNSTYLED: "p",... |
rdhyee/waterbutler | tests/providers/s3/test_provider.py | Python | apache-2.0 | 33,061 | 0.001936 | import os
import io
import time
import base64
import hashlib
import aiohttpretty
from http import client
from urllib import parse
from unittest import mock
import pytest
from waterbutler.core import (streams,
metadata,
exceptions)
from waterbutler.providers.... | def bulk_delete_body(keys):
payload = '<?xml version="1.0" encoding="UTF-8"?>'
payload += '<Delete>'
payload += ''.join(map(
lambda x: '<Object><Key>{}</Key></Object>'.format(x),
keys
)) |
payload += '</Delete>'
payload = payload.encode('utf-8')
md5 = base64.b64encode(hashlib.md5(payload).digest())
headers = {
'Content-Length': str(len(payload)),
'Content-MD5': md5.decode('ascii'),
'Content-Type': 'text/xml',
}
return (payload, headers)
def build_folde... |
ychab/mymoney | mymoney/apps/banktransactions/migrations/0001_initial.py | Python | bsd-3-clause | 2,559 | 0.004689 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bankaccounts', '0001_initial'),
('banktransactiontags', '0001_initial'),
]
... | t', models.ForeignKey(to='bankaccounts.BankAccount', related_name='banktransactions', on_delete=models.CASCADE)),
('tag', models.ForeignKey(related_name='banktransactions', on_delete=django.db.models.deletion.SET_NULL, verbose_name='Tag', to='banktransactiontags.BankTransactionTag', blank=True, null=Tru... | migrations.AlterIndexTogether(
name='banktransaction',
index_together=set([('bankaccount', 'reconciled'), ('bankaccount', 'date'), ('bankaccount', 'amount')]),
),
]
|
intelxed/mbuild | mbuild/doxygen.py | Python | apache-2.0 | 12,057 | 0.015012 | #!/usr/bin/env python
# -*- python -*-
#BEGIN_LEGAL
#
#Copyright (c) 2016 Intel Corporation
#
# 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-... | if len(output) > 0:
first_line = output[0].strip()
if base.verbose(2):
base.msgb("Doxygen version", first_line)
d | oxygen_okay = _doxygen_version_okay(first_line, 1,4,6)
else:
for o in output:
base.msgb("Doxygen-version-check STDOUT", o)
if error_output:
for line in error_output:
base.msgb("STDERR ",line.rstrip())
exc... |
Ebag333/Pyfa | eos/effects/systemoverloadhardening.py | Python | gpl-3.0 | 406 | 0.004926 | # systemOverloadHardening
#
# Used by:
# Celestials named like: Red Giant Beacon Class (6 of 6)
runTime = " | early"
type = ("projected", "passive")
def handler(fit, module, context):
fit.modules.filteredItemMultiply(lambda mod: "overloadHardeningBonus" in mod.itemModifiedAttributes,
"overloadHardeningBonus", module.getModifiedItemAttr("o | verloadBonusMultiplier"))
|
frac/celery | examples/celery_http_gateway/settings.py | Python | bsd-3-clause | 2,931 | 0.000341 | # Django settings for celery_http_gateway project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
CARROT_BACKEND = "amqp"
CELERY_RESULT_BACKEND = "database"
BROKER_HOST = "localhost"
BROKER_VHOST = "/"
BROKER_USER = "guest"
BROKER_PASSWORD = "guest"
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
... | an be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the inter | nationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.