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 |
|---|---|---|---|---|---|---|---|---|
Raul3212/TopicosAvancadosBD | dev/model/Vertice.py | Python | gpl-3.0 | 198 | 0.005051 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Vertice:
def __init__(self, id, latitude, longitude):
self.id = i | d
self.latitude = latitude
| self.longitude = longitude |
PhoenixWright/MobileBDDCore | mobilebdd/drivers/drivers.py | Python | apache-2.0 | 3,463 | 0.002599 | import logging
from mobilebdd.drivers.android import AndroidWebDriver, SelendroidWebDriver
from mobilebdd.drivers.desktop import DesktopChromeWebDriver, DesktopInternetExplorerWebDriver, DesktopFirefoxWebDriver
from mobilebdd.drivers.ios import iOSWebDriver
from mobilebdd.drivers.mobileweb import ChromeWebDriver, WebV... | webviews. prob
# a bug but i dont want to deal with it right now.
u'4.2',
u'4.3',
u'4.4',
]
def webdriver_me(os_ver, os_type, app_path=u'', device_type=u''):
"""
returns a ref to the class that matches for the given os and device type
:param os_ver: version of the os
:param os_type: d... | the path to the application to be installed, or a browser name
:param device_type: the type of device ('phone' or 'tablet')
"""
# ensure these aren't none so we can work with them as strings
if not os_ver:
os_ver = u''
if not os_type:
os_type = u''
if not app_path:
app_p... |
erinspace/osf.io | website/archiver/utils.py | Python | apache-2.0 | 10,456 | 0.002965 | import functools
from framework.auth import Auth
from website.archiver import (
StatResult, AggregateStatResult,
ARCHIVER_NETWORK_ERROR,
ARCHIVER_SIZE_EXCEEDED,
ARCHIVER_FILE_NOT_FOUND,
ARCHIVER_FORCED_FAILURE,
)
from website import (
mails,
settings
)
from osf.utils.sanitize import unesc... | ail_registration
pass
else: # reason == ARCHIVER_UNCAUGHT_ERROR
send_archiver_uncaught_error_mails(src, user, result, url)
dst.root.sanction.forcibly_reject()
dst.root.sanction.save()
dst.root.delete_registration_tree(save=True)
def archive_p | rovider_for(node, user):
"""A generic function to get the archive provider for some node, user pair.
:param node: target node
:param user: target user (currently unused, but left in for future-proofing
the code for use with archive providers other than OSF Storage)
"""
return node.get_addon(set... |
pythonbyexample/PBE | dbe/businesstest/urls.py | Python | bsd-3-clause | 619 | 0.006462 | from django.conf.urls import * |
from django.contrib.auth import views as auth_views
from businesstest.views import Messages
urlpatterns = patterns("businesstest.views",
# (r"messages/$", "message_list"),
(r"messages/$", Messages.as_view(), {}, "messages"),
(r"(\d+)/$", "test"),
(r"test_done/$", "test_done"),
# (r"^melting-temp-r... | "search", {}, "parse9_search"),
(r"^$", redirect_to, {"url": "/bt/1/"}),
)
urlpatterns += patterns('',
(r"^account/", include("registration.urls")),
)
|
junaruga/rpm-py-installer | tests/test_install_suse.py | Python | mit | 1,463 | 0 | """
Tests for install.py for SUSE based Linux distributions
"""
import os
import shutil
from unittest import mock
import pytest
from install import Cmd, CmdError, RemoteFileNotFoundError
pytestmark = pytest.mark.skipif(
not pytest.helpers.helper_is_suse(),
reason="Tests for openSUSE/SUSE"
)
def test_rpm_do... | rt mock_sh_e.called
assert str(exc.value) == 'Package dummy not found on remote'
def test_rpm_extract_is_ok(sys_rpm, rpm_files, monkeypatch):
# mo | cking arch object for multi arch test cases.
sys_rpm.arch = 'x86_64'
with pytest.helpers.work_dir():
for rpm_file in rpm_files:
shutil.copy(rpm_file, '.')
sys_rpm.extract('rpm-build-libs')
files = os.listdir('./usr/lib64')
files.sort()
assert files == [
... |
hoytnix/hoyt.io | flask-server/hoyt/migrations/versions/d987888a7460_tags_table.py | Python | gpl-3.0 | 1,553 | 0.003863 | """'d987888a7460' - Tags table."""
import sqlalchemy as sa
from alembic import op
#from lib.util_datetime import tzware_datetime
#from lib.util_sqlalchemy import AwareDateTime
"""
Tags table
Revision ID: d987888a7460
Revises: 216ce379d3f0
Create Date: 2016-11-01 14:13:28.216736
"""
# Revision identifiers, used by ... | , nullable=False),
sa.PrimaryKeyConstraint('id'))
op.add_column('tags', sa.Column('tag_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'tags', 'tag', ['tag_id'], ['id'])
op.drop_column('tags', 'title')
op.drop_column('tags', 'id')
### end Alembic commands ###
def downgrade()... | p.add_column('tags', sa.Column('id', sa.INTEGER(), nullable=False))
op.add_column(
'tags',
sa.Column(
'title',
sa.VARCHAR(length=128),
autoincrement=False,
nullable=False))
op.drop_constraint(None, 'tags', type_='foreignkey')
op.drop_column('ta... |
davy39/eric | Preferences/ConfigurationPages/EditorCalltipsPage.py | Python | gpl-3.0 | 2,886 | 0.003465 | # -*- coding: utf-8 -*-
# Copyright (c) 2006 - 2014 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the Editor Calltips configuration page.
"""
from __future__ import unicode_literals
from PyQt5.Qsci import QsciScintilla
from QScintilla.QsciScintillaCompat import QSCINTILLA_VERSION
from .Con... | Preferences.getEditor("CallTipsPosition"))) |
def save(self):
"""
Public slot to save the EditorCalltips configuration.
"""
Preferences.setEditor(
"CallTipsEnabled",
self.ctEnabledCheckBox.isChecked())
Preferences.setEditor(
"CallTipsVisible",
self.ctVisi... |
aragos/tichu-tournament | api/src/movement_handler.py | Python | mit | 5,763 | 0.011279 | import webapp2
import json
from collections import defaultdict
from generic_handler import GenericHandler
from google.appengine.api import users
from google.appengine.ext import ndb
from handler_utils import is_int
from handler_utils import GetPairIdFromRequest
from handler_utils import GetTourneyWithIdAndMaybeReturnS... | nd.opponent, pair_no))
for round in movement:
hands = round.hands
round_str = round.to_dict()
opp = round.opponent
if opp:
opp_pp = players_futures_dict[rou | nd.round].get_result()
if opp_pp:
round_str["opponent_names"] = [x.get("name") for x in
opp_pp.player_list()]
if hands:
del round_str['hands']
for i in xrange(len(hands)):
hand_score = hand_futures_dict[round.round][i].get_result()
if hand_score and no... |
crazyskady/ai-game-python | Chapter08/CMapper.py | Python | mit | 1,821 | 0.031851 | # -*- coding: utf-8 -*-
dCellSize = 20
WindowWidth = 400
WindowHeight = 400
class SCell(object):
def __init__(self, xmin, xmax, ymin, ymax):
self._iTicksSpentHere = 0
self._left = xmin
self._right = xmax
self._top = ymin
self.bottom = ymax
def Update(self):
self._iTicksSpentHere... | lf._iTicksSpentHere = 0
class CMapper(object):
def __init__(self, MaxRangeX, MaxRangeY):
self._dCellSize = dCellSize
self._NumCellsX = (MaxRangeX/self._dCellSize) + 1
self._NumCellsY = | (MaxRangeY/self._dCellSize) + 1
self._2DvecCells = []
for x in xrange(self._NumCellsX):
temp = []
for y in xrange(self._NumCellsY):
temp.append(SCell(x*self._dCellSize, (x+1)*self._dCellSize, y*self._dCellSize, (y+1)*self._dCellSize))
self._2DvecCells.append(temp)
self._iTotalCells = self._NumCell... |
dmpetrov/dataversioncontrol | tests/remotes/s3.py | Python | apache-2.0 | 4,225 | 0 | import locale
import os
import uuid
import pytest
from funcy import cached_property
from dvc.utils import env2bool
from .base import Base
from .path_info import CloudURLInfo
TEST_AWS_REPO_BUCKET = os.environ.get("DVC_TEST_AWS_REPO_BUCKET", "dvc-temp")
TEST_AWS_ENDPOINT_URL = "http://127.0.0.1:{port}/"
class S3(Ba... | rkspace._s3.create_bucket(Bucket=TEST_AWS_REPO_BUCKET)
yield workspace
@pytest.fixture
def real_s3():
if not S3.should_test():
pytest.skip("no real s3")
| yield S3(S3.get_url())
|
BrainTech/openbci | obci/logic/logic_speller_peer.py | Python | gpl-3.0 | 1,099 | 0.002732 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:
# Mateusz Kruszyński <mateusz.kruszynski@gmail.com>
#
import time
from obci.utils import tags_helper
from multiplexer.multiplexer_constants import peers, types
from obci.logic import logic_helper
from obci.logic.logic_decision_peer import LogicDecision
from ob... | context = ctx.get_new_context()
context['logger'] = self.logger
SpellerEngine.__init__(self, self.config.p | aram_values(), context)
self.ready()
self._update_letters()
def _run_post_actions(self, p_decision):
self._update_letters()
if __name__ == "__main__":
LogicSpeller(settings.MULTIPLEXER_ADDRESSES).loop()
|
cmoutard/mne-python | mne/viz/misc.py | Python | bsd-3-clause | 19,712 | 0 | """Functions to make simple plots with M/EEG data
"""
from __future__ import print_function
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com... | + 1)
plt.imshow(C[idx][:, idx], interpolation="nearest", cmap='RdBu_r')
plt.title(name)
plt.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.2, 0.26)
tight_layout(fig=fig_cov)
fig_svd = None
if show_svd:
fig_svd = plt.figure()
for k, (idx, name, unit, scaling) in enumerate(idx_n... | t.subplot(1, len(idx_names), k + 1)
plt.ylabel('Noise std (%s)' % unit)
plt.xlabel('Eigenvalue index')
plt.semilogy(np.sqrt(s) * scaling)
plt.title(name)
tight_layout(fig=fig_svd)
plt_show(show)
return fig_cov, fig_svd
def plot_source_spectrogram(st... |
dset0x/invenio-checker | invenio_checker/workflows/base_bundle.py | Python | gpl-2.0 | 847 | 0.001181 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; ei | ther version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You s... | 9 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
class base_bundle(object):
workflow = []
__all__ = ('base_bundle', )
|
mugurbil/gnm | examples/exp_time_series/acor_sample.py | Python | mit | 2,362 | 0.023709 | # -*- coding: utf-8 -*-
import numpy as np
from numpy import linalg as la
from math import exp,pi
import time
from optparse import OptionParser
import json
import os
import gnm
'''
Calculating the auto-corrolation time which is an ill-posed problem.
Generating the theoretical (quadrature) curve for the auto-corrolati... | tionParser()
# experiment number
parser.add_option('-c', dest='count', type='int',
default=0, help='count of experiment')
# seeding
parser.add_option('-s', dest='seed', type='int',
default=5, help='random number generator seed')
# for the sampler
parser.add_option('-n', dest='num_samples', type='int',
def... | 0000, help='number of samples')
parser.add_option('-b', dest='num_burn', type='int',
default=1000, help='number of samples burned')
parser.add_option('-m', dest='max_steps', type='int',
default=4, help='max back off steps')
parser.add_option('-z', dest='step_size', type='float',
default=0.1, help='ste... |
samui13/Gnuplot3D | script/split3D.py | Python | mit | 1,765 | 0.015864 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last-Updated : <2013/08/18 22:47:11 by samui>
import sys,os
def mkdir(folder):
if not os.path.isdir(folder):
os.system("mkdir {0}".format(folder))
if __name__ == "__main__":
data_file = os.path.abspath(sys.argv[1])
root,ext = os.path.splitext(os.p... | t.txt")
mkdir(data_folder)
mkdir(png_folder)
| mkdir(sdata_folder)
#Split Phase
Nx = 50
Ny = 50
Nz = 50
data = open(data_file,"r")
data_list = []
for k in range(Nz+1):
out_data = os.path.join(sdata_folder,"data{0}.txt".format(k))
data_list.append(out_data)
out_file = open(out_data,"w");
for j in range(... |
LLNL/spack | var/spack/repos/builtin/packages/gengeo/package.py | Python | lgpl-2.1 | 1,514 | 0.001982 | # 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 Gengeo(AutotoolsPackage):
"""GenGeo is a library of tools for creating complex particle
... | s the in-simulation geometry creation utilities
provided by ESyS-Particle itself."""
homepage = "https://launchpad.net/esys-particle/gengeo"
url = "https://launchpad.net/esys-particle/trunk/3.0-alpha/+download/gengeo-163.tar.gz"
maintainers = ['dorton21']
version('163', sha256='9c896d430d8f3... | ')
depends_on('libtool', type='build')
depends_on('m4', type='build')
depends_on('boost+python')
depends_on('openmpi')
def autoreconf(self, spec, prefix):
autogen = Executable('./autogen.sh')
autogen()
def configure_args(self):
args = [
'--verbose',
... |
mmoran0032/NMRpy | data/AWTconvertTable.py | Python | mit | 1,558 | 0 | #!/usr/bin/env python
# convertAWT.py - Mass Table Conversion Utility
import os
massFile = 'AWTMass-2003.dat'
newFile = os.path.join('..', 'nmrfreq', 'masstable.py')
def main():
with open(massFile, 'r') as file:
massDict = extractMasses(file)
writeToFile(newFile, massDict, massFile)
def extractMa... | at(mass) / 1000000.0
return mass
def writeToFile(filename, massdict, massFile):
wi | th open(filename, 'w') as f:
f.write('# Mass table for use in nmrfreq from {0}\n'.format(massFile))
f.write('table = {\n')
f.write(createIsotopesString(massdict))
f.write('}\n')
def createIsotopesString(massdict):
string = ''
for key in sorted(massdict.iterkeys()):
stri... |
bogdal/freepacktbook | freepacktbook/slack.py | Python | mit | 1,181 | 0.000847 | import json
import requests
class SlackNotification(object):
icon_url = "https://githu | b-bogdal.s3.amazonaws.com/freepacktbook/icon.png"
def __init__(self, slack_url, channel):
self.slack_url = slack_url
self.channel = channel
if not self.channel.startswith("#"):
self.channel = "#%s" % (sel | f.channel,)
def notify(self, data):
if not all([self.slack_url, self.channel]):
return
payload = {
"channel": self.channel,
"username": "PacktPub Free Learning",
"icon_url": self.icon_url,
"attachments": [
{
... |
MobProgramming/MobTimer.Python | tests/Infrastructure/TipsManager/test_TipsManager.py | Python | mit | 1,455 | 0.002062 | import unittest
import sys
import os |
from Infrastructure.FileUtilities import FileUtilities
from Infrastructure.TipsManager import TipsManager
class TestsTipsManage(unittest.TestCase):
@clas | smethod
def setUpClass(cls):
cls.fileUtilities = FileUtilities()
def test_random_tip_from_file(self):
seed = 0
dirname = os.path.dirname(__file__)
path = self.fileUtilities.go_up_dirs(dirname, 2) + "\\Tips"
tips_manager = TipsManager(seed, path)
result = tips_ma... |
sangwook236/SWDT | sw_dev/python/ext/test/graph/networkx/networkx_basic.py | Python | gpl-3.0 | 9,760 | 0.029816 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import networkx as nx
# REF [site] >> https://networkx.github.io/documentation/latest/tutorial.html
def basic_operation_tutorial():
# Create a graph.
G = nx.Graph()
# Nodes.
G.add_node(1)
G.add_nodes_from([2, 3])
H = nx.path_graph(10) # Creates a graph.
G.add_no... | aph(100, 5)
red = nx.random_lobster(100, 0.9, 0.9)
#--------------------
# Read a graph stored in a file using co | mmon graph formats, such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others.
nx.write_gml(red, './test.gml')
mygraph = nx.read_gml('./test.gml')
# REF [site] >> https://networkx.github.io/documentation/latest/tutorial.html
def drawing_tutorial():
import matplotlib.pyplot as plt
G = nx.petersen... |
escsun/radio-shop | accounts/admin.py | Python | gpl-3.0 | 722 | 0.001408 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.admin import Group as AuthGroup
from .models import User
class Group(AuthGroup):
class Meta:
proxy = True
app_label = "accounts"
verbose_name_plural = "Группы"
verb... |
admin.site.unregister(AuthGroup)
admin.site.register(User, MyUserAdmin)
admin.site. | register(Group, GroupAdmin)
|
solvery/lang-features | python/use_lib/asyncio_1.py | Python | gpl-2.0 | 314 | 0.010067 | #e | ncoding=utf-8
# python3
import asyncio
@asyncio.coroutine
def hello():
print("Hello world!")
# 异步调用asyncio.sleep(1):
r = yield from asyncio.sleep(1)
print("Hello again!")
# 获取EventLoop:
lo | op = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()
|
pydcs/dcs | dcs/weapons_data.py | Python | lgpl-3.0 | 212,933 | 0.006115 | # This file is generated from pydcs_export.lua
class Weapons:
AB_250_2___144_x_SD_2__250kg_CBU_with_HE_submunitions = {"clsid": "{AB_250_2_SD_2}", "name": "AB 250-2 - 144 x SD-2, 250kg CBU with HE submunitions", "weight": 280}
AB_250_2___17_x_SD_10A__250kg_CBU_with_10kg_Frag_HE_submunitions = {"clsid": "{AB_2... | s_Fuel_Tank_ = {"clsid": "{AV8BNA_AERO1D}", "name": "AERO 1D 300 Gallons Fuel Tank ", "weight": 1002.439}
AERO_1D_300_Gallons_Fuel_Tank__Empty_ = {"clsid": "{AV8BNA_AERO1D_EMPTY}", "name": "AERO 1D 300 Gallons Fuel Tank (Empty)", "weight": 93.89362}
AGM114x2_OH_58 = {"clsid": "AGM114x2_OH_58", "name": "AGM-114K... | M_114K = {"clsid": "{ee368869-c35a-486a-afe7-284beb7c5d52}", "name": "AGM-114K", "weight": 65}
AGM_114K___4 = {"clsid": "{88D18A5E-99C8-4B04-B40B-1C02F2018B6E}", "name": "AGM-114K * 4", "weight": 250}
AGM_119B_Penguin_ASM = {"clsid": "{7B8DCEB4-820B-4015-9B48-1028A4195692}", "name": "AGM-119B Penguin ASM", "wei... |
DragonRoman/rhevm-utils | 3.0/hooks/directlun/before_vm_migrate_destination.py | Python | gpl-3.0 | 3,145 | 0.00318 | #!/usr/bin/python
import os
import sys
import grp
import pwd
import traceback
import utils
import hooking
DEV_MAPPER_PATH = "/dev/mapper"
DEV_DIRECTLUN_PATH = '/dev/directlun'
def createdirectory(dirpath):
# we don't use os.mkdir/chown because we need sudo
command = ['/bin/mkdir', '-p', dirpath]
retcod... | s\n' % (devpath, err))
sys.exit(2)
stat = os.stat(srcpath)
major = os.major(stat.st_rdev)
minor = os.minor(stat.st_rdev)
command = ['/bin/mknod', devpath, 'b', str(major), str(minor)]
retcode, out, err = utils.execCmd(command, sudo=True, raw=True)
if retco | de != 0:
sys.stderr.write('directlun: error mknod %s, err = %s\n' % (devpath, err))
sys.exit(2)
mode = '660'
command = ['/bin/chmod', mode, devpath]
retcode, out, err = utils.execCmd(command, sudo=True, raw=True)
if retcode != 0:
sys.stderr.write('directlun: error chmod %s to %s... |
Petr-By/qtpyvis | qtgui/widgets/training.py | Python | mit | 6,290 | 0.00159 | import numpy as np
from PyQt5.QtWidgets import (QWidget, QProgressBar, QLabel, QCheckBox,
QPushButton, QSpinBox, QVBoxLayout, QFormLayout)
from .matplotlib import QMatplotlib
from qtgui.utils import QObserver
from tools.train import Training, TrainingController
from dltb.network import Ne... | size_range)
self._spinboxBatchSize.setValue(self._training.batch_size)
if self._training.loss is not None:
self._labelLoss.setText(str(self._training.loss))
self._trainingLoss[self._rangeIndex] = self._training.loss
if self._checkboxPlot.checkSt | ate():
self._plotLoss.plot(self._range, self._trainingLoss)
# self._plotLoss.plot(self._validationLoss)
if self._training.accuracy is not None:
self._labelAccuracy.setText(str(self._training.accuracy))
self._rangeIndex = (self._rangeIndex + 1) % len(self._range)... |
dkliban/pulp_ostree | common/setup.py | Python | gpl-2.0 | 321 | 0 | from setuptools import setup, find_packages
setup(
name | ='pulp_ostree_common',
version='1.0.0a1',
packages=find_packages(),
url='http://www.pulpproject.org',
license='GPLv2+',
author='Pulp Team',
author_email=' | pulp-list@redhat.com',
description='common code for pulp\'s ostree support',
)
|
skion/junkdns | src/resolvers/publicsuffix.py | Python | mit | 5,429 | 0.004421 | # -:- coding: utf-8 -:-#
"""
A resolver to query top-level domains via publicsuffix.org.
"""
from __future__ import absolute_import
NAME = "publicsuffix"
HELP = "a resolver to query top-level domains via publicsuffix.org"
DESC = """
This resolver returns a PTR record pointing to the top-level domain of the
hostname i... | # answer section
rdata = suffix
# https://github.com/rthalley/dnspython/issues/44
try:
# dnspython3
rrset = dns | .rrset.from_text(query.name, TTL,
dns.rdataclass.IN, dns.rdatatype.PTR,
rdata)
except AttributeError:
# dnspython2
rrset = dns.rrset.from_text(query.name, TTL,
dns.rdataclass.IN, dns.rdatatype.PTR,
... |
greglandrum/rdkit | rdkit/Chem/Fingerprints/UnitTestFingerprints.py | Python | bsd-3-clause | 2,918 | 0.011309 | #
# Copyright (C) 2003-2006 Greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
"""unit testing code for fin... | _ = DataStructs.OnBitProjSimilarity(fp2, fp1)
self.assertAlmostEqual(v1, 1, 'substruct %s not properly contained in %s' % (match, smi))
def test6(self):
""" check that the bits in a signature of size N which has been folded in half
are the same as those in | a signature of size N/2 """
smis = ['CCC(O)C(=O)O', 'c1ccccc1', 'C1CCCCC1', 'C1NCCCC1', 'CNCNCNC']
for smi in smis:
m = Chem.MolFromSmiles(smi)
fp1 = Chem.RDKFingerprint(m, 2, 7, 4096)
fp2 = DataStructs.FoldFingerprint(fp1, 2)
fp3 = Chem.RDKFingerprint(m, 2, 7, 2048)
self.assertEq... |
ksmit799/Toontown-Source | toontown/classicchars/DistributedGoofySpeedwayAI.py | Python | mit | 6,450 | 0.004186 | from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
impo... | AI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'Trans... | .State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'O... |
CMSS-BCRDB/RDS | trove/guestagent/datastore/experimental/couchbase/system.py | Python | apache-2.0 | 2,404 | 0.000832 | # Copyright (c) 2013 eBay Software Foundation
# 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
#
# Unl... | '/etc/sysctl.conf')
cmd_reset_pwd = 'sudo /opt/couchbase/bin/cbreset_password %(IP)s:8091'
pwd_file = COUCHBASE_CONF_DIR + SECRET_KEY
cmd_get_password_from_config = """sudo /opt/couchbase/bin/erl -noinput -eval \
'case file:read_file("/opt/couchbase/var/lib/couchbase/config/config.dat") \
of {ok,... | grep '\[{"root",\[{password,' | awk -F\\" '{print $4}'
"""
|
cylc/cylc | tests/functional/xtriggers/02-persistence/faker_fail.py | Python | gpl-3.0 | 873 | 0 | #!/usr/bin/env python3
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program i | s distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this progra... |
google/intellij-community | python/helpers/typeshed/scripts/create_baseline_stubs.py | Python | apache-2.0 | 6,346 | 0.001733 | #!/usr/bin/env python3
"""Script to generate unannotated baseline stubs using stubgen.
Basic usage:
$ python3 scripts/create_baseline_stubs.py <project on PyPI>
Run with -h for more help.
"""
import argparse
import os
import re
import shutil
import subprocess
import sys
from typing import Optional, Tuple
PYRIGHT_C... | directory must be the root of typeshed r | epository")
# Get normalized project name and version of installed package.
info = get_installed_package_info(project)
if info is None:
print(f'Error: "{project}" is not installed', file=sys.stderr)
print("", file=sys.stderr)
print(f'Suggestion: Run "python3 -m pip install {project}... |
newmediamedicine/indivo_server_1_0 | indivo/views/reports/procedure.py | Python | gpl-3.0 | 2,013 | 0.007452 | """
.. module:: views.reports.procedure
:synopsis: Indivo view implementations for the procedure report.
.. moduleauthor:: Daniel Haas <daniel.haas@post.harvard.edu>
.. moduleauthor:: Ben Adida <ben@adida.net>
"""
from django.http import HttpResponseBadRequest, HttpResponse
from indivo.lib.view_decorators import ... | loader, DEFAULT_ORDERBY
from indivo.lib.query import FactQuery, DATE, STRING, NU | MBER
from indivo.models import Procedure
PROCEDURE_FILTERS = {
'procedure_name' : ('name', STRING),
'date_performed': ('date_performed', DATE),
DEFAULT_ORDERBY : ('created_at', DATE)
}
PROCEDURE_TEMPLATE = 'reports/procedure.xml'
def procedure_list(*args, **kwargs):
""" List the procedure data for a given re... |
cpennington/edx-platform | lms/djangoapps/program_enrollments/management/commands/link_program_enrollments.py | Python | agpl-3.0 | 4,440 | 0.004054 | """ Management command to link program enrollments and external student_keys to an LMS user """
from uuid import UUID
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from lms.djangoapps.program_enrollments.api import link_program_enrollments
User = g... | = 'external user key {} provided multiple times'
class Command(BaseCommand):
"""
Management command to manually link ProgramEnrollments without an LMS user to an LMS user by
username.
Usage:
./manage.py lms link_program_enrollments <program_uuid> <user_item>*
where a <user_item> is a... | gram enrollments should be linked by the Django Social Auth post_save signal
handler `lms.djangoapps.program_enrollments.signals.matriculate_learner`, but in the case that
a partner does not have an IDP set up for learners to log in through, we need a way to link
enrollments.
Provided a program uuid an... |
erdc/proteus | proteus/tests/elliptic_redist/RDLS/rdls_n.py | Python | mit | 1,916 | 0.014614 | from __future__ import absolute_import
from proteus import *
from proteus.default_n import *
try:
from .rdls_p import *
from .vortex2D import *
except:
from rdls_p import *
from vortex2D import *
timeIntegration = NoIntegration
stepController = Newton_controller
# About the nonlinear solver
multilevel... | d,lag=lag_shockCapturing_rd)
numericalFluxType = DoNothing
nonlinearSmoother = None
level | NonlinearSolverConvergenceTest='r'
nonlinearSolverConvergenceTest='r'
matrix = SparseMatrix
if parallel:
multilevelLinearSolver = KSP_petsc4py#PETSc
levelLinearSolver = KSP_petsc4py#PETSc
linear_solver_options_prefix = 'rdls_'
linearSolverConvergenceTest = 'r-true'
else:
multilevelLinearSolver = LU... |
balazsfabian/pytim | pytim/itim.py | Python | gpl-3.0 | 16,238 | 0.000308 | #!/usr/bin/python
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
""" Module: itim
============
"""
from __future__ import print_function
from multiprocessing import Process, Queue
import numpy as np
try:
from __builtin__ import zi... | . Chem. 29, 945, 2008)*
:param Object universe: The MDAnalysis_ Universe, MDTraj_ trajectory
or OpenMM_ Simulation objects.
:param Object group: An AtomGroup, or an array-like object with
the indices of the atoms in the group. ... | rom this
group
:param float alpha: The probe sphere radius
:param str normal: The macroscopic interface normal direction
'x','y', 'z' or 'guess' (default)
:param bool molecular: Switches between search of interfa... |
jchome/LocalGuide-Mobile | kvmap/overlays/WMSOverlayServer.py | Python | gpl-2.0 | 5,614 | 0.020485 | from kvmap.code.projections import *
from urllib2 import urlopen
from httplib import HTTPConnection
from threading import Thread
from kivy.logger import Logger
from kivy.loader import Loader
from os.path import join, dirname
import time, os
import hashlib
try:
from pyproj import Proj
from xml.etree import Element... | t:
name = None
srss = layer.findall("SRS")
if name: # and srss:
data[name] = map(lambda x:x.text, srss)
if self.debug:
print "Provider %s provides layer %s in projections %s" % (self.provider_host, na | me, data[name])
subs = layer.findall("Layer")
for sub in subs:
self.parseLayer(sub, data)
def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None):
self.debug = (layer == None) and (index == 0)
# GetCapabilities (Layers + SRS)
if layer is None or s... |
asedunov/intellij-community | python/testData/intentions/convertDictComp_after.py | Python | apache-2.0 | 43 | 0.023256 | d | ict([(k, chr(k + 65)) for k in ran | ge(10)]) |
business-factory/captain-hook | hooks/app.py | Python | mit | 66 | 0 | # -*- c | oding: utf-8 -*-
from .api_server import AP | I
app = API()
|
ddico/account-financial-tools | account_credit_control/tests/test_res_partner.py | Python | agpl-3.0 | 1,262 | 0 | # Copyright 2017 Okia SPRL (https://okia.be)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError
class TestCreditControlP | olicyLevel(TransactionCase):
post_install = True
at_install = False
def test_check_credit_policy(self):
"""
Test the constrains on res.partner
First we try to assign an account and a policy with a wrong policy
(this policy doesn't contains the account of the partner).
... | """
policy = self.env.ref('account_credit_control.credit_control_3_time')
partner = self.env['res.partner'].create({
'name': 'Partner 1',
})
account = partner.property_account_receivable_id
with self.assertRaises(ValidationError):
partner.write({
... |
g0v/sunshine.cy | parser/property/db_settings.py | Python | cc0-1.0 | 337 | 0.005935 | #! /usr/bi | n/env python
# -*- coding: utf-8 -*-
import psycopg2
from psycopg2.extras import Json
def con():
psycopg2.extensions.register_adapter(dict, Json)
psycopg2.extensions.regist | er_adapter(list, Json)
conn = psycopg2.connect(dbname='cy', host='localhost', user='postgres', password='postgres')
return conn
|
gertvv/ictrp-retrieval | listRecords.py | Python | mit | 3,167 | 0.007578 | import os
import urllib.request, urllib.error, urllib.parse
import shutil
import tempfile
import zipfile
import re
import logging
logger = logging.getLogger()
import xml.etree.cElementTree as ET
from util import stripInvalidXmlEntities
import awsSecrets
ICTRP_SECRETS = awsSecrets.getSecrets()
def nctList():
lo... | root.findall('.//TrialID')]
logger.info('ICTRP IDs listed: {} IDs found'.format(len(ids)))
return ids
def crawlList():
baseUrl = "http://apps.who.int/trialsearch/crawl/"
authinfo = urllib.request.HTTPPasswordMgrWithDefaultRealm()
authinfo.add_password(None, baseUrl, ICTRP_SECRETS['ICTRP_CRAWL_USER... | l_opener(opener)
def crawl(page):
response = urllib.request.urlopen(baseUrl + page)
body = response.read().decode('utf-8')
response.close()
return body
pages = re.findall('href\="(crawl[0-9]+.aspx)"', crawl("crawl0.aspx"))
logging.info("Crawl - got index, {} pages".format(l... |
pre-commit/pre-commit | tests/parse_shebang_test.py | Python | mit | 4,687 | 0 | from __future__ import annotations
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
def _echo_exe() -> str:
exe = shutil.whi... | parse_shebang.normexe('./exe')
a | ssert excinfo.value.args == ('Executable `./exe` is not executable',)
def test_normexe_is_a_directory(tmpdir):
with tmpdir.as_cwd():
tmpdir.join('exe').ensure_dir()
exe = os.path.join('.', 'exe')
with pytest.raises(OSError) as excinfo:
parse_shebang.normexe(exe)
msg, = ... |
haystack/eyebrowse-server | api/migrations/0003_auto__chg_field_filterlistitemcopy_date_created.py | Python | mit | 6,965 | 0.007466 | # -*- 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):
# Changing field 'FilterListItemCopy.date_created'
db.alter_column('api_... | 'auto_now': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '2000'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.Use... | 'object_name': 'FilterListItemCopy'},
'date_created': ('django.db.models.fields.DateTimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '2000'}),
'us... |
APSL/kaneda | kaneda/queues/rq.py | Python | mit | 1,504 | 0.003989 | from __future__ import absolute_import
import logging
try:
from redis import Redis
from r | q import Queue
except ImportError:
Redis = None
Queue = None
from kaneda.exceptions import ImproperlyConfigured
from .base import BaseQueue
class RQQueue(BaseQueue):
"""
RQ queue
:param queue: queue instance of RQ class.
:param redis_url: Redis connection url where RQ will attend the async ... | gs_namespace = 'RQ'
def __init__(self, queue=None, redis_url=None, queue_name='kaneda'):
if not Redis:
raise ImproperlyConfigured('You need to install redis to use the RQ queue.')
if not Queue:
raise ImproperlyConfigured('You need to install rq library to use the RQ queue.')... |
outlace/OpenTDA | tda/__init__.py | Python | apache-2.0 | 126 | 0 | fr | om .persistent_homology import PersistentHomology
__name__ = 'OpenTDA'
__version__ = 0.1
__all__ = ['PersistentHomolog | y']
|
BRiDGEIris/cgs-apps | code/apps/variants/tests/local_login.py | Python | apache-2.0 | 561 | 0.046346 | import requests
def login(output_file):
r = requests.get('http://quickstart.cloudera:8888/accounts/login/?next=/')
tmp = r.text.split('csrfmiddlewaretoken')
tmp = tmp[1].split("value='")
t | mp = tmp[1].split("'")
token = tmp[0]
cookie = r.cookies
data = {'username':'cloudera','password':'cloudera','csrfmiddlewaretoken':token}
r = requests.post('http://quickstart.cloudera:8888/accounts/login/?next=/variants/ap | i/variants/ulb|0|1|10177|A/',data=data,cookies=cookie)
f = open(output_file,'w')
f.write(r.text)
f.close()
login('curl-results.txt')
|
puttarajubr/commcare-hq | corehq/apps/reports/models.py | Python | bsd-3-clause | 31,850 | 0.001601 | from datetime import datetime, timedelta
import logging
from urllib import urlencode
from django.http import Http404
from django.utils import html
from django.utils.safestring import mark_safe
import pytz
from corehq import Domain
from corehq.apps import reports
from corehq.apps.app_manager.models import get_app, Form,... | ugettext_noop("demo_user"),
ugettext_noop("admin"),
ugettext_noop("Unknown Users"),
ugettext_noop("CommCare Supply")]
toggle_defaults = (True, False, False, | False, False)
count = len(human_readable)
included_defaults = (True, True, True, True, False)
@classmethod
def use_defaults(cls):
return cls._get_manual_filterset(cls.included_defaults, cls.toggle_defaults)
@classmethod
def all_but_users(cls):
no_users = [True] * cls.count
... |
WarrenWeckesser/scipy | scipy/_lib/tests/test_import_cycles.py | Python | bsd-3-clause | 1,306 | 0 | import sys
import subprocess
MODULES = [
"scipy.cluster",
"scipy.cluster.vq",
"scipy.cluster.hierarchy",
"scipy.constants",
"scipy.fft",
"scipy.fftpack",
"scipy.fftpack.convolve",
"scipy.integrate",
"scipy.interpolate",
"scipy.io",
"scipy.io.arff",
"scipy.io.harwell_boe... | l.distance",
"scipy. | special",
"scipy.stats",
"scipy.stats.distributions",
"scipy.stats.mstats",
"scipy.stats.contingency"
]
def test_modules_importable():
# Regression test for gh-6793.
# Check that all modules are importable in a new Python process.
# This is not necessarily true if there are import cycles p... |
bcb/jsonrpcclient | setup.py | Python | mit | 1,595 | 0.001881 | """setup.py"""
from setuptools import setup
with open("README.md") as readme_file:
README = readme_file.read()
test_requirements = ["mock", "pytest", "responses", "testfixtures", "requests", "pyzmq"]
# Async requirements
test_requirements.extend(["pytest-asyncio", "aiohttp", "tornado", "websockets"])
setup(
... | },
include_package_data=True,
install_requires=["apply_defaults<1", "click<8", "jsonschema<4"],
license="MIT",
long_description=README,
long_description_content_type="text/markdown",
name="jsonrpcclient",
# Be PEP 561 compliant
# https://mypy.readthedocs | .io/en/stable/installed_packages.html#making-pep-561-compatible-packages
package_data={"jsonrpcclient": ["response-schema.json", "py.typed"]},
zip_safe=False,
packages=["jsonrpcclient", "jsonrpcclient.clients"],
url="https://github.com/bcb/jsonrpcclient",
version="3.3.6",
)
|
phistuck/FrequentFeedScraper | add_handler.py | Python | mit | 1,694 | 0.020661 | import webapp2, logging
from database import get_feed_source_by_name, store_feed_source, \
get_feed_source_by_url, change_feed_source_url
class AddHandler(webapp2.RequestHandler):
def post(self):
from database import FeedSource
name = self.request.get('name')
url = self.request.get('url')
frequency_... | seconds) -
<input type="number" value="1000" name="frequency_ms"/><br/>
<label> | Update?<input type="checkbox" name="should_update" value="1"/></label>
<input type="submit"/>
</form>""") |
deerwalk/voltdb | tests/sqlcoverage/schema/joined-matview-string-schema.py | Python | agpl-3.0 | 3,168 | 0 | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2017 VoltDB Inc.
#
# 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 limitati... | VOLTTYPE_STRING),
("VCHAR_INLINE_MAX", FastSerializer.VOLTTYPE_STRING),
("VCHAR_INLINE", FastSerializer.VOLTTYPE_STRING) | ,
("RATIO", FastSerializer.VOLTTYPE_FLOAT)),
"partitions": (),
"indexes": ("ID")
},
"P3": {
"columns": (("ID", FastSerializer.VOLTTYPE_INTEGER),
("VCHAR", FastSerializer.VOLTTYPE_STRING),
("VCHAR_INLINE_MAX", FastSerializer.... |
azaghal/ansible | test/lib/ansible_test/_internal/config.py | Python | gpl-3.0 | 13,139 | 0.00274 | """Configuration classes."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import sys
from . import types as t
from .util import (
find_python,
generate_pip_command,
ApplicationError,
)
from .util_common import (
docker_qualify_image,
get_docke... | ept AttributeError:
TIntegrationConfig = None # pylint: disable=invalid-name
class ParsedRemote:
"""A parsed version of a "remote" string."""
def __init__(self, arch, platform, version): # type: (t.Optional[s | tr], str, str) -> None
self.arch = arch
self.platform = platform
self.version = version
@staticmethod
def parse(value): # type: (str) -> t.Optional['ParsedRemote']
"""Return a ParsedRemote from the given value or None if the syntax is invalid."""
parts = value.split('/'... |
asridharan/dcos | packages/adminrouter/extra/src/test-harness/modules/mocker/endpoints/mesos_dns.py | Python | apache-2.0 | 5,228 | 0.001148 | # Copyright (C) Mesosphere, Inc. See LICENSE file for details.
"""MesosDNS mock endpoint"""
import copy
import logging
import re
from exceptions import EndpointException
from mocker.endpoints.recording import (
RecordingHTTPRequestHandler,
RecordingTcpIpEndpoint,
)
# pylint: disable=C0103
log = logging.getL... | eduler-alwaysthere", "127.0.0.15", 16001),
create_srv_entry("scheduler-alwaysthere", "127.0.0.1", 16002),
],
}
SCHEDULER_SRV_ALWAYSTHERE_NEST1 = {
"scheduler-alwaysthere.nest1.nest2": [
create_srv_entry("scheduler-alwaysthere.nest1.nest2", "127.0.0.1", 18000),
create_srv_entry("scheduler... | aysthere.nest1.nest2", "127.0.0.1", 16002),
],
}
SCHEDULER_SRV_ALWAYSTHERE_NEST2 = {
"scheduler-alwaysthere.nest1": [
create_srv_entry("scheduler-alwaysthere.nest1", "127.0.0.1", 17000),
create_srv_entry("scheduler-alwaysthere.nest1", "127.0.0.1", 16002),
],
}
SCHEDULER_SRV_ONLYMESOSDNS_NEST... |
jonathaneunice/textdata | test/test_eval.py | Python | apache-2.0 | 2,704 | 0.001109 | # -*- coding: utf-8 -*-
import sys
import pytest
from textdata.eval import evaluation
_PY2 = sys.version_info[0] == 2
_PY26 = sys.version_info[:2] == (2, 6)
def test_evaluation_natural():
cases = [
(' 1 ', 1),
(' 1.1 \n ', 1.1),
(' gizmo \n\t \n', 'gizmo'),
]
if not _PY26:
... | ation_broken():
cases = [
(' 1 ', '1'),
(' 1.1 \n ', '1.1'),
(' gizmo \n\t \n', 'gizmo'),
(' 1+4j ', '1+4j')
]
for value, expected in cases:
with pytest.raises(ValueError):
assert evaluation(value, 'smork') == expected
with pytest.raises(Value... | assert evaluation('007', 'natural') == 7
else:
assert evaluation('007', 'natural') == '007'
def test_evaluation_func():
custom = lambda x: x.strip().upper()
def custom2(x):
return x.strip().upper()
assert evaluation(' haPpIly ', custom) == 'HAPPILY'
assert evaluation(' haPpIly ... |
mmoiozo/mavcourse | sw/tools/dfu/dfu.py | Python | gpl-2.0 | 7,206 | 0.005551 | #!/usr/bin/env python
#
# dfu.py: Access USB DFU class devices
# Copyright (C) 2009 Black Sphere Technologies
# Copyright (C) 2012 Transition Robotics Inc.
# Written by Gareth McMullin <gareth@blacksphere.co.nz>
# Modified by Piotr Esden-Tempski <piotr@esden.net>
#
# This program is free software: you can redistribut... | E:
return True
if ((status.bState == STATE_DFU_DOWNLOAD_SYNC) or
(status.bState == STATE_DFU_DOWNLOAD_IDLE) or
(status.bState == STATE_DFU_MANIFEST_SYNC) or
(status.bState == STATE_DFU_UPLOAD_IDLE) or
(status.bSt | ate == STATE_DFU_DOWNLOAD_BUSY) or
(status.bState == STATE_DFU_MANIFEST)):
self.abort()
continue
if status.bState == STATE_DFU_ERROR:
self.clear_status()
continue
if status.bState == STATE_APP_IDLE:
... |
danakj/chromium | third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/mac_unittest.py | Python | bsd-3-clause | 4,329 | 0.003234 | # Copyright (C) 2010 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | port.host.filesystem.maybe_make_directory('/mock-checkout/xcodebuild/Release')
# Check with 'out' being newer.
port.host.filesystem.mtime = lambda f: 5 if '/out/' in f else 4
self.assertEqual(port._build_path(), '/mock-checkout/out/Release')
# Check with 'xcodebuild' being newer.
... | ck-checkout/xcodebuild/Release')
def test_driver_name_option(self):
self.assertTrue(self.make_port()._path_to_driver().endswith('Content Shell'))
self.assertTrue(self.make_port(options=optparse.Values(dict(driver_name='OtherDriver')))._path_to_driver().endswith('OtherDriver'))
def test_path_to... |
mavrix93/LightCurvesClassifier | lcc_web/web/interface/admin.py | Python | mit | 167 | 0.005988 | from django.contrib import admin
# Register your models here.
from .models im | port | DbQuery, StarsFilter
admin.site.register(DbQuery)
admin.site.register(StarsFilter) |
rickydunlop/cookiecutter-django-app-template-drf-haystack | {{cookiecutter.app_name}}/serializers.py | Python | mit | 771 | 0.022049 | from rest_framework import serializers
from drf_haystack.serializ | ers import Hayst | ackSerializerMixin
from .models import {{ cookiecutter.model_name }}
from .search_indexes import {{ cookiecutter.model_name }}Index
class {{ cookiecutter.model_name }}Serializer(serializers.ModelSerializer):
class Meta:
model = {{ cookiecutter.model_name }}
fields = '__all__'
class {{ cookiecu... |
vsaw/miniSSL | minissl/TcpDispatcher.py | Python | mit | 3,729 | 0.001341 | import socket
import asyncore
import pickle
from minissl.AbstractConnection import AbstractConnection
class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection):
"""Buffers a stream until it contains valid data serialized by pickle.
That is a big of an ugly glue code I had to come up with i... | t a problem.
"""
self.socket.sendall(data)
class TcpDispatcher(asyncore.dispatcher):
"""A powerful TCP dispatcher based on asyncore to listen for incoming
connections.
See htt | p://docs.python.org/2/library/asyncore.html for more information on
the library.
"""
def __init__(self, host, port, receive_callback):
"""Start a new dispatcher to listen on the given host socket
:param host:
The host interface to listen to
:param port:
The ... |
sakost/vkAPI | vkAPI/API.py | Python | apache-2.0 | 5,360 | 0.002425 | import hashlib
from vkAPI.mixins import *
from vkAPI.utils import *
class Session(object):
"""A Session object where you should put a default params which will always send"""
API_URL = 'https://api.vk.com/method/'
def __init__(self, access_token=None, secret=None):
"""
:except kwargs: su... | gs)
return wrapper
return decorator
class Request(object):
__slots__ = ('_api', '_method_name', '_method_args')
def __init__(self, api, method_name):
self._api = api
self._method_name = method_name
def __getattr__(self, method_name):
return Request(self._api, ... | urn self._api._session._make_request(self)
class DecorRequest(Request):
def __getattr__(self, method_name):
return DecorRequest(self._api, self._method_name + '.' + method_name)
def __call__(self, is_method=False, **method_args):
self._method_args = method_args
def decorator(func):
... |
annarev/tensorflow | tensorflow/python/ops/math_ops.py | Python | apache-2.0 | 186,089 | 0.003353 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | is sliced in the end so a correct result is returned for
# num == 1, and num == 0.
n_steps = gen_math_ops.maximum(num_int - 1, 1)
delta = (expanded_stop - expanded_start) / cast(n_steps,
| expanded_stop.dtype)
# Re-cast tensors as delta.
expanded_start = cast(expanded_start, delta.dtype)
expanded_stop = cast(expanded_stop, delta.dtype)
# If num < 0, we will throw exception in the range
# otherwise use the same div for delta
range_end = array_ops.where_v2(num_int >... |
johnsonc/OTM2 | opentreemap/treemap/migrations/0061_change_zip_code_sort_order.py | Python | gpl-3.0 | 20,859 | 0.008102 | # -*- coding: utf-8 -*-
from south.v2 import DataMigration
class Migration(DataMigration):
def forwards(self, orm):
orm.Boundary.objects.filter(category='Zip Code').update(sort_order=5)
def backwards(self, orm):
pass
models = {
u'auth.group': {
'Meta': {'object_name':... | : ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.model... | eld', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'treema... |
scripnichenko/nova | nova/api/openstack/compute/legacy_v2/contrib/flavormanage.py | Python | apache-2.0 | 4,241 | 0.000472 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ontext = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exceptio | n.FlavorNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
flavors.destroy(flavor['name'])
return webob.Response(status_int=202)
@wsgi.action("create")
def _create(self, req, body):
context = req.environ['nova.context']
authorize(context)
... |
benzkji/django-ckeditor-link | ckeditor_link/templatetags/ckeditor_link_tags.py | Python | gpl-2.0 | 3,359 | 0.001191 | import importlib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from ckeditor_link import conf
from django import template
from django.template.defaultfilters import stringfilter
try:
module_name, class_name = conf.CKEDITOR_LINK_MODEL.rsplit(".", 1)
... | try:
# this can go wrong with fk and the like
real_link = ckeditor_link_class(**kwargs)
link.set('href', real_link.get_link())
if getattr(real_link, 'get_link_target', None):
link.set('target', real_link.get_link_target())
... | k, 'get_link_attrs', None):
for attr, value in real_link.get_link_attrs().items():
link.set(attr, value)
except (ValueError, ObjectDoesNotExist):
continue
# arf: http://makble.com/python-why-lxml-etree-tostring-method-returns-bytes
# beauti... |
dustcloud/dustlink | DustLinkData/PersistenceEngine.py | Python | bsd-3-clause | 4,768 | 0.014681 | #!/usr/bin/python
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('PersistenceEngine')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())
import time
import threading
import traceback
class PersistenceEngine(threading.Thread):
... | output += [traceback.format_exc()]
output = '\n'.join(output)
print | output # critical error
log.critical(output)
# release closingSem
self.closingSem.release()
raise
finally:
# log
log.info('thread ended')
#======================== public =====... |
sassoftware/amiconfig | amiconfig_test/plugin_disablesshpasswdauth_test.py | Python | apache-2.0 | 1,526 | 0.001966 | #!/usr/bin/python
#
# Copyright (c) SAS Institute 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... | base
class PluginTest(testbase.BasePluginTest):
pluginName = 'disablesshpasswdauth'
PluginData = ""
SshdConfigContents = """\
Dummy line 1
Dummy line 2
PasswordAuthentication yes
# PasswordAuthentication yes
Dummy line 3
"""
def setUpExtra(self):
sshdConfigDir = self.mkdirs("etc/ssh")
... | sshdConfig = self.sshdConfigFile = os.path.join(
sshdConfigDir, "sshd_config")
file(sshdConfig, "w").write(self.SshdConfigContents)
def testFiles(self):
self.assertEquals(file(self.sshdConfigFile).read(),
self.SshdConfigContents.replace(
'\nPasswordA... |
ehudmagal/robotqcapp | Utils/RobotQAUtils/graphics/drawTable.py | Python | bsd-3-clause | 435 | 0.036782 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
def printLegend(rowLabels,colLabels,params):
fig = plt.figure()
co | l_labels=colLabels
row_labels=rowLabels
table_vals=params
the_table = plt.table(cellText=table_vals,
colWidths = [0.2]*4,
rowLabels=row_labels,
colLabels=col_labels,
loc='center')
plt.te | xt(12,3.4,'Table Title',size=8)
plt.title('Legend for expiriments')
plt.show() |
mahak/neutron | neutron/tests/unit/db/test_ovn_revision_numbers_db.py | Python | apache-2.0 | 12,345 | 0 | # Copyright 2019 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | on()
revision_plugin.RevisionPlugin()
self.net = self._make_network(self.fmt, 'net1', True)['network']
# Mock the default value for INCONSISTENCIES_OLDER_THAN so
# tests won't need to wait for the timeout in order to validate
# the database inconsistencies
self.older_tha... | -1)
self.older_than_mock.start()
self.addCleanup(self.older_than_mock.stop)
self.ctx = context.get_admin_context()
def _create_initial_revision(self, resource_uuid, resource_type,
revision_number=ovn_rn_db.INITIAL_REV_NUM,
... |
flexVDI/cerbero | recipes/custom.py | Python | lgpl-2.1 | 2,085 | 0.003357 | # -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
import os
import shutil
from collections import defaultdict
from cerbero.build import recipe
from cerbero.build.source import SourceType
from cerbero.build.cookbook import CookBook
from cerbero.config import Platform
from cerbero.enums import License
from c... | if not e.startswith('lib/gstreamer-'):
continue
c = e.split('/')
if len(c) != 3:
continue
e = c[2]
# we only | care about files with the replaceable %(mext)s extension
if not e.endswith ('%(mext)s'):
continue
if e.startswith('libgst'):
e = e[6:-8]
else:
e = e[3:-8]
plugins[cat_n... |
google/llvm-propeller | lldb/packages/Python/lldbsuite/test/dotest_args.py | Python | apache-2.0 | 11,181 | 0.003935 | from __future__ import absolute_import
# System modules
import argparse
import sys
import os
import textwrap
# LLDB modules
from . import configuration
def create_parser():
parser = argparse.ArgumentParser(
description='description',
prefix_chars='+-',
add_help=False)
group = None
... | extra flags to be passed to the toolchain when building the inferior programs to be debugged
| suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures'''))
group.add_argument('--dsymutil', metavar='dsymutil', dest='dsymutil', help=textwrap.dedent('Specify which dsymutil to use.'))
group.add_... |
shunw/pythonML_code | eg2_real_world_data.py | Python | mit | 4,961 | 0.01794 | from collections import Counter
from imblearn.datasets import make_imbalance
from imblearn.metrics import classification_report_imbalanced
from imblearn.pipeline import make_pipeline
from imblearn.under_sampling import ClusterCentroids
from imblearn.under_sampling import NearMiss
import matplotlib.pyplot as plt
from ... | s(version = 1, random_state = RANDOM_STATE), LinearSVC(random_state = RANDOM_STATE))
pipeline_1.fit(X_train, y_train)
ax2 = fig.add_subplot(212)
ax2.scatter_plot(X[:, [1, 2]], y, pipeline_1)
plt.show()
def wendy_try_iris():
'''
EXAMPLE: Multiclass classification with under-sampling
'''
... | ndom_state = 0)
X = pd.DataFrame(iris.data, columns = ['Sepal_length', 'Sepal_width', 'Petal_length', 'Petal_width'])
y = pd.DataFrame(iris.target, columns = ['Species'])
df = X
df['Species'] = y
'''pair plot for the features'''
# sns.set(style='whitegrid', context='notebook')
# co... |
Sarthak30/Codeforces | fox_and_snake.py | Python | gpl-2.0 | 361 | 0.113573 | a, | b = map(int,raw_input().split())
i=0
while(i<a):
j=0
c=[]
if(i%2==0):
while(j<b):
c.append('#')
j=j+1
print (''.join(c))
else:
k = int(i/2)
if (k%2==0):
while(j<(b-1)):
c.append(".")
j=j+1
c.append("#")
print (''.join(c))
else:
c.append('#')
while(j<(b-1)):
c.append(".")
... | |
SublimeText-Markdown/TableEditor | table_plugin.py | Python | gpl-3.0 | 18,180 | 0.000935 | # table_plugin.py - sublime plugins for pretty print text table
# Copyright (C) 2012 Free Software Foundation, Inc.
# Author: Valery Kocubinsky
# Package: SublimeTableEditor
# Homepage: https://github.com/vkocubinsky/SublimeTableEditor
# This file is part of SublimeTableEditor.
# SublimeTableEditor is free softwar... | ext"
else:
return "Simple"
def merge(self, edit, ctx):
table = ctx.table
new_lines = table.render_lines()
first_table_row = ctx.first_table_row
last_table_row = ctx.last_table_row
rows = range(first_table_row, last_table_row + 1)
for row, new_text... | w, 0))
old_text = self.view.substr(region)
if old_text != new_text:
self.view.replace(edit, region, new_text)
#case 1: some lines inserted
if len(rows) < len(new_lines):
row = last_table_row
for new_text in new_lines[len(rows):]:
... |
kiae-grid/panda-bigmon-core | core/htcondor/urls.py | Python | apache-2.0 | 526 | 0.013308 | from django.conf.urls import | patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
### #FIXME admin.autodiscover()
import views as htcondor_views
#from ..api.htcondorapi import views as htcondorapi_views
urlpatterns = patterns('',
### HTCondor Jo | bs
url(r'^/$', htcondor_views.list3HTCondorJobs, name='listHTCondorJobs'),
url(r'^/(?P<globaljobid>[-A-Za-z0-9_.#]+)/$', htcondor_views.htcondorJobDetails, name='HTCondorJobDetails'),
)
|
nanomolina/JP | src/odontology/register/apps.py | Python | apache-2.0 | 132 | 0 | from __future__ import unicode_literals
from django.apps import | AppConfig
class RegisterConfig(AppConfig | ):
name = 'register'
|
kstilwell/tcex | tcex/logger/rotating_file_handler_custom.py | Python | apache-2.0 | 3,432 | 0.001166 | """API Handler Class"""
# standard library
import gzip
import os
import shutil
from logging.handlers import RotatingFileHandler
from typing import Optional
class RotatingFileHandlerCustom(RotatingFileHandler):
"""Logger handler for ThreatConnect Exchange File logging."""
def __init__(
self,
f... | do the grunt work
# result = logging.Formatter.format( | self, record)
#
# return result
#
# @property
# def standard_format(self):
# """Return the standard log format"""
# return (
# '%(asctime)s - %(name)s - %(levelname)s - %(message)s '
# '(%(filename)s:%(funcName)s:%(lineno)d:%(threadName)s)'
# )
#
# @pr... |
petrus-v/server-tools | disable_openerp_online/__openerp__.py | Python | agpl-3.0 | 1,917 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2013 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | ritten
* apps and updates menu items in settings are removed
* help and account menu items in user menu are removed
* prevent lookup of OPW for current database uuid and resulting"""
""" 'unsupported' warning
""",
"category": "",
"depends": [
| 'base',
'mail',
],
"data": [
'data/ir_ui_menu.xml',
'data/ir_cron.xml',
],
"js": [
'static/src/js/disable_openerp_online.js',
],
"css": [
],
"qweb": [
'static/src/xml/base.xml',
],
"auto_install": False,
"installable": True,
"ex... |
a1ezzz/wasp-general | wasp_general/network/web/request.py | Python | lgpl-3.0 | 4,630 | 0.023542 | # -*- coding: utf-8 -*-
# wasp_general/network/web.py
#
# Copyright (C) 2016 the wasp-general authors and contributors
# <see AUTHORS file>
#
# This file is part of wasp-general.
#
# Wasp-general is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as pub... | '
:param session: origin session
:param request_line: line to parse
:return: WWebRequest
"""
r = cls.request_line_re.search(req | uest_line)
if r is not None:
method, path, protocol_sentence, protocol_version = r.groups()
return WWebRequest(session, method, path)
raise ValueError('Invalid request line')
@verify_type('paranoid', http_code=str)
def parse_headers(self, http_code):
""" Parse http-code (like 'Header-X: foo\r\nHeader-Y: ... |
sparcs-kaist/heartbeat-server | apps/core/migrations/0006_auto_20161113_0341.py | Python | mit | 645 | 0 | # -*- coding: utf-8 -*-
# | Generated by Django 1.10.1 on 2016-11-12 18:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0005_auto_20161113_0317'),
]
operations = [
migrations.RenameField(
model_name='... | ld_name='path',
new_name='path_template',
),
migrations.AddField(
model_name='backuplog',
name='path',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
]
|
grahamc/markment | tests/unit/test_html_rendering.py | Python | mit | 7,784 | 0.000257 | # -*- coding: utf-8 -*-
# <markment - markdown-based documentation generator for python>
# Copyright (C) <2013> Gabriel Falcão <gabriel@nacaolivre.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 Fou... | (MD)
dom = lhtml.fromstring(mm.rendered)
headers = dom.cssselect("h2")
headers.should.have.length_of(1)
h2 = headers[0]
h2.attrib.should.have.key("name").being.equal("rendering-content")
h2.attrib.should.have.key("id").being.equal("rendering-content")
links = h2.getchildren()
links.... | content")
a.attrib.should.have.key("href").equal("#rendering-content")
def test_code_block():
"Markment should render code blocks"
MD = MARKDOWN("""
# API Reference
This is good
```python
import os
os.system('ls /')
```
This is not good
```python
import os
os.s... |
b-long/ezbake-platform-services | efe/frontend_app/modules/ezRPStaticFileStore.py | Python | apache-2.0 | 9,011 | 0.003884 | # Copyright (C) 2013-2015 Computer Sciences 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-2.0
#
# Unless required by a... | 0} cq= {1}".format(entry.row, entry.cq))
# if entry.cq.startswith("chunk_"):
# self.__log.info("getFile: row = {0} cq= {1}".format(entry.row, entry.cq))
# chun | ks_read += 1
# data.extend(entry.val)
self.__log.debug('retrieved static file for {url}'.format(url=usrFacingUrlPrefix))
if chunks_read != chunks:
self.__log.error("did not read all the chunks from StaticFile Store")
return data.tostring() if data.buffer_info()[1] > 0... |
austensatterlee/VOSIMSynth | scripts/add_file.py | Python | gpl-3.0 | 5,486 | 0.006744 | import re
from __future__ import print_function
HEADER_TEMPLATE=r"""/*
Copyright 2016, Austen Satterlee
This file is part of VOSIMProject.
VOSIMProject 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 ver... | ('src', 'include')))
sys.exit(1)
if not parsed.directory:
sys.stderr.write("ERROR: Please provide a directory\n")
sys.exit(1)
if not parsed.filenames:
sys.stderr.write("ERROR: Please provide at least one filename\n")
sys.exit(1)
direct... | tdir(directory)
if ('src' not in dir_contents) or ('include' not in dir_contents):
raise RuntimeError("'%s' and '%s' directories not found" % (parsed.source_dir,parsed.include_dir))
include_dir = os.path.join(directory,"include")
src_dir = os.path.join(directory,"src")
if parse... |
CERT-W/certitude | components/interface/web.py | Python | gpl-2.0 | 40,631 | 0.003323 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
CERTitude: the seeker of IOC
Copyright (c) 2016 CERT-W
Contact: cert@wavestone.com
Contributors: @iansus, @nervous, @fschwebel
CERTitude is under licence GPL-2.0:
This program is free software; you can redistribute it and/or
modify it under... | CSRF_TOKEN_INDEX] = genCSRFToken()
return session[CSRF_TOKEN_INDEX]
''' APPLICATION CONFIGURATION '''
app = Flask(__name__, static_folder=STATIC_ENDPOINT)
app.secret_key = os.urandom(24)
app.jinja_env.globals['csrf_token'] = getCSRFToken
app.jinja_env.globals['csrf_to | ken_name'] = CSRF_TOKEN_INDEX
app.config['UPLOAD_FOLDER'] = 'upload'
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 5 * 60
ALLOWED_EXTENSIONS = ['txt']
app.config['IOCS_FOLDER'] = os.path.join('components', 'iocscan', '.', 'ioc')
app.config['RESULT_FILE'] = os.path.join('components', 'interface', 'static', 'data', 'results... |
codeboy/coddy-sitetools | sitetools/coddy_site/procesors.py | Python | bsd-3-clause | 486 | 0.004115 | # -*- coding: utf-8 -*-
from django.core import urlresolvers
def custom_processor(request):
proc_data = dict()
resolver = urlresolvers.get_resolver(None)
patterns = sorted(
(key, val[0][0][0]) for key, val in resolver.reverse_di | ct.iteritems() if isinstance(key, basestring))
proc_data['pat'] = patterns
|
proc_data['app'] = 'Common app'
proc_data['ip_address'] = request.META['REMOTE_ADDR']
proc_data['user'] = request.user
return proc_data
|
rouxcode/django-cms-plugins | cmsplugins/maps/migrations/0003_googlemap_cms_page.py | Python | mit | 601 | 0.001664 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2016-12-06 09:04
from | __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cms', '0016_auto_201606 | 08_1535'),
('maps', '0002_auto_20160926_1157'),
]
operations = [
migrations.AddField(
model_name='googlemap',
name='cms_page',
field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, to='cms.Page'),
),
]
|
nathanbjenx/cairis | cairis/test/test_UseCaseContribution.py | Python | apache-2.0 | 3,094 | 0.007434 | # 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... | a['theSource'])
urc,rType = urcs[self.rcData['theDestination']]
self.assertEqual(orc.source(), urc.source())
self.assertEqual(orc.destination(), urc.destination())
self.assertEqual(orc.meansEnd(), urc.meansEnd())
self.assertEqual(orc.contribution(), urc.contribution())
if __name__ == '__main__': |
unittest.main()
|
Eforcers/inbox-cleaner | src/lib/gdata/apps/audit/service.py | Python | mit | 9,512 | 0.006308 | # Copyright (C) 2008 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | the user whose account auditing details were requested
request_id: string, the request_id
Returns:
A dict containing the result of the get operation."""
uri = self._serviceUrl('account', user=user+'/'+request_id)
try:
return self._GetProperties(uri)
except gdata.service.RequestError,... | raise AppsForYourDomainException(e.args[0])
def getAllAccountInformationRequestsStatus(self):
"""Gets the status of all account auditing requests for the domain
Args:
None
Returns:
list results of the POST operation
"""
uri = self._serviceUrl('account')
return self._GetPrope... |
enthought/etsproxy | enthought/logger/util.py | Python | bsd-3-clause | 50 | 0 | # proxy module |
from apptools.logger.util import | *
|
fweidemann14/x-gewinnt | game/test_game.py | Python | gpl-3.0 | 3,095 | 0.008401 | import game as game
import pytest
import sys
sys.path.insert(0, '..')
def trim_board(ascii_board):
return '\n'.join([i.strip() for i in ascii_board.splitlines()])
t = trim_board
def test_new_board():
game.Board(3,3).ascii() == t("""
...
...
...
""")
game.Board(4,3).ascii() == t("""
.... | d
and loads the provided data into the board.
"""
board = game.Board.load(t("""
o..
o..
xxx
"""))
def test_axis_strings():
board = game.Board.load(t("""
o..
o..
xxx
"""))
# get the axis strings | in this order: | \ / -
axis_strings = board.axis_strings(0,0)
assert axis_strings[0] == 'xoo'
assert axis_strings[1] == 'x'
assert axis_strings[2] == 'x..'
assert axis_strings[3] == 'xxx' # the winner :-)
assert board.won_by == 'x'
|
ivanprjcts/equinox-spring16-API | equinox_spring16_api/equinox_api/migrations/0005_application_new_att.py | Python | lgpl-3.0 | 463 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 | on 2016-03-11 11:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('equinox_api', '0004_operation_description'),
]
operations = [
migrations.AddField(
model_name='appl | ication',
name='new_att',
field=models.BooleanField(default=True),
),
]
|
dunkhong/grr | grr/server/grr_response_server/databases/db_foreman_rules_test.py | Python | apache-2.0 | 2,967 | 0.005056 | #!/usr/bin/env python
"""Mixin tests for storing Foreman rules in the relational db."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from grr_response_core.lib import rdfvalue
from grr_response_server import foreman_rules
from grr.test_lib import test_l... | expires = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(ex)
rule = self._GetTestRule("H:00000%d" | % i, expires=expires)
self.db.WriteForemanRule(rule)
self.assertLen(self.db.ReadAllForemanRules(), 6)
with test_lib.FakeTime(110):
self.db.RemoveExpiredForemanRules()
self.assertLen(self.db.ReadAllForemanRules(), 5)
with test_lib.FakeTime(350):
self.db.RemoveExpiredForemanRules()... |
fixbugs/py-fixbugs-tools | test/75f6.py | Python | gpl-3.0 | 37 | 0.027027 |
#0y0r1+syp0ry1+0267*y0r-7i+Psr+1g | e
| |
ewerybody/a2 | ui/a2widget/demo/key_value_table_demo.py | Python | gpl-3.0 | 1,931 | 0 | import json
import pprint
from a2qt import QtWidgets
from a2widget.key_value_table import KeyValueTable
from a2widget.a2text_field import A2CodeField
_DEMO | _DATA = {
'Name': 'Some Body',
'Surname': ' | Body',
'Street. Nr': 'Thingstreet 8',
'Street': 'Thingstreet',
'Nr': '8',
'PLZ': '12354',
'City': 'Frankfurt am Main',
'Phone+': '+1232222222',
'Phone': '2222222',
'Country': 'Germany',
}
class Demo(QtWidgets.QMainWindow):
def __init__(self):
super(Demo, self).__init__()
... |
whitews/BAMA_Analytics | BAMA_Analytics/urls.py | Python | bsd-2-clause | 338 | 0.002959 | fr | om django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^', include('authenticate.urls')),
(r'^', include('analytics.urls')),
(r'^admin/', include(admin.site.urls) | ),
(r'^api/', include('rest_framework.urls', namespace='rest_framework')),
)
|
snark/ignorance | docs/conf.py | Python | isc | 8,405 | 0.005354 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ignorance documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | mt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#defaul | t_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be sho... |
FordyceLab/AcqPack | acqpack/utils.py | Python | mit | 6,206 | 0.004351 | import csv
import json
import numpy as np
import pandas as pd
def read_delim(filepath):
"""
Reads delimited file (auto-detects delimiter + header). Returns list.
:param filepath: (str) location of delimited file
:return: (list) list of records w/o header
"""
f = open(filepath, 'r')
diale... | .concat([df_rcn,df_xy], axis=1)
# check for z-axis
ds_z = df_pos.query("DEVICE=='ZStage'")['X'].reset_index(drop=True)
if len(ds_z)>0:
df['z'] = ds_z
rename = {'GRID_ROW': 'r',
| 'GRID_COL': 'c',
'LABEL': 'name',
'X': 'x',
'Y': 'y'}
df.rename(columns=rename, inplace=True)
return df
def generate_grid(c0, c1, l_img, p):
"""
Based on two points, creates a 2D-acquisition grid similar to what MicroManager would produce.
:... |
shanot/imp | modules/core/test/test_surface_tethered_chain.py | Python | gpl-3.0 | 3,454 | 0.00029 | import math
import random
import numpy as np
import IMP
import IMP.core
import IMP.test
def _get_beta(N, b):
return 3. / (2. * N * b**2)
def _get_score(z, N, b):
beta = _get_beta(N, b)
return beta * z**2 - math.log(2 * beta * z)
def _get_derv(z, N, b):
beta = _get_beta(N, b)
return 2 * beta *... | h.pi / beta)**.5
self.assertAlmostEqual(func.get_dist | ance_at_minimum(), zmin,
delta=1e-6)
self.assertAlmostEqual(func.evaluate_with_derivative(zmin)[1], 0.,
delta=1e-6)
self.assertAlmostEqual(func.get_average_distance(), zmean,
delta=1e-6)
if... |
ltowarek/budget-supervisor | third_party/saltedge/swagger_client/models/simplified_attempt.py | Python | mit | 31,285 | 0.000064 | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: support@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class SimplifiedAttempt... | age': 'str',
'fetch_scopes': 'list[str]',
'finished': 'bool',
'finished_recent': 'bool',
'from_date': 'date',
'id': 'str',
'interactive': 'bool',
'locale': 'str',
'partial': 'bool',
'store_credenti | als': 'bool',
'success_at': 'datetime',
'to_date': 'datetime',
'updated_at': 'datetime',
'show_consent_confirmation': 'bool',
'include_natures': 'list[str]',
'last_stage': 'Stage'
}
attribute_map = {
'api_mode': 'api_mode',
'api_version': 'api_ver... |
toway/towaymeetups | mba/alembic/versions/20150201_e567bd5c0b_make_banner_url_long.py | Python | gpl-3.0 | 479 | 0.004175 | """make banner url longger
Revision ID: e567bd5c0b
Revises: 23ab90c01600
Create Date: 2015-02-01 13:15:59.075956
"""
# revision identifiers, used by Alembic.
rev | ision = 'e567bd5c0b'
down_revision = '23ab90c01600'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('banners', 'link_url',
type_=sa.String(200),
existing_type=sa.String(100),
nullable=True)
def downgrade():
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.