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 |
|---|---|---|---|---|---|---|---|---|
sapfo/medeas | src/old_scripts/python_pca.py | Python | gpl-3.0 | 3,142 | 0.015595 | #!/usr/bin/env python
from __future__ import division
import numpy as np
import pylab
def PCA(Z, verbose = 0):
"""
PCA Mc Vean style
... |
L = len(Z)
if verbose: print "number of SNPs: ",L
# Centering matrix remove the average of each row
X = Z-np.average(Z,axis=1).reshape(L,1)
# matrix to diagonalise
M = 1./L*(X.T.dot(X))
... |
evals, evecs = np.linalg.eigh(M)
# Sort by eigenvalue in descending order
idx = np.argsort(evals)[::-1]
evals = evals[idx]
evecs = evecs[:,idx]
# Compute the coordinates using positive-eigenvalued components only ... |
Learningtribes/edx-platform | pavelib/paver_tests/test_servers.py | Python | agpl-3.0 | 12,322 | 0.002191 | """Unit tests for the Paver server tasks."""
import ddt
from paver.easy import call_task
from .utils import PaverTestCase
EXPECTED_COFFEE_COMMAND = (
u"node_modules/.bin/coffee --compile `find {platform_root}/lms "
u"{platform_root}/cms {platform_root}/common -type f -name \"*.coffee\"`"
)
EXPECTED_SASS_COMM... | tem}/static/sass/*.scss {system}/static/themed_sass"
)
EXPECTED_COLLECT_STATIC_COMMAND = (
u"python manage.py {system} --settings={asset_settings} collectstatic --noinput {log_string}"
)
EXPECTED_CELERY_COMMAND = (
u"python manage.py lms --settings={settings} celery worker --beat --loglevel=INFO --pythonpath=." |
)
EXPECTED_RUN_SERVER_COMMAND = (
u"python manage.py {system} --settings={settings} runserver --traceback --pythonpath=. 0.0.0.0:{port}"
)
EXPECTED_INDEX_COURSE_COMMAND = (
u"python manage.py {system} --settings={settings} reindex_course --setup"
)
@ddt.ddt
class TestPaverServerTasks(PaverTestCase):
"""
... |
AutorestCI/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2015_06_15/models/virtual_machine_scale_set_vm_instance_view.py | Python | mit | 3,269 | 0.00153 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ': 'platformFaultDomain', 'type': 'int'},
'rdp_thumb_print': {'key': 'rdpThumbPrint', 'type': 'str'},
'vm_agent': {'key': 'vmAgent', 'type': 'VirtualMachineAgentInstanceView'},
'disks': {'key': 'disks', 'type': '[DiskInstanceView]'},
'extensions': {'key': 'extensions', 'type': '[VirtualM... | key': 'statuses', 'type': '[InstanceViewStatus]'},
}
def __init__(self, platform_update_domain=None, platform_fault_domain=None, rdp_thumb_print=None, vm_agent=None, disks=None, extensions=None, boot_diagnostics=None, statuses=None):
super(VirtualMachineScaleSetVMInstanceView, self).__init__()
... |
quaddra/engage | python_pkg/engage/tests/test_run_server.py | Python | apache-2.0 | 5,669 | 0.005468 | """
Tests server start and stop functionality.
"""
import sys
import os.path
import getpass
import logging
import time
import optparse
import tempfile
import shutil
try:
import engage
except:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
import engage
import engage_ut... | arse.OptionParser(usage=usage)
parser.add_option("--run- | server", default=False, action="store_true",
help="If specified, start a test server instead of running the tests")
parser.add_option("--server-log-dir", default=None,
help="If specified, use the directory for server logfiles rather than a temporary directory")
(optio... |
skyman/YamScripts | YamTeller/yamsdaq_models.py | Python | apache-2.0 | 1,788 | 0.007271 | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Colum... | class Stock(Base):
__tablename__ = 'stocks'
id = Column(Integer, primary_key=True)
count = Column(Integer, nullable=False)
value_per_stock_at_purchase = Column(Float, nullable=False | )
owner_number = Column(Integer, ForeignKey('accounts.number'), nullable=False)
owner = relationship(Account, back_populates="owned_stocks")
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="owned_stocks")
Account.owned_stoc... |
Sult/Buah | apps/towns/models.py | Python | gpl-2.0 | 18,570 | 0.017071 | from django.db import models
from django.utils.timezone import utc
from django.db.models import get_model
from django.contrib.auth.models import User
from apps.elements.models import VersionControl, Resource
from apps.towns.forms import OutskirtForm
import random, itertools
from datetime import datetime, timedelta
f... | #get tribe/guild of town reputation and | the corrosponding modifier
#price = self.price * modifier
return self.price
#remove hero from tavern and set hero to a player
def transfer_hero(self, user):
hero = self.hero
hero.user = user
hero.town = self.tavern.town
hero.created = d... |
pythonpatterns/patterns | p0112.py | Python | unlicense | 183 | 0.005464 | a = 3 * 2
print(a)
"""<
6
>"""
b = 3 * | 2.5
print(b)
"""<
7.5
>"""
c = 2 * 3 * 4
print(c)
"""<
24
>"""
import operator as op
d = reduce(op.mul, | [2, 3, 4, 5], 1)
print(d)
"""<
120
>"""
|
dougstanley/dsci15310 | examples/9-11-13.py | Python | agpl-3.0 | 402 | 0.012438 | def repeat_lyrics():
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print "I sleep all night and | I work all day."
print_lyrics()
print_lyrics()
def print_twice(br | uce):
print bruce
print bruce
def add(a,b):
print a + b
leaf = 'brown'
def cat_twice(x):
cat = x
print cat
print cat
print leaf
|
mrquim/repository.mrquim | script.module.exodus/lib/resources/lib/sources/fr/fullstream.py | Python | gpl-2.0 | 5,642 | 0.006735 | # -*- coding: utf-8 -*-
"""
Exodus Add-on
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This progra... | mport urlparse
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import dom_parser
from resources.lib.modules import source_utils
class source:
def __init__(self):
self.priority = 1
self.language = ['fr']
self.domains = ['full... | url = self.__search([localtitle] + source_utils.aliases_to_array(aliases), year)
if not url and title != localtitle: url = self.__search([title] + source_utils.aliases_to_array(aliases), year)
if url: return urllib.urlencode({'url': url})
except:
return
def tvshow... |
googleapis/python-aiplatform | google/cloud/aiplatform_v1/services/migration_service/async_client.py | Python | apache-2.0 | 21,005 | 0.002142 | # -*- 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 required by applicable law or... | ation_path)
parse_common_location_path = staticmethod(
MigrationServiceClient.parse_common_location_path
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
... | the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
MigrationServiceAsyncClient: The constructed client.
"""
return MigrationServiceClient.from_service_account_info.__func__(MigrationServiceAsyncClient, info, *args, **kwargs) # type: igno... |
wavefrontHQ/python-client | test/test_response_container_paged_service_account.py | Python | apache-2.0 | 1,464 | 0 | # coding: utf-8
"""
Wavefront REST API
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ... | Bearer <<API-TOKEN>>\" to your HTTP requests.</p> # noqa: E501
OpenAPI spec version: v2
Contact: chitimba@wavefront.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import ab | solute_import
import unittest
import wavefront_api_client
from wavefront_api_client.models.response_container_paged_service_account import ResponseContainerPagedServiceAccount # noqa: E501
from wavefront_api_client.rest import ApiException
class TestResponseContainerPagedServiceAccount(unittest.TestCase):
"""R... |
Hippu/pilttikronikka | kronikka/kronikka_conf/settings/base.py | Python | mit | 5,147 | 0.000583 | from unipath import Path
import os
# Django settings for kronikka project.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
PROJECT_ROOT = Path(__file__).ancestor(3)
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See ... | 'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'pro | pagate': True,
},
}
}
|
AtomLinter/linter-pylama | bin/deps/pylint/checkers/async.py | Python | mit | 3,087 | 0.00162 | # Copyright (c) 2015-2017 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2017 Derek Gustafson <degustaf@gmail.com>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Checker for anything related to the async prot... | port sys
import astroid
from astroid import exceptions
from pylint import checkers
from pylint.checkers import utils as checker_utils
from pylint import | interfaces
from pylint import utils
class AsyncChecker(checkers.BaseChecker):
__implements__ = interfaces.IAstroidChecker
name = 'async'
msgs = {
'E1700': ('Yield inside async function',
'yield-inside-async-function',
'Used when an `yield` or `yield from` state... |
wkettler/pyio | filegen.py | Python | gpl-2.0 | 4,738 | 0.000844 | #!/usr/bin/env python
"""
filegen.py
File generation utility.
Copyright (C) 2013 William Kettler <william.p.kettler@gmail.com>
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 ... | ut.write("\r")
sys.stdout.write("The current file count is: %s" % global_ct)
sys.stdout.flush()
# Exit if file count limit reached
if global_ct == qty:
etime = time.time()
tput = global_size / (etime - stime)
print ""
... | print "Wrote %s files at %s KB/s" % (global_ct, tput)
print "Complete!"
return
# Create new working directory
current_dir += 1
pwd = os.path.join(dst, str(current_dir))
mkdir(pwd)
# Reset directory file count
dir_ct = 0
if __name__ =... |
serge-sans-paille/pythran | pythran/tests/euler/euler31.py | Python | bsd-3-clause | 1,019 | 0.007851 | #runas solve()
#unittest.skip recursive generator
#pythran export solve()
def solve():
'''
In England the currency is made up of pound, P, and pence, p, and there are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, P1 (100p) and P2 (200p).
It is possible to make P2 in the following way:
... | pat = pattern[:coinnum] + (p,)
bal = balance(newpat)
if bal > num: return
elif bal == num: yield newpat
elif coinnum < len(coins)-1:
for pat in gen(newpat, coinnum+1, num): |
yield pat
return sum(1 for pat in gen((), 0, 200))
|
v-iam/azure-sdk-for-python | azure-batch/azure/batch/models/batch_error_detail.py | Python | mit | 1,061 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | tional information included with the error response.
:type value: str
"""
_attribute_map = {
'key': {'key': 'key', 'type': 'str'},
'value': {'key': 'value', 'type': 'str'},
| }
def __init__(self, key=None, value=None):
self.key = key
self.value = value
|
Clear-ICT/odoo-addons | fleet_department/models/fleet.py | Python | agpl-3.0 | 1,289 | 0 | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2015 Clear ICT Solutions <info@clearict.com>.
# All Rights Reserved.
#
# This program 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, either ver... | erp import api, fields, models
class FleetVehicle(models.Model):
_inherit = 'fleet.vehicle'
@api.model
def _get_user_department(self):
res = self.env['hr.department']
for employee in self.env.user.employee_ids:
if employee.department_id:
res = employee.depart... | return res
# Fields
#
department = fields.Many2one('hr.department', default=_get_user_department)
|
csurfer/pyheatmagic | setup.py | Python | mit | 1,708 | 0 | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst')) as f:
long_descriptio | n = f.read()
setup(
# Name of the module
name='py-heat-magic',
# Details
version='0.0.2',
description='py-heat as IPython magic',
long_description=long_description,
# The project's main homepage.
url='https://github.com/csurfer/pyheatmagic',
# Author details
author='Vishwas B Sh... | sifiers=[
# Intended Audience.
'Intended Audience :: Developers',
'Intended Audience :: Education',
# License.
'License :: OSI Approved :: MIT License',
# Project maturity.
'Development Status :: 3 - Alpha',
# Operating Systems.
'Operating System :... |
ASinanSaglam/westpa | src/westpa/oldtools/aframe/mcbs.py | Python | gpl-3.0 | 5,928 | 0.005229 | '''
Tools for Monte Carlo bootstrap error analysis
'''
import logging
import math
import numpy as np
import westpa
from westpa.oldtools.aframe import AnalysisMixin
log = logging.getLogger(__name__)
class MCBSMixin(AnalysisMixin):
def __init__(self):
super().__init__()
self.mcbs_alpha = None
... | interval (alpha={:g}).'.format(
self.mcbs_nsets, self.mcbs_display_confidence, self.mcbs_alpha
)
)
if upcall:
try:
upfunc = super().process_args
except AttributeError:
pass
else:
upfunc(args)... | ci_bound_indices(self, n_sets=None, alpha=None):
n_sets = n_sets or self.mcbs_nsets
alpha = alpha or self.mcbs_alpha
return calc_ci_bound_indices(n_sets, alpha)
ciinfo_dtype = np.dtype([('expectation', np.float64), ('ci_lower', np.float64), ('ci_upper', np.float64)])
def calc_mcbs_nsets(alph... |
djanowski/pygmentize | vendor/pygments/tests/test_clexer.py | Python | mit | 898 | 0 | # -*- coding: utf-8 -*-
"""
Basic CLexer Test
~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import unittest
import os
from | pygments.token import Text, Number
from pygments.lexers import CLexer
class CLexerTest(unittest.TestCase):
def setUp(self):
self.lexer = CLexer()
def testNumbers(self):
code = '42 23.42 23. .4 | 2 023 0xdeadbeef 23e+42 42e-23'
wanted = []
for item in zip([Number.Integer, Number.Float, Number.Float,
Number.Float, Number.Oct, Number.Hex,
Number.Float, Number.Float], code.split()):
wanted.append(item)
wanted.append((Text, ' ... |
askedrelic/libgreader | tests/test_auth.py | Python | mit | 7,823 | 0.004218 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
libG(oogle)Reader
Copyright (C) 2010 Matt Behrens <askedrelic@gmail.com> http://asktherelic.com
Python library for working with the unofficial Google Reader API.
Unit tests for oauth and ClientAuthMethod in libgreader.
"""
try:
import unittest2 as unittest
exc... | irects=False)
#requests is fucking up the url encoding and double encoding ampersands
scope_url = r2.headers['location'].replace('amp%3B','')
# now get auth screen
r3 = s.get(scope_url)
# unless we have already authed!
if 'asktherelic' in r3.url:
code = r3.url.split('=')[1]
re... | ost_data['submit_access'] = 'true'
post_data['_utf8'] = '☃'
# again, fucked encoding for amp;
action_url = re.findall('action="(.*?)"', str(r3.content))[0].replace('amp;','')
r4 = s.post(action_url, data=post_data, headers=headers, allow_redirects=False)
code = r4.headers['Location'].split('=... |
Miserlou/Anomos | Anomos/parsedir.py | Python | gpl-3.0 | 5,368 | 0.004471 | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | .getsize(p)),0]
except (IOError, OSError), e:
errfunc("Could not stat " + p + " : " + str(e))
if not newtorrents:
for f in dir_contents:
p = os.path.join(directory, f)
if os.path.isdir(p):
dirs_to_check.append(p)... | ification_time, size), hash], hash is 0 if the file
# has not been successfully parsed
for p,v in new_files.items(): # re-add old items and check for changes
oldval = files.get(p)
if oldval is None: # new file
to_add.append(p)
continue
h = oldval[1]
... |
timberline-secondary/hackerspace | src/djcytoscape/urls.py | Python | gpl-3.0 | 1,100 | 0.004545 | from django.conf.urls import url
from . import views
app_name = 'djcytoscape'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^generate/(?P<quest_id>[0-9]+)/(?P<scape_id>[0-9]+)$', views.generate_map, name='generate_map'),
url(r'^generate/$', views.generate_map, name='generate_unseeded'),
... | 'quest_map_personalized'),
url(r'^(?P<ct_id>[0-9]+)/(?P<obj_id>[0-9]+)/(?P<originating_scape_ | id>[0-9]+)/$',
views.quest_map_interlink, name='quest_map_interlink'),
url(r'^(?P<pk>[0-9]+)/edit/$', views.ScapeUpdate.as_view(), name='update'),
url(r'^(?P<pk>[0-9]+)/delete/$', views.ScapeDelete.as_view(), name='delete'),
url(r'^list/$', views.ScapeList.as_view(), name='list'),
url(r'^(?P<sc... |
gsmcwhirter/simulations | test/one_pop_discrete_replicator_tests.py | Python | mit | 14,401 | 0.004305 | import simulations.dynamics.onepop_discrete_replicator as dr
import simulations.dynamics.replicator_fastfuncs as fastfuncs
import simulations.simulation as simulation
import math
import numpy as np
from nose.tools import assert_equal
class PDSim(dr.OnePopDiscreteReplicatorDynamics):
_payoffs = [[3, 0], [4, 1]]
... |
class PDSim3(dr.OnePopDiscreteReplicatorDynamics):
_payoffs = [[3, 0], [4, 1]]
def __init__(self, *args, **kwdargs):
if 'types' in kwdargs:
types = kwdargs['types']
else:
types = ['C', 'D']
super(PDSim3, self).__init__(*args, types=types, **kwdargs)
def _p... | def _add_listeners(self):
super(PDSim3, self)._add_listeners()
def generation_listener(this, ct, this_pop, last_pop):
this.force_stop = True
this.result_data = "test2"
self.on('generation', generation_listener)
class PD3Sim(dr.OnePopDiscreteReplicatorDynamics):
... |
tanghaibao/jcvi | jcvi/formats/obo.py | Python | bsd-2-clause | 2,842 | 0.000704 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
%prog obo_file
Parses obo_file and plot GO lineage
"""
import sys
import logging
from collections import deque
from functools import partial
from typing import IO, Optional
from goatools.obo_parser import GODag
from jcvi.apps.base import OptionParser
GO_URL = "http... | O term against so.obo
"""
if so is None:
so, _ = GODag_from_SO()
oterm = term
valid_names = set(x.name for x in so.values())
if term not in valid_names:
if "resolve" in method:
if "_" in term:
tparts = deque(term.split("_"))
tparts.pop() | if "prefix" in method else tparts.popleft()
nterm = "_".join(tparts).strip()
term = validate_term(nterm, so=so, method=method)
if term is None:
return None
else:
logging.error("Term `{0}` does not exist".format(term))
sys.exit(... |
vsajip/django | tests/regressiontests/test_client_regress/session.py | Python | bsd-3-clause | 930 | 0.002151 | from django.contrib.sessions.backends.base import SessionBase
class SessionStore(SessionBase):
"""
A simple cookie-based session storage implementation.
The session key is actually the sessio | n data, pickled and encoded.
This means that saving the session will change the session key.
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
def exists(self, session_key):
return False
def create(self):
self._session_key = self.enco... | eate=False):
self._session_key = self.encode(self._session).decode('ascii')
def delete(self, session_key=None):
self._session_key = self.encode({}).decode('ascii')
def load(self):
try:
return self.decode(self.session_key.encode('ascii'))
except:
self.mod... |
Micronaet/micronaet-campaign | campaign_product/product.py | Python | agpl-3.0 | 2,927 | 0.006833 | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License a... | as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID, api
from openerp import tools
from openerp.tools.translate import _
from openerp.tools... | are)
_logger = logging.getLogger(__name__)
class ProductTemplateExtra(orm.Model):
""" Model name: ProductTemplateExtra
"""
_name = 'product.template.extra'
_description = 'Product extra info'
_columns = {
'name': fields.char('Description', size=90, required=True,
tra... |
flavoi/diventi | diventi/products/migrations/0064_product_pinned.py | Python | apache-2.0 | 417 | 0 | # Generated by Django 2.2.16 on 2021-03-21 09:57
from dja | ngo.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0063_product_product_survey'),
]
operations = [
migrations.AddField(
model_name='product',
name='pinned',
field=models.BooleanField(default=False, ve... | ]
|
caelan/stripstream | robotics/openrave/problems.py | Python | mit | 6,418 | 0.000779 | from inspect import currentframe, getfile
from itertools import product
from random import sample
import os
import math
import numpy as np
from stripstream.utils import flatten
from utils import set_base_conf, Pose, box_body, get_name, set_manipulator_conf, mirror_arm_config, open_gripper, close_gripper, top_grasps,... | r c in range(n):
y = -width / 2 + (c + .5) * (box_dims[1] + separation[1])
row.append(Pose(pose_from_quat_point(
unit_quat(), np.array([x, y, z]))))
poses.append(row)
initial_poses = {}
goal_poses = {}
for i, (r, c) in enumerate(obj_coordinates):
row_... | = 0:
name = 'goal%d-%d' % (r, c)
color = BLUE
goal_poses[name] = poses[m / 2][n / 2]
else:
name = 'block%d-%d' % (r, c)
color = RED
initial_poses[name] = poses[r][c]
obj = box_body(env, name, *box_dims, color=color)
set_pose(obj... |
dzoep/khal | khal/calendar_display.py | Python | mit | 7,480 | 0.001604 | # Copyright (c) 2013-2016 Christian Geier et al.
#
# 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, ... | hmethod='fg',
default_color='',
multiple='',
color='',
highlight_event_days=False,
| locale=None,
bold_for_light_color=True):
"""
returns a list() of str() of weeks for a vertical arranged calendar
:param month: first month of the calendar,
if non given, current month is assumed
:type month: int
:param year: year of the first month ... |
pomarec/core | arkos/tracked_services.py | Python | gpl-3.0 | 14,893 | 0.000403 | """
Classes and functions to manage arkOS tracked services.
arkOS Core
(c) 2016 CitizenWeb
Written by Jacob Cook
Licensed under GPLv3, see LICENSE.md
"""
import glob
import miniupnpc
import random
from arkos import config, logger, policies, signals, storage, security
from arkos.messages import Notification
from arko... | ype=None):
"""
Get all security policies from cache storage.
:param str id: App or website ID
:param str type: Filter by type ('website', 'app', etc)
"""
data = storage.policies
if id:
return data.get(id)
if type:
return filter(lam | bda x: x.type == type, data.values())
return data.values()
def register(type, id, name, icon, ports, domain=None, policy=0,
default_policy=2, fw=True):
"""
Register a new security policy with the system.
The ``ports`` parameter takes tuples of ports to manage, like so:
ports = [... |
StaszicCode/sMusic-core | smusicclient/logs.py | Python | gpl-3.0 | 864 | 0.003472 | import datetime
import logging
import os
import config
def setup_logging():
if not os.path.exists(config.log_path):
os.makedirs(config.log_path)
log_file_name = datetime.datetime.now().strftime("client_%Y-%m-%d_%H-%M-%S")
log_formatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(... | ot_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
file_handler = logging.FileHandler("{0}/{1}.log".format(config.log_path, log_file_name))
file_handler.setFormatter(log_formatter)
root_logger.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.se... | ebug = logging.debug
print_error = logging.error
|
Ensembl/cttv024 | lib/postgap/Utils.py | Python | apache-2.0 | 4,340 | 0.03341 | #! /usr/bin/env python
"""
Copyright [1999-2018] EMBL-European Bioinformatics Institute
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... | ==========\n"
string += leadstring + "|GWAS_SNP\n"
string += leadstring + "| " + "SNP: " + summarise(gwas_snp.snp, leadstring = "") + "\n"
string += leadstring + "| " + "pvalue: " + str(gwas_snp.pvalue) + "\n"
string += leadstring + "| " + "z_score: " + str(gwas_snp | .z_score) + "\n"
string += leadstring + "| " + "evidence:\n"
string += summarise(gwas_snp.evidence, leadstring = leadstring + "| " + " ") + "\n"
string += leadstring + "============="
return string
def concatenate(list):
"""
Shorthand to concatenate a list of lists
Args: [[]]
Returntype: []
"""
retur... |
daaang/beam | lib/beam/estimates/__init__.py | Python | gpl-3.0 | 768 | 0 | # beam: Scripts for Me
# Copyright 2017 Matt LaCha | nce
#
# This file is part of beam.
#
# beam is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# beam is distributed in the hope that it... | R PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with beam. If not, see <http://www.gnu.org/licenses/>.
from .composite import CompositeEstimate
from .estimate import Estimate
|
sdpython/teachpyx | _todo/programme/graphplot.py | Python | mit | 2,480 | 0.038306 | # coding: latin-1
import sys
import os
default_path = r"C:\Program Files\gp423win32\gnuplot\bin\pgnuplot.exe"
default_temp_dir = "tempgnuplot"
imagenumber = 0
def execute_script_gnuplot (scr) :
global default_temp_dir
global imagenumber
global default_path
if not os.path.exists (default_tem... | /image_%05d.png" % imagenumber)
imagenumber += 1
scr = "set out \"" + image + "\"\n" + scr
# après
scr += "show out\n"
scr += "exit\n"
name = default_temp_dir + "/gnuscript.txt"
f = open (name, "w")
f.write (scr)
f.close ()
line = default_path + " " + name
os.s... | ge
def build_script_gnuplot (series, seriesname, title = None, \
xlabel = None, ylabel = None, histo = False) :
global default_temp_dir
global default_path
if not os.path.exists (default_temp_dir) : os.mkdir (default_temp_dir)
scr = ""
if xlabel != None : scr += "set xlabel \... |
MariaSolovyeva/inasafe | safe/impact_functions/inundation/flood_vector_building_impact/impact_function.py | Python | gpl-3.0 | 10,048 | 0 | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Flood Vector Impact on
Buildings using QGIS.
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 So... | ard_objects = True
if not has_hazard_objects:
message = tr(
'There are no objects in the hazard layer with %s '
| 'value in %s. Please check your data or use another '
'attribute.') % (
self.hazard_class_attribute,
', '.join(self.hazard_class_mapping[self.wet]))
raise GetDataError(message)
features = []
for feature in self.exposure... |
Proteogenomics/trackhub-creator | pipelines/exceptions.py | Python | apache-2.0 | 551 | 0.005525 | #
# Author : Manuel Bernal Llinares
# Project : trackhub-creator
# Timestamp : 03-07-2017 11:10 |
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#
"""
Pipeline related exceptions
"""
from exceptions import AppException
class PipelineDirectorException(AppException):
def __init__(self, value):
super(AppException, self).__init__(value)
if __name__ == '__main__':
... | alone mode")
|
SafePodOrg/SafePodWeb | safepod_site/forum/urls.py | Python | gpl-3.0 | 1,468 | 0.008856 | from django.conf.urls import patterns, url
from .views import PostListView, SearchView, AllTagsView, TaggedPostListView, MyPostListView, forum_post, PostDetailView, forum_comment, CommentDetailView
urlpatterns = [
# if its a search
url(r'^search/', SearchView.as_view( | ), name='search'),
# Ta | g views with home page and detailed views
url(r'^tag/(?P<slug>[a-zA-Z0-9-]+)/', TaggedPostListView.as_view(), name='tagged_posts'),
url(r'^tag/', AllTagsView.as_view(), name='all_tags'),
# url to handle new post
... |
rackerlabs/heat-pyrax | setup.py | Python | apache-2.0 | 3,121 | 0.001282 | #!/usr/bin/env python
from setuptools import setup
from setuptools.command.sdist import sdist as _sdist
import re
import sys
import time
import codecs
import subprocess
if sys.version < "2.2.3":
from distutils.dist import DistributionMetadata
DistributionMetadata.classifiers = None
DistributionMetadata.dow... | perating System :: OS Independent",
],
install_requires=[
"python-novaclient>=2.13.0",
"rackspace-novaclient",
"keyring",
"requests>=2.2.1",
"six>=1.5.2",
] + testing_requires,
packages=[
"pyra | x",
"pyrax/identity",
],
cmdclass={'sdist': sdist}
)
|
MrinmoiHossain/HackerRank | Python/Strings/Capitalize!.py | Python | mit | 259 | 0.007722 | def capitalize(string):
for s in string.split(" "):
string = string.rep | lace(s, s.capitalize())
return string
if __name__ == '__main__':
string = input()
capitalized_string = ca | pitalize(string)
print(capitalized_string)
|
Julian/Filesystems | filesystems/common.py | Python | mit | 7,276 | 0 | from contextlib import contextmanager
from fnmatch import fnmatch
import stat
from pyrsistent import pset
import attr
from filesystems import Path, exceptions
def _realpath(fs, path, seen=pset()):
"""
.. warning::
The ``os.path`` module's realpath does not error or warn about
loops, but we ... | try:
yield path
finally:
fs. | remove(path=path)
def _get_contents(fs, path, mode):
with fs.open(path=path, mode="r" + mode) as file:
return file.read()
def _set_contents(fs, path, contents, mode):
with fs.open(path=path, mode="w" + mode) as file:
file.write(contents)
def _create_with_contents(fs, path, contents):
w... |
Rbeaty88/ginga | ginga/gtkw/GtkMain.py | Python | bsd-3-clause | 5,866 | 0.005285 | #
# GtkMain.py -- pygtk threading help routines.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
"""
GUI threading help routines.
Usage:
import GtkMain
# See c... | eration(False)
gtk.ma | in_iteration()
finally:
pass
def gui_do(self, method, *args, **kwdargs):
"""General method for asynchronously calling into the GUI.
It makes a future to call the given (method) with the given (args)
and (kwdargs) inside the gui thread. If the calling thread is a
... |
maciejkula/scipy | scipy/interpolate/polyint.py | Python | bsd-3-clause | 32,302 | 0.002631 | from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from scipy.special import factorial
from scipy.lib.six import xrange
__all__ = ["KroghInterpolator", "krogh_interpolate", "BarycentricInterpolator",
"barycentric_interpolate", "PiecewisePolynomial",
... | e self.dtype as the y-data type.
Attributes
----------
_y_axis
Axis along which the interpolatio | n goes in the original array
_y_extra_shape
Additional trailing shape of the input arrays, excluding
the interpolation axis.
dtype
Dtype of the y-data arrays. Can be set via set_dtype, which
forces it to be float or complex.
Methods
-------
__call__
_prepare_x
... |
lmazuel/azure-sdk-for-python | azure-cognitiveservices-vision-face/setup.py | Python | mit | 2,837 | 0.001057 | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Co | rporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import re
import os.path
from io import open
from setuptools import find_packages, setup
try:
from azur | e_bdist_wheel import cmdclass
except ImportError:
from distutils import log as logger
logger.warn("Wheel is not available, disabling bdist_wheel hook")
cmdclass = {}
# Change the PACKAGE_NAME only to change folder and different name
PACKAGE_NAME = "azure-cognitiveservices-vision-face"
PACKAGE_PPRINT_NAME =... |
JshWright/home-assistant | homeassistant/components/switch/wemo.py | Python | apache-2.0 | 7,698 | 0 | """
Support for WeMo switches.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/switch.wemo/
"""
import logging
from datetime import datetime, timedelta
from homeassistant.components.switch import SwitchDevice
from homeassistant.util import convert
from ... | ndby_state == WEMO_OFF:
return STATE_OFF
elif sta | ndby_state == WEMO_STANDBY:
return STATE_STANDBY
else:
return STATE_UNKNOWN
@property
def is_on(self):
"""Return true if switch is on. Standby is on."""
return self._state
@property
def available(self):
"""True if switch is available.... |
kobotoolbox/kobocat | onadata/apps/logger/tests/test_backup_tools.py | Python | bsd-2-clause | 3,654 | 0 | # coding: utf-8
from datetime import datetime
import os
import tempfile
import shutil
from django.conf import settings
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models import Instance
from onadata.apps.logger.import_tools import django_file
from onadata.apps.logger.import_tools i... | te_instance(
self.user.username, xml_file, media_files,
date_created_override=date_created)
self.assertIsNotNone(instance)
self.assertEqual(instance.date_created.strftime("%Y-%m-%d %H:%M:%S"),
date_created.strftime("%Y-%m-%d %H:%M:%S"))
def test_date... | = "2012-01-02-12-35-48"
date_created = datetime.strptime(date_str, "%Y-%m-%d-%H-%M-%S")
filename = "%s.xml" % date_str
generated_date_created = _date_created_from_filename(filename)
self.assertEqual(generated_date_created, date_created)
# test a filename with an index suffix
... |
ekohl/ganeti | lib/client/gnt_job.py | Python | gpl-2.0 | 11,547 | 0.00918 | #
#
# Copyright (C) 2006, 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distri... | int
@return: the desired exit code
"""
selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
output = GetClient().QueryJobs(args, selected_fields)
if not opts.no_headers:
# TODO: Implement more fields
headers = {
"id": "ID",
"status": "Status" | ,
"priority": "Prio",
"ops": "OpCodes",
"opresult": "OpCode_result",
"opstatus": "OpCode_status",
"oplog": "OpCode_log",
"summary": "Summary",
"opstart": "OpCode_start",
"opexec": "OpCode_exec",
"opend": "OpCode_end",
"oppriority": "OpCode_prio",
"start_... |
jiangfire/python-network-py3code | chapter3/echosever.py | Python | gpl-2.0 | 799 | 0.042146 | #Echo server - | chapter 3- echoserver.py
import socket, traceback
host = '' #bind to all interface
port = 51423
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, | socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
while True:
try:
clientsock, clientaddr = s.accept()
except KeyboradInterrupt:
raise
except:
traceback.print_exc()
continue
#Process the connection
try:
print('Got connection from', clientsock.getpeername())
while True:
data = clientsock.recv(40... |
NervanaSystems/neon | neon/backends/kernels/cuda/__init__.py | Python | apache-2.0 | 748 | 0 | # ******************************************************************************
# Copyright 2014-2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th | e License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#... | rning permissions and
# limitations under the License.
# ******************************************************************************
|
google/segy-stack | python/test_StackFile.py | Python | apache-2.0 | 6,283 | 0.000796 | #!/usr/bin/python
#
# Copyright 2020 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 required by applicable law or ag... | .cross | line_num == 0)
assert(bbox.c1.latitude != 0.0)
assert(bbox.c1.longitude != 0.0)
if (sf.grid().num_inlines > 1):
assert(bbox.c3.y != 0.0)
assert(bbox.c4.y != 0.0)
assert(bbox.c3.inline_num == (num_il-1)*il_incr)
assert(bbox.c4.inline_num == (num_il-... |
bmazin/ARCONS-pipeline | photonlist/test/testExpTimeWeight.py | Python | gpl-2.0 | 1,192 | 0.011745 | '''
Author: Julian van Eyken Date: Jul 9 2013
Test code for per-pixel effective exposure time weighting.
'''
import os.path
import photonlist.photlist as pl
import photonlist.RADecImage as rdi
from util.FileName import FileName
def getSimpleImage(fileName=FileName(run='PAL2012',date='20121211',tstamp='20121212... | t the | per-pixel effective integration
time weighting.
'''
virtualImage = rdi.RADecImage(vPlateScale=0.1)
print 'Loading: ',os.path.basename(fileName)
phList = pl.PhotList(fileName)
baseSaveName,ext=os.path.splitext(os.path.basename(fileName))
imSaveName=baseSaveName+'.tif'
virtualImage.l... |
ic-hep/DIRAC | src/DIRAC/Core/DISET/private/Transports/SSLTransport.py | Python | gpl-3.0 | 4,302 | 0.00186 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import six
import os
from DIRAC import gLogger
from DIRAC.Core.Security import Locations
from DIRAC.Core.Utilities.ReturnValues import S_ERROR, S_OK
from DIRAC.Core.Security.X509Chain impor... | .getNotAfterDate()
| if notAfter["OK"]:
notAfter = notAfter["Value"]
else:
notAfter = "unknown"
gLogger.error("PEM file has expired", "%s is not valid after %s" % (certFile, notAfter))
return S_ERROR("PEM file %s has expired, not valid after %s" % (certFile, notA... |
pypingou/pagure | pagure/docs_server.py | Python | gpl-2.0 | 6,488 | 0 | # -*- coding: utf-8 -*-
"""
(c) 2014-2016 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
"""
from __future__ import unicode_literals, absolute_import
import logging
import os
import flask
import pygit2
from binaryornot.helpers import is_binary_string
import pagure.config
import p... | content, safe = pagure.doc_utils.convert_readme(
blob_obj.data, ext
)
if safe:
filename = name + ".htm | l"
except pagure.exceptions.PagureEncodingException:
content = blob_obj.data
else:
content = blob_obj.data
tree = sorted(tree_obj, key=lambda x: x.filemode)
return (tree, content, filename)
@APP.route("/<repo>/")
@APP.route("/<namespace>.<repo>/")
@APP.route("/... |
GUR9000/KerasNeuralFingerprint | keras/layers/convolutional.py | Python | mit | 62,591 | 0.001805 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .. import backend as K
from .. import activations, initializations, regularizers, constraints
from ..engine import Layer, InputSpec
from ..utils.np_utils import conv_output_length, conv_input_length
# imports for backwards namespace compatibility
fro... | self.input_dim = input_dim
self.input_length = input_length
if self.input_dim:
kwargs['input_shape'] = (self.input_length, self. | input_dim)
super(Convolution1D, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[2]
self.W_shape = (self.nb_filter, input_dim, self.filter_length, 1)
self.W = self.init(self.W_shape, name='{}_W'.format(self.name))
if self.bias:
self.... |
geokala/tosca-vcloud-plugin | network_plugin/floatingip.py | Python | apache-2.0 | 3,711 | 0.001078 | from cloudify import ctx
from cloudify import exceptions as cfy_exc
from cloudify.decorators import operation
from vcloud_plugin_common import with_vca_client, get_vcloud_config
from network_plugin import check_ip, isExternalIpAssigned, isInternalIpAssigned, get_vm_ip, save_gateway_configuration, getFreeIP, CREATE, DEL... | e == "DNAT":
any_type = "Any"
ctx.logger.info("Create floating ip NAT rule: original_ip '{0}',"
"translated_ip '{1}', rule type '{2}'"
.format(original_ip, translated_ip, rule_type))
gateway.add_nat_rule(
rule_type, original_ip, any_type, translated_ip, ... | way, vca_client, rule_type, original_ip, translated_ip):
any_type = 'any'
if rule_type == "DNAT":
any_type = "Any"
ctx.logger.info("Delete floating ip NAT rule: original_ip '{0}',"
"translated_ip '{1}', rule type '{2}'"
.format(original_ip, translated_ip, ru... |
ActiveLearningLab/funtool-ipro-processes | funtool_ipro_processes/reporters/sequence_reporter.py | Python | mit | 41 | 0 |
def | sequence | _results():
return None
|
exoscale/requests-exoscale-auth | exoscale_auth.py | Python | bsd-3-clause | 3,141 | 0.000318 | from __future__ import unicode_literals
import hashlib
import hmac
import time
from base64 import standard_b64encode
from datetime import datetime
from urllib.parse import parse_qs, urlparse
from requests.auth import AuthBase
class ExoscaleAuth(AuthBase):
def __init__(self, key, secret):
self.key = key
... | thorization': auth,
})
return request
class ExoscaleV2Auth(AuthBase):
def __init__(self, key, secret):
self.key = key
self.secret = secret.encode('utf-8')
def __call__(self, request):
expiration_ts = int(time.time() + 10 * 60)
self._sign_request(request, expira... | sign_request(self, request, expiration_ts):
auth_header = 'EXO2-HMAC-SHA256 credential={}'.format(self.key)
msg_parts = []
# Request method/URL path
msg_parts.append('{method} {path}'.format(
method=request.method, path=urlparse(request.url).path
).encode('utf-8'))
... |
skoslowski/gnuradio | gr-blocks/examples/tags/test_file_tags.py | Python | gpl-3.0 | 903 | 0.00443 | #!/usr/bin/env python
#
# Copyright 2011,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from __future__ import print_function
from __future__ import unicode_literals
from gnuradio import gr
from gnuradio import blocks
import sys
import numpy
d... | ():
data = numpy.arange(0, 32000, 1).tolist()
trig = 100*[0,] + 100*[1,]
src = blocks.vector_source_s(data, True)
trigger = blocks.vector_source_s(trig, True)
thr = blocks.throttle(gr.sizeof_short, 10e3)
ann = blocks.annotator_alltoall(1000000, gr.sizeof_short)
tagger = blocks.burst_tagger... | tb = gr.top_block()
tb.connect(src, thr, (tagger, 0))
tb.connect(trigger, (tagger, 1))
tb.connect(tagger, fsnk)
tb.run()
if __name__ == "__main__":
main()
|
DavidCain/mitoc-trips | ws/middleware.py | Python | gpl-3.0 | 1,876 | 0.000533 | from django.contrib.auth.models import User
from ws.messages import security
from ws.models import Participant
class PrefetchGroupsMiddleware:
"""Prefetch the user's groups for use in the requset.
We do a lot of group-centric logic - if the user's groups aren't
prefetched, then we can easily have n+1 qu... | ponse = get_res | ponse
def __call__(self, request):
if request.user.is_authenticated:
filtered_user = User.objects.filter(pk=request.user.pk)
request.user = filtered_user.prefetch_related('groups').get()
return self.get_response(request)
class ParticipantMiddleware:
"""Include the user... |
SINGROUP/pycp2k | pycp2k/classes/_mixing1.py | Python | lgpl-3.0 | 2,435 | 0.001232 | from pycp2k.inputsection import InputSection
class _mixing1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Method = None
self.Alpha = None
self.Beta = None
self.Pulay_alpha = None
self.Pulay_beta = None
... | @property
def Nsimplemix(self):
"""
See documentation for N_simple_mix
| """
return self.N_simple_mix
@Npulay.setter
def Npulay(self, value):
self.Nbuffer = value
@Nbroyden.setter
def Nbroyden(self, value):
self.Nbuffer = value
@Nmultisecant.setter
def Nmultisecant(self, value):
self.Nbuffer = value
@Nskip_mixing.setter
... |
pierg75/pier-sosreport | sos/plugins/nis.py | Python | gpl-2.0 | 1,203 | 0 | # 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 it will be useful,
# but... | OSE. 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 Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class Nis(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin):... |
philchristensen/modu | examples/modusite/modusite/model/faq.py | Python | mit | 371 | 0.026954 | # modusite
# Copyright (c) 2006-2010 Phil | Christensen
# http://modu.bubblehouse.org
#
#
from modu.persist import storable
class FAQ(storable.Storable):
def __init__(self):
super(FAQ, self).__init__('faq')
def get_answerer(self):
store = self.get_store()
store.ensure_factory('user')
user = store.load_one('user', id=self.answered_by)
return user.... | |
JohnLZeller/dd-agent | checks.d/http_check.py | Python | bsd-3-clause | 11,850 | 0.002025 | # stdlib
from datetime import datetime
import os.path
import socket
import ssl
import time
import re
from urlparse import urlparse
# 3rd party
import tornado
import requests
# project
from checks.network_checks import NetworkCheck, Status, EventType
from config import _is_affirmative
from util import headers as agent... | tance.get('collect_response_time', True))
if not url:
raise Exception("Bad configuration. You must specify | a url")
include_content = _is_affirmative(instance.get('include_content', False))
ssl = _is_affirmative(instance.get('disable_ssl_validation', True))
ssl_expire = _is_affirmative(instance.get('check_certificate_expiration', True))
return url, username, password, http_response_status_cod... |
pauleveritt/visual_debugging_games | stack_frames/game.py | Python | apache-2.0 | 1,712 | 0 | import arcade
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
MOVEMENT_SPEED = 5
GRAVITY = 0.3
class Player(arcade.Sprite):
def update(self):
self.change_y -= GRAVITY
self.center_x += self.change_x
self.center_y += self.change_y
if self.left < 0:
self.left = 0
elif sel... | self.top = SCREEN_HEIGHT - 1
class MyGame(arcade.Window):
def __init__(self, width, height, title):
super().__init__(width, height, title)
arcade.set_background_color(arcade.color.WHEAT)
self.player = Player('player.png', 0.5)
self.player.center_y = 20
self.all_sprites_lis... | |
OpenCanada/lindinitiative | lindinitiative/settings/production.py | Python | mit | 1,319 | 0 | from __future__ import absolute_import, unicode_literals
from .base import *
DEBUG = False
TEMPLATE_DEBUG = False
COMPRESS_OFFLINE = True
AWS_STORAGE_BUCKET_NAME = get_env_variable("AWS_STORAGE_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME)
DEFAULT_FILE_STORAGE = 'storag... | S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = 'https://{}.s3.amazonaws.com/'.format(AWS_STORAGE_BUCKET_NAME)
STATIC_URL = 'https://{}.s3.amazonaws.com/'.format(AWS_STORAGE_BUCKET_NAME)
MEDIA_URL = 'https://{}.s3.... | ALLED_APPS + (
'raven.contrib.django.raven_compat',
)
FAVICON_PATH = STATIC_URL + 'img/favicon.png'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': get_env_variable('DB_NAME'),
'USER': get_env_variable('DB_USER'),
'PASSWORD': get_env_vari... |
yipyip/Qurawl | qurawl/qurawl.py | Python | mit | 5,127 | 0.005851 | # -*- coding: utf-8 -*-
"""Qurawl Main"""
####
from __future__ import absolute_import
from __future__ import unicode_literals
import itertools as it
import random as rand
import difflib as diff
####
import common.debugit as debugit
import qurawl.regparse as rp
from qurawl.level import *
from qurawl.items import *
... | state and action comments"""
def __init__(self):
self.reset()
def reset(self):
self.buf = []
def __call__(self, level, msg):
self.buf.append((level, msg))
| def __iter__(self):
return iter(self.buf)
def pick(self, result, actor, thing):
if isinstance(thing, Corpse):
com = "{0} plunders the corpse of {1}."
name = thing.name.rsplit("_", 1)[0]
self.buf.append((2, com.format(actor.name, name)))
return
... |
wispwisp/supportNotebook | responseTemplates/urls.py | Python | mit | 184 | 0 | from django.conf.urls import url
fro | m . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'templates/$', vi | ews.templates, name='templates'),
]
|
GoogleCloudPlatform/cloud-pubsub-logging-python | pubsub_logging/errors.py | Python | apache-2.0 | 759 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | nore."""
pass
| |
navcoindev/navcoin-core | qa/rpc-tests/zmq_test.py | Python | mit | 3,264 | 0.006434 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test ZMQ interface
#
from test_framework.test_framework import NavCoinTestFramework
from test_framew... | lf.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b"hashblock")
self.zmqSubSocket.setsockopt(zmq.SUBSCRIBE, b | "hashtx")
self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % self.port)
return start_nodes(self.num_nodes, self.options.tmpdir, extra_args=[
['-zmqpubhashtx=tcp://127.0.0.1:'+str(self.port), '-zmqpubhashblock=tcp://127.0.0.1:'+str(self.port)],
[],
[],
[]
... |
dubourg/openturns | python/test/t_KPermutationsDistribution_std.py | Python | gpl-3.0 | 1,806 | 0.000554 | #! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
distribution = KPermutationsDistribution(5, 12)
print("Distribution ", distribution)
# Is this distribution elliptical ?
print... | getCovariance()
print("covariance=", covariance)
parameters = distribution.getParametersCollection()
print("parameters=", parameters)
except:
import sys
print("t_KPermutation | sDistribution_std.py",
sys.exc_info()[0], sys.exc_info()[1])
|
AlertaDengue/AlertaDengue | AlertaDengue/ad_main/celeryapp.py | Python | gpl-3.0 | 465 | 0 | import os
from celery import Celery
# This makes sure celery knows where settings are, so we don't need to set it
# when calling it from the command line
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ad_main.settings')
app = Ce | lery(
"ad_main",
| broker=os.getenv("CELERY_BROKER_URL"),
backend=os.getenv("CELERY_BACKEND"), #
include=["dbf.tasks"],
)
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
|
youtube/cobalt | third_party/v8/PRESUBMIT.py | Python | bsd-3-clause | 1,880 | 0.005851 | """Top-level presubmit script for Cobalt."""
import imp
# TODO(uzhilinsky): Temporarily use Steel's PRESUBMIT checks until Cobalt can
# transition to use the canned checks from depot_tools.
steel_presubmit_checks = imp.load_source(
'steel_presubmit_checks', '../tools/repo-hooks/steel_presubmit_checks.py')
CPPLIN... | to the main repository. This hook is | not used by Steel
because our code is committed from GoB via the web interface.
Args:
input_api: presubmit_support input API
output_api: presubmit_support output API
Returns:
List of failed test results. Empty if all tests were successful.
"""
# Currently not used
_ = input_api, output_api
... |
pattyshack/abc | src/jvm_bytecode/gen_access_flags.py | Python | bsd-3-clause | 5,371 | 0.000186 | IMPORTS = [
'java.io.DataInputStream',
'java.io.DataOutputStream',
'java.util.Vector',
'scala.collection.JavaConversions._'
]
# class name -> (owner type, comment, {name -> bit})
ACCESS_FLAGS = {
'ClassAccessFlags': (
'ClassInfo',
'see tab... | 'interface': 0x0200,
'abstract': 0x0400,
'synthetic': 0x1000,
'annotation': 0x2000,
'enum': 0x4000,
}),
'FieldAccessFlags': (
'FieldInfo',
'see table 4.5-A / page 90 | -91',
{
'public': 0x0001,
'private': 0x0002,
'protected': 0x0004,
'static': 0x0008,
'final': 0x0010,
'volatile': 0x0040,
'transient': 0x0080,
... |
ImperiumMaximus/budgie-cpupower-applet | applet/cpupower.py | Python | gpl-3.0 | 11,958 | 0.003094 | #!/usr/bin/env python3
# Copyright (C) 2017 Fioratto Raffaele
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
# This ... | .cpupower_proxy.set_min_perf_pct(profile[0])
if self.cpupower_proxy.get_max_perf_pct() != profile[1]:
self.cpupower_proxy.set_max_perf_pct(profile[1])
if self.cpupow | er_proxy.get_tb_state() != profile[2]:
self.cpupower_proxy.set_tb_state(profile[2])
else:
r.set_active(False)
r.connect_after('toggled', self.profile_changed, index)
index += 1
self.profiles_box.show_all()
def profile_changed(self, wi... |
hamish2014/FreeCAD_assembly2 | assembly2/utils/checkAssembly.py | Python | lgpl-2.1 | 4,299 | 0.013259 | from assembly2.core import *
import time, traceback
from FreeCAD import Base
moduleVars = {}
class CheckAssemblyCommand:
def Activated(self):
debugPrint(2, 'Conducting Assembly Part Overlap Check for: %s' % FreeCAD.ActiveDocument.Label)
objects = [obj for obj in FreeCAD.ActiveDocument.Ob | jects if hasattr(obj, 'Shape') and obj.Name ! | = 'muxedAssembly']
n = len(objects)
no_of_checks = 0.5*(n-1)*(n)
moduleVars['progressDialog'] = QtGui.QProgressDialog("Checking assembly", "Cancel", 0, no_of_checks)#, QtGui.QApplication.activeWindow()) with parent cancel does not work for some reason
p = moduleVars['progressDialog']
... |
Sonblind/orchestra | orchestra/tests/google_apps/test_convenience.py | Python | apache-2.0 | 5,072 | 0 | from unittest.mock import patch
from unittest.mock import MagicMock
from django.test import override_settings
from django.test import TestCase
from django.conf import settings
from orchestra.google_apps.convenience import _get_image_mimetype
from orchestra.google_apps.convenience import create_document_from_template
... | media_images['folder']['id'], 1)
self.assertEquals(
media_images['image_counter']['uploaded_images'], 1)
# Make sure that if the incorrect image is provided,
# still returns a new folder.
media_images = create_media_folder_with_images(
'test_parent_id',
... | ], 1)
self.assertEquals(
media_images['image_counter']['not_uploaded_images'], 2)
with self.assertRaises(GoogleDriveError):
folder = create_folder_with_permissions(
'test_parent_id', 'error')
# In order to test permission failure we did something convolu... |
StackStorm/mistral | mistral/services/security.py | Python | apache-2.0 | 3,090 | 0 | # Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | f add_trust_id(secure_object_values):
if cfg.CONF.pecan.auth_enable:
trust = | create_trust()
secure_object_values.update({
'trust_id': trust.id
})
|
jechiy/phpMyAdmin | doc/conf.py | Python | gpl-2.0 | 9,675 | 0.006925 | # -*- coding: utf-8 -*-
#
# phpMyAdmin documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 26 14:04:48 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... | ).
#html_file_suffix = None
# Output file base name for HTML help b | uilder.
htmlhelp_basename = 'phpMyAdmindoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX p... |
blairconrad/LibraryHippo | Tests/test_gael_testing.py | Python | mit | 425 | 0.002353 | import sys
import gael.testing
def test__add_appsever_import_paths__multiple_calls__only_adds_once():
components_before_add = len(sys.path)
ga | el.testing.add_appsever_import_paths()
components_after_first_add = len(sys.path)
gael.testing.add_appsever_import_paths()
components_after_second_add = len(sys.path)
assert components_before_add <= components_after_first_add == component | s_after_second_add
|
MichaelDAlbrow/pyDIA | Code/DIA_CPU_header.py | Python | mit | 35 | 0 | i | mport c_interface_functions as | CI
|
bocaaust/CrowdCop | CrowdCop_test/crowdcop/crowdcop_web/migrations/0022_auto_20160412_1630.py | Python | apache-2.0 | 791 | 0.002528 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-04-12 20:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
| ('crowdcop_web', '0021 | _auto_20160412_1629'),
]
operations = [
migrations.AlterField(
model_name='tip',
name='date',
field=models.DateTimeField(verbose_name='When did this occur (If known, enter date and time).'),
),
migrations.AlterField(
model_name='tip',
... |
dotsdl/PyTables | tables/unimplemented.py | Python | bsd-3-clause | 5,459 | 0.00055 | # -*- coding: utf-8 -*-
########################################################################
#
# License: BSD
# Created: January 14, 2004
# Author: Francesc Alted - faltet@pytables.com
#
# $Id$
#
########################################################################
"""Here is defined the UnImplemented class."... | supported in more recent HDF5 versions.>
""" % (str(self))
# These ar | e listed here for backward compatibility with PyTables 0.9.x indexes
class OldIndexArray(UnImplemented):
_c_classid = 'IndexArray'
|
wkerzendorf/wsynphot | wsynphot/data/hst/acs/convert_filters.py | Python | bsd-3-clause | 1,562 | 0.004481 | #Reading HST ACS filters
from astropy import units as u, constants as const
from numpy import genfromtxt, asscalar
import pandas as pd
import os
from glob import glob
def read_hst_filter(fname):
"""
Reading the gemini filter file into a dataframe
Parameters
----------
fname: ~str
path to... | prefix for the dictionary keys
Returns
-------
dict
"""
filter_dict = {}
for fname in fname_list:
if name_parser is not None:
filter_name = name_parser(fname)
else:
filter_name = fname
filter_pat | h = os.path.join(prefix, filter_name)
filter_dict[filter_path] = read_hst_filter(fname)
return filter_dict
def read_all_hst():
hst_nameparser = (
lambda fname: os.path.basename(
fname).lower().split('_')[1].replace('.dat', ''))
hst_filters = read_dataset(glob('filter_data/*.... |
funkyfuture/cerberus | cerberus/tests/test_rule_regex.py | Python | isc | 651 | 0.001536 | from cerberus import errors
from cerberus.tests import assert_fail, assert_success
def test_regex(va | lidator):
field = 'a_regex_email'
assert_success({field: 'valid.email@gmail.com'}, validator=validator)
assert_fail(
{field: 'invalid'},
update=True,
error=(
field,
(fiel | d, 'regex'),
errors.REGEX_MISMATCH,
r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$',
),
)
def test_regex_with_flag():
assert_success({"item": "hOly grAil"}, {"item": {"regex": "(?i)holy grail"}})
assert_fail({"item": "hOly grAil"}, {"item": {"regex": "holy grail"}})
|
slabanja/ase | ase/gui/graphene.py | Python | gpl-2.0 | 8,902 | 0.002585 | # encoding: utf-8
"""nanotube.py - Window for setting up Graphene sheets and ribbons.
"""
import gtk
from ase.gui.widgets import pack, cancel_apply_ok, oops
from ase.gui.setupwindow import SetupWindow
from ase.gui.pybutton import PyButton
from ase.structure import graphene_nanoribbon
import ase
import numpy as np
in... | = graphene_nanoribbon(n, m, type=orient, C_C=CC,
vacc=vacuum,
main_element=elem)
elif self.struct.get_active() == 2:
# Saturated nanoribbon
elem2 = self.legal_element2
... | , type=orient, C_C=CC,
C_H=self.bondlength2.value,
vacuum=vacuum,
saturated=True,
main_element=elem,
... |
snaury/kitsu.http | setup_gevent.py | Python | mit | 119 | 0.008403 | import gevent.monkey
gevent.m | onkey.patch_all()
import o | s
execfile(os.path.join(os.path.dirname(__file__), 'setup.py'))
|
brburns/netdisco | netdisco/discoverables/directv.py | Python | apache-2.0 | 693 | 0 | """Discover DirecTV Receivers."""
from netdisco.util import urlparse
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
"""Add support for discovering DirecTV Receivers."""
def info_from_entry(self, entry):
"""Return the most important info from a uP | nP entry."""
url = urlparse(entry.values['location'])
device = entry.description['device']
return url.hostname, device['serialNum | ber']
def get_entries(self):
"""Get all the DirecTV uPnP entries."""
return self.find_by_device_description({
"manufacturer": "DIRECTV",
"deviceType": "urn:schemas-upnp-org:device:MediaServer:1"
})
|
zenefits/sentry | tests/sentry/web/frontend/test_reactivate_account.py | Python | bsd-3-clause | 796 | 0 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
class Rea | ctivateAccountTest(TestCase):
@fixture
def path(self):
return reverse('sentry-reactivate-account')
def test_renders(self):
user = self.create_user('foo@example.com', is_active=False)
self.login_as(user)
| resp = self.client.get(self.path)
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'sentry/reactivate-account.html')
def test_does_reactivate(self):
user = self.create_user('foo@example.com', is_active=False)
self.login_as(user)
resp = self.client.post(... |
iulian787/spack | var/spack/repos/builtin/packages/mosh/package.py | Python | lgpl-2.1 | 1,152 | 0.003472 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Mosh(AutotoolsPackage):
"""Remote terminal application that allows roaming, supports inter... | connectivity, and provides intelligent lo | cal echo and line editing of user
keystrokes. Mosh is a replacement for SSH. It's more robust and responsive,
especially over Wi-Fi, cellular, and long-distance links.
"""
homepage = "https://mosh.org/"
url = "https://mosh.org/mosh-1.2.6.tar.gz"
version('1.3.2', sha256='da600573dfa827d88c... |
sora7/listparse | src/listparse/ui/common.py | Python | gpl-2.0 | 2,865 | 0.000349 | import tkinter
FRAME_BORDER = 5
class PageView(object):
__root = None
bd = None
def __init__(self, root=None, main_frame=None):
param = self.params()
if | root is None:
# standalone
self.__root = tkinter.Tk()
| self.__root.title(param['title'])
self.__root.geometry('%sx%s+%s+%s' % (param['w'],
param['h'],
param['x'],
param['y']
... |
lixun910/pysal | pysal/model/spreg/sur.py | Python | bsd-3-clause | 35,446 | 0.009874 | """
SUR and 3SLS estimation
"""
__author__= "Luc Anselin lanselin@gmail.com, \
Pedro V. Amaral pedrovma@gmail.com"
import numpy as np
import numpy.linalg as la
from scipy import stats
from . import summary_output as SUMMARY
from . import user_output as USER
from . import regimes as REGI
from .sur_uti... | : dictionary with names of explanatory variables for each
equation
default = None, but should be specified
is done when sur_stackxy is used
name_ds : string; name for the data set
name_w : string; name for the weights file
nam... | es
----------
bigy : dictionary with y values
bigX : dictionary with X values
bigXX : dictionary with X_t'X_r cross-products
bigXy : dictionary with X_t'y_r cross-products
n_eq : number of equations
n : number of observa... |
aureooms/repeating-decimal | reciprocals.py | Python | agpl-3.0 | 1,599 | 0.046963 | """
An integer that is not co-prime to 10 but has a prime factor other than 2 or 5
has a reciprocal that is eventually periodic, but with a non-repeating sequence
of digits that precede the repeating part. The reciprocal can be expressed as:
\frac{1}{2^a 5^b p^k q^\ell \cdots}\, ,
where a and b are not both zero... | ing digits are 03; and
the subsequent repeating digits are 571428.
"""
def transient ( d , bfactor ) :
"""
Computes the length | of the non repeating part in 1 / d decimals in
base b. Returns tuple ( n , hasrepetend ) where n is the length of the
non repeating part and hasrepetend determines if 1 / d repeats or not.
"""
n = 0
for f in bfactor :
m = 0
while d % f == 0 :
m += 1
d //= f
if m > n : n = m
return n , d > 1
... |
ericdahl/project-euler | python/p037.py | Python | bsd-3-clause | 359 | 0.008357 | import utils
primes = utils.primes(1000000)
def truncatable(n):
sn = str(n)
if len(sn) < 2:
return False
for i in range(1, len(sn)):
if int(sn[0:i]) not in primes or int(sn[-i:]) not in primes:
return False
return True
tprimes = filter(truncatable, pri | mes)
print | tprimes
print len(tprimes)
print sum(tprimes)
|
leonjza/weblick | web.py | Python | mit | 1,381 | 0.002896 | #!/usr/bin/python
# The MIT License (MIT)
#
# Copyright (c) 2015 Leon Jacobs
#
# 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
# ... | N ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER | DEALINGS IN
# THE SOFTWARE.
import ConfigParser
from app import app
# read the required configuration
config = ConfigParser.ConfigParser()
config.read('settings.ini')
port = config.getint('web', 'port')
# Run the weblick web interface
app.run(debug = False, port = port)
|
837278709/metro-openerp | third_modules/product_margin/__openerp__.py | Python | agpl-3.0 | 1,927 | 0.002595 | # -*- 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... | 'account'],
'data': [
'security/ir.model.access.csv',
'wizard/product_margin_view.xml',
'product_ | margin_view.xml'
],
'test':['test/product_margin.yml'],
'demo': [],
'installable': True,
'auto_install': False,
'images': ['images/open_margins.jpeg','images/product_margins_form.jpeg', 'images/product_margins_list.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
staeff/megaflask | app/forms.py | Python | bsd-3-clause | 1,916 | 0.00261 | from flask.ext.wtf import Form
from flask.ext.babel import gettext
from wtforms import StringField, BooleanField, TextAreaField
# DataRequired is a validator, a function that
# can be attached to a field to perform validation
# on the data submitted by the user.
from wtforms.validators import DataRequired, Length
from... | name.data != User.make_valid_nickname(self.nickname.data):
self.nickname.errors.append(gettext(
'This nickname contains invalid characters. '
'Please use letters, numbers, dots and underscores only.'
))
use | r = User.query.filter_by(nickname=self.nickname.data).first()
if user is not None:
self.nickname.errors.append(gettext('This nickname is already in user. '
'Please choose another one.'))
return False
return True
class PostForm(Form):
p... |
Aaron0927/xen-4.2.1 | tools/xm-test/tests/vtpm/07_vtpm-mig_pcrs.py | Python | gpl-2.0 | 3,482 | 0.003733 | #!/usr/bin/python
# Copyright (C) International Business Machines Corp., 2006
# Author: Stefan Berger <stefanb@us.ibm.com>
# Positive Test: create domain with virtual TPM attached at build time,
# extend a pcr
# check list of pcrs; locally migrate the domain and
# check li... | timeout=90)
except TimeoutError, e:
saveLog(consoleHistory) |
FAIL(str(e))
if status != 0:
saveLog(consoleHistory)
FAIL("xm migrate did not succeed. External device migration activated?")
domName = domain.getName()
new_domid = domid(domName)
if (old_domid == new_domid):
FAIL("xm migrate failed, domain id is still %s (loop=%d)" ... |
Kangz/nxt-standalone | generator/main.py | Python | apache-2.0 | 18,619 | 0.005962 | #!/usr/bin/env python2
# Copyright 2017 The Dawn Authors
#
# 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 l... | f.record['values']]
| self.full_mask = 0
for value in self.values:
self.full_mask = self.full_mask | value.value
class NativeType(Type):
def __init__(self, name, record):
Type.__init__(self, name, record, native=True)
class NativelyDefined(Type):
def __init__(self, name, record):
Type.__in... |
samuelgarcia/HearingLossSimulator | hearinglosssimulator/gui/wifidevice/tests/test_qwificlient.py | Python | mit | 586 | 0.015358 |
from hearinglosssimulator.gui.wifidevice.wifidevicewidget import WifiDeviceWidget
from hearinglosssimulator.gui.wifidevice.qwificlient import QWifiClient, ThreadAudioStream
from hearinglosssimulator.gui.wifidevice.gui_debug_wifidevice import WindowDebugWifiDevice
udp_ip = "192.168.1.1"
udp_port = 6666
def test_qwi... | = pg.mkQApp()
win = WindowDebugWifiDevice(client=client)
win.show()
app.exec_()
if __name__ =='__main__':
test_qwificlient()
| |
zentralopensource/zentral | tests/munki/test_tree_certificates.py | Python | apache-2.0 | 1,412 | 0.000708 | from datetime import datetime
import os
from django.test import SimpleTestCase
from zentral.contrib.munki.utils import iter_certificates, is_ca, prepare_ms_tree_certificates
class TestMunkiTreeCertificates(SimpleTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
tlsdir = os.path... | = list(iter_certificates(self.certs))
self.assertEqual(is_ca(cert), False)
self.assertEqual(is_ca(ca_cert), True)
def test_ms_tree_certificates(self):
ms_tree = {"pem_certificates": self.certs}
prepare_ms_tree_certificates(ms_tree)
self.assertEqual(
ms_tree["cer... | 'common_name': 'zentral',
'sha_1': 'f373928e75dfa460726c92c3263e664816b504d5',
'signed_by': {'common_name': 'Zentral CA',
'organization': 'Zentral',
'organizational_unit': 'IT'},
'valid_from': datetime(2019, 6, 27, 10, 56,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.