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 |
|---|---|---|---|---|---|---|---|---|
tgbugs/pyontutils | test/test_oboio.py | Python | mit | 6,002 | 0.002832 | import os
import shutil
import unittest
import pytest
from pyontutils import obo_io as oio
from .common import temp_path
obo_test_string = """format-version: 1.2
ontology: uberon/core
subsetdef: cumbo "CUMBO"
treat-xrefs-as-has-subclass: EV
import: http://purl.obolibrary.org/obo/uberon/chebi_import.owl
treat-xrefs-as-... | ome values {oh="look", a="thing!"} ! yay!', (('oh', 'look'), ('a', 'thing!'))),
('some rando}me values {oh="l{ook", a="t{hing!"} ! yay!', (('oh', 'l{ook'), ('a', 't{hing!'))),
('some rando}me values {oh="l{ook", a="t}hing!"} ! yay!', (('oh', 'l{ook'), ('a', 't}hing!'))),
)
bads ... |
assert not bads, '\n' + '\n\n'.join(f'{e}\n{a}' for e, a in bads)
def test_construct_simple_file(self):
of = oio.OboFile()
ids_names = [['123', 'test'],
['234', 'yee'],
['345', 'haw'],
['456', 'oio']]
terms = [oio.Term... |
heke123/chromium-crosswalk | native_client_sdk/src/build_tools/test_sdk.py | Python | bsd-3-clause | 8,061 | 0.009924 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Script for a testing an existing SDK.
This script is normally run immediately after build_sdk.py.
"""
import argparse
import o... | ld_libs_asan', StepBuildLibraries, pepperdir, 'address'),
('build_libs_tsan', StepBuildLibraries, pepperdir, 'thread'),
('build_tests_asan', StepBuildTests, pepperd | ir, 'address'),
('build_tests_tsan', StepBuildTests, pepperdir, 'thread'),
('sel_ldr_tests_asan', StepRunSelLdrTests, pepperdir, 'address'),
('sel_ldr_tests_tsan', StepRunSelLdrTests, pepperdir, 'thread'),
# TODO(sbc): get valgrind installed on the bots to enable this
# configuration
... |
dongyoungy/dbseer_middleware | rs-sysmon2/plugins/dstat_snooze.py | Python | apache-2.0 | 737 | 0 | class dstat_plugin(dstat):
def __init__(self):
self.name = 'snooze'
self.vars = ('snooze',)
self.type = 's'
self.width = 6
self.scale = 0
self.before = time.time()
def extract(self):
| now = time.time()
if loop != 0:
self.val['snooze'] = now - self.before
else:
self.val['s | nooze'] = self.before
if step == op.delay:
self.before = now
def show(self):
if self.val['snooze'] > step + 1:
return ansi['default'] + ' -'
color = 'white'
if step != op.delay:
color = 'gray'
snoze, c = fchg(self.val['snooze'], 6, 1... |
gw-sd-2016/Codir | codirSublime/SocketIO/websocket/_core.py | Python | gpl-2.0 | 16,014 | 0.000812 | """
websocket - WebSocket client library for Python
Copyright (C) 2010 Hiroki Ohtani(liris)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, ... | ting returned by getdefauttimeout() is used.
You can customize using 'options'.
If you set "header" list object, you can set your own custom header.
>>> conn = create_connection("ws://echo.websocket.org/",
... header=["User-Agent: MyProgram",
... "x-custom: header"])
... | time. This value is integer.
if you set None for this value,
it means "use default_timeout value"
options: "header" -> custom http header list or dict.
"cookie" -> cookie value.
"origin" -> custom origin url.
"host" -> custom host header string.
... |
xpavlus/parabaramba | venv/lib/python2.7/site-packages/cherrypy/test/test_proxy.py | Python | gpl-3.0 | 5,136 | 0.000195 | import cherrypy
from cherrypy.test import helper
script_names = ["", "/path/to/myapp"]
class ProxyTest(helper.CPWebCase):
def setup_server():
# Set up site
cherrypy.config.update({
'tools.proxy.on': True,
'tools.proxy.base': 'www.mydomain.test',
})
# Set... | ewpage = cherrypy.url(
"/this/new/page", script_name=sn)
def pageurl(self):
return self.thisnewpage
pageurl.exposed = True
def index(self):
raise cherrypy.HTTPRedirect('dummy')
index.exposed = True
def rem... | ypy.request.remote.ip
remoteip.exposed = True
def xhost(self):
raise cherrypy.HTTPRedirect('blah')
xhost.exposed = True
xhost._cp_config = {'tools.proxy.local': 'X-Host',
'tools.trailing_slash.extra': True,
... |
hirokiky/django-websettings | runtest.py | Python | mit | 1,437 | 0.001392 | import os
import sys
import django
def main():
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
sys.path.append(os.path.abspath(os.path.dirnam... | t get_runner
test_runner = get_runner(global_settings)
test_runner = test_runner()
failures = test_runner.run_tests | (['websettings'])
sys.exit(failures)
if __name__ == '__main__':
main()
|
YFFY/Supervisor | CountMan/monitor/queryer.py | Python | gpl-2.0 | 854 | 0.005855 | #! /usr/bin/env python
# --*-- coding:utf-8 --*--
import os
import sys
sys.path.append(os.path.split(os.path.split(os.path.ab | spath(sys.path[0]))[0])[0])
from CountMan.monitor.util import *
from CountMan.monitor.setting import *
class Queryer(object):
def __init__(self):
self.dao = DatabaseInterface()
self.dataSet = dict()
self | .logger = getLogger('root')
def getData(self):
for queryKey in QUERYPARAM:
self.dataSet[queryKey] = getResponse(QUERYPARAM.get(queryKey))
@property
def set2db(self):
self.getData()
self.logger.info('get query data: {0} success'.format(self.dataSet))
self.dao.ins... |
tingelst/pyversor | pyversor/c3d/directions.py | Python | bsd-3-clause | 1,721 | 0.000581 | # Copyright (c) 2015, Lars Tingelstad
# All rights reserved.
#
# 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
# l... | IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IM | PLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES... |
chrisRubiano/djangoblog | blog/urls.py | Python | mit | 500 | 0.018 | from django.conf.urls import | include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list), #URL para lista de todos los post
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail), #URL para ver los detalles del post
url(r'^post/new/$', views.post_new, name='post_new'), #URL para crear un nuevo post sin... | l panel de admin
] |
instinct-vfx/rez | src/rez/cli/bundle.py | Python | apache-2.0 | 1,729 | 0.001157 | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
'''
Bundle a context and its packages into a relocatable dir.
'''
from __future__ import print_function
import os
import os.path
import sys
def setup_parser(parser, completions=False):
group = parser.add_mutually_exclusive_group(... | groups=None):
from rez.utils.logging_ import print_error
from rez.bundle_context import bundle_context
from rez.resolved_context import ResolvedContext
rxt_filepath = os.path.abspath(os.path.expanduser(opts.RXT))
dest_dir = os.path.abspath(os.path.expanduser(opts.DEST_DIR))
# sanity checks
... | ResolvedContext.load(rxt_filepath)
bundle_context(
context=context,
dest_dir=dest_dir,
force=opts.force,
skip_non_relocatable=opts.skip_non_relocatable,
verbose=opts.verbose,
patch_libs=(not opts.no_lib_patch)
)
|
crmccreary/openerp_server | openerp/addons/account/report/account_central_journal.py | Python | agpl-3.0 | 5,320 | 0.004511 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | e = ['posted']
self.cr.execute('SELECT a.currency_id, a.code, a.name, c.symbol AS currency_code, l.currency_id, l.amount_currency, SUM(debit) AS debit, SUM(credit) AS credit \
from account_move_line l \
LEFT JOIN account_move am ON (l.move_id=am.id) \
... | EFT JOIN res_currency c on (l.currency_id=c.id) WHERE am.state IN %s AND l.period_id=%s AND l.journal_id=%s '+self.query_get_clause+' GROUP BY a.id, a.code, a.name,l.amount_currency,c.symbol, a.currency_id,l.currency_id', (tuple(move_state), period_id, journal_id))
return self.cr.dictfetchall()
def _set_ge... |
DigitalCampus/django-oppia | tests/viz/management/commands/test_cartodb_update.py | Python | gpl-3.0 | 2,062 | 0 | from io import StringIO
import re
import httpretty
from django.core.management import call_command
from oppia.test import OppiaTestCase
from settings import constants
from settings.models import SettingProperties
from tests.utils import get_file_contents
class CartoDBUpdateTest(OppiaTestCase):
fixtures = ['test... | and('cartodb_update', stdout=out)
@httpretty.activate
def test_cartodb_no_key_account(self):
cartodb_response = get_file_contents(self.cartodb_valid_response)
httpretty.register_uri(httpretty.GET,
self.cartodb_uri_regex,
body=cartodb... | ts.OPPIA_CARTODB_ACCOUNT, None)
SettingProperties.set_string(constants.OPPIA_CARTODB_KEY, None)
SettingProperties.set_string(constants.OPPIA_HOSTNAME, None)
out = StringIO()
call_command('cartodb_update', stdout=out)
|
arunkgupta/gramps | gramps/plugins/gramplet/backlinks.py | Python | gpl-2.0 | 7,865 | 0.002924 | # Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011 Nick Hall
# Copyright (C) 2011 Tim G L Lyons
#
# 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 th... | ces for an object.
"""
for classname, handle in \
self.dbstate.db.find_backlink_handles(active_handle):
name = navigation_label(self.dbstate.db, classname, handle)[0]
self.model.add((_(classname), name))
self.set_has_data( | self.model.count > 0)
def get_has_data(self, active_handle):
"""
Return True if the gramplet has data, else return False.
"""
if active_handle is None:
return False
for handle in self.dbstate.db.find_backlink_handles(active_handle):
return True
... |
dronecrew/px4tools | px4tools/mapping.py | Python | bsd-3-clause | 952 | 0 | """
Mapping functions
"""
# pylint: disable=invalid-name, missing-docstring, no-member
from __future__ import print_function
import pandas
from mpl_toolkits.basemap import Basemap
def create_map(lon, lat):
"""
Create a map projection.
"""
lon_center = lon[0]
lat_center = lat[0]
return Basem... | width=11e-5, height=1e-5, projection='tmerc')
gps_y, gps_x = gps_map(df.GPS_Lon.values, df.GPS_Lat.val | ues)
gps_z = df.GPS_Alt - df.GPS_Alt.values[0]
df_new = pandas.DataFrame(pandas.DataFrame({
'GPS_X': gps_x, 'GPS_Y': gps_y, 'GPS_Z': gps_z}, index=df.index))
return pandas.concat([df, df_new], axis=1)
# vim: set et fenc= ff=unix sts=0 sw=4 ts=4 :
|
joepettigrew/multi-blog | main.py | Python | mit | 890 | 0 | # My files
from handlers import MainPage
from handlers import WelcomePage
from handlers import SignUpPage
from handlers import SignIn
from handlers import SignOut
from handlers import NewPost
from handlers import EditPost
from handlers import DeletePost
from handlers import SinglePost
from handlers import LikePost
from... | ent
import webapp2
app = webapp2.WSGIApplication([
('/', MainP | age),
('/signup', SignUpPage),
('/welcome', WelcomePage),
('/post/([0-9]+)', SinglePost),
('/new-post', NewPost),
('/edit-post/([0-9]+)', EditPost),
('/delete-post', DeletePost),
('/like-post', LikePost),
('/dislike-post', DislikePost),
('/edit-comment', EditComment),
('/delete-c... |
concordusapps/alchemist | alchemist/tests/test_management.py | Python | mit | 489 | 0 | # -*- coding: ut | f-8 -*-
from __future__ import unicode_literals, absolute_import, division
from alchemist import management
from flask import Flask
class TestManager:
def setup(self):
self.app = Flask('alchemist')
self.app.config['COMPONENTS'] = ['alchemist']
def test_discover_commands(self):
"""Sho... | nager._commands
|
infinity0n3/fabtotum-experiments | fabtotum/fabui/database.py | Python | gpl-3.0 | 825 | 0 | #!/bin/env python
# -*- coding: utf-8; -*-
#
# (c) 2016 FABtotum, http://www.fabtotu | m.com
#
# This file is part of FABUI.
#
# FABUI 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.
#
# FABUI is distributed in the hope th... | en 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 FABUI. If not, see <http://www.gnu.org/licenses/>.
# Import standard python module
# Import ext... |
titos-carrasco/DaguCar | Python/TestDaguCar.py | Python | mit | 591 | 0.060914 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from rcr.robots.dagucar.DaguCar import DaguCar
def main():
car = DaguCar( "/dev/rfcomm1", 500 )
| car.MoveForward( 15 )
car.Pause( 1000 )
car.MoveBackward( 15 )
car.Pause( 1000 )
car.MoveLeft( 15 )
car.Pause( 1000 )
car.MoveRight( 15 )
car.Pause( 1000 )
car.MoveForwardLeft( 15 )
car.Pause( 1000 )
car.MoveForwardRight( 15 )
car.Pause( 1000 )
car.MoveBackward | Left( 15 )
car.Pause( 1000 )
car.MoveBackwardRight( 15 )
car.Pause( 1000 )
car.Stop()
car.Close()
###
main()
|
laborautonomo/Mailpile | mailpile/__main__.py | Python | apache-2.0 | 118 | 0 | import sys
from mailpile.app import Main
|
def main():
Main( | sys.argv[1:])
if __name__ == "__main__":
main()
|
xsuchy/tito | src/tito/distributionbuilder.py | Python | gpl-2.0 | 2,016 | 0.008433 | import os
from tito.builder import UpstreamBuilder
from tito.common import debug, run_command
class DistributionBuilder(UpstreamBuilder):
" | "" This class is used for building packages for distributions.
Parent class UpstreamBuilder build one big patch from upstream and create e.g.:
Patch0: foo-1.2.13-1-t | o-foo-1.2.13-3-sat.patch
This class create one patch per each release. E.g.:
Patch0: foo-1.2.13-1-to-foo-1.2.13-2-sat.patch
Patch1: foo-1.2.13-2-to-foo-1.2.13-3-sat.patch
"""
def __init__(self, name=None, version=None, tag=None, build_dir=None,
pkg_config=None, global_config=None, us... |
malemburg/epcon | microblog/feeds.py | Python | bsd-2-clause | 2,027 | 0.00296 | # -*- cod | ing: UTF-8 -*-
from django.conf import settings as dsettings
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.core.urlresolvers import reverse
from microblog import models
from microblog import settings
import os.path
class FeedsDict(dict):
"""
dict custom che solleva un FeedDo... | elf).__getitem__(k)
except KeyError:
raise FeedDoesNotExist()
languages = FeedsDict((l, l) for l, n in dsettings.LANGUAGES)
languages[None] = settings.MICROBLOG_DEFAULT_LANGUAGE
class LatestPosts(Feed):
def get_object(self, request, lang_code=None):
return languages[lang_code]
de... |
carloscadena/django-imager | imagersite/imager_api/tests.py | Python | mit | 2,994 | 0 | """Test modile for API."""
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import factory
from imager_images.models import Album
from imager_images.models import Photo
from imagersite.settings import MEDIA_ROOT
import os
from rest... | t_type="image/png"
)
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create albums for testing."""
class Meta(object):
"""Meta."""
model = Album
title = factory.Sequence(lambda n: "album{}".format(n))
class ApiTests(APITestCase):
"""Tests for the Api."""
def setU... | hotos = [PhotoFactory.create(profile=user.profile) for i in range(20)]
album = AlbumFactory.build()
album.profile = user.profile
album.save()
for photo in photos:
album.photos.add(photo)
album.cover_photo = photos[0]
album.save()
def tearDown(self):
... |
Architektor/PySnip | venv/lib/python2.7/site-packages/twisted/test/test_monkey.py | Python | gpl-3.0 | 5,637 | 0.001951 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.monkey}.
"""
from __future__ import division, absolute_import
from twisted.trial import unittest
from twisted.python.monkey import MonkeyPatcher
class TestObj:
def __init__(self):
self.foo = 'foo valu... | heck our test object.
self.assertEqual(self.originalObject.foo, self.testObject.foo)
self.assertEqual(self.originalObject.bar, self.testObject.bar)
self.assertEqual(self.originalObject.baz, self.testObject.baz)
def test_constructWithPatches(self):
"""
Constructing a L{Monke... | 'foo', 'haha'),
(self.testObject, 'bar', 'hehe'))
patcher.patch()
self.assertEqual('haha', self.testObject.foo)
self.assertEqual('hehe', self.testObject.bar)
self.assertEqual(self.originalObject.baz, self.testObject.baz)
def test_patchExisting(self):... |
EICT/C-BAS | src/vendor/schedule/scheduleexceptions.py | Python | bsd-3-clause | 857 | 0.009335 | from eisoil.core.exception import CoreException
|
class ScheduleException(CoreException):
def __init_ | _(self, desc):
self._desc = desc
def __str__(self):
return "Schedule: %s" % (self._desc,)
class ScheduleOverbookingError(ScheduleException):
def __init__(self, schedule_subject, resource_id, start_time, end_time):
"""All parameters should be strings or be able to str(...) itself."""
... |
alxgu/ansible | lib/ansible/module_utils/storage/emc/emc_vnx.py | Python | gpl-3.0 | 1,915 | 0.005744 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF... | ETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
emc_vnx_argument_spec = {
'sp_address': dict(type='str', required=True),
'sp_user': dict(type='str', required=False, defa... |
amimoto/walky | walky/client/common.py | Python | mit | 1,360 | 0.011029 | from __future__ import absolute_import
import weakref
import threading
import asyncore
import socket
from walky.objects import *
from walky.port import *
from walky.engine import *
class Client(object):
engine = None
settings = None
connection = None
port = None
engine_class = Engine
object... | ',self.port_class)
settings.setdefault('object_class',self.object_class)
self.port = settings.get('port')
self.settings = settings
self.reset()
def reset(self):
if self.engine: self.engine.shutdown()
self.engine = self.settings['engine_class']()
def connect(se... | ine.start()
self.connection = self.engine.connection_new(*args,**kwargs)
def run(self):
pass
def on_readline(self,line):
try:
pass
except Exception as ex:
pass
def sendline(self,line):
self.port().sendline(line)
def object_get(self,reg_... |
jluukvg/text-classifier | python/randomize_tweet_order.py | Python | mit | 957 | 0 | # -*- coding: utf-8 -*-
import os
import codecs
import random
# this is the path of the folder that will contain the tweet files
tweets_folder = os.path.join("D:", os.sep, "Documents", "PycharmProjects",
"easy_group_classifier", "text_files")
# checks i | f previous path exists, if not, it creates it
if not os.path.isdir(tweets_folder):
os.makedirs(tweets_folder)
# the name of the file with clean tweets to scramble
filename = "technology"
tweets_file = os.path.join(tweets_folder, "%s.txt" % filename)
shuffled_file = os.path.join(tweets_folder, "%s_shuffled.t... | st.append(tweet)
random.shuffle(tweet_list)
with codecs.open(shuffled_file, "wb", encoding="utf-8") as f:
for tweet in tweet_list:
f.write("%s\n" % tweet)
|
UnbDroid/robomagellan | Codigos/Raspberry/desenvolvimentoRos/build/rosserial/rosserial_arduino/catkin_generated/rosserial_arduino-extras.cmake.installspace.context.cmake.py | Python | gpl-3.0 | 1,578 | 0.003169 | # generated from catkin/cmake/template/cfg-extras.context.py.in
DEVELSPACE = 'FALSE' == 'TRUE'
INSTALLSPACE = 'TRUE' == 'TRUE'
CATKIN_DEVEL_PREFIX = '/home/pi/Documents/desenvolvimentoRos/devel'
CATKIN_GLOBAL_BIN_DESTINATION = 'bin'
CATKIN_GLOBAL_ETC_DESTINATION = 'etc'
CATKIN_GLOBAL_INCLUDE_DESTINATION = 'include'
C... | share'
CATKIN_PACKAGE_BIN_DESTINATION = 'lib/rosserial_arduino'
CATKIN_PACKAGE_ETC_DESTINATION = 'etc/rosserial_arduino'
CATKIN_PACKAGE_INCLUDE_DESTINATION = 'include/rosserial_arduino'
CATKIN_PACKAGE_LIB_DESTINATION = 'lib'
CATKIN_PA | CKAGE_LIBEXEC_DESTINATION = ''
CATKIN_PACKAGE_PYTHON_DESTINATION = 'lib/python2.7/dist-packages/rosserial_arduino'
CATKIN_PACKAGE_SHARE_DESTINATION = 'share/rosserial_arduino'
CMAKE_BINARY_DIR = '/home/pi/Documents/desenvolvimentoRos/build'
CMAKE_CURRENT_BINARY_DIR = '/home/pi/Documents/desenvolvimentoRos/build/rosser... |
HewlettPackard/oneview-ansible | test/test_oneview_ethernet_network_facts.py | Python | apache-2.0 | 4,198 | 0.001906 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2019) Hewlett Packard Enterprise Development LP
#
# 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/licen... | tedUplinkGroups']
)
PRESENT_ENETS = [{
"name": "Test Ethernet | Network",
"uri": "/rest/ethernet-networks/d34dcf5e-0d8e-441c-b00d-e1dd6a067188"
}]
ENET_ASSOCIATED_UPLINK_GROUP_URIS = [
"/rest/uplink-sets/c6bf9af9-48e7-4236-b08a-77684dc258a5",
"/rest/uplink-sets/e2f0031b-52bd-4223-9ac1-d91cb519d548"
]
ENET_ASSOCIATED_PROFILE_URIS = [
"/rest/server-profiles/83e2e117... |
illicitonion/givabit | lib/sdks/google_appengine_1.7.1/google_appengine/google/appengine/ext/appstats/datamodel_pb.py | Python | apache-2.0 | 81,798 | 0.01879 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | == 24:
self.set_total_amount_of_calls(d.getVarInt64())
continue
if tt == 32:
self.set_total_cost_of_calls_microdollars(d.getVarInt64())
continue
if tt == 42:
length = d.getVarInt32()
tmp = ProtocolBuffer.Decoder(d.buffer(), d.pos(), d.pos() + length)
| d.skip(length)
self.add_total_billed_ops().TryMerge(tmp)
continue
if (tt == 0): raise ProtocolBuffer.ProtocolBufferDeco |
AlessandroZ/LaZagne | Linux/lazagne/softwares/wifi/wifi.py | Python | lgpl-3.0 | 1,246 | 0.001605 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from lazagne.config.module_info import ModuleInfo
try:
from ConfigParser import RawConfigParser # Python 2.7
except ImportError:
from configparser import RawConfigParser # Python 3
from collections import OrderedDict
class Wifi(ModuleInfo):
d... | cp = RawConfigParser()
cp.read(os.path.join(directory, w))
values = OrderedDict()
| try:
values['SSID'] = cp.get('wifi', 'ssid')
values['Password'] = cp.get('wifi-security', 'psk')
pwd_found.append(values)
except Exception:
pass
else:
self.info('You need sud... |
richli/dame | setup.py | Python | mit | 1,201 | 0.001665 | import sys
import os.path
import subprocess
PY3 = sys.version >= '3'
from setuptools import setup, find_packages
# http://blog | s.nopcode.org/brainstorm/2013/05/20/pragmatic-python-versioning-via-setuptools-and-git-tags/
# Fetch version from git tags, and write to version.py.
# Also, when git is not available (PyPi package), use stored version.py.
version_py = os.path.join(os.path.dirname(__file__), 'dame', 'version.py')
try:
| version_git = subprocess.check_output(
["git", "describe", "--always"]).rstrip()
# Convert bytes to str for Python3
if PY3:
version_git = version_git.decode()
except:
with open(version_py, 'r') as fh:
version_git = fh.read().strip().split('=')[-1].replace('"', '')
version_msg = (... |
sserrot/champion_relationships | venv/Lib/site-packages/setuptools/command/sdist.py | Python | mit | 8,092 | 0.000124 | from distutils import log
import distutils.command.sdist as orig
import os
import sys
import io
import contextlib
from setuptools.extern import six, ordered_set
from .py36compat import sdist_add_defaults
import pkg_resources
_default_revctrl = list
def walk_revctrl(dirname=''):
"""Find all files under revisio... | self.copy_file('setup.cfg', dest)
self.get_finalized_command('egg_info').save_version_info(dest)
def _manifest_is_not_generated(self):
# check for special comment used in 2.7.1 and higher
if not os.path.isfile(self.mani | fest):
return False
with io.open(self.manifest, 'rb') as fp:
first_line = fp.readline()
return (first_line !=
'# file GENERATED by distutils, do NOT edit\n'.encode())
def read_manifest(self):
"""Read the manifest file (named by 'self.manifest') and u... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2020_12_01/operations/_virtual_machine_images_operations.py | Python | mit | 21,016 | 0.00452 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ALIZER.url("offer", offer, 'str'),
"subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
}
url = _format_url_section(url, **path_format_arguments)
# Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-versio... | i_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return H |
woozyking/techies | techies/stasistrap.py | Python | mit | 1,129 | 0.000886 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Techies' Stasis Trap
:copyright: (c) 2014 Runzhou Li (Leo)
:license: The MIT License (MIT), see LICENSE for details.
"""
import sys
from logging import Handler, NOTSET
_ref_atributes = [
'%(levelname)s',
'%(name)s',
'%(pathname)s',
'%(module)s',
... | ssage)s'
]
'''
Reference log format, best used with UniQueue or CountQueue
'''
REF_LOG_FORMAT = ':'.join(_ref_atributes)
class QueueHandler(Handler):
'''
Queue Logging Handler
Inherits standard logging.Handler that emits to any standard Queue
compatible implementations. Including the ones in techie... | er(QueueHandler, self).__init__(level)
else:
Handler.__init__(self, level)
self.q = q
def emit(self, record):
try:
self.q.put(self.format(record))
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
|
amyxchen/openhtf | test/phase_info_test.py | Python | apache-2.0 | 2,220 | 0.013964 | # Copyright 2016 Google 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 applicable law or agre... | tUp(self):
self._phase_data = mock.Mock(plug_manager=plugs.PlugManager())
def testBasics(self):
phase = openhtf.PhaseInfo.WrapOrCopy(PlainFunc)
self.assertIs(phase.func, PlainFunc)
self.assertEqual(0, len(p | hase.plugs))
self.assertEqual('PlainFunc', phase.name)
self.assertEqual('Plain Docstring', phase.doc)
phase(self._phase_data)
test_phase = openhtf.PhaseInfo.WrapOrCopy(NormalTestPhase)
self.assertEqual('NormalTestPhase', test_phase.name)
self.assertEqual('return value', test_phase(s... |
LLNL/spack | lib/spack/spack/test/cmd/python.py | Python | lgpl-2.1 | 1,190 | 0 | # 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)
import platform
import sys
import pytest
import spack
from spack.main import SpackCommand
python = SpackCommand('python... | ert out.strip() == spack.spack_version
def test_python_inte | rpreter_path():
out = python('--path')
assert out.strip() == sys.executable
def test_python_version():
out = python('-V')
assert platform.python_version() in out
def test_python_with_module():
# pytest rewrites a lot of modules, which interferes with runpy, so
# it's hard to test this. Tryi... |
maikhoepfel/daphne | daphne/cli.py | Python | bsd-3-clause | 7,303 | 0.001917 | import sys
import argparse
import logging
import importlib
from .server import Server, build_endpoint_description_strings
from .access import AccessLogGenerator
logger = logging.getLogger(__name__)
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 8000
class CommandLineInterface(object):
"""
Acts as the main CLI en... | )
self.parser.add_argument(
'-e',
'--endpoint',
| dest='socket_strings',
action='append',
help='Use raw server strings passed directly to twisted',
default=[],
)
self.parser.add_argument(
'-v',
'--verbosity',
type=int,
help='How verbose to make the output',
... |
cc13ny/Allin | jiuzhang/Nine Chapters/2 Binary Search & Sorted Array/py/SearchforaRange.py | Python | mit | 719 | 0.006954 | class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : a list of length 2, [index1, index2]
"""
def searchRange(self, A, target):
# write your code here
res = []
l, r = 0, len(A) - 1
while l <= r:
m = (l ... | 1
else:
l = m + 1
res.append(l)
l, r = 0, len(A) - 1
while l <= r:
m = (l + r) / 2
if A[m] > target:
r = m - 1
el | se:
l = l + 1
res.append(r)
if res[0] > res[1]: return [-1, -1]
return res
|
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/usersync/base.py | Python | apache-2.0 | 277 | 0.00722 | fr | om ajenti.api import *
@interface
class UserSyncProvider (BasePlugin):
allows_renaming = False
syncs_root = False
def test(self):
return False
def check_password(self, username, password):
return False
def syn | c(self):
pass |
Capitains/MyCapytain | tests/retrievers/test_cts5.py | Python | mpl-2.0 | 10,090 | 0.000892 | import unittest
import requests
import responses
from mock import patch, MagicMock
from MyCapytain.retrievers.cts5 import *
class TestEndpointsCts5(unittest.TestCase):
""" Test Cts5 Endpoint request making """
def setUp(self):
self.cts = HttpCtsRetriever("http://domainname.com/rest/cts")
def ... | y",
"request": "GetPrevNextUrn",
"urn": "urn"
}
)
def test_request_Cts_getLabel_arguments(self):
""" Tests that methods g | etLabel maps correctly to request"""
with patch('requests.get') as patched_get:
self.cts.getLabel(urn="urn", inventory="inventory")
patched_get.assert_called_once_with(
"http://domainname.com/rest/cts", params={
"inv": "inventory",
... |
kate-v-stepanova/genomics-status | status/projects.py | Python | mit | 36,140 | 0.006364 | """ Handlers for sequencing project information.
"""
import json
import string
import traceback
import tornado.web
import dateutil.parser
import datetime
import requests
import re
import paramiko
import base64
import urllib
import os
import logging
from itertools import ifilter
from collections import defaultdict
fr... | atus.util import dthandler, SafeHandler
from genologics import lims
from genologics.entities import Project
from genologics.entities import Sample
from genologics.entities import Process
from ge | nologics.entities import Artifact
from genologics.entities import Protocol
from genologics.config import BASEURI, USERNAME, PASSWORD
from zendesk import Zendesk, ZendeskError, get_id_from_url
lims = lims.Lims(BASEURI, USERNAME, PASSWORD)
application_log=logging.getLogger("tornado.application")
class PresetsHandler(S... |
psicobyte/ejemplos-python | cap5/p62.py | Python | gpl-3.0 | 112 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
corto = 10
largo = l | ong(corto)
print type(corto)
print | type(largo)
|
ininex/geofire-python | resource/lib/python2.7/site-packages/gcloud/bigtable/test_instance.py | Python | mit | 31,982 | 0 | # Copyright 2015 Google 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 applicable law or a... | test_copy(self):
display_name = 'display_name'
client = _Client(self.PROJECT)
instance = self._makeOne(self.INSTANCE_ID, client, self.LOCATION_ID,
displa | y_name=display_name)
new_instance = instance.copy()
# Make sure the client copy succeeded.
self.assertFalse(new_instance._client is client)
self.assertEqual(new_instance._client, client)
# Make sure the client got copied to a new instance.
self.assertFalse(instance is ne... |
sander76/home-assistant | tests/components/awair/test_sensor.py | Python | apache-2.0 | 9,940 | 0.000101 | """Tests for the Awair sensor platform."""
from unittest.mock import patch
from homeassistant.components.awair.const import (
API_CO2,
API_HUMID,
API_LUX,
API_PM10,
API_PM25,
API_SCORE,
API_SPL_A,
API_TEMP,
API_VOC,
ATTR_UNIQUE_ID,
DOMAIN,
SENSOR_TYPES,
)
from homeassist... | Awair mint."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, MINT_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = er.async_get(hass)
assert_expected_propertie | s(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"98",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
f"{AWAIR_UUID}... |
5y/flask | flask/testsuite/basic.py | Python | bsd-3-clause | 48,486 | 0.002311 | # -*- coding: utf-8 -*-
"""
flask.testsuite.basic
~~~~~~~~~~~~~~~~~~~~~
The basic functionality.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
import uuid
import time
import flask
import pickle
import unittest
from datetime import datetime
from... | e(rv.data) # head truncates
self.assert_equal(c.post('/more').data, b'POST')
self.assert_equal(c.get('/more').data, b'G | ET')
rv = c.delete('/more')
self.assert_equal(rv.status_code, 405)
self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])
def test_disallow_string_for_allowed_methods(self):
app = flask.Flask(__name__)
with self.assert_raises(TypeError):
@app.rou... |
pannkotsky/groupmate | backend/wsgi.py | Python | mit | 384 | 0 | """
WSGI config for p | roject.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settin... | cation()
|
PoisonBOx/PyGames | 2.Pie/drawLine.py | Python | gpl-2.0 | 453 | 0.002208 | import sys
import pygame
from pygame.locals import *
pygame.init()
screen = | pygame.display.set_mode((600, 500))
pygame.display. | set_caption("Drawing Lines")
screen.fill((0, 80, 0))
# draw the line
color = 100, 255, 200
width = 8
pygame.draw.line(screen, color, (100, 100), (500, 400), width)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type in (QUIT, KEYDOWN):
sys.exit() |
duaneg/django-hookbox | djhookbox/views.py | Python | bsd-3-clause | 5,848 | 0.007182 | # Part of django-hookbox
# Copyright 2011, Duane Griffin <duaneg@dghda.com>
from django.conf import settings
from django.dispatch import Signal
from django.http import HttpResponse
from django.template import loader, RequestContext
from django.views.decorators.csrf import csrf_exempt
import json
import logging
import... | All functions are called with the operation type and user as the first two
arguments. Operations on a channel (i.e. not connect/disconnect) will be
called with a channel | name as the third argument, and publish will be
called with the payload as the fourth argument.
If a string argument is given the function will only be called for
matching webhooks. If no argument is given it will be called for all
webhooks.
Webhooks may optionally return a result, handling of whi... |
dontnod/weblate | openshift/wsgi_install.py | Python | gpl-3.0 | 3,281 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright © 2014 Daniel Tschan <tschan@puzzle.ch>
#
# This file is part of Weblate <https://weblate.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 Foun... | round-color: #ddd;
}
p {
margin: 0 0 2em;
}
pre {
padding: 13.333px 20px;
margin: 0 0 20px;
font-size: 13px;
line-height: 1.4;
background-color: #fff;
border-left: 2px solid rgba(120,120,120,0.35);
font-family: Menlo,Monaco,"Liberation Mono",Consolas,monospace !important;
}
.content {
display: table;
... | position: relative;
min-height: 1px;
padding-left: 30px;
padding-right: 30px;
}
</style>
</head>
<body>
<div class="content">
<h1>$action1 Weblate</h1>
<p>
Weblate is being $action2.
Please wait a few minutes and refresh this page.
</p>
$log
</div>
</body>
</html>''')
context ... |
tdoughty1/mongodb_M101P | Week1/Lecture/hello_world/hello_world.py | Python | gpl-2.0 | 237 | 0.025316 | import bottle
@bottle.route('/')
def home_page():
mythings = ['apple','orange','banana','peach']
return bottle.template('hello_world', usern | ame='Todd',things= | mythings)
bottle.debug(True)
bottle.run(host='localhost', port=8082)
|
plotly/python-api | packages/python/plotly/plotly/tools.py | Python | mit | 25,137 | 0.000517 | # -*- coding: utf-8 -*-
"""
tools
=====
Functions that USERS will possibly want access to.
"""
from __future__ import absolute_import
import json
import warnings
import six
import re
import os
from plotly import exceptions, optional_imports
from plotly.files import PLOTLY_DIR
DEFAULT_PLOTLY_COLORS = [
"rgb(3... | Scatter(x=[1,2,3], y=[2,1,2], xaxis='x1', yaxis='y1')]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Example 2:
# print out string showing the subplot | grid you've put in the layout
fig = tools.get_subplots(rows=3, columns=2, print_grid=True)
Keywords arguments with constant defaults:
rows (kwarg, int greater than 0, default=1):
Number of rows, evenly spaced vertically on the figure.
columns (kwarg, int greater than 0, default=1):
N... |
ttreeagency/PootleTypo3Org | pootle/apps/pootle_app/views/index/index.py | Python | gpl-2.0 | 4,828 | 0.000414 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# 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... | 'traduire',
],
'topstats': gentopstats_root(),
'permissions': request.permissions,
'can_edit': can_edit,
'languages_table': languages_table,
'projects_table': proje | cts_table,
}
visible_langs = [l for l in languages if l['stats']['total']['words'] != 0]
templatevars['moreprojects'] = (len(projects) > len(visible_langs))
if can_edit:
from pootle_misc.siteconfig import load_site_config
from pootle_app.forms import GeneralSettingsForm
siteconf... |
zlpmichelle/crackingtensorflow | wide_deep/wide_deep.py | Python | apache-2.0 | 8,315 | 0.007216 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e(F | LAGS.train_epochs // FLAGS.epochs_per_eval):
model.train(input_fn=train_input_fn)
results = model.evaluate(input_fn=eval_input_fn)
# Display evaluation metrics
print('Results at epoch', (n + 1) * FLAGS.epochs_per_eval)
print('-' * 30)
for key in sorted(results):
print('%s: %s' % (key, res... |
tschinz/iPython_Workspace | settings/profile_wpwiki/ipython_notebook_config.py | Python | gpl-2.0 | 24,145 | 0.003686 | # Configuration file for ipython-notebook.
c = get_config()
#------------------------------------------------------------------------------
# NotebookApp configuration
#------------------------------------------------------------------------------
# NotebookApp will inherit config from: BaseIPythonApplication, Appli... | dding javascript/css to be available from the notebook server
# machine, or overriding individual files in the IPython
# c.NotebookApp.extra_static_paths = []
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
... | iles for that profile,
# then they will be staged into the new directory. Otherwise, default config
# files will be automatically generated.
# c.NotebookApp.copy_config_files = False
# The full path to a private key file for usage with SSL/TLS.
# c.NotebookApp.keyfile = u''
# Supply overrides for the tornado.web.App... |
daniellinye/HRINFG3 | euromast/components/stateManagment.py | Python | mit | 1,431 | 0.002096 | import pygame as pg
from i18n import i18n
class BaseScene(object):
"""
Parent class for individual game states to inherit from.
"""
def __init__(self, helpers=None):
self.done = False
self.quit = False
self.sounds = helpers['sounds'] if helpers else None
self.assets = he... | Handle a single event passed by the Game object.
"""
pass
def update(self, dt):
"""
Update the state. Called by the Game object once
per frame.
dt: time since last frame
"""
pass
def draw(self, surface):
"""
Draw everythi... | en.
"""
pass
|
julio77nz/MusicSea | musicsea/features/steps/register_album.py | Python | gpl-3.0 | 2,839 | 0.003875 | from behave import *
import operator
from django.db.models import Q
use_step_matcher("parse")
@given('Exists album at group "{group_name}" by "{username}"')
def step_impl(context, group_name, username):
from django.contrib.auth.models import User
user = User.objects.get(username=username)
from musicseaapp... | te', group.pk):
form = context.browser.find_by_tag('form').first
for heading in row.headings:
context.browser.fill(heading, row[heading])
form.find_by_value('Submit').first.click()
@then('I\'m viewing the details page for album at group "{group_name}" by "{username}"... | name):
q_list = [Q((attribute, context.table.rows[0][attribute])) for attribute in context.table.headings]
from django.contrib.auth.models import User
q_list.append(Q(('user', User.objects.get(username=username))))
from musicseaapp.models import Group
q_list.append(Q(('group', Group.objects.get(name... |
andersx/cs-proteins | scripts/visualize_noe.py | Python | unlicense | 1,599 | 0.003752 | import glob
import sys
import string
import Bio.PDB
def parse_noe(filename):
f = open(filename, 'r')
noe_pairs = []
for line in f.readlines():
res_a = int(string.split(line)[2])
res_b = int(string.split(line)[7])
noe_pair = [res_a, res_b]
if noe_pair n... | 5].rstrip(")")[:-1]
name_b = string.split(line)[10].rstrip(")")[:-1]
noe_pair = [res_a, res_b, name_a, name_b]
if [res_a, res_b, name_a, name_b] not in noe_pairs and \
[res_b, res_a, name_b, name_a] not in noe_pairs:
noe_pairs.append(noe_pair)
f.cl... |
noe_file = sys.argv[2]
count_restraints(noe_file)
cmd.load(native_pdb, "native")
cmd.hide("all")
cmd.show("cartoon", "native")
if noe:
for pair in parse_noe(noe_file):
cmd.distance("noe", "native and resi %i and name ca" % (pair[0]),
"native and resi %i and name ca" % (pa... |
H-uru/libhsplasma | Python/scripts/prp-checkfiles.py | Python | gpl-3.0 | 5,456 | 0.004032 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of HSPlasma.
#
# HSPlasma 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... | est="keeprepack", default=False,
help="Do not remove the temporary repacked file (h | as no effect if --check-repack is not given)")
parser.add_option("-p", "--ignore-physics",
action="store_true", dest="ignorephysics", default=False,
help="Do not compare re-packed physicals (has no effect if --check-repack is not given)")
(options, args) = parser.parse_args()
# set ... |
arielalmendral/ert | python/python/ert_gui/shell/libshell/shell_collection.py | Python | gpl-3.0 | 5,721 | 0.002972 | import shlex
import textwrap
from ert_gui.shell.libshell import autoCompleteList, ShellFunction, ShellProperty, widthAsPercentageOfConsoleWidth, getTerminalSize
class ShellCollection(object):
command_help_message = "The command: '%s' supports the following keywords:"
def __init__(self, name, parent=None, des... | tattr(self, "do_%s" % keyword)
return func(arguments)
else:
self.lastCommandFailed("Unknown keyword: '%s'" % keyword)
self.printGuidance()
def printGuidance(self):
print(self.command_help_message % self.name)
self.shellContext().shell().columnize(self.fi... | keywords = self.findKeywords()
keyword_column_width = widthAsPercentageOfConsoleWidth(20)
parameter_column_width = widthAsPercentageOfConsoleWidth(30)
help_column_width = widthAsPercentageOfConsoleWidth(48)
help_format = " %-" + str(keyword_column_width) + "s %-" + str(parameter... |
ihidalgo/uip-prog3 | Parciales/practicas/kivy-designer-master/designer/buildozer_spec_editor.py | Python | mit | 8,139 | 0.000614 | import os
import json
import tempfile
import webbrowser
import designer
from kivy.app import App |
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, ConfigParser, StringProperty
from kivy.uix.settings import Settings, InterfaceWithSidebar, MenuSidebar,\
ContentPanel, SettingsPanel
from designer.uix.settings import SettingList, SettingDict
from pygments.lexers.configs import I... | tentPanel(ContentPanel):
def on_current_uid(self, *args):
result = super(SpecContentPanel, self).on_current_uid(*args)
if isinstance(self.current_panel, SpecCodeInput):
self.current_panel.load_spec()
return result
class SpecMenuSidebar(MenuSidebar):
def on_selected_uid(se... |
MuhammadAlkarouri/hug | benchmarks/http/pyramid_test.py | Python | mit | 281 | 0 | from pyramid.view import view_config
fro | m pyramid.config import Configurator
@view_config(route_name='text', renderer='string')
def text(request):
return 'Hello, World!'
config = Configurator()
config.add_route('text', '/text')
config.scan()
app = config.make_wsgi_ | app()
|
samrushing/caesure | docs/match.py | Python | bsd-2-clause | 11,932 | 0.011314 | # -*- Python -*-
# XXX originally from the python implementation of irken.
# See "The Implementation of Functional Programming Languages",
# Chapter 5: "Efficient Compilation of Pattern-Matching".
# http://research.microsoft.com/en-us/um/people/simonpj/papers/slpj-book-1987/
#
# Thanks for the hint, OCaml people! (Xa... | name.split (':')
self.subs = subs
def __len__ (self):
# arity of this constructor
ret | urn len (self.subs)
def __repr__ (self):
return '(%s/%s %s)' % (self.datatype, self.alt, ' '.join ([repr(x) for x in self.subs]))
# bad match
class MatchError (Exception):
pass
class IncompleteMatch (Exception):
pass
FAIL = ['%%fail']
ERROR = ['%%match-error']
# The next step in this code is to... |
Captain-Coder/tribler | Tribler/Core/Modules/restapi/events_endpoint.py | Python | lgpl-3.0 | 13,739 | 0.005968 | from twisted.web import server, resource
from Tribler.Core.Modules.restapi.util import convert_db_channel_to_json, convert_search_torrent_to_json, \
fix_unicode_dict
from Tribler.Core.simpledefs import (NTFY_CHANNELCAST, SIGNAL_CHANNEL, SIGNAL_ON_SEARCH_RESULTS, SIGNAL_TORRENT,
... | tor that Tribler has completed the startup procedure and is ready to use.
- channel_discovered: An indicator that Tribler has discovered a new channel. The event contains the name,
description and dispersy community id of the discovered channel.
- torrent_discovered: An indicator that Tribler has discover... | sy community id of the discovered torrent.
- torrent_removed_from_channel: An indicator that a torrent has been removed from a channel. The event contains
the infohash and the dispersy id of the channel which contained the removed torrent.
- torrent_finished: A specific torrent has finished downloading. T... |
grow/pygrow | grow/templates/tests_test.py | Python | mit | 2,013 | 0 | """Tests for the template tests."""
import unittest
from grow.templates import tests
class BuiltinTestsTestCase(unittest.TestCase):
def test_subset_filter(self):
"""Provided value is a subset when has all the required values."""
value = ['banana', 'apple']
test_value = ['banana']
... | et_filter_equal(self):
"""Provided value is a superset when equal."""
value = ['banana']
test_value = ['banana']
self.assertTrue(tests.is_superset_of(value, test_value))
def test_superset_filter_not(self):
"""Provided value is not a superset when has extra values."""
... | 'banana']
self.assertFalse(tests.is_superset_of(value, test_value))
def test_superset_filter_none(self):
"""Provided value is a superset when both are blank."""
value = []
test_value = []
self.assertTrue(tests.is_superset_of(value, test_value))
if __name__ == '__main__':
... |
anurag03/integration_tests | cfme/tests/containers/test_cockpit.py | Python | gpl-2.0 | 2,473 | 0.002426 | import pytest
from cfme.containers.provider import ContainersProvider
from cfme.markers.env_markers.provider import providers
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.providers import ProviderFilter
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.usefixtures... | reason='Cockpit Feature is only available in 5.9 and greater')
@pytest.mark.parametrize('cockpit', [False, True], ids=['disabled', 'enabled'])
def test_cockpit_button_access(appliance, provider, cockpit, request):
""" The test verifies the existence of cockpit "Web Console"
button on ... | splayed.
"""
request.addfinalizer(lambda: appliance.server.settings.disable_server_roles('cockpit_ws'))
if cockpit:
appliance.server.settings.enable_server_roles('cockpit_ws')
wait_for(lambda: appliance.server_roles['cockpit_ws'] is True, delay=10, timeout=300)
elif not cockpit:
... |
michal-stuglik/django-blastplus | manage.py | Python | mit | 283 | 0 | #!/ | usr/bin/env python
import os
import sys
if __name__ == "__main__":
# testing environment
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blastplus.test_settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) | |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/numpy/distutils/exec_command.py | Python | mit | 8,663 | 0.003925 | """
exec_command
Implements exec_command function that is (almost) equivalent to
commands.getstatusoutput function but on NT, DOS systems the
returned status is actually correct (though, the returned status
values may be different by a factor). In addition, exec_command
takes keyword arguments for (re-)defining enviro... | concatenated string of executable and arguments.
execute_in : str
Before running command ``cd execute_in`` and after ``cd -``.
use_shell : {bool, None}, optional
If True, execute ``sh -c command``. Default None (True)
use_tee : {bool, None}, o | ptional
If True use tee. Default None (True)
Returns
-------
res : str
Both stdout and stderr messages.
Notes
-----
On NT, DOS systems the returned status is correct for external commands.
Wild cards will not work for non-posix systems or when use_shell=0.
"""
log... |
eCrowdMedia/ebooklib | docs/conf.py | Python | agpl-3.0 | 9,313 | 0.007516 | # -*- coding: utf-8 -*-
#
# EbookLib documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 25 11:49:49 2014.
#
# 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
# autogenerated file.
#
# Al... | theme, see the
# documentation.
#html_theme_opt | ions = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#... |
arsfeld/conduit | test/python-tests/TestSyncGConfFolder.py | Python | gpl-2.0 | 1,001 | 0.022977 | #common sets up the conduit environment
from common import *
#setup test
test = | SimpleSyncTest()
#Setup the key to sync
gconf = test.get_dataprovider("GConfTwoWay")
gconf.module.whitelist = ['/apps/metacity/general/num_workspaces']
folder = test.get_dataprovider("TestFolderTwoWay")
test.prepare(gconf, folder)
test.set_two_way_policy({"conflict":"ask","deleted":"ask"})
test.set_two_way_sync(True... | #Now modify the file
f = folder.module.get(
folder.module.get_all()[0]
)
f._set_file_mtime(datetime.datetime(2008,1,i))
a,b = test.sync()
aborted,errored,conflicted = test.get_sync_result()
ok("Sync #%s: Completed without conflicts" % i, aborted == False ... |
bendoran/vogen | src/vogen/as3parser.py | Python | mit | 2,621 | 0.021366 | import re
from vogen.voparser import VoParser, VoVariable
class AS3VoParser( VoParser ):
def parse( self, input_string, verbose ):
self.input_string = input_string
self.verbose = verbose
class_names = re.findall(r"class (\w+)", self.input_string );
#Find the class_... | eturn_text += "\n\t\t){"
for variable in variables :
return_text += "\n\t\t\tthis._" + variable.variable_name + " = " + variable.variable_name + ";"
return_text += "\n\t\t}"
#A bit of White Space
return_tex | t += "\n"
#Print the Getters
for variable in variables :
return_text += "\n\t\tpublic function get " + variable.variable_name + "() : " + variable.variable_type + "{"
return_text += "\n\t\t\treturn this._" + variable.variable_name + ";"
return_text += "\n\t\t... |
dextervip/rpv | GerenDisponibilidade/professor/tests.py | Python | gpl-3.0 | 810 | 0.007407 | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from professor.models | import Professor, DiaSemana, DisponibilidadeAula
from professor.models import Professor, DiaSemana, DisponibilidadeAula
class SimpleTest(TestCase):
def adicionaDisponibilidade(self):
p = Professor.objects.get(id=1)
p.informarDisponibilidade("qua", "14:30")
p = Professor... | 0].diaSemana.nome_curto, "qua")
self.assertEqual(result[0].diaSemana.nome_curto, "quar") |
tiredpixel/pikka-bird-collector-py | pikka_bird_collector/collectors/mysql.py | Python | mit | 5,160 | 0.00814 | from pikka_bird_collector.parsers.table import Table as Parser
from .base_port_command import BasePortCommand, Base
class Mysql(BasePortCommand):
"""
Collector for MySQL (https://www.mysql.com/).
The collector is enabled whenever non-empty settings are passed.
Multiple instances r... | values are remapped if they match these. This
probably won't cause you problems, but if encounter a string which is no
longer a string, this is probably why. :)
DEPENDENCIES:
mysql
Available in PATH.
SETTINGS:
minimal:
... | USER",
'password': "PASSWORD",
'collect': {
'master_status': False,
'slave_status': False,
'slave_hosts': False,
'variables': True}}}
"""
... |
uvchik/pvlib-python | pvlib/test/test_atmosphere.py | Python | bsd-3-clause | 5,239 | 0.005535 | import itertools
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_allclose
from pvlib import atmosphere
from pvlib import solarposition
latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700
times = p | d.date_range(start='20140626', end='20140626', freq='6h', tz=tz)
ephem_data = solarposition.get_solarposition(times, latitude, longitude)
# need to add physical tests instead of just functional tests
def test_pres2alt():
atmosphere.pres2alt(100000)
def test_alt2press():
atmosphere.pres2alt(1000)
@pytest... | t = atmosphere.relativeairmass(ephem_data['zenith'], model)
assert isinstance(out, pd.Series)
out = atmosphere.relativeairmass(ephem_data['zenith'].values, model)
assert isinstance(out, np.ndarray)
def test_airmass_scalar():
assert not np.isnan(atmosphere.relativeairmass(10))
def test_airmass_scalar... |
dsavransky/miscpy | miscpy/PlotFun/logHist.py | Python | mit | 1,435 | 0.013937 | import matplotlib.pyplot as plt
import numpy as np
def logHist(X, N=30,fig=None, noclear=False, pdf=False, **kywds):
'''
Plot logarithmic histogram or probability density function from
sampled data.
Args:
X (numpy.ndarray): 1-D array of sampled values
N (Optional[int]): Number of bins ... |
x (ndarray): abscissa values of frequencies
n (ndarray): (normalized) frequency values
'''
x = np.logspace(np.log10(np.min(X)),np.log10(np.max(X)),N+1)
n,x = np.histogram(X,bins=x)
n = n/float(X.size)
plt.figure(fig)
if not noclear: plt.clf()
if pdf:
n /= np.... | plt.bar(x[:len(x)-1],n,width=np.diff(x),**kywds)
a = plt.gca()
a.set_xlim(10.**np.floor(np.log10(np.min(X))),10.**np.ceil(np.log10(np.max(X))))
a.set_xscale('log')
plt.axis()
return x,n
|
sfu-fas/coursys | quizzes/management/commands/special_case_tutorial.py | Python | gpl-3.0 | 1,849 | 0.005408 | """
Create quiz TimeSpecialCase for all students in a particular lab/tutorial section.
Usage will be like:
./manage.py special_case_tutorial 2020su-cmpt-120-d1 q1 D101 '2021-10-07T09:30' '2021-10-07T10:30'
"""
import datetime
from django.core.management.base import BaseCommand
from django.db import transaction
from ... | _time', type=parse_datetime, help='end time for this section')
def handle(self, *args, **options):
offering_slug = options['offering_slug']
activity_slug = options['activity_slug']
section = options['section']
start_time = options['s | tart_time']
end_time = options['end_time']
offering = CourseOffering.objects.get(slug=offering_slug)
quiz = Quiz.objects.get(activity__slug=activity_slug, activity__offering=offering)
members = Member.objects.filter(offering=offering, role='STUD', labtut_section=section)
with t... |
Elec/django-recaptcha | captcha/widgets.py | Python | bsd-3-clause | 1,285 | 0 | # -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
from captcha import client
class ReCap | tcha(forms.widgets.Widget):
if getattr(settings, "RECAPTCHA_NOCAPTCHA", False):
recaptcha_response_name = 'g-recaptcha-response'
recaptcha_challenge_name = 'g-recaptcha-response'
else:
recaptcha_challenge_name = | 'recaptcha_challenge_field'
recaptcha_response_name = 'recaptcha_response_field'
def __init__(self, public_key=None, use_ssl=None, attrs={}, *args,
**kwargs):
self.public_key = public_key if public_key else \
settings.RECAPTCHA_PUBLIC_KEY
self.use_ssl = use_ssl ... |
Huyuwei/tvm | tests/python/relay/test_cpp_build_module.py | Python | apache-2.0 | 4,614 | 0.001734 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | e gpu does not support fp16")
r | eturn
n = 10
for (src, dst) in [('float32', 'float16'), ('float16', 'float32')]:
x = relay.var("x", relay.TensorType((n,), src))
y = x.astype(dst)
func = relay.Function([x], y)
# init input
X = tvm.nd.array(n * np.random.randn(n).astype(src)... |
mezz64/home-assistant | homeassistant/components/hangouts/__init__.py | Python | apache-2.0 | 4,741 | 0.001476 | """Support for Hangouts."""
import logging
from hangups.auth import GoogleAuthError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.conversation.util import create_matcher
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASS... | ig entry."""
try:
bot = HangoutsBot(
hass,
config.data.get(CONF_REFRESH_TOKEN),
hass.data[DOMAIN][CONF_INTENTS],
hass.data[DOMAIN][CONF_DEFAULT_CONVERSATIONS],
hass.data[DOMAIN][CONF_ERROR_SUPPRESSED_CONVERSATIONS],
)
hass.data[DOMA... | )
return False
dispatcher.async_dispatcher_connect(
hass, EVENT_HANGOUTS_CONNECTED, bot.async_handle_update_users_and_conversations
)
dispatcher.async_dispatcher_connect(
hass, EVENT_HANGOUTS_CONVERSATIONS_CHANGED, bot.async_resolve_conversations
)
dispatcher.async_dispatc... |
dsarlis/Cloud-Burst | etl/process.py | Python | apache-2.0 | 258 | 0.007752 | from sys import argv
for line | in open(argv[1]):
tweet_id, hashtags, hashtags_count, user_id, created_at, followers_count, score, text = line.replace('\n', '').split('\t')
print ','.join([tweet_id, user_id, created_at, followers_count, score, text] | )
|
sagiss/sardana | src/sardana/taurus/qt/qtgui/extra_sardana/expdescription.py | Python | lgpl-3.0 | 19,906 | 0.00628 | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... | urceModel.index(sourceRow, 0, sourceParent)
# item = idx.internalPointer()
# return 'Acquirable' in item.itemData().interfaces
# ALLOWED_TYPES = ['Motor', 'CTExpChannel', 'ZeroDExpChannel', 'OneDExpChannel',
# 'TwoDExpChannel', 'ComChannel', 'IORegiste | r', 'PseudoMotor',
# 'PseudoCounter']
from sardana.sardanadefs import ElementType, TYPE_ACQUIRABLE_ELEMENTS
ALLOWED_TYPES = [ElementType[t] for t in TYPE_ACQUIRABLE_ELEMENTS]
def filterAcceptsRow(self, sourceRow, sourceParent):
sourceModel = self.sourceModel()
idx = sou... |
anhstudios/swganh | data/scripts/templates/object/tangible/loot/loot_schematic/shared_geonosian_reinforcement_core_schematic.py | Python | mit | 527 | 0.043643 | #### NOTICE: THIS FIL | E IS AUTOGENERATED
#### MODIFICAT | IONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/loot_schematic/shared_geonosian_reinforcement_core_schematic.iff"
result.attribute_template_id = -1
result.stfName(... |
stefanseefeld/numba | numba/npyufunc/__init__.py | Python | bsd-2-clause | 809 | 0.001236 | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
from .decorators import Vectorize, GUVectorize, vectorize, guvectorize
from ._internal import PyUFunc_None, PyUFunc_Zero, PyUFunc_One
from . import _internal, array_exprs
if hasattr(_internal, 'PyUFunc_ReorderableNone'):
PyUFu... |
def _init():
def init_vectorize():
from numba.cuda.vectorizers import CUDAVectorize
return CUDAVectorize
def init_guvectorize():
from numba.cuda.vectorizers import CUDAGUFuncVecto | rize
return CUDAGUFuncVectorize
Vectorize.target_registry.ondemand['cuda'] = init_vectorize
GUVectorize.target_registry.ondemand['cuda'] = init_guvectorize
_init()
del _init
|
ncdesouza/bookworm | env/lib/python2.7/site-packages/sqlalchemy/ext/mutable.py | Python | gpl-3.0 | 23,156 | 0.000043 | # ext/mutable.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Provide support for tracking of in-place changes to scalar values,
which are propa... | etstate__)::
class MutableDict(Mutable, d | ict):
# ....
def __getstate__(self):
return dict(self)
def __setstate__(self, state):
self.update(state)
In the case that our mutable value object is pickled as it is attached to one
or more parent objects that are also part of the pickle, the :class:`.Mutable`
mixin w... |
messagebird/python-rest-api | examples/voice_message.py | Python | bsd-2-clause | 1,642 | 0.017052 | #!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import messagebird
# ACCESS_KEY = ''
# MESSAGE_ID = ''
try:
ACCESS_KEY
except NameError:
print('You need to set an ACCESS_KEY constant in this file')
sys.exit(1)
try:
MESSAGE_ID
except NameError:
print('Yo... | object for the specified MESSAGE_ID.
vmsg = client.voice_message(MESSAGE_ID)
# Print the object information.
print('\nThe following information was returned as a VoiceMessage object:\n')
print(' id : %s' % vmsg.id)
print(' href : %s' % vmsg.href)
print(' originator : ... | dy)
print(' reference : %s' % vmsg.reference)
print(' language : %s' % vmsg.language)
print(' voice : %s' % vmsg.voice)
print(' repeat : %s' % vmsg.repeat)
print(' ifMachine : %s' % vmsg.ifMachine)
print(' scheduledDatetime : %s' % vmsg.scheduledDatetime... |
brandonPurvis/osf.io | tests/test_auth.py | Python | apache-2.0 | 13,540 | 0.000517 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from nose.tools import * # noqa; PEP8 asserts
from webtest_plus import TestApp
import mock
import httplib as http
from flask import Flask
from modularodm import Q
from werkzeug.wrappers import BaseResponse
from framework import auth
from framework.auth im... | rt_equal(User.load(user._id), user)
def test_get_user_by_email(self):
user = UserFactory()
assert_equal(auth.get_user(email=user.username), user)
def test_get_user_with_wrong_password_returns_false(self):
user = UserFactory.build()
user.set_password('killerqueen')
asser... | )
class TestAuthObject(OsfTestCase):
def test_repr(self):
auth = AuthFactory()
rep = repr(auth)
assert_in(str(auth.user), rep)
def test_factory(self):
auth_obj = AuthFactory()
assert_true(isinstance(auth_obj.user, auth.User))
def test_from_kwargs(self):
... |
shtripat/gluster_bridge | tendrl/gluster_bridge/flows/set_volume_option.py | Python | lgpl-2.1 | 705 | 0 | import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = ap | i_job
self.atom = SetVolumeOption
def start(self):
attributes = json.loads(self.api_job[' | attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id']... |
caioserra/apiAdwords | examples/adspygoogle/dfp/v201308/get_user_team_association.py | Python | apache-2.0 | 1,916 | 0.001566 | #!/usr/bin/python
#
# Copyright 2013 Google 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 b... | oin('..', '..', '..', '..'))
# Initialize appropriate service.
user_team_association_service = client.GetService(
'UserTeamAssociationService', version='v201308')
# Set the IDs of th | e user and team to get the association for.
user_id = 'INSERT_USER_ID_HERE'
team_id = 'INSERT_TEAM_ID_HERE'
# Get user team association.
user_team_association = user_team_association_service.GetUserTeamAssociation(
team_id, user_id)[0]
# Display results.
print ('User team association between user with ID \'%s\' a... |
arielalmendral/ert | python/python/ert_gui/ide/keywords/definitions/range_string_argument.py | Python | gpl-3.0 | 2,862 | 0.004892 | import re
from ert_gui.ide.keywords.definitions import ArgumentDefinition
class RangeStringArgument(ArgumentDefinition):
NOT_A_VALID_RANGE_STRING = "The input should be of the type: <b><pre>\n\t1,3-5,9,17\n</pre></b>i.e. integer values separated by commas, and dashes to represent ranges."
VALUE_NOT_IN_RANGE ... | ent.NOT_A_VALID_RANGE_STRING)
break
if self.__max_value is not None and (num_1 >= self.__max_value or num_2 >= self.__max_value):
| validation_status.setFailed()
validation_status.addToMessage(RangeStringArgument.VALUE_NOT_IN_RANGE % (self.__max_value - 1))
break
if number_match and self.__max_value is not None:
num = int(number_match.gr... |
fxia22/ASM_xf | PythonD/site_python/twisted/im/tocsupport.py | Python | gpl-2.0 | 8,589 | 0.014321 | # Twisted, the Framework of Your Internet
# Copyright (C) 2001-2003 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed i... | mID[roomname]=roomid
self.roomIDreverse[roomid]=roomname
self.getGroupConversation(roomname | ).setGroupMembers(users)
def chatUpdate(self,roomid,member,inroom):
group=self.roomIDreverse[roomid]
if inroom:
self.getGroupConversation(group).memberJoined(member)
else:
self.getGroupConversation(group).memberLeft(member)
def chatHearMessage(self, roomid, userna... |
lgh8820/ansible-test | yjy_all_scripts/clear_arch_tables.py | Python | mit | 630 | 0.036508 | #!/usr/bin/env python
# -*- coding=utf8 -*-
"""clear the mysql database yjy_archtecture tables in aa.txt"""
import MySQLdb as mdb
db_conn = mdb.connect("localhost","root","HEkgDDZZ","yjy_human")
cursor = d | b_conn.cursor()
with open("/root/scripts/clear_human_sql.tables") as f:
| tables = f.readlines()
print tables
try:
for table in tables:
tb = table.strip()
print tb
sql = """TRUNCATE TABLE """+ tb
cursor.execute(sql)
data = cursor.fetchall()
print data
sql1 = """select * from """+ tb
cursor.execute(sql1)
data1 = cursor.fetchall()
print data1
except mdb.Erro... |
JeremyRubin/bitcoin | test/functional/p2p_leak.py | Python | mit | 7,392 | 0.001894 | #!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test message sending before handshake completion.
Before receiving a VERACK, a node should not send an... | ich start at nVersion == 70016
pre_wtxidrelay_peer = self.nodes[0].add_p2p_connection(NoVerackIdlePeer(), send_version=False, wait_for_verack=False)
pre_wtxidrelay_peer.send_message(self.create_old_version(70015))
# Wait until the peer gets the verack in response to the version. Though, don't w... | _peer.wait_for_verack()
pre_wtxidrelay_peer.wait_for_verack()
no_version_idle_peer.wait_until(lambda: no_version_idle_peer.ever_connected)
no_verack_idle_peer.wait_until(lambda: no_verack_idle_peer.version_received)
pre_wtxidrelay_peer.wait_until(lambda: pre_wtxidrelay_peer.version_rece... |
johnkerl/scripts-math | pythonlib/randmatc_m.py | Python | bsd-2-clause | 1,088 | 0.02114 | #!/usr/bin/python -Wall
# ================================================================
# Joh | n Kerl
# kerl.john.r@gmail.com
# 2008-02-06
# ================================================================
from __future__ import division # 1/2 = 0.5, not 0.
imp | ort sys
import randc_m # For random complex scalars
import math
from sackmatc_m import *
# ----------------------------------------------------------------
def randmatc(m, n):
A = make_zero_matrix(m, n)
for i in range(0, m):
for j in range(0, n):
A[i][j] = randc_m.randc_mean_sq_1()
return A
# ----------------... |
frostblooded/kanq | api/models/medal.py | Python | mit | 373 | 0.002681 | from django.db import models
from .user import User
from .post import Post
class Medal(models.Model):
rank = models.Int | egerField()
user = models.ForeignKey(User, relat | ed_name='medals')
post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name='medal')
def __str__(self):
return "%s %s" % (self.post.title, self.rank)
|
diego-d5000/MisValesMd | env/lib/python2.7/site-packages/django/core/management/commands/makemessages.py | Python | mit | 22,994 | 0.003305 | from __future__ import unicode_literals
import fnmatch
import glob
import io
import os
import re
import sys
from itertools import dropwhile
import django
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.core.management.utils import (
find... | command with one of either the "
"--locale, --exclude or --all options.")
requires_system_checks = False
leave_locale_alone = True
msgmerge_options = ['-q', '--previous']
msguniq_options = ['--to- | code=utf-8']
msgattrib_options = ['--no-obsolete']
xgettext_options = ['--from-code=UTF-8', '--add-comments=Translators']
def add_arguments(self, parser):
parser.add_argument('--locale', '-l', default=[], dest='locale', action='append',
help='Creates or updates the message files f... |
beblount/Steer-Clear-Backend | tests/forms_tests.py | Python | mit | 3,278 | 0.00061 | from steerclear import app
from steerclear.forms import RideForm
from steerclear.models import *
import unittest, flask
"""
RideFormTestCase
----------------
Test class for the RideForm class
"""
class RideFormTestCase(unittest.TestCase):
"""
submit_form
-----------
helper method to submit a RideForm ... | ssengers": 4,
u"start_latitude": 1.1,
u"start_l | ongitude": 2.2,
u"end_latitude": 3.3,
u"end_longitude": 4.4,
}
"""
test_ride_form_correct_submit
-----------------------------
Tests that a RideForm can be validated correctly
"""
def test_ride_form_correct_submit(self):
result = self.submit_form(self.pay... |
dbiesecke/dbiesecke.github.io | repo/script.module.urlresolver/lib/urlresolver/plugins/bitporno.py | Python | mit | 1,372 | 0.005831 | '''
urlresolver XBMC Addon
Copyright (C) 2017
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 t | he License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implie | d warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from urlresolver.plugins.__generic_resolver__ import Generic... |
grodrigo/django_general | persons/urls.py | Python | gpl-3.0 | 427 | 0 | from django.conf.urls import url
from . import views
app_name = 'persons'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^thanks/$', views.thanks, name='thanks'),
url(r'^upload/$', | views.upload_file, name='upload_file'),
url(r'^success/$', views.success, name='success'),
url(r'^uploadImage/$', views.uploadImage, name=' | uploadImage'),
]
|
l5h5t7/ZeroNet | src/Test/TestFileRequest.py | Python | gpl-2.0 | 3,984 | 0.00251 | import cStringIO as StringIO
import pytest
import time
from Connection import ConnectionServer
from Connection import Connection
from File import FileServer
@pytest.mark.usefixtures("resetSettings")
@pytest.mark.usefixtures("resetTempSettings")
class TestFileRequest:
def testGetFile(self, file_server, site):
... | e_server.sites[site.address] = site
buff = StringIO.StringIO()
response = connection.reque | st("streamFile", {"site": site.address, "inner_path": "content.json", "location": 0}, buff)
assert "stream_bytes" in response
assert "sign" in buff.getvalue()
# Invalid file
buff = StringIO.StringIO()
response = connection.request("streamFile", {"site": site.address, "inner_path... |
PisiLinuxNew/gonullu | gonullu/__init__.py | Python | gpl-3.0 | 132 | 0 | from gonullu.farm import | Farm
from gonullu.docker import Docker
from g | onullu.volunteer import Volunteer
from gonullu.log import Log
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.