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 |
|---|---|---|---|---|---|---|---|---|
isohybrid/dotfile | vim/bundle/git:--github.com-klen-python-mode/pylibs/pylint/checkers/misc.py | Python | bsd-2-clause | 2,594 | 0.003084 | # pylint: disable=W0511
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that... | __implements__ = IRawChecker
# configuration section name
name = 'miscellaneous'
msgs = MSGS
options = (('notes',
{'type' : 'csv', 'metavar' : '<comma separated values>',
'default' : ('FIXME', 'XXX', 'TODO'),
'help' : 'List of note tags to take in con... | }),
)
def __init__(self, linter=None):
BaseChecker.__init__(self, linter)
def process_module(self, node):
"""inspect the source file to found encoding problem or fixmes like
notes
"""
stream = node.file_stream
stream.seek(0)
# wa... |
ellmetha/django-machina | machina/test/factories/polls.py | Python | bsd-3-clause | 1,023 | 0 | import factory
import factory.django
from faker import Faker
from machina.core.db.models import get_model
from machina.test.factories.auth import UserFactory
from machina.test.factories.conversation import TopicFactory
faker = Faker()
Topi | cPoll = get_model('forum_polls', 'TopicPoll')
TopicP | ollOption = get_model('forum_polls', 'TopicPollOption')
TopicPollVote = get_model('forum_polls', 'TopicPollVote')
class TopicPollFactory(factory.django.DjangoModelFactory):
topic = factory.SubFactory(TopicFactory)
question = faker.text(max_nb_chars=200)
class Meta:
model = TopicPoll
class Topic... |
jhmatthews/panlens | constants.py | Python | gpl-2.0 | 1,157 | 0.057044 | import math as mth
import numpy as np
#----------------------
# J Matthews, 21/02
# This is a file containing useful constants for python coding
#
# Units in CGS unless stated
#
#----------------------
#H=6.62606957E-27
HEV=4.13620e-15
#C=29979245800.0
#BOLTZMANN=1.3806488E-16
VERY_BIG=1e50
H=6.6262e-27
HC=1.98587e-... | _OVER_M =7.96e8
ALPHA= 7.297351e-3 # Fine structure constant
BOHR= 0.529175e-8 # Bohr radius
CR= 3.288051e15 #Rydberg frequency for H != Ryd freq for infinite mass
ANGSTROM = 1.e-8 #Definition of an Angstrom in units of this code, e.g. cm
EV2ERGS =1.602192e-12
RADIAN= 57.29578
RYD2ERGS | =2.1798741e-11
PARSEC=3.086E18
|
KevinVDVelden/7DRL_2015 | Game/MapGen.py | Python | gpl-2.0 | 4,996 | 0.055244 | import math
import random
import GameData
from Util.TileTypes import *
from Util import Line, StarCallback
def initializeRandom( x, y ):
dist = math.sqrt( x ** 2 + y ** 2 )
angle = math.atan2( x, y ) / math.pi * 5
rand = ( random.random() * 7 ) - 3.5
val = ( ( dist + angle + rand ) % 10 )
if val ... | cb(-int( s * r ) + x0,-int( c * r ) + y0 )
r += 0.5
angle -= stepSize
def buildFixedWalls( self, I, _buffer, val ):
#Clear center room
centerX = int( self.width / 2 )
centerY = int( self.height / 2 )
for x in range( centerX - GameData.MapGen_CenterRoom_Size[0] - 1, ce... | centerY + GameData.MapGen_CenterRoom_Size[1] + 1 ):
_buffer[ I( x, y ) ] = 0
#Build center room walls
for x in range( centerX - GameData.MapGen_CenterRoom_Size[0] - 1, centerX + GameData.MapGen_CenterRoom_Size[0] + 1 ):
_buffer[ I( x, centerY - GameData.MapGen_CenterRoom_Size[1] - 1 ) ] = v... |
bjuvensjo/scripts | vang/nexus3/upload.py | Python | apache-2.0 | 1,766 | 0.003964 | #!/usr/bin/env python3
from argparse import Arg | umentParser
from os import environ
from sys import argv
from requests import put
def read_file(file_path): # pragma: no cover
with open(file_path, 'r | b') as f:
return f.read()
def upload(file_path, repository, repository_path, url, username, password):
url = f'{url}/repository/{repository}/{repository_path}'
data = read_file(file_path)
headers = {'Content-Type': 'application/octet-stream'}
response = put(url, data=data, headers=headers, aut... |
CaesarTjalbo/musictagger | mp3names/model_classes.py | Python | gpl-3.0 | 3,029 | 0.028722 | # -*- coding: utf-8 -*-
import sys
import os
import logging
import random
import PyQt4
from PyQt4.QtCore import *
#from PyQt4.QtCore import QAbstractTableModel
import constants
class Model(QAbstractTableModel):
keys = list()
modelType = None
def __init__(self, parent = None):
''' '''
... | #self.log.debug('rowCount end')
if hasattr(self, 'album') and self.album:
if hasattr(self.album, 'rows'):
return len(self.album.rows)
return 0
def columnCount(self, parent = None):
''' '''
#self.log.debug('columnCount start')
#self.log.de... | elf, index, role = None):
''' '''
#self.log.debug('data start')
if index.isValid():
if index.row() >= 0 or index.row() < len(self.rows):
if role == Qt.DisplayRole or role == Qt.ToolTipRole or role == Qt.EditRole:
return self.album.rows[index.row()... |
sschaetz/n5a | test/test_generate.py | Python | mit | 361 | 0.00831 | from | n5a import make_type
from n5a.generate import generate
from .test_definitions import get_pos3d_definition
def test_generate_string():
s = generate(get_pos3d_definition())
assert 'struct Pos3D' in s
def test_generate_file():
s = generate(get_pos3d_definition())
with | open('test/test_cpp/generated/pos3d.hpp', 'w') as f:
f.write(s) |
DragonQuiz/MCEdit-Unified | stock-filters/Forester.py | Python | isc | 51,634 | 0.000562 | # Version 5
'''This takes a base MineCraft level and adds or edits trees.
Place it in the folder where the save files are (usually .../.minecraft/saves)
Requires mcInterface.py in the same folder.'''
# Here are the variables you can edit.
# This is the name of the map to edit.
# Make a backup if you are experimenting... | ARIATION = 12
# Do you want branches, trunk, and roots?
# True makes all of that
# False does not create the trunk and br | anches, or the roots (even if they are
# enabled further down)
WOOD = True
# Trunk thickness multiplyer
# from zero (super thin trunk) to whatever huge number you can think of.
# Only works if SHAPE is not a "stickly" subtype
# Example:
# 1.0 is the default, it makes decently normal sized trunks
# 0.3 makes very thin ... |
chriscoyfish/coala-bears | bears/java/InferBear.py | Python | agpl-3.0 | 896 | 0 | import re
from coalib.bearlib.abstractions.Lint import Lint
from coalib.bears.LocalBear import LocalBear
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class InferBear(LocalBear, Lint):
executable = 'infer'
arguments = '-npb -- javac {filename}'
output_regex = re.compile(
r'(.+):'
... | AUTHORS_EMAILS = {'coala-devel@googl | egroups.com'}
LICENSE = 'AGPL-3.0'
ASCIINEMA_URL = 'https://asciinema.org/a/1g2k0la7xo5az9t8f1v5zy66q'
CAN_DETECT = {'Security'}
def run(self, filename, file):
'''
Checks the code with ``infer``.
'''
return self.lint(filename)
|
looker/sentry | src/sentry/debug/panels/redis.py | Python | bsd-3-clause | 2,952 | 0.000678 | from __future__ import absolute_import, unicode_literals
from django.template import Context, Template
from django.utils.translation import ugettext_lazy as _
from time import time
from .base import CallRecordingPanel
from . | .utils.function_wrapper import FunctionWrapper
from ..utils.patch_context import PatchContext
TEMPLATE = Template(
"""
{% load i18n %}
<h4>{% trans "Requests" %}</h4>
<table>
<thead>
<tr>
<th>{% tran | s "Duration" %}</th>
<th>{% trans "Command" %}</th>
<th>{% trans "Args" %}</th>
</tr>
</thead>
<tbody>
{% for call in calls %}
<tr>
<td>{{ call.duration }} ms</td>
<td>{{ call.command }}</td>
<td>{{ call.args }} {{ call.kwargs }... |
GoogleCloudPlatform/terraform-python-testing-helper | test/test_args.py | Python | apache-2.0 | 4,448 | 0.002248 | # Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t | o in writing, software
# distributed under the License is distribut | ed 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.
"Test the function for mapping Terraform arguments."
import pytest
import tftest
ARGS_TESTS = (
({'auto_approv... |
Williams224/davinci-scripts | ksteta3pi/Consideredbkg/MC_12_11134011_MagUp.py | Python | mit | 4,905 | 0.026911 | #-- GAUDI jobOptions generated on Mon Jul 20 10:20:49 2015
#-- Contains event types :
#-- 11134011 - 42 files - 900254 events - 251.92 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass Step-125836
#-- StepId : 125836
#-- StepName : Stripping20-NoPrescalingFlagged for Sim08... | 0046297/0000/00046297_00000025_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00046297/0000/00046297_00000026_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00046297/0000/00046297_00000027_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00046297/0000/00046297_00000029_2.AllStreams.dst',
'LFN:/lhcb/MC/2... | /2012/ALLSTREAMS.DST/00046297/0000/00046297_00000031_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00046297/0000/00046297_00000032_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00046297/0000/00046297_00000033_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00046297/0000/00046297_00000034_2.AllStreams... |
xkmato/casepro | casepro/contacts/migrations/0021_contact_is_stopped_pt1.py | Python | bsd-3-clause | 745 | 0.002685 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contacts', '0020_unset_suspend_from_dynamic'),
]
operat | ions = [
migrations.AddField(
model_name='contact',
name='is_stopped',
field=models.NullBooleanField(help_text='Whether this contact opted out of receiving messages'),
), |
migrations.AlterField(
model_name='contact',
name='is_stopped',
field=models.NullBooleanField(default=False,
help_text='Whether this contact opted out of receiving messages'),
),
]
|
matrix-org/synapse | synapse/replication/slave/storage/directory.py | Python | apache-2.0 | 767 | 0 | # Copyright 2015, 2016 OpenMarket Ltd
#
# 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/LIC | ENSE-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 WARRANTIE | S OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from synapse.storage.databases.main.directory import DirectoryWorkerStore
from ._base import BaseSlavedStore
class DirectoryStore(DirectoryWorkerStore, BaseS... |
DarkFenX/Pyfa | service/port/multibuy.py | Python | gpl-3.0 | 3,507 | 0.001426 | # =============================================================================
# Copyright (C) 2014 Ryan Holmes
#
# This file is part of pyfa.
#
# pyfa 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 v... | tem, item), itemAmount)
string = _prepareString(fit.ship.item, updatedAmounts)
callback(string)
priceSvc = sPrc.getInstance()
priceSvc.findCheaperReplacements(itemAmounts, formatCheaperExportCb)
else:
string = _prepareString(fit.ship.item, itemAmounts)
if cal... | tainer[item] += quantity
def _prepareString(shipItem, itemAmounts):
exportLines = []
exportLines.append(shipItem.name)
for item in sorted(itemAmounts, key=lambda i: (i.group.category.name, i.group.name, i.name)):
count = itemAmounts[item]
if count == 1:
exportLines.append(item.... |
Wakeupbuddy/pexpect | pexpect/replwrap.py | Python | isc | 4,604 | 0.002389 | """Generic wrapper for read-eval-print-loops, a.k.a. interactive shells
"""
import os.path
import signal
import sys
import re
import pexpect
PY3 = (sys.version_info[0] >= 3)
if PY3:
def u(s): return s
basestring = str
else:
def u(s): return s.decode('utf-8')
PEXPECT_PROMPT = u('[PEXPECT_PROMPT>')
PEXPEC... | :param cmd_or_spawn: This can either be an instance of :class:`pexpect.spawn`
in which a REPL | has already been started, or a str command to start a new
REPL process.
:param str orig_prompt: The prompt to expect at first.
:param str prompt_change: A command to change the prompt to something more
unique. If this is ``None``, the prompt will not be changed. This will
be formatted with the... |
bbsan2k/nzbToMedia | libs/beetsplug/badfiles.py | Python | gpl-3.0 | 4,564 | 0 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limi... | ght notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Use command-line tools to check for audio file corruption.
"""
from __future__ import division, absolute_import, print_function
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
fro... | tput, CalledProcessError, list2cmdline, STDOUT
import shlex
import os
import errno
import sys
class BadFiles(BeetsPlugin):
def run_command(self, cmd):
self._log.debug(u"running command: {}",
displayable_path(list2cmdline(cmd)))
try:
output = check_output(cmd, st... |
GoogleCloudPlatform/declarative-resource-client-library | python/services/monitoring/service.py | Python | apache-2.0 | 7,348 | 0.001225 | # Copyright 2022 Google LLC. 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 o... | .name)
if Primitive.to_proto(self.display_name):
request.resource.display_name = Primitive.to_proto(self.display_name)
if ServiceCustom.to_proto(self.custom):
request.resource.custom.CopyFrom(ServiceCustom.to_proto(self.cust | om))
else:
request.resource.ClearField("custom")
if ServiceTelemetry.to_proto(self.telemetry):
request.resource.telemetry.CopyFrom(
ServiceTelemetry.to_proto(self.telemetry)
)
else:
request.resource.ClearField("telemetry")
i... |
renner/spacewalk | backend/satellite_tools/reposync.py | Python | gpl-2.0 | 62,750 | 0.002343 | #
# Copyright (c) 2008--2018 Red Hat, Inc.
# Copyright (c) 2010--2011 SUSE Linux Products GmbH
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FO... | from rhnChannel c1 left outer join rhnChannel c2 on c1.parent_channel = c2.id
order by c2.label desc, c1.label asc
"""
h = rhnSQL.prepare(sql)
h.execute()
d_parents = {}
while 1:
row = h.fetchone_dict()
if not row:
break
if not b_only_custom or rhnC... | nel(row['id']):
parent_channel = row['parent_channel']
if not parent_channel:
d_parents[row['label']] = []
else:
# If the parent is not a custom channel treat the child like
# it's a pare |
MrWhoami/WhoamiBangumi | Youku.py | Python | mit | 1,140 | 0.00088 | # -*- coding:utf_8 -*-
import urllib2
from bs4 import BeautifulSoup
from Bangumi import Bangumi
class Youku(Bangumi):
link = "http://comic.youku.com"
name = u'优酷'
def getBangumi(self):
"""Youku processing function"""
# Get Youku bangumi HTML
req = urllib2.Request(self.link)
... | btitle = binfo.fin | d(class_="v-meta-title")
bname = btitle.find("a").string
blink = btitle.find('a')['href']
self.add(wd, bname, bupdate, blink)
|
philpot/tocayo | tocayoproj/tocayoapp/migrations/0008_auto_20151212_1607.py | Python | apache-2.0 | 455 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-12 | 16:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tocayoapp', '0007_gender_description'),
]
operations = [
migrations.AlterField(
model_name='gender',
name='description... | arField(max_length=15),
),
]
|
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/texture_swizzle.py | Python | lgpl-3.0 | 781 | 0.025608 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL | ._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GL_ARB_texture_swizzle'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GL,'GL_ARB_texture_swizzle',error_checker=_errors._error_checker)
GL_TEXTURE_SWIZZLE_A=_C('GL_TEX... | E_SWIZZLE_R=_C('GL_TEXTURE_SWIZZLE_R',0x8E42)
GL_TEXTURE_SWIZZLE_RGBA=_C('GL_TEXTURE_SWIZZLE_RGBA',0x8E46)
|
lifemapper/core | LmWebServer/flask_app/scenario.py | Python | gpl-3.0 | 3,342 | 0.00389 | """This module provides REST services for Scenario"""
import werkzeug.exceptions as WEXC
from LmCommon.common.lmconstants import HTTPStatus
from LmWebServer.common.lmconstants import HTTPMethod
from LmWebServer.services.api.v2.base import LmService
from LmWebServer.services.common.access_control import check_user_perm... | NotFound('Scenario {} not found'.format(scenario_id))
if check_user_permission(user_id, scn, HTTPMethod.GET):
return scn
else:
raise WEXC.Forbidden('User {} does not have permission to get scenario {}'.format(
user_id, scenario_id))
# .......................... | self, user_id, after_time=None, before_time=None, alt_pred_code=None, date_code=None,
gcm_code=None, epsg_code=None, limit=100, offset=0):
"""Return a list of scenarios matching the specified criteria"""
scn_atoms = self.scribe.list_scenarios(
offset, limit, user_id=us... |
dadosgovbr/ckanext-dadosabertos | ckanext/dadosgovbr/controllers/scheming.py | Python | agpl-3.0 | 12,430 | 0.001853 | # coding=utf-8
import logging
from urllib import urlencode
import datetime
import mimetypes
import cgi
from ckan.common import config
from paste.deploy.converters import asbool
import paste.fileapp
import ckan.logic as logic
import ckan.lib.base as base
import ckan.lib.i18n as i18n
import ckan.lib.maintain as maint... | tionError
check_access = logic.check_access
get_action = logic.get_action
tuplize_dict = logic.tuplize_dict
clean_dict = logic.clean_dict
parse_params = logic.parse_params
flatten_to_string_key = logic.flatt | en_to_string_key
lookup_package_plugin = ckan.lib.plugins.lookup_package_plugin
def _encode_params(params):
return [(k, v.encode('utf-8') if isinstance(v, basestring) else str(v))
for k, v in params]
def url_with_params(url, params):
params = _encode_params(params)
return url + u'?' + urlenco... |
deadRaccoons/TestAirlines | tabo/cherrypy/cherrypy/lib/static.py | Python | gpl-2.0 | 14,778 | 0 | import os
import re
import stat
import mimetypes
try:
from io import UnsupportedOperation
except ImportError:
UnsupportedOperation = object()
import cherrypy
from cherrypy._cpcompat import ntob, unquote
from cherrypy.lib import cptools, httputil, file_generator_limited
mimetypes.init()
mimetypes.types_map['... | tent_type, content_length, debug=False):
"""Internal. Set response.body to the given file object, perhaps ranged."""
response = cherrypy.serving.response
# HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code
request = cherrypy.serving.request
if request.protocol >= (1, 1):
res... | nse.headers['Content-Range'] = "bytes */%s" % content_length
message = ("Invalid Range (first-byte-pos greater than "
"Content-Length)")
if debug:
cherrypy.log(message, 'TOOLS.STATIC')
raise cherrypy.HTTPError(416, message)
if r:
... |
uclouvain/OSIS-Louvain | program_management/tests/ddd/service/read/test_get_program_tree_version_from_node_service.py | Python | agpl-3.0 | 2,219 | 0.003607 | # ############################################################################
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business i... | ###
from unittest import mock
from django.test import SimpleTestCase
from program_management.ddd import command
from program_management.ddd.domain.service.identity_search import ProgramTreeVersionIdentitySearch
from program_management.ddd.repositories.program_tree_version import ProgramTreeVersionRepository
from prog... | t(ProgramTreeVersionIdentitySearch, 'get_from_node_identity')
@mock.patch.object(ProgramTreeVersionRepository, 'get')
def test_domain_service_is_called(self, mock_domain_service, mock_repository_get):
cmd = command.GetProgramTreeVersionFromNodeCommand(code="LDROI1200", year=2018)
get_program_tre... |
Donkyhotay/MoonPy | twisted/protocols/sip.py | Python | gpl-3.0 | 41,973 | 0.003502 | # -*- test-case-name: twisted.test.test_sip -*-
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
"""Session Initialization Protocol.
Documented in RFC 2543.
[Superceded by 3261]
This module contains a deprecated implementation of HTTP Digest authentication.
See L{twisted.cred.cred... | idden: C{bool}
@ivar otherParams: Any other parameters in the header.
@type otherParams: C{dict}
"""
de | f __init__(self, host, port=PORT, transport="UDP", ttl=None,
hidden=False, received=None, rport=_absent, branch=None,
maddr=None, **kw):
"""
Set parameters of this Via header. All arguments correspond to
attributes of the same name.
To maintain compatib... |
crateio/crate.web | crate/web/history/models.py | Python | bsd-2-clause | 2,810 | 0 | from django.db import models
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from model_utils import Choices
from model_utils.models import TimeStampedModel
from crate.web.packages.... | ged("hidden"):
if instance.hidden:
e = Event.objects.create(
package=instance.release.package.name,
version=instance.release.version,
action=Event.ACTIONS.file_remove
)
if e is not None:
try:
e.data = {
... | filename,
"digest": instance.digest,
"uri": instance.get_absolute_url(),
}
except ValueError:
pass
else:
e.save()
|
Bobspadger/python-amazon-mws | tests/test_param_methods.py | Python | unlicense | 4,345 | 0.000921 | """
Testing for enumerate_param, enumerate_params, and enumerate_keyed_param
"""
import unittest
import mws
# pylint: disable=invalid-name
class TestParamsRaiseExceptions(unittest.TestCase):
"""
Simple test that asserts a ValueError is raised by an improper entry to
`utils.enumerate_keyed_param`.
"""
... | .1": "colorful",
"Summat.2": "cheery",
"Summat.3": "turkey",
"FooBaz.what.1": "singular",
"hot_dog.1": "something",
"hot_dog.2": "or",
"hot_dog.3": "other",
}
def test_keyed_params():
"""
Asserting the result through enumerate_keyed_param is as expected.
... | SellerSKU': 'Football2415',
# 'Quantity': 3},
# {'SellerSKU': 'TeeballBall3251',
# 'Quantity': 5},
# ...
# ]
# Returns:
# {
# 'InboundShipmentPlanRequestItems.member.1.SellerSKU': 'Football2415',
# 'InboundShipmentPlanRequestIt... |
fruitnuke/catan | tests.py | Python | gpl-3.0 | 714 | 0.001401 | from main import Board
import collections
import unittest
class ClassicBoardTests(unittest.TestCase):
def test_tile_iterator(self):
options = {
'randomize_production': False,
'randomize_ports': False}
board = Board(options)
| self.assertEqual([t.value for t in board.tiles if t.value], board._numbers)
hexes = collections.Counter([t.terrain for t in board.tiles])
self.assertEqual(hexes['F'], 4)
self.assertEqual(hexes['P'], 4)
self.assertEqual(hexes['H'], 4)
self.assertEqual(hexes['M'], 3)
... | .assertEqual(hexes['D'], 1)
if __name__ == '__main__':
unittest.main()
|
RobertIan/ethoStim | individualtesting/trial.py | Python | mit | 7,935 | 0.008696 | #! /usr/python
'''
///////////////////////////////////////////////////////////
// Permission is hereby granted, free of charge,
// to any person obtaining a copy of
// this software and associated documentation files
// (the "Software"), to deal in the Software without
// restriction, including without limitation... | , help="training round")
ap.add_argument("-fd", "--feed", help="feed with this stimulus",action="store_true")
ap.add_argument("-c", "--camera",help="do you want to record using this pi?",action="store_true")
ap.add_argument("-m:", "--startTime", help="time since epoch that you want to start your trial")
... | rgs = vars(ap.parse_args())
## parse trial details and pass it to the Trial class
if args.["feed"]:
T = Trial(args["presentedStim"], args["startTime"], 'feed')
else:
T = Trial(args["presentedStim"], args["startTime"], 'notfeed'))
T.checkPiIP()
T.whatStimulus()
T.videoFileName(a... |
biomodels/MODEL1310160000 | MODEL1310160000/model.py | Python | cc0-1.0 | 427 | 0.009368 | import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1310160000.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
| except ImportError:
return False
| else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractImpatientmtlreader533234643WordpressCom.py | Python | bsd-3-clause | 594 | 0.031987 |
def extractImpatientmtlreader53 | 3234643WordpressCom(item):
'''
Parser for 'impatientmtlreader533234643.wordpress.com'
'''
vol, chp, frag, postfix = extrac | tVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
retu... |
dangillet/cocos | samples/demo_multiple_scenes.py | Python | bsd-3-clause | 3,011 | 0.001993 | #
# cocos2d
# http://python.cocos2d.org
#
from __future__ import division, print_function, unicode_literals
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
import cocos
from cocos.director import directo... | ayer(cocos.layer.Layer):
def __init__(self):
super(TestLayer, self).__init__()
x, y = director.get_window_size()
sprite1 = Sprite('grossini.png')
sprite2 = Sprite('grossinis_sister1.png')
sprite3 = Sprite('grossinis_sister2.png')
| sprite1.position = (x // 2, y // 2)
sprite2.position = (x // 4, y // 2)
sprite3.position = (3 * x / 4.0, y // 2)
self.add(sprite2)
self.add(sprite1)
self.add(sprite3)
sprite1.do(RotateBy(360, 1) * 16)
sprite2.do(RotateBy(-360, 1) * 16)
sprite3.do(Rota... |
materials-commons/materialscommons.org | backend/scripts/admin/check_for_top_dir.py | Python | mit | 1,695 | 0.00295 | #!/usr/bin/env python
import rethinkdb as r
from optparse import OptionParser
def run(rql):
try:
return rql.run()
except r.RqlRuntimeError:
return None
def main(port, include_deleted):
conn = r.connect('localhost', port, db='materialscommons')
cursor = r.table('project2datadir') \
... | mat(owner))
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-P", "--port", dest="port", type="int", help="rethinkdb port", default=30815)
parser.add_option("-I", "--include-deleted", dest="incd", action="store_true", help="include deleted files", default=False)
|
(options, args) = parser.parse_args()
include_deleted = options.incd
port = options.port
print("Using database port = {}".format(port))
if include_deleted:
print("Including deleted files in search")
else:
print("Excluding deleted files from search")
main(port, include_del... |
petrutlucian94/nova | nova/tests/unit/api/openstack/compute/contrib/test_multiple_create.py | Python | apache-2.0 | 22,783 | 0.000088 | # Copyright 2013 IBM Corp.
# 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 app... | self.instance_cache_by_id = {}
self.instance_cache_by_uuid = {}
ext_info = plugins.LoadedExtensio | nInfo()
self.controller = servers_v21.ServersController(
extension_info=ext_info)
CONF.set_override('extensions_blacklist', 'os-multiple-create',
'osapi_v3')
self.no_mult_create_controller = servers_v21.ServersController(
extension_info=ext_info)... |
cgchemlab/chemlab | tools/convert_gromacs2espp.py | Python | gpl-3.0 | 4,036 | 0.005699 | #!/usr/bin/env | python
# Copyright (C) 2012,2013,2015(H),2016
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it und... | ESPResSo++ 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
# alon... |
ShivamSarodia/ShivC | rules.py | Python | gpl-2.0 | 15,247 | 0.00164 | """
The symbols and rules for the CFG of C. I generated these myself by hand, so
they're probably not perfectly correct.
"""
from rules_obj import *
from lexer import *
import tokens
### Symbols ###
# Most symbols are either self-explanatory, or best understood by examining the
# rules below to see how they're used.... | ny pointers on the first variable
declare_type_base = Rule(declare_type, [Token("type")])
declare_type_cont = Rule(declare_type, [declare_type, tokens.aster])
# used to separate declarations. all these are declare_separators:
# ,
# ,*
# , **
#
declare_separator_base = Rule(declare_separator, [tokens.comma])
declare_se... | = Rule(declare_expression, [declare_type, Token("name")])
# a non-array declaration with an assignment, like `int hello = 4` or `int* hello = &p`.
assign_declare = Rule(declare_expression, [declare_expression, tokens.equal, E], 49)
# an array declaration with assignment, like `int hi[4] = {1, 2, 3, 4}`.
# Note--I imagi... |
beeverycreative/beeconnect | WaitForConnection.py | Python | gpl-2.0 | 8,838 | 0.009391 | #!/usr/bin/env python3
"""
* Copyright (c) 2015 BEEVC - Electronic Systems This file is part of BEESOFT
* 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... | self.connected = self.beeCon.connected
#return True
else:
# USB Bu | ffer need cleaning
print('Printer not responding... cleaning buffer\n')
self.beeCmd.cleanBuffer()
self.beeCon.close()
self.beeCon = None
# return None
self.nextPu... |
ewan-klein/nltk_twitter | twokenise.py | Python | apache-2.0 | 6,480 | 0.013622 |
""" tokenizer for tweets! might be appropriate for other social media dialects too.
general philosophy is to throw as little out as possible.
development philosophy: every time you change a rule, do a diff of this
program's output on ~100k tweets. if you iterate through many possible rules
and only accept the ones t... | eft_RE = mycompile(EdgePunctLeft)
EdgePunctRight_RE= mycompile(EdgePunctRight)
def edge_punct_munge(s):
| s = EdgePunctLeft_RE.sub( r"\1\2 \3", s)
s = EdgePunctRight_RE.sub(r"\1 \2\3", s)
return s
def unprotected_tokenize(s):
return s.split()
if __name__=='__main__':
for line in open('tweets.txt'):
print(" ".join(tokenize(line[:-1])))
#for line in sys.stdin:
#print u" ".join(tokeni... |
JustusSchwan/MasterThesis | trash/utility_positional.py | Python | mit | 4,965 | 0.000604 | import numpy as np
import cv2
import math
# Calculates rotation matrix to euler angles
# The result is the same as MATLAB except the order
# of the euler angles ( x and z are swapped ).
def rot_vec_to_euler(r):
# Rotate around x axis by 180 degrees to have [0, 0, 0] when facing forward
R = np.dot(np.array([[1... | ize[1]
center = (img_size[1] / 2, img_size[0] / 2)
self.camera_matrix = np.array(
[[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]], dtype="double"
)
if self.rvec is None:
(success, self.rvec, self.tvec) = cv2.solve... | self.dist_coeffs, flags=cv2.SOLVEPNP_EPNP)
else:
(success, self.rvec, self.tvec) = cv2.solvePnP(
self.model_points, landmarks[self.image_points[:, np.newaxis], :],
self.camera_matrix, self.dist_coeffs, flags=cv2.SOLVEPNP_EPNP,
rvec=self.rvec, tvec=sel... |
cripplet/practice | hackerrank/quora/skeleton.py | Python | mit | 393 | 0.045802 | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
pass
def solve | (args, verbose=False):
r = proc_input(args)
def test():
assert(str_to_int('1 2 3') == [ 1, 2, 3 ])
if __name__ == '__main__':
| from sys import argv
if argv.pop() == 'test':
test()
else:
solve(list(fileinput.input()), verbose=True)
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractAtarutranslationBlogspotCom.py | Python | bsd-3-clause | 570 | 0.033333 |
def extractAtarutranslationBlogspotCom(item):
'''
Parser for 'atarutranslat | ion.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title' | ].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl... |
mkusz/invoke | tests/_support/deeper_ns_list.py | Python | bsd-2-clause | 212 | 0.023585 | from invoke import task, Collection
@task
def toplevel(ctx):
pass
@task
def subtas | k(ctx):
pass
ns = Collection(
toplevel,
Collection('a', subtask,
Collection('nother', subtask)
)
| )
|
potray/TFM-Web | tfm/migrations/0005_auto_20151124_1311.py | Python | gpl-2.0 | 467 | 0.002141 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tfm', '0004_auto_20151124_1307'),
]
operations = [
migrations.AlterField(
model_name='patient',
name='p... | |
uml-robotics/manus_arm | arm/src/arm/msg/_cartesian_moves.py | Python | bsd-2-clause | 9,235 | 0.015268 | """autogenerated by genpy from arm/cartesian_moves.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import arm.msg
import genpy
import std_msgs.msg
class cartesian_moves(genpy.Message):
_md5sum = "56c11a250225b8cc4f58b0e6670caaa1"
_type = "arm/car... | e
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
header,end,moves
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwd... | kwds)
#message fields cannot be None, assign default values for those that are
if self.header is None:
self.header = std_msgs.msg.Header()
if self.end is None:
self.end = genpy.Time()
if self.moves is None:
self.moves = []
else:
self.header = std_msgs.msg.Header... |
retrodpc/Bulbaspot-Cogs | sentry/sentry.py | Python | apache-2.0 | 11,849 | 0.005233 | # Ivysalt's sentry module. It keeps track of people who join and leave a chat.
# LICENSE: This single module is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
# @category Tools
# @copyright Copyright (c) 2018 dpc
# @version 1.1
# @author dpc
import asyncio
i... | print("Creating " + folder + " folder...")
os.makedirs(folder)
def check_files():
default = {}
if not os.path.isfile(joinleave_path):
print("Creating joinleave.json")
fileIO(joinleave_path, "save", default)
if not os.path.isfile(bans_path):
print("Creating bans.j... | ith open(joinleave_path) as joinleave_file:
joinleave_data = json.load(joinleave_file)
with open(bans_path) as sentry_file:
sentry_bans = json.load(sentry_file)
def save(path, data):
with open(path, "w") as file:
json.dump(data, file, indent=4)
class Sentry:
"""Adds various sentry commands.... |
DDMAL/Gamera | gamera/fudge.py | Python | gpl-2.0 | 2,585 | 0.001161 | # -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*-
# vim: set tabstop=3 shiftwidth=3 expandtab: |
#
# Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom,
# and Karl MacMillan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published b | y 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 Pub... |
c-w/GettyArt | getty_art/util.py | Python | mit | 488 | 0 | """Module for helper functions."""
import os
import tempfile
| def tmpfile(suffix='', prefix='tmp', directory=None):
"""Wrapper around tempfile.mkstemp that creates a new temporary file path.
"""
filehandle, filename = tempfile.mkste | mp(suffix, prefix, directory)
os.close(filehandle)
return filename
def expandpath(path):
"""Expands all the variables in a path.
"""
path = os.path.expandvars(path)
path = os.path.expanduser(path)
return path
|
ravselj/subliminal | subliminal/tests/test_subliminal.py | Python | mit | 8,711 | 0.002296 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import shutil
from unittest import TestCase, TestSuite, TestLoader, TextTestRunner
from babelfish import Language
from subliminal import list_subtitles, download_subtitles, save_subtitles, download_best_subtitles, scan_video... | )[1])[0]) + '.en.srt', 'w').close()
scanned_video = scan_video(os.path.join(TEST_DIR, os.path.split(video.name)[1]))
self.assertEqual(scanned_video.subtitle_languages, {Language('eng')})
def test_scan_video_subtitles_languages(self):
video = EPISODES[0]
open(os.path.join(TEST_DIR, o... | o.name)[1])[0]) + '.fr.srt', 'w').close()
open(os.path.join(TEST_DIR, |
Marocco2/EpicRace | update.py | Python | lgpl-3.0 | 2,289 | 0.004806 | from BOX.box_lib import requests
import os
import configparser
import traceback
import functools
import threading
configfile = os.path.join(os.path.dirname(__file__), 'EpicRace.ini')
config = configparser.ConfigParser()
config.read(configfile)
def async(func):
@functools.wraps(func)
def wrapper(*args, **kwar... | urn t
return wrapper
def log(log):
log = ('update: ' + str(log))
with open("apps\\python\\EpicRace\\log.txt", 'w') as h:
h.write(log)
h.close()
#@async
def update():
with open("apps\\python\\EpicRace\\sha.txt", 'r') as g:
sha = g.read()
g.close()
try:
br... | {'Accept': 'application/vnd.github.VERSION.sha'}
r = requests.get(check_link, headers=headers)
if r.text != sha: # Check if server version and client version is the same
with open("apps\\python\\EpicRace\\sha.txt", 'w') as j:
j.write(r.text)
j.close()
... |
asherwunk/objconfig | tests/writer/test_abstractwriter.py | Python | mit | 728 | 0.008242 | """
Test objconfig.writer.AbstractWriter |
"""
import pytest
from objconfig.exception import RuntimeException
from objconfig.writer import WriterInterface
from objconfig.writer import AbstractWriter
from objconfig import Config
import os
def test_methods_abstractwriter():
writer = AbstractWriter()
conf = Config({})
assert isinstance(writer,... | s.path.realpath(__file__)), "test"), conf)
with pytest.raises(RuntimeException):
writer.toString(conf)
os.remove(os.path.join(os.path.dirname(os.path.realpath(__file__)), "test"))
|
10clouds/edx-platform | common/djangoapps/enrollment/tests/test_api.py | Python | agpl-3.0 | 10,138 | 0.002071 | """
Tests for student enrollment.
"""
from mock import patch, Mock
import ddt
from django.core.cache import cache
from nose.tools import raises
import unittest
from django.test import TestCase
from django.test.utils import override_settings
from django.conf import settings
from course_modes.models import CourseMode
f... | Mode.modes_for_course') as mock_modes_for_course:
mock_course_modes = [Mock(slug=mode) for mode in course_modes]
mock_modes_for_course.return_value = mock_course_modes
# Enroll in the course and verify the URL we get sent to
result = api.add_enrollment(self.USERNAME, self... | self.assertIsNotNone(result)
self.assertEquals(result['student'], self.USERNAME)
self.assertEquals(result['course']['course_id'], self.COURSE_ID)
self.assertEquals(result['mode'], expected_mode)
@ddt.data(
['professional'],
['verified'],
['ver... |
beiko-lab/gengis | bin/Lib/site-packages/numpy/f2py/tests/test_array_from_pyobj.py | Python | gpl-3.0 | 21,255 | 0.017549 | import unittest
import os
import sys
import copy
import nose
from numpy.testing import *
from numpy import array, alltrue, | ndarray, asarray, can_cast,zeros, dtype
from numpy.core.multiarray import typeinfo
import util
wrap = None
def setup():
"""
Build the required testing extension module
"""
global wrap
# Check compiler availability first
if not util.has_c_compiler():
raise nose.SkipTes... | ay_from_pyobj_ext',
sources=['wrapmodule.c', 'fortranobject.c'],
define_macros=[])
"""
d = os.path.dirname(__file__)
src = [os.path.join(d, 'src', 'array_from_pyobj', 'wrapmodule.c'),
os.path.join(d, '..', 'src', 'for... |
voxie-viewer/voxie | ext/RawDataTestScript.py | Python | mit | 1,854 | 0.001618 | #!/usr/bin/python3
#
# Copyright (c) 2014-2022 The Voxie Authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... | ions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND | , EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#... |
zakandrewking/cobrapy | cobra/io/mat.py | Python | lgpl-2.1 | 11,174 | 0.000179 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
from collections import OrderedDict
from uuid import uuid4
from warnings import warn
from numpy import object as np_object
from numpy import array, inf, isinf
from six import string_types
from cobra.core import Metabolite, Model, Reaction
from... | f min(rxn_gene.shape) > 0:
for i, reaction in enumerate(model.reactions):
for gene in reaction.genes:
rxn_gene[i, model.genes.index(gene)] = 1
mat["rxnGeneMat"] = rxn_gene
mat["grRules"] = _cell(rxns.list_attr("gene_reaction_rule"))
mat["rxns"] = _cell(rxns.list_attr(... | ("name"))
mat["subSystems"] = _cell(rxns.list_attr("subsystem"))
mat["csense"] = "".join((
met._constraint_sense for met in model.metabolites))
stoich_mat = create_stoichiometric_matrix(model)
mat["S"] = stoich_mat if stoich_mat is not None else [[]]
# multiply by 1 to convert to float, work... |
ros/catkin | setup.py | Python | bsd-3-clause | 416 | 0 | from catkin_pkg.python_setup import generate_distutils_setup
from setuptools import setup
d = generate_distutils_setup(
packages=['catkin | '],
package_dir={'': 'python'},
scripts=[
'bin/catkin_find',
'b | in/catkin_init_workspace',
'bin/catkin_make',
'bin/catkin_make_isolated',
'bin/catkin_test_results',
'bin/catkin_topological_order',
],
)
setup(**d)
|
m00dawg/holland | plugins/holland.backup.mysqldump/holland/backup/mysqldump/plugin.py | Python | bsd-3-clause | 21,830 | 0.002199 | """Command Line Interface"""
import os
import re
import codecs
import logging
from holland.core.exceptions import BackupError
from holland.lib.compression import open_stream, lookup_compression
from holland.lib.mysql import MySQLSchema, connect, MySQLError
from holland.lib.mysql import include_glob, exclude_glob, \
... | = boolean(default=no)
file-per-database = boolean(default=yes)
additional-options = force_list(default=list())
estimate-method = string(default='plugin')
[compression]
method = option('none', 'gzip', 'gzip-rsyncable', 'pigz', 'bzip2', 'pbzip2', 'lzma', 'lzop', 'gpg', default='gzip')
options = string(default=... | = string(default=None)
password = string(default=None)
socket = string(default=None)
host = string(default=None)
port = integer(min=0, default=None)
""".splitlines()
class MySQLDumpPlugin(object):
"""MySQLDump Backup Plugin interface for Holland"... |
adityavagarwal/DonkeyKong | board.py | Python | mpl-2.0 | 19,483 | 0.00272 | __author__ = 'Aditya Vikram Agarwal'
import pygame
from random import randint
import random
import player
import princess
import donkey
import block
import fireball
import coin
import ladder
class Board:
def __init__(self, screen, testmode):
self.MODE = testmode
self.blocks = []
self.ladd... | ALF_LADDER_HEIGHT),
ladder.Ladder("Images/castleladder.png", "Images/castleladder.png", (220, 45),
self.LADDER_WIDTH, ((self.FULL_LADDER_HEIGHT - 5) * 2) / 3)
]
for | l in self.ladders:
x, y = l.getPosition()
w, h = l.getSize()
if h == self.FULL_LADDER_HEIGHT:
self.ladderlimits[l.getPosition()] = y + 1 + 60
else:
if h == ((self.FULL_LADDER_HEIGHT - 5) * 2) / 3:
self.ladderlimits[l.ge... |
carthagecollege/django-djforms | djforms/music/theatre/summer_camp/views.py | Python | unlicense | 3,884 | 0.002317 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from djforms.music.theatre.summer_camp import BCC, TO_LIST, REG_FEE
from djforms.processors.models import Contact, Order
from djforms.processors.forms import TrustCommerceForm
from djfor... | g = contact
sent = send_mail(
request, | TO_LIST,
'Music Theatre summer camp registration',
contact.email,
'music/theatre/summer_camp/registration_email.html',
order, BCC
)
order.send_mail = sent
order.save()
... |
srijanmishra/django-facebook | django_facebook/decorators.py | Python | mit | 2,793 | 0.003222 | import facebook
from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.conf import settings
... | a page is only accessed from within a facebook application.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# Make sure we're receiving a signed_request from facebook
if not request.POST.get('signed_request'):
return HttpRes | ponseBadRequest('<h1>400 Bad Request</h1><p>Missing <em>signed_request</em>.</p>')
# Parse the request and ensure it's valid
signed_request = request.POST["signed_request"]
data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY)
if data is Fals... |
nott/next.filmfest.by | modeladminutils/wagtail_hooks.py | Python | unlicense | 891 | 0 | from django.conf.urls import include, url
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core import urlresolvers
from django.utils.html import format_html
from wagtail.wagtailcore import hooks
from modeladminutils import admin_urls
@hooks.register('register_admin_urls')
def regi... | """
<script src="{0}"></script>
<script>window.chooserUrls.adminmodelChooser = '{1}';</script>
""",
static('modeladminutils/js/adminmodel-chooser.js'),
urlresolvers.reverse('modeladminutils:choose_adm | inmodel')
)
|
guescio/toolbox | searchPhaseTools.py | Python | gpl-2.0 | 2,268 | 0.019841 | #!/usr/bin/env python
#******************************************
#collection of handy tools when dealing with fits and search pahse
#******************************************
#import stuff
import sys, os, math, ROOT
#******************************************
def simpleFit(fileName, histDir, histName, hmin=1100., ... | le:
raise SystemExit('\n***ERROR*** couldn\'t find file: %s'%fileName)
if histDir != '':
hist = file.GetDirectory(histDir).Get(histName)
else:
hist = file.Get(histName)
if not hist:
raise SystemExit('\n** | *ERROR*** couldn\'t find hist: %s'%histName)
hist.Scale(1.,'width')
hist.GetXaxis().SetTitle('m [GeV]');
hist.GetYaxis().SetTitle('entries/GeV');#NOTE it's scaled
hist.SetMarkerColor(1);
hist.SetLineColor(1);
if draw is True:
c1 = ROOT.TCanvas('c1', 'c1', 100, 50, 800, 600)
c1... |
wattlebird/Bangumi_Spider | setup_bgmapi.py | Python | bsd-2-clause | 207 | 0.057971 | from setuptools import setu | p, find_packages
setup(
name = 'project',
version = '1.0',
packages = find_packages(),
entry_points = {'scrapy': ['settings = bgmapi.settin | gs']},
) |
Torkvamedo/smx | Homework/lesson 6/second.py | Python | unlicense | 414 | 0.01173 | data = [set(op | en(i).read().split()) for i in ('C:\\Users\\Aliwka\\Desktop\\ДЗ-курсы\\Homework6\\first.txt', 'C:\\Users\\Aliwka\\Desktop\\ДЗ-курсы\\Homework6\\second.txt')]
diff = data[0].difference(data[1])
if diff:
print(diff, 'слова кото | рые есть в первом файле, но нет во втором')
print(data[1],data[0],'слова из обоих файлов')
|
valdergallo/raidmanager | manager/apps.py | Python | mit | 107 | 0 | # enco | ding: utf-8
from django.apps import AppConfig
class ManagerConfig(AppConfig):
name = 'man | ager'
|
TheRealBanana/bLyrics | src/dialogs/logic/active_filtering_search.py | Python | gpl-2.0 | 4,055 | 0.008878 | # I'm pretty sure this idea is going to end up being a lot of code so its going in a separate file
#
# The idea is simple, don't create a new search tab but instead narrow down the library view as we type.
# Each letter typed should narrow down the library view instantly and without causing any interruption to the user... | anged(QString)"), lambda qstr: self.entryChanged(qstr, "artist"))
QtCore.QObject.connect(self.searchDialog.lyricsSearchStringInput, QtCore.SIGNAL("textChanged(QString)"), lambda qstr: self.entryChanged(qstr, "lyrics"))
def entryChanged(self, newstr, field):
print "EC: %s %s" % (newstr, field)
... | teFilters()
def updateFilters(self):
#All *Changed functions call this after adding thier new FilterOperationObject to filteropchain
pass
#Called when the very first filter object is created. We need to do things different with it since it iterates over
#the main library.
def chainInit... |
wearpants/osf.io | tests/test_addons.py | Python | apache-2.0 | 40,457 | 0.002027 | # -*- coding: utf-8 -*-
import time
import mock
import datetime
import unittest
from nose.tools import * # noqa
import httplib as http
import jwe
import jwt
import furl
import itsdangerous
from modularodm import storage, Q
from framework.auth import cas
from framework.auth import signing
from framework.auth.core im... | f-8'), settings.WATERBUTLER_JWE_SALT.encode('utf-8'))
def configure_addon(self):
self.user.add_addon('github')
self.user_addon = self.user.get_addon('github')
self.oauth_settings = GitHubAccountFactory( | display_name='john')
self.oauth_settings.save()
self.user.external_accounts.append(self.oauth_settings)
self.user.save()
self.node.add_addon('github', self.auth_obj)
self.node_addon = self.node.get_addon('github')
self.node_addon.user = 'john'
self.node_addon.repo... |
gizela/gizela | gizela/util/gama_data_fun.py | Python | gpl-3.0 | 1,739 | 0.00575 | # gizela
#
# Copyright (C) 2010 Michal Seidl, Tomas Kubin
# Author: Tomas Kubin <tomas.kubin@fsv.cvut.cz>
# URL: <http://slon.fsv.cvut.cz/gizela>
#
# $Id$
"""
module with functions for
gama-data-obs.py and gama-data-adj.py scripts
"""
import sys
def read_configuration_file(configFile, localSystem2D, localSyst... | []
localSystem = None
| if configFile is not None:
from gizela.util.parse_config_file import parse_config_file
try:
configDict = parse_config_file(configFile)
except Exception, e:
print >>sys.stderr, \
"Parsing of configuration file '%s' failed." % configFile
print... |
severr/severr-python | trakerr_client/models/app_event.py | Python | apache-2.0 | 18,881 | 0.000371 | # coding: utf-8
"""
Trakerr API
Get your application events and errors to Trakerr via the *Trakerr API*.
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file... | """
Gets the event_type of this AppEvent.
type or event or error (eg. NullPointerException)
:return: The event_type of this AppEvent.
:rtype: str
| """
return self._event_type
@event_type.setter
def event_type(self, event_type):
"""
Sets the event_type of this AppEvent.
type or event or error (eg. NullPointerException)
:param event_type: The event_type of this AppEvent.
:type: str
"""
sel... |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/bin/2.78/scripts/addons_contrib/data_overrides/util.py | Python | gpl-3.0 | 3,986 | 0.006021 | ### 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 distributed... | es a lot when running operators internally,
# disable since we only need one undo step after main operators anyway
self.use_global_undo = prefs.edit.use_global_undo
prefs.edit.use_global_undo = False
return (self.curact, self.cursel)
def __exit__(self, exc_type, exc_value, trac... | py.context.user_preferences
# restore active/selected state
scene.objects.active = self.curact
for ob in scene.objects:
ob.select = self.cursel.get(ob, False)
prefs.edit.use_global_undo = self.use_global_undo
def select_single_object(ob):
scene = bpy.context.scene
... |
jboissard/mathExperiments | toiletRoll.py | Python | apache-2.0 | 357 | 0.016807 | """
rel | ation between the length of material coiled around cylinder and its width (toilet paper)
http://math.stackexchange.com/questions/1633704/the-length-of-toilet-roll
"""
import numpy as np
x = 1 # width of one sheet
w = 80 #partial radius (total radius - minus radius of paper tube)
r = 30 # radius of paper tube
L = (n... | r)
print L |
PetePriority/home-assistant | homeassistant/components/velbus/binary_sensor.py | Python | apache-2.0 | 1,110 | 0 | """
Support for Velbus Binary Sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.velbus/
"""
import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.velbus import (
DOMAIN... | tities,
discovery_info=None):
"""Set u | p Velbus binary sensors."""
if discovery_info is None:
return
sensors = []
for sensor in discovery_info:
module = hass.data[VELBUS_DOMAIN].get_module(sensor[0])
channel = sensor[1]
sensors.append(VelbusBinarySensor(module, channel))
async_add_entities(sensors)
class Vel... |
MarsBighead/mustang | Python/somescript.py | Python | mit | 167 | 0.023952 | #!/usr/bin/python
import sys
t | ext = sys.stdin.read()
print 'Text:',text
words = text.split()
print 'Words: | ',words
wordcount = len(words)
print 'Wordcount:',wordcount
|
sailuh/perceive | Websites/Experiments/loginapp/migrations/0002_auto_20170205_1501.py | Python | gpl-2.0 | 427 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-05 15:01
from __future__ import unicode_literals
from django.db i | mport migrations
class Migration(migrations.Migration):
dependencies = [
( | 'loginapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='registration',
old_name='comments',
new_name='comment',
),
]
|
popazerty/dvbapp2-gui | lib/python/Plugins/SystemPlugins/SoftwareManager/plugin.py | Python | gpl-2.0 | 81,566 | 0.028676 | from Plugins.Plugin import PluginDescriptor
from Screens.Console import Console
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.Ipkg import Ipkg
from Screens.SoftwareUpdate import UpdatePlugin
fr... | can for local extensions and install them." ) + self.oktext, None))
for p in plugins.getPlugin | s(PluginDescriptor.WHERE_SOFTWAREMANAGER):
if p.__call__.has_key("SoftwareSupported"):
callFnc = p.__call__["SoftwareSupported"](None)
if callFnc is not None:
if p.__call__.has_key("menuEntryName"):
menuEntryName = p.__call__["menuEntryName"](None)
else:
menuEntryName = _('Extend... |
vortex-ape/scikit-learn | sklearn/model_selection/tests/test_split.py | Python | bsd-3-clause | 57,882 | 0.000017 | """Test the split module"""
from __future__ import division
import warnings
import pytest
import numpy as np
from scipy.sparse import coo_matrix, csc_matrix, csr_matrix
from scipy import stats
from itertools import combinations
from itertools import combinations_with_replacement
from sklearn.utils.testing import asser... | def fit(self, X, Y=None, sample_weight=None, class_prior=None,
sparse_sample | _weight=None, sparse_param=None, dummy_int=None,
dummy_str=None, dummy_obj=None, callback=None):
"""The dummy arguments are to test that this fit function can
accept non-array arguments through cross-validation, such as:
- int
- str (this is actually array-like)
... |
lukeexton96/Robotics | catkin_ws/build/commanding_velocity/catkin_generated/pkg.installspace.context.pc.py | Python | gpl-3.0 | 386 | 0 | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_P | ACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "co | mmanding_velocity"
PROJECT_SPACE_DIR = "/home/computing/catkin_ws/install"
PROJECT_VERSION = "0.0.0"
|
FrozenPigs/Taigabot | core/reload.py | Python | gpl-3.0 | 5,824 | 0.001545 | import collections
import glob
import os
import re
import sys
import traceback
if 'mtimes' not in globals():
mtimes = {}
if 'lastfiles' not in globals():
lastfiles = set()
def make_signature(f):
return f.func_code.co_filename, f.func_name, f.func_code.co_firstlineno
def format_plug(plug, kind='', lpa... | s[make_signature(func)].append(name)
for sig, names in sorted(commands.iteritems()):
names.sort(key=lambda x: (-len(x), x)) # long names first
out = ' ' * 6 + '%s:%s:%s' % sig
out += ' ' * (50 - len(out)) + ', '.join(names)
print out
... | continue
print ' {}:'.format(kind)
for plug in plugs:
try:
print format_plug(plug, kind=kind, lpad=6)
except UnicodeEncodeError:
pass
print
|
jamesturk/oyster | oyster/core.py | Python | bsd-3-clause | 10,992 | 0.000455 | import | datetime
i | mport logging
import hashlib
import random
import sys
import pymongo
import scrapelib
from .mongolog import MongoHandler
from .storage import engines
from celery.execute import send_task
class Kernel(object):
""" oyster's workhorse, handles tracking """
def __init__(self, mongo_host='localhost', mongo_port... |
slozier/ironpython2 | Tests/test_complex.py | Python | apache-2.0 | 2,104 | 0.008555 | # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import unittest
from iptest.type_util import *
from iptest import run_test
class ComplexTest(unittest.TestCase... | ertEqual(a-complex(), a)
self.assertEqual(a+complex(), a)
self.assertEqual(complex()/a, complex())
self.assertEqual(complex()*a, complex())
self.assertEqual(complex()%a, complex())
self.assertEqual(complex() // a, complex())
self.assertEqual(complex(2), complex(2, 0))
... | self.assertEqual(a.real, 2)
self.assertEqual(a.imag, 1)
def test_repr(self):
self.assertEqual(repr(1-6j), '(1-6j)')
def test_infinite(self):
self.assertEqual(repr(1.0e340j), 'infj')
self.assertEqual(repr(-1.0e340j),'-infj')
run_test(__name__)
|
ionelmc/python-redis-lock | tests/helper.py | Python | bsd-2-clause | 2,211 | 0.000905 | from __future__ import division
from __future__ import print_function
import logging
import os
import sys
import time
from redis import StrictRedis
from redis_lock import Lock
from conf import TIMEOUT
from conf import UDS_PATH
if __name__ == '__main__':
logging.basicConfig(
level=logging.DEBUG,
... | ap, ())
pids = []
for | _ in range(125):
pid = os.fork()
if pid:
pids.append(pid)
else:
try:
conn = StrictRedis(unix_socket_path=UDS_PATH)
sched.run()
finally:
os._exit(0)
for pid in pids:
... |
sfu-fas/coursys | oldcode/planning/views/view_capabilities.py | Python | gpl-3.0 | 1,166 | 0.002573 | from planning.models import TeachingCapability, PlanningCourse
from courselib.auth import requires_role
from coredata.models import Person
from django.shortcuts import render_to_response
from django.template import RequestContext
@requires_role('PLAN')
def | view_capabilities(request):
instructors = Person.objects.filter(role__role__i | n=["FAC", "SESS", "COOP"],
role__unit__in=request.units)
capabilities = []
for i in instructors:
capabilities.append(TeachingCapability.objects.filter(instructor=i))
capabilities_list = list(zip(instructors, capabilities))
courses = PlanningCourse.objects... |
hagenw/ltfat | mat2doc/mat/release_keep_tests.py | Python | gpl-3.0 | 654 | 0.010703 | print "Creating downloadable package"
# Remove unwanted files
s=os.path.join(conf.t.dir,'timing')
rmrf(s)
os.rmdir(s)
# R | ecursively remove the .git files
for root, dirs, files in os.walk(conf.t.dir, topdown=False):
for name in files:
if name in ['.gitattributes','.gitignore','desktop.ini']:
os.remove(os.path.join(root, nam | e))
# "bootstrap" the configure files
os.system("cd "+conf.t.dir+"/src; ./bootstrap")
s=os.path.join(conf.t.dir,'src','autom4te.cache')
rmrf(s)
os.rmdir(s)
# Compile the Java classes
os.system("cd "+conf.t.dir+"/blockproc/java; make")
os.system("cd "+conf.t.dir+"/blockproc/java; make classclean")
|
Distrotech/bzr | bzrlib/tests/per_workingtree/test_check.py | Python | gpl-2.0 | 2,606 | 0.000767 | # Copyright (C) 2009 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in ... | d)]),
set(tree._get_check_refs()))
def test__check_with_refs(self):
# _check can be called with a dict of the things required.
tree | = self.make_branch_and_tree('tree')
if not isinstance(tree, InventoryWorkingTree):
raise TestNotApplicable(
"_get_check_refs only relevant for inventory working trees")
tree.lock_write()
self.addCleanup(tree.unlock)
revid = tree.commit('first post')
n... |
ewbankkit/cloud-custodian | tools/c7n_mailer/c7n_mailer/azure_mailer/__init__.py | Python | apache-2.0 | 101 | 0.009901 | i | mport logging
logging.ge | tLogger('azure.storage.common.storageclient').setLevel(logging.WARNING)
|
sourcepole/qgis-wps-client | processingwps/WpsAlgorithm.py | Python | gpl-2.0 | 11,916 | 0.005874 | from __future__ import absolute_import
from builtins import str
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.Processing import Processing
from processing.core.ProcessingLog import ProcessingLog
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from p... | )
elif outputType == StringOutput:
self.addOutput(OutputString(str(output.identifier), str(output.title)))
def defineProcess(self):
"""Create the execute request"""
request = ExecutionRequest(self.process)
request.addExecuteRequestHeader()
| # inputs
useSelected = False
request.addDataInputsStart()
for input in self.process.inputs:
inputType = type(input)
value = self.getParameterValue(input.identifier)
if inputType == VectorInput:
layer = dataobjects.getObjectFromUri(value, False)... |
tst-mswartz/earthenterprise | earth_enterprise/src/server/wsgi/search/plugin/coordinate_search_handler.py | Python | apache-2.0 | 10,743 | 0.003165 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Copyright 2017 Google 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 re... | return search_status, | search_results
def ConstructKMLResponse(self, latitude, longitude):
"""Prepares KML response.
KML response has the below format:
<kml>
<Folder>
<name/>
<StyleURL>
---
</StyleURL>
<Point>
<coordinates/>
</Point>
</Folder>
... |
wesabe/fixofx | lib/ofxtools/csv_converter.py | Python | apache-2.0 | 14,873 | 0.004034 | # Copyright 2005-2010 Wesabe, 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 ... | , either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ofxtools.CsvConverter - translate CSV files into OFX files.
#
import datetime
import dateutil.parser
import ofx
import ofxtools
import re
import sys
import xml.sax.saxutils as sax
f... | def __init__(self, qif, colspec=None, fid="UNKNOWN", org="UNKNOWN",
bankid="UNKNOWN", accttype="UNKNOWN", acctid="UNKNOWN",
balance="UNKNOWN", curdef=None, lang="ENG", dayfirst=False,
debug=False):
self.qif = qif
self.colspec = colspec
... |
zwChan/VATEC | ~/eb-virt/Lib/encodings/iso2022_jp_1.py | Python | apache-2.0 | 1,100 | 0.006364 | #
# iso2022_jp_1.py: Python Unicode Codec for ISO2022_JP_1
#
# Written by Hye-Shik Chang <perky@FreeBSD.org>
#
import _codecs_iso2022, codecs
import _multibytecodec as mbc
codec = _codecs_iso2022.getcodec('iso2022_jp_1')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
c... | mentalEncoder(mbc.MultibyteIncrementalEncoder,
codecs.IncrementalEncoder):
codec = codec
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
codecs.IncrementalDecoder) | :
codec = codec
class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
codec = codec
class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
codec = codec
def getregentry():
return codecs.CodecInfo(
name='iso2022_jp_1',
encode=Codec()... |
geographika/mappyfile | docs/examples/geometry/geometry.py | Python | mit | 1,786 | 0.004479 | import os
from copy import deepcopy
from shapely.geometry import LineString
import mappyfile
import sys, os
sys.path.append(os.path.abspath("./docs/examples"))
from helper import create_image
def dilation(mapfile):
line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
ll = mappyfile.find(mapfil... | made to this layer only
pl2 = deepcopy(pl)
pl2["name"] = "newpolygon"
mapfile["layers"].append(pl2)
dilated = dilated.buffer(-0.3)
pl2["features"][0]["wkt"] = dilated.wkt
style = pl["classes"][0]["styles"][0]
style["color"] = "#9999 | 99"
style["outlinecolor"] = "#b2b2b2"
def main():
mf = "./docs/examples/geometry/geometry.map"
mapfile = mappyfile.open(mf)
mapfile["size"] = [600, 600]
output_folder = os.path.join(os.getcwd(), "docs/images")
dilated = dilation(mapfile)
create_image("dilated", mapfile, output_folder=outp... |
chenhh/PyMOGEP | src/PyMOGEP/decorator.py | Python | gpl-2.0 | 2,384 | 0.005872 | #-*-coding:utf-8-*-
'''
@author: Hung-Hsin Chen
@mail: chenhh@par.cse.nsysu.edu.tw
@license: GPLv2
'''
import functools
def symbol(sym):
'''
Decorator that assigns a symbol to a function.
The symbol is stored in the function.symbol attribute.
@param sym: symbol to a function
'''
def decorator(... | (self, memory_name)
# except AttributeError:
# # Haven't memoized anything yet
# memo = {}
# setattr(self, memo | ry_name, memo)
#
# try:
# return memo[key]
# except KeyError:
# # Haven't seen this key yet
# memo[key] = results = func(self, key)
# return results
# return decorator
|
alingse/panshell | panshell/core.py | Python | apache-2.0 | 2,543 | 0 | # coding=utf-8
from __future__ import print_function
import cmd
import inspect
import sys
from panshell.base import FS
class Shell(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.stack = []
self.fsmap = {}
self.fs = None
self._funcs = []
self._keyword... | prompt(self):
if self.fs:
return self.fs.prompt
return 'pansh$>'
def plugin(self, fscls, **setting):
if not issubclass(fscls, FS):
raise Exception('must inherit `panshell.base.FS`')
name = fscls.name
if name in self.fsmap:
raise Exceptio... | ng, fs)
def get_names(self):
"""
rewrite cmd.Cmd `dir(self.__class__)`
"""
return dir(self)
def __getattr__(self, name):
if name.startswith('do_'):
action = name[3:]
if action not in self._keywords:
return getattr(self.fs, name)
... |
kisom/crypto_intro | src/secretkey.py | Python | isc | 2,939 | 0 | # secretkey.py: secret-key cryptographic functions
"""
Secret-key functions from chapter 1 of "A Working Introduction to
Cryptography with Python".
"""
import Crypto.Cipher.AES as AES
import Crypto.Hash.HMAC as HMAC
import Crypto.Hash.SHA384 as SHA384
import Crypto.Random.OSRNG.posix as RNG
import pbkdf2
import streql... | ired, it means only
# a single \x80 is required.
padding_required = 15 - (len(data) % 16)
data = '%s\x80' % data
data = '%s%s' % (data, '\x00' * padding_required)
return data
def unpad_data(data):
"""unpad_data removes padding from the data."""
if not data:
return data
data... | trip('\x00')
if data[-1] == '\x80':
return data[:-1]
else:
return data
def generate_nonce():
"""Generate a random number used once."""
return RNG.new().read(AES.block_size)
def new_tag(ciphertext, key):
"""Compute a new message tag using HMAC-SHA-384."""
return HMAC.new(key, ... |
jucimarjr/IPC_2017-1 | lista02/lista02_exercicio01_questao05.py | Python | apache-2.0 | 883 | 0.002291 | # ----------------------------------------------------------
# Introdução a Programação de Computadores - IPC
# Univ | ersidade do Estado do Amazonas - UEA
# Prof. Jucimar Jr
# Edson de Lima Barros 1715310043
# Gabriel Nascimento de Oliveira 1715310052
# Luiz Daniel Raposo Nunes de Mello 1715310049
# Renan de Almeida Campos | 0825060036
# Tiago Ferreira Aranha 1715310047
# Wilbert Luís Evangelista Marins 1715310055
# Mackson Garcez Moreno de Oliveira júnior 1215090300
#
# 1.5. Faça um Programa que converta metros para centímetros.
# ----------------------------------------------------------
leng... |
oblique-labs/pyVM | rpython/rtyper/rstr.py | Python | mit | 35,786 | 0.000643 | from rpython.annotator import model as annmodel
from rpython.rlib import jit
from rpython.rtyper import rint
from rpython.rtyper.error import TyperError
from rpython.rtyper.lltypesystem.lltype import Signed, Bool, Void, UniChar
from rpython.rtyper.lltypesystem import lltype
from rpython.rtyper.rmodel import IteratorRep... | d_isdigit(self, hop):
string_repr = hop.args_r[0].repr
[v_str] = hop.inputargs(string_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_isdigit, v_str)
def rtype_method_isalpha(self, hop):
string_repr = hop.args_r[0].repr
[v_str] = hop.inputargs(... | string_repr = hop.args_r[0].repr
[v_str] = hop.inputargs(string_repr)
hop.exception_cannot_occur()
return hop.gendirectcall(self.ll.ll_isalnum, v_str)
def _list_length_items(self, hop, v_lst, LIST):
"""Return two Variables containing the length and items of a
list. Need to ... |
8l/beri | cheritest/trunk/tests/branch/test_raw_bltzall_lt_back.py | Python | apache-2.0 | 1,853 | 0.003238 | #-
# Copyright (c) 2011 Steven J. Murdoch
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed ... | legal/license-1-0.txt
#
# Unless required by applicable law or agreed to in writing, Work 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 unde... | aw_bltzall_lt_back(BaseBERITestCase):
def test_before_bltzall(self):
self.assertRegisterNotEqual(self.MIPS.a0, 0, "instruction before bltzall missed")
def test_bltzall_branch_delay(self):
self.assertRegisterEqual(self.MIPS.a1, 2, "instruction in brach-delay slot missed")
def test_bltzall_s... |
bcrochet/eve | eve/io/mongo/geo.py | Python | bsd-3-clause | 3,352 | 0 | # -*- coding: utf-8 -*-
"""
eve.io.mongo.geo
~~~~~~~~~~~~~~~~~~~
Geospatial functions and classes for mongo IO layer
:copyright: (c) 2017 by Nico | la Iarocci.
:license: BSD, see LICENSE for more details.
"""
class GeoJSON(dict):
def __init__(self, json):
try:
self['type'] = json['type']
except KeyError:
raise TypeError("Not compilant to GeoJSON")
self.update(json)
if len(self.keys()) != 2:
... |
def _correct_position(self, position):
return isinstance(position, list) and \
all(isinstance(pos, int) or isinstance(pos, float)
for pos in position)
class Geometry(GeoJSON):
def __init__(self, json):
super(Geometry, self).__init__(json)
try:
i... |
ssh1/stbgui | lib/python/Screens/InfoBarGenerics.py | Python | gpl-2.0 | 119,400 | 0.029414 | from ChannelSelection import ChannelSelection, BouquetSelect | or, SilentBouquetSelector
from Components.ActionMap | import ActionMap, HelpableActionMap
from Components.ActionMap import NumberActionMap
from Components.Harddisk import harddiskmanager
from Components.Input import Input
from Components.Label import Label
from Components.MovieList import AUDIO_EXTENSIONS, MOVIE_EXTENSIONS, DVD_EXTENSIONS
from Components.PluginComponent ... |
ysh329/wordsDB | mydef/def_get_ngram_2_db.py | Python | apache-2.0 | 6,600 | 0.01 | # -*- coding: utf-8 -*-
# !/usr/bin/python
################################### PART0 DESCRIPTION #################################
# Filename: def_get_ngram_2_db.py
# Description:
#
# Author: Shuai Yuan
# E-mail: ysh329@sina.com
# Create: 2015-8-17 22:17:26
# Last:
__author__ = 'yuens'
################################... | er-essence', '%s', 'ex')"""\
% (database_name, table_name, word, showtimes, len(word))\
)
con.commit()
except MySQLdb.Error, e:
con.rollback() |
logging.error("Failed in inserting %s gram word %s, which is existed."\
% (len(word), word))
logging.error("MySQL Error %d: %s." % (e.args[0], e.args[1]))
else: # exited word
id = id_tuple[0]
try:
cursor.execu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.