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
shirlei/helios-server
helios_auth/view_utils.py
Python
apache-2.0
1,428
0.013305
""" Utilities for all views Ben Adida (12-30-2008) """ from django.conf import settings from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import loader import helios_auth from helios_auth.security import get_user ## ## BASICS ## SUCCESS = HttpResponse("SUCCES...
ues or {}) return render_to_response('helios_auth/templates/%s.html' % template_name, vars_with_user) def render_template_raw(request, template_name, values=None): t = loader.get_template(template_name + '.html') values = values or {} vars_with_user = prepare_vars(request, values) return t.render(context...
json_txt)
w568w/GitHubStar
settings.py
Python
gpl-3.0
220
0.075
# -*
- coding:utf-8 -*- #############settings############# NAME = "1" #GitStar用户名 PASSWORD = "1" #GitStar密码 GITNAME = "1" #GitHub用户名 GITPASSWORD = "1" #GitHub密码 ########
#####settings#############
byuphamerator/phamerator-dev
phamerator/plugins/get_relatives.py
Python
gpl-2.0
429
0.006993
#!/usr/bin/env python from phamerator import * from phamerator.phamerator_manage_db import * from phamerator.db_conf import db_conf import sys, getpass GeneID = sys.argv[1] password = getpass.
getpass() db = raw_input('database: ') c = db_conf(username='root', password=password,
server='134.126.132.72', db=db).get_cursor() print get_relatives(c, GeneID, alignmentType='both', clustalwThreshold=0.275, blastThreshold=0.0001)
NeostreamTechnology/Microservices
venv/lib/python2.7/site-packages/simplejson/tests/test_item_sort_key.py
Python
mit
1,376
0.00436
from unittest import TestCase import simplejson as json from operator import itemgetter class TestItemSortKey(TestCase): def test_simple_first(self): a = {'a': 1, 'c': 5, 'jack': 'jill', 'pick': 'axe', 'array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'} self.assertEqual( ...
def test_case(self): a = {'a': 1, 'c': 5, 'Jack': 'jill', 'pick': 'axe', 'Array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'} self.assertEqual( '{"Array": [1, 5, 6, 9], "Jack": "jill", "a": 1,
"c": 5, "crate": "dog", "pick": "axe", "tuple": [83, 12, 3], "zeak": "oh"}', json.dumps(a, item_sort_key=itemgetter(0))) self.assertEqual( '{"a": 1, "Array": [1, 5, 6, 9], "c": 5, "crate": "dog", "Jack": "jill", "pick": "axe", "tuple": [83, 12, 3], "zeak": "oh"}', json.dumps(...
davidam/python-examples
perceval/perceval_gerrit_me.py
Python
gpl-3.0
615
0
#! /usr/bin/env python3 from datetime import datetime, timedelta from pe
rceval.backends.core.gerrit import Gerrit # hostname of the Gerrit instance hostname = 'gerrit.opnfv.org' # user for sshing to the Gerrit instance user = 'd.arroyome' # retrieve on
ly reviews changed since one day ago from_date = datetime.now() - timedelta(days=1) # create a Gerrit object, pointing to hostname, using user for ssh access repo = Gerrit(hostname=hostname, user=user) # fetch all reviews as an iterator, and iterate it printing each review id for review in repo.fetch(from_date=from_da...
jasondunsmore/heat
heat_integrationtests/functional/test_default_parameters.py
Python
apache-2.0
3,045
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
_value: value: {get_resource: random1} ''' scenarios = [ ('none', dict(param=None, default=None, temp_def=True, expect1=50, expect2=40)), ('default', dict(param=None, default=12, temp_def=True, expect1=12, expect2=12)), ('both', dict(pa
ram=15, default=12, temp_def=True, expect1=12, expect2=15)), ('no_temp_default', dict(param=None, default=12, temp_def=False, expect1=12, expect2=12)), ] def setUp(self): super(DefaultParametersTest, self).setUp() def test_defaults(sel...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/network/cmd/ping/tasking_dsz.py
Python
unlicense
444
0.009009
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11
2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: tasking_dsz.py import mcl.framework import mcl.tasking class dsz: INTERFACE = 16842801 PFAM = 4129 PROVIDER_ANY = 4129 PROVIDER = 16846881 PROVIDER_FLAV = 16912417 RP
C_INFO_SEND = mcl.tasking.RpcInfo(mcl.framework.DSZ, [INTERFACE, PROVIDER_ANY, 0])
cga-harvard/cga-worldmap
geonode/proxy/views.py
Python
gpl-3.0
15,886
0.008939
import random from django.http import HttpResponse from httplib import HTTPConnection, HTTPSConnection from urlparse import urlsplit import httplib2 import urllib from django.utils import simplejson as json from django.conf import settings from django.contrib.auth.decorators import login_required from django.utils.html...
s[1]) > -90 else -90 coords[3] = coords[3] if float(coords[3]) < 90 else 90 newbbox = str(coords[0]) + ',' + str(coords[1]) + ',' + str(coords[2]) + ',' + str(coords[3]) url = url + "kind=" + kind + "&max-results=" + maxResults + "&bbox=" + newbbo
x + "&q=" + urllib.quote(query.encode('utf-8')) #+ "&alt=json" feed_response = urllib.urlopen(url).read() return HttpResponse(feed_response, mimetype="text/xml") def flickr(request): url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%s" % settings.FLICKR_API_KEY bbox = ...
Wopple/fimbulvetr
src/client/util.py
Python
bsd-3-clause
613
0.008157
import math def get_direction(src, targe
t): diff =
map(lambda a, b: a - b, target, src) mag = math.sqrt(sum(map(lambda a: a ** 2, diff))) if mag == 0: return [0, 0] return map(lambda a: a / mag, diff) def distance(pos1, pos2): return math.sqrt(sum(map(lambda a: a ** 2, map(lambda a, b: a - b, pos1, pos2)))) def magnitude(vector): return ma...
OxPython/Python-dict-str
dict_str.py
Python
epl-1.0
411
0.009756
''' Created on Jul 2, 2014 @author: viejoemer I can print a dict as a string in Python? ¿Yo puedo imprimi
r un dict como un string en Python? str(dict) Produces a printable string representation of a dictionary, but this not work for JSON format. ''' #Definition of a dictionary d = {'three': 3, 'two': 2, 'one': 1} print
(type(d)) print(d) #Print a dict like a string s = str(d) print(type(s)) print(s)
MiraHead/mlmvn
src/dataio/arffio.py
Python
gpl-2.0
8,420
0.000238
#! /usr/bin/env python ''' Arff loader for categorical and numerical attributes, based on scipy.io.arff.arffloader With minor changes for this project (eg. categorical attributes are mapped onto integers and whole dataset is returned as numpy array of floats) If any unsupported data types appear or if arff is malforme...
) return np.float(data) def safe_nominal(data, ls_values): """ nominal convertor """ svalue = data.strip() if svalue[0] == '{': raise ValueError("This looks like a sparse ARFF: not supported yet") if svalue in ls_values: return ls_values.index(svalue) else: raise ValueE...
(line): "
oehokie/brwry-python
device.py
Python
mit
1,314
0.05175
import RPi.GPIO as io io.setwarnings(False) io.setmode(io.BCM) class Device: def __init__(self,config): self.config = config for device in self.config['gpioPINs']['unavailable']: io.setup(int(device),io.OUT) io.output(int(device),False) for device in self.config['gpioPINs']['available']: io.setup(int...
ef updateDevices(se
lf,config): self.config = config def getCurStatus(self,devType): curStatus = {} for device in self.config[devType]: curStatus[str(device['deviceName'])] = io.input(int(device['gpioPIN'])) return curStatus def deviceStatus(self,pin): #note: checking the input of an output pin is permitted return io....
chaen/DIRAC
docs/diracdoctools/cmd/codeReference.py
Python
gpl-3.0
13,727
0.009543
#!/usr/bin/env python """ create rst files for documentation of DIRAC """ import os import shutil import socket import sys import logging import glob from diracdoctools.Utilities import writeLinesToFile, mkdir, makeLogger from diracdoctools.Config import Configuration, CLParser as clparser LOG = makeLogger('CodeRef...
it__.py' not in files: continue eli
f any(f.lower() in root.lower() for f in self.config.code_ignoreFolders): LOG.debug('Skipping folder: %s', root) continue modulename = root.split('/')[-1].strip('.') codePath = root.split(self.config.sourcePath)[1].strip('/.') docPath = codePath if docPat
fishstamp82/loprop
test/test_bond.py
Python
gpl-3.0
5,042
0.018247
import unittest import numpy as np str_nobond = """AU 3 1 2 1 1 0.00000000 0.00000000 0.00000000 -0.66387672 0.00000000 -0.00000000 0.34509720 3.78326969 -0.00000000 -0.00000000 3.96610412 0.00000000 3.52668267 0.00000000 -0.00000000 -2.98430053 0.00000000 ...
[8.0, 0.0, 1.0, 0.0, 1.0], dtype = float ) r_bond = a0 * np.array( [l.split()[1:4] for l in lines ], dtype = float) q_bond = np.array( [l.split()[4] for l in lines], dtype = float) d_bond = np.array( [l.split()[5:8] for l in lines], dtype = float) a_bond = np.ar
ray( [l.split()[8:15] for l in lines], dtype = float) b_bond = np.array( [l.split()[15:26] for l in lines], dtype = float) #Read in string that is for bonds output -b lines = [line for line in str_nobond.split('\n') if len(line.split()) > 10 ] n_nobond = np.array( [8.0, 1.0, 1.0], dtype = ...
atuljain/odoo
openerp/addons/base/ir/ir_http.py
Python
agpl-3.0
6,283
0.003183
#---------------------------------------------------------- # ir_http modular http routing #---------------------------------------------------------- import logging import re import sys import werkzeug.exceptions import werkzeug.routing import openerp from openerp import http from openerp.http import request from op...
rter, self).__init__(url_map) self.model = model # TODO add support for slug in the form [A-Za-z0-9-] bla-bla-89 -> id 89 self.regex = '([0-9,]+)' def to_python(self, value): return request.registry[self.model].browse(request.cr, UID_PLACEHOLDER, [int(i) for i in value.split(
',')], context=request.context) def to_url(self, value): return ",".join(i.id for i in value) class ir_http(osv.AbstractModel): _name = 'ir.http' _description = "HTTP routing" def _get_converters(self): return {'model': ModelConverter, 'models': ModelsConverter} def _find_handler...
googleapis/python-bigquery-storage
google/cloud/bigquery_storage_v1/reader.py
Python
apache-2.0
27,503
0.000618
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
_exhausted_exception_is_r
etryable(self, exc): if isinstance(exc, google.api_core.exceptions.ResourceExhausted): # ResourceExhausted errors are only retried if a valid # RetryInfo is provided with the error. # # TODO: Remove hasattr logic when we require google-api-core >= 2.2.0. ...
lyoniionly/django-cobra
src/cobra/core/configure/user_config.py
Python
apache-2.0
1,284
0.001558
from cobra.cor
e.loading import get_model from cobra.core import json class UserConfig(object): default_config = { 'guide.task.participant': '1', 'guide.document.share': '1', 'guide.customer.share': '1', 'guide.workflow.operation': '1', 'guide.workflow.createform': '1', 'order.ta...
.menu.display':'', 'viewState.task': 'list', 'guide.biaoge.showintro': '1', 'workreport.push.set': '1', 'agenda.push.set': '1' } def __init__(self, user): self.__user_config = self.__build_user_config(user) def __build_user_config(self, user): UserOption = g...
epcoullery/epcstages
stages/models.py
Python
agpl-3.0
27,475
0.00398
import json from collections import OrderedDict from contextlib import suppress from datetime import date, timedelta from django.conf import settings from django.db import models from django.db.models import Case, Count, When from . import utils CIVILITY_CHOICES = ( ('Madame', 'Madame'), ('Monsieur', 'Monsie...
self): return self.name def is_Ede_pe(self): return 'EDE' in self.name and 'pe' in self.name def is_Ede_ps(self): return 'EDE' in self.name and 'ps' in self.name class Teacher(models.Model): civility = models.CharField(max_length=10, choices=CIVILITY_CHOICES, verbose_name='Civili...
bose_name='Prénom') last_name = models.CharField(max_length=40, verbose_name='Nom') abrev = models.CharField(max_length=10, verbose_name='Sigle') birth_date = models.DateField(verbose_name='Date de naissance', blank=True, null=True) email = models.EmailField(verbose_name='Courriel', blank=True) cont...
josephbisch/the-blue-alliance
helpers/cache_clearer.py
Python
mit
14,357
0.003761
from google.appengine.ext import ndb from controllers.api.api_district_controller import ApiDistrictListController, ApiDistrictEventsController, ApiDistrictRankingsController from controllers.api.api_event_controller import ApiEventController, ApiEventTeamsController, \ ...
erence this media """ reference_keys = affected_refs['references'] years = affected_refs['year'] return cls._get_media_cache_keys_and_controllers(reference_keys, years) + \ cls._queries_to_cache_keys_and_controllers(get_affected_queries.media_updated(affected_refs)) @cl...
" Gets cache keys and controllers that reference this robot """ team_keys = affected_refs['team'] return cls._get_robots_cache_keys_and_controllers(team_keys) + \ cls._queries_to_cache_keys_and_controllers(get_affected_queries.robot_updated(affected_refs)) @classmethod ...
apache/incubator-superset
superset/db_engine_specs/hana.py
Python
apache-2.0
2,364
0.001269
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
": "TO_DATE({col})", "P1M": "TO_DATE(SUBSTRING(TO_DATE({col}),0,7)||'-01')", "P3M": "TO_DATE(SUBSTRING( \ TO_DATE({col}), 0, 5)|| LPAD(CAST((CAST(SUBSTRING(QUARTER( \ TO_DATE({col}), 1), 7, 1) as int)-1)*3 +1 as text),2,'0')
||'-01')", "P1Y": "TO_DATE(YEAR({col})||'-01-01')", } @classmethod def convert_dttm( cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None ) -> Optional[str]: tt = target_type.upper() if tt == utils.TemporalType.DATE: return f"TO_D...
callowayproject/django-tinymcewrapper
example/simpleapp/admin.py
Python
apache-2.0
377
0.002653
from django.contrib import admin from .models import SimpleModel, InlineModel c
lass SimpleInline(admin.TabularInline): model = InlineModel class SimpleModelAdmin(admin.ModelAdmin): list_display = ('name', ) prepopulated_fields = {'slug': ('name',)} s
earch_fields = ('name',) inlines = [SimpleInline] admin.site.register(SimpleModel, SimpleModelAdmin)
DalenWBrauner/FloridaDataOverlay
Website/Florida_Data_Overlay/Overlay/models.py
Python
mit
1,899
0.005793
from django import forms from django.db import models class Births(models.Model): year = models.IntegerField("Year") county = models.CharField("County",max_length=20) mothersAge = models.IntegerField("Mother's Age") mothersEdu = models.CharField("Mother's Education",max_length=50) source = models.U...
e) s += "%), according to " + self.source return s
class Upload(models.Model): upfile = models.FileField(upload_to='Updates Go Here')
foarsitter/equal-gain-python
decide/data/reader.py
Python
gpl-3.0
6,159
0.001461
# -*- coding: utf-8 -*- from __future__ import absolute_import import csv from copy import copy from typing import List, Dict import typesystem from .types import PartialActor, ActorIssue, PartialIssue, IssuePosition, IssueDescription, Comment types = { PartialActor.starts_with: PartialActor, ActorIssue.sta...
ition.issue in self.issues: issue = self.issues[issue_position.issue] if issue.lower is None: issue.lower = issue_position.position elif issue_position.position < issue.lower: i
ssue.lower = issue_position if issue.upper is None: issue.upper = issue_position.position elif issue_position.position > issue.upper: issue.upper = issue_position.position self.set_default_issue_positions() def set_de...
kyle8998/Practice-Coding-Questions
leetcode/295-Hard-Find-Median-From-Data-Stream/answer.py
Python
unlicense
2,682
0.010067
#!/usr/bin/env python3 #------------------------------------------------------------------------------- # Optimal 2 Heap O(1) Solution #------------------------------------------------------------------------------- from heapq import * class MedianFinder: def __init__(self): """ initialize your ...
ums)//2]) else: return (self.nums[len(self.nums)//2] + self.nums[(len(self.nums)//2)-1]) / 2 # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian() #---------------------------------------------------------...
---------------------
blakev/sowing-seasons
summer/ext/logs.py
Python
mit
362
0.005525
import socket from logging import Filter from summer.settings import APP_CONFIG class IPFilter(Filter): def __init__(self, nam
e=''): super(IPFilter, self).__init__(name) self.ip = soc
ket.gethostbyname(socket.gethostname()) def filter(self, record): record.ip = self.ip + ':%s' % APP_CONFIG.get('port', '??') return True
schlichtanders/pyparsing-2.0.3-OrderedDict
examples/excelExpr.py
Python
mit
2,327
0.017619
# excelExpr.py # # Copyright 2010, Paul McGuire # # A partial implementation of a parser of Excel formula expressions. # from pyparsingOD import (CaselessKeyword, Suppress, Word, alphas, alphanums, nums, Optional, Group, oneOf, Forward, Regex, operatorPrecedence, opAsso
c, dblQuotedString, delimitedList,
Combine, Literal, QuotedString) EQ,EXCL,LPAR,RPAR,COLON,COMMA = map(Suppress, '=!():,') EXCL, DOLLAR = map(Literal,"!$") sheetRef = Word(alphas, alphanums) | QuotedString("'",escQuote="''") colRef = Optional(DOLLAR) + Word(alphas,max=2) rowRef = Optional(DOLLAR) + Word(nums) cellRef = Combine(Group(Optional(...
crack-mx/habemoscurriculum
habemusCurriculum/habemusCurriculum/wsgi.py
Python
mit
411
0
""" WSGI config for habem
usCurriculum project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "h...
lication = get_wsgi_application()
GoogleCloudPlatform/sap-deployment-automation
third_party/github.com/ansible/awx/awx/conf/models.py
Python
apache-2.0
2,977
0
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. # Python import json # Django from django.db import models # Tower from awx.main.models.base import CreatedModifiedModel, prevent_search from awx.main.fields import JSONField from awx.main.utils import encrypt_field from awx.conf import settings_registry __a...
od def get_cache_id_key(self, key): return '{}_ID'.format(key) def display_value(self): if self.key == 'LICENSE' and 'license_key' in self.value: # don't log the license key in activity stream value = self.value.copy() value['license_key'] = '********' ...
a activity_stream_registrar.connect(Setting) import awx.conf.access # noqa
lehmannro/translate
misc/lru.py
Python
gpl-2.0
4,388
0.000684
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009 Zuza Software Foundation # # This file is part of translate. # # 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 o...
if not (len(self.queue) and self.queue[-1][0] == key): self.queue.append((key, value)) return value def __delitem__(self, key): # can't efficiently find item in queue to delete, check # boundaries. otherwise just wait til
l next cache purge while len(self.queue) and self.queue[0][0] == key: # item at left end of queue pop it since it'll be appended # to right self.queue.popleft() while len(self.queue) and self.queue[-1][0] == key: # item at right end of queue pop it since ...
william5065/fineMonkeyRunner
test.py
Python
apache-2.0
1,099
0.014138
#!/usr/bin/env finemonkeyrunner # -*- coding:utf8 -*- import sys sys.path.append(r'D:\learning\python\auto\fineMonkeyRunner') from com.fine.android.finemonkeyrunner import fineMonkeyRunner # 导入包路径,否则找不到 ---注意 #sys.path.append(r'C:\Users\wangxu\AppData\Local\Android\sdk\tools\testscript') #sys.path.append(r'D:\learning...
inemonkeyrunner.assertcurrentactivity('com.mdsd.wiicare/com.mdsd.wiicare.function.LoginActivity_') view = finemonkeyrunner.getviewbyID('id/etAccount') print finemonk
eyrunner.getviewinfo_classname(view) #print finemonkeyrunner.getelementinfo_locate('id/etAccount') #print finemonkeyrunner.getviewinfo_visible(view) #finemonkeyrunner.typebyid('id/etPassword','123') #ss = finemonkeyrunner.getviewssametext('id/drawerLayout','经鼻气管插管') #print finemonkeyrunner.viewlist #finemonkeyrunner.ge...
liuyonggg/learning_python
riddle/einstein.py
Python
mit
4,632
0.025907
from pyeda.inter import * ''' The Englishman lives in the red house. The Swede keeps dogs. The Dane drinks tea. The green house is just to the left of the white one. The owner of the green house drinks coffee. The Pall Mall smoker keeps birds. The owner of the yellow house smokes Dunhills. The man in the center house ...
ot (*[X[r,c,v] for v in range(1,6)]) for c in range(1,6)]) for r in range(1,6)]) self.C = And (*[ And (*[ OneHot (*[X[r,c,v] for r in range(1,6)])
for v in range(1,6)]) for c in range(1,6)]) # The Englishman lives in the red house. self.r1 = Or (*[ And(X[r, 1, 1], X[r, 2, 1]) for r in range(1,6)]) # The Swede keeps dogs. self.r2 = Or (*[ And(X[r, 1, 2], X[r, 3, 1]) for r in range(1,6)]) # The Dane drinks tea. self....
novafloss/django-anysign
demo/django_anysign_demo/models.py
Python
bsd-3-clause
253
0
from django_anysign import api as django_anysign class SignatureTy
pe(django_anysign.SignatureType): pass class Signature(django_anysign.SignatureFactory(SignatureType)): pass
class Signer(django_anysign.SignerFactory(Signature)): pass
jorisvandenbossche/DS-python-data-analysis
notebooks/_solutions/case4_air_quality_analysis9.py
Python
bsd-3-clause
327
0.009288
fig, ax = plt.subplots() data['2012':].mean().plot(kind='bar', ax=ax, rot=0, color='C0') ax.set_ylabel("NO$_2$ c
oncentration (µg/m³)") ax.axhline(y=40., color='darkorange') ax.text(0.01, 0.48, 'Yearly limit is 40 µg/m³', horizontal
alignment='left', fontsize=13, transform=ax.transAxes, color='darkorange');
hjq300/zim-wiki
zim/errors.py
Python
gpl-2.0
4,949
0.024247
# -*- coding: utf-8 -*- # Copyright 2009-2013 Jaap Karssenberg <[email protected]> # The Error class needed to be put in a separate file to avoid recursive # imports. '''This module contains the base class for all errors in zim''' import sys import logging logger = logging.getLogger('zim') use_gtk_error...
#~ except: #~ logger.error('Failed to run error dialog') def show_error(error): '''Show an error by calling L{log_error()} and when running interactive also calling L{ErrorDialog}. @param error: the error object ''' log_error(error) if use_gtk_errordialog: _run_error_dialog(error) def exception_handler(d...
to be used in C{except} blocks as a catch-all for both intended and unintended errors. @param debug: debug message for logging ''' # We use debug as log message, rather than the error itself # the error itself shows up in the traceback anyway exc_info = sys.exc_info() error = exc_info[1] del exc_info # recommen...
ulikoehler/cv_algorithms
test/TestGrassfire.py
Python
apache-2.0
513
0.009747
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import io from numpy.testing import assert_approx_equal, asse
rt_allclose, assert_array_equal from nose.tools import assert_equal, assert_true, assert_false, assert_greater, assert_less import cv2 import cv_algorithms import numpy as np class TestGrassfire(object): def test_grassfire(self): "Test grassfire transform" mask = np.zeros((10,10), dtype=np.uint8) ...
re(mask)
JShadowMan/trainquery
Example.py
Python
mit
1,687
0.012026
#!/usr/bin/env python3 # # Copyright (C) 2016-2017 ShadowMan # import time import random import asyncio import logging import cProfile from trainquery import train_query, utils, train_selector, train_query_result, exceptions logging.basicConfig(level = logging.INFO) async def foreach_train(result): ...
logging.info('query seat retry count exceeded. ignore this train[{}]'.format(selector.train_code)) print('\t\t', selector.train_code, await selector.check()) loop = asyncio.get_event_loop() loop.set_debug(True) query = train_query.TrainQuery() task = [ asyncio.ensure_future(query.que...
* 24, result_handler= foreach_train), loop = loop), asyncio.ensure_future(query.query('北京', '南京', int(time.time()) + 3600 * 24, result_handler = foreach_train), loop = loop), asyncio.ensure_future(query.query('北京', '南京', int(time.time()) + 3600 * 24, result_handler = foreach_train), loop = loop) ] # resu...
bennylope/django-simple-auth
tests/test_models.py
Python
bsd-2-clause
302
0
# encoding: utf-8 from __future__ import unicode_literals fr
om django.test import TestCase from simple_auth.models import Password class ModelTests(TestCase):
def test_save_object(self): Password.objects.create( name="My test", password="ajdkjkjakdj", )
antechrestos/cf-python-client
main/cloudfoundry_client/v3/service_instances.py
Python
apache-2.0
1,550
0.001935
from typing import Optional, TYPE_CHECKING, List from cloudfoundry_client.v3.entities import Entity, EntityManager, ToOneRelationship if TYPE_CHECKING: from cloudfoundry_client.client import CloudFoundryClient class ServiceInstanceManager(EntityManager): def __init__(self, target_endpoint: str, client: "Clo...
self, name: str, space_guid: str, service_plan_guid: str, meta_labels: Optional[dict] = None, meta_annotations: Optional[dict] = None, parameters: Optional[dict] = None, tags: Optional[List[str]] = None, ) -> Entity: data = { "name": ...
"type": "managed", "relationships": {"space": ToOneRelationship(space_guid), "service_plan": ToOneRelationship(service_plan_guid)}, } if parameters: data["parameters"] = parameters if tags: data["tags"] = tags if meta_labels or meta_annotations: ...
saikobee/pypixel
examples/rainbow_random_circles.py
Python
lgpl-2.1
257
0.023346
#!/usr/bi
n/python2 from pypixel import * show() h = 0 while True: x = random(WIDTH) y = random(HEIGHT) r = random(50, 100) h += 1 h %= 360 s = 100 v = 100 c = hsv2rgb((h, s, v)) circle(c, (x, y), r) update()
StephenBarnes/qtile
libqtile/window.py
Python
mit
42,566
0.000094
# Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "
Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software
is # furnished to do so, subject to the following conditions: # # 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 WA...
mikaelboman/home-assistant
homeassistant/components/netatmo.py
Python
mit
1,792
0
""" Support for the Netatmo devices (Weather Station and Welcome camera). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/netatmo/ """ import logging from urllib.error import HTTPError from homeassistant.const import ( CONF_API_KEY, CONF_PASSWORD, CON...
https://github.com/jabesq/netatmo-api-python/archive/' 'v0.5.0.zip#lnetatmo==0.5.0'] _LOGGER = logging.getLogger(__name__) CONF_SECRET_KEY = 'secret_key' DOMAIN = "netatmo" NETATMO_AUTH = None _LOGGER = logging.getLogger(__name__) def setup(hass, config): """Setup the Netatmo devices.""" if not valida...
CONF_USERNAME, CONF_PASSWORD, CONF_SECRET_KEY]}, _LOGGER): return None import lnetatmo global NETATMO_AUTH try: NETATMO_AUTH = lnetatmo.ClientAuth(config[DOMAIN][CONF_API_KEY]...
cocoloco69/pynet
week4/w4e2.py
Python
apache-2.0
1,206
0.021559
#!/usr/bin/env python import paramiko import time from getpass import getpass max_buffer = 65535 def send_command(rconn,cmd,idle): rconn.send(cmd + '\n') time.sleep(idle) return rconn.recv(max_buffer) def main(): ip_addr = '50.76.53.27' username = 'pyclass' password = getpass() port ...
conn = rconn_pre.invoke_shell() output = send_command(rconn,"term length 0",1) print output output = send_command(rconn,"show log",2)
print "Show log before changes\n %s" % output output = send_command(rconn,"conf t",1) print "Entering config mode\n %s" % output output = send_command(rconn,"logging buffered 10000",2) print "Making changes to the logging buffer\n %s" % output output = send_command(rconn,"exit",1) print ...
zhenxuan00/mmdgm
conv-mmdgm/layer/LogisticRegression.py
Python
mit
4,977
0.004219
import cPickle import gzip import os import sys import time import numpy import theano import theano.tensor as T class LogisticRegression(object): """ Multi-class Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classif...
# probabilities # Where: # W is a matrix where column-k represent the separation hyper plain for # class-k # x is a matrix where row-j represents input training sample-j # b is a vector where element-k represent the free parameter of hyper # plain-k # actuall...
escription of how to compute prediction as class whose # probability is maximal self.y_pred = T.argmax(self.p_y_given_x, axis=1) # end-snippet-1 # parameters of the model self.params = [self.W, self.b] def negative_log_likelihood(self, y): """ Return the mea...
GbalsaC/bitnamiP
openedx/core/djangoapps/user_api/preferences/tests/test_api.py
Python
agpl-3.0
17,881
0.003427
# -*- coding: utf-8 -*- """ Unit tests for preference APIs. """ import datetime import ddt import unittest from mock import patch from pytz import UTC from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings from dateu...
get_user_preference(self.user, self.test_preference_key), "new_value" ) @patch('openedx.core.djangoapps.user_api.models.UserPreference.delete') @patch('openedx.core.djangoapps.user_api.models.UserPreference.save') def test_update_user_preferences_errors(sel
f, user_preference_save, user_preference_delete): """ Verifies that set_user_preferences returns appropriate errors. """ update_data = { self.test_preference_key: "new_value
flammified/terrabot
terrabot/packets/packet5.py
Python
mit
340
0
from . import packet class Packet5(packet.Packet): def _
_init__(self, player, slot): super(Packet5, self).__init__(0x5) self.add_data(player.playerID) self.add_data(slot) self.add_structured_data("<h", 0) # Stack self.add_data(0) # Prefix self.add_s
tructured_data("<h", 0) # ItemID
mbarsacchi/mbarsacchi.github.com
python/MarkovChain_simple.py
Python
mit
2,443
0.011052
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Nov 14 10:59:19 2017 @author: marcobarsacchi """ import numpy.random as random class MarkovChain(object): """Simple Markov Chain Model. """ def __init__(self, n, P, T, states=None, verbose= False): """Initialize a simple Marko...
elf.state = random.choice(range(self.n),1,p=self.p)[0] self.verbose = verbose def set_state(self, state): """Set the state for the MarkovChain to the specified state. Can
be used for initialization. """ self.state = self.states.index(state) if self.states else state if self.verbose: state = self.states[self.state] if self.states else self.state print 'State is now: %s' % (state) def get_state(self): """Get the state of...
AwesomeTurtle/personfinder
app/admin_create_repo.py
Python
apache-2.0
2,406
0.000416
#!/usr/bin/python2.7 # Copyright 2016 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 required by applicable law or ...
profile_websites=DEFAULT_PROFILE_WEBSITES, map_default_zoom=6, map_default_center=[0, 0], map_size_pixels=[400, 280], read_auth_key_required=True, search_auth_key_required=True, deactivated=False, launched=False, deact...
results_page_custom_htmls={'en': '', 'fr': ''}, view_page_custom_htmls={'en': '', 'fr': ''}, seek_query_form_custom_htmls={'en': '', 'fr': ''}, footer_custom_htmls={'en': '', 'fr': ''}, bad_words='', published_date=get_utcnow_timestamp(), ...
anderslanglands/alShaders2
tests/tests.py
Python
bsd-3-clause
17,604
0.00409
# # # Copyright (c) 2014, 2015, 2016, 2017 Psyop Media Company, LLC # See license.txt # # import unittest import subprocess import os import OpenImageIO as oiio from OpenImageIO import ImageBuf, ImageSpec, ImageBufAlgo def get_all_arnold_tests(): """ Returns the list of arnold integration tests (Only run in Ar...
pixels(result, correct_result, threshold) if compresults is None: return if compresults.maxerror == 0.0: result_msg = file_name + " - Perfect match." else: result_msg = file_name + " - meanerror: %s rms_error: %s PSNR: %s maxerror: %s " % ( com...
(compresults.nfail, 0, "%s. Did not match within threshold %s. %s" % (msg, file_name, result_msg)) # if print_results: # print("Passed: (within tolerance) - ", result_msg) def assertAllResultImagesEqual(self, tolerance): """ Checks all correct images match resul...
maksimbulva/sc2streamhelper_info
battlenetclient/apps.py
Python
mit
105
0
from django.ap
ps import AppConfig class
BattlenetclientConfig(AppConfig): name = 'battlenetclient'
musicbrainz/picard
test/test_bytes2human.py
Python
gpl-2.0
4,925
0.000609
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2013, 2019-2020 Laurent Monin # Copyright (C) 2014, 2017 Sophist-UK # Copyright (C) 2017 Sambhav Kothari # Copyright (C) 2018 Wieland Hoffmann # Copyright (C) 2018-2019 Philipp Wolfer # # This program is free software; you can ...
test(lang) self.assertEqual(bytes2human.binary(45682), '44.6 KiB') self.assertEqual(bytes2human.binary(-45682), '-44.6 KiB') self.assertEqual(bytes2human.binary(-45682, 2), '-44.61 KiB') self.assertEqual(bytes2human.decimal(45682), '45.7 kB') self.assertEqual(byte
s2human.decimal(45682, 2), '45.68 kB') self.assertEqual(bytes2human.decimal(9223372036854775807), '9223.4 PB') self.assertEqual(bytes2human.decimal(9223372036854775807, 3), '9223.372 PB') self.assertEqual(bytes2human.decimal(123.6), '123 B') self.assertRaises(ValueError, bytes2human.deci...
sahildua2305/eden
modules/s3/s3profile.py
Python
mit
20,693
0.001546
# -*- coding: utf-8 -*- """ S3 Profile @copyright: 2009-2013 (c) Sahana Software Foundation @license: MIT 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 restrict...
ion doesn't serialize_url #m = ("%(id)s/*,*/%(id)s/*" % dict(id=id)).split(",") #filter = (S3FieldSelector(s).like(m))
| (S3FieldSelector(s) == id) m = ("%(id)s,%(id)s/*,*/%(id)s/*,*/%(id)s" % dict(id=id)).split(",") m = [f.replace("*", "%") for f in m] filter = S3FieldSelector(s).like(m) # @ToDo: #elif context == "organisation": # # Show records linked to this Organisation...
discoproject/disco
tests/test_raw.py
Python
bsd-3-clause
433
0.006928
from disco.test import Te
stCase, TestJob class RawJob(TestJob): @staticmethod def map(e, params): yield 'raw://{0}'.format(e), '' class RawTestCase(TestCase): def runTest(self): input = ['raw://eeny', 'raw://meeny', 'raw://miny', 'raw://moe'] self.job = RawJob().run(input=input) self.assertEqual(so...
nput))
erikjjpost/scripts
PcapTimeline.py
Python
cc0-1.0
1,022
0.03229
from scapy.all import * import plotly from datetime import datetime import pandas as pd #Read the packets from file packets=rdpcap('mypcap.pcap') #lists to hold packetinfo pktBytes=[] pktTimes=[] #Read each packet and append to the lists for pkt in packets: if IP in pkt: try: pktBytes.app...
ate to a timestamp df=df.set_index('Times') df2=df.resample('2S').sum() print(df2) #Create the graph plotly.offline.plot({ "data":[plotly.graph_objs.Scatter(x=df2.index, y=df2['Bytes'])], "layout":plotly.graph_objs.Layout(title="Bytes over Time ", xaxis=dict(title="Time"), yaxis
=dict(title="Bytes"))}) Output
FABtotum/colibri-fabui
fabui/ext/py/fabtotum/fabui/constants.py
Python
gpl-2.0
2,175
0.012414
#!/bin/env python # -*- coding: utf-8; -*- # # (c) 2016 FABtotum, http://www.fabtotum.com # # This file is part of FABUI. # # FABUI 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...
############# # ERROR CODES # ############################ ERROR_KILLED = 100 ERROR_STOPPED = 101 ERROR_DOOR_OPEN = 102 ERROR_MIN_TEMP = 103 ERROR_MAX_TEM
P = 104 ERROR_MAX_BED_TEMP = 105 ERROR_X_MAX_ENDSTOP = 106 ERROR_X_MIN_ENDSTOP = 107 ERROR_Y_MAX_ENDSTOP = 108 ERROR_Y_MIN_ENDSTOP = 109 ERROR_IDLE_SAFETY = 110 ERROR_WIRE_END = 111 ERROR_Y_BOTH_TRIGGERED = 120 ERROR_Z_BOTH_TRIGGERED = 121 ERROR_AMBIENT_TEMP = 122 ERROR_EXTRUDE_...
thinkingserious/sendgrid-onenote
app.py
Python
mit
2,377
0.008835
from flask import Flask, request import sendgrid import json import requests import os app = Flask(__name__) SENDGRID_USER = os.getenv('SENDGRID_USER') SENDGRID_PASS = os.getenv('SENDGRID_PASS') ONENOTE_TOKEN = os.getenv('ONENOTE_TOKEN') # Make the WSGI interface available at the top level so wfastcgi can get it. wsg...
return "HTTP/1.1 200 OK" @app.route('/', methods = ['GET']) def hello(): """Renders a sample page.""" return "Hello Universe!" @app.route('/tos', methods = ['GET']) def tos(): return "Terms of Servi
ce Placeholder." @app.route('/privacy', methods = ['GET']) def privacy(): return "Privacy Policy Placeholder." if __name__ == '__main__': import os HOST = os.environ.get('SERVER_HOST', 'localhost') try: PORT = int(os.environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 555...
jumoconnect/openjumo
server/configs/devinstance/local_settings.py
Python
mit
786
0.005089
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'jumodj
ango', 'USER': 'jumo', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', }, } PROXY_SERVER = "" BROKER_HOST = "" BROKER_PORT = 5672 BROKER_USER = "" BROKER_PASSWORD = "" BROKER_VHOST = "/" #Facebook settings FACEBOOK_APP_ID = '' FACEBOOK_API_KEY = '' FACEBOO
K_SECRET = '' STATIC_URL = "http://localhost:8000" HTTP_HOST = "localhost:8000" ADMIN_MEDIA_PREFIX = STATIC_URL + '/static/media/admin/' #ADMIN_MEDIA_PREFIX = 'http://static.jumo.com/static/media/admin/' IGNORE_HTTPS = True CELERY_ALWAYS_EAGER=True DSTK_API_BASE = "http://DSTKSERVER" # Make sure to fill in S3 info...
waqasbhatti/wcs2kml
python/fits/fitsparse.py
Python
bsd-3-clause
7,156
0.016769
#!/usr/bin/python # Copyright (c) 2007-2009, Google Inc. # Author: Ryan Scranton # All rights reserved. # # Redis
tribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form mus...
als provided with the distribution. # * Neither the name of Google Inc. nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ...
biomodels/MODEL1011090002
MODEL1011090002/model.py
Python
cc0-1.0
427
0.009368
import os path = os.path.dirname
(os.path.realpath(__file__)) sbmlFilePath = os.path.join(path, 'MODEL1011090002.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('libsb...
sbml = libsbml.readSBMLFromString(sbmlString)
Satariall/xvm-test
src/xpm/xvm_main/configwatchdog.py
Python
gpl-3.0
1,794
0.007246
""" XVM (c) www.modxvm.com 2013-2015 """ __all__ = ['startConfigWatchdog', 'stopConfigWatchdog'] # PUBLIC def startConfigWatchdog(): # debug('startConfigWatchdog') _g_configWatchdog.stopConfigWatchdog() _g_configWatchdog.configWatchdog() def stopConfigWatchdog(): # debug('stopConfigWatchdog') _...
urn except Exception, ex: err(traceback.format_exc()) self.configWatchdogTimerId = BigWorld.callback(1, self.configWatchdog) def stopConfigWatchdog(self): # deb
ug('stopConfigWatchdog') if self.configWatchdogTimerId is not None: BigWorld.cancelCallback(self.configWatchdogTimerId) self.configWatchdogTimerId = None _g_configWatchdog = _ConfigWatchdog()
camallen/aggregation
experimental/mongo/IBCC.py
Python
apache-2.0
12,657
0.009718
#!/usr/bin/env python from __future__ import print_function import csv import pymongo from itertools import chain, combinations import shutil import os import sys if os.path.exists("/home/ggdhines/github/pyIBCC/python"): sys.path.append("/home/ggdhines/github/pyIBCC/python") else: sys.path.append("/Users/greghi...
row[12] #has this species already been added to the list? i
f not(species in expertClassifications[subjectIndex]): expertClassifications[subjectIndex].append(species) #start off by assuming that we have classified all photos correctly correct_classification = [1 for i in range(len(self.subject_list))] counter = -1 #go through e...
adamjchristiansen/CS470
bzagents/other_pigeons/wild_pigeon.py
Python
gpl-3.0
2,746
0.02185
#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is...
0.py localhost 49857 ################################################################# import sys import math import time import random import numpy from bzrc import BZRC, Command from numpy import linspace class Agent(object): """Class handles all command and control logic for a teams tanks.""" def __init__(self...
() self.commands = [] self.num_ticks = 0 self.MAXTICKS = 100 def tick(self, time_diff): """Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.othertanks = othertanks self.flags = [flag for flag in flags if fl...
30loops/libthirty
libthirty/base.py
Python
bsd-3-clause
3,588
0.000279
# Copyright (c) 2011-2012, 30loops.net # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of condition...
self.request(se
lf.uri(), 'DELETE')
UNINETT/nav
tests/integration/models/model_test.py
Python
gpl-2.0
855
0
""" Query DB using Django models test Intended purpose is to catch obvious omissions in DB state or the Django models themselves. """ import os from django.db import connection try: # Django >= 1.8 import django.apps get_models = django.apps.apps.get_models del django.apps except ImportError: # D...
port get_models import pytest import nav.models # Ensure that all modules are loaded for file_name in os.listdir(os.path.dirname(nav.models.__file__)): if file_name.endswith('.py') and not file_name.startswith('__init__'): module_name = file_name.replace('.py', '') __import__('nav.models.%s' % mo...
name) @pytest.mark.parametrize("model", get_models()) def test_django_model(model): connection.close() # Ensure clean connection list(model.objects.all()[:5])
Panos512/inspire-next
inspirehep/dojson/experiments/model.py
Python
gpl-2.0
1,040
0
# -*- coding: utf-8 -*- # # This file
is part of INSPIRE. # Copyright (C) 2014, 2015, 2016 CERN. # # INSPIRE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # INSPIRE is d...
e hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with INSPIRE. If not, see <http://ww...
stuysu/roomres.stuysu.org
utils/utils.py
Python
mit
7,391
0.01353
import smtplib from pymongo import MongoClient import hashlib import re from random import randrange import datetime from calendar import monthrange #test connection = MongoClient("localhost", 27017, connect=False) db = connection['database'] collection = db['rooms'] """ Returns hashed password Args: text - strin...
""" def add_room(l): for room in l: check = list(db.rooms.find({'room': room})) today = str(datetime.date.today()) month = str(today.split('-')[1]) year = str(today.split('-')[0]) date = year + '-' + month + '-' month2 = str((int(month)+1)%12) if month=="12"...
t = {'day': date + str(d) , 'room':room, 'club': ''} t2 = {'day': date2 + str(d) , 'room':room, 'club': ''} d+=1 db.rooms.insert(t) db.rooms.insert(t2) """ adds club name to end of date-room-club Args: d = date r = room # e = club name Return...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/epmapper/epm_twr_t.py
Python
gpl-2.0
764
0.007853
# encoding: utf-8 # module samba.dcerpc.epmapper # from /usr/lib/python2.7/dist-packages/samba/dcerpc/epmapper.so # by generator 1.135 """ epmapper DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class epm_twr_t(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real ...
nknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with typ
e S, a subtype of T """ pass tower = property(lambda self: object(), lambda self, v: None, lambda self: None) # default tower_length = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
roadmapper/ansible
lib/ansible/modules/cloud/vultr/vultr_ssh_key_info.py
Python
gpl-3.0
3,509
0.001426
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2018, Yanis Guenane <[email protected]> # (c) 2019, René Moser <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = ...
ripti
on: Date the ssh key was created returned: success type: str sample: "2017-08-26 12:47:48" ssh_key: description: SSH public key returned: success type: str sample: "ssh-rsa AA... [email protected]" ''' from ansible.module_utils.basic import AnsibleModule from ansible.m...
kagalle/darfortie
darfortie/darfortie_params.py
Python
gpl-3.0
4,855
0.012358
# Script Name: darfortie.py # Author: Ken Galle # License: GPLv3 # Description: returns a dictionary of values to be used as parameters in the dar command: # dar_path : path and name to dar executable, optional, defaults to 'dar' # config : string, possibly None # prune : list of string, possibly empty # increm...
"the existing backups found in the destination folder. <source_path> is the " + \
"root path to back up (dar -R). <dest_path_and_base_name> is the dar base name. This " + \ "may include an optional path. This program will supply date strings to the final " + \ "name and dar itself will supply slice numbers to form the complete filename." epilogString = "Based on http://dar.linux.f...
PyFilesystem/pyfilesystem2
tests/test_url_tools.py
Python
mit
1,370
0.000731
# coding: utf-8 """Test url tools. """ from __future__ import unicode_literals import platform import unittest from fs._url_tools import url_quote class TestBase(unittest.TestCase): def test_quote(self): test_fixtures = [ # test_snippet, expected ["foo/bar/egg/foofoo", "foo/bar/e...
] ) else: test_fixtures.extend( [ # colon:tmp is bad path under Windows ["test/colon:tmp", "test/colon%3Atmp"], # Unix treat \ as %5C ["test/forward\\slash", "test/forward%5Cslash"...
.assertEqual(url_quote(test_snippet), expected)
shadowmint/nwidget
samples/snake/views/credits_view.py
Python
apache-2.0
1,085
0.004608
# Copyright 2013 Douglas Linder # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http:/
/www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language go
verning permissions and # limitations under the License. import pyglet import cocos import model import nwidget class CreditsView(cocos.layer.Layer): """ Testing class """ def __init__(self, assets): super(CreditsView, self).__init__() # Clear events from other views nwidget.events.clear(cocos.direc...
daedric/cntouch_driver
.ycm_extra_conf.py
Python
gpl-2.0
6,853
0.024953
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either...
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE ...
# # For more information, please refer to <http://unlicense.org/> import os import ycm_core # These are the compilation flags that will be used in case there's no # compilation database set (by default, one is not set). # CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. flags = [ '-Wall',...
System25/gecosws-config-assistant
firstboot_lib/Builder.py
Python
gpl-2.0
11,770
0.001869
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software 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, ...
(object, predicate=None): """Return all members of an object as (name,
value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError, RuntimeError: continue except Exception: continue ...
asposeslides/Aspose_Slides_Java
Plugins/Aspose-Slides-Java-for-Python/tests/WorkingWithText/ReplaceText/ReplaceText.py
Python
mit
393
0.007634
__author__ = 'fahadadeel' import jpype import os.path from WorkingWithText import Repl
aceText asposeapispath = os.path.join(os.path.abspath("../../../"), "lib") print "You need to put your Aspose.Slides for Java APIs .jars in this folder:\n"+asposeapispath jpype
.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % asposeapispath) testObject = ReplaceText('data/') testObject.main()
akvo/akvo-rsr
akvo/rsr/migrations/0068_iaticheck.py
Python
agpl-3.0
1,001
0.003996
# -*- coding: utf-8 -*- import django.db.models.deletion from django.db import models, migrations import akvo.rsr.fields class Migration(migrations.Migration): dependencies = [ ('rsr', '0067_auto_20160412_1858'), ] operations = [ migrations.CreateModel( name='IatiCheck', ...
atus')), ('description', akvo.rsr.fields.ValidXMLTextField(verbose_name='description')), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='iati_checks', verbose_name='project', to='rsr.Project')), ], options={ ...
, ]
tarikfayad/trelby
src/locations.py
Python
gpl-2.0
2,162
0.000463
import mypickle import util # manages location-information for a single screenplay. a "location" is a # single place that can be referred to using multiple scene names, e.g. # INT. MOTEL ROOM - DAY # INT. MOTEL ROOM - DAY - 2 HOURS LATER # INT. MOTEL ROOM - NIGHT class Locations: cvars = None def __init__(...
, and if that results in a location # with 0 scenes, removes that location completely. also upper-cases # all the scene names, sorts the lists, first each location list's # scenes, and then the locations based on the first scene of the # location. def refresh(self, sceneNames): locs = [] ...
or scene in sceneList: name = util.upper(scene) if (name in sceneNames) and (name not in added): scenes.append(name) added[name] = None if scenes: scenes.sort() locs.append(scenes) locs.sort() ...
verycumbersome/the-blue-alliance
controllers/ajax_controller.py
Python
mit
11,365
0.001848
import logging import os import urllib2 import json import time import datetime from base_controller import CacheableHandler, LoggedInHandler from consts.client_type import ClientType from google.appengine.api import memcache from google.appengine.api import urlfetch from google.appengine.ext import ndb from google.a...
mport Favorite from models.mobile_client import MobileClient from models.sitevar import Sitevar from models.typeahead_entry import TypeaheadEntry class AccountInfoHandler(LoggedInHandler): "
"" For getting account info. Only provides logged in status for now. """ def get(self): self.response.headers['content-type'] = 'application/json; charset="utf-8"' user = self.user_bundle.user self.response.out.write(json.dumps({ 'logged_in': True if user else False, ...
sdlBasic/sdlbrt
win32/mingw/opt/lib/python2.7/distutils/tests/test_check.py
Python
lgpl-2.1
4,034
0.000744
# -*- encoding: utf8 -*- """Tests for distutils.command.check.""" import unittest from test.test_support import run_
unittest from distutils.command.check import check, HAS_DOCUTILS from distutils.tests import support from distutils.errors import DistutilsSetupError class CheckTestCase(support.LoggingSilencer, support.TempdirManager, unittest.TestCase): def _run(self, metadata=None, **op...
cmd = check(dist) cmd.initialize_options() for name, value in options.items(): setattr(cmd, name, value) cmd.ensure_finalized() cmd.run() return cmd def test_check_metadata(self): # let's run the command with no metadata at all # by defau...
rhyolight/nupic.son
app/soc/modules/gci/views/readonly_template.py
Python
apache-2.0
879
0.002275
# Copyright 2012 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. #
You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the Licen...
he License. """Module containing the GCI readonly template classes. """ from soc.views import readonly_template class GCIModelReadOnlyTemplate(readonly_template.ModelReadOnlyTemplate): """Class to render readonly templates for GCI models. """ template_path = 'modules/gci/_readonly_template.html'
unnikrishnankgs/va
venv/lib/python3.5/site-packages/IPython/utils/tests/test_io.py
Python
bsd-2-clause
2,734
0.004023
# encoding: utf-8 """Tests for io.py""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import io as stdlib_io import os.path import stat import sys from io import StringIO from subprocess import Popen, PIPE import unittest import nose.tools as nt from IPython....
else: del tee def test(self): for chan in ['stdout', 'stderr']: for check in ['close', 'del']: self.tchan(chan, check) def test_io_init(): """Test that io.stdin/out/err exist at startup""" for name in ('stdin', 'stdout', 'stderr'): cmd = doctes...
) p = Popen([sys.executable, '-c', cmd], stdout=PIPE) p.wait() classname = p.stdout.read().strip().decode('ascii') # __class__ is a reference to the class object in Python 3, so we can't # just test for string equality. assert 'IPython.utils.io.IOStrea...
City-of-Helsinki/smbackend
services/migrations/0055_rename_unit_description_fields.py
Python
agpl-3.0
1,495
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-05-04 09:42 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("services", "0054_rename_last_modified_time"), ] operations = [ migrations.RenameFi...
new_name="description_fi", ), migrations.RenameField( model_name="unit", old_name="desc_sv", new_name="description_sv", ), migrations.RenameField( model_name="unit", old_name="short_desc", new_name="short_des...
nameField( model_name="unit", old_name="short_desc_en", new_name="short_description_en", ), migrations.RenameField( model_name="unit", old_name="short_desc_fi", new_name="short_description_fi", ), migrations.RenameFi...
michaeldove/abode
chat/protocol.py
Python
mit
735
0.008163
import re ################################################################################ # Human Command Protocol ################################################################################ class HumanCommandProtocol: def __init__(self): self.commands = (('^help', self.help),) def help(s...
p text, list of lines.. """ return ['describe controls'] def parse(self, text): """ Parse text and execute appropriate command. """ for (pattern, handler) in self.commands: match = re.search(pattern, text) if match:
return handler(text) return ('Unknown command',)
rg3915/wttd2
eventex/subscriptions/models.py
Python
mit
808
0
from django.db import models from django.shortcuts import resolve_url as r fr
om eventex.subscriptions.validators import validate_cpf class Subscription(models.Model): name = models.CharField('nome', max_length=100) cpf = models.CharField('CPF', max_length=11, validators=[validate_cpf]) email = models.EmailField('e-mail', blank=True) phone = models.CharField('telefone', max_len...
ield('criado em', auto_now_add=True) class Meta: ordering = ('-created_at',) verbose_name = 'inscrição' verbose_name_plural = 'inscrições' def __str__(self): return self.name def get_absolute_url(self): return r('subscriptions:detail', self.pk)
supracd/pygal
pygal/test/test_stacked.py
Python
lgpl-3.0
2,083
0
# -*- coding: utf-8 -*- # This file is part of pygal # # A python svg graph plotting library # Copyright © 2012-2015 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version...
version. # # This library 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser Gener...
d_line(): """Test stacked line""" stacked = StackedLine() stacked.add('one_two', [1, 2]) stacked.add('ten_twelve', [10, 12]) q = stacked.render_pyquery() assert set(q("desc.value").text().split(' ')) == set( ('1', '2', '11', '14')) def test_stacked_line_reverse(): """Test stack fro...
jianajavier/pnc-cli
pnc_cli/swagger_client/models/product_singleton.py
Python
apache-2.0
2,857
0.0014
# coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applica...
self.attribute_map = { 'content': 'content' } self._content = None @property def content(self): """ Gets the content of this ProductSingleton. :return: The content of this ProductSingleton. :rtype: ProductRest """ retu
rn self._content @content.setter def content(self, content): """ Sets the content of this ProductSingleton. :param content: The content of this ProductSingleton. :type: ProductRest """ self._content = content def to_dict(self): """ Returns ...
agaldona/odoo-addons
procurement_purchase_by_sale_contract/tests/test_procurement_purchase_by_sale_contract.py
Python
agpl-3.0
2,609
0
# -*- coding: utf-8 -*- # (c) 2016 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.
0.html import openerp.tests.common as common class TestProcurementPurchaseBySaleContract(common.TransactionCase): def setUp(self): super(TestProcurementPurchaseBySaleContract, self).setUp() self.procurement_model = self.env['procurement.order'] self.sale_model = self.env['sale.order'] ...
roduct_product_36') product.categ_id.procured_purchase_grouping = 'sale_contract' product.route_ids = [(6, 0, [self.ref('purchase.route_warehouse0_buy'), self.ref('stock.route_warehouse0_mto')])] account_vals = {'name': 'purchase_order...
manahl/mockextras
mockextras/__init__.py
Python
bsd-2-clause
69
0
from ._stub
import * from .
_fluent import * from ._matchers import *
tomato42/fsresck
tests/nbd/test_request.py
Python
gpl-2.0
6,139
0.000163
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Description: File system resilience testing application # Author: Hubert Kario <[email protected]> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Copyright (c) 2015 Hubert Kario. All rights reserved. # # This ...
onditions of the GNU General Public License version 2. # # This program i
s distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with th...
sam81/pysoundanalyser
pysoundanalyser/dialog_apply_filter.py
Python
gpl-3.0
11,571
0.00458
# -*- coding: utf-8 -*- # Copyright (C) 2010-2017 Samuele Carcagno <[email protected]> # This file is part of pysoundanalyser # pysoundanalyser 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...
oveWidget(self.endCutoffWidget) #self.endCutoffWidget.setParent(None) self.endCutoffWidget.deleteLater() elif prevFilterType == self.tr('highpass'): self.grid.removeWidget(self.cutoffLabel) #self.cutoffLabel.setParent(None) sel...
#self.startCutoffLabel.setParent(None) self.startCutoffLabel.deleteLater() self.grid.removeWidget(self.cutoffWidget) #self.cutoffWidget.setParent(None) self.cutoffWidget.deleteLater() self.grid.removeWidget(self.startCutoffWidget) ...
hb9kns/PyBitmessage
src/helper_random.py
Python
mit
172
0.005814
import
os from pyelliptic.openssl import OpenSSL def randomBytes(n): try: return os.urandom(n) except NotImplementedError: return OpenSSL.rand
(n)
cschulee/ee542-code
find_leds.py
Python
mit
2,091
0.020086
# find_leds.py Find LEDs # 2014-10-30 # The purpose of this script is to find the # coordinates of Light Emitting Diodes in # camera frame # Currently it only looks for green and stores # an intermediate and an altered picture back # to the current working directory, to show # things are working # Import necessar...
BLUE_MAX= np.array([120,255,255],np.uint8) # Convert img to Hue, Saturation, Value format hsv_img = cv2.cvtColor(img
,cv2.COLOR_BGR2HSV) # Threshold the image - results in b&w graphic where # in-threshold pixels are white and out-of-threshold # pixels are black img_threshed = cv2.inRange(hsv_img, BLUE_MIN, BLUE_MAX) # Find the circles circles = cv2.HoughCircles(img_threshed,cv2.cv.CV_HOUGH_GRADIENT,10,5,param1=200,param2=5,minRad...
plotly/plotly.py
packages/python/plotly/plotly/validators/treemap/_ids.py
Python
mit
430
0
import _plot
ly_utils.basevalidators class IdsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="ids", parent_name="treemap", **kwargs): super(IdsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, anim=kwargs.pop("an...
c"), **kwargs )
i5o/openshot-sugar
openshot/windows/TransitionProperties.py
Python
gpl-3.0
7,648
0.037003
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor is free software: you can redistribute it and/or modify # it under the terms of the GNU G...
project type dropdown box model = self.cboDirection.get_model() iter = model.get_iter_first() while True: # get the value of each item in the dropdown value = model.get_value(iter, 0).lower() # check for the matching project type if self.cur
rent_transition.reverse == False and value == _("Up").lower(): # set the item as active self.cboDirection.set_active_iter(iter) # check for the matching project type if self.current_transition.reverse == True and value == _("Down").lower(): # set the item as active self.cboDirection.set...
Alshain-Oy/Cloudsnake-Application-Server
code_examples/class_test_01.py
Python
apache-2.0
546
0.062271
#!/usr/bin/env python # Cloudsnake Application server # Licensed under
Apache License, see license.txt # Author: Markus Gronholm <[email protected]> Alshain Oy class Luokka( object ):
def __init__( self, N ): self.luku = N def test( self ): return self.luku def test_001( data ): #print >> cloudSnake.output, "Moi kaikki" #print >> cloudSnake.output, cloudSnake.call( 'mean', [ [1,2,3,4] ] ) print >> cloudSnake.output, "Luokkakoe nro 1" otus = cloudSnake.call( 'Luokka', [7] ) print ...
zstackio/zstack-woodpecker
integrationtest/vm/mini/image_replication/test_replicate_image_with_bs_almost_full.py
Python
apache-2.0
2,743
0.002552
''' New Integration test for image replication. Test Image Replicating while ImageStore Backup storage almost full @author: Legion ''' import os import time import random import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib from zstacklib.utils import ssh image_name = 'image-...
remove(bs) bs2 = bs_list[0] fallocate_size = int(bs.availableCapacity) - 9169934592 fallocate_size2 = int(bs2.availableCapacity) - 9989934592 fallocate_cmd = 'fallocate -l %s big_size_file' % fallocate_size fallocate_cmd2 = 'fallocate -l %s big_size_file' % fallocate_size2 ssh.execute(falloca...
env('imageUrl_windows')) img_repl.wait_for_image_replicated(image_name) img_repl.delete_image() img_repl.expunge_image() time.sleep(3) img_repl.add_image(image_name, bs_uuid=bs.uuid, url=os.getenv('imageUrl_raw')) img_repl.create_vm(image_name, 'image-replication-test-vm') img_repl.dele...
jkolbe/INF1340-Fall14-A1
exercise2.py
Python
mit
1,039
0.002887
#!/usr/bin/env python3 """ Perform a checksum on a UPC Assignment 1, Exercise 2, INF1340 Fall 2014 """ __autho
r__ = 'Joanna Kolbe, Tania Misquitta' __email__ = "[email protected]" __copyright__ = "2014 JK, TM" __status__ = "Prototype" # imports one per line def checksum (upc): """ Checks if the digits in a UPC is consistent with checksum :param upc: a 12-digit universal product code :return: Bo...
False, otherwise :raises: TypeError if input is not a strong ValueError if string is the wrong length (with error string stating how many digits are over or under """ # check type of input # raise TypeError if not string # check length of string # raise ValueError if not 12 ...
iglpdc/nipype
nipype/interfaces/dipy/tests/test_auto_TensorMode.py
Python
bsd-3-clause
882
0.010204
# AUTO-GENERATE
D by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..tensors import TensorMode def test_TensorMode_inputs(): input_map = dict(bvals=dict(mandatory=True, ), bvecs=dict(mandatory=True, ), in_file=dict(mandatory=True, ), mask_file=dict(), out_f
ilename=dict(genfile=True, ), ) inputs = TensorMode.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_TensorMode_outputs(): output_map = dict(out_f...
jackrzhang/zulip
zerver/templatetags/app_filters.py
Python
apache-2.0
6,764
0.001774
import os from html import unescape from typing import Any, Dict, List, Optional import markdown import markdown.extensions.admonition import markdown.extensions.codehilite import markdown.extensions.extra import markdown.extensions.toc import markdown_include.include from django.conf import settings from django.templ...
tional cases (such as our Freshdesk webhook docs), # code blocks in some of our Markdown templates have characters such # as '{' encoded as '&#123;' to prevent clashes with Jinja2 syntax, # but the encoded form never gets decoded because the text ends up # inside a <pre> tag. So here, we...
dered_html' is True. rendered_html = unescape(rendered_html) return mark_safe(rendered_html)
soscpd/bee
root/tests/zguide/examples/Python/fileio3.py
Python
mit
2,555
0.00274
# File Transfer model #3 # # In which the client requests each chunk individually, using # command pipelining to give us a credit-based flow control. import os from threading import Thread import zmq from zhelpers import socket_set_hwm, zpipe CHUNK_SIZE = 250000 def client_thread(ctx, pipe): dealer = ctx.socke...
dealer.send_multipart([ b"fetch", b"%i" % total, b"%i" % CHUNK_SIZE ]) try: chunk = dealer.recv() except zmq.ZMQError as e: if e.errno == zmq.ETERM: return #
shutting down, quit else: raise chunks += 1 size = len(chunk) total += size if size < CHUNK_SIZE: break # Last chunk received; exit print ("%i chunks received, %i bytes" % (chunks, total)) pipe.send(b"OK") # .split File server thread #...
logicalhacking/ExtensionCrawler
ExtensionCrawler/request_manager.py
Python
gpl-3.0
1,347
0.001485
import time import random from contextlib import contextmanager from multiprocessing import Lock, BoundedSemaphore, Value class RequestManager: def __init__(self, max_workers): self.max_workers = max_workers self.lock = Lock() self.sem = BoundedSemaphore(max_workers) self.last_requ...
time.sleep(max(0.0, self.last_restricted_request.value + 0.6 + (random.random() * 0.15) - time.time())) try: yield except Exception as e: raise e finally: self.last_request.value = time.time() self.sem.release()
@contextmanager def restricted_request(self): with self.lock: for i in range(self.max_workers): self.sem.acquire() time.sleep(max(0.0, self.last_request.value + 0.6 + (random.random() * 0.15) - time.time())) try: yield except Exception as e:...
mweb/python
exercises/simple-cipher/example.py
Python
mit
935
0
from string import ascii_lowercase from time import time import random class Cipher(object): def __init__(self, key=None): if not key: random.seed(time()) key = ''.join(random.choice(ascii_lowercase) for i in range(100)) elif not key.isalpha() or not key.islower(): ...
() key = self.key * (len(text) // len(self.key) + 1) return ''.join(chr((ord(c) - 194 + ord(k)) % 26 + 97) for c, k in zip(text, key)) def decode(sel
f, text): key = self.key * (len(text) // len(self.key) + 1) return ''.join(chr((ord(c) - ord(k) + 26) % 26 + 97) for c, k in zip(text, key)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, 'd')