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 |
|---|---|---|---|---|---|---|---|---|
beernarrd/gramps | gramps/gen/lib/eventref.py | Python | gpl-2.0 | 7,345 | 0.000953 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2010 Michiel D. Nauta
# Copyright (C) 2011 Tim G L Lyons
# Copyright (C) 2013 Doug Blank <doug.blank@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# ... | ions.
:returns: Returns the list of child secondary child objects that may
refer citations.
:rtype: list
"""
return self.attribute_list
def get_note_child_list(self):
"""
Return the list of child secondary objects that may refer notes.
:re... | refer notes.
:rtype: list
"""
return self.attribute_list
def get_referenced_handles(self):
"""
Return the list of (classname, handle) tuples for all directly
referenced primary objects.
:returns: Returns the list of (classname, handle) tuples for referenced
... |
sgibbes/zonal_stats_app | utilities/prep_shapefile.py | Python | apache-2.0 | 3,132 | 0.005109 | import os
import numpy as np
import math
import arcpy
def intersect_file(intersect_file, intersect_col=None):
intersect_aoi_basename = os.path.basename(intersect_file)
intersect_calc = {'adm2': """!FC_NAME! +"_"+!ISO!+ str(!ID_1!)+'d'+ str(!ID_2!)""",
'adm1': """!FC_NAME! +"_"+!ISO!+ st... | delete_database():
tables_dir = os.path. | join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
zstats_results_db = os.path.join(tables_dir, 'tables', 'zstats_results_db.db')
if os.path.exists(zstats_results_db):
print("deleting database")
os.remove(zstats_results_db)
def build_analysis(analysis_requested):
# if analys... |
vslinko-archive/vasya-hobot | src/server/mappers.py | Python | mit | 1,754 | 0.00057 | # Vasya Hobot
#
# Copyright (c) 2013-2014 Vyacheslav Slinko
# Licensed under the MIT License
from thrift.Thrift import TType
from api.skype.ttypes import Chat, User, Message
__all__ = ['remap_chat_object', 'remap_user_object', 'remap_message_object']
def mapper_factory(struct):
fields = []
for field in s... | for field in fields:
value = getattr(obj, field[0])
if field[2] == TType.STRING and value:
value = value.encode('utf8')
setattr(new_obj, field[1], value)
return new_obj
return _mapper
chat_mapper | = mapper_factory(Chat)
user_mapper = mapper_factory(User)
message_mapper = mapper_factory(Message)
def remap_user_object(obj):
if obj.Handle == "":
return None
new_obj = user_mapper(obj)
return new_obj
def remap_chat_object(obj):
new_obj = chat_mapper(obj)
new_obj.activeMembers = map(re... |
laurenbarker/SHARE | share/migrations/0008_auto_20161207_1535.py | Python | apache-2.0 | 6,115 | 0.002944 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-12-07 15:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import share.models.fields
class Migration(migrations.Migration):
dependencies = [
('share', '0007_auto_20161122_1810'... | e='+', to='share.ExtraDataVersion'),
),
migrations.AlterField(
model_name='throughcontributor',
name='extra_version',
field=models.OneToOneField(db_index=False, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='share.ExtraDa... | name='extra_version',
field=models.OneToOneField(db_index=False, editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='share.ExtraDataVersion'),
),
migrations.AlterField(
model_name='throughsubjectsversion',
name='subject',
... |
box/etcdb | tests/functional/dml/test_insert.py | Python | apache-2.0 | 1,931 | 0.003625 | import pytest
from etcdb import OperationalError
from etcdb.lock import WriteLock
def test_insert(cursor):
cursor.execute('CREATE TABLE t1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))')
cursor.execute("INSERT INTO t1(id, name) VALUES (1, 'aaa')")
cursor.execute("INSERT INTO t1(id, name)... | ationalError):
| cursor.execute("UPDATE t1 SET name = 'bbb' WHERE id = 1")
|
fabiand/igor | examples/testcases/libs/common/common.py | Python | lgpl-2.1 | 2,546 | 0.009427 |
import logging
import os
import subprocess
logger = logging.getLogger(__name__)
logging.basicConfig( \
format='%(levelname)s - %(asctime)s - %(module)s - %(message)s', \
level=logging.DEBUG)
# Picking up from client-bootstrap.sh
class Igor(object):
apiurl = None
session = None
current_step = Non... | ())
# pylint: enable-msg=E1101
return r
def debug_curl(url):
"""Curl a URL
>>> debug_curl("localhost")
''
"""
debug("Calling '%s'" % url)
return run("curl --silent '%s'" % url)
def api_url(p):
"""Build an api url
>>> api_url("p")
'__APIURL__/p'
"""
return os.path.jo... | api_call(p):
"""Build and curl an API URL
>>> api_call("p")
''
"""
return debug_curl(api_url(p))
def step_succeeded():
api_call("jobs/{session}/step/{step}/success".format(session=igor.session,
step=igor.current_step))
def step_failed()... |
paladini/pink-floyd-lyric-generator | pink-floyd-lyric-generator.py | Python | mit | 1,095 | 0.007306 | #!/usr/bin/python3
import sys
import os
import glob
from pymarkovchain import MarkovChain
if __name__ == '__main__':
# Checking and saving arguments
if len(sys.argv) != 2:
raise "Usage: python3 pink-floyd-lyric-generator.py [number_of_phrases_to_generate]"
number_of_phrases = sys.argv[1]
# Ge... | lob(os.path.join('lyrics/', '*.lyric')):
with open(filename, 'r') as lyric:
lyrics += l | yric.read()
# Generating the database
mc.generateDatabase(lyrics)
mc.dumpdb()
# Printing a string
for i in range(0, int(number_of_phrases)):
print(mc.generateString()) |
tomjelinek/pcs | pcs/lib/booth/constants.py | Python | gpl-2.0 | 446 | 0 | DEFAULT | _INSTANCE_NAME = "booth"
GLOBAL_KEYS = (
"transport",
"port",
"name",
"authfile",
"maxtimeskew",
"site",
"arbitrator",
"site-user",
"site-group",
"arbitrator-user",
"arbitrator-group",
"debug",
"ticket",
)
TICKET_KEYS = (
"acqu | ire-after",
"attr-prereq",
"before-acquire-handler",
"expire",
"mode",
"renewal-freq",
"retries",
"timeout",
"weights",
)
|
sinotradition/meridian | meridian/tst/acupoints/test_shentang22.py | Python | apache-2.0 | 301 | 0.006645 | #!/usr/b | in/python
#coding=utf-8
'''
@author: sheng
@license:
'''
import unittest
from meridian.acupoints import shentang22
class TestShentang22Functions(unittest.TestCase):
def setUp(self):
pass
def test_xxx(self):
pass
if __name__ == '__main_ | _':
unittest.main()
|
Tanych/CodeTracking | 286-Walls-and-Gates/solution.py | Python | mit | 1,268 | 0.045741 | class Solution(object):
def dfs(self,rooms):
# get all gate position
queue=[(i,j,0) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v]
while queue:
i,j,depth=queue.pop()
# has a min path to gate and update
if depth<rooms[i][j]:
... | if 0<=newi<len(rooms) and 0<=newj<len(rooms[0]) and depth<rooms[newi][newj]:
queue.append((newi,newj,depth+1))
def bfs(self,rooms):
# get all gate position
queue=[(i,j) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v]
while queue:
... | 0<=newi<len(rooms) and 0<=newj<len(rooms[0]) and rooms[newi][newj]==2147483647:
rooms[newi][newj]=rooms[i][j]+1
queue.append((newi,newj))
def wallsAndGates(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: void Do not return ... |
dmadeka/bqplot | bqplot/traits.py | Python | apache-2.0 | 9,620 | 0.00395 | # Copyright 2015 Bloomberg Finance L.P.
#
# 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 i... | bj):
if value:
return dt.datetime.strptime(value.rstrip('Z'), '%Y-%m-%dT%H:%M:%S.%f')
else:
return value
date_serialization = dict(to_json=date_to_json, from_json=date_from_json)
class Date(TraitType):
"""
A datetime trait type.
Converts the passed date into a string format that ... | ue
if isinstance(value, dt.date):
return dt.datetime(value.year, value.month, value.day)
if np.issubdtype(np.dtype(value), np.datetime64):
# TODO: Fix this. Right now, we have to limit the precision
# of time to microseconds because np.datetime64.a... |
frederica07/Dragon_Programming_Process | PyOpenGL-3.0.2/tests/test_glutwindow.py | Python | bsd-2-clause | 3,343 | 0.032605 | """Test simple functions (i.e. no pointers involved)"""
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time
start = time.time()
window = None
def drawText( value, x,y, windowHeight, windowWidth, step = 18 ):
"""Draw the given text at given 2D position in window
"""
glMa... | Mode(GL_MODELVIEW);
def display():
glutSetWindow(window);
glClearColor (0.0, 0.0, (ti | me.time()%1.0)/1.0, 0.0)
glClear (GL_COLOR_BUFFER_BIT)
drawText( 'hello', 20,20, size[0],size[1] )
#glutBitmapCharacter( GLUT_BITMAP_8_BY_13, ord('a'))
glutSolidTeapot( .2 )
glFlush ()
glutSwapBuffers()
size = (250,250)
def reshape( *args ):
global size
size = args
glViewport( *( ... |
WikipediaLibrary/TWLight | TWLight/users/migrations/0057_expire_all_sessions.py | Python | mit | 818 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-05-08 17:49
from __future__ import unicode_literals
from django.db import migrations
from django.core import management
from django.contrib.sessions.models import Session
from django.utils.timezone import now
def expire_all_sessions(apps, schema_edit | or):
# Clear any expired sessions.
management.call_command("clearsessions")
# Set any remaining sessions to expire.
sessions = Session.objects.all()
for session in sessions:
session.expire_date = now()
session.save()
# Clear those sessions too.
management.call_command("clear... | Migration(migrations.Migration):
dependencies = [("users", "0056_remove_authorization_partner")]
operations = [migrations.RunPython(expire_all_sessions)]
|
bartscheers/tkp | documentation/conf.py | Python | bsd-2-clause | 9,711 | 0.006386 | # -*- coding: utf-8 -*-
#
# TKP API documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 7 17:00:49 2011.
#
# 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
# autog | enerated file.
#
# All configuration values have a default; values that are comm | ented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
... |
mzdaniel/oh-mainline | vendor/packages/Django/tests/modeltests/proxy_models/tests.py | Python | agpl-3.0 | 11,673 | 0.002142 | from django.test import TestCase
from django.db import models, DEFAULT_DB_ALIAS
from django.db.models import signals
from django.core import management
from django.core.exceptions import FieldError
from django.contrib.contenttypes.models import ContentType
from models import MyPerson, Person, StatusPerson, LowerStatu... | class Meta:
proxy = True
self.assertRaises(TypeError, build_no_cb | c)
def test_no_base_classes(self):
def build_no_base_classes():
class NoBaseClasses(models.Model):
class Meta:
proxy = True
self.assertRaises(TypeError, build_no_base_classes)
def test_new_fields(self):
def build_new_fields():
... |
jamielennox/python-keystoneclient | keystoneclient/tests/v2_0/test_client.py | Python | apache-2.0 | 6,828 | 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
# d... | son=client_fixtures.project_scoped_token())
cl = client.Client(username='exampleuser',
password='password',
tenant_name='exampleproject',
auth_url=self.TEST_URL)
cache = json.dumps(cl. | auth_ref)
new_auth_url = "http://new-public:5000/v2.0"
new_client = client.Client(auth_ref=json.loads(cache),
auth_url=new_auth_url)
self.assertIsNotNone(new_client.auth_ref)
self.assertTrue(new_client.auth_ref.scoped)
self.assertTrue(new_client... |
Distrotech/yum-utils | plugins/ovl/ovl.py | Python | gpl-2.0 | 1,800 | 0.001667 | # Copyright (C) 2015 Red Hat, Inc.
#
# Authors: Pavel Odvody <podvody@redhat.com>
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This progr... | Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
from yum.plugins import TYPE_CORE
from os import ... | gin_type = (TYPE_CORE,)
mtab = '/etc/mtab'
def should_touch():
"""
Touch the files only once we've verified that
we're on overlay mount
"""
with open(mtab, 'r') as f:
line = f.readline()
return line and line.startswith('overlay /')
return False
def prereposetup_hook(conduit):
... |
supercheetah/diceroller | pyinstaller/PyInstaller/lib/junitxml/tests/test_junitxml.py | Python | artistic-2.0 | 12,777 | 0.003131 | #
# junitxml: extensions to Python unittest to get output junitxml
# Copyright (C) 2009 Robert Collins <robertc@robertcollins.net>
#
# Copying permitted under the LGPL-3 licence, included with this library.
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import datetime
impo... | ult
class TestJUnitXmlResult__init__(unittest.TestCase):
def test_with_stream(self):
result = junitxml.JUnitXmlResult(StringIO())
class TestJUnitXmlResult(unittest.TestCase):
def setUp(self):
self.output = StringIO()
self.result = junitxml.JUnitXmlResult(self.output)
def get_o... | put = self.output.getvalue()
# Collapse detailed regions into specific strings we can match on
return re.sub(r'(?s)<failure (.*?)>.*?</failure>',
r'<failure \1>failure</failure>', re.sub(
r'(?s)<error (.*?)>.*?</error>', r'<error \1>error</error>',
re.sub(r'time="\d+\... |
EmpireProject/Empire | lib/modules/python/situational_awareness/network/active_directory/get_fileservers.py | Python | bsd-3-clause | 4,433 | 0.005865 | class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Get FileServers',
# list of one or more authors for the module
... | her comments
| 'Comments': ['']
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
# The 'Agent' option is the only one that MUST be in a module
... |
Gustry/inasafe | safe/gis/vector/test/test_smart_clip.py | Python | gpl-3.0 | 926 | 0.00108 | # coding=utf-8
import unittest
from safe.test.utilities import (
get_qgis_app,
load_test_vector_layer)
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()
from safe.gis.vector.smart_clip import smart_clip
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inas... | Down(self):
pass
def test_clip_vector(self):
"""Test we can smart clip two layers, like indivisible polygons."""
analysis = load_test_vector_layer(
'gisv4', 'analysis', 'analysis.geojson')
exposure = load_test_vector_layer(
'gisv4', 'exposure', 'buildings.g... | keywords
# todo
|
james-antill/yum | yum/packages.py | Python | gpl-2.0 | 90,704 | 0.005413 | #!/usr/bin/python -tt
# This program is free software; you can redi | stribute 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 progra | m is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ... |
cripplet/treedoc-py | src/ops/next_node.py | Python | mit | 1,836 | 0.007081 | """TreeNode operation to find next node."""
import threading
from src.core import tree
from src.ops import abstract
class NextNodeOp(abstract.AbstractOp):
"""Finds next TreeNode instance in the tree in in-order traversal."""
def do(self, root, args):
"""Implements NextNodeOp.
See http://www.geeksforg... | = tree.TreeNode.LEFT:
root.metadata['next'] = node.parent
return root.metadata.get('next')
node = node.parent
raise StopIteration('Last | node reached.')
|
openslack/openslack-monitor | aggregator/storm/count_words.py | Python | apache-2.0 | 1,013 | 0.006704 | from collections import defaultdict
from collections import namedtuple
import logging
from pyleus.storm import SimpleBolt
log = logging.getLogger('counter')
Counter = namedtuple("Counter", "word count") # 输出是两个字段
class CountWordsBolt(SimpleBolt):
OUTPUT_FIELDS = Counter # 输出是两个字段
def initialize(self):
... | es # 获得上游的word
self.words[word] += 1 # 计数
log.debug("{0} {1}".format(word, self.words[word]))
# 注意这里输出到下游的是两个字段 word 与 word的计数
self.emit((word, self.words[word]), anchors=[tup])
if __name__ == '__main__':
logging.basicConfig(
level=logging.DEBUG,
filename='/tmp/word... | at="%(message)s",
filemode='a',
)
CountWordsBolt().run() |
hiatobr/midiacapoeira | models/01_db.py | Python | gpl-3.0 | 142 | 0.007042 | # -*- codi | ng: utf-8 -*-
# this file is released under public domain and you can use without | limitations
db = DAL("sqlite://storage.sqlite")
|
DmitryADP/diff_qc750 | vendor/nvidia/tegra/3rdparty/python-support-files/src/Lib/commands.py | Python | gpl-2.0 | 2,540 | 0.001575 | """Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is remov... |
r | eturn getstatusoutput(cmd)[1]
# Ditto but preserving the exit status.
# Returns a pair (sts, output)
#
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is No... |
mamico/scorched | scorched/tests/schema.py | Python | mit | 52,325 | 0.005103 | schema = {u'copyFields': [{u'dest': u'text', u'source': u'author'},
{u'dest': u'text', u'source': u'cat'},
{u'dest': u'text', u'source': u'content'},
{u'dest': u'text', u'source': u'content_type'},
{u'dest': u'text', u'source': u'description'},
... | u'replace': u'all',
u're | placement': u''}],
u'tokenizer': {u'class': u'solr.KeywordTokenizerFactory'}},
u'class': u'solr.TextField',
u'name': u'alphaOnlySort',
u'omitNorms': True,
u'sortMissingLast': True},
{u'class': u'solr... |
cmcginty/PyWeather | weather/units/tests/test_temp.py | Python | gpl-3.0 | 8,293 | 0.002291 | #!/usr/bin/env python
#
# Unit Tests for temp module
#
# See __usage__ for an explanation of runtime arguments.
#
# -Christopher Blunck
#
import unittest
from ..temp import *
__author__ = 'Christopher Blunck'
__email__ = 'chris@wxnet.org'
__revision__ = '$Revision: 1.6 $'
__doc__ = '''
Unit tests the temp module... | assert int(rankine_to_celsius(527)) == 19, "value not correct"
assert int(rankine_to_celsius(617)) == 69, "value not correct"
def test__rankine_to_fahrenheit(self):
# make sure some special values work
assert int(rankine_to_fahrenheit(491)) == 31, "value not correct"
as | sert int(rankine_to_fahrenheit(671)) == 211, "value not correct"
# make sure some hard coded values work
assert int(rankine_to_fahrenheit(0)) == -459, "value not correct"
assert int(rankine_to_fahrenheit(527)) == 67, "value not correct"
assert int(rankine_to_fahrenheit(617)) == 157, "va... |
tkensiski/rexus | Rexus/device_poller/devices/digital_device.py | Python | gpl-3.0 | 488 | 0 | from rexus.devices import Device
class DigitalDevice(Device):
def __init__(self, config, interface):
super(DigitalDevice, self).__init__(config=config, interface=interface)
self.active = None
# Re | turn the value that we want to display
# Override this in the top level class
def get_state(self):
return self.active
def | __repr__(self):
return "<DigitalDevice: Active:{value}> ".format(
value=self.get_state(),
)
|
kralf/morsel | python/lib/morsel/console/clipboard.py | Python | gpl-2.0 | 559 | 0.023256 | import gtk, pygtk
import os
import sys
pygtk | .require('2.0')
#-------------------------------------------------------------------------------
class Clipboard(object):
def __init__(self):
object.__init__(self)
self.clipboard = gtk.clipboard_get()
#-------------------------------------------------------------------------------
| def getText(self):
return self.clipboard.wait_for_text()
def setText(self, text):
self.clipboard.set_text(text)
self.clipboard.store()
text = property(getText, setText)
|
JesseLivezey/plankton | pylearn2/scripts/plankton/gen_train_register.py | Python | bsd-3-clause | 1,233 | 0.012165 | import os, sys
from scipy.misc import imread, imsave
from scipy.ndimage.interpolation import rotate
import numpy as np
if len(sys.argv) < 3:
print "Usage: python gen_train_register.py input_folder output_folder"
exit(1)
fi = sys.argv[1]
fo = sys.argv[2]
classes = os.listdir(fi)
os.chdir(fo)
for cls in class... | = os.listdir(os.path.join(fi,cls))
for img in imgs:
orig_img = imread(os.path.join(fi,cls,img))
nimg = 1. - orig_img/255.
# orig_angle = np.arctan((nimg.shape[0]*1.)/nimg.shape[1])*180./np.pi
# n_angles = np.round(orig_angle/45.)
# oimg = rotate(nimg, 360-(45*n_angles), resh... | ')
pts = np.array(np.where(nimg >= np.median(nimg[nimg>0.])))
xy_pts = np.zeros_like(pts, dtype='float')
xy_pts[0] = pts[1] - nimg.shape[1]/2.
xy_pts[1] = nimg.shape[0]/2. - pts[0]
u,s,v = np.linalg.svd(xy_pts,full_matrices=False)
orig_angle = np.arctan(u[1,0]/u[0,0])*18... |
emacsmirror/stgit | stgit/lib/stack.py | Python | gpl-2.0 | 14,760 | 0.001287 | """A Python class hierarchy wrapping the StGit on-disk metadata."""
import re
from stgit.config import config
from stgit.exception import StackException
from stgit.lib import log, stackupgrade
from stgit.lib.git import Repository
from stgit.lib.git.branch import Branch, BranchException
def _stack_state_ref(stack_nam... | ):
m = re.match(r'(.*?)(-)?(\d+)$', unique_name)
if m:
base, sep, n_str = m.groups()
n = int(n_str) + 1
if sep:
unique_name = '%s%s%d' % (base, sep, n)
else:
unique_name = '%s%d' % (base... | :
unique_name = '%s-1' % unique_name
assert self.is_name_valid(unique_name)
return unique_name
class Stack(Branch):
"""Represents a StGit stack.
A StGit stack is a Git branch with extra metadata for patch stack state.
"""
def __init__(self, repository, name):
... |
grendel513/django-DefectDojo | dojo/__init__.py | Python | bsd-3-clause | 376 | 0 | from __future__ import absolute_import
# This will make | sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as ce | lery_app # noqa
__version__ = '1.1.4'
__url__ = 'https://github.com/rackerlabs/django-DefectDojo'
__docs__ = 'http://defectdojo.readthedocs.io/'
__demo__ = 'http://defectdojo.pythonanywhere.com/'
|
theheros/kbengine | kbe/res/scripts/common/Lib/distutils/dist.py | Python | lgpl-3.0 | 47,477 | 0.000716 | """distutils.dist
Provides the Distribution class, which represents the module distribution
being built/installed/distributed.
"""
import sys, os, re
try:
import warnings
except ImportError:
warnings = None
from distutils.errors import *
from distutils.fancy_getopt import FancyGetopt, translat... | negative options are options that exclude other options
negative_opt = {'quiet': 'verbose'}
# -- Creation/initialization methods -------------------------------
def __init__ (self, attrs=None):
"""Construct a new Distribution instance: initialize all the
attributes of a Distribut... | ributes their "real" values. (Any attributes not mentioned in
'attrs' will be assigned to some null value: 0, None, an empty list
or dictionary, etc.) Most importantly, initialize the
'command_obj' attribute to the empty dictionary; this will be
filled in with real command objects ... |
richardliaw/ray | python/ray/tune/examples/bayesopt_example.py | Python | apache-2.0 | 1,732 | 0 | """This example demonstrates the usage of BayesOpt with Ray Tune.
It also checks that it is usable with a separate scheduler.
"""
import time
from ray import tune
from ray.tune.schedulers import AsyncHyperBandScheduler
from ray.tune.suggest import ConcurrencyLimiter
from ray.tune.suggest.bayesopt import BayesOptSearc... | y for testing")
args, _ = parser.parse_known_args()
algo = BayesOptSearch(utility_kwargs={
"kind": "ucb",
"kappa": 2.5,
"xi": 0.0
})
algo = ConcurrencyLimiter(algo, max_concurrent=4)
scheduler = AsyncHyperBandScheduler()
analysis = | tune.run(
easy_objective,
name="my_exp",
metric="mean_loss",
mode="min",
search_alg=algo,
scheduler=scheduler,
num_samples=10 if args.smoke_test else 1000,
config={
"steps": 100,
"width": tune.uniform(0, 20),
"height": t... |
samuelmaudo/yepes | yepes/utils/unidecode/x019.py | Python | bsd-3-clause | 3,615 | 0.070816 | data = (
'', # 0x00
'', # 0x01
'', # 0x02
'', # 0x03
'', # 0x04
'', # 0x05
'', # 0x06
'', # 0x07
'', # 0x08
'', # 0x09
'', # 0x0a
'', # 0x0b
'', # 0x0c
'', # 0x0d
'', # 0x0e
'', # 0x0f
'', # 0x10
'', # 0x11
'', # 0x12
'', # 0x13
'', # 0x14
'', # 0x15
'',... | # 0x53
'', # 0x54
'', # 0x55
'', # 0x56
'', # 0x57
'', # 0x58
'', # 0x59
'', # 0x5a
'', # 0x5b
'', # 0x5c
'', # 0x5d
'', # 0x5e
'', # 0x5f
'', # 0x60
'', # | 0x61
'', # 0x62
'', # 0x63
'', # 0x64
'', # 0x65
'', # 0x66
'', # 0x67
'', # 0x68
'', # 0x69
'', # 0x6a
'', # 0x6b
'', # 0x6c
'', # 0x6d
'', # 0x6e
'', # 0x6f
'', # 0x70
'', # 0x71
'', # 0x72
'', # 0x73
'', # 0x74
'', # 0x75
'', # 0x76
'', # 0x77
'', ... |
sarvex/tensorflow | tensorflow/python/keras/utils/vis_utils_test.py | Python | apache-2.0 | 3,671 | 0.005448 | # Copyright 2018 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... | add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png'
try:
vis_utils.plot_model(
model, to_file=dot_img_fil... | self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_wrapped_layers_and_models(self):
inputs = keras.Input(shape=(None, 3))
lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
x = lstm(... |
maxive/erp | addons/account/models/res_users.py | Python | agpl-3.0 | 933 | 0.004287 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResUsers(models.Model):
_inherit = 'res.users'
has_group_warning_account = fields.Boolean(
'A warning can be set on a partner (Account)', compute='_compute_gr | oups_id', inverse='_inverse_groups_id',
group_xml_id='account.group_warning_account')
has_group_cash_rounding = fields.Boolean(
'Allow the cash rounding management', compute='_compute_groups_id', inverse='_inverse_groups_id',
group_xml_id='account.group_cash_rounding')
group_account_us... | string='Accounting & Finance', compute='_compute_groups_id', inverse='_inverse_groups_id',
category_xml_id='base.module_category_accounting_and_finance')
|
ceko/cekolabs_empanada | cekolabs_empanada/tags.py | Python | mit | 4,928 | 0.014205 | import parsers
import tokenizer
import context
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in unicode(text))
class Tag(object):... | f, context):
return ''
class I | fTag(PairedTag):
closing_literal = 'if'
def render(self, context):
#if tag can have an else tag too, so we need to first check for that.
#this is a stack of groups to evaluate in order
expression_groups = []
current_group = []
current_group_conditional = self
... |
ATNF/askapsdp | Code/Base/py-askap/current/doc/conf.py | Python | gpl-2.0 | 352 | 0.008523 | # DO THIS FIRST to set p | roject name !!!
import askapdev.sphinx
# CAN NOT contain spaces! |
askapdev.sphinx.project = u'askap.parset'
from askapdev.sphinx.conf import *
version = 'current'
release = 'current'
|
annarev/tensorflow | tensorflow/python/data/kernel_tests/dataset_spec_test.py | Python | apache-2.0 | 2,172 | 0.002762 | # Copyright 2020 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... | asetSpec`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
| from absl.testing import parameterized
import numpy as np
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.eager import def_function
from tensorflow.python.framework import combinations
from tensorflow.python.framework import dtypes
fro... |
machaharu/odenos | src/test/python/org/o3project/odenos/core/component/network/packet/test_packet_status.py | Python | apache-2.0 | 6,151 | 0.000163 | # -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... | UT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
from org.o3project.odenos.core.component.network.packet.packet_status\
import PacketStatus
... | 3210,
6540,
9870,
["in_packets"],
7410,
8520,
9630,
... |
frictionlessdata/datapackage-pipelines | datapackage_pipelines/specs/hashers/__init__.py | Python | mit | 126 | 0.007937 | from .hash_calculator import | HashCalculator
from .dependency_resolver import resolve_dependencies, DependencyMissi | ngException
|
thaim/ansible | lib/ansible/module_utils/network/eos/facts/lldp_global/lldp_global.py | Python | mit | 2,946 | 0.000679 | #
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The eos lldp_global fact class
It is in this file the configuration is collected from the device
for a given resource, parsed, and the facts tree is populated
based on th... | self._module = module
self.argument_spec = Lldp_globalArgs.argument_spec
spec = | deepcopy(self.argument_spec)
if subspec:
if options:
facts_argument_spec = spec[subspec][options]
else:
facts_argument_spec = spec[subspec]
else:
facts_argument_spec = spec
self.generated_spec = utils.generate_dict(facts_argum... |
Alidron/demo-zwave-react | demo-zwave-react.py | Python | mpl-2.0 | 1,436 | 0.003482 | # Copyright (c) 2015-2016 Contributors as no | ted in the AUTHORS file
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import signal
import sys
from functools import partial
from isac import IsacNode, IsacValue
fr... | , partial(self.sigterm_handler))
self.action_value = IsacValue(self.node, 'zwave://0xdefbc93b.power_strip001/switch_binary/1/switch', survey_last_value=False, survey_static_tags=False)
self.sensor_value = IsacValue(self.node, 'zwave://0xdefbc93b.13/alarm/access_control', survey_last_value=False, surve... |
mosbasik/message_board | main/urls.py | Python | apache-2.0 | 784 | 0.003827 | from django.conf.urls import include, url
urlpatterns = [
url(r'^$', 'main.views.index', name='index'),
url(r'^register/$', 'main.views.register', name='register'),
url(r'^login/$', 'main.views.login', name='login'),
url(r'^logout/$', 'main.views.logout', name='logout'),
url(r'^create-post/$', 'm... | .get_posts', name='get_posts'),
url(r'^create-favorite/$', 'main.views.create_favorite', name='create_favorite'),
url(r'^delete-favorite/$', 'main.views.delete_favorite', name='delete_favorite'),
url(r'^get-favorites/$', 'main.views.get_favorites', n | ame='get_favorites'),
url(r'^(?P<username>\w+)/favorites/$', 'main.views.view_favorites', name='view_favorites'),
]
|
iNecas/katello | cli/test/katello/tests/utils/option_validator_test.py | Python | gpl-2.0 | 11,718 | 0.006656 | from unittest import TestCase
from katello.cl | ient.core.base import Action
from katello.client.i18n_optparse import OptionParser
from katello.client.utils.option_validator import OptionValidator
from katello.tests.test_utils import ColoredAssertionError
import os
class OptionValidatorTestCase(TestCase):
failureException = ColoredAssertionError
def setup... | in accepted_options:
parser.add_option('--'+opt, dest=opt, action="store_true")
return parser
def setup_validator(self, accepted_options, given_options):
parser = self.setup_parser(accepted_options)
(options, arguments) = parser.parse_args(given_options)
return OptionV... |
jelmer/python-fastimport | fastimport/tests/test_dates.py | Python | gpl-2.0 | 1,135 | 0 | # Copyright (C) 2012 Canonical Ltd
#
# This program is free software; you can redist | ribute 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 WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this prog... |
GeoMop/GeoMop | src/JobPanel/ui/validators/validation.py | Python | gpl-3.0 | 3,569 | 0.004483 | # -*- coding: utf-8 -*-
"""
Validators for UI
@author: Jan Gabriel
@contact: jan.gabriel@tul.cz
"""
from enum import Enum
from PyQt5.QtGui import QColor
from PyQt5 import QtWidgets
class ValidationColors(Enum):
"""
Holds colors for form validation.
"""
white = QColor("#ffffff")
red = QColor("#f698... | s.QComboBox):
cls.colorize_frame(field, ValidationColors.red.value)
| class PresetsValidationColorizer():
"""validator for controls in preset."""
def __init__(self):
self.controls={}
"""dictionary of validated controls"""
def add(self, key, control):
"""add control for validation"""
self.controls[key] = control
def co... |
linode/python-linode-api | linode_api4/objects/tag.py | Python | bsd-3-clause | 3,873 | 0.005939 | import string
import sys
from datetime import datetime
from enum import Enum
from os import urandom
from random import randint
from linode_api4.errors import UnexpectedResponseError
from linode_api4.paginated_list import PaginatedList
from linode_api4.objects import (Base, DerivedBase, Property, Instance, Volume,
... | this entity type - do nothing?
return None
# discard the envelope
real_json = json['data']
real_id = real_json['id']
# make the real object t | ype
return Base.make(real_id, client, make_cls, parent_id=None, json=real_json)
|
51itclub/51itclub.github.io | ChnRoutesPlus/gfwlist2pacplus/main.py | Python | mit | 5,601 | 0.002142 | #!/usr/bin/python
# -*- coding: gbk -*-
#coding=gbk
import pkgutil
import urlparse
import json
import logging
import urllib2
from argparse import ArgumentParser
import os
__all__ = ['main']
gfwlist_url = 'https://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
gfwlist_url = 'https://raw.githubusercontent.co... | turn content
def get_hostname(something):
try:
# quite enough for GFW
if not something.startswith('http:'):
something = 'http://' + so | mething
r = urlparse.urlparse(something)
return r.hostname
except Exception as e:
logging.error(e)
return None
def add_domain_to_set(s, something):
hostname = get_hostname(something)
if hostname is not None:
if hostname.startswith('.'):
hostname = hostna... |
google-code-export/gui2py | gui/controls/checkbox.py | Python | lgpl-3.0 | 1,619 | 0.005559 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"gui2py's CheckBox control (uses wx.CheckBox)"
__author__ = "Mariano Reingart (reingart@gmail.com)"
__copyright__ = "Copyright (C) 2013- Mariano Reingart" # where applicable
# Initial implementation was based on PythonCard's CehckBox component,
# but redesigned an... | f.wx_obj.SetLabel(value),
type="string", default="Option")
onclick = EventSpec('click', binding=wx.EVT_CHECKBOX, kind=FormEvent)
if __name__ == "__main__":
# basic test until unit_test
app = wx.App(redirect=False)
frame = wx.Frame(None)
c = CheckBox(frame, name="chk... | .label == "Check me!"
from pprint import pprint
# assign some event handlers:
c.onclick = lambda event: pprint("click: %s" % event.target.value)
frame.Show()
app.MainLoop()
|
yanheven/glance | glance/cmd/registry.py | Python | apache-2.0 | 2,684 | 0.002981 | #!/usr/bin/env python
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file ... | ay 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. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Reference implementation server for Glance Registry
"""
impo... |
felixturner/three.js | utils/exporters/blender/2.64/scripts/addons/io_mesh_threejs/__init__.py | Python | mit | 17,429 | 0.018418 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | #############################################################
# Custom properties
# ################################################################
bpy.types.Object.THREE_castShadow = bpy.props.BoolProperty()
bpy.types.Object.THREE_receiveShadow = bpy.props.BoolProperty()
bpy.types.Object.THREE_doubleSided = bpy.prop... | .types.Material.THREE_useVertexColors = bpy.props.BoolProperty()
bpy.types.Material.THREE_depthWrite = bpy.props.BoolProperty(default = True)
bpy.types.Material.THREE_depthTest = bpy.props.BoolProperty(default = True)
THREE_material_types = [("Basic", "Basic", "Basic"), ("Phong", "Phong", "Phong"), ("Lambert", "Lamber... |
richo/quietnet | send.py | Python | mit | 2,002 | 0.005994 | import sys
import pyaudio
import quietnet
import options
import psk
FORMAT = pyaudio.paInt16
CHANNELS = options.channels
RATE = options.rate
FREQ = options.freq
FREQ_OFF = 0
FRAME_LENGTH = options.frame_length
DATASIZE = options.datasize
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RAT... | fer_from_bit_pattern(pattern, FREQ, FREQ_OFF)
play_buffer(buffer)
except KeyError:
print("Messages may o | nly contain printable ASCII characters.")
except KeyboardInterrupt:
# clean up our streams and exit
stream.stop_stream()
stream.close()
p.terminate()
print("exited cleanly")
|
plotly/python-api | packages/python/plotly/plotly/validators/layout/slider/transition/_duration.py | Python | mit | 518 | 0.001931 | import _plotly_utils.basevalidators
class D | urationValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="duration", parent_name="layout.slider.transition", **kwargs
):
super(DurationValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit | _type=kwargs.pop("edit_type", "arraydraw"),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "info"),
**kwargs
)
|
grlee77/numpy | numpy/core/_asarray.py | Python | bsd-3-clause | 12,184 | 0.000492 | """
Functions in the ``as*array`` family that promote array-likes into arrays.
`require` fits this category despite its name not matching this pattern.
"""
from .overrides import (
array_function_dispatch,
set_array_function_like_doc,
set_module,
)
from .multiarray import array
__all__ = [
"asarray",... | is an ndarray or a subclass
of ndarray, it is returned as-is and no copy is performed.
See Also
--------
asarray : Similar function which always returns ndarrays.
asco | ntiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and
Infs.
... |
induane/stomp.py3 | stomp/colors.py | Python | apache-2.0 | 219 | 0.018265 | import p | latform
if platform.system().lower() != 'windows':
GREEN = "\33[32m"
RED = "\33[31m"
NO_COLOR = "\33[0m"
BOLD="\33[1m"
else:
GREEN = ""
| NO_COLOR = ""
RED = ""
BOLD = "" |
NLeSC/pyxenon | xenon/__init__.py | Python | apache-2.0 | 969 | 0 | from .server import (init)
from .objects import (
JobDescription,
FileSystem, Scheduler, Path, Job,
PosixFilePermission, CopyMode, CopyStatus, JobStatus, QueueStatus)
from .proto.xenon_pb2 import (
CopyRequest, CertificateCredential, PasswordCredential, KeytabCredential,
PropertyDescription, Crede... | , PathAlreadyExistsException)
from .version import (
pyxenon_version)
__version__ = pyxenon_version
__all__ = [
'init',
'FileSystem', 'Scheduler', 'Path',
'Posix | FilePermission', 'Job',
'JobDescription', 'CopyRequest', 'QueueStatus', 'JobStatus',
'CopyStatus', 'CertificateCredential', 'PasswordCredential',
'KeytabCredential',
'PropertyDescription', 'CredentialMap', 'DefaultCredential',
'UserCredential', 'CopyMode',
'UnknownRpcException', 'XenonException... |
johannesring/pytave | package/__init__.py | Python | gpl-3.0 | 917 | 0.00655 | # -*- coding:utf-8 -*-
#
# Copyright 2008 David Grundberg, Håkan Fors Nilsson
#
# This file is part of Pytave.
#
# Pytave is free software: you can redistr | ibute 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.
#
# Pytave is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warra... | See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pytave. If not, see <http://www.gnu.org/licenses/>.
import _pytave
from pytave import *
# Emacs
# Local Variables:
# fill-column:70
# coding:utf-8
# indent-tabs-mode:t
# tab-width... |
rohitranjan1991/home-assistant | homeassistant/components/swiss_hydrological_data/sensor.py | Python | mit | 5,036 | 0.000794 | """Support for hydrological data from the Fed. Office for the Environment."""
from __future__ import annotations
from datetime import timedelta
import logging
from swisshydrodata import SwissHydroData
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistan... | station, condition))
add_entities(entities, True)
class SwissHydrologicalDataSensor(SensorEntity):
"""Implementation of a Swiss hydrological sensor."""
d | ef __init__(self, hydro_data, station, condition):
"""Initialize the Swiss hydrological sensor."""
self.hydro_data = hydro_data
self._condition = condition
self._data = self._state = self._unit_of_measurement = None
self._icon = CONDITIONS[condition]
self._station = stati... |
ohduran/CrowdFinanceInfographic | virtualenv/lib/python3.5/site-packages/setuptools/unicode_utils.py | Python | mit | 995 | 0.001005 | import unicodedata
import sys
from setuptools.extern import six
# HFS Plus uses decomposed UTF-8
def decompose(path):
if isinstance(path, six.text_type):
return unicodedata.normalize('NFD', path)
try:
path = path.decode('utf-8')
path = unicodedata.normalize('NFD', path)
path = ... | codeError:
pass # Not UTF-8
return path
def filesys_decode(path):
"""
Ensure that the given path is decoded,
NONE when no expected encoding works
"""
if isinstance(path, six.text_type):
return path
fs_enc = sys.getfilesystemencoding() or 'utf-8'
candidates = fs_enc, ... | in candidates:
try:
return path.decode(enc)
except UnicodeDecodeError:
continue
def try_encode(string, enc):
"turn unicode encoding into a functional routine"
try:
return string.encode(enc)
except UnicodeEncodeError:
return None
|
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/tm/tmglobal_tmtrafficpolicy_binding.py | Python | apache-2.0 | 6,800 | 0.037647 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | policy_binding()
response = obj.get_resources(service)
return response
except Exception as e:
raise e
@classmethod
def get_filtered(cls, service, filter_) :
ur""" Use this API to fetch filtered set of tmglobal_tmtrafficpolicy_binding resources.
Filter string should be in JSON format.eg: "port:80,servi... | except Exception as e:
raise e
@classmethod
def count(cls, service) :
ur""" Use this API to count tmglobal_tmtrafficpolicy_binding resources configued on NetScaler.
"""
try :
obj = tmglobal_tmtrafficpolicy_binding()
option_ = options()
option_.count = True
response = obj.get_resources(service,... |
canhhs91/greenpointtrees | greenpointtrees/bin/pildriver.py | Python | mit | 15,643 | 0.000384 | #!/Volumes/SSDATA/www/greenpointtrees/greenpointtrees/bin/python
"""PILdriver, an image-processing calculator using PIL.
An instance of class PILDriver is essentially a software stack machine
(Polish-notation interpreter) for sequencing PIL image
transformations. The state of the instance is the interpreter stack.
T... | . If there are no command-line arguments, the
module runs an interactive interpreter, each line of which is split into
space-separated tokens | and passed to the execute method.
In the method descriptions below, a first line beginning with the string
`usage:' means this method can be invoked with the token that follows
it. Following <>-enclosed arguments describe how the method interprets
the entries on the stack. Each argument specification begins with a
t... |
MichaelAquilina/CryptoTools | src/tests/aes_test.py | Python | mit | 561 | 0 | from Crypto import Random
from src.aes import encrypt_message, decrypt_message
def test_integrity():
plaintext = 'Test Text'
key = Random.new().read(16)
# Ensure that D(k, E(k, p)) == p
assert decrypt_message(key, encrypt_message(key, plaintext)) == plaintext
def test_privacy():
plaintext = 'T... | ad(16)
key2 = prng.read(16)
# Ensure decrypting with a different key does not reveal the plaintext
| assert decrypt_message(key1, encrypt_message(key2, plaintext)) != plaintext
|
secondfoundation/Second-Foundation-Src | src/diakonos/wolf/wolf.py | Python | lgpl-2.1 | 1,458 | 0.01166 | import sys
import urllib2
import urllib
import httplib
from xml.etree import ElementTree as etree
class wolfram(object):
def __init__(self, appid):
self.appid = appid
self.base_url = 'http://api.wolframalpha.com/v2/query?'
self.head | ers = {'User-Agent':None}
def _get_xml(self, ip):
url_params = {'input':ip, 'appid':self.appid}
data = urllib.urlencode(url_params)
req = urllib2.Request(self.base_url, data, self.headers)
xml = urllib2.urlopen(req).read()
return xml
def _xmlparser(self, xml):
... | g(xml)
#retrieving every tag with label 'plaintext'
for e in tree.findall('pod'):
for item in [ef for ef in list(e) if ef.tag=='subpod']:
for it in [i for i in list(item) if i.tag=='plaintext']:
if it.tag=='plaintext':
data_dics[e.g... |
dragondgold/OctoPrint | src/octoprint/server/__init__.py | Python | agpl-3.0 | 34,524 | 0.024883 | # coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import uuid
from sockjs.torn... | Need(user.get_name()))
if user.is_user():
identity.provides.add(RoleNeed("user"))
if user.is_admin():
identity.provides.add(RoleNeed("admin"))
def | load_user(id):
if id == "_api":
return users.ApiUser()
if session and "usersession.id" in session:
sessionid = session["usersession.id"]
else:
sessionid = None
if userManager is not None:
if sessionid:
return userManager.findUser(username=id, session=sessionid)
else:
return userManager.findUser(us... |
Southpaw-TACTIC/Team | src/python/Lib/site-packages/PySide/examples/state-machine/eventtrans.py | Python | epl-1.0 | 1,534 | 0.001956 | #Author velociraptor Genjix <aphidia@hotmail.com>
from PySide.QtGui import *
from PySide.QtCore import *
class MainWindow(QMainWindow) | :
def __init__(self):
super(MainWindow, self).__init__()
button = QPushButton(self)
button.setGeometry(QRect(100, 100, 100, 100))
machine = QStateMachine(self)
s1 = QState()
s1.assignProperty(button, 'text', 'Outside')
s2 = QState()
s2.assignProperty(... | leaveTransition = QEventTransition(button, QEvent.Leave)
leaveTransition.setTargetState(s1)
s2.addTransition(leaveTransition)
s3 = QState()
s3.assignProperty(button, 'text', 'Pressing...')
pressTransition = QEventTransition(button, QEvent.MouseButtonPress)
pressTra... |
kishkaru/python-driver | cassandra/policies.py | Python | apache-2.0 | 32,311 | 0.000867 | # Copyright 2013-2016 DataStax, 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 agreed to in writi... | self._position = randint(0, len( | hosts) - 1) if hosts else 0
def distance(self, host):
dc = self._dc(host)
if dc == self.local_dc:
return HostDistance.LOCAL
if not self.used_hosts_per_remote_dc:
return HostDistance.IGNORED
else:
dc_hosts = self._dc_live_hosts.get(dc)
... |
baoboa/pyqt5 | examples/richtext/calendar.py | Python | gpl-3.0 | 7,071 | 0.005374 | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... | gth(QTextLength.PercentageLength, 14),
QTextLength(QTextLength.PercentageLength, 14),
QTextLength(QTextLength.PercentageLength, 14),
QTextLength(QTextLength.PercentageLength, 14)]
tableF | ormat.setColumnWidthConstraints(constraints)
table = cursor.insertTable(1, 7, tableFormat)
frame = cursor.currentFrame()
frameFormat = frame.frameFormat()
frameFormat.setBorder(1)
frame.setFrameFormat(frameFormat)
format = cursor.charFormat()
format.setFontPoin... |
zfrenchee/pandas | pandas/tests/series/test_period.py | Python | bsd-3-clause | 9,779 | 0 | import numpy as np
import pandas as pd
import pandas.util.testing as tm
import pandas.core.indexes.period as period
from pandas import Series, period_range, DataFrame, Period
def _permute(obj):
return obj.take(np.random.permutation(len(obj)))
class TestSeriesPeriod(object):
def setup_method(self, method):... | == s, exp)
exp = Series([True, True, False, True])
tm.assert_series_equal(base != s, exp)
exp = Series([False, True, False, False])
tm.assert_series_equal(base > s, exp)
exp = Series([True, False, False, True])
tm.assert_series_equal(base < s, exp)
exp = Serie... | rt_series_equal(base >= s, exp)
exp = Series([True, False, True, True])
tm.assert_series_equal(base <= s, exp)
def test_align_series(self):
rng |
bokeh/bokeh | tests/unit/bokeh/sampledata/test_gapminder.py | Python | bsd-3-clause | 2,214 | 0.010388 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | ne:
import bokeh.sampledata.gapminder as bsg
data = getattr(bsg, name)
assert isinstance(data, pd.DataFrame)
# don't check detail for external data
#-----------------------------------------------------------------------------
# Dev API
#----------------------------------------------------------------... | --------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
|
nemesiscodex/JukyOS-sugar | extensions/deviceicon/battery.py | Python | gpl-2.0 | 9,334 | 0.000107 | # Copyright (C) 2006-2007, Red Hat, 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 distribut... | _text(status_text)
class DeviceModel(gobject.GObject):
__gproperties__ = {
'level': (int, None, None, 0, 100, 0, gobject.PARAM_READABLE),
'time-remaining': (int | , None, None, 0, sys.maxint, 0,
gobject.PARAM_READABLE), # unit: seconds
'charging': (bool, None, None, False, gobject.PARAM_READABLE),
'discharging': (bool, None, None, False, gobject.PARAM_READABLE),
'present': (bool, None, None, False, gobject.PARAM_READABLE),
... |
vileopratama/vitech | src/addons/stock_calendar/stock.py | Python | mit | 668 | 0.005988 | from openerp.osv import fields, osv
class stock_warehouse_orderpoint(osv.osv):
_inherit = "stock.warehouse.orderpoint"
_columns = {
'calendar_id': fields.many2one('resource.calendar', 'Calendar',
help="In the calendar you can define the days that the goods will b... | "),
'purchase_calendar_id': fields.m | any2one('resource.calendar', 'Purchase Calendar'),
'last_execution_date': fields.datetime('Last Execution Date', readonly=True),
}
|
hjanime/VisTrails | vistrails/db/versions/v1_0_0/domain/log.py | Python | bsd-3-clause | 3,203 | 0.008742 | ###############################################################################
##
## Copyright (C) 2014-2015, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... | # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
## OTHERWISE) ARISIN... | OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
##
###############################################################################
from __future__ import division
from auto_gen import DBLog as _DBLog
from auto_gen import DBAbstraction, DBModule, DBGroup, DBLoopExec, \
DBGr... |
backpacker69/pypeerassets | pypeerassets/voting.py | Python | bsd-3-clause | 7,188 | 0.002226 | import warnings
from pypeerassets.kutil import Kutil
from pypeerassets.protocol import Deck
from pypeerassets import pavoteproto
from hashlib import sha256
from binascii import unhexlify
from pypeerassets import transactions
from pypeerassets.pautils import read_tx_opreturn, find_tx_sender, get_block_info
from .network... | nsactions.make_raw_transaction(vote.deck.network, inputs['utxos'], outputs)
class VoteCast:
'''vote cast object, internal represtentation of the vote_cast transaction'''
def __init__(self, vote: Vote, sender: str, blocknum: int,
confirmations: int, timestamp: int):
self.vote = vote
... | = confirmations
self.timestamp = timestamp
@property
def is_valid(self):
'''check if VoteCast is valid'''
if not (self.blocknum >= self.vote.start_block and
self.blocknum <= self.vote.end_block):
return False
if not self.confirmations >= 6:
... |
pankajp/pyface | pyface/grid/checkbox_renderer.py | Python | bsd-3-clause | 154 | 0.006494 | import logging
logging.warn('DEPR | ECATED: pyface.grid, '
'use pyface.ui.wx.grid instead.')
from pyface.ui.wx.grid.checkbox_rendere | r import *
|
theonaun/theo_site | app_surgeo/migrations/0008_auto_20150928_0007.py | Python | mit | 979 | 0.001021 | # -*- coding: utf-8 -*-
fr | om __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('app_surgeo', '0007_auto_20150927_1509'),
]
operations = [
migrations.AlterField(
model_name='forenametogender',
| name='forename',
field=models.CharField(db_index=True, max_length=25),
),
migrations.AlterField(
model_name='surnametorace',
name='surname',
field=models.CharField(db_index=True, max_length=25),
),
migrations.AlterField(
model... |
badmetacoder/fabric-examples | server-inventory.py | Python | mit | 2,676 | 0.004111 | from fabric.api import sudo
from fabric.api import run
from fabric.api import local
from fabric.api import env
from fabric.api import get
def _record(cmd, dump_file):
"""The real hard worker. Executes the given command and transfers the output
file to the local directory.
"""
cmd_str = cmd % dump_file
... | dump_file)
except Exception as e:
print e.message
env['warn_only'] = warn_only_state
def process_invent | ory(dump_file='process-dump.txt'):
"""dumps output of ps auxw
"""
cmd_str = 'ps auxw > /tmp/%s'
return _record(cmd_str, dump_file)
def net_servers_inventory(dump_file='net-servers-dump.txt'):
"""dumps output of netstat -tulpn
"""
cmd_str = 'sudo netstat -tulpn > /tmp/%s'
return _record... |
codebio/gmvv | surda/surda/urls.py | Python | gpl-3.0 | 300 | 0.016667 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = | patterns('',
# Examples:
# url(r'^$', 'surda.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(a | dmin.site.urls)),
)
|
drmrd/ansible | lib/ansible/modules/cloud/amazon/ec2_ami_copy.py | Python | gpl-3.0 | 7,355 | 0.002311 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible 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.
#
... | description: latest patch
# Tagged AMI copy (will not copy the same AMI twice)
- ec2_ami_copy:
source_region: us-east-1
region: eu-west-1
source_image_id: ami-xxxxxxx
tags:
Name: My-Super-AMI
Patch: 1.2.3
tag_equality: yes
# Encrypted AMI copy
- ec2_ami_copy:
source_region:... | _copy:
source_region: us-east-1
region: eu-west-1
source_image_id: ami-xxxxxxx
encrypted: yes
kms_key_id: arn:aws:kms:us-east-1:XXXXXXXXXXXX:key/746de6ea-50a4-4bcb-8fbc-e3b29f2d367b
'''
RETURN = '''
image_id:
description: AMI ID of the copied AMI
returned: always
type: string
sample: ami-e6... |
mweb/python | exercises/two-fer/two_fer_test.py | Python | mit | 424 | 0 | import unittest
import two_fer
class Two_Fer_test(unittest.TestCase):
def test_empty(self):
self.assertEqual(two_fer.two_fer(), 'One for you, one for me.')
def test_eve(self):
self.assertEqual(two_fer.two_fer("Eve"), "On | e for Eve, one for me.")
def test_bob(self):
self.assertEqual(two_fer.two_fer("Bob"), "One for Bob, one for me.")
if __name__ == '__main__' | :
unittest.main()
|
gbtimmon/ase16GBT | code/4/ga/pwang13.py | Python | unlicense | 8,789 | 0.001024 | # %matplotlib inline
# All the imports
from __future__ import print_function, division
from math import *
import random
import sys
import matplotlib.pyplot as plt
# TODO 1: Enter your unity ID here
__author__ = "pwang13"
class O:
"""
Basic Class which
- Helps dynamic updates
- Pretty Prints
... | (point):
return point
# return point
cone = Problem()
# point = cone.generate_one()
# cone.evaluate(point)
# print (point)
def populate(problem, size):
population = []
# TODO 6: Create a list of points of length 'size'
for _ i | n xrange(size):
population.append(problem.generate_one())
return population
# return (problem.generate_one() for _ in xrange(size))
def crossover(mom, dad):
# TODO 7: Create a new point which contains decisions from
# the first half of mom and second half of dad
# print(mom.decisions)
... |
jemofthewest/GalaxyMage | data/core/abilities/wingedfeet.py | Python | gpl-2.0 | 268 | 0.003731 | VERS | ION = 1
NAME = _("Winged Feet")
DESCRIPTION = _("Increases the movement rate of a unit.")
ABILITY_TYPE = ACTION
COST = 10
TARGET_TYPE = FRIENDLY
RANGE = Diamond(0, 5, 16)
AOE = Single()
EFFECTS = [Status(Status.PLUS_MOVE, power=1.0, hit=0.5, duration=5)]
| |
tomcounsell/Cobra | apps/admin/models/rating_subject.py | Python | gpl-2.0 | 277 | 0.028881 | from django.db import models
class RatingSubject(models.Model | ):
#we may be able to move this to a list of choices for the Rating model
name = models.CharField(max_length=20)
# MODEL PROPERTIES
# MODEL FUNCTI | ONS
def __unicode__(self):
return self.name
|
CloudNiner/fadds-parser | setup.py | Python | mit | 122 | 0 | # -*- coding: utf-8 -*-
from setuptools | import setup
setup(setup_requires=['pbr'],
pbr=True,
test_suite | ="")
|
kerwinxu/barcodeManager | zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/ifl.py | Python | bsd-2-clause | 2,880 | 0.004167 | """SCons.Tool.ifl
Tool-specific initialization for the Intel Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 200... | OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/ifl.py 5023 2010/06/14 22:05:46 scons"
import SCons.Defaults
from SCons.Scanner.Fortran import FortranScan
from FortranCommon import add_all_to_env
... | ifl to an Environment."""
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES... |
mahim97/zulip | zerver/lib/mention.py | Python | apache-2.0 | 1,137 | 0.004398 |
from typing import Optional, Set, Text
import re
# Match multi-word string between @** ** or match any one-word
# sequences after @
find_mentions = r'(?<![^\s\'\"\(,:<])@(\*\*[^\*]+\*\*|all|everyone)'
user_group_mentions = r'(?<![^\s\'\"\(,:<])@(\*[^\*]+\*)'
wildcards = ['all', 'everyone']
def user_mention_matches... | ext[1:-1]
def possible_user_group_mentions(content: Text) -> Set[Text]:
matches = re.findall(user_group_men | tions, content)
return {extract_user_group(match) for match in matches}
|
gaolichuang/neutron-fwaas | neutron_fwaas/services/firewall/drivers/mcafee/constants.py | Python | apache-2.0 | 9,141 | 0 | # Copyright 2015 Intel Corporation.
# Copyright 2015 Yalei Wang <yalei.wang at intel com>
#
# 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://... | _interface': | {
'failure_mode': 'normal',
'logical_interface_ref':
'http://localhost:8082/5.7/elements/logical_interface/1',
'nicid': '1-2'
}
... |
Djhacker18/Python | Practica1Conver.py | Python | gpl-2.0 | 202 | 0.039604 | def main():
print "hola"
print "Como te llmas | ?"
nombre = raw_input()
pri | nt "Buenos dias", nombre
print "Que edad tienes?"
edad = raw_input()
print "que bien te conservas para tener", edad
main()
|
xodus7/tensorflow | tensorflow/python/estimator/estimator.py | Python | apache-2.0 | 89,962 | 0.004635 | # Copyright 2016 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... | tion
from tensorflow.python.training import monitored_session
from tensorflow.python.training import saver
from tensorflow.python.training import training
from tensorflow.python.training import trai | ning_util
from tensorflow.python.training import warm_starting_util
from tensorflow.python.util import compat
from tensorflow.python.util import compat_internal
from tensorflow.python.util import function_utils
from tensorflow.python.util import nest
from tensorflow.python.util.tf_export import estimator_export
_VALI... |
Bobspadger/python-amazon-mws | mws/apis/finances.py | Python | unlicense | 2,941 | 0.0017 | """
Amazon MWS Finances API
"""
from __future__ import absolute_import
from ..mws import MWS
# from .. import utils
from ..decorators import next_token_action
class Finances(MWS):
"""
Amazon MWS Finances API
Docs:
http://docs.developer.amazonservices.com/en_US/finances/Finances_Overview.html
"""... | rId': amazon_order_id,
'PostedAfter': posted_after,
'PostedBefore': posted_before,
'MaxResultsPerPage': max_results,
}
return self.make_request(data)
def list_financial_events_by_next_token(self, token):
"""
Alias for `list_financial_events(next_t... | urn self.list_financial_events(next_token=token)
|
boutproject/BOUT-2.0 | examples/non-local_1d/analyse_check_q_boundary_condition.py | Python | gpl-3.0 | 2,183 | 0.046768 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Runs the conduction example, produces some output
#
nproc = 1 # Number of processors to use
from boututils import shell, launch, plotdata
from boutdata import collect
import numpy as np
from sys import argv
from math import sqrt, log10, log, pi
from matplotlib impo... | sheath_potential = 0.5*Te_right*log(2*pi*electron_mass/ion_mass*(1+gamma*Ti_right/Te_right))
q_electron_right.append((2.0*Te_right-sheath_potential)*n_right*V[i,2,right_index+1,0]) # in W/m^2
pyplot.figure(1)
pyplot.plot(q_electron_left,'r',q[:,2,2,0],'b',q_electron_right,'r',q[:,2,right_index+1,0],'b')
pyplot.title... | t.ylabel("Q/eV.m$^{-2}$")
pyplot.figure(2)
pyplot.plot(q[:,2,2,0]-q_electron_left,'b',q[:,2,right_index+1,0]-q_electron_right,'r')
pyplot.title("Difference between heat flux and its calculated boundary value at the left (blue) and right (red) boundaries\n\n")
pyplot.xlabel(u"t/μs")
pyplot.ylabel("dQ/eV.m$^{-2}$")
pyplo... |
adexin/Python-Machine-Learning-Samples | Convolutional_Neural_Networks/blr.py | Python | mit | 1,020 | 0.002941 | import numpy as np
from scipy.signal import convolve2d
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Custom Convolution
def conv2d(X, W):
n1, n2 = X.shape
m1, m2 = W.shape
y = np.zeros((n1 + m1 - 1, n2 + m2 - 1))
for i in range(n1 + m1 - 1):
for ii in range(m1):
... | y[i, j] = W[ii, jj] * X[i - ii, j - jj]
return y
img = mpimg.imread('lena.png')
bw = img.mean(axis=2)
W = np.zeros((20, 20))
for i in range(20):
for j in range(20):
dist = (i - 9.5)**2 + (j - 9.5)**2
W[i, j] = np.exp(-dist / 50)
out = conv2d(bw, W)# convolve2d(in1=bw, in2=W)
plt.imshow(... | on all 3 color channels
out3 = np.zeros(img.shape)
for i in range(3):
out3[:, :, i] = convolve2d(in1=img[:, :, i], in2=W, mode='same')
plt.imshow(out3)
plt.show()
|
swbooking/RobotMaria | snippets/rgb_led/rgb_led.py | Python | mit | 701 | 0.002853 | #!/usr/bin/env python
import Adafruit_BBIO.GPIO as GPIO
import time
red_pin = "P8_10"
green_pin = "P8_12"
blue_pin = "P8_14"
GPIO.setup(red_pin, GPIO.OUT)
GPIO.output(red_pin, GPIO.LOW)
GPIO.setup(green_pin, GPIO.OUT)
GPIO.output(green_pin, GPIO.LOW)
GPIO.setup(blue_pin, GPIO.OUT)
GPIO.output(blue_pin, GPIO.LOW)
... | "
GPIO.output(green_pin, GPIO.HIGH)
time.sleep(5)
GPIO.output(green_pin, GPIO.LOW)
print "Turning on Blue"
GPIO.output(blue_pin, GPIO.HIGH)
time.sleep(5)
GPIO.output(blue_pi | n, GPIO.LOW)
|
lamkeewei/battleships | server/models/User.py | Python | apache-2.0 | 90 | 0.033333 | from google.appengine. | ext import ndb
class User(ndb.Model):
name = ndb.StringProperty() | |
cedricporter/funcat | funcat/data/tushare_backend.py | Python | apache-2.0 | 3,292 | 0.001549 | # -*- coding: utf-8 -*-
#
from cached_property import cached_property
from .backend import DataBackend
from ..utils import lru_cache, get_str_date_from_int, get_int_date
class TushareDataBackend(DataBackend):
@cached_property
def ts(self):
try:
import tushare as ts
return ts... | book_id)
return "{}[{}]".form | at(order_book_id, self.code_name_map.get(code))
|
RPi-Distro/pgzero | test/test_sound_formats.py | Python | lgpl-3.0 | 2,385 | 0.000419 | import sys
from unittest import TestCase, expectedFailure, skipIf
import pygame
from pgzero.loaders import sounds, set_root, UnsupportedFormat
pygame.init()
class SoundFormatsTest(TestCase):
"""Test that sound formats we cannot open show an appropriate message."""
@classmethod
def setUpClass(s... | orm == "win32", "This will crash on Windows")
def test_load_11kulaw(self):
self.assert_errmsg('w | av22kulaw', 'WAV audio encoded as .* µ-law')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp316(self):
self.assert_errmsg('wav8kmp316', 'WAV audio encoded as MP3')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp38(self)... |
debugger06/MiroX | osx/build/bdist.macosx-10.5-fat/python2.7-standalone/app/temp/objc/_objc.py | Python | gpl-2.0 | 540 | 0.007407 |
def __load():
import imp, os, sys
ext = 'objc/_objc.so'
for path in sys.path:
if not path.endswith('l | ib-dynload'):
continue
ext = os.path.join(path, ext)
if os.path.exists(ext):
#print "py2app extension module", __name__, "->", ext
| mod = imp.load_dynamic(__name__, ext)
#mod.frozen = 1
break
else:
raise ImportError(repr(ext) + " not found")
else:
raise ImportError("lib-dynload not found")
__load()
del __load
|
mozilla/verbatim | vendor/lib/python/translate/storage/zip.py | Python | gpl-2.0 | 2,203 | 0.001816 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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 t... | enerate all the storage objects
for unit in store.unit_iter():
yield unit
def scanfiles(self):
"""Populate the internal file data."""
self.filedata = []
self.archive = ZipFile(self.filename)
for completename in self.archive.name | list():
dir, name = path.split(completename)
self.filedata.append((dir, name))
|
antismap/MICshooter | sources/bonus.py | Python | mit | 1,158 | 0.000864 | import os
import common_pygame
import random
pygame = common_pygame.pygame
screen = common_pygame.screen
class Bonus():
def __init__(self, sounds, menu):
self.menu = menu
self.sounds = sounds
self.bonusType = 0
self.bonusAnim = 0
self.font = pygame.font.Font(None, 64)
... | str("plasma gun !"), True, (255, 255, 0)))
self.score = 0
self.bonuscount = 1
def ProcessBonus(self, ship):
# if ship.score %200 ==0 and ship.weapon==1 and ship.score>0:
if ship.score > 400 * self.bonuscount and self.score < 400 * self.bonuscount:
self.menu.pla... | self.bonusType = 0
self.bonusAnim = 30
self.score = ship.score
self.bonuscount = self.bonuscount + 1
if self.bonusAnim > 0:
self.bonusAnim = self.bonusAnim - 1
# show bonus for the plasma weapon
if self.bonusType == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.