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 |
|---|---|---|---|---|---|---|---|---|
mosdef-hub/msibi | msibi/utils/error_calculation.py | Python | mit | 1,706 | 0.000586 | ##############################################################################
# MSIBI: A package for optimizing coarse-grained force fields using multistate
# iterative Boltzmann inversion.
# Copyright (c) 2017 Vanderbilt University and the Authors
#
# Authors: Christoph Klein, Timothy C. Moore
#
# | Permission is hereby granted, free of charge, to any p | erson obtaining a copy
# of this software and associated documentation files, to deal
# in MSIBI without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# # copies of MSIBI, and to permit persons to whom MSIBI is
# furnished to do so, subj... |
3dfxsoftware/cbss-addons | purchase_requisition_make_po/__init__.py | Python | gpl-2.0 | 28 | 0 | import p | urcha | se_requisition
|
ladybug-analysis-tools/butterfly | butterfly/g.py | Python | gpl-3.0 | 1,428 | 0 | # coding=utf-8
"""g[ravity] class."""
from foamfile import FoamFile, foam_file_from_file
from collections import OrderedDict
class G(FoamFile):
"""G (gravity) class."""
# set default valus for this class
__default_values = OrderedDict()
__default_values['dimensions'] = '[0 1 -2 0 0 0 0]'
__defaul... | de'] = None
__default_values['value'] = '(0 0 -9.81)'
def __init__(self, values=None):
"""Init class."""
FoamFile.__init__(self, name='g',
cls='uniformDimensionedVectorField',
location='constant',
default_values=self.... | values=values)
@classmethod
def from_file(cls, filepath):
"""Create a FoamFile from a file.
Args:
filepath: Full file path to dictionary.
"""
return cls(values=foam_file_from_file(filepath, cls.__name__))
@property
def dimensions(sel... |
Droriel/python_training | fixture/session.py | Python | apache-2.0 | 1,567 | 0.000639 | # -*- coding: utf-8 -*-
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
# Fill in username
wd.find_element_by_name("user").click()
wd.find_element_by_name("user").clear... | n password
wd.find_element_by_name("pass").click()
wd.find_element_by_name("pass").clear()
wd.find_element_by_name("pass").send_keys(password)
wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").click()
| if not self.is_logged_in():
raise ValueError()
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Wyloguj się").click()
def ensure_logout(self):
wd = self.app.wd
if self.is_logged_in():
self.logout()
def is_logged_in_as(self, username... |
pbrod/scipy | scipy/optimize/_trustregion.py | Python | bsd-3-clause | 8,925 | 0 | """Trust-region optimization."""
from __future__ import division, print_function | , absolute_import
import math
import numpy as np
import scipy.linalg
from .optimize import (_check_unknown_options, wrap_function, _status_message,
OptimizeResult)
__all__ = []
class BaseQuadraticSubproblem(object):
"""
Base/ab | stract class defining the quadratic model for trust-region
minimization. Child classes must implement the ``solve`` method.
Values of the objective function, jacobian and hessian (if provided) at
the current iterate ``x`` are evaluated on demand and then stored as
attributes ``fun``, ``jac``, ``hess``.... |
0x0aNL/p2pool-0x0a | p2pool/networks/solcoin.py | Python | gpl-3.0 | 599 | 0.013356 | from p2pool.bitcoin import networks
PARENT | = networks.nets['solcoin']
SHARE_PERIOD = 20 # seconds target spacing
CHAIN_LENGTH = 12*60*60//20 # shares
R | EAL_CHAIN_LENGTH = 12*60*60//20 # shares
TARGET_LOOKBEHIND = 15 # shares
SPREAD = 20 # blocks
IDENTIFIER = 'e0f0b08e5af1e89a'.decode('hex')
PREFIX = 'a6f2b07e0ac18b6e'.decode('hex')
P2P_PORT =7360
MIN_TARGET = 0
MAX_TARGET = 2**256//2**20 - 1
PERSIST = False
WORKER_PORT = 8360
BOOTSTRAP_ADDRS = 'p2pool.solcoin.net rav3... |
yaitza/python | PROJECT2016/xmltoexcel/write_excel.py | Python | apache-2.0 | 2,920 | 0.004549 | #!/usr/bin/python
# coding=utf-8
import os
import xlwt
from xml_handler import xml_handler
from xml_testcase import xml_testcase
class write_excel:
def __init__(self, xml_path):
self.xml_path = xml_path
self.work_book = xlwt.Workbook()
self.work_sheet = self.work_book.add_sheet('test_case... | testcases.xls"
print case_dir_excel
wr = write_excel(case_dir_xml)
wr.write_title()
wr.write_content()
wr.save_excel( | case_dir_excel)
|
zhouhan0126/SCREENTEST1 | tests/splinter_test.py | Python | gpl-2.0 | 11,129 | 0.002067 | from splinter import Browser
from time import sleep
from selenium.common.exceptions import ElementNotVisibleException
from settings import settings
from lib import db
from lib import assets_helper
import unittest
from datetime import datetime, timedelta
asset_x = {
'mimetype': u'web',
'asset_id': u'4c8dbce552e... | = 'http://foo:bar@localhost:8080'
settings_url = 'http://foo:bar@localhost:8080/settings'
system_info_url = 'http://foo:bar@localhost:8080/system_info'
def wait_for_and_do(browser, query, callback):
not_filled = True
n = 0
whi | le not_filled:
try:
callback(browser.find_by_css(query).first)
not_filled = False
except ElementNotVisibleException, e:
if n > 20:
raise e
n += 1
class WebTest(unittest.TestCase):
def setUp(self):
with db.conn(settings['databa... |
vlmaksime/plugin.video.zona.mobi | tests.py | Python | gpl-3.0 | 5,425 | 0.002949 | # coding: utf-8
# Module: tests
import os
import sys
import unittest
import shutil
cwd = os.path.dirname(os.path.abspath(__file__))
cache_dir = os.path.join(cwd, 'cache')
plugin_name = 'plugin.video.zona.mobi'
# Import our module being tested
sys.path.append(os.path.join(cwd, plugin_name))
from resources.lib.zonamo... | o = False
print('In list %d movies:' % (video_list['count']))
for video in video_list['list']:
video_info = video['video_info']
print('name_id: %s' % (video_info['name_id']))
has_video = True
self.assertTrue(has_video)
def test_browse_content_tv | series(self):
print('\n#test_browse_content_tvseries')
video_list = self.api.get_video_list('tvseries')
has_video = False
print('In list %d tvseries:' % (video_list['count']))
for video in video_list['list']:
video_info = video['video_info']
print('name... |
alanjw/GreenOpenERP-Win-X86 | openerp/addons/stock/stock.py | Python | agpl-3.0 | 163,768 | 0.006106 | # -*- 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... | not prod_id:
return dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
| product_product_obj = self.pool.get('product.product')
cr.execute('select distinct product_id, location_id from stock_move where location_id in %s', (tuple(ids), ))
dict1 = cr.dictfetchall()
cr.execute('select distinct product_id, location_dest_id as location_id from stock_move where locati... |
rolandovillca/python_basis | function_python/the__init__function.py | Python | mit | 1,797 | 0.007234 | '''
What does self do? what is it meant to be? and is it mandatory?
What does the __init__ method do? why is it necessary?
'''
# EXAMPLE 1:
# ==============================================================================
# here's a simple example I used to understand the difference between a variable
# declared insid... | def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
'''
The self variable represents the instance of the object itself.
Most object-oriented languages pass this as a hidden parameter to the methods
defined on an object; Python does not. You have to declare it e... | e of the A class and call its methods, it will be
passed automatically, as in ...
'''
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
'''
The __init__ method is roughly what represents a constructor in Python.
When you call A() Python ... |
forseti-security/forseti-security | tests/scanner/scanners/forwarding_rule_rules_scanner_test.py | Python | apache-2.0 | 7,464 | 0.003215 | # Copyright 2017 The Forseti Security 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 ap... |
from tests.unittest_utils import ForsetiTestCase
from google.cloud.forseti.scanner.scanners import forwarding_rule_scanner
from tests.unittest_utils import get_datafile_path
from google.cloud.forseti.common.gcp_type import forwarding_rule as fr
class ForwardingRule(object):
"""Represents ForwardRule resource."""... | t_datafile_path(__file__,
'forward_rule_test_1.yaml')
scanner = forwarding_rule_scanner.ForwardingRuleScanner(
{}, {}, mock.MagicMock(), '', '', rules_local_path)
project_id = "abc-123"
gcp_forwarding_rules_resource_data = [
{
"id": "46",
... |
servalproject/nikola | nikola/plugins/command_import_blogger.py | Python | mit | 7,714 | 0.00013 | # Copyright (c) 2012 Roberto Alsina y otros.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, pub... | self.context['REDIRECTIONS'] = self.configure_redirections(
self.url_map)
self.import_posts(channel)
self.write_urlmap_csv(
os.path | .join(self.output_folder, 'url_map.csv'), self.url_map)
self.write_configuration(self.get_configuration_output_path(
), conf_template.render(**self.context))
@classmethod
def get_channel_from_file(cls, filename):
if not os.path.isfile(filename):
raise Exception("Missing fil... |
timdiels/chicken_turtle_util | pytil/test.py | Python | lgpl-3.0 | 2,286 | 0.000875 | # Copyright (C) 2016 VIB/BEG/UGent - Tim Diels <tim@diels.me>
#
# This file is part of pytil.
#
# pytil 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 3 of the License, or
# (at your opt... | return set(map(str, children - ignored_children))
expected = contents()
yield
actual = contents()
assert actual | == expected, f'\nActual: {actual}\nExpected: {expected}'
|
JonnaStalring/AZOrange | azorange/AZutilities/TCPMondrian.py | Python | lgpl-3.0 | 33,237 | 0.008033 | #import printStatWithName
from AZutilities import dataUtilities
from AZutilities import paramOptUtilities
from trainingMethods import AZorngRF
from trainingMethods import AZorngCvSVM
import Orange
import orange
import math
import copy
import string
"""
Modul | e for calculation of non conformity scores and the corresponding p-values and
conformal predictions for binary classifiers.
getPvalue
|
|
getScore
|
|
{Methods to calculate the non-conf score}
"""
def meanStd(data):
| """ Calculate mean and standard deviation of data data[]: """
length, mean, std = len(data), 0, 0
for elem in data:
mean = mean + elem
mean = mean / float(length)
for elem in data:
std = std + (elem - mean) ** 2
std = math.sqrt(std / float(length))
mean = round(mean, 3)
std =... |
sqlalchemy/mako | mako/cmd.py | Python | mit | 2,814 | 0.001066 | # mako/cmd.py
# Copyright 2006-2021 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from argparse import ArgumentParser
from os.path import dirname
from os.path import isfile
import sys
from... | te().render())
sys.exit(1)
def cmdline(argv=None):
parser = ArgumentParser()
parser.add_argument | (
"--var",
default=[],
action="append",
help="variable (can be used multiple times, use name=value)",
)
parser.add_argument(
"--template-dir",
default=[],
action="append",
help="Directory to use for template lookup (multiple "
"directories ... |
lesglaneurs/lesglaneurs | presentation/migrations/0013_auto_20160505_1512.py | Python | gpl-3.0 | 790 | 0.002532 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('presentation', | '0012_auto_20160505_1508'),
]
operations = [
migrations.CreateModel(
name='Role',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(default=b'membre', help_text=b... | rsonne pour un projet en particulier", max_length=128)),
],
),
migrations.AlterField(
model_name='membership',
name='membership',
field=models.ForeignKey(to='presentation.Role'),
),
]
|
ericforbes/post-review | postreview/BaseService.py | Python | mit | 994 | 0.006036 | from __future__ import absolute_import
from builtins import object
from .logger import create_logger
from future.utils import with_metaclass
class Meta(type):
def __str__(self):
return self.SERVICE_NAME
class BaseService(with_metaclass(Meta, object)):
SERVICE_NAME = None
GIT_CONFIG_API_KEY = None
... | pace, project, logger):
self.source_branch = source
self.parent_branch = parent
self.origin_domain = origin_domain
self.namespace = namespace
self.project = project
self.logger = logger
def issue_pull_request(self, obj):
raise NotImplementedError()
... | t_branch_exists(self, token):
raise NotImplementedError()
@classmethod
def check_service_name(child_impl_class, service_name):
return service_name == child_impl_class.SERVICE_NAME |
xelphene/swaf | swaf/__init__.py | Python | gpl-3.0 | 704 | 0.039773 |
import operator
def makeHandler(callable, route, filters=None, description=None):
assert operator.isCallable(callable)
calla | ble.swaf_route = route
callable.swaf_filters = filters
callable.swaf_description = description
return callable
def handler(route, filters=None, description=None):
def decorate(o):
o = makeHandler(o, route, filters, description)
return o
return decorate
def makeFilter(f, filter_name=None, filters=None):
if... |
def filter(filter_name=None, filters=None):
def decorate(o):
o = makeFilter(o, filter_name, filters)
return o
return decorate
|
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/isomorphism/__init__.py | Python | gpl-3.0 | 354 | 0 | from networkx.algorithms.isomorphism.isomorph import *
from networkx.algorithms.isomorphism.vf2userfunc import *
from networkx.algorithms.isomorphism.matchhelpers import *
from networkx.algorithms.isomorphism.tempor | alisomorphvf2 import *
from networkx.algorithms.isomorphism.ismags import *
from networkx.algorithms.isomor | phism.tree_isomorphism import *
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/PIL/_imaging.py | Python | gpl-2.0 | 3,425 | 0.026277 | # encoding: utf-8
# module PIL._imaging
# from /us | r/lib/python2.7/dist-pac | kages/PIL/_imaging.so
# by generator 1.135
# no doc
# no imports
# Variables with simple values
DEFAULT_STRATEGY = 0
FILTERED = 1
FIXED = 4
HUFFMAN_ONLY = 2
jpeglib_version = '8.0'
PILLOW_VERSION = '2.5.1'
RLE = 3
zlib_version = '1.2.8'
# functions
def alpha_composite(*args, **kwargs): # real signature unknow... |
pegasus-isi/pegasus | packages/pegasus-python/src/Pegasus/service/_encoder.py | Python | apache-2.0 | 1,941 | 0.00103 | __author__ = "Rajiv Mayani"
import logging
import uuid
from decimal import Decimal
from enum import Enum
from flask.json import JSONEncoder
from sqlalchemy import inspect
from Pegasus.service.base import ErrorResponse, OrderedDict, PagedResponse
log = logging.getLogger(__name__)
class PegasusJsonEncoder(JSONEncod... | elif hasattr(o, "__json__"):
return o.__json__()
elif hasattr(o, "__table__"):
unloaded = | inspect(o).unloaded
_v = {
k: getattr(o, k)
for k in o.__mapper__.column_attrs.keys()
if k not in unloaded
}
for k in getattr(o, "__includes__", {}):
_v[k] = getattr(o, k)
for k in getattr(o, "__excludes__... |
googleapis/python-oslogin | scripts/fixup_oslogin_v1_keywords.py | Python | apache-2.0 | 6,257 | 0.000959 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | args + kwargs)]),
keyword=cst.Name("request")
)
return updated.with_changes(
args=[request_arg] + ctrl_kwargs
)
def fix_files(
in_dir: pathlib.Path,
out_dir: pathlib.Path,
*,
transformer=osloginCallTransformer(),
):
"""Duplicate the input dir to th... | * in_dir is a real directory
* out_dir is a real, empty directory
"""
pyfile_gen = (
pathlib.Path(os.path.join(root, f))
for root, _, files in os.walk(in_dir)
for f in files if os.path.splitext(f)[1] == ".py"
)
for fpath in pyfile_gen:
with open(fpath, 'r') as f:
... |
mscuthbert/abjad | abjad/tools/indicatortools/test/test_indicatortools_Tempo__to_markup.py | Python | gpl-3.0 | 1,253 | 0.000798 | # -*- encoding: utf -*-
from abjad import *
def test_indicatortools_Tempo__to_markup_01():
tempo = Tempo(Duration(1, 4), 60)
markup = tempo._to_markup()
assert systemtools.Tes | tManager.compare(
markup,
r'''
\markup {
\fontsize
#-6
\general-ali | gn
#Y
#DOWN
\note-by-number
#2
#0
#1
\upright
{
=
60
}
}
'''
), format(marku... |
dladd/pyFormex | pyformex/gui/colors.py | Python | gpl-3.0 | 5,194 | 0.010974 | # $Id$
##
## This file is part of pyFormex 0.8.9 (Fri Nov 9 10:49:51 CET 2012)
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: http://pyformex.org
## Project page: http://savannah.nongnu.org/projects/pyformex/
##... | nput can be any of the following:
- a QColor
- a string specifying the Xwindow name of the color
- a hex string '#RGB' with 1 to 4 hexadecimal digits per color
- a tuple or list of 3 integer values in the range 0..255
- a tuple or list of 3 f | loat values in the range 0.0..1.0
Any other input may give unpredictable results.
Examples:
>>> GLcolor('indianred')
(0.803921568627451, 0.3607843137254902, 0.3607843137254902)
>>> print(GLcolor('#ff0000'))
(1.0, 0.0, 0.0)
>>> GLcolor(red)
(1.0, 0.0, 0.0)
>>> GLcolor([200,200,255])... |
ddimensia/RaceCapture_App | autosportlabs/racecapture/views/util/alertview.py | Python | gpl-3.0 | 3,843 | 0.017695 | import kivy
kivy.require('1.9.1')
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.metrics import dp
from kivy.app import Builder
from kivy.properties import StringProperty, ObjectProperty
from kivy.clock import Clock
from kivy.metrics import sp
from... | lf.register_event_type('on_answer')
super(ConfirmPopup,self).__init__(**kwargs)
def on_answer(self, *args):
pass
def editor_popup(title | , content, answerCallback):
content = EditorPopup(content=content)
content.bind(on_answer=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(0.7, 0.8),
auto_dismiss= False,
title_size=sp(18))
popup.open()
... |
Doveps/savant | savant/db.py | Python | mit | 906 | 0.003311 | # Copyright (c) 2015 Kurt Yoder
# See the file LICENSE for copying permission.
import os
import logging
import ZODB
import BTrees.OOBTree
import transaction
class DB(object):
'''Encapsulate access to the inferences database.'''
def __init__(self, path):
self.path = os.path.join(path, 'inferences.zodb... | name__ + '.' + type(self).__name__)
self.db = ZODB.DB(self.path)
self.connection = self.db.open()
self.dbroot = self.connection.root()
self.logger.debug('dbroot has: %s',self.dbroot)
for root in ['comparisons', 'sets', 'playbooks']:
if not root in self.dbroot:
... | lf):
transaction.commit()
|
jordanemedlock/psychtruths | temboo/core/Library/Flickr/Tags/ListPopularTags.py | Python | apache-2.0 | 4,964 | 0.005439 | # -*- coding: utf-8 -*-
###############################################################################
#
# ListPopularTags
# Retrieves the popular tags for a given user (or the currently logged in user).
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2... | ameters. When OAuth parameters are passed, the authenticated user is assu | med.)
"""
super(ListPopularTagsInputSet, self)._set_input('UserID', value)
class ListPopularTagsResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the ListPopularTags Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"... |
uclaros/QGIS | python/plugins/db_manager/db_plugins/html_elems.py | Python | gpl-2.0 | 5,237 | 0.000573 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@... | return html
def hasContents(self):
if isinstance(self.data, list) or isinstance(self.data, tuple):
empty = True
for item in self.data:
if item.hasContents():
empty = False
break
return not empty
if hasat... | |
hesseltuinhof/mxnet | python/mxnet/gluon/model_zoo/__init__.py | Python | apache-2.0 | 105 | 0 | # coding: utf-8
"""Prede | fined and pretrained models."""
from . import model_store
from . impor | t vision
|
ericd/redeem | redeem/gcodes/M668.py | Python | gpl-3.0 | 835 | 0.00479 | """
GCode M668
Adjust backlash compensation for each named axis
M668 Xn Yn | Zn En Hn An Bn Cn
Author: Anthony Clay
License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/
"""
from GCodeCommand import GCodeCommand
import logging
class M668(GCodeCommand):
def execute(self, g):
for index, axis in enumerate(["X", "Y", "Z", "E", "H", "A", "B", "C"]):
if g.has... | on[index] = float(g.get_value_by_letter(axis))/1000.0 # Convert to meters.
logging.info("Backlash compensation for axis " + str(axis) + " changed to " + str(self.printer.backlash_compensation[index]))
self.printer.path_planner.update_backlash()
def get_description(self):
ret... |
samdsmx/omegaup | frontend/tests/ui/conftest.py | Python | bsd-3-clause | 23,897 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# type: ignore
'''Fixtures for Selenium end-to-end tests.'''
import contextlib
import json
import logging
import os.path
import time
import urllib
from typing import Optional
import pytest
from selenium import webdriver
from selenium.common.exceptions import WebDriver... | ''Helper to _really_ send keys to an element.
For some yet unexplained reason when running in non-headless mode, the
interactions | with text elements do not always register by the browser.
This causes input elements to remain empty even after sending the keys.
T |
eandersson/python-rabbitmq-examples | Flask-examples/amqpstorm_threaded_rpc_client.py | Python | gpl-3.0 | 3,624 | 0 | """
This is a simple example on how to use Flask and Asynchronous RPC calls.
I kept this simple, but if you want to use this properly you will need
to expand the concept.
Things that are not included in this example.
- Reconnection strategy.
- Consider implementing utility functionality for checking and gett... | ses.
def has_response(correlation_id)
def get_response(correlation_id)
Apache/wsgi configuration.
- Each process you start with apache will create a new connection to
RabbitMQ.
- I would r | ecommend depending on the size of the payload that you have
about 100 threads per process. If the payload is larger, it might be
worth to keep a lower thread count per process.
For questions feel free to email me: me@eandersson.net
"""
__author__ = 'eandersson'
import threading
from time import sleep
fro... |
smozaffari/WASP | CHT/chromstat.py | Python | apache-2.0 | 4,398 | 0.004093 |
import sys
import numpy as np
class ChromStats(object):
def __init__(self):
self.n = 0
self.n_nan = 0
self.sum = 0
self.min = None
self.max = None
def mean(self):
"""Calculates mean of sites that are not nan
on this chromsome"""
n = self.n - s... | ist, verbose=False):
| """Retrieves stats that are stored as attributes for the specified
set of chromosomes."""
combined = ChromStats()
chrom_stat = ChromStats()
for chrom in chrom_list:
node_name = "/%s" % chrom.name
if node_name in h5f:
node = h5f.getNode(node_name)
if 'n' no... |
rkmaddox/mne-python | examples/visualization/xhemi.py | Python | bsd-3-clause | 1,520 | 0 | # -*- coding: utf-8 -*-
"""
===========================
Cross-hemisphere comparison
===========================
This example illustrates how to visualize the difference between activity in
the left and the right hemisphere. The data from the right hemisphere is
mapped to the left hemisphere, and then the difference is... | tc = mne.compute_source_morph(stc, 'sample', 'fsaverage_sym', smooth=5,
| warn=False,
subjects_dir=subjects_dir).apply(stc)
# Compute a morph-matrix mapping the right to the left hemisphere,
# and vice-versa.
morph = mne.compute_source_morph(stc, 'fsaverage_sym', 'fsaverage_sym',
spacing=stc.vertices, warn=Fa... |
syedshabihhasan/UtilityCode | src/combine_num_files.py | Python | gpl-2.0 | 1,705 | 0.000587 | # author: Syed Shabih Hasan
import argparse
import os
import sys
from tqdm import tqdm
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("-f", help="folder", required=True)
parser.add_argument("-e", help="extension", required=True)
parser.add_argument("-o", help="output", require... |
def main():
print("starting...gathering arguments")
folder, extension, output, first_line = get_args()
sorted_file_list = get_sorted_list(folder, extension)
err = combine_files(sorted_file_list, output, first_line)
print("errors:")
if len(err) == 0:
print("None")
else:
| for i in err:
print(i, err[i])
print("TADAAA!")
if __name__ == "__main__":
main()
|
JoelBondurant/RandomCodeSamples | python/routes.py | Python | apache-2.0 | 575 | 0.027826 | fin = open("routesRaw.txt", "r")
routes = {}
for x in fin:
xs = x.split("\t")
routeId = | xs[1]
operationId = xs[2]
stepNumber = int(xs[3].replace("\n", ""))
if (routeId in routes):
routes[routeId].append(operationId)
else:
routes[routeId] = []
routes[routeId].append(operationId)
if (len(routes[routeId]) != stepNumber):
input("err!")
fin.close()
fout = open("routes.txt", "w")
... | fout.close()
|
yclavinas/TSA | semurl.py | Python | bsd-3-clause | 988 | 0.01417 | #!/usr/bin/python
import re
# phone = "2004-959-559 # This is Phone Number http://www.google.com \n"
# # Delete Python-style comments
# num = re.sub(r'#.*$', "", phone)
# # print "Phone Num : ", num
# # Remove anything other than digits
# num = re.sub(r'\D', "", phone)
# # print "Phone Num : ", num
# phone = "20... | TILINE)
#melhorar ne?
data = re.sub(r'[a-z]*@[a-z]+mail.com', '', data, flag | s=re.MULTILINE)
saveFile.write(data)
saveFile.write('\n')
print("End :D")
saveFile.close()
text.close() |
trungdtbk/faucet | tests/unit/faucet/test_valve_dot1x.py | Python | apache-2.0 | 4,824 | 0.001036 | #!/usr/bin/env python
"""Unit tests run as PYTHONPATH=../../.. python3 ./test_valve_dot1x.py."""
# Copyright (C) 2015 Research and Innovation Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2019 The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... | y of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific ... | ttest
from faucet import faucet_dot1x
from clib.valve_test_lib import DOT1X_CONFIG, DOT1X_ACL_CONFIG, ValveTestBases
class ValveDot1xSmokeTestCase(ValveTestBases.ValveTestNetwork):
"""Smoke test to check dot1x can be initialized."""
CONFIG = """
dps:
s1:
%s
interfaces:
p1:
... |
chrispaul/attracker | attracker_app/migrations/0002_segment_additional_miles.py | Python | mit | 455 | 0.002198 | # -*- coding | : utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('attracker_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='segment',
name='additional_mi... | field=models.FloatField(default=0, verbose_name='Non-AT miles hiked with the segment'),
),
]
|
tardyp/buildbot | master/buildbot/test/integration/test_worker_comm.py | Python | gpl-2.0 | 13,868 | 0.000361 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | # clear out master_persp on disconnect
def clear_persp():
self.master_persp = None
persp.broker.notifyOnDisconnect(clear_persp)
def fire_deferreds():
self._detached = True
self._detach_deferreds, deferreds = None, self._detach_deferreds
for d ... | te_print(%r)" % (message,))
def remote_getWorkerInfo(self):
return {
'info': 'here',
'worker_commands': {
'x': 1,
},
'numcpus': 1,
'none': None,
'os_release': b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(),
... |
jrydberg/edgy | src/edgy/xml/xpath/atoms.py | Python | mit | 3,689 | 0.002982 | #
# pdis.xpath.atoms
#
# Copyright 2004 Helsinki Institute for Information Technology (HIIT)
# and the authors. All rights reserved.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Sof... | athEvaluationError, \
' | Unbound namespace prefix "%s".' % self.prefix
if self.local_part == '*':
name = None
else:
name = self.local_part
return (uri, name)
class FunctionName(QName):
pass
#
# Atomic nodes
#
class Literal:
"""
Node representing a string literal
"""
def __... |
LowResourceLanguages/hltdi-l3 | disambiguatr/mostfrequent.py | Python | gpl-3.0 | 1,841 | 0.003259 | #!/usr/bin/env python3
import re
import sys
from learner import Learner
class MostFrequentBaseline(Learner):
def __init__(self, xs):
"""Find the most frequent qw out of these training instances and build
a classifier that always returns that as its answer."""
classes = [x.qw for x in xs]
... | rgv[2].
class MostFrequentOverText(Learner):
"""Classifier that always returns the MFS, but considering the whole text,
n | ot just the instances in the ambiguous pairs we extracted."""
def __init__(self, xs):
"""Find the most frequent qw out of these training instances and build
a classifier that always returns that as its answer."""
classes = [x.qw for x in xs]
uniqueclasses = sorted(set(classes))
... |
fedspendingtransparency/data-act-validator | dataactvalidator/migrations/versions/c0a714ade734_adding_timestamps_to_all_tables.py | Python | cc0-1.0 | 3,174 | 0.007876 | """adding timestamps to all tables
Revision ID: c0a714ade734
Revises: 1a886e694fca
Create Date: 2016-04-20 14:46:06.407765
"""
# revision identifiers, used by Alembic.
revision = 'c0a714ade734'
down_revision = '1a886e694fca'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def ... | eated_at')
op.drop_column('multi_field_rule_type', 'updated_at')
op.drop_column('multi_field_rule_type', 'created_at')
op.drop_column('multi_field_rule', 'updated_at')
op.drop_column('multi_field_rule', 'created_at')
op.drop_column('file_type', 'updated_at')
op.drop_colu | mn('file_type', 'created_at')
op.drop_column('file_columns', 'updated_at')
op.drop_column('file_columns', 'created_at')
op.drop_column('field_type', 'updated_at')
op.drop_column('field_type', 'created_at')
### end Alembic commands ###
|
bjaraujo/ENigMA | trunk/wrappers/swig/python/examples/csg1.py | Python | gpl-2.0 | 1,025 | 0.016585 |
import subprocess
from ENigMA import ENigMA
center = ENigMA.CGeoCoordinateDouble(0,0,0)
radius = ENigMA.CGeoVectorDouble(1,1,1)
a = ENigMA.CCsgCubeDouble.create(center, radius)
b = ENigMA.CCsgSphereDouble.create(center, 1.35, 16, 12)
vertex_x1 = ENigMA.CGeoCoordinateDouble(-2,0,0)
vertex_x2 = ENigMA.C... | rdinateDouble(0,0,-2)
vertex_z2 = ENigMA.CGeoCoordinateDouble(0,0,+2)
e = ENigMA.CCsgCylinderDouble.create(vertex_z1, vertex_z2, 0.7, 16)
tol = 1E-6
a.setTolerance(tol)
b.setTolerance(tol)
c.setTolerance(tol)
d.setTolerance(tol)
e.setTolerance(tol)
f = a.intersect(b).subtract(c.add(d).add(e))
print(... | l'])
|
mjs/juju | acceptancetests/tests/test_assess_budget.py | Python | agpl-3.0 | 12,438 | 0.000161 | """Tests for assess_budget module."""
import logging
import json
from random import randint
import StringIO
from subprocess import CalledProcessError
from mock import (
Mock,
patch,
)
from assess_budget import (
_try_greater_than_limit_budget,
_try_negative_budget,
assess_budget,
assess_budge... | autospec=True)
set_b = patch("assess_budget.assess_set_budget",
autospec=True)
create_b = patch("assess_budget.assess_create_budget",
autospec=True)
b_limit = patch("assess_budget | .assess_budget_limit",
autospec=True)
init_b = patch("assess_budget._try_setting_budget",
autospec=True)
expect_b = patch("assess_budget._set_budget_value_expectations",
autospec=True)
update_e = patch("assess_budget._get_bu... |
cloudant/python-cloudant | src/cloudant/error.py | Python | apache-2.0 | 7,385 | 0.001354 | #!/usr/bin/env python
# Copyright (c) 2015, 2016 IBM. 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 requir... | : A list of arguments used to format the exception message.
"""
def __init__(self, code=100, *args):
try:
msg = CLIENT[code].format(*args)
except (KeyError, IndexError):
code = 100
msg = CLIENT[code]
super(CloudantClientException, self).__init__(msg, c... | """
Provides a way to issue Cloudant library database specific exceptions.
:param int code: A code value used to identify the database exception.
:param args: A list of arguments used to format the exception message.
"""
def __init__(self, code=100, *args):
try:
if code in DATA... |
plotly/python-api | packages/python/plotly/plotly/validators/layout/coloraxis/_colorscale.py | Python | mit | 560 | 0.003571 | import _plotly_utils.basevalidators
class ColorscaleValidator(_plotly_utils.basevalidators.ColorscaleValidator):
def __init | __(
self, plotly_name="colorscale", parent_name="layout.coloraxis", **kwargs
):
super(ColorscaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
implied_edits=kwargs.pop("implied_ed... | )
|
obi-two/Rebelion | data/scripts/templates/object/tangible/loot/collectible/collectible_parts/shared_sculpture_structure_04.py | Python | mit | 508 | 0.043307 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/collectible/collectible_parts/sha | red_sculpture_structure_04.iff"
result.attribute_template_id = -1
result.stfName("collectible_loot_items_n","sculpture_structure_04")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return | result |
shaneHowearth/Statutory_Holidays | New_Zealand/Provincial/Taranaki.py | Python | gpl-2.0 | 392 | 0.007653 | __author_ | _ = 'shane'
from datetime import date, timedelta
def get_holiday(year):
MARCH=3
# Second Monday in March, to avoid Easter
weekday = date(year, MARCH, 1).weekday()
# 0 +1
if weekday == 0:
day = 7
else:
day = 8 - weekday
return date(year, MARCH, day) + timedelta(days=7)
def ... | 1)
|
y4n9squared/HEtest | hetest/python/circuit_generation/circuit_common/file_handle_object.py | Python | bsd-2-clause | 2,432 | 0.001645 |
# *****************************************************************
# Copyright (c) 2013 Massachusetts Institute of Technology
#
# Developed exclusively at US Government expense under US Air Force contract
# FA8721-05-C-002. The rights of the United States Government to use, modify,
# reproduce, release, perform, disp... | n.
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def get_file_object(self, file_name, command):
"""returns a file object. command shoule be either 'r' or 'w'."""
# this method exists to aid in unit testing. we do not want to actually
# be accessing files | during unit tests, so we will use a subclass
# of this class wherein this method is overwritten.
return open(file_name, command)
def close_file_object(self, file_object):
"""closes the file object."""
# this method exists to aid in unit testing. we do not want to
# be closi... |
sonofatailor/django-oscar | src/oscar/apps/dashboard/app.py | Python | bsd-3-clause | 2,615 | 0 | from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.contrib.auth.forms import AuthenticationForm
from oscar.core.application import (
DashboardApplication as BaseDashboardApplication)
from oscar.core.loading import get_class
class DashboardApplication(BaseDashboardApp... | url(r'^users/', self.users_app.urls),
url(r'^content-blocks/', s | elf.promotions_app.urls),
url(r'^pages/', self.pages_app.urls),
url(r'^partners/', self.partners_app.urls),
url(r'^offers/', self.offers_app.urls),
url(r'^ranges/', self.ranges_app.urls),
url(r'^reviews/', self.reviews_app.urls),
url(r'^vouchers/',... |
adrientetar/robofab | Lib/robofab/pens/printingPens.py | Python | bsd-3-clause | 2,042 | 0.028404 | from robofab.pens.pointPen import BasePointToSegmentPen
from ufoLib.pointPen import AbstractPointPen
"""
Printing pens print their data. Useful for demos and debugging.
"""
__all__ = ["PrintingPointPen", "PrintingSegmentPen", "SegmentPrintingPointPen"]
class PrintingPointPen(AbstractPointPen):
"""A PointPen tha... | assert not self.havePath
print("pen.addComponent(%r, %s)" % (baseGlyphNam | e, tuple(transformation)))
from fontTools.pens.basePen import AbstractPen
class PrintingSegmentPen(AbstractPen):
"""A SegmentPen that prints every step.
"""
def moveTo(self, pt):
print("pen.moveTo(%s)" % (pt,))
def lineTo(self, pt):
print("pen.lineTo(%s)" % (pt,))
def curveTo(self, *pts):
print("pe... |
merenlab/anvio | anvio/migrations/profile/v32_to_v33.py | Python | gpl-3.0 | 3,027 | 0.007268 | #!/usr/bin/env python
# -*- coding: utf-8
import sys
import argparse
import anvio.db as db
import anvio.utils as utils
import anvio.terminal as terminal
from anvio.errors import ConfigError
run = terminal.Run()
progress = terminal.Progress()
current_version, next_version = [x[1:] for x in __name__.split('_to_')]
... | -----------------------
progress.new('Updating DB')
variable_nts_table_name = 'variable_nucleotides'
if variable_nts_table_name in tables_in_db:
progress.update('Renaming columns in variability table...')
profile_db._exec("""ALTER TABLE %s RE | NAME COLUMN in_partial_gene_call TO in_noncoding_gene_call;""" % variable_nts_table_name)
profile_db._exec("""ALTER TABLE %s RENAME COLUMN in_complete_gene_call TO in_coding_gene_call;""" % variable_nts_table_name)
# ---------------------------------------------------------------------------------
# b... |
joeghodsi/interview-questions | cracking-the-coding-interview/ch5-bit-manipulation/x5.6-swap-even-odd-bits.py | Python | unlicense | 789 | 0.008872 | '''
Problem: Given an int, num, swap it's even bits with it's odd bits (ie swap bit 1 with bit 2, bit 3
with bit 4, etc -> 0110 0010 becomes 1001 0001)
Solution: Brute force is to iterate in pairs and | swap said pairs. This means you are performing
32/64 swaps where you mask even and mask odd and shift them and set them in num. Instead,
realize that you are continually swapping even bits with the bit to their right and odd bits
with bits to their left. Therefore instead you could create a pair of mask | s (even mask:
1010 1010, odd mask: 0101 0101) then AND both against the number to get the even bits (odd 0s)
and odd bits (even 0s) then right-shift the even results and left-shift the odd results and OR
them together
- linear time, constant space
'''
|
NablaWebkom/django-wiki | wiki/templatetags/wiki_tags.py | Python | gpl-3.0 | 5,449 | 0.000367 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import re
from django import template
from django.conf import settings as django_settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Model
from django.forms import BaseForm
from django.templat... | 'preview': preview_content is not None,
'plugins': plugin_registry.get_plugins(),
'STA | TIC_URL': django_settings.STATIC_URL,
'CACHE_TIMEOUT': settings.CACHE_TIMEOUT,
})
return context
@register.inclusion_tag('wiki/includes/form.html', takes_context=True)
def wiki_form(context, form_obj):
if not isinstance(form_obj, BaseForm):
raise TypeError(
"Error including for... |
dmort27/panphon | panphon/__init__.py | Python | mit | 118 | 0 | from __future__ import absolute_import
from panphon.featuretable import Featur | eTable
from panphon._panphon imp | ort pat
|
XeCycle/indico | indico/core/index/base.py | Python | gpl-3.0 | 7,870 | 0.001525 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | uid = elem.getUniqueId()
if uid not in self._rev_index:
yield "[%s] An entry for '%s | '(%s) should exist in _rev_index" \
% (cls, uid, ts)
elif key not in self._rev_index[uid]:
yield "[%s] Element '%s'(%s) should be in _rev_index['%s']" \
% (cls, uid, ts, key)
if dbi and i % 1000 == 999:
dbi.a... |
okfn/datapackage-validate-py | setup.py | Python | mit | 1,643 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import io
from setuptools import setup, find_packages
description = (
'(DEPRECATED) A Python library to validate Data Package datapackage.json'
' files.'
... | nce :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
| 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries :: Python Modules',
'... |
jocave/snapcraft | snapcraft/plugins/maven.py | Python | gpl-3.0 | 5,693 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | ft.plugins.jdk.JdkPlugin):
@classmethod
def schema(cls):
schema = super().schema()
schema['properties']['maven-options'] = {
'type': 'array',
'minitems': 1,
'uniqueItems': True,
'items': {
'type': 'string',
},
... | }
schema['properties']['maven-targets'] = {
'type': 'array',
'minitems': 1,
'uniqueItems': True,
'items': {
'type': 'string',
},
'default': [''],
}
# Inform Snapcraft of the properties associated with bui... |
justyns/home-assistant | homeassistant/helpers/event.py | Python | mit | 7,340 | 0 | """Helpers for listening to events."""
import functools as ft
from datetime import timedelta
from ..const import (
ATTR_NOW, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, MATCH_ALL)
from ..util import dt as dt_util
def track_state_change(hass, entity_ids, action, from_state=None,
to_state=None)... |
entity_ids, from_state and to_state can be string or list.
Use list to match multiple.
Returns the listener that listens on the bus for EVENT_STATE_CHANGED.
Pass the return value into hass.bus.remove_liste | ner to remove it.
"""
from_state = _process_match_param(from_state)
to_state = _process_match_param(to_state)
# Ensure it is a lowercase list with entity ids we want to match on
if isinstance(entity_ids, str):
entity_ids = (entity_ids.lower(),)
else:
entity_ids = tuple(entity_id... |
wks/lrparsing3 | setup.py | Python | gpl-2.0 | 1,264 | 0.019778 | #!/usr/bin/env python3
#
# (c) 2013, Russell Stuart.
# Licensed under GPLv2, or any later version. See COPYING for details.
#
from distutils.core import setup
import re
def get_long_description():
handle = open("doc/lrparsing.rst")
while not next(handle).startswith("====="):
pass
long_description=[]
for l... | andle:
if line.startswith("====="):
break
line = re.sub(":[a-z]*:`([^`<]*[^`< ])[^`]*`", "\\1", line)
long_description.append(line)
return ''.join(long_description[:-1])
setup(
name="lrparsing",
description="An LR(1) parser hiding behind a pythonic interface",
long_description=get_long_... | ssell Stuart",
author_email="russell-lrparsing@stuart.id.au",
url="http://www.stuart.id.au/russell/files/lrparsing",
package_dir={"": "lrparsing"},
py_modules=["lrparsing"],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Ge... |
mbuesch/partmgr | partmgr/gui/protected_spinbox.py | Python | gpl-2.0 | 1,870 | 0.016578 | # -*- coding: utf-8 -*-
#
# PartMgr GUI - Protected spin box
#
# Copyright 2014 Michael Buesch <m@bues.ch>
#
# 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
#... | ll be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Softwar... | mgr.gui.util import *
class ProtectedSpinBox(AbstractProtectedWidget):
valueChanged = Signal(int)
def __init__(self, parent=None):
AbstractProtectedWidget.__init__(self, parent)
self.spin = QSpinBox(self)
self.spin.setAccelerated(True)
self.setKeyboardTracking(True)
self.setEditWidget(self.spin)
self... |
clagiordano/weblibs | utility/hMUD-master/flashpolicyd_v0.6/Standalone/flashpolicyd.py | Python | gpl-3.0 | 3,628 | 0.003308 | #!/usr/bin/env python
#
# flashpolicyd.py
# Simple socket policy file server for Flash
#
# Usage: flashpolicyd.py [--port=N] --file=FILE
#
# Logs to stderr
# Requires Python 2.5 or later
from __future__ import with_statement
import sys
import optparse
import socket
import thread
import exceptions
import contextlib
V... | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', port))
self.sock.listen(5)
def read_policy(self, path):
with file(path, 'rb') as f:
policy = f.read(10001)
... | ntimeError('File probably too large to be a policy file',
path)
if 'cross-domain-policy' not in policy:
raise exceptions.RuntimeError('Not a valid policy file',
path)
return policy
def... |
827992983/yue | admin/migrations/0008_vm_system.py | Python | gpl-3.0 | 443 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-04-26 1 | 2:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admin', '0007_vm_user'),
]
operations = [
migrations.AddField(
model_n | ame='vm',
name='system',
field=models.CharField(default='', max_length=32),
),
]
|
mdobrychlop/pyry3d_chimera_extension | Calculate.py | Python | gpl-3.0 | 37,311 | 0.019646 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# www.genesilico.pl
#
from numpy import array
from random import uniform
import shutil
from shutil import rmtree
import os
from copy import deepcopy
from Modules.Input... | of all complex components
density_map : density map object
trans and con are PyRy3D objects from Trans.py and Config.py modules
"""
#print "PyRy3D arranged complex components randomly inside the SIMULATION BOX"
#print "The PyRy3D score now is equal to\t:"
sort_by_covbonds... | nts:
if len(component.disorders) != 0:
for el in component.disorders:
if el.fragment_type == "simulated_volume":
#print "Component with unknown structure will be positioned randomly inside simulation box"
position_component(... |
lreis2415/SEIMS | seims/preprocess/sd_delineation.py | Python | gpl-3.0 | 11,534 | 0.002341 | """Subbasin delineation based on TauDEM, as well as calculation of latitude dependent parameters
@author : Liangjun Zhu, Junzhi Liu
@changelog: 13-01-10 jz - initial implementation
16-12-07 lj - rewrite for version 2.0, improve calculation efficiency by numpy
17-06-23 lj - r... | tream_d8]
# output masked files
output_files = [cfg.taudems.subbsn_m, cfg.taudems.d8flow_m, cfg.taudems.stream_m,
cfg.spatials.slope, cfg.spatials.filldem, cfg.spatials.d8acc,
cfg.spatials.stream_order, cfg.spatials.dinf, cfg.spat | ials.dinf_d8dir,
cfg.spatials.dinf_slp, cfg.spatials.dinf_weight,
cfg.spatials.dist2stream_d8]
default_values = list()
default_values = [DEFAULT_NODATA] * len(original_files)
# other input rasters need to be masked
# soil and landuse
... |
openstack/tempest-lib | tempest_lib/tests/services/compute/test_interfaces_client.py | Python | apache-2.0 | 3,944 | 0 | # Copyright 2015 NEC Corporation. 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 ... | e",
"regionOne")
def _test_interface_operation(self, operation="create", bytes_body=False):
response_code = 200
expected_op = self.FAKE_SHOW_DATA
mock_operation = self.func2mock['get']
params = {'server_id': self.FAKE_SERVER_I... | d_op = self.FAKE_LIST_DATA
function = self.client.list_interfaces
params = {'server_id': self.FAKE_SERVER_ID}
elif operation == 'show':
function = self.client.show_interface
elif operation == 'delete':
expected_op = {}
mock_operation = self.fun... |
amiller27/First-Experiences-in-Research | writer/shakespeare_get.py | Python | gpl-2.0 | 722 | 0.020776 | import urllib2, HTMLParser
import re
text_file = open("shakespeare.txt", 'w')
class HTMLShakespeareParser(HTMLParser.HTMLParser):
def handle | _starttag(self, tag, attrs):
if tag == "a":
link = dict( | attrs)["href"]
if "/index.html" in link:
works.append(link[:-11])
works = []
html_index_file = urllib2.urlopen("http://shakespeare.mit.edu")
HTMLShakespeareParser().feed(html_index_file.read())
html_index_file.close()
for title in works:
html_data_file = urllib2.urlopen("http://shakespeare.mit.edu/" + title +... |
daethnir/authprogs | authprogs/tests/test_authprogs.py | Python | gpl-2.0 | 23,493 | 0.00017 | #!/usr/bin/python3
# vim: set ts=4 et
"""authprogs unit tests."""
# Copyright (C) 2013 Bri Hatch (daethnir) <bri@ifokr.org>
#
# This file is part of authprogs.
#
# Authprogs is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License v2 as published by
# ... | logfile=logfile,
configdir=configdir,
configfile=configfile,
silent=True,
**ap_args
)
return ap
# pylint: disable-msg=R0904
class AuthProgsTests(unittest.TestCase):
"""AuthProgs unit test class."""
def test_get_client_ip(self):
"""Verify we get the IP f... | vars."""
ap = getap()
# Save environment for later
environ = os.environ.copy()
try:
ap = getap()
os.environ.clear()
os.environ['SSH_CLIENT'] = '4.19.1.21 49725 22'
self.assertEqual(ap.get_client_ip(), '4.19.1.21')
ap = getap... |
DBrianKimmel/PyHouse | Project/src/Modules/Core/Drivers/Usb/Usb_open.py | Python | mit | 6,996 | 0.001715 | """
@name: Modules/CXore/Drivers/USB/usb_open.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2011-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Mar 27, 2011
@summary: This module is for communicating with USB devices.
This will interface various PyHo... | Name)
return l_ret
@staticmethod
def is_hid(p_device):
if p_device.bUsbDeviceClass == 3:
| return True
class Api(object):
m_controller_obj = None
@staticmethod
def _save_find_device(p_USB_obj, p_device):
p_USB_obj.UsbDevice = p_device
p_USB_obj.num_configs = p_device.bNumConfigurations
p_USB_obj.hid_device = True # lightingUtility.is_hid(p_device)
p_U... |
ares/robottelo | tests/foreman/ui/test_user.py | Python | gpl-3.0 | 61,539 | 0 | # -*- encoding: utf-8 -*-
"""Test class for Users UI
:Requirement: User
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import random
from fauxfactory import gen_string
from nailgun import entities
from robottelo import ssh
from ... | ance: Critical
"""
with Session(self) as session:
for first_name in valid_strings():
with self.subTest(first_name):
| name = gen_string('alpha')
make_user(session, username=name, first_name=first_name)
self.user.validate_user(name, 'firstname', first_name)
@tier1
def test_positive_create_with_surname(self):
"""Create User for all variations of Surname
:id: 0a2dc... |
aviarypl/mozilla-l10n-addons-server | src/olympia/devhub/decorators.py | Python | bsd-3-clause | 2,494 | 0 | import functools
from django import http
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from olympia import amo
from olympia.access import acl
from olympia.addons.decorators import addon_view_factory
from olympia.addons.models import Addon
from olympia.amo.decorators import ... | t owner_for_post):
return fun()
# Ignore disabled so they can view their add-on.
elif acl.check_addon_ownership(request, addon, dev=True,
ignore_disabled=True):
# Redirect to the submit flow if they're not done.
... | evhub.submit.details', addon.slug)
return fun()
raise PermissionDenied
return wrapper
# The arg will be a function if they didn't pass owner_for_post.
if callable(owner_for_post):
f = owner_for_post
owner_for_post = False
return decorator(f)
else:
... |
gehaxelt/nautiluscoin | contrib/wallettools/walletchangepass.py | Python | mit | 219 | 0.004566 | from jsonrpc import Se | rviceProxy
access = ServiceProxy("http://127.0.0.1:9334")
pwd = raw_input("Enter old wallet | passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2) |
yarhajile/sven-daemon | Sven/Module/__init__.py | Python | gpl-2.0 | 27 | 0 | _ | _author__ = 'elijah | ethun'
|
vyscond/cocos | test/test_camera_orbit_reuse.py | Python | bsd-3-clause | 1,290 | 0.015504 | from __future__ import division, print_function, unicode_literals
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
# total time duration * action multiplier
testinfo = "s, t 2.0, s, t 4.0, s, t 6.1, s, q"
... | .img = pyglet.resource.image('background_image.png')
def draw( self ):
glColor4ub(255, 255, 255, 255)
glPushMatrix()
self.transform()
self.img.blit(0,0)
glPopMatrix()
def main():
director.init( resizable=True )
director.set_depth_test()
main_scene = cocos.scene... | Layer(), z=0 )
rot = OrbitCamera( delta_z=60, duration=2 )
# In real code after a sequence of grid actions the StopGrid() action
# should be called. Omited here to stay in the last grid action render
main_scene.do( rot * 3 )
director.run (main_scene)
if __name__ == '__main__':
main()
|
labsanmartin/Bika-LIMS | bika/lims/browser/client/__init__.py | Python | agpl-3.0 | 925 | 0 | from views.batches import ClientBatchesView
from views.analysisrequests import ClientAnalysisRequestsView
from views.analysisrequests import ClientBatchAnalysisRequestsView
from views.samples import ClientSamplesView
from views.analysisprofiles import ClientAnalysisProfilesView
from views.artemplates import ClientARTem... | tsView
from views.contacts import ClientContactVocabularyFactory
from views.samplingrounds import ClientSamplingRoundsView
from ajax import ReferenceWidgetVocabulary
from ajax import ajaxGetClientInfo
from workflow import ClientWork | flowAction
|
RAPD/RAPD | src/plugins/pdbquery/plugin.py | Python | agpl-3.0 | 47,200 | 0.004725 | """pdbquery RAPD plugin"""
"""
This file is part of RAPD
c
Copyright (C) 2017, Cornell University
All rights reserved.
RAPD is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, version 3.
RAPD is distributed ... | n_phase | r
from plugins.subcontractors.rapd_cctbx import get_pdb_info, get_mtz_info, get_res, get_spacegroup_info
from plugins.get_cif.plugin import check_pdbq
# from plugins.subcontractors.parse import parse_phaser_output, set_phaser_failed
from utils import archive
import utils.credits as rcredits
import utils.exceptions as e... |
deepmind/dm-haiku | examples/transformer/model.py | Python | apache-2.0 | 4,120 | 0.004854 | # Copyright 2020 DeepMind Technologies Limited. 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 ... | h_norm = layer_norm(h, name=f'h{i}_ln_2')
h_dense = DenseBlock(init_scale, name=f'h{i}_mlp')(h_norm)
h_dense = hk.dropout(hk.next_rng_key(), dropout_rate, h_dense)
h = h + h_dense
h = layer_norm(h, name='ln_f')
return h
def layer_norm(x: jnp.ndarray, name: Optional[str] = None) -> jnp.ndarr... | ate_scale=True,
create_offset=True,
name=name)(x)
|
AleksNeStu/ggrc-core | test/selenium/src/tests/test_my_work_page.py | Python | apache-2.0 | 3,938 | 0.004063 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""My Work page smoke tests."""
# pylint: disable=no-self-use
# pylint: disable=invalid-name
# pylint: disable=too-few-public-methods
# pylint: disable=unused-argument
import pytest # pylint: disable=impo... | ert initial_position == lhn.Menu(selenium).my_objects.element.location
@pytest.mark.smoke_tests
def test_lhn_remembers_tab_state(self, selenium):
"""Tests if LHN remembers which tab is selected (my or all objects) after
closing it."""
conftest_utils.navigate_to_page_with_lhn(selenium)
header = dash... |
new_lhn = header.open_lhn_menu()
assert selenium_utils.is_value_in_attr(new_lhn.my_objects.element) is True
# check if all objects tab saves state
lhn_menu = header.open_lhn_menu()
lhn_menu.select_all_objects()
header.close_lhn_menu()
header.open_user_list()
new_lhn = header.open_lhn_me... |
drmpeg/gr-dvbt2 | apps/vv016_256qam34.py | Python | gpl-3.0 | 6,112 | 0.012271 | #!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Vv016 256Qam34
# Generated: Wed Feb 11 04:36:51 2015
##################################################
# Call XInitThreads as the _very_ first thing.
# After some Qt import, it's too late
import ctypes
impor... | _0, 0))
self.connect((self.dvbt2_bbheader_bb_0, 0), (self.dvbt2_bbscrambler_bb_0, 0))
self.connect((self.dvbt2_bbscrambler_bb_0, 0), (self.dvbt2_bch_bb_0, 0))
self.connect((self.dvbt2_bch_bb_0, 0), (self.dvbt2_ldpc_bb_0, 0))
self.connect((self.dvbt2_cellinterleaver_cc_0, ... |
self.connect((self.dvbt2_framemapper_cc_0, 0), (self.dvbt2_freqinterleaver_cc_0, 0))
self.connect((self.dvbt2_freqinterleaver_cc_0, 0), (self.dvbt2_pilotgenerator_cc_0, 0))
self.connect((self.dvbt2_interleaver_bb_0, 0), (self.dvbt2_modulator_bc_0, 0))
self.connect((self.d... |
teknogods/eaEmu | eaEmu/util/timer.py | Python | gpl-3.0 | 2,714 | 0.027634 | from twisted.application.internet import TimerService
from twisted.application.service import Service
from twisted.internet import task
from twisted.internet import defer
class LoopingCall(task.LoopingCall):
def __call__(self):
def cb(result):
if self.running:
self._reschedule()
... | self.ping = defer.Deferred()
## the pingFunc is assumed to be a syncronous function that
## sends the request along to the client and returns immediately.
## TODO: maybe assume that this returns a deferred that is fired when
## the response is received?
pingFunc(*args, ... | self.ping.setTimeout(self.step - 1) # timeout if no response before next iteration
return self.ping ## LoopingCall will reschedule as soon as this fires
self._loop = LoopingCall(sendPing)
self._loop.start(self.step, now=self.now).addErrback(self._failed)
def stopService(self):
## bug ... |
Jerryzcn/Mmani | doc/sphinxext/numpy_ext/astropyautosummary.py | Python | bsd-2-clause | 3,983 | 0.000753 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This sphinx extension builds off of `sphinx.ext.autosummary` to
clean up some issues it presents in the Astropy docs.
The main issue this fixes is the summary tables getting cut off before the
end of the sentence in some cases.
Note: Sphinx 1.2 appea... | is
extension with newer versions of Sphinx is deprecated.
"""
import re
from distutils.version import LooseVer | sion
import sphinx
from sphinx.ext.autosummary import Autosummary
from ...utils import deprecated
# used in AstropyAutosummary.get_items
_itemsummrex = re.compile(r'^([A-Z].*?\.(?:\s|$))')
@deprecated('1.0', message='AstropyAutosummary is only needed when used '
'with Sphinx versions le... |
zsiciarz/variablestars.net | observations/urls.py | Python | mit | 661 | 0.003026 | from django.conf.urls import url
| from .views import ObservationListView, AddObservationView, UploadObservationsView
app_name = "observations"
urlpatterns = [
url(r"^$", ObservationListView.as_view(), name="observation_list"),
url(
r"^(?P<observer_id>\d+)/$",
ObservationListView.as_view(),
name="observation_list_by_obs... | ddObservationView.as_view(),
name="add_observation_for_star",
),
url(r"^upload/$", UploadObservationsView.as_view(), name="upload_observations"),
]
|
mozbugbox/liferea-plugin-studio | accels/gtkshortcutgen.py | Python | gpl-3.0 | 5,205 | 0.00365 | #!/usr/bin/python3
# vim:fileencoding=utf-8:sw=4:et
"""
GtkShortcutsWindow helper for generating GtkBuilder XML file.
```
shortcuts1 = [
shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"),
]
shortcuts2 = [
shortcut_entry("Import channels from file", "<ctrl>o"),
shortcu... | :
ke = etree.Element("child")
eroot.append(ke)
subroot = do_object_tree(kid)
ke.append(subroot)
return eroot
return do_object_tree(base_entry)
def shortcut_entry(title, accel=None, gesture=None, **kwargs):
props = { "title": title, "visibl... | props["shortcut-type"] = gesture
props.update(kwargs)
entry = {
"klass": "Shortcut",
"properties": props,
}
return entry
def group_entry(title, shortcuts, **kwargs):
entry = {
"klass":"Group",
"properties": {
"visible": 1,
... |
julienawilson/data-structures | src/test_deque.py | Python | mit | 2,665 | 0 | """Tests for Deque."""
import pytest
@pytest.fixture()
def empty_deque():
"""Build a sample deque for testing."""
from deque import Deque
empty_deque = Deque()
return empty_deque
@pytest.fixture()
def full_deque():
"""Build a sample deque for testing."""
from deque import Deque
full_deq... | empty deque."""
assert empty_deque.peek_left() is None
def test_peek_full_left(full_deque):
"""Test for peek | left on deque."""
assert full_deque.peek_left() == 3
def test_size_empty(empty_deque):
"""Test for size on empty deque."""
assert empty_deque.size() == 0
def test_size_full(full_deque):
"""Test for size on deque with nodes."""
assert full_deque.size() is 3
|
channprj/uptime-robot | app/__init__.py | Python | mit | 583 | 0.003431 | __author__ = "CHANN"
__email__ = "chann@chann.kr"
__version__ = "0.0. | 0"
import os
import sys
import re
from flask import Flask
from flask import | render_template
from flask import url_for
from flask import redirect
from flask import request
from flask import flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from app.forms import SignUpForm
from app import init
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlche... |
satishgoda/rbhus | rbhusUI/guiBin/rbhusPipeAdmin.py | Python | gpl-3.0 | 2,325 | 0.023226 | #!/usr/bin/python
from PyQt4 import QtCore, QtGui
import glob
import os
import sys
import tempfile
tempDir = tempfile.gettempdir()
dirSelf = os.path.dirname(os.path.realpath(__file__))
print(dirSelf)
sys.path.append(dirSelf.rstrip(os.sep).rstrip("guiBin").rstrip(os.sep) + os.sep + "lib")
scb = "rbhusPipeProjCreate.... | ils as rUtils
import authPipe
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(rbhusPipeAdminPanelMod.Ui_MainWindow):
def setupUi(self, Form):
rbhusPipeAdminPanelMod.Ui_MainWindow.setupUi(self,Form)
icon = QtGui.QIcon()
| icon.addPixmap(QtGui.QPixmap(_fromUtf8(dirSelf.rstrip(os.sep).rstrip("guiBin").rstrip(os.sep).rstrip("rbhusUI").rstrip(os.sep)+ os.sep +"etc/icons/rbhusPipe.svg")), QtGui.QIcon.Normal, QtGui.QIcon.On)
Form.setWindowIcon(icon)
self.form = Form
self.center()
self.pushCreate.clicked.connect(self.rbhusPipe... |
martynjarvis/stb-tester | _stbt/utils.py | Python | lgpl-2.1 | 986 | 0 | import errno
import os
import tempfile
from contextlib import contextmanager
from shutil import rmtree
def mkdir_p(d):
"""Python 3.2 has an optional argument to os.makedirs called exist_ok. To
support older versions of python we can't use this and need to catch
exceptions"""
try:
os.makedirs(... | =W0622
dirname = tempfile.mkdtemp(suffix, prefix, dir)
try:
yield dirname
finally:
rmtre | e(dirname)
@contextmanager
def scoped_curdir():
with named_temporary_directory() as tmpdir:
olddir = os.path.abspath(os.curdir)
os.chdir(tmpdir)
try:
yield olddir
finally:
os.chdir(olddir)
|
LamCiuLoeng/aeo | rpac/model/ordering.py | Python | mit | 6,204 | 0.053514 | # -*- coding: utf-8 -*-
'''
Created on 2014-4-9
@author: CL.lam
'''
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import DateTime, Integer, Text, Numeric
from sqlalchemy.orm import relation, synonym, backref
from sqlalchemy.ext.declarative import declared_attr
from rpac.model import Declarat... | p_id", Integer, ForeignKey( 'master_print_shop.id' ) )
printShop = relation( PrintShop, primaryjoin = PrintShop.id == printS | hopId )
printShopCopy = Column( "printshop_copy", Text, default = None )
items = Column( "items", Text )
so = Column( Text )
completeDate = Column( 'complete_date', DateTime )
totalQty = Column( "total_qty" , Text )
# shipQty = Column( "ship_qty", Text )
courier = Column( "courier", Text )
... |
rosmo/ansible | test/units/module_utils/xenserver/test_misc.py | Python | gpl-3.0 | 756 | 0.002646 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# 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
import pytest
from .FakeAnsibleModule import FakeAnsibleModule, ExitJsonException, FailJsonException
def test_xapi_to_module_vm_power_state_bad_power_state(xenserver):
"""Tests that None is returned on bad power state."""
assert xenserver.xapi_to_module_vm_po... | i_vm_power_state("bad") is None
|
habnabit/pip | tests/unit/test_wheel.py | Python | mit | 14,091 | 0 | """Tests for wheel binary packages and .dist-info."""
import os
import pytest
from mock import patch, Mock
from pip._vendor import pkg_resources
from pip import pep425tags, wheel
from pip.exceptions import InvalidWheelFilename, UnsupportedWheel
from pip.utils import unpack_file
def test_get_entrypoints(tmpdir):
... | : 'cp')
def test_supported_multiarch_darwin(self):
"""
Multi-arch wheels (intel) are supported on components (i386, x86_64)
"""
with patch('pip.pep425tags.get_platform',
lambda: 'macosx_10_5_universal'):
universal = pep425tags.get_supported(['27'], Fals... | 5tags.get_platform',
lambda: 'macosx_10_5_x86_64'):
x64 = pep425tags.get_supported(['27'], False)
with patch('pip.pep425tags.get_platform',
lambda: 'macosx_10_5_i386'):
i386 = pep425tags.get_supported(['27'], False)
with patch('pip.pep425tags... |
paulmartel/voltdb | tests/bench/throughput/run.py | Python | agpl-3.0 | 1,927 | 0.002076 | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitati... | SE OR
# OTHER DEALINGS IN THE SOFTWARE.
from subprocess import *
def run(procs, threadsPerProc, workload):
results = []
totalThroughput = 0.0
output = Popen(['./throughput', str(procs), str(threadsPerProc), workload], stdout=PIPE).communicate()[0]
lines = output.split('\n')
for line in lines:
... | nt line
line = line.split(' ')[1]
parts = line.split(',')
results += [float(parts[2])]
for r in results:
totalThroughput += r
print "--"
print "PER THREAD AVG: " + str(totalThroughput / (procs * threadsPerProc))
print "PER PROC AVG: " + str(totalThroug... |
laz2/sc-core | bindings/python/sc_core/pm_test.py | Python | lgpl-3.0 | 3,358 | 0.018772 |
"""
-----------------------------------------------------------------------------
This source file is part of OSTIS (Open Semantic Technology for Intelligent Systems)
For the latest info, see http://www.ostis.net
Copyright (c) 2010 OSTIS
OSTIS is free software: you can redistribute it and/or modify
it under the ter... | 009
@author: Denis Koronchik
'''
import pm
import | time
import thread
import threading
import sys, traceback
class Processor(threading.Thread):
def __init__(self, params = {}):
"""Constuructor
@param params: dictionary with parameters to start processor module
Available parameters:
repo_path - path to repository folder
@... |
waybarrios/worldmap | manage.py | Python | gpl-3.0 | 253 | 0.003953 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main_ | _":
from django.core.management import execute_from_command_line
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "worldmap.settings")
execute_from_command_line(sys | .argv)
|
raybesiga/postie | test_postie.py | Python | mit | 708 | 0.001412 | import unittest
from postie import Postie
from postie import create_parser
import os
class TestPostie(unittest.TestCase):
def setUp(self):
self.parser = create_parser()
def test_no_args(self):
with self.assertRaises(SystemExit):
self.parser.parse_args([])
def test_no_csv_arg... | test.txt'])
self.assertIsNone(arg.csv)
def test_no_template_arg(self):
with self.assert | Raises(SystemExit):
arg = self.parser.parse_args(['-csv', 'test.csv'])
self.assertIsNone(arg.template)
if __name__ == '__main__':
unittest.main()
|
pudo/opennames | opensanctions/core/dataset.py | Python | mit | 3,076 | 0.000325 | import yaml
from banal import ensure_list
from ftmstore import get_dataset as get_store
from opensanctions import settings
from opensanctions.core.lookup import Lookup
from opensanctions.util import joinslug
class Dataset(object):
"""A dataset is a unit of execution of crawlers, and a grouping of entities.
T... | DATABASE_URI)
@classmethod
def _from_metadata(cls, file_path):
from opensanctions.core.source import Source
from opensanctions.core.collection import Collection
with open(file_path, "r") as fh:
config = yaml.load(fh, Loader=yaml.SafeLoader)
type_ = config.get("type... | if type_ == Source.TYPE:
return Source(file_path, config)
@classmethod
def _load_cache(cls):
if not hasattr(cls, "_cache"):
cls._cache = {}
for glob in ("**/*.yml", "**/*.yaml"):
for file_path in settings.METADATA_PATH.glob(glob):
... |
Thiyageshv/PizzaReminder | drf_demo/urls.py | Python | bsd-3-clause | 497 | 0.008048 | from rest_framework import routers
from drf_demo.model_less.views import TaskViewSet, userlocviewset, groupviewset
from django.conf.urls import patterns, include, url
from django.contrib import admin
router = routers.DefaultRouter()
router.register(r'tasks', TaskViewSet, base_name='tasks')
router.register(r'users', u... | include(router.urls)),
url(r'^admin/', admin.site.urls),
]
| |
sunqm/pyscf | pyscf/lib/logger.py | Python | apache-2.0 | 6,296 | 0.005241 | #!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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
#
# U... | debug2 = debug2
debug3 = debug3
debug4 = debug4
timer = timer
timer_debug1 = timer_debug1
def new_logger(rec=None, verbose=None):
'''Create and return a :class:`Logger` object
Args:
rec : An object which carries the attributes stdout and verbose
verbose : a Logger object, or ... | not specified (None),
rec.verbose will be used in the new Logger object.
'''
if isinstance(verbose, Logger):
log = verbose
elif isinstance(verbose, int):
if getattr(rec, 'stdout', None):
log = Logger(rec.stdout, verbose)
else:
log = Logger(sys.std... |
digideskio/lets-encrypt-preview | letsencrypt_apache/tests/dvsni_test.py | Python | apache-2.0 | 4,161 | 0.00024 | """Test for letsencrypt_apache.dvsni."""
import unittest
import shutil
import mock
from acme import challenges
from letsencrypt.plugins import common
from letsencrypt.plugins import common_test
from letsencrypt_apache.tests import util
class DvsniPerformTest(util.ApacheTest):
"""Test the ApacheDVSNI challenge... | "Include", self.sni.challenge_conf)),
1)
self.assertEqual(len(responses), 2)
for i in xrange(2):
self.assertEqual(responses[i].s, "randomS%d" % i)
def test_mod_config(self):
for achall in self.achalls:
self.sni.add_chall(achall)
v_addr1 = [common.... | 127.0.0.1", "443"))]
ll_addr = []
ll_addr.append(v_addr1)
ll_addr.append(v_addr2)
self.sni._mod_config(ll_addr) # pylint: disable=protected-access
self.sni.configurator.save()
self.sni.configurator.parser.find_dir(
"Include", self.sni.challenge_conf)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.