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 |
|---|---|---|---|---|---|---|---|---|
LLNL/spack | var/spack/repos/builtin/packages/qnnpack/package.py | Python | lgpl-2.1 | 3,348 | 0.002688 | # Copyright 2013-2021 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 Qnnpack(CMakePackage):
"""QNNPACK (Quantized Neural Networks PACKage) is a mobile-optimize... | elease-1.8.0.zip',
sha256='f3ed3b58511efd272eb074a3a6d6fb79d | 7c2e6a0e374323d1e6bcbcc1ef141bf',
destination='deps',
placement='googletest',
)
resource(
name='psimd',
git='https://github.com/Maratyszcza/psimd.git',
destination='deps',
placement='psimd'
)
resource(
name='pthreadpool',
git='https://githu... |
pcmoritz/ray-1 | python/ray/util/dask/__init__.py | Python | apache-2.0 | 1,309 | 0 | import dask
from .scheduler import ray_dask_get, ray_dask_get_sync
from .callbacks import (
RayDaskCallback,
local_ray_callbacks,
unpack_ray_callbacks,
)
from .optimizations import dataframe_optimize
dask_persist = dask.persist
def ray_dask_persist(*args, **kwargs):
kwargs["ray_persist"] = True
r... | s)
ray_dask_persist | _mixin.__doc__ = dask_persist_mixin.__doc__
# We patch dask in order to inject a kwarg into its `dask.persist()` calls,
# which the Dask-on-Ray scheduler needs.
# FIXME(Clark): Monkey patching is bad and we should try to avoid this.
def patch_dask(ray_dask_persist, ray_dask_persist_mixin):
dask.persist = ray_dask... |
dreamer-dead/porto | src/api/python/setup.py | Python | lgpl-3.0 | 440 | 0.027273 | from setuptools import setup
def readme():
| with open('README.rst') as f:
return f.read()
setup(name='portopy',
version='0.1',
description='Python API for porto',
long_description=readme(),
url='https://github.com/yandex/porto',
author='marchael',
author_email='marchael@yandex-team.ru',
license='none',
packages=['porto'],... | protobuf',
],
zip_safe=False)
|
dmuhamedagic/crmsh | crmsh/cibstatus.py | Python | gpl-2.0 | 12,096 | 0.000496 | # Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# See COPYING for license information.
import os
from tempfile import mkstemp
from lxml import etree
from . import tmpfiles
from . import xmlutil
from . import utils
from . import config
from .utils import ext_cmd, show_dot_graph, page_string
from .msg... | iv = o.get("interval")
if iv == interval or (interval == "-1" and iv != "0"):
l.append(o)
return l
def split_op(op):
if op == "probe":
return "monitor", "0"
elif op == "monitor":
return "monitor", "-1"
elif op[0:8] == "monitor:":
return ... | ce[7:]) or source
class CibStatus(object):
'''
CIB status management
'''
cmd_inject = "</dev/null >/dev/null 2>&1 crm_simulate -x %s -I %s"
cmd_run = "2>&1 crm_simulate -R -x %s"
cmd_simulate = "2>&1 crm_simulate -S -x %s"
node_ops = {
"online": "-u",
"offline": "-d",
... |
imayhaveborkedit/discord.py | discord/client.py | Python | mit | 44,891 | 0.001983 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 u... | _remove`
- Typing events will be disabled (:func:`on_typing_start`).
- If ``fetch_offline_members`` is set to ``False`` then the user cache will not exist.
This makes it difficult or impossible | to do many things, for example:
- Computing permissions
- Querying members in a voice channel via :attr:`VoiceChannel.members` will be empty.
- Most forms of receiving :class:`Member` will be
receiving :class:`User` instead, except for m... |
ByrdOfAFeather/AlphaTrion | Announcements/views.py | Python | mit | 1,700 | 0.025294 | from django.shortcuts import render
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Announcement
from .forms import AnnouncementForm
def announcem... | :param announcementid: the id to delete an announcement
:type announcementid: integ | er
"""
announcement = get_object_or_404(Announcement, pk=announcementid)
announcement.delete()
return HttpResponseRedirect(reverse('announcements-home', current_app='Announcements'))
|
matthiaskoenig/tellurium-web | teweb/combine/metadata/annotation.py | Python | lgpl-3.0 | 6,591 | 0.003641 | """
Handle the term annotations.
"""
from pprint import pprint
from combine.metadata.webservices import json_providers_for_uri, json_term_for_uri
ICON_WARNING = "<span class=\"fa fa-exclamation-circle fa-lg\" title=\"true\" style=\"color:red\"> </span>"
ICON_TRUE = "<span class=\"fa fa-check-circle fa-lg\" title=\"tr... | class="comment">OBO Synonyms</span> '
for synonym in obo_synonyms:
html += synonym.get("nam | e") + "; "
html += "<br />\n"
# resources
# pprint(self.providers)
for provider in self.providers:
url = Annotation._url_from_provider(provider, obo_id)
info = provider["info"]
official = provider["official"]
if official:
... |
shubhamgupta123/erpnext | erpnext/stock/get_item_details.py | Python | gpl-3.0 | 35,632 | 0.025819 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, throw
from frappe.utils import flt, cint, add_days, cstr, add_months
import json
from erpnext.accounts.doctype.prici... |
reserved_so = get_so_reservation_for_item(args)
out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
def set_valuation_rate(out, args):
if frappe.db.exists("Product Bundle", args.item_code, cache=True):
valuation_rate = 0.0
bundled_items = frappe.get_doc("Product Bundle", args.item_... | out.get("warehouse")).get("valuation_rate") \
* bundle_item.qty)
out.update({
"valuation_rate": valuation_rate
})
else:
out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
def process_args(args):
if isinstance(args, string_types):
args = json.loads(args)
args = fr... |
daj0ker/BinPy | BinPy/examples/source/ic/Series_7400/IC7440.py | Python | bsd-3-clause | 1,248 | 0.001603 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Usage of IC 7400
# <codecell>
from __future__ import print_function
from BinPy import *
# <codecell>
# Usage of IC 7440:
ic = IC_7440()
print(ic.__doc__)
# <codecell>
# The Pin configuration is:
inp = {1: 1, 2: 0, 4: 0, 5: 0, 7: 0, ... | C with the current configuration\n
ic.drawIC()
# <codecell>
# Run the IC with the current configuration using -- print ic.run() --
# Note that the ic.run() returns a dict of pin configuration similar to
print (ic.run())
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run(... | the final configuration
ic.drawIC()
# <codecell>
# Seting the outputs to the current IC configuration using --
# ic.setIC(ic.run()) --
ic.setIC(ic.run())
# Draw the final configuration
ic.drawIC()
# Run the IC
print (ic.run())
# <codecell>
# Connector Outputs
c = Connector()
# Set the output connector to a p... |
tijeco/Fuster | utils/jason_parser.py | Python | gpl-3.0 | 235 | 0 | import json
from pprint import pprint
with | open('family_853.aln.codon.FUBAR.json') as data_file:
data = json.load(data_file)
pprint(data["MLE"]["content"]['0'][0 | ])
pprint(data["MLE"]["headers"])
pprint(data["MLE"]["headers"][0])
|
ThomasJunk/ringo | ringo/lib/request/helpers.py | Python | gpl-2.0 | 2,171 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import urlparse
def encode_unicode_dict(unicodedict, encoding="utf-8"):
bytedict = {}
for key in unicodedict:
if isinstance(unicodedict[key], unicode):
bytedict[key] = unicodedict[key].encode(encoding)
elif isinstance(unic... | :returns: Dictionary with key values pairs
"""
# We convert the encoded querystring into a bystring to enforce that
# parse_pq returns a dictionary which can be later decoded using
# decode_bystring_dict. If we use the encoded string directly the
# returned dicionary | would contain bytestring as unicode. e.g
# u'M\xc3\xbcller' which can't be decoded later.
encoded = str(encoded)
# Now convert the query string into a dictionary with UTF-8 encoded
# bytestring values.
values = urlparse.parse_qs(encoded)
for key in values:
values[key] = values[key][0]
... |
Curious72/sympy | sympy/vector/coordsysrect.py | Python | bsd-3-clause | 24,903 | 0.001084 | from sympy.core.basic import Basic
from sympy.vector.scalar import BaseScalar
from sympy import eye, trigsimp, ImmutableMatrix as Matrix, Symbol
from sympy.core.compatibility import string_types, range
from sympy.core.cache import cacheit
from sympy.vector.orienters import (Orienter, AxisOrienter, BodyOrienter,
... | e + '_x', name + '_y', name + '_z')
else:
_check_strings('variable_names', vector_names)
variable_names = list(variable_names)
latex_scalars = [(r"\mathbf{{%s}_{%s}}" % (x, name)) for
x in variable_names]
pretty_scalars = [(name + '_' + ... | in variable_names]
obj._x = BaseScalar(variable_names[0], 0, obj,
pretty_scalars[0], latex_scalars[0])
obj._y = BaseScalar(variable_names[1], 1, obj,
pretty_scalars[1], latex_scalars[1])
obj._z = BaseScalar(variable_names[2], 2, obj,
... |
jvansteirteghem/twunnel | twunnel/local_proxy_server__https.py | Python | mit | 7,810 | 0.009859 | # Copyright (c) Jeroen Van Steirteghem
# See LICENSE
from twisted.internet import interfaces, protocol, reactor, tcp
from zope.interface import im | plements
import twunnel.logger
class HTTPSInputProtocol(protocol.Protocol):
implements(interfaces.IPushProducer)
def __init__(self):
twunnel.logger.log(3, "trace: HTTPSInputProtocol.__init__")
self.configuration = None
self.outputProtocolConnectionManager = None
se... | ionMade(self):
twunnel.logger.log(3, "trace: HTTPSInputProtocol.connectionMade")
self.connectionState = 1
def connectionLost(self, reason):
twunnel.logger.log(3, "trace: HTTPSInputProtocol.connectionLost")
self.connectionState = 2
if self.outpu... |
tungvx/deploy | .google_appengine/google/appengine/_internal/django/template/defaulttags.py | Python | apache-2.0 | 42,800 | 0.003084 | """Default tags used by the template system, available to all templates."""
import sys
import re
from itertools import groupby, cycle as itertools_cycle
from google.appengine._internal.django.template import Node, NodeList, Template, Context, Variable
from google.appengine._internal.django.template import TemplateSyn... | ('nodelist_loop', 'nodelist_empty')
def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None):
self.loopvars, self.sequence = loopvars, sequence
self.is_reversed = is_reversed
self.nodelist_loop = nodelist_loop
if nodel | ist_empty is None:
self.nodelist_empty = NodeList()
else:
self.nodelist_empty = nodelist_empty
def __repr__(self):
reversed_text = self.is_reversed and ' reversed' or ''
return "<For Node: for %s in %s, tail_len: %d%s>" % (', '.join(self.loopvars), self.sequence, len... |
MartinHjelmare/home-assistant | homeassistant/components/openhome/media_player.py | Python | apache-2.0 | 6,577 | 0 | """Support for Openhome Devices."""
import logging
from homeassistant.components.media_player import (
MediaPlayerDevice)
from homeassistant.components.media_player.const import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK,
SUPPORT_SELECT_SOURCE, SUPPORT_STOP, SUPPORT_TURN_OFF,... | hass, device)
add_entities([device], True)
DEVICES.append(device)
return True
class OpenhomeDevice(MediaPlayerDevice):
"""Representation of an Openhome device."""
def __init__(self, hass, device):
"""Initialise the Openhome device."""
self.hass = hass
self._device = devi... | self._supported_features = SUPPORT_OPENHOME
self._source_names = list()
self._source_index = {}
self._source = {}
self._name = None
self._state = STATE_PLAYING
def update(self):
"""Update state of device."""
self._in_standby = self._device.IsInStandby()... |
adityacs/ansible | lib/ansible/modules/network/nxos/nxos_vtp_password.py | Python | gpl-3.0 | 7,998 | 0.002126 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | s+(?P<domain>\S+).*'
try:
match_version = re.match(version_regex, body, re.DOTALL)
version = match_version.groupdict()['version']
except AttributeError:
version = ''
try:
match_domain = | re.match(domain_regex, body, re.DOTALL)
domain = match_domain.groupdict()['domain']
except AttributeError:
domain = ''
if domain and version:
vtp_parsed['domain'] = domain
vtp_parsed['version'] = version
vtp_parsed['vtp_password'] = get_vtp_p... |
flower-pot/xf-indicator | xf_indicator/__init__.py | Python | mit | 1,347 | 0.003712 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2014 Frederic Branczyk fbranczyk@gmail.com
# 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 ... | t to the following conditions:
#
# The abo | ve copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONI... |
nicoladimauro/dcsn | discretize.py | Python | gpl-2.0 | 3,335 | 0.016206 | # =============================================================================
# Univerity of Bari "Aldo Moro"
# Department of Computer Science
# Nicola Di Mauro
# =============================================================================
# Copyright (c) 2016 Nicola Di Mauro,
# n1col4.d1m4uro un1b4.1t
# (rep... | ed[r,i] = 1
def _compute_LAIM(self, l, r, midpoint, i):
quanta_matrix = np.zeros((self.n_labels,2))
for k in r | ange(self.n_labels):
quanta_matrix[k][0]=np.sum(np.logical_and(self.data['X'][:,i]<=midpoint,self.data['Y'][:,k]==1))
quanta_matrix[k][1]=np.sum(np.logical_and(self.data['X'][:,i]>midpoint,self.data['Y'][:,k]==1))
m = np.sum(quanta_matrix[:,0])
if m == 0:
return -1
... |
python-rope/rope | ropetest/type_hinting_test.py | Python | lgpl-3.0 | 15,637 | 0.001215 | from textwrap import dedent
try:
import unittest2 as unittest
except ImportError:
import unittest
from rope.contrib.codeassist import code_assist
from rope.base.oi.type_hinting import evaluate
from ropetest import testutils
class AbstractHintingTest(unittest.TestCase):
def setUp(self):
super(Ab... | uper(AbstractHintingTest, self).run(result)
class DocstringParamHintingTest(AbstractHintingTest):
def test_hint_param(self):
code = dedent('''\
class Sample(object):
def a_method(self, a_arg):
""":type a_arg: threading.Thread"""
a_arg.is_... | "is_alive", "attribute", result)
def test_hierarchical_hint_param(self):
code = dedent('''\
class ISample(object):
def a_method(self, a_arg):
""":type a_arg: threading.Thread"""
class Sample(ISample):
def a_method(self, a_arg):
... |
Distrotech/PyQt-x11 | examples/animation/easing/easing_rc2.py | Python | gpl-2.0 | 22,193 | 0.000225 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Wed Mar 20 11:16:13 2013
# by: The Resource Compiler for PyQt (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x14\x1d\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x... | xe4\x0f\x00\x00\x00\xff\xff\x22\x3a\
\xc4\x19\x19\x99\x18\x0e\xee\x7e\xce\xa0\xa9\xac\xcb\x50\x16\x95\
\xcb\xc0\xc0\xc0\xc0\xc0\xca\xc2\xc2\xc0\xc8\xc8\xc8\xf0\xff\x3f\
\x24\x99\xdc\x78\x7b\x92\xa1\x66\x43\x3a\x83\x4f\x65\x04\xc3\xda\
\x43\x5b\xa0\x21\xc6\x08\x0f\xb9\x10\xed\x3c | \x06\x45\x41\x6d\x86\
\x9f\x7f\xbe\x31\x30\x33\x31\x33\xfc\xff\xc7\xc8\xf0\xf4\xf1\x17\
\x06\x6d\x25\x55\x06\x19\x51\x69\xa8\x63\x19\x18\xfe\x13\x51\x12\
\x01\x00\x00\x00\xff\xff\x84\xd4\x2b\x0e\xc2\x40\x14\x46\xe1\xf3\
\xdf\xa6\x4c\x05\xeb\x40\xa0\x50\x2c\x02\x0d\x49\x75\x05\x0e\xc9\
\x1e\x58\x09\x8a\x2d\x90\x60\x70\x... |
aniketp41/Gymkhana-Nominations | nomi/migrations/0098_auto_20170624_1938.py | Python | mit | 547 | 0.001828 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 | on 2017-06-24 19:38
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nomi', '0097_auto_20170624_1936'),
]
operations = [
migrations.AlterField(
model_name='groupnominat... | 52), null=True),
),
]
|
jendrikseipp/rednotebook | setup.py | Python | gpl-2.0 | 4,992 | 0.001002 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# Copyright (c) 2009-2019 Jendrik Seipp
#
# RedNotebook 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... | h.basename(src))
dest = os.path.join(locale_dir, lang, "LC_MESSAGES", "rednotebook.mo")
dest_dir = os.pat | h.dirname(dest)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
print("Compiling {src} to {dest}".format(**locals()))
subprocess.check_call([sys.executable, MSGFMT, "--output-file", dest, src])
class build_trans(cmd.Command):
"""
Code taken from mussorgsky
(https... |
cloudbau/glance | glance/openstack/common/gettextutils.py | Python | apache-2.0 | 7,422 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Red Hat, Inc.
# All Rights Reserved.
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | e:
self.params = (other, )
else:
self.params = copy.deepcopy(other)
return self
# overrides to be more string-like
def __unicode__(self):
return self.data
def __str__(self):
return self.data.encode('utf-8')
def __getstate__(self):
to_co... | ', '_right_extra_msg', '_left_extra_msg',
'domain', 'params', 'locale']
new_dict = self.__dict__.fromkeys(to_copy)
for attr in to_copy:
new_dict[attr] = copy.deepcopy(self.__dict__[attr])
return new_dict
def __setstate__(self, state):
for (k, v) in st... |
bjoernricks/kaizen | kaizen/db/update/update_0.py | Python | gpl-2.0 | 2,234 | 0.001791 | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# kaizen - Continuously improve, build and manage free software
#
# Copyright (C) 2011 Björn Ricks <bjoern.ricks@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as publishe... | ng update %r %r" % (self.version, self.name))
db = self.db.rules
query = db.query(RulesPhase.rules, RulesPhase.version).distinct( \
RulesPhase.rules, RulesPhase.version)
for rulesphase in query:
rules_name = rulesphase[0] |
rules_version = rulesphase[1]
handler = RulesHandler(self.config, rules_name, rules_version)
rules = handler.rules
install_directories = InstallDirectories(rules_name,
rules_version)
install_directories.bui... |
kalxas/QGIS | scripts/mkuidefaults.py | Python | gpl-2.0 | 2,903 | 0.000344 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
***************************************************************************
mkuidefaults.py
---------------------
Date : June 2013
Copyright : (C) 2013 by Juergen E. Fischer
Email : jef at norbit dot de
***... | hunks(ba, 16):
f.write(' {},\n'.format(
', '.join(map(hex, struct.unpack('B' * len(chunk), chunk)))))
except TypeError as ex:
pass
try:
ba = bytes(s.value("/app/LayoutDesigner/state"))
f.write("};\n\nstatic const | unsigned char " +
"defaultLayerDesignerUIstate[] =\n{\n")
for chunk in chunks(ba, 16):
f.write(' {},\n'.format(
', '.join(map(hex, struct.unpack('B' * len(chunk), chunk)))))
except TypeError as ex:
pass
f.write("};\n\n#endif // UI_DEFAULTS_H\n")
|
nint8835/SchoolTracker | Start.py | Python | mit | 530 | 0 | import logging
import os
fr | om SchoolTracker import SchoolTracker
from SchoolTracker.Dispatcher.TwitterDispatcher import TwitterDispatcher
from SchoolTracker.Dispatcher.PushoverDispatcher import PushoverDispatcher
if os.getenv("SCHOOLTRACKER_DEBUG", False):
log_level = logging.DEBUG
else:
log_level = logging.INFO
schooltracker = SchoolTr... | spatcher)
schooltracker.start()
|
fatbox/TestFlight-Appcelerator-Module | build.py | Python | apache-2.0 | 5,843 | 0.049974 | #!/usr/bin/env python
#
# Appcelerator Titanium Module Packager
#
#
import os, sys, glob, string
import zipfile
from datetime import date
cwd = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))
os.chdir(cwd)
required_module_keys = ['name','version','moduleid','description','copyright','license','co... | before + method + after
if newc!=c:
x = open(f,'w')
x.write(newc)
x.close()
def die(msg):
print msg
sys.exit(1)
def warn(msg):
print "[WARN] %s" % msg
def validate_license():
c = open(os.path.join(cwd,'LICENSE') | ).read()
if c.find(module_license_default)!=1:
warn('please update the LICENSE file with your license text before distributing')
def validate_manifest():
path = os.path.join(cwd,'manifest')
f = open(path)
if not os.path.exists(path): die("missing %s" % path)
manifest = {}
for line in f.readlines():
line =... |
laputian/dml | test/bm_stacko_1_1.py | Python | mit | 489 | 0.014315 | # http://stackoverflow.com/questions/13202799/python-code-geometric-brownian-motion-whats-wrong |
import matplotlib.pyplot as plt
import numpy as np
T = 2
mu = 0.1
sigma = 0.1
S0 = 10
dt = 0.01
alpha = 0.1
N = round(T/dt | )
t = np.linspace(0, T, N)
W = np.random.standard_normal(size = N)
W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
X = ((mu + alpha * W)-0.5*sigma**2)*t + sigma*W
S = S0*np.exp(X) ### geometric brownian motion ###
plt.plot(t, S, '-', t, W, '--')
plt.show() |
bytescout/ByteScout-SDK-SourceCode | PDF.co Web API/Invoice Parser API/Python/Get Invoice Info From Uploaded File/GetInvoiceInfoFromUploadedFile.py | Python | apache-2.0 | 2,505 | 0.008383 | import os
import requests # pip install requests
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "******************************************"
# Base URL for PDF.co Web API requests
BASE_URL = | "https://api.pdf.co/v1"
# Source PDF file
SourceFile = ".\\sample.pdf"
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
ge | tInfoFromPDF(uploadedFileUrl)
def getInfoFromPDF(uploadedFileUrl):
"""Get Information using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["url"] = uploadedFileUrl
parameters["inline"] = True
# Prepare URL for 'i... |
CountZer0/PipelineConstructionSet | maya/plugins/2014/win64/AM_ExposeTransform.py | Python | bsd-3-clause | 37,816 | 0.005738 | """
A node and corresponding command to expose transform information about one
transform node with respect to another.
\b Creation \b Info:
\b Donations: http://adammechtley.com/donations/
\b License: The MIT License
Copyright (c) 2011 Adam Mechtley (http://adammechtley.com)
Permission is hereby granted, free of c... | AM_ExposeTransformCmd.kExposedObjectFlag):
sel.add(argData.flagArgumentString(AM_ExposeTransformCmd.kExposedObjectFlag, 0))
sel.getDagPath(sel.length() - 1, self.__exposedObjectArg)
else:
raise Exception(
... | gument to be specified or selected; found %i.' % sel.length())
else:
iter = OM.MItSelectionList(sel, OM.MFn.kDependencyNode)
selectedObject = OM.MObject()
while not iter.isDone():
# in edit or query mode, the object must be an am_exposeTra... |
SeedScientific/polio | datapoints/migrations/0073_auto__del_field_datapointabstracted_region_id__del_field_datapointabst.py | Python | agpl-3.0 | 22,049 | 0.007347 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'DataPointAbstracted', fields ['region_id', 'camp... | ntAbstracted.region_id' and its values cannot be restored.")
# The following code is provided here to aid in writing a correct migration # Adding field 'DataPointAbstracted.region_id'
db | .add_column('datapoint_abstracted', 'region_id',
self.gf('django.db.models.fields.IntegerField')(),
keep_default=False)
# User chose to not deal with backwards NULL issues for 'DataPointAbstracted.campaign_id'
raise RuntimeError("Cannot reverse this migratio... |
apple/coremltools | coremltools/test/modelpackage/test_modelpackage.py | Python | bsd-3-clause | 20,269 | 0.0037 | # Copyright (c) 2021, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
import os
import pytest
import shutil
import tempfile
import coremltools
from coreml... | author"
assert model.license == "Test license"
assert model.short_description == "Test model"
assert model.input_description["feature_1"] == "This is feature 1"
assert model.output_description["output"] == "This is output"
# | cleanup
_remove_path(package.name)
def test_predict_api(self):
model = MLModel(self.spec)
package = tempfile.TemporaryDirectory(suffix=".mlpackage")
package.cleanup()
model.save(package.name)
if utils._macos_version() >= (12, 0):
for compute_units in c... |
iparanza/earthenterprise | earth_enterprise/src/fusion/portableglobe/servers/windows/glc_unpacker.py | Python | apache-2.0 | 15,906 | 0.014271 | #!/usr/bin/python
#
# 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 a... | unpacker.delete_GlcUnpacker
__del__ = lambda self : None;
def FindDataPacket(self, *args): return _glc_unpacker.GlcUnpacker_FindDataPacket(self, *args)
def FindMapDataPacket(self, *args): return _glc_unpacker.GlcUnpacker_FindMapDataPacket(self, *args)
def FindQtpPacket(self, *args): return _glc_unpack | er.GlcUnpacker_FindQtpPacket(self, *args)
def FindLayerFile(self, *args): return _glc_unpacker.GlcUnpacker_FindLayerFile(self, *args)
def FindFile(self, *args): return _glc_unpacker.GlcUnpacker_FindFile(self, *args)
def FindMetaDbRoot(self, *args): return _glc_unpacker.GlcUnpacker_FindMetaDbRoot(self, *args... |
edoburu/django-private-storage | private_storage/urls.py | Python | apache-2.0 | 179 | 0.005587 | from djan | go.urls import re_path
from .views import PrivateStorageView
urlpatterns = [
re_path(r'^(?P<path>.*)$', PrivateStorageView.as_view(), name='serve_private_file'),
| ]
|
canwe/NewsBlur | vendor/tweepy/parsers.py | Python | mit | 2,622 | 0.002288 | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
from tweepy.models import ModelFactory
from tweepy.utils import import_simplejson
from tweepy.error import TweepError
class Parser(object):
def parse(self, method, payload):
"""
Parse the response payload and return the r... | :
pass
def parse(self, method, payload):
return payload
def parse_error(self, payload):
return payload
class JSONParser(Parser):
payload_format = 'json'
def __init__(self):
self.json_lib = import_simplejson()
def parse(self, method, payload):
try:
... | y('cursor')
if needsCursors and isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
cursors = json['previous_cursor'], json['next_cursor']
return json, cursors
else:
return json
def parse_error(self, payload):
error = self.json... |
Belgabor/django | tests/regressiontests/backends/models.py | Python | bsd-3-clause | 3,896 | 0.00308 | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.db import models
from django.db import connection, DEFAULT_DB_ALIAS
class Square(models.Model):
root = models.IntegerField()
square = models.PositiveIntegerFi... | ld(max_length=100)
m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.ManyToManyField(Person,blank=True)
class Tag(models.Model):
name = models.CharField(max_length=30)
content_type = models.ForeignKey(ContentType, r | elated_name='backend_tags')
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Post(models.Model):
name = models.CharField(max_length=30)
text = models.TextField()
tags = generic.GenericRelation('Tag')
class Meta:
db... |
plxaye/chromium | src/remoting/tools/gaia_auth.py | Python | apache-2.0 | 1,043 | 0.008629 | # Copyright (c) 2010 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.
import getpass
import os
import urllib
DEFAULT_GAIA_URL = "https://www.google.com:443/accounts/ClientLogin"
class GaiaAuthenticator:
def __init__(sel... | 'source': 'chromoting',
'service': self._service,
'PersistentCookie': 'true',
'accountType': 'GOOGLE'})
f = urllib.urlopen(self._url, params);
result = f.read()
for line in result.splitl | ines():
if line.startswith('Auth='):
auth_string = line[5:]
return auth_string
raise Exception("Gaia didn't return auth token: " + result)
|
fathat/squirtle | squirtle/matrix.py | Python | bsd-3-clause | 2,127 | 0.009873 | import math
import ctypes
from parse import *
class Matrix(object):
def __init__(self, string=None):
self.values = [1, 0, 0, 1, 0, 0] #Identity matrix seems a sensible default
if isinstance(string, str):
if string.startswith('matrix('):
self.values = [float(x) for x in p... | startswith('translate('):
x, y = [float(x) for x in parse_list(string[10:-1])]
self.values = [1, 0, 0, 1, x, y]
eli | f string.startswith('scale('):
sx, sy = [float(x) for x in parse_list(string[6:-1])]
self.values = [sx, 0, 0, sy, 0, 0]
elif string is not None:
self.values = list(string)
def __call__(self, other):
return (self.values[0]*other[0] + self.va... |
jrg365/gpytorch | test/lazy/test_lazy_evaluated_kernel_tensor.py | Python | mit | 6,765 | 0.002661 | #!/usr/bin/env python3
import math
import unittest
from unittest.mock import MagicMock, patch
import torch
import gpytorch
from gpytorch.test.lazy_tensor_test_case import LazyTensorTestCase, _ensure_symmetric_grad
class TestLazyEvaluatedKernelTensorBatch(LazyTensorTestCase, unittest.TestCase):
seed = 0
de... | _cg_mock.called)
else:
self.assertFalse(linear_cg_mock.called)
def test_inv_matmul_matrix_with_checkpointing(self):
# Add one checkpointing test
lazy_tensor = self.create_lazy_tensor().requires_grad_(True)
lazy_tensor_copy = lazy_tensor.clone().detach_().requires... | ()
with gpytorch.beta_features.checkpoint_kernel(2):
res = lazy_tensor.inv_matmul(test_vector)
actual = evaluated.inverse().matmul(test_vector_copy)
self.assertLess(((res - actual).abs() / actual.abs().clamp(1, 1e5)).max().item(), 3e-1)
grad = torch.randn_like(re... |
annapowellsmith/openpresc | openprescribing/frontend/tests/commands/test_generate_presentation_replacements.py | Python | mit | 4,653 | 0 | from django.core.management import call_command
from django.test import TestCase
from frontend.models import Chemical
from frontend.models import Presentation
from frontend.models import Product
from frontend.models import Section
from mock import patch
@patch('frontend.management.commands.generate_presentation_repl... | esentation.objects.get(bnf_code='YYYYYYYYYYYYYYY')
self.assertEqual(p.replaced_by.bnf_code, 'ZZZZZZZZZZZZZZZ')
self.assertEqual(p.current_version.bnf_code, 'ZZZZZZZZZZZZZZZ')
# Double replacement including section change
p = Presentation.objects.get(bnf_code='777777777777777')
s... | ion.objects.get(bnf_code='MMMMMMMMMMMMMMM')
self.assertEqual(p.current_version.bnf_code, 'MMMMMMMMMMMMMMM')
def test_chemical_currency(
self,
mock_cleanup_empty_classes,
mock_create_bigquery_table,
mock_handle):
call_command(
'generate_pre... |
duncanmmacleod/ligo.org | ciecplib/sessions.py | Python | gpl-3.0 | 1,712 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Cardiff University (2020)
#
# This file is part of ciecplib.
#
# ciecplib is free software: you can redistribute it and/or modify
# it under the terms of the GN | U General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ciecplib is distributed in the h | ope that it will be useful,
# but WITHOUT ANY WARRANTY; without 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 ciecplib. If not, see <http://ww... |
HumanBrainProject/neuroglancer-scripts | unit_tests/test_volume_reader.py | Python | mit | 2,013 | 0 | import nibabel as nib
import numpy as np
import pytest
import json
from unittest.mock import patch
from neuroglancer_scripts.volume_reader import nibabel_image_to_info, \
volume_file_to_precomputed
def prepare_nifti_images():
| random_rgb_val = np.random.rand(81).reshape((3, 3, 3, 3)) * 255
random_rgb_val = random_rgb_val.astype(np.uint8)
right_type = np.dtype([("R", "u1"), ("G", "u1"), ("B", "u1")])
new_data = random_rgb_val.copy().view(dtype=right_type).reshape((3, 3, 3))
rgb_img = nib.Nifti1Image( | new_data, np.eye(4))
random_uint8_val = np.random.rand(27).reshape((3, 3, 3)) * 255
random_uint8_val = random_uint8_val.astype(np.uint8)
uint8_img = nib.Nifti1Image(random_uint8_val, np.eye(4))
return [(rgb_img, 3), (uint8_img, 1)]
@pytest.mark.parametrize("nifti_img,expected_num_channel",
... |
Netflix/sleepy-puppy | manage.py | Python | apache-2.0 | 7,364 | 0.001765 | #!/usr/bin/env python
# Copyright 2015 Netflix, 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 requ... | he License.
import getpass
import os
from flask_script.commands import ShowUrls, Clean
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from sleepypuppy.admin.admin.models import Administrator
from sleepypuppy import app, db
from js_strings import default_script, alert_box, co... | teCommand)
@manager.shell
def make_shell_context():
"""
Creates a python REPL with several default imports
in the context of the app
"""
return dict(app=app)
@manager.command
def create_db():
"""
Creates a database with all of the tables defined in
your Alchemy models
"""
db.... |
borisroman/vdsm | vdsm/storage/sd.py | Python | gpl-2.0 | 29,084 | 0.000344 | #
# Copyright 2009-2011 Red Hat, Inc.
#
# 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 program is distributed ... | US, DOM_ACTIVE_STATUS]
DEPRECATED_STATUSES = {DEPRECATED_DOM_INACTIVE_STATUS: DOM_ATTACHED_STATUS}
# Domain Role
MASTER_DOMAIN = 'Master'
REGULAR_DOMAIN = 'Regular'
# Domain Class
DATA_DOMAIN = 1
ISO_DOMAIN = 2
BACKUP_DOMAIN = 3
DOMAIN_CLASSES = {DATA_DOMAIN: 'Data', ISO_DOMAIN: 'Iso',
| BACKUP_DOMAIN: 'Backup'}
# Metadata keys
DMDK_VERSION = "VERSION"
DMDK_SDUUID = "SDUUID"
DMDK_TYPE = "TYPE"
DMDK_ROLE = "ROLE"
DMDK_DESCRIPTION = "DESCRIPTION"
DMDK_CLASS = "CLASS"
DMDK_POOLS = "POOL_UUID"
# Lock related metadata keys
DMDK_LOCK_POLICY = 'LOCKPOLICY'
DMDK_LOCK_RENEWAL_INTERVAL_SEC = 'LOCKRENEWALI... |
sebastienc/kubernetes-py | kubernetes_py/models/v1/Secret.py | Python | apache-2.0 | 8,321 | 0.002764 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
import base64
import json
from six import string_types
from kubernetes_py.models.unversioned.BaseModel import BaseModel
from kubernetes_py.mo... | ----- metadata
@property
def metadata(self):
return self._metadata
@metadata.setter
def metadata(self, md=None):
if not isinstance(md, ObjectMeta):
raise SyntaxError("Secret: metadata: [ {0} ] is invalid.".format(md)) |
self._metadata = md
# ------------------------------------------------------------------------------------- data
@property
def data(self):
d = {}
for k, v in self._data.items():
d[k] = base64.b64decode(v)
if isinstance(d[k], bytes):
d[k] = d... |
dattalab/d_code | imaging/alignment/image_registration/image_registration/fft_tools/tests/test_upsample_1d.py | Python | mit | 2,642 | 0.02271 | from image_registration.fft_tools import zoom
import numpy as np
import pytest
import itertools
def gaussian(x):
return np.exp(-x**2/2.)
@pytest.mark.parametrize(('imsize','upsample_factor'),
list(itertools.product(range(20,27),range(1,25))))
def test_plot_tests(imsize, upsample_factor,doplot=False):
"""
... | gure(3); clf()
plot(gaussian(xz-(imsize-1)/2.)-z)
assert ((gaussian(xz - (imsize-1)/2.)-z)**2). | sum() < 4e-5*upsample_factor+0.12*imsize**-1.83
@pytest.mark.parametrize(('imsize','upsample_factor','offset'),
list(itertools.product(range(20,27),range(1,25),(-1,0,1))))
def test_gaussian_upsample(imsize, upsample_factor, offset):
"""
Test that, when upsampled, z[::upsample_factor] = g
Tested for of... |
crs4/pydoop | test/common/test_test_support.py | Python | apache-2.0 | 1,753 | 0 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2021 CRS4.
#
# 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... | /foo/bar/python
from __future__ import print_function
from future import whatever
import foobar
print("Hello, world")
"""
class TestTestSupport(unittest.TestCase):
def test_inject_code(self):
lines = TARGET_CODE.splitlines()
new_code = uuid.uuid4().hex
ret = pts.inject_code(new_code, TA... | GET_CODE)
ret_lines = ret.splitlines()
self.assertEqual(ret_lines[:3], lines[:3])
self.assertTrue(new_code in ret_lines[3:-4])
self.assertEqual(ret_lines[-4:], lines[-4:])
def test_set_python_cmd(self):
cmd = "/usr/bin/python3"
ret = pts.set_python_cmd(TARGET_CODE, c... |
biospi/mzmlb | pwiz/scripts/wix/pwiz-setup.py | Python | apache-2.0 | 3,683 | 0.014119 | #
# $Id: pwiz-setup.py 9964 2016-08-09 20:32:10Z chambm $
#
#
# Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
#
# Copyright 2012 Vanderbilt University - Nashville, TN 37232
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... | templatePath + "/pwiz-setup.wxs.template").read()
wxsTemplate = wxsTemplate.replace("__CONTEXTMENU_PROPERTIES__",contextMenuProperties())
wxsTemplate = wxsTemplate.replace("__CONTEXTMENU_REGISTRY__",contextMenuRegistries())
wxsTemplate = wxsTemplate.replace("__CONTEXTMENU_CHECKBOXEN__", | contextMenuOptions())
wxsTemplate = wxsTemplate.replace("{ProductGuid}", guid)
wxsTemplate = wxsTemplate.replace("{version}", version)
wxsTemplate = wxsTemplate.replace("msvc-release", installPath)
# delete old wxs and wixObj files
for filepath in glob.glob(buildPath + "/*.wxs"):
os.remove(filepath)
for filepath i... |
hpbader42/Klampt | Python/klampt/vis/visualization.py | Python | bsd-3-clause | 123,948 | 0.014046 | """Klamp't visualization routines. See Python/demos/vistemplate.py for an
example of how to run this module.
The visualization module lets you draw most Klamp't objects in a 3D world
using a simple interface. It also lets you customize the GUI using Qt
widgets, OpenGL drawing, and keyboard/mouse intercept routines... | a new split-screen
vis.dialog()
... or
vis.show()
... do stuff afterwards ...
vis.kill()
- To run a custom dialog in a QtWindow
vis.setPlugin([desired plugin or None for visualization])
vis.setParent(qt_window)
vis.dialog()
... or
vis.show()
... do stuff afterwards ...
vis.kill()
- To launc... | w was previously called with a plugin and you wish to
revert to the default visualization, you should call setPlugin(None) first to
restore the default.
- To create a separate window with a given plugin:
w1 = vis.createWindow() #w1=0
show()
w2 = vis.createWindow() #w2=1
vis.setPlugin(plugin)
vis.dialo... |
txdywy/airbb | misc/util.py | Python | mpl-2.0 | 1,425 | 0.008421 | import smtplib
import email.utils
from email.mime.text import MIMEText
import functools
import qiniu
try:
from config import AIRBB_HOST
except Exception, e:
print '==============no AIRBB_HOST set, ues airbb.xx as default==============', e
AIRBB_HOST = 'airbb.ml'
AIRBB_SUPPORT = 'support@%s' % AIRBB_HOST
d... | e(s)==str:
return s.decode('utf8','ignore')
else:
return s
def ex(func):
@functools.wraps(func)
def foo(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception, e:
print '===================send email ex======= | =========', e
return foo
@ex
def send_email(title, content, addr_to, addr_fr=None):
# Create the message
if not addr_fr:
addr_fr = ALANCER_SUPPORT
msg = MIMEText(makes(content), 'html')
msg['To'] = email.utils.formataddr(('Recipient', addr_to))
msg['From'] = email.utils.formataddr(('... |
robert-hh/XPT2046-touch-pad-driver-for-PyBoard | touch.py | Python | mit | 9,126 | 0.006246 | # asyncio version
# The MIT License (MIT)
#
# Copyright (c) 2016, 2017 Robert Hammelrath (basic driver)
# 2016 Peter Hinch (asyncio extension)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# ... | parameter(confidence, margin, delay, cal)
if asyn:
self.asynchronous = True
import uasyncio as asy | ncio
loop = asyncio.get_event_loop()
loop.create_task(self._main_thread())
# set parameters for get_touch()
# res: Resolution in bits of the returned values, default = 10
# confidence: confidence level - number of consecutive touches with a margin smaller than the given level
# which the ... |
yellcorp/Yellib | raw/src/org/yellcorp/lib/math/gen-factorial.py | Python | mit | 331 | 0 | #!/usr/bin/python
| import struct
import sys
import math
if len(sys.argv) != 2:
prin | t "Usage: gen-factorial filename"
sys.exit(1)
outfile = open(sys.argv[1], 'wb')
i = 0
try:
while True:
outfile.write(struct.pack("<d", float(math.factorial(i))))
i += 1
except OverflowError:
pass
outfile.close()
|
nitin-cherian/LifeLongLearning | Python/Experiments/ITERATORS/Polyglot.Ninja/iterables.py | Python | mit | 1,634 | 0.002448 | # iterables.py
print("""
An iterable is any object that returns an iterator when iter() function is invoked on it.
""")
print("""Writing an iterable that repeatedly returns an integer without stopping
{code}
class InfiniteIterator:
def __init__(self):
self.__int = 0
def __next__(self):
self._... | Numbers:
def __iter__(self):
return InfiniteIterator()
inf = InfiniteNumbers()
for i in inf:
if i > 100:
break
{code}
""")
class InfiniteIterator:
def __init__(self):
self.__int = 0
def __next__(self):
| self.__int += 1
return self.__int
class InfiniteNumbers:
def __iter__(self):
return InfiniteIterator()
inf = InfiniteNumbers()
for i in inf:
if i > 100:
break
print(i)
print("""
Write an iterator that stop after giving 100 integers
{code}
class HundredIterator:
def... |
StanfordLegion/legion | bindings/python/tests/pass/print_once.py | Python | apache-2.0 | 785 | 0.002548 | #!/usr/bin/env python3
# Copyright 2021 Stanford University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi | s 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 ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.... |
ahb0327/intellij-community | python/testData/addImport/localImportInlineFunctionBody.after.py | Python | apache-2.0 | 58 | 0.017241 | def fu | nc():
import module
module
# <ref> | |
TGAC/KAT | deps/boost/tools/build/test/library_property.py | Python | gpl-3.0 | 1,127 | 0.000887 | #!/usr/bin/python
# Copyright 2004 Vladimir Prus
# 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)
# Test that the <library> property has no effect on "obj" targets. Previously,
# it affected all targets, so
#
# project : ... | { gee(); }
""")
t.write("lib/x.cpp", """
void
#if defined(_WIN32)
__declspec(dllexport)
#endif
g | ee() {}
""")
t.write("lib/jamfile.jam", """
lib x : x.cpp ;
""")
t.write("lib/jamroot.jam", """
""")
t.run_build_system()
t.expect_addition("bin/$toolset/debug*/a.exe")
t.expect_nothing("lib/bin/$toolset/release/x.obj")
t.cleanup()
|
rackerlabs/python-proboscis | tests/compatability/testng/before_and_after/src/python/BeforeAndAfter.py | Python | apache-2.0 | 701 | 0.00428 | from proboscis import *
class BeforeAndAfter(object):
d | ef getName(self):
return str(type(self))
def println(self, msg):
print("%s : %s" % (self.getName(), msg))
class BeforeAndAfterSuccess(BeforeAndAfter):
@before_class
def beforeEverything(self):
self.println("@BeforeClass");
@before_method
def setUp(self):
self.pr... | method1(self):
self.println("@Test 1")
@test
def method2(self):
self.println("@Test 2")
@after_class
def afterEverything(self):
self.println("@AfterClass")
@after_method
def tearDown(self):
self.println("@AfterMethod")
|
matejcik/osc | osc/core.py | Python | gpl-2.0 | 290,098 | 0.004505 | # Copyright (C) 2006 Novell Inc. All rights reserved.
# This program is free software; it may be used, copied, modified
# and distributed under the terms of the GNU General Public Licence,
# either version 2, or version 3 (at your option).
from __future__ import print_function
__version__ = '0.159git'
# __store_ver... | rch>
</repository>
<repository na | me="SLE_12">
<path project="SUSE:SLE-12:GA" repository="standard" />
<arch>x86_64</arch>
<arch>i586</arch>
</repository>
-->
</project>
"""
new_package_templ = """\
<package name="%(name)s">
<title></title> <!-- Title of package -->
<description></description> <!-- for long description -->
<!-- f... |
pymedusa/Medusa | ext/oauthlib/oauth2/rfc6749/endpoints/introspect.py | Python | gpl-3.0 | 4,937 | 0 | # -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749.endpoint.introspect
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An implementation of the OAuth 2.0 `Token Introspection`.
.. _`Token Introspection`: https://tools.ietf.org/html/rfc7662
"""
from __future__ import absolute_import, unicode_literals
import json
import ... | rization server
offering token introspection MAY disallow the use of HTTP GET on
th | e introspection endpoint and instead require the HTTP POST method
to be used at the introspection endpoint.
"""
valid_token_types = ('access_token', 'refresh_token')
def __init__(self, request_validator, supported_token_types=None):
BaseEndpoint.__init__(self)
self.request_validator = re... |
chrisseto/osf.io | reviews/views.py | Python | apache-2.0 | 9,559 | 0.003975 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import Q
from django.shortcuts import get_object_or_404
from guardian.shortcuts import get_objects_for_user
from rest_framework import generics
from rest_framework import permissions
from rest_framework.exceptions import PermissionDe... | Attributes
name type description
====================================================================================
date_created iso8601 timestamp timestamp that the review log was created
... | the review log was last modified
from_state string state of the reviewable before this log was created
to_state string state of the reviewable after this log was created
comment ... |
SySS-Research/outis | syhelpers/modulebase.py | Python | mit | 4,301 | 0.00372 | from syhelpers.log import print_error, print_table_terminal
class ModuleBase:
"""
Base class for all modules (handler, transport, platform, ...)
Allows functions for options
"""
def __init__(self):
"""
Initialize Module, should be overwritten and options should be added
""... | er() not in self.options:
return []
if "Options" n | ot in self.options[str(name).upper()]:
return []
return [v for v in self.options[str(name).upper()]['Options'] if v.startswith(str(value).upper())]
def setoption(self, name, value):
"""
Sets option <name> to value <value> if possible.
Can be overwritten and expanded by m... |
pmacosta/putil | tests/test_eng.py | Python | mit | 40,156 | 0.005977 | # test_eng.py
# Copyright (c) 2013-2016 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0103,C0111,C0302,E0611,R0913,R0915,W0108,W0212
# Standard library imports
import functools
import sys
import pytest
from numpy import array, ndarray
# Putil imports
import putil.eng
from putil.test import AE, AI,... | 1E+24'),
(10000000000000000000000000, '10E+24'),
(10000000000000000000000000.1234567890, '10E+24'),
(100000000000000000000000000, '100E+24'),
(100000000000000000000000000.1234567890, '100E+24'),
(-0.000000000000000000000001001234567890, '-1.00123456789E-24'),
(-0.000000000000000000000001, '-1E-2... | 00.123456789E-24'),
(-0.0000000000000000000001, '-100E-24'),
(-0.000000000000000000001001234567890, '-1.00123456789E-21'),
(-0.000000000000000000001, '-1E-21'),
(-0.00000000000000000001001234567890, '-10.0123456789E-21'),
(-0.00000000000000000001, '-10E-21'),
(-0.0000000000000000001001234567890,... |
wikkiewikkie/flask-googlecharts | flask_googlecharts/utils.py | Python | mit | 1,703 | 0.002349 | import datetime
def prep_data(data):
# type: (dict) -> dict
"""Takes a dict intended to be converted to JSON for use with Google Charts and transforms date and datetime
into date string representations as described here:
https://developers.google.com/chart/interactive/docs/datesandtimes
TODO: I... | val['v'].month-1, # JS Dates are 0-based
val['v'].day,
val['v'].hour,
| val['v'].minute,
val['v'].second,
val['v'].microsecond)
elif isinstance(val['v'], datetime.date):
val['v'] = "Date({}, {}, {})".format(val['v'].year,
... |
ostree/plaso | tests/cli/tools.py | Python | apache-2.0 | 10,715 | 0.002708 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the CLI tools classes."""
import argparse
import io
import sys
import unittest
from plaso.cli import tools
from tests.cli import test_lib
class CLIToolTest(test_lib.CLIToolTestCase):
"""Tests for the CLI tool base class."""
_EXPECTED_BASIC_OPTIONS = u'\n'... | n', column_width=100)
string = output_writer.ReadOutput()
expected_string = (
b' '
b' Name : \n'
b' '
b' ... | ""Tests the PrintHeader function."""
output_writer = test_lib.TestOutputWriter()
cli_tool = tools.CLITool(output_writer=output_writer)
cli_tool.PrintHeader(u'Text')
string = output_writer.ReadOutput()
expected_string = (
b'\n'
b'************************************* '
b'Text... |
psci2195/espresso-ffans | testsuite/python/test_checkpoint.py | Python | gpl-3.0 | 14,929 | 0.000201 | # Copyright (C) 2010-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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 v... | te = lbf.get_params()
reference = {'agrid': 0.5, 'visc': 1.3, 'dens': 1.5, 'tau': 0.01}
for key in reference:
self.assertTrue(key in state)
self.assertAlmostEqual(reference[key], state[key], delta=1E-7)
@utx.skipIfMissingFeatures('ELECTROKINETICS') |
@ut.skipIf(not EK, "Skipping test due to missing mode.")
def test_EK(self):
ek = system.actors[0]
ek_species = ek.get_params()['species'][0]
cpt_path = self.checkpoint.checkpoint_dir + "/ek"
ek.load_checkpoint(cpt_path)
precision = 5
m = np.pi / 12
nx = i... |
editxt/editxt | resources/syntax/ruby.syntax.py | Python | gpl-3.0 | 6,546 | 0.005805 | # -*- coding: UTF-8 -*-
# Syntax definition automatically generated by hljs2xt.py
# source: ruby.js
name = 'Ruby'
file_patterns = ['*.ruby', '*.rb', '*.gemspec', '*.podspec', '*.thor', '*.irb']
keyword = """
and false then defined module in return redo if BEGIN retry end for
true self when next until do begin ... | ELIMITER
rules = [('keyword', keyword)]
class params1:
default_text_color = DELIMITER
rules = [('params', RE(r"\("), [RE(r"\)")], params)]
params1.__name__ = 'params'
class function:
default_text_color = DELIMITER
rules = [
('keyword', ['def']),
('title', title0),
comment0,... | arams1], function)
symbol = ('symbol', [RE(r"[a-zA-Z_]\w*(?:\!|\?)?:")])
class symbol0:
default_text_color = DELIMITER
rules = [
string1,
string2,
string3,
string4,
string5,
string6,
string7,
string8,
string9,
string10,
st... |
richard-schwab/annotatorjs-django | manage.py | Python | gpl-2.0 | 252 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "annotator.settings")
from django.c | ore.management import execute_from_command_line
exec | ute_from_command_line(sys.argv)
|
quodlibet/mutagen | mutagen/asf/__init__.py | Python | gpl-2.0 | 9,848 | 0.000102 | # Copyright (C) 2005-2006 Joe Wreschnig
# Copyright (C) 2006-2007 Lukas Lalinsky
#
# 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... | bitrate = 0
channels = 0
codec_type = u""
codec_name = u""
codec_description = u""
def __init__(self):
self.length = 0.0
self.sample_rate = 0
self.bitrate = 0
self.channels = 0
self.codec_type = u""
self.codec_name = u""
self.codec_descriptio... | """
s = u"ASF (%s) %d bps, %s Hz, %d channels, %.2f seconds" % (
self.codec_type or self.codec_name or u"???", self.bitrate,
self.sample_rate, self.channels, self.length)
return s
class ASFTags(list, DictMixin, Tags): # type: ignore
"""ASFTags()
Dictionary contain... |
dcramer/reraise | setup.py | Python | apache-2.0 | 912 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
tests_require = [
'pytest',
'unittest2',
]
setup(
name='reraise',
version='0.1.0',
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://gi | thub.com/dcramer/reraise',
description='Reraise exceptions, like a boss.',
long_description=__doc__,
package_dir={'': 'src'},
packages=find_packages('src'),
license='Apache 2.0',
zip_safe=False,
| extras_require={
'tests': tests_require,
},
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development',
'Programming Language ... |
XeryusTC/18xx-accountant | accountant/core/migrations/0006_auto_20161219_2038.py | Python | mit | 1,048 | 0.003817 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-19 20:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
| ('core', '0005_auto_20161219_1600'),
]
operations = [
mig | rations.CreateModel(
name='Share',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('shares', models.IntegerField(default=1)),
('company', models.ForeignKey(on_delete=django.db.models.dele... |
ahmedkareem999/MITx-6.00.1x | polySum.py | Python | mit | 1,018 | 0.01382 | '''
Week-2:Exercise-grader-polysum
A regular polygon has n number of sides. Each side has length s.
The area of a regular polygon is: (0.25∗n∗s^2)/tan(π/n)
The perimeter of a polygon is: length of the | boundary of the polygon
Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places.
'''
#code
import math
def polysum(n,s):
'''
Input: n - number of sides(should ... | float)
Output: Returns Sum of area and the square of the perimeter of the regular polygon(gives a float)
'''
#Code
def areaOfPolygon(n,s):
#Pi = 3.1428
area = (0.25 * n * s ** 2)/math.tan(math.pi/n)
return area
def perimeterOfPolygon(n,s):
perimeter = n * s
... |
dementrock/nbgrader | nbgrader/preprocessors/clearsolutions.py | Python | bsd-3-clause | 4,589 | 0.000436 | from traitlets import Unicode
from .. import utils
from . import NbGraderPreprocessor
class ClearSolutions(NbGraderPreprocessor):
code_stub = Unicode(
"# YOUR CODE HERE\nraise NotImplementedError()",
config=True,
help="The code snippet that will replace code solutions")
text_stub = ... | _region(cell)
# determine whether the cell is a solution/grade cell
is_solution = utils.is_solution(cell)
# check that it is marked as a solution cell if we replaced a solution
# region -- if it's not, then this is a problem, because the cell needs
# to be given an id
i... | "please make sure all solution regions are within "
"solution cells")
# replace solution cells with the code/text stub -- but not if
# we already replaced a solution region, because that means
# there are parts of the cells that should be preserved
if is_solut... |
forslund/mycroft-core | test/integrationtests/skills/skill_tester.py | Python | apache-2.0 | 24,044 | 0 | # Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | er.instance:
skill_loader.instance.log = LOG.create_logger(
skill_loader.instance.name)
log[path] = buf.getvalue()
return skill_list, log
def unload_skills(skills):
for s in skills:
s.default_shutdown()
class InterceptEmitter(object):
"""
This class inter... | g emitted communication is intercepted for analysis
"""
def __init__(self):
self.emitter = EventEmitter()
self.q = None
def on(self, event, f):
# run all events
print("Event: ", event)
self.emitter.on(event, f)
def emit(self, event, *args, **kwargs):
ev... |
tanwanirahul/django-batch-requests | tests/test_base.py | Python | mit | 2,053 | 0.001948 | '''
@author: Rahul Tanwani
@summary: Contains base test case for reusable test methods.
'''
import json
from django.test import TestCase
from batch_requests.settings import br_settings as settings
class TestBase(TestCase):
'''
Base class for all reusable test methods.
'''
def assert_reponse_co... | '''
Makes a batch request using django client.
'''
return self.client.post("/api/v1/batch/", json.dumps([self._batch_request(method, url, body, headers)]),
| content_type="application/json")
def make_multiple_batch_request(self, requests):
'''
Makes multiple batch request using django client.
'''
batch_requests = [self._batch_request(method, path, data, headers) for method, path, data, headers in requests]
return self.clie... |
grnet/snf-ganeti | lib/tools/common.py | Python | bsd-2-clause | 6,956 | 0.008482 | #
#
# Copyright (C) 2014 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | te(OpenSSL.crypto.FILETYPE_PEM, cert_pem)
except Exception, err:
raise error_fn("(stdin) Unable to load certificate: %s" % err)
try:
key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, cert_pem)
except OpenSSL.crypto.Error, err:
raise error_fn("(stdin) Unable to load private key: %s" % ... | ificate also given on stdin
try:
utils.X509CertKeyCheck(cert, key)
except OpenSSL.SSL.Error:
raise error_fn("(stdin) Certificate is not signed with given key")
# Standard checks, including check against an existing local certificate
# (no-op if that doesn't exist)
_check_fn(cert)
key_encoded = Ope... |
algerbrex/Schemey | src/compiler.py | Python | unlicense | 9,756 | 0.000615 | """
compiler.py
----------------------------------------
This module contains the implementation of the
Scheme com | piler for Schemey. It takes in one
or more expressions(a list of Pair objects), and generates
a code object ready for serialization and/or direct
execution by the virtual machine.
"""
from .bytecode import *
from .expressions import *
from .utils import flatten, find_ | or_append
from ._parser import Parser
DEBUG = False
class Label:
"""
Implements a class to hold the position
of an undefined jump target in the bytecode.
"""
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Label(name={})'.format(self.name)
def _assem... |
open2c/bioframe | tests/test_core_stringops.py | Python | mit | 2,559 | 0.001172 | import pandas as pd
import numpy as np
import pytest
from bioframe.core import stringops
from bioframe.core.stringops import parse_region
def test_to_ucsc_string():
assert stringops.to_ucsc_string(("chr21", 1, 4)) == "chr21:1-4"
def test_parse_region():
# UCSC-style names
assert parse_region("chr21") =... | ",
1000,
2000,
)
# Punctuation in names (aside from :)
assert parse_region("name-with-hyphens-") == ("name-with-hyphens-", 0, None)
assert parse_region("GL000207.1") == ("GL000207.1", 0, None)
assert parse_region("GL000207.1:1000-2000") = | = ("GL000207.1", 1000, 2000)
# Trailing dash
assert parse_region("chr21:1000-") == ("chr21", 1000, None)
# Humanized units
assert parse_region("6:1kb-2kb") == ("6", 1000, 2000)
assert parse_region("6:1k-2000") == ("6", 1000, 2000)
assert parse_region("6:1kb-2M") == ("6", 1000, 2000000)
ass... |
franck-talbart/codelet_tuning_infrastructure | ctr-common/plugins/8b9f58b8-9d01-4af4-8884-42443337da67/util.py | Python | gpl-3.0 | 8,819 | 0.010319 | #************************************************************************
# Codelet Tuning Infrastructure
# Copyright (C) 2010-2015 Intel Corporation, CEA, GENCI, and UVSQ
#
# 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
# th... | the repository entry
(ret_code, json_ret) = cti_rm_entry(repository_uid, True, format, remove_dependencies)
if ret_code != 0:
if format == 'json':
json_result['output'].append(json_ret)
json_result['output'].append("Cannot remove the repository entry.")
... | he repository entry."
if path_ctr:
# Remove from the global index file
ctr.ctr_plugin_global_index_file_rm(path_ctr)
if not os.path.isdir(path_ctr):
if format == 'json':
json_result['output'].append("Local repository not found on your... |
martysyuk/PY-3-Learning | homeworks/lesson2-2.py | Python | mit | 1,637 | 0.001332 | # -*- coding: UTF-8 -*-
"""
Домашнее задание по уроку 2-2
«Работа с разными форматами данных»
Выполнил Мартысюк Илья PY-3
"""
import re
import glob
import chardet
from os.path import join
from xml.etree.cElementTree import XMLParser, parse
def open_data_file(path):
with open(path, 'rb') as encoding_detect_file:
... | long_dict[t] += 1
except KeyError:
long_dict.update({t: 1})
long_dict = sorted(long_dict.items(), key=lambda x: x[1], reverse=True)
print(long_dict)
return long_dict
def print_result(long_dict):
print('ТОП 10 самых часто встречающихся слов:')
for i in ... |
files = glob.glob(join(path, '*.xml'))
for file in files:
print('\nОбработка файла {}'.format(file))
print_result(compile_data(open_data_file(file)))
|
paulsmith/geodjango | django/newforms/extras/widgets.py | Python | bsd-3-clause | 2,692 | 0.0026 | """
Extra HTML Widget classes
"""
import datetime
import re
from django.newforms.widgets import Widget, Select
from django.utils.dates import MONTHS
from django.utils.safestring import mark_safe
__all__ = ('SelectDateWidget',)
RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')
class SelectDateWidget(Widget):
""... | es.sort()
local_attrs = self.build_attrs(id=self.month_field % id_)
select_html = Select(choices=month_choices).render(self.month_field % name, month_val, local_attrs)
output.append(select_html)
day_choices = [(i, i) for i in range(1, 32)]
local_attrs['id'] = self.day_field % id... | ars]
local_attrs['id'] = self.year_field % id_
select_html = Select(choices=year_choices).render(self.year_field % name, year_val, local_attrs)
output.append(select_html)
return mark_safe(u'\n'.join(output))
def id_for_label(self, id_):
return '%s_month' % id_
id_for_la... |
nyghtowl/mixed-tape | alpha-track/keras_cifar10.py | Python | apache-2.0 | 6,031 | 0.00199 | # Original code at https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py
# Original license at https://github.com/fchollet/keras/blob/master/LICENSE
#
# All revisions and additions:
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# ... | keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Act | ivation, Flatten
from keras.layers import Conv2D, MaxPooling2D
import os
import pickle
from IPython.utils.path import ensure_dir_exists
import numpy as np
batch_size = 32
num_classes = 10
epochs = 200
workers = 8
num_pred_print = 20
data_augmentation = True
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_na... |
mheinl/OnionCrawler | OnionCrawler/middlewares.py | Python | mit | 1,886 | 0 | # -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class OnionCrawlerSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scr... | esponse, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(response, exception, spider):
#... | es an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
... |
scality/manila | manila_tempest_tests/tests/api/admin/test_export_locations.py | Python | apache-2.0 | 5,994 | 0 | # Copyright 2015 Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
@test.attr(type=["gate", ])
def test_share_contains_all_export_locations_of_all_share_instances(self):
share_export_locations = self.admin_client.list_share_export_locations(
self.share['id'])
share_instances_export_locations = [ | ]
for share_instance in self.share_instances:
share_instance_export_locations = (
self.admin_client.list_share_instance_export_locations(
share_instance['id']))
share_instances_export_locations.extend(
share_instance_export_locations)
... |
alex/django-fixture-generator | fixture_generator/tests/tests.py | Python | bsd-3-clause | 3,734 | 0.004017 | import sys
from StringIO import StringIO
import django
from django.core.management import call_command
from django.test import TestCase
from fixture_generator import fixture_generator
from fixture_generator.management.commands.generate_fixture import (
linearize_requirements, CircularDependencyError)
@fixture_g... | alse, **kwargs):
stdout = StringIO()
stderr = StringIO()
run = lambda: call_command("generate_fixture", fixture, stdout=stdout, stderr=stderr, **kwargs)
|
if error:
# CommandError gets turned into SystemExit
self.assertRaises(SystemExit, run)
else:
run()
return stdout.getvalue(), stderr.getvalue()
def test_basic(self):
output, _ = self.generate_fixture("tests.test_1")
self.assertEqual(outpu... |
GoogleCloudPlatform/cloud-alerting-notification-forwarding | notification_integration/utilities/pubsub.py | Python | apache-2.0 | 2,130 | 0.002817 | # Copyright 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
#
# http://www.apache.org/licenses/LI | CENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limi | tations under the License.
"""Module to extract notification data for a generic Pubsub message."""
import base64
import binascii
import json
from typing import Any, Dict, Text
class Error(Exception):
"""Base class for all errors raised in this module."""
class DataParseError(Error):
"""Raised when the enco... |
petertodd/tuke | Tuke/tests/context/_context/_cfunction.py | Python | gpl-3.0 | 595 | 0.001681 | # vim: tabstop=4 expandtab shiftwidth=4 fileencoding=utf8
# (c) 2008 Peter Todd <pete@petertodd.org>
#
# This program is made available under the GNU GPL version 3.0 or
# greater. See the accompanying file COPYING for details.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of ... | "
from Tuke.context._context._cfun | ction import test
self.assert_(test())
|
WaveBlocks/WaveBlocksND | examples/henon_heiles/eigenstates[eps=0.25].py | Python | bsd-3-clause | 830 | 0.00241 | dimension = 2
ncomponents = 1
potential = "henon_heiles"
eigenstate_of_level = 0
eigenstates_indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
starting_point = [0.5, 0.5]
eps = 0.25
hawp_template = {
"type": "HagedornWavepacket",
"dimension": dimension,
"ncomponents": 1,
"eps": eps,
... | ': 'TensorProductQR',
'dimension': dimension,
'qr_rules': [{'dimension': 1, 'order': 32, 'type': 'GaussHermiteQR'},
{'dimension': 1, 'order': 32, 'type': 'GaussHermiteQR'}]
| }
}
}
|
bbarrows89/CSC110_Projects | click.py | Python | mit | 240 | 0.016667 | # Br | yan Barrows
# CSC 110 - Winter 17
# click.py
from graphics import *
def main():
win = GraphWin("Click Me!")
for i in range(5):
p = win.getMouse()
print("You clicked at: (", p.getX(), ",",p.getY(), | ")")
main()
|
obi-two/Rebelion | data/scripts/templates/object/tangible/terminal/shared_terminal_hq_imperial.py | Python | mit | 467 | 0.044968 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
res | ult = Tangible()
result.template = "object/tangible/terminal/shared_terminal_hq_imperial.iff"
result.attribute_template_id = -1
result.stfName("terminal_name","terminal_hq_imperial")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return | result |
hirefrank/bowery-sms | app.py | Python | gpl-2.0 | 240 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from sms.app | import app
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
| if port == 5000:
app.debug = True
app.run(host='0.0.0.0', port=port)
|
smartmob-project/gitmesh-deploy | tests/conftest.py | Python | mit | 4,407 | 0 | # -*- coding: utf-8 -*-
import aiohttp.web
import os
import pytest
import testfixtures
from contextlib import contextmanager
from subprocess import check_output
@pytest.yield_fixture
def http_client(event_loop):
with aiohttp.ClientSession() as session:
yield session
@pytest.yield_fixture
def storage(... | request.scheme,
request.host,
request.app.router['pending'].url(),
),
}, headers={
'x-request-id': request.headers.get('x-request-id', '?'),
})
async def deploy(request):
requests.append(await request.json())
return a... | eb.Response(status=201, headers={
'x-request-id': request.headers.get('x-request-id', '?'),
})
async def pending(request):
return aiohttp.web.json_response({
'pending': requests,
}, headers={
'x-request-id': request.headers.get('x-request-id', '?'),
... |
hawkerpl/k2 | djangobb_forum/migrations/0003_djangobb_datamigration_0.py | Python | gpl-2.0 | 14,128 | 0.007928 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for profile in orm.Profile.objects.all():
profile.show_smilies = True
profile.save()
def backward... | .fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_p | ermissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': ... |
marlengit/BitcoinUnlimited | qa/rpc-tests/test_framework/test_framework.py | Python | mit | 9,681 | 0.003409 | #!/usr/bin/env python3
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Copyright (c) 2015-2016 The Bitcoin Unlimited developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Base class for RPC testing
# Add python-bit... | om.seed(self.randomseed)
print("Random seed: %s" % self.randomseed)
if self.options.trace_rpc:
import logging
logging.basicConfig(level=logging.DEBUG)
if self.options.coveragedir:
enable_coverage(self.options.coveragedir)
os.environ['PATH'] = self.o... | on_precision()
success = False
try:
if not os.path.isdir(self.options.tmpdir):
os.makedirs(self.options.tmpdir)
# Not pretty but, I changed the function signature
# of setup_chain to allow customization of the setup.
# However derived obj... |
mshameers/me | db_create.py | Python | gpl-2.0 | 529 | 0.00189 | #!/home/mshameers/Templates/py2.7_flask.9/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
fro | m app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHE | MY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
|
kchawla-pi/united-states-of-browsers | tests/tests/test_db_search.py | Python | gpl-3.0 | 3,037 | 0 | import pytest
from united_states_of_browsers.db_merge.db_search import (
check_fts5_installed,
search,
)
pytestmark = pytest.mark.skipif(
not check_fts5_installed(),
reason="FTS5 not available. Search disabled",
)
def test_search_with_keywords_and_dates(searchable_db_path):
actual_search_result... | rch_results_rec_ids = [*range(10, 20), *range(29, 39)]
actual_search_results_rec_ids = sorted(
[
row["rec_id"]
for row in search(
searchable_db_path,
)
] |
)
assert expected_search_results_rec_ids == actual_search_results_rec_ids
def test_search_date_start(searchable_db_path):
expected_search_results_rec_ids = []
actual_search_results_rec_ids = sorted(
[
row["rec_id"]
for row in search(
searchable_db_path,... |
google-research/fixmatch | imagenet/augment/rand_augment.py | Python | apache-2.0 | 5,934 | 0.007078 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | self._apply_one_layer(aug_image)
output_dict[aug_image_key] = a | ug_image
if aug_image_key != 'image':
output_dict['image'] = image
return output_dict
|
yotchang4s/cafebabepy | src/main/python/test/test_importlib/import_/test___package__.py | Python | bsd-3-clause | 5,630 | 0.00071 | """PEP 366 ("Main module explicit relative imports") specifies the
semantics for the __package__ attribute on modules. This attribute is
used, when available, to detect which package a module belongs to (instead
of using the typical __path__/__name__ test).
"""
import unittest
import warnings
from .. import util
cla... | _):
with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
| with util.import_state(meta_path=[importer]):
self.__import__('pkg.fake')
module = self.__import__('',
globals=globals_,
fromlist=['attr'], level=2)
return module
def test_using___pa... |
apache/bloodhound | bloodhound_multiproduct/tests/__init__.py | Python | apache-2.0 | 4,522 | 0.000442 | # -*- coding: utf-8 -*-
#
# 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 (... | /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 language governing permissions and limit... | deque
from fnmatch import fnmatch
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from pkg_resources import resource_exists, resource_filename, \
resource_isdir, resource_listdir
class TestLoader(unittest.TestLoader):
testLoaderAttribute = '__te... |
persandstrom/home-assistant | homeassistant/components/light/tuya.py | Python | apache-2.0 | 3,246 | 0 | """
Support for the Tuya light.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.tuya/
"""
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ENTITY_ID_FORMAT,
SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP,... | onfig, add_entities, discovery_info=None):
"""Set up Tuya light platform."""
if discovery_info is None:
return
| tuya = hass.data[DATA_TUYA]
dev_ids = discovery_info.get('dev_ids')
devices = []
for dev_id in dev_ids:
device = tuya.get_device_by_id(dev_id)
if device is None:
continue
devices.append(TuyaLight(device))
add_entities(devices)
class TuyaLight(TuyaDevice, Light):
... |
bpurgaso/hydra-ircbot | hydra/Hydra.py | Python | apache-2.0 | 9,993 | 0.003603 | '''
Created on Feb 3, 2013
@author: bpurgaso
'''
from twisted.words.protocols import irc
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet import threads
from ConfigManager import ConfigManager
from Authenticator import Authenticator
from subprocess import PIPE, STDOUT, ... | s, your power level'\
' is'\
' insufficient.' % user]))
except:
self.postToIRC((channel, ['Check your formatting and'\
| ' try again.']))
else:
self.msg(channel, "You aren't authorized for register.")
#WHOAMI
elif command == 'whoami':
if self.auth.isUserAuthorized('whoami', user):
self.postToIRC((channel, [self.auth.whoami(user)]))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.