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 |
|---|---|---|---|---|---|---|---|---|
luisibanez/cloud-whisperer | Rackspace/getListOfImages.py | Python | apache-2.0 | 1,726 | 0.00927 | #!/usr/bin/python
#---------------------------------------------------------------------------
# Copyright 2011 The Open Source Electronic Health Record Agent
#
# 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... | //www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions a... | --------------------------------------------------------------
#
# Retrieves the list of available images from the Cloud service.
#
# This script expects to find the token.json file in the 'Session' directory.
# That file should have been created during the authentication stage.
#
# The response is put in the file:
#
#... |
liqd/a4-meinberlin | tests/extprojects/dashboard_components/test_views_extproject_basic.py | Python | agpl-3.0 | 3,909 | 0 | import pytest
from dateutil.parser import parse
from adhocracy4.dashboard import components
from adhocracy4.test.helpers import redirect_target
from meinberlin.apps.extprojects.phases import ExternalPhase
from meinberlin.test.helpers import assert_dashboard_form_component_response
from meinberlin.test.helpers import s... | public == data.get('is_public')
assert external_project.url == data.get('url')
assert external_project.proje | ct_type == \
'meinberlin_extprojects.ExternalProject'
phase.refresh_from_db()
assert phase.start_date == parse("2013-01-01 17:00:00 UTC")
assert phase.end_date == parse("2013-01-10 17:00:00 UTC")
@pytest.mark.django_db
def test_edit_view_group_member(
client, phase_factory, external_projec... |
google/or-tools | examples/contrib/volsay.py | Python | apache-2.0 | 1,860 | 0.015054 | # Copyright 2011 Hakan Kjellerstrand hakank@gmail.com
#
# 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 ... | pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CLP_LINEAR_PROGRAMMING)
# data
# declare variables
Gas = solver.NumVar(0, 100000, 'Gas')
Chloride = solver.NumVar(0, 1000 | 00, 'Cloride')
#
# constraints
#
solver.Add(Gas + Chloride <= 50)
solver.Add(3 * Gas + 4 * Chloride <= 180)
# objective
objective = solver.Maximize(40 * Gas + 50 * Chloride)
print('NumConstraints:', solver.NumConstraints())
#
# solution and search
#
solver.Solve()
print()
print('objecti... |
fruser/tagfind | tagfind/log_info.py | Python | mit | 633 | 0.017378 | import logging
from logging.config import dictConfig
def logger():
logging_config = dict(
version | = 1,
formatters = {
'f': {'format':
'%(asctime)s %(levelname)-8s %(message)s'}
},
handlers = {
'h': {'class': 'logging.StreamHandler',
'formatter': 'f',
| 'level': logging.DEBUG}
},
root = {
'handlers': ['h'],
'level': logging.DEBUG,
},
)
dictConfig(logging_config)
return logging.getLogger()
def main():
pass
if __name__ == '__main__':
main() |
barshow/Stino | stino/pyarduino/arduino_compiler.py | Python | mit | 22,629 | 0.00053 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# 1. Copyright
# 2. Lisence
# 3. Author
"""
Documents
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import threading
import subprocess
import re
import ti... | h != last_sketchbook_path or \
target_board_id != last_board_id or \
target_sub_board_ids != last_sub_board_ids or \
bare_gcc != last_bare_gcc or big_project != last_big_project:
last_build_file.set('ide_path', ide_path)
las | t_build_file.set('sketchbook_path', sketchbook_path)
last_build_file.set('board_id', target_board_id)
last_build_file.set('sub_board_ids', target_sub_board_ids)
last_build_file.set('bare_gcc', bare_gcc)
last_build_file.set('big_project', big_project)
self.is_n... |
unhammer/hfst3 | old_python/test/test_transducer_functions.py | Python | gpl-3.0 | 12,958 | 0.006019 | import libhfst
def compare_alphabets(t1, t2):
alpha1 = t1.get_alphabet()
alpha2 = t2.get_alphabet()
return alpha1 == alpha2
types = [libhfst.SFST_TYPE, libhfst.TROPICAL_OPENFST_TYPE, libhfst.FOMA_TYPE]
for type in types:
if not libhfst.HfstTransducer.is_implementation_type_available(type):
... | hfst.HfstTransducer("hippopotamus", "hippopotami", tok, type)
hippopotamus1.set_final_weights(1.2)
hippopotamus2 = libhfst.HfstTransducer("hippopotamus", "hippopotamuses", tok, type)
hippopotamus2.set_final_weights(1.4)
animals.disjunct(hippopotamus1)
animals.disjunct(hippopotamus2)
animals.mini... | aths(animals, 5, 0)
#print results
# Convert into optimized lookup format
animals_ol = libhfst.HfstTransducer(animals)
if type == libhfst.TROPICAL_OPENFST_TYPE:
animals_ol.convert(libhfst.HFST_OLW_TYPE)
else:
animals_ol.convert(libhfst.HFST_OL_TYPE)
result = libhfst.detoken... |
amiv-eth/amivapi | amivapi/tests/studydocs/test_summary.py | Python | agpl-3.0 | 1,869 | 0 | # -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Tests for studydocuments summaries."""
import json
from amivapi.tests.utils import WebTestNoAuth
class StudydocsSummaryTest(WebTestNoAuth):
... | puted for the matched documents."""
self._load_data()
match = json.dumps({'title': {'$in': ['first', 'second']}})
respons | e = self.api.get("/studydocuments?where=%s" % match,
status_code=200).json
assert '_summary' in response
assert response['_summary'] == {
'lecture': {
'a': 2,
},
'professor': {
'a': 1,
'b... |
kugel-/peasy | plugins/peasypytest.py | Python | gpl-3.0 | 1,239 | 0.008071 | from __future__ impor | t print_function
import gettext
import gi
gi.require_version('Peas', '1.0')
from gi.repository import GObject
from gi.repository | import Peas
from gi.repository import Peasy
from gi.repository import Geany
gettext.bindtextdomain("peasy", "/home/kugel/dev/geany.git/build-linux/dest/share/locale")
gettext.textdomain("peasy")
_ = gettext.gettext
class PeasyPyTester(Peasy.Plugin, Peasy.PluginHelp):
__gtype_name = 'PeasyPyTester'
object = G... |
beardypig/streamlink | tests/test_plugin_utils.py | Python | bsd-2-clause | 3,845 | 0.002081 | import sys
import unittest
from streamlink.plugin.api.utils import itertags
def unsupported_versions_1979():
"""Unsupported python versions for itertags
3.7.0 - 3.7.2 and 3.8.0a1
- https://github.com/streamlink/streamlink/issues/1979
- https://bugs.python.org/issue34294
"""
v = sys.v... | ertTrue(len(links), 1)
self.assertEqual(links[0].tag, "link")
self.assertEqual(links[0].text, None)
self.assertEqual(links[0].attributes, {"rel": "stylesheet",
"type": "text/css",
"href": "https://test.... | )
self.assertTrue(len(links), 1)
self.assertEqual(links[0].tag, "p")
self.assertEqual(links[0].text.strip(), '<a \nhref="http://test.se/foo">bar</a>')
self.assertEqual(links[0].attributes, {})
|
mcowger/python-cloudfoundry | setup.py | Python | mit | 820 | 0.003659 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages
from distutils.core import setup
setup(
author=u'Matt Cowger',
author_email='matt@cowger.us',
name='python-cloudfoundry2',
description='Python interface to CloudFoundry v2 API',
version="0.1",
url='https://github... |
license='MIT License',
packages = find_packages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language | :: Python',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
install_requires=[
open("requirements.txt").readlines(),
],
) |
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/plugins/network/api.py | Python | apache-2.0 | 1,407 | 0 | import psutil
from ajenti.api import *
from ajenti.ui import *
@plugin
class NetworkManager (BasePlugin):
def get_devices(self):
return psutil.net_io_counters(pernic=True).keys() |
@interface
class INetworkConfig (object):
interfaces = {}
@property
def interface_list(self):
return self.interfaces.values()
def rescan(self):
pass
def save(self):
pass
@interface
class INetworkConfigBit (object):
def apply(self):
| pass
@plugin
class NetworkConfigBit (UIElement, INetworkConfigBit):
cls = 'unknown'
iface = None
title = 'Unknown'
typeid = 'box'
class NetworkInterface(object):
def __init__(self):
self.up = False
self.auto = False
self.name = ''
self.devclass = ''
s... |
Team02-TeamGuinness/BIOE421_RoboHand | ablation-GUI/CONFIG/2014-October-30/11-13-41 AM ParamScan-testing_z1-CONFIG.py | Python | gpl-2.0 | 595 | 0.065546 | #File
fname = 'ParamScan-testing_z1.gcode'
f=open(fname,'w')
#Laser Parameters
laserPower = 10 #% max power
dwellTime = 7 #ms
x_start = 398
y_start = 343
z_start = 122.85 #mm above home
pauseTime = 500 #ms; time paused after movement before ablation
feedRate = 500 #movement spe... | lready | been homed |
jolevq/odoopub | openerp/addons/base/ir/ir_ui_view.py | Python | agpl-3.0 | 54,182 | 0.003857 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ('graph', 'Graph'),
('calendar', 'Calendar'),
('diagram','Diagram'),
| ('gantt', 'Gantt'),
('kanban', 'Kanban'),
('search','Search'),
('qweb', 'QWeb')], string |
CloudBoltSoftware/cloudbolt-forge | blueprints/office365/create.py | Python | apache-2.0 | 3,692 | 0.003793 | import requests
import json
import re
import ast
import adal
from utilities.models import ConnectionInfo
from infrastructure.models import CustomField
'''
From Azure AD, grant application API access to Microsoft graph - Application permission ->
Grant DirectoryReadAll and DirectoryReadWriteAll
'''
CI = ConnectionInfo... | 'Used by the Office 365 blueprints',
'show_as_attribute': True}
)
CustomField.objects.get_or_create(
name='user_id', type='STR',
defaults={'label': | 'ID', 'description': 'Used by the Office 365 blueprints', 'show_as_attribute': True}
)
|
ygol/odoo | odoo/addons/test_populate/tests/test_populate.py | Python | agpl-3.0 | 7,068 | 0.003537 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import collections
import logging
from odoo.tests import common
from odoo.cli.populate import Populate
from odoo.tools import mute_logger, populate
from unittest.mock import patch
_logger = logging.getLogger(__name__)
... | at all fields in _populate_factories exists """
def setUp(self):
super(T | estPopulateValidation, self).setUp()
self.env.registry.populated_models = collections.defaultdict(list)
self.addCleanup(delattr, self.env.registry, 'populated_models')
def test_populate_factories(self):
for model in self.env.values():
factories = model._populate_factories() or [... |
TieWei/nova | nova/block_device.py | Python | apache-2.0 | 16,864 | 0.000652 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Isaku Yamahata <yamahata@valinux co jp>
# 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
#
# ... | the
# License for the specific language governing permissions and limitations
# under the License.
import re
from oslo.config import cfg
from nova import exception
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.openstack.common import strutils
from ... | import utils
from nova.virt import driver
CONF = cfg.CONF
CONF.import_opt('default_ephemeral_format', 'nova.virt.driver')
LOG = logging.getLogger(__name__)
DEFAULT_ROOT_DEV_NAME = '/dev/sda1'
_DEFAULT_MAPPINGS = {'ami': 'sda1',
'ephemeral0': 'sda2',
'root': DEFAULT_ROOT_DEV_N... |
Eficent/odoo-operating-unit | mrp_operating_unit/models/procurement.py | Python | agpl-3.0 | 1,509 | 0 | # -*- coding: utf-8 -*-
# © 2015 Eficent - Jordi Ballester Alomar
# © 2015 Serpent Consulting Services Pvt. Ltd. - Sudhir Arya
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from openerp.osv import fields, orm
class ProcurementOrder(orm.Model):
_inherit = 'procurement.order'
def _chec... | return True
_constraints = [
(_check_mrp_production_operating_unit,
'The Production Order and the Procurement Order must '
'belong to t | he same Operating Unit.', ['operating_unit_id',
'production_id'])]
def _prepare_mo_vals(self, cr, uid, procurement, context=None):
res = super(ProcurementOrder, self)._prepare_mo_vals(cr, uid,
procu... |
PatrikValkovic/grammpy | grammpy/transforms/InverseCommon.py | Python | mit | 807 | 0.001239 | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.12.2017 16:03
:Licence MIT
Part o | f grammpy
"""
from typing import TYPE_CHECKING
from .SplittedRules import splitted_rules
if TYPE_CHECKING: # pragma no cover
from .. import Nonterminal
class InverseCommon:
"""
Class that aggregates functions transforming common parsed tree.
"""
@staticmethod
def splitted_rules(root):
... | th the original one.
This method is mandatory if you insert Rule class with multiple rules into the grammar.
:param root: Root of the parsed tree.
:return: Modified tree.
"""
# TODO should by done automatically
return splitted_rules(root)
|
tenstartups/wal-e | wal_e/blobstore/__init__.py | Python | bsd-3-clause | 534 | 0 | def get_blobstore(la | yout):
"""Return Blobstore instance for a given storage layout
Args:
layout (StorageLayout): Target storage layout.
"""
if layout.is_s3:
from wal_e.blobstore import s3
blobstore = s3
elif layout.is_wabs:
from wal_e.bl | obstore import wabs
blobstore = wabs
elif layout.is_swift:
from wal_e.blobstore import swift
blobstore = swift
elif layout.is_gs:
from wal_e.blobstore import gs
blobstore = gs
return blobstore
|
bytescout/ByteScout-SDK-SourceCode | Cloud API Server/PDF To JSON API/Python/Convert PDF To JSON From Uploaded File Asynchronously/ConvertPdfToJsonFromUploadedFileAsynchronously.py | Python | apache-2.0 | 4,742 | 0.007381 | """ Cloud API asynchronous "PDF To Text" job example.
Allows to avoid timeout errors when processing huge or scanned PDF documents.
"""
import os
import requests # pip install requests
import time
import datetime
# Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
# If ... | ploadedFileUrl != None):
convertPdfToJson(uploadedFileUrl, DestinationFile)
def convertPdfToJson(uploadedFileUrl, destinationFile):
"""Converts PDF To Json using PDF.co Web API"""
# Prepare URL for 'PDF To Json' API request
url = "{}/pdf/convert/to/json?async={}&name={}&password={}&pages={}&url={... | uploadedFileUrl
)
# Execute request and get response as JSON
response = requests.get(url, headers={ "content-type": "application/octet-stream" })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Asynchronous job ID
jo... |
gustavomazevedo/tbackup-client | client/migrations/0001_initial.py | Python | mit | 8,611 | 0.007084 | # -*- 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):
# Adding model 'Backup'
db.create_table(u'client_backup', (
(... | ('django.db.models.fields.BooleanField')(default=True)),
))
db.send_create_signal('client', ['Schedule'])
# Adding model 'Destination'
db.create_table(u'client_destination', (
('name', self.gf('django.db.models.fields.CharField')(max_length=1024, primary_key=True)),
... | (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=1024)),
('remote_id', self.gf('django.db.models.fields.BigIntegerField')()),
))
db.send_create_signal('client', ['Origin'])
# Add... |
PhyloStar/PyBayes | ML.py | Python | gpl-2.0 | 3,629 | 0.011849 | from collections import defaultdict
import numpy as np
def matML_dot(state, taxa, ll_mats):
LL_mat = defaultdict()
root | = state["root"]
p_t = state["transitionMat"]
pi = state["pi"]
edges = state["postorder"]
for parent, child in edges[::-1]:
if child in taxa:
if parent not in LL_mat:
#print(child, ll_mats[child], "\n", ll_mats[child].shape,"\n")
#print(p_t[parent... |
else:
LL_mat[parent] *= np.dot(p_t[parent,child], ll_mats[child])
else:
if parent not in LL_mat:
LL_mat[parent] = np.dot(p_t[parent,child], LL_mat[child])
else:
LL_mat[parent] *= np.dot(p_t[parent,child], LL_mat[child])
... |
embray/astropy_helpers | astropy_helpers/commands/build_sphinx.py | Python | bsd-3-clause | 9,455 | 0.001375 | import inspect
import os
import pkgutil
import re
import shutil
import subprocess
import sys
import textwrap
from distutils import log
from distutils.cmd import DistutilsOptionError
import sphinx
from sphinx.setup_command import BuildDoc as SphinxBuildDoc
from ..utils import minversion
PY3 = sys.version_info[0] >=... | if iden.endswith('_dir'):
# Directories should be absolute, because the `chdir` call
# in the new process moves to a different directory
| subproccode[i] = repr(os.path.abspath(val))
else:
subproccode[i] = repr(val)
subproccode = ''.join(subproccode)
# This is a quick gross hack, but it ensures that the code grabbed from
# SphinxBuildDoc.run will work in Python 2 if it uses the print
... |
rkhleics/wagtailmenus | wagtailmenus/migrations/0011_auto_20160415_1519.py | Python | mit | 848 | 0.002358 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailmenus', '0010_auto_20160201_1558'),
]
operations = [
migrations.AlterF | ield(
model_name='flatmenuitem',
name='url_append',
field=models.CharField(help_text="Use this to optionally append a #hash or querystring to the above page's URL.", max_length=255, verbose_name='Append to URL', blank=True),
),
migrations.AlterField(
model... | name='url_append',
field=models.CharField(help_text="Use this to optionally append a #hash or querystring to the above page's URL.", max_length=255, verbose_name='Append to URL', blank=True),
),
]
|
kuiche/chromium | third_party/scons/scons-local/SCons/Tool/mwcc.py | Python | bsd-3-clause | 6,796 | 0.00412 | """SCons.Tool.mwcc
Tool-specific initialization for the Metrowerks CodeWarrior compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 ... | env.PrependENVPath('PATH', version.dllpath)
ENV = env['ENV']
ENV['CWFolder'] = version.path
ENV['LM_LICENSE_FILE'] = version.license
plus = lambda x: '+%s' % x
ENV['MWCIncludes'] = string.join(map(plus, version.includes), os.pathsep)
ENV | ['MWLibraries'] = string.join(map(plus, version.libs), os.pathsep)
return 1
def find_versions():
"""Return a list of MWVersion objects representing installed versions"""
versions = []
### This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be im... |
Andrew0701/coursework-web | progress/home/captcha.py | Python | apache-2.0 | 497 | 0.006036 | f | rom django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
myfield = AnyOtherField()
captcha = CaptchaField()
def some_view(request):
if request.POST:
form = CaptchaTestForm(request.POST)
# Validate the form: the captcha field will automatically
... | |
the01/python-paps | paps/si/__init__.py | Python | mit | 711 | 0 | # -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division |
from __future__ import print_function
from __future__ import unicode_literals
__author__ = "d01"
__email | __ = "jungflor@gmail.com"
__copyright__ = "Copyright (C) 2015-16, Florian JUNG"
__license__ = "MIT"
__version__ = "0.2.1"
__date__ = "2016-04-06"
# Created: 2015-03-21 06:16
import logging
from .sensorInterface import SensorClientInterface, SensorServerInterface, \
SensorException, SensorJoinException, SensorStar... |
ERP-Ukraine/maintainer-quality-tools | travis/run_pylint.py | Python | agpl-3.0 | 11,577 | 0.000346 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import ast
import os
import re
import sys
import click
import pylint.lint
import travis_helpers
from getaddons import get_modules_changed, is_module
from git_run import GitRun
try:
import ConfigParser
except ImportError:
im... | tra_params
def get_beta_msgs():
"""Get beta msgs from beta.cfg file
:return: List of strings with beta message names"""
beta_cfg = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'cfg/travis_run_pylint_beta.cfg')
if not os.path.isfile(beta_cfg):
return []
confi | g = ConfigParser.ConfigParser()
config.readfp(open(beta_cfg))
return [
msg.strip()
for msg in config.get('MESSAGES CONTROL', 'enable').split(',')
if msg.strip()]
def get_modules_cmd(dir):
modules_cmd = []
include_lint = os.environ.get('INCLUDE_LINT')
if include_lint:
... |
xkollar/spacewalk | backend/server/importlib/productNamesImport.py | Python | gpl-2.0 | 1,057 | 0.000946 | #
# Copyright (c) 2008--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. | You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission | is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
#
# Product Names Import
from importLib import Import
class ProductNamesImport(Import):
def __init__(self, batch, backend):
Import.__init__(self, batch, backend)
def preprocess(self... |
USGSDenverPychron/pychron | pychron/hardware/furnace/nmgrl/funnel.py | Python | apache-2.0 | 2,158 | 0.000463 | # ===============================================================================
# Copyright 2016 Jake Ross
#
# 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... |
return self.ask("InDownPosition") == "OK"
else:
return not self._simulation_funnel_up
def read_position(self):
pos = self.ask(self._build_command("GetPosition"))
| try:
return float(pos)
except (TypeError, ValueError):
pass
def set_value(self, pos):
self.ask(self._build_command("SetPosition", position=pos))
def lower(self, block=True):
self.ask(self._build_command("LowerFunnel"))
if block:
self.... |
mit0110/oppia | core/controllers/recent_commits.py | Python | apache-2.0 | 1,988 | 0 | # Copyright 2014 The Oppia 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 applicable ... | urlsafe_start_cursor = self.request.get('cursor')
query_type = self.request.get('query_type')
if query_type == 'all_non_private_commits':
all_commits, new_urlsafe_start_cursor, more = (
exp_services.get_next_page_of_all_non_private_commits( |
urlsafe_start_cursor=urlsafe_start_cursor))
else:
raise self.PageNotFoundException
exp_ids = set([commit.exploration_id for commit in all_commits])
exp_ids_to_exp_data = (
exp_services.get_exploration_titles_and_categories(exp_ids))
all_comm... |
pyvec/pyvodb | setup.py | Python | mit | 1,702 | 0 |
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
super().finalize_options()
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
... | 'click >= 6.7, <7.0',
'czech-holidays',
'python-slugify',
]
tests_require = ['pytest']
if sys.version_info < (3, 4):
# pathlib is in the stdlib since Python 3.4
requires.append('pathlib >= 1.0.1, < 2.0')
setup_args = dict(
name='pyvodb',
version='1.0',
packages=find_packages(),
url='... | ifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: P... |
txstate-etc/thrawler | nodes.py | Python | mit | 1,009 | 0.009911 | #!/usr/bin/python3
# nodes.py is to re | cursively gather page links
# from magnolia RESTful output of nodes.
# Example usage:
# curl --user '...' -H 'Accept: application/json' 'http://localhost:8080/mjdf38i3tv0b56vz/.rest/nodes/v1/website/testing-site-destroyer?depth=999&excludeNodeTypes=mgnl:resource,mgnl:metaData,mgnl:content,mgnl:contentNode,mgnl:area,mgn... | rt argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--domain", help="The virtual host domain name used for this site")
parser.add_argument("-s", "--site", help="The site name")
args = parser.parse_args()
def nodes(d):
for k, v in d.items():
if k == "path":
print(v.replace("/"+args.si... |
s20121035/rk3288_android5.1_repo | external/chromium_org/build/android/lighttpd_server.py | Python | gpl-3.0 | 9,421 | 0.005838 | #!/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.
"""Provides a convenient wrapper for spawning a test lighttpd instance.
Usage:
lighttpd_server PATH_TO_DOC_ROOT
"""
import co... | ts = extra_config_contents
self.config_path = config_path or self._Mktmp('config')
self.error_log = error_log or self._Mktmp('error_log')
self.access_log = access_log or self._Mktmp('access_log')
self.pid_file = self._Mktmp('pid_file')
self.process = None
def _Mktmp(self, name):
return os.pat... | return random.randint(constants.LIGHTTPD_RANDOM_PORT_FIRST,
constants.LIGHTTPD_RANDOM_PORT_LAST)
def StartupHttpServer(self):
"""Starts up a http server with specified document root and port."""
# If we want a specific port, make sure no one else is listening on it.
if self.fix... |
antiboredom/videogrep | videogrep/tests/test_videogrep.py | Python | mit | 517 | 0.005803 | import os
from subprocess import call
from videogrep impor | t videogrep
filename = 'TEST_OUTPUT.mp4'
def test_videogrep():
videogrep.videogrep('test_videos/test.mp4', filename, 'video', 'pos')
files = os.listdir('.')
assert filename in files
def test_cli():
command = 'videogrep_cli.py -i test_videos/test.mp4 -s video -st pos'
call(command.split())
fil... | 'supercut.mp4' in files
def test_cleanup():
call(['rm', filename])
call(['rm', 'supercut.mp4'])
|
js850/pele | pele/gui/takestep_explorer.py | Python | gpl-3.0 | 4,352 | 0.009421 | from PyQt4 import QtGui, QtCore, Qt
from ui.ui_takestep_explorer import Ui_MainWindow as UI
import numpy as np
class QMinimumInList(QtGui.QListWidgetItem):
def __init__(self, minimum):
text="%.4f (%d)"%(minimum.energy, minimum._id)
QtGui.QListWidgetItem.__init__(self, text)
self.minimu... | self.update_view(with_path=get_path)
def on_listMinima_currentItemChanged(self, new, old):
self.coords = No | ne
self.quenched = new.minimum.coords
self.update_view()
def update_view(self, with_path=False):
pot = self.system.get_potential()
label = ""
if self.quenched is not None:
e, grad = pot.getEnergyGradient(self.quenched)
label = "quenche... |
radicalbit/ambari | ambari-server/src/main/resources/common-services/KAFKA/0.10.0.3.0/package/scripts/upgrade.py | Python | apache-2.0 | 3,109 | 0.009971 |
#!/usr/bin/env python
"""
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")... | since cluster security is not enabled.")
return
Logger.info("Upgrade type: {0}, direction: {1}".format(str(upgrade_type), params.upgrade_direction))
# If the schema upgrade script exists in the version upgrading to, then attempt to upgrade/downgrade it while still using the present bits.
kafka_acls_scrip... | ffix = "--upgradeAcls"
elif params.upgrade_direction == Direction.DOWNGRADE:
kafka_acls_script = format("{stack_root}/{downgrade_from_version}/kafka/bin/kafka-acls.sh")
command_suffix = "--downgradeAcls"
if kafka_acls_script is not None:
if os.path.exists(kafka_acls_script):
Logger.info("Found Ka... |
mtrgroup/django-mtr-utils | tests/app/tests/models/mixins.py | Python | mit | 991 | 0 | from django.test import TestCase
from ...models import Office
class PublishedMixinTest(TestCase):
def test_only_published_manager_and_queryset_default_datetime(self):
data = [
dict(published=False, address='office', office='not_published'),
dict(office='published', address='some ... | published_offices.append(office)
else:
not_published_offices.append(office)
self.assertQuerysetEqual(
Office.objects.published(), reversed(published_offices),
transform=lambda o: o)
self.assert | QuerysetEqual(
Office.published_objects.all(), reversed(published_offices),
transform=lambda o: o)
|
lcpt/xc | verif/tests/solution/constraint_handler/lagrange_handler_test_01.py | Python | gpl-3.0 | 3,099 | 0.040671 | # -*- coding: utf-8 -*-
# Test from Ansys manual
# Reference: Strength of Material, Part I, Elementary Theory & Problems, pg. 26, problem 10
__author__= "Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2014, LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
E= 30e6 # Young modulus (... | nche a
b= 0.3*l # Length of tranche b
F1= 1000.0 # Force magnitude 1 (pounds)
F2= 1000.0/2.0 # Force magnitude 2 (pounds)
import xc_base
import geom
import xc
from model import predefined_spaces
from solution import pr | edefined_solutions
from materials import typical_materials
# Model definition
feProblem= xc.FEProblem()
preprocessor= feProblem.getPreprocessor
nodes= preprocessor.getNodeHandler
# Problem type
modelSpace= predefined_spaces.SolidMechanics2D(nodes)
nodes.defaultTag= 1 #First node number.
nod= nodes.newNodeXY(0,0)
n... |
MakeHer/edx-platform | lms/djangoapps/discussion_api/tests/test_render.py | Python | agpl-3.0 | 3,254 | 0.001844 | """
Te | sts for content rendering
"""
from unittest import TestCase
import ddt
from discussion_api.render import render_body
def _add_p_tags(raw_body):
| """Return raw_body surrounded by p tags"""
return "<p>{raw_body}</p>".format(raw_body=raw_body)
@ddt.ddt
class RenderBodyTest(TestCase):
"""Tests for render_body"""
def test_empty(self):
self.assertEqual(render_body(""), "")
@ddt.data(
("*", "em"),
("**", "strong"),
... |
Spacecraft-Code/SPELL | src/spell/spell/lang/helpers/genhelper.py | Python | lgpl-3.0 | 21,984 | 0.018695 | ###################################################################################
## MODULE : spell.lang.helpers.genhelper
## DATE : Mar 18, 2011
## PROJECT : SPELL
## DESCRIPTION: Helpers for generic features
## --------------------------------------------------------------------------------
##
## Cop... | if tov.isRel():
defaultTimeout = tov.rel()
else:
raise SyntaxException("Cannot accept absolute times", str(tov))
elif type(tov) in [int,float]:
defau | ltTimeout = tov
else:
raise SyntaxException("Ignored timeout malformed value", repr(tov))
else:
self.addConfig(Timeout,defaultTimeout)
# Mark procedure prompts
self.addConfig(Scope,SCOPE_PROC)
# Store information for possible failures
sel... |
sboosali/commands-frontends-dragon13 | NatLink/SampleMacros/natspeak_sample6.py | Python | mit | 1,733 | 0.010964 | #
# Python Macro Language for Dragon NaturallySpeaking
# (c) Copyright 1999 by Joel Gould
# Portions (c) Copyright 1999 by Dragon Systems, Inc.
#
# This sample macro file was created for my talk to the Boston Voice Users
# group on November 9, 1999. It is explained in my PowerPoint slides.
#
# natspeak_sample6.py
... | initialize(self):
self. | load(self.gramSpec)
def gotResults_mainRule(self,words,fullResults):
natlink.playString('Saw <mainRule>')
def gotResults_fontRule(self,words,fullResults):
natlink.playString('Saw <fontRule>')
thisGrammar = ThisGrammar()
thisGrammar.initialize()
def unload():
global thisGrammar
if thi... |
tboyce021/home-assistant | tests/components/light/test_device_trigger.py | Python | apache-2.0 | 8,300 | 0.001446 | """The test for light device automation."""
from datetime import timedelta
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.light import DOMAIN
from homeassistant.const import CONF_PLATFORM, STATE_OFF, STATE_ON
from homeassistant.helpers import device_registry
from ... | "trigger", device_entry.id)
assert triggers == expected_triggers
async def test_get_trigger_capabilities(hass, devi | ce_reg, entity_reg):
"""Test we get the expected capabilities from a light trigger."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry... |
bergolho1337/URI-Online-Judge | Basicos/Python/1050/main.py | Python | gpl-2.0 | 420 | 0 | # -*- coding: utf-8 -*-
ddd = int(raw_input())
if (ddd == 61):
print("Brasilia")
elif (ddd == 71):
print("Salvador")
elif (ddd == 11):
print("Sao Paulo")
elif (ddd == 21):
| print("Rio de Janeiro")
elif ( | ddd == 32):
print("Juiz de Fora")
elif (ddd == 19):
print("Campinas")
elif (ddd == 27):
print("Vitoria")
elif (ddd == 31):
print("Belo Horizonte")
else:
print("DDD nao cadastrado")
|
hegxiten/Worldwide-Railway-Network | WorldRailNetwork_WRN_workspace/src/network_process.py | Python | apache-2.0 | 7,862 | 0.017171 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on Jan 17, 2017
@author: hegxiten
'''
import sys
import geo.haversine as haversine
from imposm.parser import OSMParser
import geo.haversine as haversine
import numpy
import time
from scipy import spatial
import csv
import codecs
import math
default_encoding='u... | 8.24111(longitude)<<'''
def output_links_csv():
target = codecs.open(FOLDER+FILE+"_links.csv", 'w',encoding='utf-8')
headerkeys=attribute_mapper.values()[0].keys()
header='vertex_1,vertex_2'
for k in headerkeys:
header=header+','+k
target.write(header+'\n')
... | ct:
for (a,b) in node_fromto_dict[x]:
if a in node_fromto_dict and b in node_fromto_dict:
row_to_write=str(a)+","+str(b)
for attr in headerkeys:
row_to_write=row_to_write+','+attribute_mapper[(a,b)].get(attr,"N/A")
... |
mmcauliffe/django-phonological-statistics | setup.py | Python | gpl-3.0 | 843 | 0.008304 | from distutils.core import setup
packages=['phonostats','phonostats.media']
template_patterns = [
'templates/*.html',
'templates/*/*.html',
'templates/*/*/*.html',
]
setup(
name='dja | ngo-phonological-statistics',
version='0.1.20',
author='Michael McAuliffe',
author_email='michael.e.mcauliffe@gmail.com',
url='http://pypi.python.org/pyp | i/django-phonological-statistics/',
license='LICENSE.txt',
description='Django module that allows for querying of a database of phonological lemmas to determine statistics about inputted phonological strings',
long_description=open('README.md').read(),
install_requires=['django',
... |
rvianello/rdkit | rdkit/Chem/MolDb/Loader.py | Python | bsd-3-clause | 408 | 0.007353 | # $Id$
#
# Copyright (C) 2007-2009 Greg Landrum
# @@ 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.
#
try:
import | sqlalchemy
except ImportError:
from rdkit.Chem.MolDb.Lo | ader_orig import *
else:
from rdkit.Chem.MolDb.Loader_sa import *
|
tsdmgz/ansible | lib/ansible/modules/web_infrastructure/ansible_tower/tower_credential.py | Python | gpl-3.0 | 7,515 | 0.00173 | #!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... | %s' % filename)
if os.path.isdir(filename):
module.fail_json(msg='attempted to read contents of dire | ctory: %s' % filename)
with open(filename, 'rb') as f:
params['ssh_key_data'] = f.read()
if state == 'present':
result = credential.modify(**params)
json_output['id'] = result['id']
elif state == 'absent':
resul... |
orbnauticus/silk | silk/webdb/drivers/__init__.py | Python | bsd-3-clause | 201 | 0 |
# sqlite is always available
from . import sq | lite
__all__ = ['sqlite']
# mysql driver depends on MySQLdb
try:
from . import mysql
except ImportError:
mysql = None
__all__.append('m | ysql')
|
kernsuite-debian/lofar | CEP/Calibration/BBSControl/scripts/solflag.py | Python | gpl-3.0 | 8,453 | 0.002129 | # solflag.py:
#
# Copyright (C) 2007
# ASTRON (Netherlands Institute for Radio Astronomy)
# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This file is part of the LOFAR software suite.
# The LOFAR software suite is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public L... | tten to the measurement
updateMain: (default True) if set to True, both the FLAG and the
FLAG_ROW column will be updated if set to False, only the
FLAG_ROW column will be updated
cutoffLow: (default None) if set, all values less than or equal to
... | r than or equal to
cutoffHigh will be flagged
debug: (default False) if set to True, a plot is generated for each
source - station combination that shows what has been flagged.
"""
# Read station names from MS.
antennaTable = pyrap.tables.table("%s/ANTEN... |
deisi/home-assistant | homeassistant/components/sensor/mqtt.py | Python | mit | 2,630 | 0 | """
Support for MQTT sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mqtt/
"""
import logging
import voluptuous as vo | l
import homeassistant.components.mqtt as mqtt
from homeassistant.const import CONF_NAME, CONF_VALUE_TEMPLATE, STATE_UNKNOWN
from homeassistant.components.mqtt import CONF_STATE_TOPIC, CONF_QOS
import homeassistant.helpers.config_validation as cv
from homeassistant.help | ers.entity import Entity
from homeassistant.helpers import template
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['mqtt']
CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement'
DEFAULT_NAME = "MQTT Sensor"
PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): ... |
rizar/attention-lvcsr | libs/Theano/theano/gof/utils.py | Python | mit | 14,120 | 0.000283 | from __future__ import print_function
import linecache
import sys
import numpy
from six import iteritems
from theano import config
from theano.compat import OrderedDict, PY3
def simple_extract_stack(f=None, limit=None, skips=[]):
"""This is traceback.extract_stack from python 2.7 with this change:
- Commen... | for x in seq1 if x not in seq2]
def to_return_values(values):
if len(values) == 1:
return values[0]
else:
return values
def from_return_values(values):
if isinstance(values, (list, tuple)):
return values
else:
return [values]
def toposort(prereqs_d):
"""
Sor... | all2 = set()
# for x, y in iteritems(prereqs_d):
# all2.update(y)
# print all1.difference(all2)
seq = []
done = set()
postreqs_d = {}
for x, prereqs in iteritems(prereqs_d):
for prereq in prereqs:
postreqs_d.setdefault(prereq, set()).add(x)
next = set([k for ... |
jorisvandenbossche/DS-python-data-analysis | notebooks/_solutions/case2_observations_processing20.py | Python | bsd-3-clause | 45 | 0.022222 | p | lot_data.apply(transform_utm_to_wgs, a | xis=1) |
erinspace/osf.io | addons/wiki/utils.py | Python | apache-2.0 | 7,881 | 0.001523 | # -*- coding: utf-8 -*-
import os
import urllib
import uuid
import ssl
from pymongo import MongoClient
import requests
from bs4 import BeautifulSoup
from addons.wiki import settings as wiki_settings
from addons.wiki.exceptions import InvalidVersionError
# MongoDB forbids field names that begin with "$" or contain ".... | wname):
"""
Generate private uuid for internal use in sharejs namespacing.
Note that this will NEVER be passed to to the client or sharejs.
"""
private_uuid = str(uuid.uuid1())
wiki_key = to_mongo_key(wname)
node.wiki_private_uuids[wiki_key] = private_uuid
node.save()
return priva... | ate uuid into the form used in mongo and sharejs.
This includes node's primary ID to prevent fork namespace collision
"""
wiki_key = to_mongo_key(wname)
private_uuid = node.wiki_private_uuids.get(wiki_key)
return str(uuid.uuid5(
uuid.UUID(private_uuid),
str(node._id)
)) if privat... |
b1-systems/kiwi | test/unit/system/root_import/init_test.py | Python | gpl-3.0 | 998 | 0 | from mock import patch
from pytest import raises
from kiwi.system.root_import i | mport RootImport
from kiwi.exceptions import KiwiRootImportError
class TestRootImport:
@patch('kiwi.system.root_import.RootImportOCI')
def test_docker_import(self, mock_docker_import):
RootImport('root_dir', 'file:///image.tar. | xz', 'docker')
mock_docker_import.assert_called_once_with(
'root_dir', 'file:///image.tar.xz',
custom_args={'archive_transport': 'docker-archive'}
)
@patch('kiwi.system.root_import.RootImportOCI')
def test_oci_import(self, mock_oci_import):
RootImport('root_dir',... |
AntoinePassemiers/Motionlens | Server/app.py | Python | gpl-3.0 | 1,136 | 0.026408 | from flask import Flask, request
from werkzeug.utils import secure_filename
import os
from dataflow import *
import numpy as np
import re
import time
ROOT_FOLDER = os.getcwd()
UPLOAD_FOLDER = "Motionlens/Server/fil | es"
DATA_PATH = "files"
EXTENSION = ".mdcar"
app = Flask(__name__)
@app.route("/file", methods = ["GET"])
def get():
return "ge | t-ok"
@app.route("/file", methods = ["POST"])
def upload():
"""
pattern = r'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'
for match in re.finditer(pattern,str(request.get_data())):
print("yoyo : " + str(match.start()))
"""
#print(request.get_data())
rawstring = request.get_data()
#rawstring = s[2:-1]
#rawstring ... |
bokeh/bokeh | bokeh/protocol/receiver.py | Python | bsd-3-clause | 7,389 | 0.005143 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | not isinstance(fragment, bytes):
raise ValidationError(f"expected binary fragment but received text fragment for {self._curr | ent_consumer.__name__}")
return fragment
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#----------... |
StevenCHowell/zazmol | src/python/extensions/matrix_math/setup_matrix_multiply.py | Python | gpl-3.0 | 1,074 | 0.020484 | '''
SASSIE Copyright (C) 2011 Joseph E. Curtis
This program comes wi | th ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it under certain
conditions; see http://www.gnu.org/licenses/gpl-3.0.html for details.
'''
# System imports
from distutils.core import *
| from distutils import sysconfig
# Third-party modules - we depend on numpy for everything
import numpy
from numpy.distutils.core import Extension, setup
# Obtain the numpy include directory. This logic works across numpy versions.
try:
numpy_include = numpy.get_include()
except AttributeError:
numpy_i... |
openqt/algorithms | leetcode/python/lc166-fraction-to-recurring-decimal.py | Python | gpl-3.0 | 951 | 0.009464 | # coding=utf-8
import unittest
"""166. Fraction to Recurring Decimal
https://leetcode.com/problems/fraction-to-recurring-decimal/description/
Given two integers representing the numerator and denominator of a fraction,
return the fraction in string format.
If the fractional part is repeating, enclose the repeating p... | 1
**Output:** "2"
**Example 3:**
|
**Input:** numerator = 2, denominator = 3
**Output:** "0.(6)"
Similar Questions:
"""
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
def te... |
procamora/Wiki-Personal | pelican-plugins/github-wiki/__init__.py | Python | gpl-3.0 | 20 | 0 | from .wiki imp | ort | *
|
nickmilon/mongoUtils | mongoUtils/tools/scripts.py | Python | apache-2.0 | 362 | 0.005525 | '''
some usefull scripts fun | ctions etc
Created on Dec 12, 2015
@author: milon
'''
from Hellas.Delphi import time_func
@time_func
d | ef query_bm(col, query, operations):
for i in range(0, operations):
r = col.find(query).count()
@time_func
def query_bm_one(col, query, operations):
for i in range(0, operations):
r = col.find_one(query) |
cfobel/sconspiracy | Python/racy/renv/environment.py | Python | bsd-3-clause | 4,531 | 0.011476 | # -*- coding: UTF8 -*-
# ***** BEGIN LICENSE BLOCK *****
# Sconspiracy - Copyright (C) IRCAD, 2004-2010.
# Distributed under the terms of the BSD Licence as
# published by the Open Source Initiative.
# ****** END LICENSE BLOCK ******
from SCons.Environment import Environment as Env
from SCons import Action
env_vars... | wargs['CXX'] = cxx
Env.__init__(self, *args, **kwargs)
FLAGS = (
'$( ${{_concat(INCPREFIX, {0}, INCSUFFIX, '
'__env__, RDirs, TARGET, SOURCE)}} $)'
)
self['CPP_LIBEXT_PATH'] = []
self['_CPPINCFLAGS'] = (
FLAGS.format... | PPATH')
+ FLAGS.format('CPP_LIBEXT_PATH')
)
act = self.Action( CopyBuilder, "Install '$$SOURCE' as '$$TARGET'")
self.__CopyBuilder__ = self.Builder(
action = act,
source_factory = self.Entry,
target_factory = self.Entr... |
zwChan/VATEC | ~/eb-virt/Lib/site-packages/pip/_vendor/distlib/scripts.py | Python | apache-2.0 | 15,223 | 0.00046 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2015 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from io import BytesIO
import logging
import os
import re
import struct
import sys
from .compat import sysconfig, detect_encoding, ZipFi... | executable = self._get_alternate_executable(executable, options)
if sys.platform.startswith('java'): # pragma: no cover
executable = self._fix_jython_executable(executable)
# Normalise case for Windows
executable = os.path.normcase(executable)
# If t | he user didn't specify an executable, it may be necessary to
# cater for executable paths with spaces (not uncommon on Windows)
if enquote:
executable = _enquote_executable(executable)
# Issue #51: don't use fsencode, since we later try to
# check that the shebang is decodabl... |
JacksonBates/rhymer | rhyme.py | Python | gpl-2.0 | 2,132 | 0.006098 | #!/usr/bin/env python
import random
from itertools import izip as zip, count
PHONES = ['AA0', 'AA1', 'AA2', 'AE0', 'AE1', 'AE2', 'AH0', 'AH1', 'AH2', 'AO0', 'AO1', 'AO2', 'AW0', 'AW1', 'AW2', 'AY0', 'AY1', 'AY2', 'EH0', 'EH1', 'EH2', 'ER0', 'ER1', 'ER2', 'EY0', 'EY1', 'EY2', 'IH0', 'IH1', 'IH2', 'IY0', 'IY1', 'I... | list comp that matches words that share identical phonemes fr | om the last stressed vowel
# ^ i.e. it finds true rhymes!
print candidates
rhyme()
|
marratj/ansible | lib/ansible/modules/network/f5/bigip_partition.py | Python | gpl-3.0 | 10,561 | 0.000663 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUM... | return False
def | exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
... |
diogocs1/comps | web/openerp/addons/test_new_api/__openerp__.py | Python | apache-2.0 | 501 | 0 | # -*- coding: utf-8 -*-
{
'name': 'Test New API',
'version': '1.0' | ,
'category': 'Tests',
'description': """A module to test the new API.""",
'author': 'OpenERP SA',
'maintainer': 'OpenERP SA',
'website': 'http://www.openerp.com',
'depends': ['base'],
'installable': True,
'auto_install': False,
'data': [
'ir.model.access.csv',
| 'views.xml',
'demo_data.xml',
],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
southskies/osdial | bin/python/db_optimize.py | Python | agpl-3.0 | 5,170 | 0.013346 | #!/usr/bin/python
#
# Copyright (C) 2014 Lott Caskey <lottcaskey@gmail.com>
#
import sys, os, pwd, re, time | , pprint, gc
import argparse
import MySQLdb, logging
from osdial import OSDial
from warnings import filterwarnings
import MySQLdb as Database
filterwarnings('ignore', category = Database.Warning)
PROGNAME = 'osdial_db_optimize'
VERSION = '0.1'
opt = {'verbose':False,'loglevel':False,'debug':False,'test':False,'daem... | parser.add_argument('-v', '--verbose', action='count', default=0, help='Increases verbosity.', dest='verbose')
parser.add_argument('--version', action='version', version='%(prog)s %(ver)s' % {'prog':PROGNAME,'ver':VERSION})
parser.add_argument('--debug', action='store_true', help='Run in debug mode.',dest='deb... |
asaygo/malwrforensics | scripts/pop3.py | Python | gpl-3.0 | 1,227 | 0.04564 | #!python
###############################################
# POP3 Fuzzer #
# Author: malwrforensics #
# Contact: malwr at malwrforensics dot com #
###############################################
import sys, socket
from random import randint
MIN_LIMIT = 50
MAX_LIMI... | buf = f.read()
f.close()
sploit = "-ERR " + buf
conn.send(sploit)
c | onn.close()
except:
print ("[*] Client err.")
###MAIN###
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 110))
s.listen(1)
print ("[+] Listening on port 110.")
conn, addr = s.accept()
print '[*] Received connection from: ', addr
#send_random_err(s)
send_data_from_file(s, "poc.txt")
|
agripo/website | core/migrations/0029_auto_20151028_1609.py | Python | gpl-2.0 | 595 | 0.001689 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0028_auto_20151026_0926'),
]
operations = [
migrations.AlterField(
model_name='partner',
name='logo',
| field=models.ImageField(default=None, upload_to='partners', verbose_name='Logo', help_text="Envoyez le logo du partenaire ici.<br />Il doit faire 150x150px. Si la largeur est différente de la hauteur, l'image apparaitra déformée."),
),
]
|
homeworkprod/byceps | byceps/services/tourney/transfer/models.py | Python | bsd-3-clause | 2,347 | 0 | """
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import NewType, Optional
from uuid im | port UUID
from ....typing import PartyID
from ...user.transfer.models import User
TourneyCategoryID = NewType('TourneyCategoryID', UUID)
@dataclass(frozen=True)
class TourneyCategory:
id: TourneyCategoryID
party_id: PartyID
position: int
title: str
TourneyID = NewType('TourneyID', UUID)
@datac... |
dave-shawley/ietfparse | tests/test_headers_deprecation.py | Python | bsd-3-clause | 1,272 | 0 | import unittest
import warnings
from ietfparse import headers
class DeprecationTests(unittest.TestCase):
def test_that_parse_http_accept_header_emits_deprecation_warning(self):
warnings.simplefilter('always')
w | ith warnings.catch_warnings(record=True) as caught:
headers.parse_http_accept_header('Accept: application/json')
self.assertEqual(len(caught), 1)
self.assertEqual(caught[-1].category, DeprecationWarning)
def test_that_parse_link_header_emits_deprecation_warning(self):
wa... | example.com/TheBook/chapter2>; rel="previous"; '
'title="previous chapter"')
self.assertEqual(len(caught), 1)
self.assertEqual(caught[-1].category, DeprecationWarning)
def test_that_parse_list_header_emits_deprecation_warning(self):
warnings.simplefilter('always')
... |
clarinsi/reldi-lib | reldi/lexicon.py | Python | apache-2.0 | 1,528 | 0.003927 | # from exceptions import ApiException
from client import Client
import json
class Lexicon(Client):
"""Lexicon class"""
def __init__(self, language='hr'):
super(Lexicon, self).__init__()
self.language = language
def queryEntries(self, surface=None, lemma=None, msd=None, rhymes_with=None, n... | _regex=False):
if not self._auth.hasToken():
raise ValueError("U | nauthorized")
if self.language is None:
raise ValueError("Language not set")
params = {}
if surface is not None:
params['surface'] = surface
if lemma is not None:
params['lemma'] = lemma
if msd is not None:
params['msd'] = msd
... |
JoelBender/bacpypes | py27/bacpypes/local/schedule.py | Python | mit | 22,187 | 0.005093 | #!/usr/bin/env python
"""
Local Schedule Object
"""
import calendar
from time import mktime as _mktime
from ..debugging import bacpypes_debugging, ModuleLogger
from ..core import deferred
from ..task import OneShotTask
from ..primitivedata import Atomic, Null, Unsigned, Date, Time
from ..constructeddata import Arr... | entry.dateRange:
match = match_date_range(date, calendar_entry.dateRange)
elif calendar_entry.weekNDay:
match = match_weeknday(date, calendar_entry.weekNDay)
else:
raise RuntimeError("")
if _debug: date_in_calendar_entry._debug(" - match: | %r", match)
return match
#
# datetime_to_time
#
def datetime_to_time(date, time):
"""Take the date and time 4-tuples and return the time in seconds since
the epoch as a floating point number."""
if (255 in date) or (255 in time):
raise RuntimeError("specific date and time required")
t... |
galactose/wviews | optimisation.py | Python | gpl-3.0 | 5,702 | 0.000351 | """
optimisation.py: Optimisations for worldview solving
Copyright (C) 2014 Michael Kelly
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
... | = len(stat_struct.keys())
# while countb:
# counta = len(stat_struct[stat_struct.keys()[countb-1]])
# while counta:
# | temp = valuator_string & 0x1
# valuator_string >>= 1
# if not temp:
# remove_item = stat_struct[stat_struct.keys()[countb-1]][counta-1]
# stat_struct[stat_struct.keys()[countb-1]].remove(remove_item)
# counta -= 1
# countb -= 1
# c... |
petrutlucian94/nova | nova/objects/instance_action.py | Python | apache-2.0 | 8,756 | 0 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | context, instance_uuid, action_name)
db_action = db.action_start(context, values)
if want_result:
return cls._from_db_object(context, cls(), db_action)
@base.remotable_classmethod
def action_finish(cls, context, instance_uuid, want_result=True):
values = cls.pack_action_fini... | @base.remotable
def finish(self):
values = self.pack_action_finish(self._context, self.instance_uuid)
db_action = db.action_finish(self._context, values)
self._from_db_object(self._context, self, db_action)
class InstanceActionList(base.ObjectListBase, base.NovaObject):
# Version 1.0:... |
superdesk/Live-Blog | documentor/libraries/Sphinx-1.1.3-py3.2/sphinx/quickstart.py | Python | agpl-3.0 | 35,318 | 0.001076 | # -*- coding: utf-8 -*-
"""
sphinx.quickstart
~~~~~~~~~~~~~~~~~
Quickly setup documentation source to work with Sphinx.
:copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys, os, time, re
from os import path
from codecs import open... | th) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "d... | c']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%%b %%d, %%Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates,... |
radiasoft/optics | tests/utilities/uti_plot_matplotlib.py | Python | apache-2.0 | 24,880 | 0.010892 | """uti_plot backend for matplotlib
.. moduleauthor:: O. Chubar, N. Canestrari
"""
import os
import sys
import subprocess
import platform
from array import *
from math import *
import numpy as np
import tests.utilities.uti_plot_com as uti_plot_com
import tests.utilities.uti_math as uti_math
import tests.utilities.uti_p... | _format = fname_format
self._figure_num = 0
def uti_plot_show(self):
'Render the plots generated thus far; Prompts user to do the generation'
self._pyplot_show()
#def plot1D(ar1d,x_range,labels=('energy, KeV','Ph/s/0.1%BW')):
def uti_plot1d(self, ar1d, x_r | ange, labels=('energy [eV]', 'ph/s/0.1%bw')):
#fig = _pl.figure(figsize=(12,8))
fig = self._pl.figure()
self._plot_1D(ar1d,x_range,labels,fig)
return self._maybe_savefig(fig)
#def plot2D(ar2d,x_range,y_range,labels=('Horizontal position, mm','Vertical position, mm')):
def uti_pl... |
jantman/awslimitchecker | dev/missing_instance_types.py | Python | agpl-3.0 | 1,475 | 0 | #!/usr/bin/env python
# List EC2 Instance Types
# see: https://aws.amazon.com/blogs/aws/new-aws-price-list-api/
import requests
from awslimitchecker.services.ec2 import _Ec2Service
print('GETing AWS Pricing Offers index JSON')
offers = requests.get(
'https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.j... | n alctypes:
print('MISSING INSTANCE TYPE: %s' % itype)
missing.append(itype)
print('awslimitchecker currently has %d of %d instance types' % (
| len(alctypes), len(uniq)
))
if len(missing) > 0:
print('Missing types: %s' % missing)
extra = []
for itype in sorted(alctypes):
if itype not in uniq:
print('EXTRA INSTANCE TYPE: %s' % itype)
extra.append(itype)
print('awslimitchecker currently has %d extra instance types' % len(extra))
if len(e... |
KleinYuan/cnn | core/base_graph.py | Python | mit | 2,591 | 0.003088 | import tensorflow as tf
class BaseGraph:
"""
A generic computation graph class, with only two constraints are
1. The requirements for net instance passed in:
- net should have method of define_net
- net should have method of get_placeholders
2. Losses can only be calculated w... | raph.as_default():
self.predictions = self.net.define_net()
self.x_pl, self.y_pl, self.is_training_pl = self.net.get_placeholders()
# Loss
try:
self.losses['mse'] = tf.reduce_mean(tf.square(self.predictions - self.y_pl))
self.losses['cross... | s=self.y_pl, logits=self.predictions))
except ValueError as e:
self.logger.warn(e)
self.loss = self.losses[self.loss_type]
tf.summary.scalar("loss", self.loss)
tf.summary.scalar("lr", self.learning_rate)
# Optimizer
self.optimizer... |
tainstr/misura.canon | misura/canon/option/tests/test_sqlstore.py | Python | mit | 3,011 | 0.000996 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
from misura.canon import option
from misura.canon.option import get_typed_cols, get_insert_cmd, base_col_def, print_tree
import sqlite3
from misura.canon.tests import testdir
db = testdir + 'storage/tmpdb'
c1 = testdir + 'storage/Conf.csv'
def go(t)... |
st = option.SqlStore(kid='ciao')
st.desc = st0.desc
k0 = set(st.desc.keys())
| cursor = self.conn.cursor()
st.write_table(cursor, 'conf1')
self.conn.commit()
cursor.execute('select handle from conf1')
r = cursor.fetchall()
k1 = set([eval(k[0]) for k in r])
self.assertEqual(k0, k1)
st2 = option.SqlStore(kid='ciao')
st2.read_tab... |
suutari-ai/shoop | shuup/testing/single_page_checkout_with_login_and_register_conf.py | Python | agpl-3.0 | 1,619 | 0.002471 | # This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.conf import settings
from django.conf.urls import include, url
from django.con... | t.empty:EmptyPhase"
urlpatterns = [
url(r'^checkout/$', SinglePageCheckoutViewWithLoginAndRegister.as_view(), name='checkout'),
url(r'^checkout/(?P<phase>.+)/$', SinglePageCheckoutViewWithLoginA | ndRegister.as_view(), name='checkout'),
url(r'^admin/', include(admin.site.urls)),
url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")),
url(r'^api/', include('shuup.api.urls')),
url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")),
] + static... |
vitchyr/rlkit | rlkit/torch/networks/cnn.py | Python | mit | 12,489 | 0.00016 | import numpy as np
import torch
from torch import nn as nn
from rlkit.policies.base import Policy
from rlkit.pythonplusplus import identity
from rlkit.torch.core import PyTorchModule, eval_np
from rlkit.torch.data_management.normalizer import TorchFixedNormalizer
from rlkit.torch.pytorch_util import activation_from_... | ormalization_type != 'none':
h = self.conv_norm_layers[i](h)
if self.pool_type != 'none':
h = self.pool_layers[i](h)
h = self.hidden_activation(h)
return h
def apply_forward_fc(self, h):
for i, layer in enumerate(self.fc_layers):
h... | lf.hidden_activation(h)
return h
class ConcatCNN(CNN):
"""
Concatenate inputs along dimension and then pass through MLP.
"""
def __init__(self, *args, dim=1, **kwargs):
super().__init__(*args, **kwargs)
self.dim = dim
def forward(self, *inputs, **kwargs):
flat_inpu... |
tortuepin/pomodoro-python | pomodoro.py | Python | mit | 5,789 | 0.012093 | import CursesTimer
import Audio
import Utils
import database
import datetime
class Pomodoro:
'''
pomodoro関連
'''
def __init__(self):
self.db = database.database()
self.t = CursesTimer.CursesTimer()
self.u = Utils.Utils()
self.NofPomodoro = 4 #休憩まで何回ポモドーロするか
... | lf):
'''
1日が終わった時に呼び出される関数
countをリセットし、次の1日が終わ | る時間を作る
'''
self.initPomodoroCount();
today = datetime.datetime.today()
#もし今のhourがdayendより前ならenddatetimeは今日
if today.hour < self.dayend:
self.nextEndDatetime = self.nextEndDatetime.replace(day = today.day)
#もし今のhourがdayendより後ならenddatatimeは明日
if today.ho... |
NoNotCar/monolith | Monolith/Vehicles.py | Python | mit | 2,659 | 0.002256 | '''
Created on 17 Jun 2015
Don't be late!
@author: NoNotCar
'''
import Entity
import Img
import pygame
class Vehicle( | Entity.Entity):
vspeed = 16
img = Img.blank32
name = "Vehicle"
pickup = False
solid = True
boat = False
def __init__(self, x, y, | p):
self.p = p
self.x = x
self.y = y
self.dir = (1, 0)
self.imgflip = False
self.fimg = pygame.transform.flip(self.img, True, False)
self.exinit(x, y, p)
self.output = []
self.hasp = False
def exinit(self, x, y, p):
pass
def get_... |
westinedu/similarinterest | zinnia/management/commands/feed2zinnia.py | Python | bsd-3-clause | 7,134 | 0.00014 | """Feed to Zinnia command module"""
import os
import sys
from urllib2 import urlopen
from datetime import datetime
from optparse import make_option
from django.conf import settings
from django.utils import timezone
from django.core.files import File
from django.utils.text import Truncator
from django.utils.html import... | ure in feed_entry.enclosures:
if 'image' in enclosure.get('type') \
and enclosur | e.get('href'):
img_tmp = NamedTemporaryFile(delete=True)
img_tmp.write(urlopen(enclosure['href']).read())
img_tmp.flush()
entry.image.save(os.path.basename(enclosure['href']),
File(im... |
PepperPD/edx-pepper-platform | common/djangoapps/track/views.py | Python | agpl-3.0 | 5,519 | 0.002355 | import json
import logging
import pytz
import datetime
import dateutil.parser
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import redirect
from django.conf import settings
from mitxmako.shortcuts import render_to_response
from django_future.csrf ... | ecord_instances = TrackingLog.objects.all().order_by('-time')
if username:
record_instances = record_instances.filter(username=username)
record_instances = record_instances[ | 0:nlen]
# fix dtstamp
fmt = '%a %d-%b-%y %H:%M:%S' # "%Y-%m-%d %H:%M:%S %Z%z"
for rinst in record_instances:
rinst.dtstr = rinst.time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Eastern')).strftime(fmt)
return render_to_response('tracking_log.html', {'records': record_instances})
|
ska/myels | Finestra.py | Python | gpl-3.0 | 6,515 | 0.015503 | #!/usr/bin/python
import socket
import time
from Tkinter import *
import logging
class Finestra:
def __init__(self):
self.__f=''
self.__s=''
self.__StatusBar=''
self.__ButtonAcition=''
self.__Slider=''
self.__APl='21'
self.__active=FALSE
s... | ht="150")
self.frameR2C1.configure( width="100", height="150")
self.frameR2C2.configure( width="100", height="150")
self.frameR3.configure( width="200", height="30", bd=1, relief=GROOVE)
self.frameR0.grid(row=0, column=0, columnspan=3)
self.frameR1C0.grid(ro | w=1, column=0)
self.frameR1C1.grid(row=1, column=1)
self.frameR1C2.grid(row=1, column=2)
self.frameR2C0.grid(row=2, column=0)
self.frameR2C1.grid(row=2, column=1)
self.frameR2C2.grid(row=2, column=2)
self.frameR3.grid(row=3, column=0, columnspan=3)
menubar... |
scaramallion/pynetdicom3 | pynetdicom/tests/test_sop.py | Python | mit | 18,339 | 0.002345 | """Tests for the sop_class module."""
import pytest
from pydicom._uid_dict import UID_dictionary
from pynetdicom.sop_class import (
uid_to_sop_class,
uid_to_service_class,
SOPClass,
_SERVICE_CLASSES,
_APPLICATION_EVENT_CLASSES,
ProceduralEventLoggingSOPClass,
_BASIC_WORKLIST_CLASSES,
... | ELEVANT_PATIENT_QUERY_CLASSES.values():
assert uid in UI | D_dictionary
for uid in _RT_MACHINE_VERIFICATION_CLASSES.values():
assert uid in UID_dictionary
for uid in _STORAGE_CLASSES.values():
assert uid in UID_dictionary
for uid in _STORAGE_COMMITMENT_CLASSES.values():
assert uid in UID_dictionary
for uid in _SUBSTANCE_ADMINISTRATION_CL... |
Yelp/ybinlogp | testing/print_events.py | Python | isc | 876 | 0 | """
Print events from a mysql binlog.
"""
import logging
import os.path
import sys
from ybinlogp import YBinlogP
def get_filename():
if len(sys.argv) != 2:
raise SystemExit("Usage: %s <filename>" % sys.argv[0])
return sys.argv[1]
def main(filename):
dirname = os.path.dirname(filename)
par | ser = YBinlogP(filename, always_update=True)
while True:
for i, event in enumerate(parser):
print event
if event.event_type == "ROTATE_EVENT":
next_file = os.path.join(dirname, event.data.file_name)
parser.close()
parser = YBinlogP(next... | True)
else:
print "Got to end at %r" % (parser.tell(),)
break
parser.close()
if __name__ == "__main__":
logging.basicConfig()
filename = get_filename()
main(filename)
|
eli261/jumpserver | apps/terminal/migrations/0005_auto_20180122_1154.py | Python | gpl-2.0 | 774 | 0.002584 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-01-22 03:54
from __future__ import unicode_literals
from django.db i | mport migrations, models
class Migration(migrations.Migration):
dependencies = [
('terminal', '0004_session_remote_addr'),
]
operations = [
migrations.AddField(
model_name='terminal',
name='command_storage',
field=models.CharField(choices=[('default', ... | model_name='terminal',
name='replay_storage',
field=models.CharField(default='default', max_length=128, verbose_name='Replay storage'),
),
]
|
emonty/ola | tools/rdm/ola_rdm_test.py | Python | lgpl-2.1 | 8,131 | 0.010085 | #!/usr/bin/python
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that ... | d for all devices
connected to the responder. Think twice about running this on your
production lighting rig.
""")
parser = OptionParser(usage, description=description)
parser.add_option('-c', '--slot_count', default=10,
help='Number of slots to send when sending DMX.')
parser.add_op... |
help='Print debug information to assist in diagnosing '
'failures.')
parser.add_option('-f', '--dmx_frame_rate', default=0,
type='int',
help='Send DMX frames at this rate in the background.')
parser.add_option('-l', '--log', metav... |
hysia/awsome-collections | python/rtcp.py | Python | cc0-1.0 | 4,783 | 0.035985 | # -*- coding: utf-8 -*-
'''
filename:rtcp.py
@desc:
利用python的socket端口转发,用于远程维护
如果连接不到远程,会sleep 36s,最多尝试200(即两小时)
@usage:
./rtcp.py stream1 stream2
stream为:l:port或c:host:port
l:port表示监听指定的本地端口
c:host:port表示监听远程指定的端口
@author: watercloud, zd, hysia
@date: 2009-7
使用场景:
一:
A服务器在内网,公网无法直接访问这台服务器,但是A服务器可以联网访问公网的B服务器(假设IP为... | sys.exit(1)
if streams[num] != None:
return streams[num]
else:
time.sleep(1)
def _xstream(num, s1, s2):
'''
交换两个流的数据
num为当前流编号,主要用于调试目的,区分两个回路状态用。
'''
try:
while True:
#注意,recv函数会阻塞,直到对端完全关闭(close后还需要一定时间才能关闭,最快关闭方法是shutdow)
buff = s1.recv(1024)
if debug > 0:
print num,"recv"
if len(... | nt num,"sendall"
except :
print num,"one connect closed."
try:
s1.shutdown(socket.SHUT_RDWR)
s1.close()
except:
pass
try:
s2.shutdown(socket.SHUT_RDWR)
s2.close()
except:
pass
streams[0] = None
streams[1] = None
print num, "CLOSED"
def _server(port, num):
'''
处理服务情况,num为流编号(第0号还是第1号)
'''
s... |
maandree/ponypass | src/obscurepass.py | Python | gpl-3.0 | 2,412 | 0.008306 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ponypass – Secure superultraawesomemasing passphrase wallet
#
# Copyright © 2013 Mattias Andrée (maandree@member.fsf.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
# ... | them to Princess Celestia so she can banish them to the moon)
@param text:str The text to print (empty string is default)
@param end:str The appendix to the text to print (line breaking is default)
'''
def print(text = '', end = '\ | n'):
sys.stdout.buffer.write((str(text) + end).encode('utf-8'))
def genobsure(length = 60):
lines = None
with open(GLYPHS, 'r') as file:
lines = [line.replace('\r', '') for line in file.read()[:-1].split('\n')]
count = 0
counts = []
firsts = []
for line in lines:
if '..' i... |
lykling/denyhosts | DenyHosts/util.py | Python | gpl-2.0 | 4,756 | 0.001051 | import sys
import os
import time
from smtplib | import SMTP
import logging
from constants import BSD_STYLE, TIME_SPEC_LOOKUP
from regex import TIME_SPEC_REGEX
from types import IntType
debug = logging.getLogger("util").debug
def setup_logging(prefs, enable_debug, verbose, daemon):
if daemon:
daemon_log = prefs.get('DAEMON_LOG')
if daemon_log:
... | fh.setLevel(logging.DEBUG)
msg_fmt = prefs.get('DAEMON_LOG_MESSAGE_FORMAT')
time_fmt = prefs.get('DAEMON_LOG_TIME_FORMAT')
formatter = logging.Formatter(msg_fmt, time_fmt)
fh.setFormatter(formatter)
# add the handler to the root logger
log... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/cache/memory.py | Python | bsd-3-clause | 1,272 | 0.001572 | # (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
cache: memory
short_description: RAM ba... |
return self._cache.get(key)
def set(self, key, value):
self._cache[key] = value
def keys(self):
retu | rn self._cache.keys()
def contains(self, key):
return key in self._cache
def delete(self, key):
del self._cache[key]
def flush(self):
self._cache = {}
def copy(self):
return self._cache.copy()
def __getstate__(self):
return self.copy()
def __setstate... |
makinacorpus/formhub | main/tests/test_form_api.py | Python | bsd-2-clause | 7,229 | 0.003597 | import json
from django.core.urlresolvers import reverse
from test_base import MainTestCase
from main.views import api
from odk_viewer.models.parsed_instance import ParsedInstance, \
_encode_for_mongo, _decode_from_mongo
import base64
def dict_for_mongo_without_userform_id(parsed_instance):
d = parsed_instan... | types_to_referral_facility":"none"}'
data = {'query': query, 'start': -100, 'limit': -100}
response = self.client.get(self.api_url, data)
self.assertEqual(response.status_code, 400)
def test_api_count(self):
# query string
query = '{"transport/available_transportation_types_... | e, 200)
find_d = json.loads(response.content)[0]
self.assertTrue(find_d.has_key('count'))
self.assertEqual(find_d.get('count'), 1)
def test_api_column_select(self):
# query string
query = '{"transport/available_transportation_types_to_referral_facility":"none"}'
colu... |
sghai/robottelo | tests/upgrades/test_subscription.py | Python | gpl-3.0 | 2,935 | 0 | """Test for subscription related Upgrade Scenario's
:Requirement: Upgraded Satellite
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: CLI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from nailgun import entities
from robottelo.test import APITestCase
from upgrade_tests import po... | and post-upgrade scenarios to test
manifest refresh before and after upgrade
Test Steps:
1. Before Satellite upgrade, upload a manifest.
2. Refresh the manifest.
3. Upgrade satellite.
4. Re | fresh the manifest.
5. Delete the manifest.
"""
@classmethod
def setUpClass(cls):
cls.manifest_url = os.environ.get('MANIFEST_URL')
cls.org_name = 'preupgrade_subscription_org'
@pre_upgrade
def test_pre_manifest_scenario_refresh(self):
"""Pre-upgrade scenario that uploa... |
erudit/eruditorg | eruditorg/erudit/admin/journal.py | Python | gpl-3.0 | 8,218 | 0.001583 | from django.contrib import admin
from django.contrib.admin.widgets import AdminIntegerFieldWidget
from django.core.validators import MaxValueValidator, MinValueValidator
from modeltranslation.admin import TranslationAdmin
from django.urls import reverse
from django.utils import timezone as tz
from django.utils.html imp... | e,
"issue_slug": obj.volume_slug,
"localidentifier": obj.localidentifier,
},
)
if not obj.is_published and obj.journal.collection.is_main_collection:
url = "{url}?ticket={ticket}". | format(url=url, ticket=obj.prepublication_ticket)
return format_html("<a href={}>{}</a>", url, _("Voir sur le site"))
view_issue_on_site.short_description = _("Voir le numéro sur le site")
def get_readonly_fields(self, request, obj=None):
return self.readonly_fields + ("is_published",)
class... |
geertj/gruvi | tests/perf_http.py | Python | mit | 2,074 | 0 | #
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... |
client.request('GET', '/')
for i in range(pipeline):
resp = client.getresponse()
self.assertEqual(resp.body.read(), b'Hello!')
nrequests += pipeline
| t1 = time.time()
throughput = nrequests / (t1 - t0)
self.add_result(throughput)
server.close()
client.close()
if __name__ == '__main__':
unittest.defaultTestLoader.testMethodPrefix = 'perf'
unittest.main()
|
briancurtin/python-openstacksdk | openstack/tests/unit/test_profile.py | Python | apache-2.0 | 4,605 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use t | his file except in compliance with the License. You may ob | tain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.