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
JoakimLindbom/ago
scheduler/scheduler.py
Python
gpl-3.0
7,085
0.005222
#!/usr/bin/python AGO_SCHEDULER_VERSION = '0.0.1' ############################################ """ Basic class for device and device group schedule """ __author__ = "Joakim Lindbom" __copyright__ = "Copyright 2017, Joakim Lindbom" __date__ = "2017-01-27" __credits__ = ["Joakim Lindbom", "The ago control ...
"], "value": r["value"]} #print x self.rules[seq] = x #print (seq, self.rules[seq]) def __str__(self): """Return a string representing content f the Rule object""" s = "na
me={}, uuid={}, type={}, # rules: {} ".format(self.name, self.uuid, self.type, len(self.rules)) return s def execute(self): results = [] for k, r in self.rules.iteritems(): if r["type"] == "variable check": if r["variable"] == "HouseMode": vv ...
nharrer/kodi-update-movie-dateadded
update_movie_dateadded.py
Python
mit
5,104
0.005094
import sys import os import re import time import datetime from contextlib import closing # --------------------------------------------------- # Settings # --------------------------------------------------- # IMPORTANT: In the standard case (sqlite3) just point this to your own MyVideos database. DATABA...
ormat(id, date
added, dateadded_new, fullpath)) with closing(conn.cursor()) as cursor: cursor.execute("UPDATE files SET dateAdded = '{0}' WHERE idFile = {1}".format(dateadded_new, id)) conn.commit() else: if VERBOSE: print('idFile {0}: Date OK. DB date {1} matc...
Etzeitet/pythonjournal
pythonjournal/proptest.py
Python
gpl-2.0
953
0.012592
#!/usr/local/bin/python3 class TestClass(object): def foo(): doc = "The foo property." def fget(self): return self._foo def fset(self, value): self._foo = value def fdel(self): del self._foo return locals() foo = property(**foo()) ...
self.foo = "foo" self.bar = "bar" def test_method(self, attr): if attr == 1: prop = self.foo else: prop = self.bar print(prop) prop = 'TADA!' tc = TestClass(1,2
) print(tc.foo) print(tc.bar) tc.test_method('foo') #print(tc.foo) #print(dir(tc))
rooi/CouchPotatoServer
couchpotato/core/notifications/trakt/main.py
Python
gpl-3.0
1,553
0.010947
from couchpotato.core.logger import CPLog from couchpotato.core.notifications.base import Notification log = CPLog(__name__) class Trakt(Notification): urls = { 'base': 'http://api.trakt.tv/%s', 'library': 'movie/library/%s', 'unwatchlist': 'movie/unwatchlist/%s', } listen_to = [...
{} post_data = { 'username': self.conf('automation_username'),
'password' : self.conf('automation_password'), 'movies': [{ 'imdb_id': data['library']['identifier'], 'title': data['library']['titles'][0]['title'], 'year': data['library']['year'] }] if data else [] } result = self.call((self.ur...
jdegene/ArcGIS-scripts
SMOS.py
Python
mit
2,615
0.008413
""" Uses a folder full of SMOS *.dbl files, converts them with the ESA snap command line tool pconvert.exe to IMG Uses then arcpy to to convert IMG to GeoTIFF and crops them in the process to a specified extent and compresses them """ import os, subprocess, shutil import arcpy from arcpy import env from arcpy.sa i...
creationflags=0x08000000) subP.wait() # console subprocess sometimes throws error and no output is generated -> skip file & print name try: raster = Raster(imgFol + dblFile[:-3] + "data/" + "Soil_Moisture.img") except: print dblFile[:-3] continue ...
o new folder, only honoring above extent, converting to GeoTiff, -999 is nodata arcpy.CopyRaster_management(raster, tifFol + dblFile[:-3] + "tif", "DEFAULTS","-999", "-999") # try to delete Files from imgFol (*.data is recognized as folder -> shutil) for x in os.listdir(imgFol): ...
openprocurement/openprocurement.tender.belowthreshold
openprocurement/tender/belowthreshold/tests/award.py
Python
apache-2.0
14,334
0.003084
# -*- coding: utf-8 -*- import unittest from copy import deepcopy from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.adapters import TenderBelowThersholdConfigurator from openprocurement.tender.belowthreshold.tests.base import ( TenderContentWebTest, test_bids, tes...
create_tender_lot_award_complaint, patch_tender_lot_award_complaint, get_tender_lot_award_complaint, get_tender_lot_award_complaints, # Tender2LotAwardComplaintResourceTest create_tende
r_lots_award_complaint, patch_tender_lots_award_complaint, # TenderAwardComplaintDocumentResourceTest not_found, create_tender_award_complaint_document, put_tender_award_complaint_document, patch_tender_award_complaint_document, # Tender2LotAwardComplaintDocumentResourceTest create_tende...
technoarch-softwares/linkedin-auth
setup.py
Python
bsd-2-clause
1,410
0.002128
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) install_requires = [ 'requests==2.8.1...
Django', 'Framework :: Django :: 1.8', # replace "X.Y" as appropriate 'Intended Audience :: Develope
rs', 'License :: OSI Approved :: BSD License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', # Replace these appropriately if you are stuck on Python 2. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3...
ebraunkeller/kerouac-bobblehead
ProcessAttendance.py
Python
mit
1,977
0.02782
# Process the attendance data by adding fields for day of week and school year and reoder the fields # so that they match the enrollment file: date, lasid, status (ABS), day, school year # also, clean the bad data. Many absence records are on days not in the calendar. Check the date # of the absence against the cale...
plit("/")[0].zfill(2)+"/"+date.split("/")[1].zfill(2)+"/"+date.split("/")[2] def schoolyear(date): if int(date.split("/")[0]) <8 : return date.split("/")[2] else: return str(int(date.split("/")[2])+1) def calday(date): cal_date = datetime.strptime(date_func(date),'%m/%d/%Y') return cal_dat...
Attend.csv" CalendFile ="C:\Users\Elaine\Documents\BKL\Lowell\\2016-2017\NewCalendar.csv" csvfile=open(AttFile,'rb') reader=csv.reader(csvfile) Ccsvfile = open(CalendFile,'rb') Creader = csv.reader(Ccsvfile) with open(OutFile,'a+b') as csvout: wr=csv.writer(csvout,delimiter=',') wr.writerow(['Date...
sharad/calibre
src/calibre/ebooks/oeb/transforms/rasterize.py
Python
gpl-3.0
9,021
0.002771
''' SVG rasterization transform. ''' from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' import os, re from urlparse import urldefrag from lxml import etree from PyQt5.Qt import ( Qt, QByteArray, QBuffer, QIODevice, QColor, QImage, QPa...
lf.images: href = self.images[key] else: logger = self.
oeb.logger logger.info('Rasterizing %r to %dx%d' % (svgitem.href, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) ...
D4wN/brickv
src/build_data/windows/OpenGL/GL/EXT/separate_shader_objects.py
Python
gpl-2.0
2,874
0.022617
'''OpenGL extension EXT.separate_shader_objects This module customises the behaviour of the OpenGL.raw.GL.EXT.separate_shader_objects to provide a more Python-friendly API Overview (from the spec) Prior to this extension, GLSL requires multiple shader domains (vertex, fragment, geometry) to be linked into a sin...
ling with user-defined varyings. The hope is a future extension will improve this situation. The official definition of this exte
nsion is available here: http://www.opengl.org/registry/specs/EXT/separate_shader_objects.txt ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.EXT.separate_shader_objects import * ### END AUTOGENERATED SECTIO...
uw-it-aca/scout-vagrant
provisioning/templates/sample.wsgi.py
Python
apache-2.0
1,364
0.002199
""" WSGI config for server_proj project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATIO...
ht make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import site site.addsitedir('/path/to/
spacescout_builds/server_proj/lib/python2.6/site-packages') site.addsitedir('/path/to/spacescout_builds/server_proj') #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server_proj.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "server_proj.settings" # This application object is used by any WSGI server configured t...
MikeMitterer/dart-mdl-mustache
test/no_spec/whitespace.py
Python
bsd-2-clause
760
0.040789
import pystache def render(source, values): print pystache.render(source, values) render( "{{ # # foo }} {{ oi }} {{ / # foo }}", {'# foo': [{'oi': 'OI!'}]}) # OI! rende
r( "{{ #foo }} {{ oi }} {{ /foo }}", {'foo': [{'oi': 'OI!'}]}) # OI! render( "{{{ #foo }}} {{{ /foo }}}", {'#foo': 1, '/foo': 2}) # 1 2 render( "{{{ { }}}", {'{': 1}) # 1 render( "{{ > }}}",
{'>': 'oi'}) # "}" bug?? render( "{{\nfoo}}", {'foo': 'bar'}) # // bar render( "{{\tfoo}}", {'foo': 'bar'}) # bar render( "{{\t# foo}}oi{{\n/foo}}", {'foo': True}) # oi render( "{{{\tfoo\t}}}", {'foo': True}) # oi # Don't work in mustache.js # render( # "{{ { }}", # {'{': 1}) # ERROR unclosed tag # re...
imajes/Sick-Beard
sickbeard/nzbget.py
Python
gpl-3.0
6,926
0.00361
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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 t...
", 'ignore')) if nzbGetRPC.writelog("INFO", "SickBeard connected to drop off " + nzb_filename + " any moment now."): logger.log(u"Successful connected to NZBGet", logger.DEBUG) else: logger.log(u"Successful connected to NZBGet, but unable to send a message", logger.ERROR) ...
logger.log(u"Please check if NZBGet is running. NZBGet is not responding.", logger.ERROR) return False except xmlrpclib.ProtocolError, e: if (e.errmsg == "Unauthorized"): logger.log(u"NZBGet username or password is incorrect.", logger.ERROR) else: logger...
thasso/pyjip
jip/scripts/__init__.py
Python
bsd-3-clause
1,603
0
#!/usr/bin/env python """This module contains a set of default tools that are deployed with jip """ import jip @jip.tool("cleanup") class cleanup(object): """\ The cleanup tool removes ALL the defined output files of its dependencies. If you have a set of intermediate jobs, you can put this as a final...
help] Options: --help Show this help message -c, --cmd <cmd>... The command to run Inputs: -i, --input <input> The input file to read [default: stdin]
Outputs: -O, --outfile <outfile> The output file -o, --output <output> The output file to write [default: stdout] """ def get_command(self): return "bash", """(${cmd})${output|arg("> ")}"""
UpSea/midProjects
BasicOperations/00_Python/00_Python_05_Deco01.py
Python
mit
772
0.032051
''' mid 此例展示带参数的装饰器如何装饰带参数的函数 此时,装饰器的参数,被装饰的函数,被装饰函数的参数都有确定的传递位置 ''' def d(argDec): #1) 装饰器的参数 def _d(funcDecored): #2) 被装饰函数 def __d(*arg, **karg): #3
) 被装饰函数的参数
print (argDec) print("do sth before decored func..") r= funcDecored(*arg, **karg) print("do sth after decored func..") return r return __d return _d @d("first") def func01(): print("call func01") @d("second") def func02(a, b=2): print("c...
Robbie1977/NRRDtools
test.py
Python
mit
436
0.025229
# Create the data. from numpy import pi, s
in, cos, mgrid dphi, dtheta = pi/250
.0, pi/250.0 [phi,theta] = mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta] m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4; r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7 x = r*sin(phi)*cos(theta) y = r*cos(phi) z = r*sin(phi)*sin(theta) # View it. from mayavi import ml...
katakumpo/niceredis
tests/test_scripting.py
Python
mit
2,723
0
from __future__ import with_statement import pytest from redis import exceptions from redis._compat import b multiply_script = """ local value = redis.call('GET', KEYS[1]) value = tonumber(value) return value * ARGV[1]""" class TestScripting(object): @pytest.fixture(autouse=True) def reset_scripts(self, r):...
ipt_flush() assert r.script_exists(sha) ==
[False] r.script_load(multiply_script) assert r.script_exists(sha) == [True] def test_script_object(self, r): r.set('a', 2) multiply = r.register_script(multiply_script) assert not multiply.sha # test evalsha fail -> script load + retry assert multiply(keys=[...
edx-solutions/edx-platform
openedx/core/lib/xblock_builtin/xblock_discussion/xblock_discussion/__init__.py
Python
agpl-3.0
12,281
0.002931
# -*- coding: utf-8 -*- """ Discussion XBlock """ import logging import six from six.moves import urllib from six.moves.urllib.parse import urlparse # pylint: disable=import-error from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from django.utils.translation import ge...
course id NB: The goal is to move this XBlock out of edx-platform, and so we use scope_ids.usage_id instead
of runtime.course_id so that the code will continue to work with workbench-based testing. """ return getattr(self.scope_ids.usage_id, 'course_key', None) @property def django_user(self): """ Returns django user associated with user currently interacting with the...
ColinDuquesnoy/QCrash
tests/test_dialogs/test_review.py
Python
mit
455
0
from qcrash._dialogs.review import DlgReview def test_review(qtbot): dlg = DlgReview('some content', 'log content', None, None) assert dlg.ui.edit_main.toPlainText() == 'some content'
assert dlg.ui.edit_log.toPlainText() == 'log content' qtbot.keyPress(dlg.ui.edit_main, 'A') assert dlg.ui.edit_main.toPlainText() == 'Asome content' qtbot.keyPress(dlg.ui.edit_log, 'A') assert dlg.ui.edit_
log.toPlainText() == 'Alog content'
lichong012245/django-lfs-0.7.8
lfs/marketing/models.py
Python
bsd-3-clause
1,567
0
# django imports from django.db import models from django.utils.translation import ugettext_lazy as _ # lfs imports from lfs.catalog.models import Product from lfs.order.models import Order class Topseller(models.Model): """Selected products are in any case among topsellers. """ product = models.ForeignK...
shop owner """ product = models.ForeignKey(Product, verbose_name=_(u"Product")) position = models.PositiveSmallIntegerField(_(u"Position"), default=1) active = models.BooleanField(_(u"Active"), default=True) class Meta: ordering = ["position"] def __unicode__(self): return "%s...
""" order = models.ForeignKey(Order, verbose_name=_(u"Order")) send_date = models.DateTimeField(auto_now=True) def __unicode__(self): return "%s (%s)" % (self.order.id, self.rating_mail_sent)
nachiketkarmarkar/XtremPerfProbe
generatePlots.py
Python
mit
6,181
0.015046
import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plot import matplotlib.pylab from matplotlib.backends.backend_pdf import PdfPages import re def drawPlots(data,plotObj,name,yLabel,position): drawing = plotObj.add_subplot(position,1,position) drawing.set_ylabel(yLabel, font...
'_rate_average', name): plotName = 'Bandwidth Utilization' drawPlots(data,hba_bw,name,"Bandwidth Utilization", hbaBwInit+1) if re.search('Storage_adapter%s'%(hba), name) and re.search(r'_latency_average', name): plotName = 'Latency' drawPlots(d...
savefig(hba_bw) pdfDoc.savefig(cpu) pdfDoc.savefig(memory) pdfDoc.close() plot.close(hba_iops) plot.close(hba_bw) plot.close(hba_latency) plot.close(cpu) plot.close(memory) # plot.show() def main(): drawXtremIOCharts() # data = np.genfromtxt('xtremPerfStats.csv', dtype=float...
scanny/python-pptx
pptx/enum/action.py
Python
mit
1,548
0.000646
# encoding: utf-8 """ Enumerations that describe click action settings """ from __future__ import absolute_import from .base import alias, Enumeration, EnumMember @alias("PP_ACTION") class PP_ACTION_TYPE(Enumeration): """ Specifies the type of a mouse action (click or hover action). Alias: ``PP_ACTION...
ry/office/ff744895.aspx" __members__ = ( EnumMember("END_SHOW", 6, "Slide show ends."), EnumMember("FIRST_SLIDE", 3, "Returns to the first slide."), EnumMember("HYPERLINK", 7, "Hyperlink."), EnumMember("LAST_SLIDE", 4, "Moves to the last slide."), EnumMember("LAST_SLIDE_VIEW...
es to slide specified by slide number."), EnumMember("NAMED_SLIDE_SHOW", 10, "Runs the slideshow."), EnumMember("NEXT_SLIDE", 1, "Moves to the next slide."), EnumMember("NONE", 0, "No action is performed."), EnumMember("OPEN_FILE", 102, "Opens the specified file."), EnumMember("O...
Orav/kbengine
kbe/src/lib/python/Lib/test/test_opcodes.py
Python
lgpl-3.0
2,787
0.011123
# Python test set -- part 2, opcodes from test.support import run_unittest import unittest class OpcodeTest(unittest.TestCase): def test_try_inside_for_loop(self): n = 0 for i in range(10):
n = n+i try: 1/0 except NameError: pass
except ZeroDivisionError: pass except TypeError: pass try: pass except: pass try: pass finally: pass n = n+i if n != 90: self.fail('try inside for') def test_raise_class_exceptions(self): class AClass...
Tesora/tesora-project-config
tools/check_irc_access.py
Python
apache-2.0
5,790
0.000173
#! /usr/bin/env python # Copyright 2011, 2013-2014 OpenStack Foundation # Copyright 2012 Hewlett-Packard Development Company, 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://...
self.failed = True print("%s does not have permissions on %s:" % (self.nick, self.current_channel)) for nick, flags, msg in self.current_list: print(msg) print # If this is the first channel checked, set the failure ...
d = False self.current_channel = None self.advance() return parts = msg.split() self.current_list.append((parts[1], parts[2], msg)) def main(): parser = argparse.ArgumentParser(description='IRC channel access check') parser.add_argument('-l', dest='config', ...
qadium-memex/linkalytics
linkalytics/factor/constructor/merge.py
Python
apache-2.0
603
0.014925
from . elasticfactor import ElasticFactor from ... environment import cfg from elasticsearch import Elasticsearch def run(node): id_a, id_b = node.get('id_a', '63166071_1'), node.get('id_b', '63166071_2') es = Elasticsearch() data_a = es.get(index="factor_state2016", doc_type='factor
_network', id=id_a) data_b = es.get(index="factor_state2016", doc_type='factor_network', id=id_b) const
ructor = ElasticFactor(cfg["cdr_elastic_search"]["hosts"] + cfg["cdr_elastic_search"]["index"]) merged = constructor.merge(data_a["_source"], data_b["_source"]) return merged
antivirtel/Flexget
flexget/_version.py
Python
mit
453
0.004415
""" Current FlexGet version. T
his is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by release scripts in continuous integration. Should (almost) never be set manually. The version should always be set to the <next release version>.dev The jenkins release job will automatically strip the .de...
1.2.500.dev'
obmarg/pypod
feed.py
Python
bsd-2-clause
6,209
0.015139
#!/usr/bin/python import feedparser import os import pickle import logging from episode import Episode log = logging.getLogger() class Feed: """ Class representing a single podcast feed """ def __init__( self, name, url, destPath, episodes, ...
Episode( self, name ): """ Checks if an episode has already been download Params: name - The name of the episode to look for Returns True or False """ return any( True for e in self.episodes if e.name == name ) d...
tries: if not self.HasEpisode( entry.title ): epUrl = self.GetDownloadUrl( entry ) if not epUrl: continue self.AddToDownloadList( epUrl, entry.title, self.MakeEpisod...
birkin/dashboard
config/urls.py
Python
mit
1,021
0.026445
from dashboard_app import views from django.conf.urls import include, url from django.contrib i
mport admin from django.views.generic import RedirectView admin.autodiscover(
) urlpatterns = [ ## primary app urls... url( r'^info/$', views.info, name='info_url' ), url( r'^widgets/$', views.widgets_redirect, name='widgets_redirect_url' ), url( r'^widgets/(?P<identifier>[^/]+)/$', views.widgets, name='widgets_url' ), url( r'^widget_detail/(?P<identifier>[^/]+)/$', vie...
JunctionAt/JunctionWWW
blueprints/player_profiles/views/admin_reset.py
Python
agpl-3.0
1,619
0.002471
from flask_wtf import Form from wtforms import HiddenField, StringField from wtforms.validators import InputRequired, EqualTo from flask_login import current_user, abort, login_required from flask import r
equest, flash, redirect, render_template import random import bcrypt from models.user_model import User from .. import blueprint class ResetForm(Form): who = HiddenField()
confirm_who = StringField('Confirm Username', validators=[InputRequired(), EqualTo('who')]) @blueprint.route("/reset/<what>", methods=["POST"]) @login_required def reset(what): if not current_user.has_permission('reset.{}'.format(what)): a...
pinakinathc/python_code
movies/entertainment_center.py
Python
gpl-3.0
1,497
0.028724
import media import fresh_tomatoes toy_story=media.Movie( "Toy Story", "A story of a boy and his toys that come to life", "http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/watch?v=vwyZH85NQC4") #print (toy_story.storyline) avatar=media.Movie( "Avatar", "A marine on an alien...
ie( "Midnight in PAris", "Going back in time to meet authors", "http://upload.wikime
dia.org/wikipedia/em/9/9f/Midnight_in_paris_Poster.jpg", "https://www.youtube.com/watch?v=atLg2wQQxuU") hunger_games=media.Movie( "Hunger Games", "A really real reality show", "http://upload.wikimedia.org/wikipedia/en/4/42/Hunger-GamesPoster.jpg", "https://www.youtube.com/watch?v=PbA63a7HObo") movies=[toy_story...
Ritsyy/fjord
fjord/base/tests/test_views.py
Python
bsd-3-clause
5,907
0
import json from django.test.utils import override_settings import pytest from pyquery import PyQuery from fjord.base import views from fjord.base.tests import ( LocalizingClient, TestCase, AnalyzerProfileFactory, reverse ) from fjord.base.views import IntentionalException from fjord.search.tests imp...
ttr['href'] == '/ou812' def test_sanitized_next_url(self): self.client_login_user(self.jane) url = reverse('new-user-view') resp = self.client.get(url, { 'next': 'javascript:prompt%28document.cookie%29' }) assert resp.status_code == 200 self.assertTemplat...
next_url = pq('#next-url-link') assert next_url.attr['href'] == '/en-US/' # this is the dashboard
rayhu-osu/vcube
crowdshipping/urls.py
Python
mit
178
0.039326
from dj
ango.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^contact/$', views.contact, na
me = 'contact'), ]
faribas/RMG-Py
unittest/qm/qmverifierTest.py
Python
mit
1,393
0.015793
""" Created on May 17, 2012 @author: nmvdewie """ import unittest import rmgpy.qm.qmtp as qm import os import rmgpy.qm.qmverifier as verif import rmgpy.molecule as mol class Test(unittest.TestCase): def testVerifierDoesNotExist(self): molecule = mol.Molecule() name = 'UMRZSTCPUPJPOJ-UHFFFAOYSA' ...
nChIaug = 'InChI=1/C10H16/c1-7-4-5-8-6-9(7)10(8,2)3/h4,8-9H,5-6H2,1-3H3' molfile = qm.molFile(molecule, name, directory, InChIaug) verifier = verif.QMVerifier(molfile) verifier.verify() self.assertTrue(verifier.succesfulJobExists()) self.assertTrue(verifier.mopacResultEx...
self.assertFalse(verifier.gaussianResultExists) if __name__ == "__main__": unittest.main( testRunner = unittest.TextTestRunner(verbosity=2) )
JamesMura/sentry
src/sentry/runner/commands/dsym.py
Python
bsd-3-clause
6,651
0
""" sentry.runner.commands.dsym ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import uuid import json import click import six import warnings import threading from sentry.runne...
information. These zip files contain JSON dumps. The actual zipped up dsym files cannot be used here, they need to be preprocessed. """ import zipfile from sentry.utils.db import is_mysql if threads != 1 and is_mysql(): warnings.warn(Warning('disabled threading for mysql')) thr...
sdk_info['version_major'], sdk_info['version_minor'], sdk_info['version_patchlevel'], sdk_info['version_build'], )).ljust(18) with click.progressbar(f.namelist(), label=label) as bar: process_archive(bar, f, sdk_info, t...
OpenDeployment/openstack-cloud-management
tools/checkOs_InstallStatus.py
Python
apache-2.0
6,462
0.023367
#!/usr/bin/python ## ################################################################################ ## the package and lib that must install: ## ## OpenIPMI ## yum install OpenIPMI-python ## ## Pexpect:Version 3.3 or higher ## caution: a lower version will cause some error like "timeout nonblocking() in read" when...
fresh os is default as 1 day. return : [errorList,oldOsHost] """ oldOsHost = [] errorList = [] cli = "stat /lost+found/ | grep Modify | awk -F ' ' {'print $2,$3,$4'};" cli += "exit $?" ## auto logout ## delete the existed ssl public key for the new install host wit...
cli) for host in hosts)) result=res.get() # import time import datetime import string for output in result: if output[1] and output[1] != '' : timeArr=output[1].split('\n')[1].split(' ') realTimeStruct = time.strptime(timeArr[0]+' '+timeArr[1].split('.')[0],'%Y-%m...
DigitalArtsNetworkMelbourne/huemovie
lib/terminalsize.py
Python
mit
2,958
0.003719
#!/usr/bin/env python # Source: https://gist.github.com/jtriley/1108174 import os import shlex import struct import platform import subprocess class TerminalSize: def get_terminal_size(self): """ getTerminalSize() - get width and height of consol
e - works on linux,os x,windows,cygwin(windows) originally retrieved from: http://stackoverflow.com/questions/566746/how-to-get-console-wind
ow-width-in-python """ current_os = platform.system() tuple_xy = None if current_os == 'Windows': tuple_xy = self._get_terminal_size_windows() if tuple_xy is None: tuple_xy = self._get_terminal_size_tput() # needed for window's pyth...
7Robot/BeagleBone-Black
PROJETS/2013/FiveAxesArm/asserv/Motor.py
Python
gpl-2.0
3,370
0.026237
# -*-coding:Utf-8 -* import Adafruit_BBIO.GPIO as GPIO import Adafruit_BBIO.ADC as ADC import Adafruit_BBIO.PWM as PWM import time from math import * class Motor : """Classe définissant un moteur, caractérisé par : - le rapport de cycle de son PWM - la pin de son PWM - son sens de rotation - la pin de ...
potaMax def getEcart(self) :
"""Renvoie l'écart entre la consigne angulaire et l'angle actuel""" return self.consigneAngle - self.angle def getCommande(self) : """Renvoie une commande pour asservir le moteur en angle. La commande est comprise entre -100.0 et +100.0""" # A FAIRE : pour l'instant juste proportionnel ...
seecr/dc-erfgeo-enrich
digitalecollectie/erfgeo/pittoannotation.py
Python
gpl-2.0
7,137
0.004063
# -*- coding: utf-8 -*- ## begin license ## # # "Digitale Collectie ErfGeo Enrichment" is a service that attempts to automatically create # geographical enrichments for records in "Digitale Collectie" (http://digitalecollectie.nl) # by querying the ErfGeo search API (https://erfgeo.nl/search). # "Digitale Collectie Erf...
, query=query, geoCoordinates=geoCoordinates))) def _renderRdfXml(self, pit, uri, targetUri, query, geoCoordinates=None): source = None if query: source = "%s?%s" % (self._searchApiBaseUrl, urlencode({'q': query})) yield '''<rdf:RDF %(xmlns_rdf)s>\n''' % namespaces annot...
a:Annotation %(xmlns_oa)s %(xmlns_rdfs)s %(xmlns_dcterms)s %(xmlns_owl)s %(xmlns_hg)s %(xmlns_geos)s %(xmlns_geo)s' % namespaces yield '%s\n>' % annotationRdfAbout yield ' <oa:annotatedBy rdf:resource="%s"/>\n' % uris.idDigitaleCollectie yield ' <oa:motivatedBy rdf:resource="%s"/...
HPENetworking/topology_docker
lib/topology_docker/shell.py
Python
apache-2.0
2,063
0
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Hewlett Packard Enterprise Development LP # # 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 ...
re__ import unicode_literals, absolute_import from __future__ import print_function, division from topology.platforms.shell import PExpectShell, PExpectBashShell class DockerExecMixin(object): """ Docker `
`exec`` connection mixin for the Topology shell API. This class implements a ``_get_connect_command()`` method that allows to interact with a shell through a ``docker exec`` interactive command, and extends the constructor to request for container related parameters. :param str container: Container un...
lcoandrade/DsgTools
core/DSGToolsProcessingAlgs/Algs/OtherAlgs/fileInventoryAlgorithm.py
Python
gpl-2.0
8,002
0.0015
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2019-01-04 git sha ...
E_LIST' COPY_FILES = 'COPY_FILES' COPY_FOLDER= 'COPY_FOLDER' OUTPUT = 'OUTPUT'
def initAlgorithm(self, config): """ Parameter setting. """ self.addParameter( QgsProcessingParameterFile( self.INPUT_FOLDER, self.tr('Input folder'), behavior=QgsProcessingParameterFile.Folder ) ) se...
rg3/captlog
setup.py
Python
cc0-1.0
1,110
0.000901
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of captlog. # # captlog - The Captain's Log (secret diary and notes application) # # Written in 2013 by Ricardo Garcia <r@rg3.name> # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to...
# # You should have received a copy of the CC0 Public Domain Dedication along with # this software. If not, see # <http://creativecommons.org/publicdomain/zero/1.0/>. from distutils.core import setup VERSION = '0.1.1' setup( name='captlog', version=VERSION, description="The Captain's Log (secret diary an...
og'], package_dir={'CaptainsLog': 'src/lib'}, package_data={'CaptainsLog': ['pixmap/*']}, scripts=['src/bin/captlog'], provides=['CaptainsLog (%s)' % (VERSION, )], requires=['Crypto (>=2.6)'], )
nsgomez/vboxmanager
models.py
Python
mit
539
0.007421
from peewee import * from playhouse.sqlite_ext import SqliteExtDatabase db = SqliteExtDatabase('store/virus_manager.db', threadlocals=True) class BaseModel(Model): class Meta: database = db class ManagedMachine(BaseModel): image_name = TextField(unique=True) reference_image = TextField() ...
machine = ForeignKeyField(ManagedMachine, related_name='infections') db.create_t
ables([ManagedMachine, Infection], True)
Pringley/basinweb
basin/views.py
Python
mit
1,780
0.004494
from django.shortcuts import render from rest_framework import viewsets from basin.models import Task from basin.serializers import TaskSerializer def index(request): context = {} return render(request, 'index.html', context) def display(request): state = 'active' if request.method == 'POST': ...
queryset = Task.objects
.active() serializer_class = TaskSerializer class SleepingViewSet(viewsets.ModelViewSet): queryset = Task.objects.sleeping() serializer_class = TaskSerializer class BlockedViewSet(viewsets.ModelViewSet): queryset = Task.objects.blocked() serializer_class = TaskSerializer class DelegatedViewSet(vi...
your-favorite-hacker/shellcode
x86_32/Example_Code/ascii_converter.py
Python
gpl-3.0
331
0.018127
#!/usr/bin/env python # # ascii
converter for shellcoding-lab at hack4 # ~dash in 2014 # import sys import binascii text = sys.argv[1] def usage(): print "./%s <string2convert>" % (sys.argv[0]) if len(sys.argv)<2: usage() exit() val = binascii.hexlify(text[::-1]) print "Stringlen: %d" % len(text) print "String: %s" % val
antoinecarme/pyaf
tests/artificial/transf_Logit/trend_MovingMedian/cycle_12/ar_/test_artificial_1024_Logit_MovingMedian_12__0.py
Python
bsd-3-clause
264
0.087121
import pyaf.Bench.TS_da
tasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D'
, seed = 0, trendtype = "MovingMedian", cycle_length = 12, transform = "Logit", sigma = 0.0, exog_count = 0, ar_order = 0);
iamsteadman/bambu-attachments
bambu_attachments/apps.py
Python
apache-2.0
104
0.009615
from django.apps import AppConfig cl
ass AttachmentsConfig(AppConfig)
: verbose_name = 'Attachments'
LeonRave/Tarea_Git
a.py
Python
mit
66
0.075758
def suma(a, b): retur
n a+b def resta(a,
b): return a+b
bijaydev/Implementation-of-Explicit-congestion-notification-ECN-in-TCP-over-wireless-network-in-ns-3
src/flow-monitor/bindings/modulegen__gcc_ILP32.py
Python
gpl-2.0
454,665
0.015106
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
acket-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetad
ata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [cla...
OpenDA-Association/OpenDA
model_bmi/java/test/org/openda/model_bmi/testData/wflow_bin/wflow/stats.py
Python
lgpl-3.0
24,590
0.019113
#!/usr/local/bin/python # # Created on July 10, 2000 # by Keith Cherkauer # # This python script computes several standard statistics on arrays # of values # # Functions include: # get_mean # get_median # get_var # get_stdev # get_skew # get_sum # get_min # get_max # get_count_over_threshold # get_quantile #...
act ) def
get_var(values, N="", mean="", NoData=NoDataVal): """This function computes the variance of an array of values after filtering out the NoData values. The mean value of the array must be provided to the routine. It returns both the variance value and the number of valid data points used. The ...
tracfm/tracfm
tracfm/polls/migrations/0010_auto__add_field_poll_detailed_chart.py
Python
agpl-3.0
13,004
0.008151
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Poll.detailed_chart' db.add_column('polls_poll', 'detailed_chart', self.gf('django.db.mode...
ield', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'secondary_category_set': ('djang...
rohitranjan1991/home-assistant
homeassistant/components/econet/__init__.py
Python
mit
5,194
0.000963
"""Support for EcoNet products.""" from datetime import timedelta import logging from aiohttp.client_exceptions import ClientError from pyeconet import EcoNetApiInterface from pyeconet.equipment import EquipmentType from pyeconet.errors import ( GenericHTTPError, InvalidCredentialsError, InvalidResponseFor...
ER_HEATER, EquipmentType.THERMOSTAT]
) except (ClientError, GenericHTTPError, InvalidResponseFormat) as err: raise ConfigEntryNotReady from err hass.data[DOMAIN][API_CLIENT][config_entry.entry_id] = api hass.data[DOMAIN][EQUIPMENT][config_entry.entry_id] = equipment hass.config_entries.async_setup_platforms(config_entry, PLA...
opendatatrentino/opendata-harvester
harvester_odt/pat_geocatalogo/constants.py
Python
bsd-2-clause
669
0
API_XML_NSMAP = { "csw": "http://www.opengis.net/cat/csw/
2.0.2", "dc": "http://purl.org/dc/elements/1.1/", "dct": "http://purl.org/dc/terms/", "geonet": "http://www.fao.org/geonetwork", "xsi": "http://www.w3.org/2001/XMLSchema-instance", } LINKED_XML_NSMAP = { "csw": "http://www.opengis.net/cat/csw/2.0.2", "gco": "http://www.isotc211.org/2005/gco", ...
http://www.isotc211.org/2005/srv", "xlink": "http://www.w3.org/1999/xlink", "xsi": "http://www.w3.org/2001/XMLSchema-instance", }
alephdata/ingestors
ingestors/directory.py
Python
mit
1,551
0
from followthemoney import model from ingestors.ingestor import Ingestor class DirectoryIngestor(Ingestor): """Traverse the entries in a directory.""" MIME_TYPE = "inode/directory" SKIP_ENTRIES = [".git", ".hg", "__MACOSX", ".gitignore"] def ingest(self, file_path, entity): """Ingestor imp...
@classmethod def crawl(cls, manager, file_path, parent=None): for path in
file_path.iterdir(): name = path.name if name is None or name in cls.SKIP_ENTRIES: continue sub_path = file_path.joinpath(name) child = manager.make_entity("Document", parent=parent) child.add("fileName", name) if sub_path.is_dir()...
isaachenrion/jets
src/monitors/saver.py
Python
bsd-3-clause
985
0.001015
import torch import pickle import logging from .baseclasses import ScalarMonitor
from .meta import Regurgitate class Saver(ScalarMonitor): def __init__(self, save_monitor, model_file, settings_file, **kwargs): self.saved = False self.save_monitor = save_monitor self.model_file = model_file self.settings_file = settings_file super().__init__('save', **kw...
f.save_monitor.changed: self.save(model, settings) self.value = self.save_monitor.value return self.value def save(self, model, settings): with open(self.model_file, 'wb') as f: torch.save(model.cpu().state_dict(), f) if torch.cuda.is_available(): ...
mmccoo/kicad_mmccoo
menus_and_buttons/menus_and_buttons.py
Python
apache-2.0
2,271
0.005284
import pcbnew import wx import wx.aui # get the path of this script. Will need it to load the png later. import inspect import os filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) print("running {} from {}".format(filename, path)) def findPcbnewWind...
= top_tb.FindToolByIndex(idx) # #print("
toolbar item {}".format(tbi.GetShortHelp())) def MyButtonsCallback(event): # when called as a callback, the output of this print # will appear in your xterm or wherever you invoked pcbnew. print("got a click on my new button {}".format(str(event))) # Plan for three sizes of bitmaps: # SMALL - for me...
nerandell/aiopg
aiopg/cursor.py
Python
bsd-2-clause
11,747
0.00017
import asyncio import warnings import psycopg2 from .log import logger class Cursor: def __init__(self, conn, impl, timeout, echo): self._conn = conn self._impl = impl self._timeout = timeout self._echo = echo @property def echo(self): """Return echo mode status...
"cursors yet") return ret @asyncio.coroutine def fetchall(self): """Fetch all (remaining) rows of a query result. Ret
urns them as a list of tuples. An empty list is returned if there is no more record to fetch. """ ret = self._impl.fetchall() assert not self._conn._isexecuting(), ("Don't support server side " "cursors yet") return ret @async...
WimpyAnalytics/django-andablog
demo/common/migrations/0001_initial.py
Python
bsd-2-clause
2,365
0.004651
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='User', ...
ofile name')), ('slug', models.SlugField(unique=True)), ('groups', mod
els.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', verbose_name='groups')), ('user_permissions', models.ManyToManyField(related_query_name='us...
peiyuwang/pants
src/python/pants/backend/codegen/tasks/simple_codegen_task.py
Python
apache-2.0
531
0.001883
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.base.depr...
precated_module('1.5.0dev0', 'Use pa
nts.task.simple_codegen_task instead') SimpleCodegenTask = SimpleCodegenTask
fredericmohr/mitro
mitro-mail/build/venv/lib/python2.7/site-packages/sqlalchemy/dialects/sqlite/base.py
Python
gpl-3.0
34,783
0.001265
# sqlite/base.py # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: sqlite :name: SQLite Date and Time Types ------------------- SQ...
qlite.org/whentouse.html>`_ near the bottom of the page. .. _sqlite_foreign_keys: Foreign Key Support ------------------- SQLite supports FOREIGN KEY syntax when emitting CREATE statements for tables, however by default these constraints have no effect on the operation of the table. Constraint checking on SQLite h...
ER symbols enabled. * The ``PRAGMA foreign_keys = ON`` statement must be emitted on all connections before use. SQLAlchemy allows for the ``PRAGMA`` statement to be emitted automatically for new connections through the usage of events:: from sqlalchemy.engine import Engine from sqlalchemy import event ...
spulec/PyQS
example/api/helpers.py
Python
mit
545
0
import json import logging from flask i
mport jsonify def construct_response(message, payload, status): body = {} if status == 500: body['message'] = ( 'Something went wrong constructing response. ' 'Is your payload valid JSON?' ) body['request_payload'] = str(payload) else: body['message...
resp.status_code = status return resp
saramic/learning
data/tensorflow/src/2_4_creating_tensors.py
Python
unlicense
405
0.032099
import tensorflow as tf m1 = tf.const
ant([[1., 2.]]) m2 = tf.constant([[1], [2]]) m3 = tf.constant([ [[1,2], [3,4], [5,6]], [[7,8], [9,10], [11,12]] ]) print(m1) pri
nt(m2) print(m3) # 500 x 500 tensor print(tf.ones([500, 500])) # 500 x 500 tensor with 0.5 value print(tf.ones([500, 500]) * 0.5)
expyriment/expyriment
expyriment/misc/_colour.py
Python
gpl-3.0
15,022
0.000466
# -*- coding: utf-8 -*- """Colour class. This module contains a class implementing an RGB colour. """ __author__ = 'Florian Krause <florian@expyriment.org>, \ Oliver Lindemann <oliver@expyriment.org>' __version__ = '' __revision__ = '' __date__ = '' import colorsys from . import round # The named colours are th...
urquoise': (72, 209, 204), 'mediumvioletred': (199, 21, 133), 'midnightblue': (25, 25, 112), 'mintcream': (245, 255, 250), 'mistyrose': (255, 228, 225), 'moccasin': (255, 228, 181), 'navajowhite': (255, 222,...
ldlace': (253, 245, 230), 'olive': (128, 128, 0), 'olivedrab': (107, 142, 35), 'orange': (255, 165, 0), 'orangered': (255, 69, 0), 'orchid': (218, 112, 214), 'palegoldenrod': (238, 23...
mattop101/ShellSwitch
shellswitch.py
Python
mit
5,372
0.003351
import pygame import sys from shellswitch_lib import ShellSwitchGameGrid DISPLAY_WIDTH = 512 DISPLAY_HEIGHT = 384 class ShellSwitcher: def __init__(self): pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() self.screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIG...
le.sprite = self.tile_sprites[4] self.counter_bombs_y = [self.grid_data.bombs_in_row(i) for i in range(self.grid_data.rows)] self.counter_bombs_x = [self.grid_data.bombs_in_col(j) for j in range(self.grid_data.cols)] self.counter_score_y = [self.grid_data.points_in_row(k) for k in range(self.gr...
f, mouse_pos): """ Change the clicked tile to the corresponding sprite """ for tile in self.grid_data: if tile.area.collidepoint(mouse_pos) and not tile.is_clicked: if self.score == 0: self.score = tile.mult else: ...
abhishekjiitr/my-nltk
examples/ex6.py
Python
mit
762
0.003937
import nltk from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer train_text = state_union.raw("2005-GWBush.txt") sample_text = state_union.raw("2006-GWBush.txt") custom_sent_tokenizer = PunktSentenceTokenizer(train_text) tokenized = custom_sent_tokenizer.tokenize(sample_text) def pro...
rser = nltk.RegexpParser(chunkGram) chunked = c
hunkParser.parse(tagged) chunked.draw() except Exception as e: print(str(e)) process_content()
rev22/svgl
scripts/test_suite.py
Python
lgpl-2.1
767
0.009126
import os import popen2 HOME = '/home/conversy' #TEST_SUITE_DIR = HOME+'/Archives/svgtests' TEST_SUITE_DIR = HOME+'/Archives/svgtoolkit-20001010/samples' lfiles = os.listdir(TEST_SUITE_DIR) tmpfile = '/tmp/conversysvgtest' excludes = ['SVGAnimat', 'SVGSVGElement::xmlns', 'SVGTitleElement::cont
ent', 'SVGDescElement::content', 'xmlns:xlink'] filter = ' && cat ' + tmpfile for i in excludes: filter = filter + ' | grep -v "%s" '%i fo
r filename in lfiles: prefix, ext = os.path.splitext(filename) if ext=='.svg': longname = TEST_SUITE_DIR+ '/' + filename print longname cmd = "./svgtest " + longname + ' 2>' + tmpfile + filter #print cmd stdout, stdin, stderr = popen2.popen3(cmd) print stdout.read...
reisub-de/dmpr-simulator
dmprsim/analyze/random_network.py
Python
mit
809
0
import random from pathlib import Path from dmprsim.topologies.randomized import RandomTopology from dmprsim.topologies.utils import ffmpeg SIMU_TIME = 300 def main(args, results_dir: Path, scenario_dir: Path): sim = RandomTopology( simulation_
time=getattr(args, 'simulation_time', 300), num_routers=getattr(args, 'num_routers', 100), random_seed_prep=getattr(args, 'random_seed
_prep', 1), random_seed_runtime=getattr(args, 'random_seed_runtime', 1), scenario_dir=scenario_dir, results_dir=results_dir, args=args, tracepoints=('tx.msg',), area=(640, 720), velocity=lambda: random.random()**6, ) sim.prepare() for _ in sim.start():...
davidhernon/libmapper
swig/test.py
Python
lgpl-2.1
3,790
0.018997
import sys, mapper def h(sig, id, f, timetag): try: print sig.name, f except: print 'exception' print sig, f def setup(d): sig = d.add_input("/freq", 1, 'i', "Hz", None, None, h) print 'inputs',d.num_inputs print 'minimum',sig.minimum sig.minimum = 34.0 print 'mini...
print i print 'links for device "/testsend.1":' for i in mon.db.links_by_src_device_name('/testsend.1'): print i print 'link for /testsend.1, /testrecv.1:' print mon.db.get_link_by_src_dest_names("/testsend.1", "/testrecv.1") print 'not fo
und link:' print mon.db.get_link_by_src_dest_names("/foo", "/bar") if i==500: mon.connect("/testsend.1/outsig_3", "/testrecv.1/insig_3", {'mode': mapper.MO_EXPRESSION, 'expression': 'y=x', 'src_min': [1,2,3,4], 'boun...
leeseuljeong/leeseulstack_neutron
neutron/agent/linux/ip_lib.py
Python
apache-2.0
20,419
0.000392
# Copyright 2012 OpenStack Foundation # 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 requ...
# Only callers that nee
d to force use of the root helper # need to register the option. self.force_root = False def _run(self, options, command, args): if self.namespace: return self._as_root(options, command, args) elif self.force_root: # Force use of the root helper to en...
plotly/python-api
packages/python/plotly/plotly/validators/layout/ternary/aaxis/_tickfont.py
Python
mit
1,549
0.000646
import _plotly_utils.basevalidators class TickfontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="tickfont", parent_name="layout.ternary.aaxis", **kwargs ): super(TickfontValidator, self).__init__( plotly_name=plotly_name, par...
erates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-pre
mise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standa...
torchbox/zencoder-py
setup.py
Python
mit
363
0.00551
from distutils.core import setup setup(name='zencoder', version='0.4', description='Integration library for Zencoder', author='Alex Schworer', author_email='alex.schworer@gmail.com', url='http://github.com/sch
worer
/zencoder-py', license="MIT License", install_requires=['httplib2'], packages=['zencoder'] )
twenty0ne/CocosBuilder-wxPython
CCBDocument.py
Python
mit
26,533
0.043078
""" <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>centeredOrigin</key> <false/> <key>currentResolution</key> <integer>0</integer> <key>currentSequenceId</key> <integer>0</integer> <ke...
>baseClass</key> <string>CCMenuItemImage</stri
ng> <key>children</key> <array/> <key>customClass</key> <string></string> <key>displayName</key> <string>CCMenuItemImage</string> <key>memberVarAssignmentName</key> <string></string> <key>memberVarAssignmentType</key> <integer>0</integer> <key>properties...
CSD-Public/stonix
src/tests/rules/unit_tests/zzzTestRulePreventXListen.py
Python
gpl-2.0
4,504
0.00222
#!/usr/bin/env python3 ############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contrac...
ks, distribute copies to the public, # # perform publicly and display publicly, and to permit others to do so. # # # ############################################################################### ''' This is a Unit Test for Rule
ConfigureAppleSoftwareUpdate @author: ekkehard j. koch @change: 03/18/2013 Original Implementation @change: 2016/02/10 roy Added sys.path.append for being able to unit test this file as well as with the test harness. ''' import unittest import sys sys.path.append("../../../..") from src.test...
funbaker/astropy
astropy/stats/tests/test_bayesian_blocks.py
Python
bsd-3-clause
4,205
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import numpy as np from numpy.testing import assert_allclose from .. import bayesian_blocks, RegularEvents def test_single_change_point(rseed=0): rng = np.random.RandomState(rseed) x = np.concatenate([rng.rand(100), ...
blocks(t, fitness=RegularEvents, dt=dt) assert_allclose(bins1, bins2) # class instance fitness bins3 = bayesian_blocks(t, fitness=RegularEvents(dt=dt)) assert_allclose(bins1, bins3) def test_errors(): rng = np.random.RandomState(0) t = rng.rand(100) # x must be integer or None for events...
ueError): bayesian_blocks(t, fitness='regular_events', x=10 * t, dt=1) # x must be specified for measures with pytest.raises(ValueError): bayesian_blocks(t, fitness='measures') # sigma cannot be specified without x with pytest.raises(ValueError): bayesian_blocks(t, fitness='eve...
google/vizier
vizier/pyvizier/shared/parameter_config.py
Python
apache-2.0
21,349
0.007494
"""ParameterConfig wraps ParameterConfig and ParameterSpec protos.""" import collections import copy import enum import math from typing import Generator, List, Optional, Sequence, Tuple, Union from absl import logging import attr from vizier.pyvizier.shared import trial class ParameterType(enum.IntEnum): """Val...
lueError( 'default_value has an incorrect type. ParameterType has type {}, ' 'but default_value has type {}'.format(param_type.name, type(default_value))) @attr.s(auto_attribs=True, frozen=True, init=True, slots=True) class ParameterConfig: """A Vizier Parame...
g. Use ParameterConfig.factory to create a valid instance. """ _name: str = attr.ib( init=True, validator=attr.validators.instance_of(str), kw_only=True) _type: ParameterType = attr.ib( init=True, validator=attr.validators.instance_of(ParameterType), repr=lambda v: v.name if v is not No...
pypa/virtualenv
tests/unit/seed/wheels/test_wheels_util.py
Python
mit
901
0
from __future__ import absolute_import, unicode_literals import pytest from virtualenv.seed.wheels.embed import MAX, get_embed_wheel from virtualenv.seed.wheels.util import Wheel def test_wheel_support_no_python_requires(mocker): wheel = get_embed_wheel("setuptools", for_py_version=None) zip_mock = mocker.M...
ock() mocker.patch("virtualenv.seed.wheels.util.ZipFile", new=zip_mock) zip_mock.return_value.__enter__.return_value.read = lambda name: b"" supports = wheel.support_py("3.8") assert supports is True def test_bad_as_version_tuple(): with pytest.raises(ValueError, match="bad"): Wheel.as_ve...
ls", MAX) assert wheel.support_py("3.3") is False def test_wheel_repr(): wheel = get_embed_wheel("setuptools", MAX) assert str(wheel.path) in repr(wheel)
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/candc/src/lib/tokeniser/fixes.py
Python
mit
820
0.023171
#!/usr/bin/env python import sys def fix_terminator(tokens): if not tokens: return last = tokens[-1] if last not in ('.', '?', '!') and last.endswith('.'): tokens[-1] = last[:-1] tokens.append('.') def balance_quotes(tokens): count = tokens.count("'") if not count: return processed = 0
for i, token in enumerate(tokens): if token == "'": if processed % 2 == 0 and (i == 0 or processed != count - 1): tokens[i] = "`" processed += 1 def output(
tokens): if not tokens: return # fix_terminator(tokens) balance_quotes(tokens) print ' '.join(tokens) prev = None for line in sys.stdin: tokens = line.split() if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'): prev.append(tokens[0]) else: output(prev) prev = tokens output(prev)
Ebag333/Pyfa
eos/effects/elitereconbonusradarstrength2.py
Python
gpl-3.0
384
0.002604
# eliteReconBonusRadarStrength2 # # Used by: # Ship: Chameleon # Ship: Falcon # Ship: Rook type = "passive" def handler(fit, ship, context): fit.modules.filteredItemBoost(lambda
mod: mod.item.group.name == "ECM", "scanRadarStrengthBonus", ship.getModifiedItemAttr("eliteBonusReconShip2"),
skill="Recon Ships")
memaldi/ckanext-sparql
ckanext/sparql/controller.py
Python
agpl-3.0
2,273
0
from ckan.controllers.package import PackageController from ckan.plugins import toolkit as tk from ckan.common import request import ckan.model as model import ckan.logic as logic import logging import requests import ConfigParser import os import json log = logging.getLogger(__name__) config = ConfigParser.ConfigPar...
'sparql-query-maker/query'
package_id = None for resource in c.pkg_dict.get('resources', []): if resource.get('format', '').lower() in RDF_FORMAT: package_id = resource['id'] break log.debug(package_id) if package_id is not None: pay...
odoo-chile/l10n_cl_invoice
models/partner.py
Python
agpl-3.0
2,394
0.006268
# -*- coding: utf-8 -*- from openerp import fields, models, api import re class res_partner(models.Model): _inherit = 'res.partner' #def _get_default_tp_type(self): # return self.env.ref('l10n_cl_invoice.res_IVARI').id # todo: pasar los valores por defecto a un nuevo módulo # por ejemplo "l10n...
id') def onchange_document(self): mod_obj = self.env['ir.model.data'] if self.document_number and (( 'sii.document_type', self.document_type_id.id) == mod_obj.get_object_reference( 'l10n_cl_invoice', 'dt_RUT') or ('sii.document_type', self.docu...
_cl_invoice', 'dt_RUN')): document_number = ( re.sub('[^1234567890Kk]', '', str( self.document_number))).zfill(9).upper() self.vat = 'CL%s' % document_number self.document_number = '%s.%s.%s-%s' % ( document_number[0:2], document_nu...
hack4impact/legal-checkup
app/models/api.py
Python
mit
2,549
0.003531
from .. import db class ApiParameterLink(db.Model): __tablename__ = 'api_parameter_link' api_id = db.Column(db.Integer, db.ForeignKey('apis.id'), primary_key=True) parameter_id = db.Column(db.Integer, db.ForeignKey('parameters.id'), primary_key=True) parameter_description = db.Column(db.String(128)) ...
egion self.description = description def __repr__(self): return '<Api \'%s %s %s %s\'>' % (self.name, self.url, self.region, self.description) class Parameter(db.Model): __tablename__ = 'parameters'
id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) param_format = db.Column(db.String(64)) count = db.Column(db.Integer) apis = db.relationship('Api', secondary='api_parameter_link') def get_apis(self): return ApiParameterLink.query.filter_by(paramete...
ovnicraft/odoo_addons
smile_base/models/ir_values.py
Python
agpl-3.0
4,447
0.002474
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under th...
'ir.actions.wizard'): groups = action_def.get('groups_id') if groups: cr.execute('SELECT 1 FROM res_groups_users_rel WHERE gid IN %s AND uid=%s', (tuple(gr
oups), uid)) if not cr.fetchone(): if action['name'] == 'Menuitem': raise Warning(_('You do not have the permission to perform this operation !!!')) continue # keep only the fi...
Spiderlover/Toontown
toontown/hood/DLHood.py
Python
mit
1,237
0.00485
from toontown.safezone.DLSafeZoneLoader import DLSafeZoneLoader from toontown.town.DLTownLoader import DLTownLoader from toontown.toonbase import ToontownGlobals from toontown.hood.ToonHood import ToonHood class DLHood(ToonHood): not
ify = directNotify.newCategory('DLHood') ID = ToontownGlobals.DonaldsDreamland TOWNLOADER_CLASS = DLTownLoader SAFEZONELOADER_CLASS = DLSafeZoneLoader STO
RAGE_DNA = 'phase_8/dna/storage_DL.pdna' SKY_FILE = 'phase_8/models/props/DL_sky' TITLE_COLOR = (1.0, 0.9, 0.5, 1.0) HOLIDAY_DNA = { ToontownGlobals.WINTER_DECORATIONS: ['phase_8/dna/winter_storage_DL.pdna'], ToontownGlobals.WACKY_WINTER_DECORATIONS: ['phase_8/dna/winter_storage_DL.pdna'], ...
wilsonianb/nacl_contracts
build/update_pnacl_tool_revisions.py
Python
bsd-3-clause
16,688
0.00797
#!/usr/bin/python # Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import collections import datetime import email.mime.text import getpass import os import re import smtplib import...
(commit_hash): """List of files changed in a commit.""" return GitCommitInfo(obj=commit_hash, num=1, extra=['--name-only']).split('\n') def GitChangesPath(commit_hash, path): """Returns True if the commit changes a file under the given path.""" return any([ re.search('^' + path, f...
', name]).strip()) != 0 def GitCheckout(branch, force=False): """Checkout an existing branch. force throws away local changes.""" ExecCommand(['git', 'checkout'] + (['--force'] if force else []) + [branch]) def GitCheckoutNewBranch(branch): """Create and checkout a new git branch...
plotly/python-api
packages/python/plotly/plotly/validators/scatterternary/selected/marker/_size.py
Python
mit
509
0.001965
import _plotly_utils.basevalidators class SizeValid
ator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="scatterternary.selected.marker", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("e...
role=kwargs.pop("role", "style"), **kwargs )
oleiade/Fridge
fabfile/__init__.py
Python
mit
365
0
#
-*- coding: utf-8 -*- # Copyright (c) 2012 theo crevon # # See the file LICENSE for copying permission. import install import config import service from fabric.api import env, task env.hosts = ['localhost'] @task def bootstrap(): """Deploy, configure, and start Fridge on hosts""
" install.bootstrap() config.bootstrap() service.start_all()
theanalyst/cinder
cinder/openstack/common/db/sqlalchemy/test_migrations.py
Python
apache-2.0
11,078
0
# Copyright 2010-2011 OpenStack Foundation # Copyright 2012-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/li...
user=user, passwd=passwd, database=database) return present.lower() in ('', 'true') def _have_postgresql(user, passwd, database): present = os.environ.get('TEST_POSTGRESQL_PRESENT') if present is None: return utils....
'postgres', user=user, passwd=passwd, database=database) return present.lower() in ('', 'true') def _set_db_lock(lock_path=None, lock_prefix=None): def decorator(f): @functools.wraps(f) ...
terbolous/SickRage
lib/feedparser/namespaces/georss.py
Python
gpl-3.0
11,117
0.003868
# Support for the GeoRSS format # Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org> # Copyright 2002-2008 Mark Pilgrim # All rights reserved. # # This file is a part of feedparser. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following con...
return _parse_georss_line(valu
e, swap, dims) elif geom_type == 'polygon': ring = _parse_georss_line(value, swap, dims) return {'type': 'Polygon', 'coordinates': (ring['coordinates'],)} else: return None def _gen_georss_coords(value, swap=True, dims=2): # A generator of (lon, lat) pairs from a string of encoded G...
Barmaley13/BA-Software
gate/sleepy_mesh/node/headers/header/unit.py
Python
gpl-3.0
5,361
0.003917
""" Header Unit Class """ ### INCLUDES ### import logging from gate.conversions import round_int from variable import HeaderVariable from common import MIN_ALARM, MAX_ALARM ### CONSTANTS ### ## Logger ## LOGGER = logging.getLogger(__name__) # LOGGER.setLevel(logging.DEBUG) ### CLASSES ### class HeaderUnit(Header...
data_out = provider['data_out'][self['data_field']] elif self['data_field'] in data_in: data_
out = data_in[self['data_field']] if self['internal_name'] in data_out: output = data_out[self['internal_name']] return output def get_string(self, provider, data_in=None): """ Fetches current value for the selected units if log data is not provided. Ot...
elffersj/cnfgen
tests/test_subsetcardinality.py
Python
gpl-3.0
2,350
0.00766
import networkx as nx import sys from cnfformula import CNF from cnfformula import SubsetCardinalityFormula from . import TestCNFBase from .test_commandline_helper import TestCommandline from .test_graph_helper import complete_bipartite_graph_proper class TestSubsetCardinality(TestCNFBase): def test_empty(self)...
nx.Graph() F = SubsetCardinalityFormula(graph) self.assertCnfEqual(F,G) def test_not_bipartite(self): graph = nx.complete_graph(3) with self.assertRaises(KeyError): SubsetCardinalityFormula(graph) def test_complete_even(self): graph = complet
e_bipartite_graph_proper(2,2) F = SubsetCardinalityFormula(graph) dimacs = """\ p cnf 4 4 1 2 0 3 4 0 -1 -3 0 -2 -4 0 """ self.assertCnfEqualsDimacs(F,dimacs) def test_complete_even_odd(self): graph = complete_bipartite_graph_proper(2,...
sckasturi/saltlake
commands/score.py
Python
gpl-2.0
3,127
0.002558
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcier and Reed Koser # # 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 Licen...
desc()).limit(3).all() send('High Scores:') for x in data:
send("%s: %s" % (x.nick, x.score)) elif match.group(1) == 'low': data = session.query(Scores).order_by(Scores.score).limit(3).all() send('Low Scores:') for x in data: send("%s: %s" % (x.nick, x.score)) else: send("%s is not a valid f...
mscuthbert/abjad
abjad/tools/tonalanalysistools/test/test_tonalanalysistools_ChordSuspension___eq__.py
Python
gpl-3.0
634
0.009464
# -*- encoding: utf-8 -*- from abjad import * from abjad.tools import tonalanalysistools def test_tonalanalysistools_ChordSuspension___eq___01():
chord_suspension = tonalanalysistools.ChordSuspens
ion(4, 3) u = tonalanalysistools.ChordSuspension(4, 3) voice = tonalanalysistools.ChordSuspension(2, 1) assert chord_suspension == chord_suspension assert chord_suspension == u assert not chord_suspension == voice assert u == chord_suspension assert u == u assert no...
nicolargo/pymdstat
pymdstat/__init__.py
Python
mit
297
0
#!/usr/bin/env py
thon # -*- coding: utf-8 -*- # # PyMDstat # ... # # Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com> __appname__ = "PyMDstat" _
_version__ = "0.4.2" __author__ = "Nicolas Hennion <nicolas@nicolargo.com>" __licence__ = "MIT" __all__ = ['MdStat'] from .pymdstat import MdStat
kazukiotsuka/mongobase
mongobase/modelbase.py
Python
mit
5,018
0.000598
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tools/modelbase.py # # # MODEL DEFINITION: # 1. create a subclass. # 2. set each definitions as below in the subclass. # # __structure__ = {} # define keys and the data type # __required_fields__ = [] # lists required keys # __default_values__ = {} # set def...
.__default_values__[key] else: default_val = None setattr(self, key, default_val) def getattr(self, key): return getattr(self, key) def setattr(self, key, value): return setattr(self, key, value)
def purify(self): """Return an instance as dictionary format. returns: object (dict): object only with keys in __structure__. """ extracted = {} for key in self.__structure__: extracted[key] = self[key] if 'search_text' in self: extra...
joeflack4/jflack
joeutils/data_structures/comprehensions/maps/__init__.py
Python
mit
883
0
"""Map Comprehensions""" def inverse_filter_dict(dictionary, keys): """Filter a dictionary by any keys not given. Args: dictionary (dict): Dictionary. keys (iterable): Iterable containing data type(s) for valid
dict key. Return: dict: Filtered dictionary. """ return {key: val for key, val in dictionary.items() if key not in keys} def ne_dict(dictionary): """Prune dictionary of empty key-value pairs. Aliases: pruned() """ return {k: v for k, v in dictionary.items() if v} def pruned(dic...
ldren(dictionary, n=1): """Return with only key value pairs that meet required n children.""" return {key: val for key, val in dictionary.items() if len(val) >= n}
Elastica/kombu
kombu/transport/pyamqp.py
Python
bsd-3-clause
5,262
0.00019
""" kombu.transport.pyamqp ====================== pure python amqp transport. """ from __future__ import absolute_import, unicode_literals import amqp from kombu.five import items from kombu.utils.amq_manager import get_manager from kombu.utils.text import version_string_as_tuple from . import base DEFAULT_PORT =...
nfo.heartbeat, }, **conninfo.transport_options or {}) conn = self.Connection(**opts) conn.client = self.client conn.connect() return conn def verify_connection(self, connection): return c
onnection.connected def close_connection(self, connection): """Close the AMQP broker connection.""" connection.client = None connection.close() def get_heartbeat_interval(self, connection): return connection.heartbeat def register_with_event_loop(self, connection, loop): ...
wdv4758h/ZipPy
edu.uci.python.benchmark/src/benchmarks/sympy/sympy/printing/tests/test_ccode.py
Python
bsd-3-clause
10,134
0.001875
from sympy.core import pi, oo, symbols, Function, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt, gamma from sympy.utilities.pytest import raises from
sympy.printing.ccode import CCodePrinter from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx # import test from sympy import ccode x, y, z = symbols('x,y,z') g = Function('g') def test_printmethod(): class fabs(Abs): def _ccode(self, printer): ...
eturn "fabs(%s)" % printer._print(self.args[0]) assert ccode(fabs(x)) == "fabs(x)" def test_ccode_sqrt(): assert ccode(sqrt(x)) == "sqrt(x)" assert ccode(x**0.5) == "sqrt(x)" assert ccode(sqrt(x)) == "sqrt(x)" def test_ccode_Pow(): assert ccode(x**3) == "pow(x, 3)" assert ccode(x**(y**3)) ==...
ProjectSWGCore/NGECore2
scripts/mobiles/naboo/narglatch_sick.py
Python
lgpl-3.0
1,632
0.026961
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
te.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setMeatType("Carnivore Meat") mobileTemplate.setMeatAmount(60) mobileTemplate.setHideType("Bristley Hide") mobileTem
plate.setHideAmount(45) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setBoneAmount(40) mobileTemplate.setSocialGroup("narglatch") mobileTemplate.setAssistRange(2) mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE) mobileTemplate.setStalker(False) templates = Vector() templa...
jesopo/bitbot
src/core_modules/cron.py
Python
gpl-2.0
2,510
0.00239
import datetime, time from src import ModuleManager, utils TIMESTAMP_BOUNDS = [ [0, 59], [0, 23], [1, 31], [1, 12], [0, 6], ] class Module(ModuleManager.BaseModule): def on_load(self): now = datetime.datetime.utcnow() next_minute = now.replace(second=0, microsecond=0) n...
t) in items: if not self._schedule_match_part(i, timestamp_part, schedule_part): return False return True def _schedule_match_part(self, i, timestamp_part, schedule_part): if "," in schedule_part: for schedule_part in schedule_part.split(","): ...
return True elif "/" in schedule_part: range_s, _, step = schedule_part.partition("/") if "-" in range_s: range_min, _, range_max = range_s.partition("-") range_min = int(range_min) range_max = int(range_max) e...
archen/django
django/core/urlresolvers.py
Python
bsd-3-clause
22,195
0.001532
""" This module converts requested URLs to callback view functions. RegexURLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a tuple in this format: (view_function, function_args, function_kwargs) """ from __future__ import unicode_literals from importlib import import_...
rl_name = url_name
@property def namespace(self): return ':'.join(self.namespaces) @property def view_name(self): return ':'.join(filter(bool, (self.namespace, self.url_name))) def __getitem__(self, index): return (self.func, self.args, self.kwargs)[index] def __repr__(self): r...
lunixbochs/fs-uae-gles
launcher/fs_uae_launcher/fsui/wx/separator.py
Python
gpl-2.0
394
0.010152
from __future__ import division from __future__ import print_function from __future__ import absolute
_import import wx from .common import update_class class Separator(wx.StaticLine): def __init__(self, parent): wx.StaticLine.__i
nit__(self, parent.get_container(), -1, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL) update_class(Separator)