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 |
|---|---|---|---|---|---|---|---|---|
gf53520/kafka | kafka-merge-pr.py | Python | apache-2.0 | 19,703 | 0.004213 | #!/usr/bin/env python
#
# Licensed to t | he Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file excep... | the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#... |
hnakamur/saklient.python | saklient/cloud/errors/dontcreateinsandboxexception.py | Python | mit | 899 | 0.009331 | # -*- coding:utf-8 -* | -
from ...errors.httpforbiddenexception import HttpForbiddenException
import saklient
# module saklient.cloud.errors.dontcreateinsandboxexception
class DontCreateInSandboxException(HttpForbiddenException):
## 要求された操作は許可されていません。ゾーンをまたぐ一部のリソースは課金対象です。料金をご確認の上、他のゾーンで作成してください。
## @param {int} status
# @... | status, code, "要求された操作は許可されていません。ゾーンをまたぐ一部のリソースは課金対象です。料金をご確認の上、他のゾーンで作成してください。" if message is None or message == "" else message)
|
ternaus/submission_merger | src/mean_log_merger_bimbo.py | Python | mit | 753 | 0.009296 | from __future__ import d | ivision
__author__ = 'Vladimir Iglovikov'
'''
Merges prediction for https://www.kaggle.com/c/grupo-bimbo-inventory-demand competition
Expm1(Mean([Log1p | (x), Log1p(y)]))
'''
import os
import numpy as np
import sys
import pandas as pd
import time
files = sys.argv[1:]
try:
files.remove('mean_log_merger_bimbo.py')
except:
pass
data = [pd.read_csv(fName).sort_values(by='id') for fName in files]
ids = data[0]['id']
result = pd.DataFrame()
submission = pd.DataFrame(... |
looker/sentry | src/sentry/identity/providers/dummy.py | Python | bsd-3-clause | 857 | 0 | from __future__ import absolute_import, print_function
__all__ = ['DummyProvider']
from django.http import HttpResponse
from | sentry.identity.base import Provider
from sentry.pipeline impor | t PipelineView
class AskEmail(PipelineView):
def dispatch(self, request, pipeline):
if 'email' in request.POST:
pipeline.bind_state('email', request.POST.get('email'))
return pipeline.next_step()
return HttpResponse(DummyProvider.TEMPLATE)
class DummyProvider(Provider):
... |
mohamed--abdel-maksoud/chromium.src | mojo/public/tools/bindings/generators/mojom_dart_generator.py | Python | bsd-3-clause | 11,104 | 0.007745 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generates Dart source files from a mojom.Module."""
import mojom.generate.generator as generator
import mojom.generate.module as mojom
import mojom.gener... | .PackedBool)"
if mojom.IsArrayKind(kind):
return "decodeArrayPointer(%s)" % CodecType(kind.kind)
if mojom.IsInterfaceKind(kind) or mojom.IsInterfaceRequestKind(kind):
return DartDecodeSnippet(mojom.MSGPIPE)
if mojom.IsEnumKind(ki | nd):
return DartDecodeSnippet(mojom.INT32)
def DartEncodeSnippet(kind):
if kind in mojom.PRIMITIVES:
return "encodeStruct(%s, " % CodecType(kind)
if mojom.IsStructKind(kind):
return "encodeStructPointer(%s, " % DartType(kind)
if mojom.IsMapKind(kind):
return "encodeMapPointer(%s, %s, " % \
... |
light940929/niagadsofinquery | testexample/simplePostwithPython.py | Python | mit | 3,247 | 0.00616 | """NIAGADSOFINQUERY API application.
simplePostwithPython.py get -n <titlename> -i <individualnum> -s <snpnum> -f <tfampath> -p <tpedpath> -a <apitoken>
Usage:
simplePostwithPython.py get -n <titlename> -i <individualnum> -s <snpnum> -f <tfampath> -p <tpedpath> -a <apitoken>
simplePostwithPython.py (-h | --help)... | '--titlename'], "chr": ids[0], "variant_id": ids[1], "location": ids[2], "coordinate": ids[3], "call": call}
data = json.dumps(values)
print data
req = requests.post(url_genotypes, data, headers=headers)
print req.status_code
postPhenot | ypes(url_phenotypes, token, headers)
postGenotypes(url_genotypes, token, headers)
|
rahulunair/nova | nova/tests/functional/test_server_faults.py | Python | apache-2.0 | 5,378 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to | in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, eithe | r express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional import fixtures as func_fixtures
from nova.tests.functional import integrated_helpe... |
skonefal/workloadsutils | ab_util.py | Python | apache-2.0 | 972 | 0.013374 | import os
import datetime
import time
IDLE_TIME = 2 * 60
STRESS_ITERATION_TIME = 10 * 60
STRESS_LEVELS = [2,10,25,50,75,100]
# ENDPOINTS = ["http://10.102.44.201/index.php/Special:Random", "http://10.102.44.202/index.php/Special:Random", "http://10.102.44.203/index.php/Special:Random"]
def d | o_stress():
print("{0}: Starting idle time for {1} seconds".format(datetime.datetime.now(), IDLE_TIME))
time.sleep(IDLE_TIME)
for stress_level in STRESS_LEVELS:
Timestamp = datetime.datetime.now()
print("{0}: Starting stress level {1} for {2} secs".format(
datetime.datetime.now()... | TERATION_TIME))
os.system("ab -c {0} -n 500000 -l -r http://10.102.44.202/index.php/Special:Random".format(
stress_level))
pass
print("{0}: Stress finished after {1} iterations".format(
datetime.datetime.now(), len(STRESS_LEVELS)))
return
if __name__ == '__main__':
... |
ramineni/myironic | ironic/tests/drivers/test_pxe.py | Python | apache-2.0 | 44,025 | 0.000409 | # coding=utf-8
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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/li... | 'deploy_kernel')
deploy_ramdisk = os.path.join(http_url, self.node.uuid,
'deploy_ramdisk')
kernel = os.path.join(http_url, self.node.uuid, 'kernel')
ramdisk = os.path.join(http_url, self.node.uuid, 'ramdisk')
root_d... | 'deploy_kernel')
deploy_ramdisk = os.path.join(CONF.pxe.tftp_root, self.node.uuid,
'deploy_ramdisk')
kernel = os.path.join(CONF.pxe.tftp_root, self.node.uuid,
'kernel')
ramdisk = os. |
gglyptodon/marcook | markovchain.py | Python | gpl-3.0 | 1,417 | 0.015526 | import random
import sys
class MarkovChain(object):
def __init__(self, separator = None, corpus = None):
self.separator = separator
self.corpus = corpus
self.chain = self.setChain()
def setChain(self):
chain = {}
if self.separator is None:
allItems = self.co... | chain[mx].append("\n")
except KeyError as e:
chain[mx] = ["\n"]
return(chain)
def printSth(self,maxItems = 20):
res =""
t = random.choice(self.chain.keys())
| for i in range(0,maxItems):
try:
print(self.chain[t])
tmp = random.choice(self.chain[t])
res += " "+tmp
t= tmp
except KeyError as e:
return(res)
return(res)
def main():
mc = MarkovChain(corpus = open(... |
SU-ECE-17-7/ibeis | _broken/_old_qt_hs_matcher/automated_params.py | Python | apache-2.0 | 2,697 | 0.003708 | # -*- coding: utf-8 -*-
"""
module that specified how we choose paramaters based on current search database
properties
"""
from __future__ import absolute_import, division, print_function
#import six
import utool as ut
#import numpy as np
#import vtool as vt
#from ibeis.algo.hots import hstypes
#from ibeis.algo.hots im... | e:
python -m ibeis.algo.hots.automated_params
python -m ibeis.algo.hots.automated_ | params --allexamples
python -m ibeis.algo.hots.automated_params --allexamples --noface --nosrc
"""
import multiprocessing
multiprocessing.freeze_support() # for win32
import utool as ut # NOQA
ut.doctest_funcs()
|
Dining-Engineers/left-luggage-detection | misc/demo/demo_mp_async.py | Python | gpl-2.0 | 1,051 | 0 | #!/usr/bin/env python
import freenect
import signal
import matplotlib.pyplot as mp
from misc.demo import frame_convert
mp.ion()
image_rgb = None
image_depth = None
keep_running = True
def display_depth(dev, data, timestamp):
global image_depth
data = frame_convert.pretty_depth(data)
mp.gray()
mp.f... | th:
image_depth.set_data(data)
else:
image_depth = mp.imshow(data, interpolation='nearest', animated=True)
mp.draw()
def display_rgb(dev, data, timestamp):
global image_rgb
mp.figure(2)
if image_rgb:
image_rgb.set_data(data)
else:
image_rgb = mp.ims | how(data, interpolation='nearest', animated=True)
mp.draw()
def body(*args):
if not keep_running:
raise freenect.Kill
def handler(signum, frame):
global keep_running
keep_running = False
print('Press Ctrl-C in terminal to stop')
signal.signal(signal.SIGINT, handler)
freenect.runloop(depth=... |
EricSchles/regulations-parser | regparser/notice/compiler.py | Python | cc0-1.0 | 21,565 | 0.000139 | """ Notices indicate how a regulation has changed since the last version. This
module contains code to compile a regulation from a notice's changes. """
from bisect import bisect
from collections import defaultdict
import copy
import itertools
import logging
from regparser.grammar.tokens import Verb
from regparser.tr... | _utils
from regparser.utils import roman_nums
def get_parent_label(node):
""" Given a node, get the label of it's parent. """
if node.node_type == Node.SUBPART:
return node.label[0]
elif node.node_type == Node.INTERP:
marker_position = node.label.index(Node.INTERP_MARK)
interpretin... |
comment_pars = node.label[marker_position + 1:]
if comment_pars: # 111-3-a-Interp-4-i
return '-'.join(node.label[:-1])
elif len(interpreting) > 1: # 111-3-a-Interp
return '-'.join(interpreting[:-1] + [Node.INTERP_MARK])
else: ... |
pillmuncher/hornet | src/examples/parsing.py | Python | mit | 12,639 | 0.003561 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Mick Krippendorf <[email protected]>
__version__ = '0.2.5a'
__date__ = '2014-09-27'
__author__ = 'Mick Krippendorf <[email protected]>'
__license__ = 'MIT'
import pprint
from hornet import *
from hornet.symbols import (
A, Adj,... | vp(Number, nominative, intransitive),
s >>
np(Number, Case) &
vp(Number, Case, transitive),
np(plural, Case) >>
noun(_, plural, Case),
np(Number, Case) >>
det(Gender, Number, Case) &
noun(Gender, Number, Case),
vp(Number... | vp(_, dative, transitive) >>
verb(Number, nominative, transitive) &
np(Number, nominative),
vp(Number, nominative, transitive) >>
verb(Number, nominative, transitive) &
np(_, dative),
vp(Number, nominative, transitive) >>
verb(Number, accus... |
Fauxmoehawkeen/soundcloud-python-master | soundcloud/resource.py | Python | bsd-2-clause | 1,625 | 0 | try:
import json
except ImportError:
import simplejson as json
from UserList import UserList
class Resource(object):
"""Object wrapper for resources.
Provides an object interface to resources returned by the Soundcloud API.
"""
def __init__(self, obj):
self.obj = obj
def __getst... | source(response):
"""Return a response wrapped in the appropriate wrapper type.
Lists will be returned as a ```ResourceList``` ins | tance,
dicts will be returned as a ```Resource``` instance.
"""
try:
content = json.loads(response.content)
except ValueError:
# not JSON
content = response.content
if isinstance(content, list):
result = ResourceList(content)
else:
result = Resource(conten... |
ecreall/dace | dace/objectofcollaboration/system.py | Python | agpl-3.0 | 2,093 | 0.000478 | # Copyrig | ht (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Vincent Fretin, Amen Souissi
import transaction
from substanced.util import get_oid
from dace.processinstance.event import DelayedCallback
from dace.util import (
find_catalog, getAllS... |
get_system_request, BaseJob)
from dace import log
last_transaction_by_machine = {}
def _call_action(action):
transaction.begin()
try:
context = action.get_potential_context()
if context is None:
return
request = get_system_request()
request.invalidate_cache ... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/azure/azure_rm_acs.py | Python | bsd-3-clause | 27,547 | 0.002868 | #!/usr/bin/python
#
# Copyright (c) 2017 Julien Stroheker, <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | ure_rm_acs
'''
RETURN = '''
state:
description: Current state of the azure container service
returned: always
type: dict
'''
from ansible.module_utils.azure_rm_common | import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.containerservice.models import (
ContainerService, ContainerServiceOrchestratorProfile, ContainerServiceCustomProfile,
ContainerServiceServi |
phildini/logtacts | invitations/consumers.py | Python | mit | 1,739 | 0.004025 | import logging
import requests
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.utils import timezone
from invitations.models import Invitation
logger = logging.getLogger('email... | sage.send()
invite.status = Invitation.SENT
invite.sent = timezone.now()
invite.save()
except:
| sentry.exception('Problem sending invite', exc_info=True, extra={'invite_id': invite.id})
invite.status = Invitation.ERROR
invite.save()
|
jsymolon/ARMSim | TestBKPT.py | Python | gpl-2.0 | 1,495 | 0.002676 | import unittest
import armv6instrdecode
import globals
import utils
import logging
import ARMCPU
import pdb
# if ConditionPassed(cond) then
# Rd = Rn + shifter_operand
# if S == 1 and Rd == R15 then
# if CurrentModeHasSPSR() then
# CPSR = SPSR
# else UNPREDICTABLE
# else if S == 1 then
# N Flag... | C Flag = CarryFrom(Rn + shifter_operand)
# V Flag = Ove | rflowFrom(Rn + shifter_operand)
logfile = "TestBKPT.log"
with open(logfile, 'w'):
pass
logging.basicConfig(filename=logfile,level=logging.DEBUG)
class TestBKPT(unittest.TestCase):
"""Instructions"""
# preparing to test
def setUp(self):
""" Setting up for the test """
self.addr = 0
... |
partofthething/home-assistant | tests/components/abode/test_cover.py | Python | apache-2.0 | 2,112 | 0.000473 | """Tests for the Abode cover device."""
from unittest.mock import patch
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COV... | ID)
| assert entry.unique_id == "61cbz3b542d2o33ed2fz02721bda3324"
async def test_attributes(hass):
"""Test the cover attributes are correct."""
await setup_platform(hass, COVER_DOMAIN)
state = hass.states.get(DEVICE_ID)
assert state.state == STATE_CLOSED
assert state.attributes.get(ATTR_DEVICE_ID) ==... |
meerkat-code/meerkat_api | setup.py | Python | mit | 539 | 0 | #!/usr/bin/env python3
import uuid
from setuptools import setup, find_packages
import pathlib
import pkg_resour | ces
with pathlib.Path('requirements.txt').open() as requirements_txt:
reqs = [
str(requirement)
for requirement
in pkg_resources.parse_requirements(requirements_txt)
]
setup(
name='Meerkat API',
version='0.0.1',
long_description=__doc__,
packages=find_packages(),
in... | se,
install_requires=reqs,
test_suite='meerkat_api.test'
)
|
labordoc/labordoc-next | modules/webdeposit/lib/webdeposit_workflow.py | Python | gpl-2.0 | 7,407 | 0.00216 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2012, 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your opt... |
def set_workflow(self, workflow):
""" Sets the workflow """
self.eng.setWorkflow(workflow)
self.workflow = workflow
self.steps_num = len(workflow)
self.obj['s | teps_num'] = self.steps_num
def set_object(self):
self.db_workflow_obj = \
WfeObject.query.filter(WfeObject.workflow_id == self.get_uuid()). \
first()
if self.db_workflow_obj is None:
self.bib_obj = BibWorkflowObject(data=self.obj,
... |
jobscry/vz-blog | __init__.py | Python | mit | 183 | 0.005464 | # -*- | mode: python; coding: utf-8; -*-
VERSION = (1, 3, 3)
__version__ = '.'.join(map(str, VERSION))
__author__ = 'Joe Vasquez'
__email__ = '[email protected] | '
__license__ = 'MIT' |
romanvm/romans_blog | blog/views.py | Python | gpl-3.0 | 4,713 | 0.001061 | from datetime import date
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.conf import settings
from django.utils.translation import ugettext as _
from django.utils.dateformat import format as format_date
from django.shortcuts import get_object_or_404
from dj... | per().get_queryset().prefetch_related('categories')
class _PageTitleMixIn:
"""
Adds page_title to ListView's context
"""
page_title = None
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['page_title'] = self.page_title
return cont... | splays the list of all published posts starting from the recent.
Template: ``blog_posts_list.html``
Specific context variable: ``posts``
"""
queryset = Post.objects.published()
class BlogFeaturedPostsView(_PageTitleMixIn, _PostsListView):
"""
Displays the list of featured posts
Template... |
deter-project/magi | magi/testbed/emulab.py | Python | gpl-2.0 | 7,564 | 0.006478 | # Copyright (C) 2012 University of Southern California
# This software is licensed under the GPLv3 license, included in
# ./GPLv3-LICENSE.txt in the source distribution
from collections import defaultdict
import itertools
import logging
import os
import shlex
import sys
from magi.util import helpers
from magi.util.ex... | """ Load the nickname file to get the node, experiment and project names """
try:
self._store.update(node='?', experiment='?', project='?', eid='?')
nickname = self.getNicknameData()
p = nickname.split('.')
self._store.update(node=p[0], experiment=p[1], proje... | nt=None, project=None):
""" Set the node, experiment, and project name """
if node:
self._store.update(node=node)
if experiment:
self._store.update(experiment=experiment)
if project:
self._store.update(project=project)
self._st... |
GeoMop/PythonOCC_Examples | src/bspline_surface.py | Python | gpl-2.0 | 3,394 | 0.003536 | """
Small Modification of src/examples/Geometry/geometry_demos.py
"""
from OCC.gp import *
from OCC.Geom import *
from OCC.TColGeom import *
from OCC.TColgp import *
from OCC.GeomConvert import *
from OCC.BRepBuilderAPI import *
from OCC.TopoDS import *
from OCC.STEPControl import *
from OCC.Display.SimpleGui import... | 4.SetValue(1, 3, gp_Pnt(5, 3, 1))
array4.SetValue(2, 1, gp_Pnt(3, 4, 1))
array4.SetValue(2, 2, gp_Pnt(4, 4, 1))
array4.SetValue(2, 3, gp_Pnt(5, 4, 1))
array4.SetValue(3, 1, gp_Pnt(3, 5, 2))
array4.SetValue(3, 2, gp_Pnt(4, 5, 2))
array4.SetValue(3, 3 | , gp_Pnt(5, 5, 1))
BZ1 = Geom_BezierSurface(array1)
BZ2 = Geom_BezierSurface(array2)
BZ3 = Geom_BezierSurface(array3)
BZ4 = Geom_BezierSurface(array4)
bezierarray = TColGeom_Array2OfBezierSurface(1, 2, 1, 2)
bezierarray.SetValue(1, 1, BZ1.GetHandle())
bezierarray.SetValue(1, 2, BZ2.GetHand... |
juan-cardelino/matlab_demos | ipol_demo-light-1025b85/app_available/blmv_nonlinear_cartoon_texture_decomposition/app.py | Python | gpl-2.0 | 11,626 | 0.006795 | """
Nonlinear cartoon+texture decomposition ipol demo web app
"""
from lib import base_app, build, http, image
from lib.misc import ctime
from lib.misc import prod
from lib.base_app import init_app
import shutil
import cherrypy
from cherrypy import TimeoutError
import os.path
import time
from math import ceil
class a... | G
#
def select_subimage(self, x0, y0, x1, y1):
"""
cut subimage from original image
"""
# draw selected rectangle on the image
imgS = image(self.work_dir + 'input_0.png')
imgS.draw_line([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)],
| color="red")
imgS.draw_line([(x0+1, y0+1), (x1-1, y0+1), (x1-1, y1-1), (x0+1, y1-1),
(x0+1, y0+1)], color="white")
imgS.save(self.work_dir + 'input_0s.png')
# crop the image
# try cropping from the original input image (if different from input_0)
i... |
wdzhou/mantid | scripts/HFIR_4Circle_Reduction/mplgraphicsview3d.py | Python | gpl-3.0 | 9,817 | 0.001121 | #pylint: disable=R0901,R0902,R0904
from __future__ import (absolute_import, division, print_function)
from six.moves import range
import numpy as np
import os
from PyQt4.QtGui import QSizePolicy
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from ... | :param data_key: key to locate the data stored to this class
:param base_color: None or a list of 3 elements from 0 to 1 for RGB
:return:
"""
# Check
assert isinstance(data_key, int) and data_key >= 0
assert base_color is None or len(base_c | olor) == 3
# get data and check
points = self._dataDict[data_key][0]
intensities = self._dataDict[data_key][1]
assert isinstance(points, np.ndarray)
assert isinstance(points.shape, tuple)
assert points.shape[1] == 3, '3D data %s.' % str(points.shape)
if len(poi... |
BlakeTeam/VHDLCodeGenerator | blocks/Standard Library/Gate AND.py | Python | gpl-3.0 | 2,291 | 0.014841 | #-------------------------------------------------------------------------------
# PROJECT: VHDL Code Generator
# NAME: Dynamic AND Gate
#
# LICENSE: GNU-GPL V3
#-------------------------------------------------------------------------------
__isBlock__ = True
__className__ = "ANDGate"
__win__ = "ANDGat... | stem,self.name)
def generate(self):
filetext = ""
if self.getOutputS | ignalSize(0) == 1:
filetext += "%s <= %s"%(self.getOutputSignalName(0),self.getInputSignalName(0))
for i in range(1,self.numInput):
filetext += " and %s"%(self.getInputSignalName(i))
else:
filetext += "%s <= "%self.getOutputSignalName(0)
for i in r... |
yehnan/python_book_yehnan | ch06/ch06_8queen_hettingers_gf.py | Python | gpl-2.0 | 315 | 0.003175 |
# Raymond Hettingers
# http://code.activestate.com/recipes/ | 576647/
from itertools import permutations
def queen_gf(n):
cols = range(n)
for ans in permutations(cols):
if (n == len(set(ans[i]+i for i in cols)) ==
len(set(ans[i]-i for i in cols))):
| yield ans
|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/test/test_usage.py | Python | gpl-3.0 | 56 | 0.017857 | ../../../../.. | /share/pyshared/twisted/test/test_usage. | py |
nive/nive_cms | nive_cms/image.py | Python | gpl-3.0 | 2,927 | 0.015032 | # Copyright 2012, 2013 Arndt Droullier, Nive GmbH. All rights reserved.
# Released under GPL3. See license.txt
#
__doc__ = """
Image
-----
The image element inserts images into the web page.
Images uploaded as fullsize will be be linked as pop ups.
If the Python Image Library (PIL) is installed automated image conve... | span3"
# image type definition ------------------------------------------------------------------
#@nive_module
configuration = ObjectConf(
id = "image",
name = _(u"Image"),
dbparam = "images",
context = "nive_cms.image.image",
template = "image.pt",
selectTag = StagPageElement,
extens... | ns = [],
icon = "nive_cms.cmsview:static/images/types/image.png",
description = _(u"The image element inserts images into the web page.")
)
configuration.data = [
FieldConf(id="image", datatype="file", size=0, default=u"", name=_(u"Imagefile")),
FieldConf(id="imagefull", datatype="file", size=0... |
Loki88/RSA-Test | ui/Menu/__init__.py | Python | agpl-3.0 | 72 | 0.013889 | #!/usr/bin/env python
# -*- coding: utf | -8 -*-
fro | m .Menu import MenuBox |
clchiou/garage | py/g1/operations/databases/servers/tests/test_connections.py | Python | mit | 8,015 | 0 | import unittest
import unittest.mock
import functools
from g1.asyncs import kernels
from g1.operations.databases.bases import interfaces
from g1.operations.databases.servers import connections
# I am not sure why pylint cannot lint contextlib.asynccontextmanager
# correctly; let us disable this check for now.
#
# py... | manager.writing(tx_id) as conn:
self.assert_manager(0, tx_id, (), (), ())
self.assertIs(conn, self.conn)
with self.assertRaises(interfaces.TransactionNotFoundError):
async with self.manager.writing(tx_id + 1):
pass
self.asse | rt_manager(0, 0, (), (tx_id, ), ())
self.conn.begin.assert_called_once()
@synchronous
async def test_transacting(self):
self.assert_manager(0, 0, (), (), ())
async with self.manager.transacting() as conn:
tx_id = self.manager.tx_id
self.assertNotEqual(tx_id, 0)
... |
xuru/pyvisdk | pyvisdk/do/storage_iorm_config_option.py | Python | mit | 1,080 | 0.009259 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def StorageIORMConfigOption(vim, *args, **kwargs):
''' | Configuration setting ranges for IORMConfigSpec object.'''
obj = vim.client.factory.create('ns0:StorageIORMConfigOption')
# do some validation checking...
if (len(args) + len(kwargs)) < 3:
raise IndexError('Expected at least 4 arguments got: %d' % len(args))
required = [ 'congestionThresh... | setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
|
ustuehler/git-cvs | tests/test_cvs.py | Python | isc | 727 | 0.001376 | from os.path import dirname, join
import unittest
from cvsgit.cvs import CVS
from cvsgit.changeset import Change
class Test(unittest.TestCase):
def test_rcsfilename(self):
"""Find the RCS file for a w | orking copy path.
"""
cvs = CVS(join(dirname(__file__), 'data', 'zombie'), None)
c = Change(timestamp='',
author='',
log='',
filestatus='',
filename='patches/patch-Makefile',
revision='',
... | c/patch-Makefile,v')
actual = cvs.rcsfilename(c)
self.assertEqual(expected, actual)
|
abetusk/www.meowcad.com | cgi/about.py | Python | agpl-3.0 | 1,664 | 0.020433 | #!/usr/bin/python
import re,cgi,cgitb,sys
import os
import urllib
import Cookie
import datetime
import meowaux as mew
cgitb.enable()
login_signup="""
<ul class='nav navbar-nav' style='float:right; margin-top:7px; margin-right:5px; ' >
<li>
<form action='/login' style='display:inline;' >
<button class='bt... | </form>
</li>
</ul>
"""
cookie = Cookie.SimpleCookie()
cookie_hash = mew.getCookieHash( os.environ )
msg,msgType = mew.processCookieMessage( cookie, cookie_hash )
loggedInFlag = False
if ( ("userId" in coo | kie_hash) and ("sessionId" in cookie_hash) and
(mew.authenticateSession( cookie_hash["userId"], cookie_hash["sessionId"] ) != 0) ):
loggedInFlag = True
template = mew.slurp_file("template/about.html")
nav = mew.slurp_file("template/navbarflush_template.html")
footer = mew.slurp_file("template/footer_template.... |
martinjrobins/hobo | pints/_nested/__init__.py | Python | bsd-3-clause | 29,201 | 0 | #
# Sub-module containing nested samplers
#
# This file is part of PINTS (https://github.com/pints-team/pints/) which is
# released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
import pints
import numpy as np
try:
from scipy.special import logsumexp... | rs.
Parameters
----------
log_prior : pints.LogPrior
A logprior to draw proposal samples from.
"""
def __init__(self, log_prior):
# Store logprior
if not isinstance(log_prior, pints.LogPrior):
raise Value | Error('Given log_prior must extend pints.LogPrior')
# prior accessed by subclasses to do prior sampling in ask() step
self._log_prior = log_prior
# Current value of the threshold log-likelihood value
self._running_log_likelihood = -float('inf')
self._proposed = None
# ... |
rossasa/server-tools | base_user_role/migrations/8.0.1.1.0/post-migration.py | Python | agpl-3.0 | 766 | 0 | # -*- coding: utf-8 -*-
# Copyright 2016 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/ | licenses/agpl).
from openerp import api, SUPERUSER_ID
def migrate_res_users_role(env):
"""Migrate user roles database schema.
('res_users_role_user_rel' many2many table to 'res.users.role.line' model.
" | ""
role_line_model = env['res.users.role.line']
query = "SELECT role_id, user_id FROM res_users_role_user_rel;"
env.cr.execute(query)
rows = env.cr.fetchall()
for row in rows:
vals = {
'role_id': row[0],
'user_id': row[1],
}
role_line_model.create(vals... |
mph-/lcapy | doc/examples/netlists/circuit-VRLC2-vr.py | Python | lgpl-2.1 | 442 | 0.004525 | from lca | py import Circuit
cct = Circuit("""
V 1 0 step 10; down
L 1 2 1e-3; right, size=1.2
C 2 3 1e-4; right, size=1.2
R 3 0_1 1; down
W 0 0_1; right
""")
import numpy as np
t = np.linspace(0, 0.01, 1000)
| vr = cct.R.v.evaluate(t)
from matplotlib.pyplot import subplots, savefig
fig, ax = subplots(1)
ax.plot(t, vr, linewidth=2)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Resistor voltage (V)')
ax.grid(True)
savefig('circuit-VRLC2-vr.png')
|
valdergallo/django-chrono | example/models.py | Python | gpl-3.0 | 963 | 0 | # -*- coding: utf-8 -*-
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
age = models.CharField(max_length=10)
def __unicode__(self):
return self.first_name
class PersonFile(models.Model):
... | return self.filefield
class Mercado(models.Model):
item = models.CharField(max_length=50)
qtde = models.IntegerField(default=0)
def __unicode__(self):
return self.item
class Invoice(models.Model):
name = models.CharField(max_length=50)
sales_date = models.DateField()
price = ... | voice)
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
|
bcare/roverpi | roverserver/enginectrl.py | Python | gpl-3.0 | 14,624 | 0.019147 |
from multiprocessing import Process, JoinableQueue, Manager, Lock, Value, Event
import wiringpi as wp
import RPi.GPIO as rpio
from slaveprocess import SlaveProcess
import time
rpio.setmode(rpio.BCM)
class PMWProcess(Process):
def __init__(self,**kwargs):
super(PWMProcess, self).__init__(**kwargs)
... | eq'):
self.pwm_freq = float(self.cfg.gpio.pwm_freq)
else:
self.pwm_freq = 50.0
###################### DEFAULT DRIVE VE | CTORS #######################
#################################
# COMMANDS
#################################
## Drive commands :
# North :
# _ _
# ^ | |_____| | ^ | |x| |
# | | | ^ | | | ... |
ponty/eagexp | eagexp/version.py | Python | bsd-2-clause | 775 | 0 | from easyprocess import EasyProcess
from entrypoint2 import entrypoint
from pyvirtualdisplay.display import Display
def extract_version(txt):
"""This function tries to extract the version from the help | text"""
words = txt.replace(",", " ").split()
version = None
for x in revers | ed(words):
if len(x) > 2:
if x[0].lower() == "v":
x = x[1:]
if "." in x and x[0].isdigit():
version = x
break
return version
def version():
"""
return eagle version.
It does not work without X!
:rtype: string
"""
... |
pythonprobr/oscon2014 | strategy/strategy_best2.py | Python | mit | 3,172 | 0.001261 | # strategy_best2.py
# Strategy pattern -- function-based implementation
# selecting best promotion from current module globals
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineI... | for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order):
"""10% discount for each LineItem with 20 or more units"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += i... | item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# BEGIN STRATEGY_BEST2
promos = [globals()[name] for name in globals() # <1>
if name.endswith('_promo') # <2>
and name != 'best_promo'] # <3>
def best_promo(order):
"... |
ZEROFAIL/goblin | tests/test_properties.py | Python | agpl-3.0 | 7,949 | 0 | """Test model properties."""
import pytest
from gremlin_python.statics import long
from goblin import element, exception, manager, properties
def test_set_change_property(person, lives_in):
# vertex
assert not person.name
person.name = 'leif'
assert person.name == 'leif'
person.name = 'leifur'
... | lue for v in place.important_numbers} == set([1, 2, 3])
place.important_numbers = (1, 2, 3, 4)
assert isinstance(place.important_numbers, set)
assert {v.value for v in place.important_numbers} == set([1, 2, 3, 4])
place.important_numbers = set([1, 2, 3])
assert isinstance(place.important_numbers, se... | pytest.raises(exception.ValidationError):
place.important_numbers.add('dude')
def test_set_card_union(place):
place.important_numbers = set([1, 2, 3])
place.important_numbers = place.important_numbers.union({3, 4, 5})
def test_set_card_64bit_integer(place):
place.important_numbers = set([long(1)... |
eriknw/eqpy | setup.py | Python | bsd-3-clause | 1,281 | 0 | #!/usr/bin/env python
from os.path import exists
from setuptools import setup
import eqpy
setup(
name='eqpy',
version=eqpy.__version__,
descript | ion='Solve systems of equations and assumptions, linear and '
'non-linear, numerically and symbolically.',
url='h | ttp://github.com/eriknw/eqpy/',
author='https://raw.github.com/eriknw/eqpy/master/AUTHORS.md',
maintainer='Erik Welch',
maintainer_email='[email protected]',
license='BSD',
keywords='math CAS equations symbolic sympy',
packages=[
'eqpy',
],
classifiers=[
'License :: ... |
ZelphirKaltstahl/rst-internal-links-to-raw-latex | RSTInternalLinks/HeadingsParser.py | Python | gpl-3.0 | 13,092 | 0.004987 | import re
class HeadingsParser():
"""
The HeadingParser parses the document for headings.
NOT YET: converts headings to raw latex headings in the correct way, so that they can be referrenced to later
see https://www.sharelatex.com/learn/Sections_and_chapters for info about the levels"""
def __ini... | elf.subtitle_start_marker_regex = re.compile(r'[-]{3,}')
self.subtitle_end_marker_regex = re.compile(r'[-]{3,}')
self.subtitle_content_regex = re.compile(
r'''
^ # beginning of line
[ ] | # one whitespace
[A-Za-z0-9äöüÄÖÜ]+ # alphanumerical string, no whitespace
(?P<subtitle>[A-Za-z0-9äöüÄÖÜ ]+) # alphanumerical string, whitespace ok
[A-Za-z0-9äöüÄÖÜ]+ # alphanumerical string, no whitespace
[ ]... |
yuyuyu101/VirtualBox-NetBSD | src/libs/xpcom18a4/python/tools/tracer_demo.py | Python | gpl-2.0 | 4,360 | 0.003899 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | ult(attr,0) + 1
setattr(self._ob, attr, val)
# Installed as a global XPCOM function that if exists, will be called
# to wrap each XPCOM object created.
def MakeTracer(ob):
| # In some cases we may be asked to wrap ourself, so handle that.
if isinstance(ob, Tracer):
return ob
return Tracer(ob)
def test():
import xpcom.server, xpcom.components
xpcom.server.tracer = MakeTracer
contractid = "Python.TestComponent"
for i in range(100):
c = xpcom.componen... |
googleapis/python-resource-manager | google/cloud/resourcemanager_v3/services/projects/async_client.py | Python | apache-2.0 | 70,063 | 0.001313 | # -*- 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... | nfo: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to... |
"""
return ProjectsClient.from_service_account_info.__func__(ProjectsAsyncClient, info, *args, **kwargs) # type: ignore
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
fil... |
adrianschroeter/kiwi | test/unit/privileges_test.py | Python | gpl-3.0 | 568 | 0 | from mock import patch
from .test_helper | import raises
from kiwi.exceptions import KiwiPrivilegesError
from kiwi.privileges import Privileges
class TestPrivileges(object):
@raises(KiwiPrivilegesError)
@patch('os.geteuid')
def test_check_for_root_permiossion_false(self, mock_euid):
mock_euid.return_value = 1
Privileges.check_for_... | mock_euid):
mock_euid.return_value = 0
assert Privileges.check_for_root_permissions() is True
|
IQSS/gentb-site | apps/predict/migrations/0003_auto_20160525_1521.py | Python | agpl-3.0 | 853 | 0.002345 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('predict', '0002_auto_20160524_0947'), |
]
operations = [
migrations.RemoveField(
model_name='predictdataset',
name='dropbox_url',
),
migrations.AlterField(
model_name='predictdataset',
name='file_type',
field=models.CharField(max_length=25, choices=[(b'vcf', b'Varia... | all Format (VCF)'), (b'fastq', b'FastQ Nucleotide Sequence'), (b'manual', b'Mutations Manual Entry')]),
),
migrations.AlterField(
model_name='predictdataset',
name='title',
field=models.CharField(max_length=255, verbose_name=b'Dataset Title'),
),
]
|
nielsbuwen/ilastik | ilastik/applets/autocontextClassification/opBatchIoSelective.py | Python | gpl-3.0 | 11,464 | 0.012648 | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <[email protected]>
#
# This program is free software; you can redistribute it and/or
# mod... | ged, so we have work to do when we get executed.
self.Dirty.setValue(True)
def execute(self, slot, subindex, roi, result):
if slot == self.Dirty:
assert False # Shouldn't get to this line because the dirty output is given a value directly
if slot == sel | f.OutputDataPath:
assert False # This slot is already set via setupOutputs
if slot == self.ExportResult:
# We can stop now if the output isn't dirty
if not self.Dirty.value:
result[0] = True
return
exportFormat = self.... |
ties/py-sonic | libsonic/errors.py | Python | gpl-3.0 | 1,413 | 0.012739 | """
This file is part of py-sonic.
py-sonic 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.
py-sonic is distributed in the hope that it wil... | ror(SonicError):
pass
# This maps the error code numbers from the Subsonic server to their
# appropriate Exceptions
ERR_CODE_MAP = {
0: SonicError ,
10: ParameterError ,
20: VersionError ,
30: VersionError ,
40: CredentialError ,
50: AuthError ,
60: LicenseError ,
70: DataNotFoundEr... | E_MAP[code]
return SonicError
|
dorvaljulien/StarFiddle | anim_plot.py | Python | mit | 1,736 | 0.009793 | import time
import nu | mpy as np
import cPickle as pk
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.widgets import Button
class PlotAnimation:
"""
Takes a list of PySnap and launch an interactive animation.
| """
def __init__(self, Anim, DataControl, **kwargs):
self.data = DataControl
self.previous_n = 0
self.Anim= Anim
def timer_update(self):
if self.Anim.n != self.previous_n:
self.data.Update(self.Anim.n)
self.previous_n = self.Anim.n
def launch(self):
... |
hofmannedv/training-python | text-analysis/character-statistics.py | Python | gpl-2.0 | 2,207 | 0.017218 | # -----------------------------------------------------------
# reads the text from the given file, and outputs its
# character statistics
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email [email protected]
# -----------------------------------------------------------
... | ileName, "r", | encoding=encoding)
# read content
data = fileHandle.read()
# close file
fileHandle.close()
# calculate the character statisitics
statistics = charStat(data)
# retrieve the single items
items = statistics.items()
# print ("sorting by character ...")
# sort the items
sortedItems = sorted(items)
lines = []
# outpu... |
mmechelke/bayesian_xfel | bxfel/core/structure_factor.py | Python | mit | 18,608 | 0.010963 |
import numpy as np
import scipy
import re
import os
import hashlib
import csb
from csb.bio.io.wwpdb import StructureParser
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i+n]
class ScatteringFactor(object):
"""
Cacluates the ... | e in self._elements:
a,b,c = self._atom_type_params[atom_type]
indices = np.where(seq==a | tom_type)[0]
fx = c + np.dot(np.exp(np.outer(-s_tols,b)),a)
f[indices,:] = fx[:]
return f
def _calculate_debyewaller_factors(self, hkl):
"""
"""
b = np.array(self._bfactor)
s_tols = 0.25 * (hkl**2).sum(-1)
t = np.exp(np.outer(-b,s_tols))
... |
cloudControl/pycclib | pycclib/cclib.py | Python | apache-2.0 | 33,766 | 0.000829 | # -*- coding: utf-8 -*-
"""
pycclib
library for accessing the cloudControl API using Python
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
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
ht... | e use get_token to get the token.
"""
return self._token
def create_app(self, app_name, type, repository_type, buildpack_url=None):
"""
Create a new application and return it.
"""
self.re | quires_token()
resource = '/app/'
data = {'name': app_name,
'type': type,
'repository_type': repository_type}
if buildpack_url:
data['buildpack_url'] = buildpack_url
content = self.request.post(resource, data)
return json.loads(con... |
alevnyaa/restfulstorch | rstorch/migrations/0002_auto_20170302_1722.py | Python | gpl-3.0 | 602 | 0 | # -* | - coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-02 14:22
from __future__ i | mport unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rstorch', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='category',
name='is_active',
field=models.BooleanFie... |
ibc/MediaSoup | worker/deps/gyp/test/configurations/target_platform/gyptest-target_platform.py | Python | isc | 1,114 | 0.002693 | #!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Tests the msvs specific msvs_target_platform option. |
"""
import TestGyp
import TestCommon
def RunX64(exe, stdout):
try:
test.run_built_executable(exe, stdout=stdout)
except WindowsError as e:
# Assume the exe is 64-bit if it can't load on 32-bit systems.
# Both versions of the error are required because different versions
# of python seem to retur... | errors for invalid exe type.
if e.errno != 193 and '[Error 193]' not in str(e):
raise
test = TestGyp.TestGyp(formats=['msvs'])
test.run_gyp('configurations.gyp')
test.set_configuration('Debug|x64')
test.build('configurations.gyp', rebuild=True)
RunX64('front_left', stdout=('left\n'))
RunX64('front_right',... |
googleads/google-ads-python | google/ads/googleads/v9/services/types/customer_service.py | Python | apache-2.0 | 7,422 | 0.000404 | # -*- coding: utf-8 -*-
# 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... | e_content_type (google.ads.googleads.v9.enums.types.ResponseContentTypeEnum.ResponseContentType):
The response cont | ent type setting. Determines
whether the mutable resource or just the
resource name should be returned post mutation.
"""
customer_id = proto.Field(proto.STRING, number=1,)
operation = proto.Field(
proto.MESSAGE, number=4, message="CustomerOperation",
)
validate_only... |
pavels/pootle | pootle/apps/pootle_app/project_tree.py | Python | gpl-3.0 | 16,304 | 0.000184 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import errno
import logging
import os
import... | path(relative_dir)
files, dirs = split_files_and_dirs(ignored_files, ext, podir_path,
file_filter)
file_set = set(files)
dir_set = set(dirs)
existing_stores = dict((store.name, store) for store in
db_dir.child_stores.live().exclude(file=... | .iterator())
existing_dirs = dict((dir.name, dir) for dir in
db_dir.child_dirs.live().iterator())
files, new_files = add_items(
file_set,
existing_stores,
lambda name: create_or_resurrect_store(
fil... |
mdkennedy3/Scarab_DCT_Control | catkin_ws/build/Scarabs/scarab/scarab_quad/catkin_generated/pkg.installspace.context.pc.py | Python | gpl-2.0 | 422 | 0.00237 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
P | ROJECT_CATKIN_DEPENDS = "roscpp;rospy;std_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lscarab_quad".split(';') if "-lscarab_quad" != "" else []
PROJECT_N | AME = "scarab_quad"
PROJECT_SPACE_DIR = "/home/monroe/catkin_ws/install"
PROJECT_VERSION = "0.0.0"
|
dominikkowalski/django-powerdns-dnssec | dnsaas/api/urls.py | Python | bsd-2-clause | 246 | 0 | from django.conf.urls import include, url
from powerdns.utils import patterns
urlpatterns = patterns(
'',
url(r'', include('dnsaas.api.v1.urls', nam | espace='default')) | ,
url(r'^v2/', include('dnsaas.api.v2.urls', namespace='v2')),
)
|
jiasir/playback | playback/cli/nova_compute.py | Python | mit | 4,590 | 0.003922 | import sys
import logging
from playback.api import NovaCompute
from cliff.command import Command
def make_target(args):
try:
target = NovaCompute(user=args.user, hosts=args.hosts.split(','), key_filename=args.key_filename,
password=args.password)
except AttributeError:
... | -rabbit-hosts',
help='rabbit hosts e.g. CONTROLLER1,CONTROLLER2',
acti | on='store', default=None, dest='rabbit_hosts')
parser.add_argument('--rabbit-user',
help='the user for rabbit, default openstack',
action='store', default='openstack', dest='rabbit_user')
parser.add_argument('--rabbit-pass',
... |
fretsonfire/fof-python | src/GameEngine.py | Python | mit | 14,664 | 0.018344 | #####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä ... | 44100, 48000])
Config.define("aud | io", "bits", int, 16, text = _("Sample Bits"), options = [16, 8])
Config.define("audio", "stereo", bool, True)
Config.define("audio", "buffersize", int, 2048, text = _("Buffer Size"), options = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536])
Config.define("audio", "delay", i... |
saintdragon2/python-3-lecture-2015 | homework_checker/civil_hw_personal_list/hw_civil_list_15030011.py | Python | mit | 441 | 0.026005 | def square_of_list(some_list, n | um):
if len(some_list) < num:
result = 0
if len(some_list) >= num:
result = some_list[num]**num
return result
def gap(some_list):
if any([type(x) == type('a') for x in some_list]):
print('문자열이 있습니다')
filtered_list = [ x for x in some_list if type(x) == type(1) or type(x... | - min(filtered_list)
|
batxes/4Cin | SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/SHH_WT_models11702.py | Python | gpl-3.0 | 17,574 | 0.025094 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | arker_set('particle_0 geometry')
marker_sets["particle_0 geometry"]=s
s= marker_sets["particle_0 geome | try"]
mark=s.place_marker((11373, 1728.13, 2526.72), (0.7, 0.7, 0.7), 890.203)
if "particle_1 geometry" not in marker_sets:
s=new_marker_set('particle_1 geometry')
marker_sets["particle_1 geometry"]=s
s= marker_sets["particle_1 geometry"]
mark=s.place_marker((10259.4, 2429.11, 3723.81), (0.7, 0.7, 0.7), 792.956)
if... |
martinribelotta/micropython | tests/float/float_divmod_relaxed.py | Python | mit | 705 | 0.001418 | # test floating point floor divide and modulus
# it has some tricky corner cases
# pyboard has 32-bit floating point and gives different (but still
# correct) answers for c | ertain combinations of divmod arguments.
def test(x, y):
div, mod = divmod(x, y)
print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-6)
test(1.23456, 0.7)
test(-1.23456, 0.7)
test(1.23456, -0.7)
test(-1.23456, -0.7)
a = 1.23456
b = 0.7
test(a, b)
test(a, -b)
test(-a, b)
test(-a, -b)
for i in rang... | o error
try:
divmod(1.0, 0)
except ZeroDivisionError:
print('ZeroDivisionError')
|
Rav3nPL/p2pool-rav | p2pool/networks/joulecoin.py | Python | gpl-3.0 | 568 | 0.012324 | from p2pool.bitcoin import networks
PARENT = networks.nets['joulecoin']
SHARE_PERIOD = 20 # seconds
CHAIN_LENGTH = 12* | 60*60//10 # shares
REAL_CHAIN_LENGTH = 12*60*60//10 # shares
TARGET_LOOKBEHIND = 20 # shares
SPREAD = 10 # blocks
IDENTIFIER = 'ac556af4e900ca61'.decode('hex')
PREFIX = '16ac009e4fa655ac'.decode('hex')
P2P_PO | RT = 7844
MIN_TARGET = 0
MAX_TARGET = 2**256//2**32 - 1
PERSIST = False
WORKER_PORT = 9844
BOOTSTRAP_ADDRS = 'rav3n.dtdns.net pool.hostv.pl p2pool.org solidpool.org'.split(' ')
ANNOUNCE_CHANNEL = '#p2pool-alt'
VERSION_CHECK = lambda v: True
|
mjkmoynihan/ReleaseRadar | setup.py | Python | apache-2.0 | 15 | 0.066667 | # TO | DO: | Setup
|
ehartsuyker/securedrop | securedrop/journalist_app/api.py | Python | agpl-3.0 | 13,022 | 0.000077 | import json
from datetime import datetime, timedelta
from flask import abort, Blueprint, current_app, jsonify, request
from functools import wraps
from sqlalchemy.exc import IntegrityError
from os import path
from uuid import UUID
from werkzeug.exceptions import default_exceptions # type: ignore
from db import db
fr... | or_404(model, object_id, column=''):
if column:
result = model.query.filter(column == object_id).one_or_none()
else:
result = model.query.get(object_id)
if result is None:
abort(404)
return result
def make_blueprint(config):
api = Blu | eprint('api', __name__)
@api.route('/')
def get_endpoints():
endpoints = {'sources_url': '/api/v1/sources',
'current_user_url': '/api/v1/user',
'submissions_url': '/api/v1/submissions',
'replies_url': '/api/v1/replies',
... |
lukaszo/rpitips-examples | RPi.GPIO/servo.py | Python | apache-2.0 | 288 | 0.010417 | import time
import RPi.GPIO as GPIO
# use B | roadcom pin numbers
GPIO.setmode(GPIO.BCM)
SERVO_PIN = 3
GPIO.setup(SERVO_PIN, GPIO.OUT)
# setup PWM
pwm = GPIO.PWM | (SERVO_PIN, 100)
pwm.start(5)
for i in range(5, 25):
pwm.ChangeDutyCycle(i)
time.sleep(0.5)
pwm.stop()
GPIO.cleanup()
|
skearnes/color-features | oe_utils/shape/tests/test_color.py | Python | bsd-3-clause | 1,693 | 0 | """
Tests for OEShape color utilities.
"""
import numpy as np
import unittest
from openeye.oechem import *
from openeye.oeshape import *
from ..color import ColorForceField
class TestColorForceField(unittest.TestCase):
"""
Tests for ColorForceField.
"""
def setUp(self):
"""
Set up te... | or a_interaction, b_interaction in zip(
color_ff.get_interactions(), self.color_ff.get_interactions()):
assert np.array_equal(a_interaction, b_interaction)
def test_isolate_interactions(self):
"""
Test ColorForceField.isolate_interactions.
"""
interaction... | assert len(color_ff.get_interactions()) == 1
for interaction in color_ff.get_interactions():
interactions.add(interaction)
assert interactions == set(self.color_ff.get_interactions())
|
osu-cass/working-waterfronts-api | working_waterfronts/working_waterfronts_api/tests/views/entry/test_edit_video.py | Python | apache-2.0 | 2,965 | 0 | from django.test import TestCase
from django.core.urlresolvers import reverse
from working_waterfronts.working_waterfronts_api.models import Video
from django.contrib.auth.models import User
class EditVideoTestCase(TestCase):
"""
Test that the Edit Video page works as expected.
Things tested:
UR... | ideo_update(self):
"""
POST a proper "update video" command to the server, and see if
the update appears in the database
"""
# Data that we'll post to the server to get the new video created
new_video = {
'caption': "A thrilling display of utmost might",
... | ://www.youtube.com/watch?v=dQw4w9WgXcQ'}
self.client.post(
reverse('edit-video', kwargs={'id': '1'}),
new_video)
video = Video.objects.get(id=1)
for field in new_video:
self.assertEqual(
getattr(video, field), new_video[field])
def test_... |
Tanych/CodeTracking | distance.py | Python | mit | 1,572 | 0.027354 | class WallsGate(object):
def dfs(self, rooms):
queue = [(i, j, 0) for i, rows in enumerate(rooms) for j, v in enumerate(rows) if not v]
while queue:
i, j, step = queue.pop()
if rooms[i][j] > step:
rooms[i][j] = step
for newi, newj in ((i + 1, j), ... | queue.append(i*col+j)
while queue:
x=queue.pop(0)
i,j=x/col,x%col
for newi,newj in (i+1,j),(i-1,j),(i,j+1),(i,j-1):
if 0 <= newi < len(rooms) and 0 <= newj < len(rooms[0]) and rooms[newi][newj]==INF:
| rooms[newi][newj]=rooms[i][j]+1
queue.append(newi*col+newj)
def naivedfs(self, rooms):
for i in xrange(len(rooms)):
for j in xrange(len(rooms[0])):
if rooms[i][j]==0:
self._dfsrev(rooms,i,j)
def _dfsrev(self,rooms,i,j):
for ... |
GoogleCloudPlatform/professional-services | examples/kubeflow-pipelines-sentiment-analysis/pipeline/build_sentiment_analysis.py | Python | apache-2.0 | 3,173 | 0.003467 | # Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | --gcpTempLocation={} \
--inputPath={} \
--outputPath={} \ |
--windowDuration={} \
--windowPeriod={}'.format(
str(project),
str(gcp_temp_location),
str(input_path),
str(output_path),
str(window),
str(period)),
]
)
@kfp.dsl.pipeline(
name='Sentiment analysis'... |
timj/scons | bin/linecount.py | Python | mit | 4,164 | 0.010327 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Count statistics about SCons test and source files. This must be run
# against a fully-populated tree (for example, one that's been freshly
# checked out).
#
# A test file is anything under the src/ directory that begins with
# 'test_' or ends in 'Tests.py', or anything unde... | numbe | r of lines
# in each category, the number of non-blank lines, and the number of
# non-comment lines. The last figure (non-comment) lines is the most
# interesting one for most purposes.
from __future__ import division, print_function
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
fmt =... |
all-umass/metric-learn | metric_learn/base_metric.py | Python | mit | 15,825 | 0.002528 | from numpy.linalg import cholesky
from scipy.spatial.distance import euclidean
from sklearn.base import BaseEstimator
from sklearn.utils.validation import _is_arraylike
from sklearn.metrics import roc_auc_score
import numpy as np
from abc import ABCMeta, abstractmethod
import six
from ._util import ArrayIndexer, check_... | dified if the metric
learner is.
| :ref:`mahalanobis_distances` : The section of the project documentation
that describes Mahalanobis Distances.
"""
pairs = check_input(pairs, type_of_inputs='tuples',
preprocessor=self.preprocessor_,
estimator=self, tuple_size=2)
pairwise_diffs = self.t... |
radio-astro-tools/spectral-cube | spectral_cube/tests/test_dask.py | Python | bsd-3-clause | 10,242 | 0.002831 | # Tests specific to the dask class
import os
from numpy.core.shape_base import block
import pytest
import numpy as np
from mock import patch
from numpy.testing import assert_allclose
from astropy.tests.helper import assert_quantity_allclose
from astropy import units as u
from astropy.utils import data
try:
from ... | '''
Testing returning a non-SpectralCube object with a user-defined
function for spectral operations.
'''
chunk_size = (-1, 1, 2)
cube = DaskSpectralCube.read(data_adv).rechunk(chunks=chunk_size)
def sum_blocks_spectral(data_chunk):
return data_chunk.sum(0)
# Tel | l dask.map_blocks that we expect the zeroth axis to be (1,)
output_chunk_size = (1, 2)
test = cube.apply_function_parallel_spectral(sum_blocks_spectral,
return_new_cube=False,
accepts_chunks=True,
... |
sargas/scipy | scipy/linalg/benchmarks/bench_basic.py | Python | bsd-3-clause | 4,065 | 0.013284 | from __future__ import division, print_function, absolute_import
import sys
from numpy.testing import *
import numpy.linalg as linalg
def random(size):
return rand(*size)
class TestSolve(TestCase):
def bench_random(self):
basic_solve = linalg.solve
print()
print(' Solving system... | basic | scipy | basic')
for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]:
| repeat *= 2
print('%5s' % size, end=' ')
sys.stdout.flush()
a = random([size,size])
# large diagonal ensures non-singularity:
for i in range(size): a[i,i] = 10*(.1+a[i,i])
print('| %6.2f ' % measure('inv(a)',repeat), end=' ')
sys.... |
wfxiang08/django178 | django/__init__.py | Python | bsd-3-clause | 876 | 0.003425 | # -*- coding:utf-8 -*-
VERSION = (1, 7, 8, 'final', 0)
def get_version(*args, **kwargs):
# Don't litter django/__init__.py with all the g | et_version stuff.
# Only import if it's actually called.
from django.utils.version import get_version
return get_version(*args, **kwargs)
def setup():
"""
Configure the settings (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
... |
apps.populate(settings.INSTALLED_APPS)
_gevent = None
def using_gevent():
global _gevent
if _gevent is None:
from django.conf import settings
_gevent = settings.USING_GEVENT
return _gevent |
magnunor/camera_aperture_position | camera_position_tools.py | Python | gpl-3.0 | 4,017 | 0.005726 | from matplotlib.path import Path
import matplotlib.patches as patches
from math import cos, sin, radians
class RectangleObject:
def __init__(self, centerPosition, sideSize1, sideSize2, label, rotation=0.0, color='black'):
self.sideSize1 = sideSize1
self.sideSize2 = sideSize2
self.label = la... | 0 = x0 + x_center_pos
self.y0 = y0 + y_center_pos
self.x1 = x1 + x_center_pos
self.y1 = y1 + y_center_pos
self.x2 = x2 + x_center_pos
| self.y2 = y2 + y_center_pos
self.x3 = x3 + x_center_pos
self.y3 = y3 + y_center_pos
class CircleObject:
def __init__(self, centerPosition, radius, label, color='black'):
self.centerPosition = centerPosition
self.radius = radius
self.label = label
self.color = ... |
psychopy/versions | psychopy/iohub/devices/keyboard/darwinkey.py | Python | gpl-3.0 | 1,860 | 0 | # -*- coding: utf-8 -*-
# Part of the psychopy.iohub library.
# Copyright (C) 2012-2016 iSolver Software Solutions
# Distributed under the terms of the GNU General Public License (GPL).
# /System/Library/Frameworks/Carbon.framework/Versions/A/Fra | meworks/
# HIToolbox.framework/Headers/Events.h
QZ_ESCAPE = 0x35
QZ_F1 = 0x7A
QZ_F2 = 0x78
QZ_F3 = 0x63
QZ_F4 = 0x76
QZ_F5 = 0x60
QZ_F6 = 0x61
QZ_F7 = 0x62
QZ_F8 = 0x64
QZ_F9 | = 0x65
QZ_F10 = 0x6D
QZ_F11 = 0x67
QZ_F12 = 0x6F
QZ_F13 = 0x69
QZ_F14 = 0x6B
QZ_F15 = 0x71
QZ_F16 = 0x6A
QZ_F17 = 0x40
QZ_F18 = 0x4F
QZ_F19 = 0x50
QZ_F20 = 0x5A
QZ_BACKQUOTE = 0x32
QZ_MINUS = 0x1B
QZ_EQUALS = 0x18
QZ_BACKSPACE = 0x33
QZ_INSERT = 0x72
QZ_HOME = 0x73
QZ_PAGEUP = 0x74
QZ_NUMLOCK = 0x47
QZ_KP_EQUALS = 0x5... |
vit1-irk/ii-db-utils | sqlite-export.py | Python | cc0-1.0 | 1,050 | 0.013333 | #!/us | r/bi | n/env python3
# forked from spline1986's versions
import os, sys, sqlite3
from ii_functions import *
args=sys.argv[1:]
if len(args)==0:
print("Usage: sqlite-export.py <db_file>")
sys.exit(1)
check_dirs()
conn = sqlite3.connect(args[0])
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS msg(
id INTEGER PR... |
scottsappen/PayMySitter | main.py | Python | apache-2.0 | 10,136 | 0.016772 | import os
import sys
import logging
import uuid
import traceback
import datetime
import cgi
import MySQLdb
import stripe
import re
import requests
import urllib
import time
import pmsconstants
from flask import Flask, render_template, request, jsonify, redirect, url_for, Markup, session, Response
from werkzeug import ... | ::')
raise Exception
#This customer update call will update the customer subscription
try:
#Save the plan on the cust | omer record at Stripe
#planType could be any plan you set up at Stripe, like a yearly or monthly plans perhaps
subscription = stripeCustomer.subscriptions.create(plan=planType)
#Save the plan type for the user in NoSQL
stripeprofile.stripe_subscription_plan = planType
stripeprofi... |
lisogallo/bitcharts-core-legacy | bitcharts.py | Python | agpl-3.0 | 24,568 | 0.00057 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Bitcharts - ORM classes and functions
Copyright(c) 2014 - Lisandro Gallo (lisogallo)
[email protected]
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 Found... | ion.args[0]
)
res = {}
return res
def is_dict(something):
"""
Check if input object is a dictionary or contains a dictionary.
Return the d | ictionary found.
:param something: Input object to check.
"""
if type(something) is dict:
for values in something.itervalues():
if type(values) is dict:
return is_dict(values)
return something
def parse_values(dictionary):
"""
Search for common keys ... |
opentrials/collectors | collectors/fdadl/collector.py | Python | mit | 2,443 | 0.000409 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import ijson
import shutil
import logging
import zipfile
import tempfile
import requests
from .. import base
from .record import Record
... | c' not in meta:
continue
# Get data
data = {
'product_ndc': meta['product_ndc'][0],
'product_type': meta['product_type'][0],
'generic_name': meta['generic_name'][0],
'brand_name': meta['brand_name'][0],
... | data['fda_application_number'] = meta['application_number'][0]
# Create record
record = Record.create(url, data)
# Write record
record.write(conf, conn)
# Log info
success += 1
if not success % 100:
logge... |
3dfxsoftware/cbss-addons | duplicated_tasks/wizard/__init__.py | Python | gpl-2.0 | 30 | 0 | import s | earch_duplicat | ed_task
|
sdwebster/learn-python-the-hard-way-solutions | 08/ex8.py | Python | mit | 352 | 0.011364 | # -*- coding: utf-8 -*-
forma | tter = "%r %r %r %r"
print formatter % (1,2,3,4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"Whose woods these are",
"I think I know",
"His house is in",
"Th | e village though"
)
|
bleedingwolf/Spyglass | spyglass/__init__.py | Python | bsd-3-clause | 68 | 0.014706 |
import backend # hopefully fixes issues with Cel | ery finding | tasks?
|
pkesist/buildpal | Python/server_svc_handler.py | Python | gpl-3.0 | 1,123 | 0.002671 | import threading
from multiprocessing import cpu_count
class Terminator:
def __init__(self):
self._should_stop = False
def stop(self):
self._should_s | top = True
def should_stop(self):
return self._should_stop
class Handler(object):
# no parameters are permitted; all configuration should be placed in the
# configuration file and handled in the Initialize() method
def __init__(self):
pass
# called when the service is... |
def Initialize(self, configFileName):
self.terminator = Terminator()
# called when the service is starting immediately after Initialize()
# use this to perform the work of the service; don't forget to set or check
# for the stop event or the service GUI will not respond to requests to
... |
fucxy/fucxy-node | gateway/modules.py | Python | gpl-3.0 | 1,672 | 0.031699 | #!/usr/bin/env python
import socket,sys,gateway_cfg,select,socketserver,http.server,urllib
from threading import *
class WebHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parseParams = urllib.parse.urlparse(self.path)
if parseParams.path=="/t" :
self.send_error(404,"You can't pass!!")
... | ig")
self.server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.server.bind((gateway_cfg.address['host'],gateway_cfg.address['port']))
self.server.listen(gateway_cfg.max_user) |
self.break_out = False
except socket.error as msg:
print("[ERROR] %s\n" % msg)
self.break_out = True
def run(self):
#start
if self.break_out == False:
print("msgcenter start!!")
while True:
try:
connection,address = self.server.accept()
connectio... |
dlutxx/cement | main.py | Python | mit | 3,137 | 0.048659 | #!python
#-*- encoding=utf-8 -*-
import sys, sqlite3, logging, os, os.path
import wx, time, re, copy, webbrowser
import wx.grid, wx.html
import json, math
from cfg import config
from util import *
from model import *
from view import *
class App(wx.App):
instance = None
def __init__(self, conf, *args):
wx.App._... | ) )
file = open(filepath, 'wb')
file.write( self.getSheetHtml(sheet).encode('utf-8') )
file.close()
webbrowser.open(filepath)
# if '__main__'==__name__:
app = App(config, False) # True, os.path.join(ctx.dir, 'run.dat') )
| App.instance = app
config.app = app
app.Run()
app.MainLoop()
|
plguhur/random-sets | simuFindNMin.py | Python | apache-2.0 | 1,243 | 0.015286 | # lance simulations pour different nombre d'electeurs
import multiprocessing
import os, sys
import shutil
import time
import numpy as np
from randomSets import *
def worker(((Ncandidats,q, Nwinners, Ntests))):
"""worker function"""
sys.stdout.write('\nSTART -- %i candidats -- \n' % Ncandidats)
sys.stdout.... | n__':
| print "Cette fois, c'est la bonne !"
print (time.strftime("%H:%M:%S"))
root = "simulations/"
try:
os.mkdir(root)
except OSError:
pass
candidates = range(10,110, 2)
Nwinners = 1
minNvoters = np.zeros((len(candidates), Nwinners))
args = []
for i in range(len(candid... |
mrricearoni/iTunesSearch | printRecentAlbums.py | Python | mit | 357 | 0.002801 | import json
from pprint import pprint
from sys import argv
jsonFile = argv[1]
with open(jsonFile) as data | _file:
data = json.load(data_file)
for i in range(0, data['resultCount']):
if data['results'][i]['trackCount'] != 1:
print(data['results'][i]['collectionName']), data['results'][i]['releaseDate']
# sort by release da | te
pprint(data)
|
ioram7/keystone-federado-pgid2013 | build/greenlet/run-tests.py | Python | apache-2.0 | 1,321 | 0.003785 | #! /usr/bin/env python
import sys, os, getopt, struct, unittest
from distutils.spawn import spawn
build = True
verbosity = 2
here = os.path.dirname(os.path.abspath(__file__))
os.chdir(here)
def bits():
"""determine if running on a 32 bit or 64 bit platform
"""
return struct.calcsize("P") * 8
# -- parse... | pawn(cmd, search_path=0)
# -- find greenlet but skip the one in "."
if not build:
oldpath = sys.path[:]
sys.path.remove(here)
import greenlet
if not build:
sys.path[:] = oldpath
sys.stdout.write("python %s (%s bit) using greenlet %s from %s\n" %
(sys.version.split()[0], bits(), greenle... | test_collector
suite = test_collector()
unittest.TextTestRunner(verbosity=verbosity).run(suite)
|
tensorflow/tensorboard | tensorboard/plugins/mesh/summary_v2_test.py | Python | apache-2.0 | 5,916 | 0.000676 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | cted_bitmask = metadata.get_components_bitmask(
[
plugin_data_pb2.MeshPluginData.VERTEX,
plugin_data_pb2.MeshPluginData.FACE,
plugin_data_pb2.MeshPluginData.COLOR,
]
)
for event in events:
self.assertEqual(
... | ted_bitmask, self.get_metadata(event).components
)
def test_pb(self):
"""Tests ProtoBuf interface."""
name = "my_mesh"
tensor_data = test_utils.get_random_mesh(
100, add_faces=True, add_colors=True
)
config_dict = {"foo": 1}
proto = summary.me... |
jackTheRipper/iotrussia | web_server/lib/werkzeug-master/examples/i18nurls/__init__.py | Python | gpl-2.0 | 57 | 0 | from i18nurls.application imp | ort Applicat | ion as make_app
|
effluxsystems/pyefflux | tests/unit/test_base.py | Python | mit | 1,403 | 0 | """
Tests for efflux.telemetry.endpoint
"""
import unittest
import mock
from efflux.telemetry.endpoint import Telemetry
class Dummy(Telemetry):
def _set_route(self):
self.base_route = None
class TelemetryTests(unittest.TestCase):
'''Tests for EffluxEndpoint'''
MOCKS = [
]
def setUp(... | required_fields(l1, l2)
)
# equal OK
self.assertTrue(
self.efflux.check_required_fields(l1, l1)
)
# not subset
self.assertFalse(
self.efflux.check_required_fields(l3, l2)
)
def test_set_namespace(self):
orig = {
'... | }
check = {
'ns_foo': 'bar',
'ns_baz': 'ball'
}
self.assertEqual(
check,
self.efflux.set_namespace('ns', orig)
)
|
sdispater/pendulum | tests/test_main.py | Python | mit | 268 | 0 | import pytz
from pendulum import _ | safe_timezone
from pendulum.tz.timezone import Timezone
def test_safe_timezone_with_tzinfo_objects():
tz = _safe_timezone(pytz.timezone("Europe/Paris"))
assert isinstance(tz, Timezone)
assert | "Europe/Paris" == tz.name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.