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
obi-two/Rebelion
data/scripts/templates/object/tangible/deed/pet_deed/shared_kimogila_deed.py
Python
mit
691
0.037627
#### NOTICE: THIS FILE IS AUTOGENE
RATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/pet_deed/shared_kimogila_deed.iff" result.attribute_template_id = 2 result.stfName("pet_de
ed","kimogila") #### BEGIN MODIFICATIONS #### result.setStringAttribute("radial_filename", "radials/deed_datapad.py") result.setStringAttribute("deed_pcd", "object/intangible/pet/shared_kimogila_hue.iff") result.setStringAttribute("deed_mobile", "object/mobile/shared_kimogila_hue.iff") #### END MODIFICATIONS ...
alanfranz/duplicity
testing/overrides/gettext.py
Python
gpl-2.0
1,496
0.004016
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4; encoding:utf8 -*- # # Copyright 2014 Michael Terry <mike@mterry.name> # # This file is part of duplicity. # # Duplicity 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...
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 duplicity; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 0
2111-1307 USA # This is just a small override to the system gettext.py which allows us to # always return a string with fancy unicode characters, which will notify us # if we ever get a unicode->ascii translation by accident. def translation(*args, **kwargs): class Translation: ZWSP = u"​" # ZERO WIDTH SP...
KaoticEvil/Sopel-Modules
horoscope.py
Python
gpl-3.0
1,835
0.002725
''' A simple module for Sopel (http://sopel.chat) to get horoscope
information from a JSON API and put it back into chat All orignal code written by: BluDragyn. (www.bludragyn.net) This module is released under the terms of the GPLv3 (https://www.gnu.org/licenses/gpl-3.0.en.html) If you use and like this module, please send me an email
(dragyn@bludragyn.net) or drop in to see me on Occultus IRC (irc.occultus.net), I hang out in #sacredpaths ''' import json import urllib3 from sopel import module @module.commands('hs', 'horoscope') def horoscope(bot, trigger): signs = set(['aquarius', 'Aquarius', 'pisces', 'Pisces', ...
brunosmmm/hdltools
hdltools/vecgen/generate.py
Python
mit
4,978
0.000201
"""Generate pass.""" from scoff.ast.visits.syntax import ( SyntaxChecker, SyntaxCheckerError, SyntaxErrorDescriptor, ) class VecgenPass(SyntaxChecker): """Visit AST and generate intermediate code.""" _CONFIG_DIRECTIVES = ("register_size",) _SYNTAX_ERR_INVALID_VAL = SyntaxCheckerError("invali...
value = int(node.val, 2) except ValueError: raise self._SYNTAX_ERR_INVALID_VAL return value def visit_AbsTimeV
alue(self, node): """Visit absolute time value.""" if node.time < 0: raise self._SYNTAX_ERR_INVALID_VAL return {"mode": "abs", "time": node.time} def visit_RelTimeValue(self, node): """Visit relative time value.""" if node.time < 0: raise self._SYNTA...
F5Networks/f5-ansible
ansible_collections/f5networks/f5_modules/plugins/doc_fragments/f5ssh.py
Python
gpl-3.0
3,698
0.004327
# -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type class ModuleDocFragment(object): # Standard F5 documentation fragment DOCUMENTATION = r''' options: pro...
vironment variable C(ANSIBLE_NET_SSH_KEYFILE). type: path transport:
description: - Configures the transport connection to use when connecting to the remote device. type: str choices: ['cli'] default: cli no_f5_teem: description: - If C(yes), TEEM telemetry data is not sent to F5. - You may omit this ...
apache/allura
Allura/allura/tests/functional/test_feeds.py
Python
apache-2.0
3,296
0.000303
# 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 (t...
/feed.atom') self.app.post('/bugs/1/update_ticket', params=dict( assigned_to='', ticket_num='', labels='', summary='This is a new ticket', status='unread', milestone='', description='This is another description'), extra_environ=...
ct(username='root')) r = self.app.get('/bugs/1/feed.atom') assert '=&amp;gt' in r assert '\n+' in r
damahou/sagewui
sagewui/blueprints/static_paths.py
Python
gpl-3.0
1,622
0
# (c) 2015 J Miguel Farto, jmfarto@gmail.com r''' Aditional static paths ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os from flask import Blueprint from flask import current_app as app from flask.helper...
S_PATH from ..config import THREEJS_PATH static
_paths = Blueprint('static_paths', __name__) @static_paths.route('/css/<path:filename>') def css(filename): # send_static file secures filename return app.send_static_file(os.path.join('sage', 'css', filename)) @static_paths.route('/images/<path:filename>') @static_paths.route('/favicon.ico', defaults={'fil...
unioslo/pybofh
bofh/formatting.py
Python
gpl-3.0
11,183
0
# -*- coding: utf-8 -*- # # Copyright 2010-2019 University of Oslo, Norway # # This file is part of pybofh. # # pybofh 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 ...
ields if f.name not in data_set) def match(self, data_set): """ Check if this FormatItem applies to a given data set. :type data_set: dict :param data_set: A partial reponse (item). :rtype: bool :returns: True if the data_set contains all required field...
elf, data_set): """ Format a given data set with this FormatItem. :type data_set: dict :rtype: six.text_type """ values = tuple(get_formatted_field(f, data_set) for f in self.fields) return self.format_str % values class FormatSuggestion...
googleapis/python-dialogflow-cx
google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py
Python
apache-2.0
32,025
0.001624
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
nt) ) def __init__( self, *, credentials: ga_credentials.Credentials = None, transport: Union[str, PagesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic
_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the pages client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the applicati...
lumidify/fahrenheit451
AICharacter.py
Python
gpl-2.0
3,797
0.003687
import os import sys import random import pygame from Engine import * from Montag import * from Character import Character from pygame.locals import * class AICharacter(Character): def __init__(self, screen, **kwargs): super().__init__(screen, **kwargs) self.enemy = kwargs.get("enemy", None) ...
.pause_time = kwargs.get("pause_time", 1000) self.pause_time_passed = 0 def click(self): if self.dialog: self.dialogmanager.start_dialog(self.dialog) def hold_position(self): self.movement_state = None def update(self, current_time=None, event=None): if not curren...
= time_change else: self.pause_time_passed = 0 if not self.dead: if not self.movement_temporarily_suppressed: if not self.walk_to_points and self.pause_time_passed >= self.pause_time: if self.movement_state == "random_walk": ...
justquick/google-chartwrapper
setup.py
Python
bsd-3-clause
1,680
0.002976
from setuptools import setup, find_packages CLASSIFIERS = ( ('Development Status :: 4 - Beta'), ('Environment :: Console'), ('Environment :: Web Environment'), ('Framework :: Django'), ('Intended Audience :: Developers'), ('Intended Audience :: Science/Research'), ('I
ntended Audience :: System Ad
ministrators'), ('License :: OSI Approved :: BSD License'), ('Natural Language :: English'), ('Operating System :: OS Independent'), ('Topic :: Artistic Software'), ('Topic :: Internet :: WWW/HTTP'), ('Topic :: Internet :: WWW/HTTP :: Dynamic Content'), ('Topic :: Internet :: WWW/HTTP :: Dyn...
jmcarp/pycrawl
pycrawl/crawl.py
Python
bsd-3-clause
3,966
0.000504
import re import abc import asyncio import contextlib import urllib.parse as urlparse import aiohttp import pyquery from pycrawl.utils import Queue from pycrawl.http import Request from pycrawl.http import Response from pycrawl.middleware import CrawlerMiddlewareManager class Spider(metaclass=abc.ABCMeta): de...
loop=self._loop) body = yield from resp.read_and_close() response = Response(request, resp, body) for callback in self._middlewares['after_response']: response = callback(response) with self._request_context(self._loop, request, response): self.parse(response) ...
@contextlib.contextmanager def _request_context(self, request, response): self._context[self.task] = {'request': request, 'response': response} try: yield finally: del self._context[self.task] @abc.abstractmethod def parse(self, response): pass c...
houssine78/addons
stock_picking_back2draft/models/__init__.py
Python
agpl-3.0
161
0
# -*- coding: utf-8 -*- # © 2016 Lorenzo Battistini - Agile Busines
s Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import
stock
patrickwind/My_Blog
venv/lib/python2.7/site-packages/click/types.py
Python
gpl-2.0
15,176
0
import os import sys import stat from ._compat import open_stream, text_type, filename_to_ui, get_streerror from .exceptions import BadParameter from .utils import safecall, LazyFile class ParamType(object): """Helper for converting values through types. The following is necessary for a valid type: * ...
rovides one.""" def get_missing_message(self, param): """Optionally might return extra information about a missing parameter. .. versionadded:: 2.0 """
def convert(self, value, param, ctx): """Converts the value. This is not invoked for values that are `None` (the missing value). """ return value def split_envvar_value(self, rv): """Given a value from an environment variable this splits it up into small chunks dep...
SkyTruth/pybossa_tools
drillpadcatimgtaskload.py
Python
agpl-3.0
1,281
0.003123
#! /usr/bin/env python #
-*- coding: utf-8 -*- import os import sys import os.path import createTasks import csv import json SERVER = "http://crowdcrafting.org" URL_ROOT = "https://s3-us-west-2.amazonaws.com/drillpadcat/" def dictre
ader(rows): rows = iter(rows) header = rows.next() for row in rows: yield dict(zip(header, row)) if len(sys.argv) != 4: print """Usage: drillpadcatimgtaskload.py frackfinder 00000000-0000-0000-0000-000000000000 somefile.csv Replace the zeroes with your access key The csv should contain at lea...
Abjad/abjad
abjad/_update.py
Python
gpl-3.0
15,897
0.000944
""" Updates start offsets, stop offsets and indicators everywhere in score. .. note:: This is probably the most important part of Abjad to optimize. Use the profiler to figure out how many unnecessary updates are happening. Then reimplement. As a hint, the update manager implements a weird version of the "obs...
r = _duration.Multiplier(60, metronome_mark.units_per_minute) clocktime_duration = duration / metronome_mark.reference_duration clocktime_duration *= multiplier timespan = _timespan.Timespan( start_offset=start_offset, stop_offset=stop_offset, annotation=(cloc...
clocktime_duration), ) timespans.append(timespan) clocktime_start_offset += clocktime_duration return timespans # TODO: reimplement with some type of bisection def _to_measure_number(component, measure_start_offsets): component_start_offset = component._get_timespan().start_offset ...
marcus-nystrom/share-gaze
sync_clocks/test_clock_resolution.py
Python
mit
1,930
0.020207
# -*- coding: utf-8 -*- """ Created on Wed Sep 09 13:04:53 2015 * If TimerTool.exe is running, kill the process. * If input parameter is given, start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """ ...
td3.append((datetime.d
atetime.now()-t3).total_seconds()) time.sleep(0.001) # Create text file and write header t = datetime.datetime.now() ip = gethostbyname(gethostname()).split('.')[-1] f_name = '_'.join([ip,'test_clock_res',str(t.year),str(t.month),str(t.day), str(t.h...
plotly/python-api
packages/python/plotly/plotly/validators/surface/_surfacecolor.py
Python
mit
459
0.002179
import _plotly_utils.basevalidators class Surfaceco
lorValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="surfacecolor", parent_name="surface", **kwargs): super(SurfacecolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type",...
ta"), **kwargs )
rosalindfdt/huzzahbadge
huzzah/register/setup.py
Python
artistic-2.0
1,740
0.000575
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from s
etuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: lo
ng_description = f.read() setup( name='adafruit-circuitpython-register', use_scm_version=True, setup_requires=['setuptools_scm'], description='CircuitPython data descriptor classes to represent hardware registers on I2C and SPI devices.', long_description=long_description, # The project's ma...
TathagataChakraborti/resource-conflicts
PLANROB-2015/seq-sat-lama/Python-2.5.2/Doc/tools/toc2bkm.py
Python
mit
4,520
0.000442
#! /usr/bin/env python """Convert a LaTeX .toc file to some PDFTeX magic to create that neat outline. The output file has an extension of '.bkm' instead of '.out', since hyperref already uses that extension. """ import getopt import os import re import string import sys # Ench item in an entry is a tuple of: # # ...
_TO_INNER: toc = toc[-1][-1] stack.insert(0, toc) toc.append(entry) else: for i in range(direction):
del stack[0] toc = stack[0] toc.append(entry) level = stype else: sys.stderr.write("l.%s: " + line) return top hackscore_rx = re.compile(r"\\hackscore\s*{[^}]*}") raisebox_rx = re.compile(r"\\raisebox\s*{[^}]*}") titl...
enthought/etsproxy
enthought/mayavi/core/api.py
Python
bsd-3-clause
84
0
# proxy modu
le from __future__ import absolu
te_import from mayavi.core.api import *
janeen666/mi-instrument
mi/core/test/test_persistent_store.py
Python
bsd-2-clause
11,196
0.003483
#!/usr/bin/env python """ @package mi.core.test.test_persistent_store @file <git-workspace>/ooi/edex/com.raytheon.uf.ooi.plugin.instrumentagent/utility/edex_static/base/ooi/instruments/mi-instrument/mi/core/test/test_persistent_store.py @author Johnathon Rusk @brief Unit tests for PersistentS
toreDict module """ # Note: Execute via, "nosetests -a UNIT -v mi/core/test/test_persistent_store.py" __author__ = 'Johnathon Rusk' __license__ = 'Apache 2.0' from nose.plugins.attrib import attr from mi.core.unit_test import MiUnitTest import sys from mi.core.persistent_store import PersistentStoreDict @attr('UNI...
_VALUES = [u"this is a unicode string", u"this is another unicode string"] self.INT_KEY = u"INT_KEY" self.INT_VALUES = [1234, 5678] self.LONG_KEY = "LONG_KEY" # Test 'str' type key self.LONG_VALUES = [sys.maxint + 1, sys.maxint + 2] self.FLOAT_KEY = u"FLOAT_KEY" self.FLOA...
wcmitchell/insights-core
insights/parsers/tests/test_hostname.py
Python
apache-2.0
685
0
from insights.parsers.hostname import Hostname from insights.tests import context_wrap HOSTNAME = "rhel7.example.com" HOSTNAME_SHORT = "rhel7" def test_hostname(): data = Hostname(context_wrap(HOSTNAME)) assert data.fqdn == "rhel7.example.com" assert data.hostname == "rhel7" assert data.domain == "ex...
assert data.domain == "" data = Hostname(context_wrap("")) assert data.fqdn is None assert data.hostname is None assert data.domain is
None
xdevelsistemas/taiga-back-community
tests/integration/resources_permissions/test_application_tokens_resources.py
Python
agpl-3.0
4,691
0.000853
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # Copyright (C) 2014-2016 Anler Hernández ...
"pk
": data.token.id}) users = [ None, data.registered_user, data.registered_user_with_token ] results = helper_test_http_method(client, "get", url, None, users) assert results == [401, 404, 200] def test_application_tokens_authorize(client, data): url=reverse('application-to...
kafana/ubik
lib/ubik/fab/tgz.py
Python
gpl-3.0
1,827
0.004926
# Copyright 2012 Lee Verberne <lee@blarg.org> # # 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 3 of the License, or # (at your option) any later version. # # This program is dis...
but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. i...
gging.getLogger(NAME) def _get_config(configfile='package.ini'): config = ConfigParser.SafeConfigParser() config.read(configfile) return config def untar(version, config, env): 'Downloads a file URI and untars to builddir' if not version: version = '' if not config: config = _g...
calfonso/python-citrination-client
citrination_client/search/pif/query/chemical/composition_query.py
Python
apache-2.0
4,113
0.004619
from citrination_client.search.pif.query.chemical.chemical_field_operation import ChemicalFieldOperation from citrination_client.search.pif.query.core.base_object_query import BaseObjectQuery from citrination_client.search.pif.query.core.field_operation import FieldOperation class CompositionQuery(BaseObjectQuery): ...
.setter def actual_weight_percent(self, actual_weight_percent): self._actual_weight_percent = self._get_object(FieldOperation, actual_weight_percent) @actual_weight_percent.deleter def actual_weight_percent(self): self._actual_weight_percent = None @property def actual_atomic_perce...
l_atomic_percent = self._get_object(FieldOperation, actual_atomic_percent) @actual_atomic_percent.deleter def actual_atomic_percent(self): self._actual_atomic_percent = None @property def ideal_weight_percent(self): return self._ideal_weight_percent @ideal_weight_percent.setter ...
dilosung/ad-manage
config/settings/common.py
Python
mit
13,364
0.002469
# -*- coding: utf-8 -*- """ Django settings for ad-manage project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from __future__ import absolute_import, unicode_l...
out', 'oscar.apps.customer.notifications.context_processors.notification
s', 'oscar.core.context_processors.metadata', # django-social-auth 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', ], }, }, ] # See: http://django-crispy-forms.readt...
gencer/mwparserfromhell
mwparserfromhell/nodes/html_entity.py
Python
mit
6,771
0.000148
# -*- coding: utf-8 -*- # # Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.
com> # # 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...
e, 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 ...
mhaddy/FeedGoo
man_feedgoo.py
Python
gpl-3.0
2,896
0.020718
#!/usr/bin/python # encoding: utf-8 # license: MIT # Raspberry Pi-pow
ered cat feeder # Ryan Matthews # mhaddy@gmail.com #import schedule import time import datetime import logging import RPi.GPIO as GPIO from twython import Twython import configvars as cv from random impo
rt randint import pygame import pygame.camera from pygame.locals import * import requests # cronitor requests.get( 'https://cronitor.link/{}/run'.format(cv.cronitor_hash), timeout=10 ) logging.basicConfig(filename=cv.log_dir+cv.log_filename,format='%(asctime)s : %(levelname)s : %(message)s',level=logging.INFO) ...
rwl/muntjac
muntjac/test/server/component/test_tab_sheet.py
Python
apache-2.0
3,921
0.001275
# @MUNTJAC_COPYRIGHT@ # @MUNTJAC_LICENSE@ from unittest import TestCase from muntjac.ui.label import Label from muntjac.ui.tab_sheet import TabSheet class Tes
tTabSheet(TestCase): def testAddExistingComponent(self): c = Label('abc') tabSheet = TabSheet()
tabSheet.addComponent(c) tabSheet.addComponent(c) itr = tabSheet.getComponentIterator() self.assertEquals(c, itr.next()) self.assertRaises(StopIteration, itr.next) self.assertNotEquals(tabSheet.getTab(c), None) def testGetComponentFromTab(self): c = Label('abc') ...
twotymz/lucy
hue/lights.py
Python
mit
705
0.025532
import logging import requests HUE_IP = '192.168.86.32' HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6' logger = logging.getLogger('hue') def getLights(): url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME) try: r = requests.get(url) except: logger.error('Failed getting stat...
_code == 200: data = r.json() return data def getStatus(id): url = 'http://{0}/api/{1}/lights/{2}'.format(HUE_IP, HUE_USERNAME, id) try: r = requests.get(url) except: logger.error('Failed getting status for light {0}'.for
mat (id)) return if r.status_code == 200: data = r.json() return data
jamslevy/gsoc
app/soc/logic/models/timeline.py
Python
apache-2.0
1,237
0.003234
#!/usr/bin/python2.5 # # Copyright 2009 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...
rt sponsor as sponsor_logic import soc.models.timeline class Logic(base.Logic): """Logic methods for the Timeline model. """ def __init__(self, model=soc.models.timeline.Timeline, base_model=None, scope_logic=sponsor_logic): """Defines the name, key_name and model for this entity. """ ...
_logic=scope_logic) logic = Logic()
tkaitchuck/nupic
external/linux64/lib/python2.6/site-packages/matplotlib/backend_bases.py
Python
gpl-3.0
69,740
0.003656
""" Abstract base classes define the primitives that renderers and graphics contexts must implement to serve as a matplotlib backend :class:`RendererBase` An abstract base class to handle drawing/rendering operations. :class:`FigureCanvasBase` The abstraction layer that separates the :class:`matplotlib.fi...
arker_trans + transforms.Affine2D().translate(x, y), rgbFace) def draw_path_collection(self, master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths...
electing drawing properties from the lists *facecolors*, *edgecolors*, *linewidths*, *linestyles* and *antialiaseds*. *offsets* is a list of offsets to apply to each of the paths. The offsets in *offsets* are first transformed by *offsetTrans* before being applied. This...
ShaolongHu/Nitrate
tcms/testplans/forms.py
Python
gpl-2.0
20,537
0
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.contrib.auth.models import User from odf.odf2xhtml import ODF2XHTML, load from tcms.core.contrib.xml2dict.xml2dict import XML2Dict from tcms.core.forms.fields import UserField, StripURLField from tinymce.widgets import TinyM...
# So we have to define the category_name at the moment then get the # product from the plan. # If we did not found the c
ategory of the product we will create one. element = 'categoryname' if case.get(element, {}).get('value'): category_name = case[element]['value'] else: raise forms.ValidationError( self.error_messages['element_is_required'] % element) # Check or c...
tv42/downburst
downburst/image.py
Python
mit
5,246
0.000191
import logging import requests import tarfile from lxml import etree from . import discover from . import template log = logging.getLogger(__name__) URLPREFIX = 'https://cloud-images.ubuntu.com/precise/current/' PREFIXES = dict( server='{release}-server-cloudimg-amd64.', desktop='{release}-desktop-cloudi...
d_images(pool, release, flavor): """ List all Ubuntu 12.04 Cloud image in the libvirt pool. Return the keys. """ PREFIX = PREFIXES[flavor].format(release=release) for name in pool.listVolumes(): log.debug('Considering image: %s', name) if not name.startswith(PREFIX
): continue if not name.endswith(SUFFIX): continue if len(name) <= len(PREFIX) + len(SUFFIX): # no serial number in the middle continue # found one! log.debug('Saw image: %s', name) yield name def find_cloud_image(pool, release, f...
yast/yast-python-bindings
examples/Table-sorting.py
Python
gpl-2.0
1,203
0.004988
# encoding: utf-8 from yast import import_module import_module('UI') from yast import * class TableSortingClient: def main(self): UI.OpenDialog( VBox( Label("Library"), MinSize( 30, 10, T
able( Header("Book Title", "Shelf"), [ Item(Id(1), "3 Trees", " -6"), Item(Id(2), "missing", None), Item(Id(3), "just another book", " 8a"), Item(Id(4), "Here comes Fred", 12), Item(Id(5), "Zoo", 25), ...
Lions", "balbla"), Item(Id(7), "Elephants ", "8b"), Item(Id(8), "wild animals", "a7"), Item(Id(9), "Weather forecast", "15yxc"), Item(Id(10), "my first Book", 1), Item(Id(11), "this is yours", 95), Item(Id(12), "Terra X", " ...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/lib2to3/fixes/fix_unicode.py
Python
gpl-3.0
1,256
0.002389
r"""Fixer for unicode. * Changes unicode to str and unichr to chr. * If "...\u..." is not unicode literal change it into "...\\u...". * Change u"..." into "...". """ from ..pgen2 import token from .. import fixer_base _mapping = {"unichr" : "chr", "unicode" : "str"} class FixUnicode(fixer_base.BaseFix): BM_c...
super(FixUnicode, self).start_tree(tree, filename) self.unicode_literals = 'unicode_literals' in tree.future_features def transform(self, node, results): if node.type == token.NAME: new = node.clone() new.value = _mapping[node.value]
return new elif node.type == token.STRING: val = node.value if not self.unicode_literals and val[0] in '\'"' and '\\' in val: val = r'\\'.join([ v.replace('\\u', r'\\u').replace('\\U', r'\\U') for v in val.split(r'\\') ...
kristinriebe/django-prov_vo
prov_vo/apps.py
Python
apache-2.0
129
0
from __future__ import unico
de_literals from
django.apps import AppConfig class ProvVoConfig(AppConfig): name = 'prov_vo'
cXhristian/django-wiki
src/wiki/plugins/images/markdown_extensions.py
Python
gpl-3.0
4,717
0.000424
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import markdown from django.template.loader import render_to_string from wiki.plugins.images import models, settings IMAGE_RE = re.compile( r'.*(\[image\:(?P<id>[0-9]+)(\s+align\:(?P<align>right|left))?(\s+size\:(?P<size>default|small|medi...
es. For instanc
e: [image:id align:left|right|center] This is the caption text maybe with [a link](...) So: Remember that the caption text is fully valid markdown! """ def run(self, lines): # NOQA new_text = [] previous_line = "" line_index = None previous_line_was_image = Fa...
coxmediagroup/googleads-python-lib
examples/dfa/v1_20/get_advertisers.py
Python
apache-2.0
2,314
0.005618
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file
except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR C
ONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fetches all advertisers in a DFA account. This example displays advertiser name, ID and spotlight configuration ID for the given search criteria. Results are limi...
google/uncertainty-baselines
baselines/mnist/utils.py
Python
apache-2.0
5,866
0.008012
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines 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 ap...
in the bins tau_tab = np.linspace(0, 1, num_bins+1) # confidence bins for i in np.arange(num_bins): # iterate over the bins # select the items where the predicted max probability fall
s in the bin # [tau_tab[i], tau_tab[i + 1)] sec = (tau_tab[i + 1] > conf) & (conf >= tau_tab[i]) nb_items_bin[i] = np.sum(sec) # Number of items in the bin # select the predicted classes, and the true classes class_pred_sec, y_sec = class_pred[sec], y[sec] # average of the predicted max probabi...
wxgeo/geophar
wxgeometrie/sympy/plotting/experimental_lambdify.py
Python
gpl-2.0
26,133
0.001378
""" rewrite of lambdify - This stuff is not stable at all. It is for internal use in the new plotting module. It may (will! see the Q'n'A in the source) be rewritten. It's completely self contained. Especially it does not use lambdarepr. It does not aim to replace the current lambdify. Most importantly it will never...
cmath or even to evalf. The following translations are tried: only numpy complex - on errors raised by sympy trying
to work with ndarray: only python cmath and then vectorize complex128 When using python cmath there is no need for evalf or float/complex because python cmath calls those. This function never tries to mix numpy directly with evalf because numpy does not understand sympy Float. If this is nee...
sh4r3m4n/twitter-wikiquote-bot
bot.py
Python
gpl-3.0
1,879
0.009052
#-*- coding: utf- -*- import os import sys import random import time import json import wikiquote import tuitear from threading import Thread CONGIG_JSON = 'bots.json'
# Variable local, para modificar el intervalo real cambiar la configuración INTERVALO = 1 stop = False def start_bot(bot): """ Hilo que inicia el bot pasado como argumento (diccionario) """ citas = [] for pagina in bot['paginas']: print 'Cargando', pagina quotes = wikiquote.get_quotes(pa...
citas += quotes tiempo = 0 while not stop: if tiempo >= bot['intervalo']: quote, pagina = random.choice(citas) tweet = bot['format'].encode('utf8') % dict(pagina = \ pagina.encode('utf8'), frase = quote.encode('utf8')) if len(tweet) > 138: ...
Khilo84/PyQt4
examples/draganddrop/delayedencoding/delayedencoding.py
Python
gpl-2.0
4,777
0.007327
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2010 Hans-Peter Jansen <hpj@urpla.net>. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_...
:") dragIcon = QtGui.QPushButton("Export") dragIcon.setIcon(QtGui.QIcon(':/images/drag.png')) dragIcon.pressed.connect(self.startDrag) layout = QtGui.QGridLayout() layout.addWidget(instructTopLabel, 0, 0, 1, 2)
layout.addWidget(imageArea, 1, 0, 2, 2) layout.addWidget(instructBottomLabel, 3, 0) layout.addWidget(dragIcon, 3, 1) self.setLayout(layout) self.setWindowTitle("Delayed Encoding") def createData(self, mimeType): if mimeType != 'image/png': return i...
eandersson/amqp-storm
amqpstorm/tests/functional/management/basic_tests.py
Python
mit
2,492
0
from amqpstorm.management import ManagementApi from amqpstorm.message import Message from amqpstorm.tests import HTTP_URL from amqpstorm.tests import PASSWORD from amqpstorm.tests import USERNAME from amqpstorm.tests.utility import TestFunctionalFramework from amqpstorm.tests.utility import setup class ApiBasicFuncti...
name, requeue=False) self.assertIsInstance(result, list) self.assertIsInstance(result[0], Message) self.assertEqual(result[0].bo
dy, self.message) # Make sure the message wasn't re-queued. self.assertFalse(api.basic.get(self.queue_name, requeue=False)) @setup(queue=True) def test_api_basic_get_message_requeue(self): api = ManagementApi(HTTP_URL, USERNAME, PASSWORD) api.queue.declare(self.queue_name) ...
tensorflow/tensorflow
tensorflow/python/data/experimental/kernel_tests/optimization/shuffle_and_repeat_fusion_test.py
Python
apache-2.0
2,195
0.003645
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
options.experimental_optimization.shuffle_and_repeat_fusion = True dataset = dataset.with_options(options) get_next = self.getNext(dataset) for
_ in range(2): results = [] for _ in range(10): results.append(self.evaluate(get_next())) self.assertAllEqual([x for x in range(10)], sorted(results)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(get_next()) with self.assertRaises(errors.OutOfRangeError): s...
tensorflow/datasets
tensorflow_datasets/summarization/gigaword.py
Python
apache-2.0
4,196
0.003337
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets 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 appl...
rmat. There are two features: - document: article. - summary: headline. """ _URL = "https://drive.google.com/uc?export=download&id=1USoQ8lJgN8kAWnUnRrupMGrPMLlDVqlV" _DOCUMENT = "document" _SUMMARY = "summary" class Gigaword(tfds.core
.GeneratorBasedBuilder): """Gigaword summarization dataset.""" # 1.0.0 contains a bug that uses validation data as training data. # 1.1.0 Update to the correct train, validation and test data. # 1.2.0 Replace <unk> with <UNK> in train/val to be consistent with test. VERSION = tfds.core.Version("1.2.0") de...
networkpadwan/appliedpython
week1/parse2.py
Python
apache-2.0
435
0.009195
#!/usr/bin/env python from cisc
oconfparse import CiscoConfParse print "We will use this program to parse a cisco config file" filename = raw_input("Please enter the name of the file that needs to be parsed: ") #print filename i
nput_file = CiscoConfParse(filename) crypto_find = input_file.find_objects_w_child(parentspec=r"^crypto map CRYPTO", childspec=r"pfs group2") #print crypto_find for item in crypto_find: print item.text
openstack/nomad
cyborg/common/exception.py
Python
apache-2.0
10,839
0
# Copyright 2017 Huawei Technologies Co.,LTD. # 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 # # Unl...
om oslo_log import log import six from six.moves import http_client from cyborg.common.i18n import _ from cyborg.conf import CONF LOG = log.getLogger(__name__) class CyborgException(Exception): """Base Cyborg Exception To correctly use this class, inherit from it and
define a '_msg_fmt' property. That message will get printf'd with the keyword arguments provided to the constructor. If you need to access the message from an exception you should use six.text_type(exc) """ _msg_fmt = _("An unknown exception occurred.") code = http_client.INTERNAL_SERVER_...
karllessard/tensorflow
tensorflow/python/platform/resource_loader.py
Python
apache-2.0
4,522
0.00774
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
es[-1] current_directory = _os.path.basename(candidate_dir) if '.runfiles' in current_directory: # Our file should never be directly under runfiles. # If the history has only one item, it means we are directly inside the # runfiles directory, something is wrong, fall back to the default return...
ies[-2] break else: new_candidate_dir = _os.path.dirname(candidate_dir) # If we are at the root directory these two will be the same. if new_candidate_dir == candidate_dir: break else: directories.append(new_candidate_dir) return data_files_dir or script_dir @tf_e...
ravenac95/lxc4u
tests/test_meta.py
Python
mit
2,809
0.001068
from mock import Mock, patch, MagicMock from lxc4u.meta import * def test_initialize
_lxc_meta(): meta1 = LXCMeta() meta1['hello'] = 'hello' meta2 = LXCMeta(initial=dict(hello=123)) assert meta1['hello'] == 'hello' assert meta2['hello'] == 123 @patch('__builtin__.open') @patch('json.loads') @patch('os.path.exists') def test_meta_load_from_file(mock_exists, mock_loads, mock_open)...
fake_path = 'path' # Run Test meta = LXCMeta.load_from_file(fake_path) # Assertions assert isinstance(meta, LXCMeta) == True @patch('__builtin__.open') @patch('json.loads') @patch('os.path.exists') def test_meta_load_from_file_with_no_file(mock_exists, mock_loads, mock_open): mock_exists.return_...
rlazojr/totalinstaller
plugin.program.totalinstaller/default.py
Python
gpl-2.0
104,757
0.029945
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import weblogin import zipfile import ntpath ARTPATH = 'http://totalxbmc.tv/totalrevolution/art/' + os.sep FANART = 'http://totalxbmc.tv/totalrev...
mp = xbmc.translatePath(os.path.join(userdatafolder,'guitemp','')) factory = xbmc.translatePath(os.path.join(HOME,'..','factory','_DO_NOT_DELETE.txt')) #----------------------------------------------------------------------------------------------------------------- #Simple shortcut to create a notifica...
#----------------------------------------------------------------------------------------------------------------- #Popup class - thanks to whoever codes the help popup in TVAddons Maintenance for this section. Unfortunately there doesn't appear to be any author details in that code so unable to credit by name. cl...
Worldev/Mikicat-Antivirus
antivirus.py
Python
gpl-3.0
20,145
0.0076
#!/usr/bin/python3 #################################### BY MIKICAT ############################################### ###############################A WORLDEV AFFILIATE############################################# ###IF YOU DETECT BUGS, PLEASE OPEN AN ISSUE OR REPORT THEM TO http://mikicatantivirus.weebly.com/contact.htm...
ystem32 ext7 = '.vb' # Do not scan it in system32 ext8 = '.gzquar' e
xt9 = '.vexe' ext10 = '.sys' # Important: Only detect this if found in Downloads. If it is in any other detection of any other part of the code, please delete the "or file.endswith(ext10)". If it is put in the system32, it will delete essential system files. ext11 = '.aru' ext12 = '.smtmp' ext13 = '.ctbl' ext14 = '.dxz...
nuagenetworks/nuage-openstack-neutron
nuage_neutron/db/migration/alembic_migrations/versions/liberty_release.py
Python
apache-2.0
838
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...
distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """Liberty Revision ID: liberty Revises: None Create Date: 2015-11-13 00:00:00.000000 """ # r...
e Liberty release.""" pass
sysadminmatmoz/odoo-clearcorp
purchase_prediction/__init__.py
Python
agpl-3.0
1,003
0.000997
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have r...
################################################################ from . import models
erudit/zenon
eruditorg/apps/userspace/library/authorization/apps.py
Python
gpl-3.0
196
0
# -*- coding: utf-8 -*- from dja
ngo.apps import AppConfig class AuthorizationConfig(AppConfig): label = 'userspace_library_authorizations' name = 'apps.userspace.lib
rary.authorization'
mdxs/gae-init
main/auth/twitter.py
Python
mit
1,532
0.00718
# coding: utf-8 from __future__ import absolute_import import flask import auth import config import model import util from main import app twitter_config = dict( access_token_url='https://api.twitter.com/oauth/access_token', api_base_url='https://api.twitter.com/1.1/', authorize_url='https://api.twitter.co...
ken, fetch_request_token=auth.fetch_oauth1_request_token, ) twitter = auth.create_oauth_app(twitter_config, 'twitter') @app.route('/api/auth/callback/twitter/') def twitter_authorized(): id_token = twitter.authorize_access_token() if id_token is None: flask.flash('You denied the request to sign in.') r...
account/verify_credentials.json') user_db = retrieve_user_from_twitter(response.json()) return auth.signin_user_db(user_db) @app.route('/signin/twitter/') def signin_twitter(): return auth.signin_oauth(twitter) def retrieve_user_from_twitter(response): auth_id = 'twitter_%s' % response['id_str'] user_db =...
jonathon-love/snapcraft
snapcraft/tests/test_plugin_maven.py
Python
gpl-3.0
19,419
0.000412
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
', 'package']), ]) @mock.patch.object(maven.MavenPlugin, 'run') def test_build_war(self, run_mock): env_vars = ( ('http_proxy', None), ('https_proxy', None), ) for v in env_vars: self.useFixture(fixtures.EnvironmentVariable(v[0], v[1])) ...
ions, self.project_options) def side(l): os.makedirs(os.path.join(plugin.builddir, 'target')) open(os.path.join(plugin.builddir, 'target', 'dummy.war'), 'w').close() run_mock.side_effect = side os.makedirs(plugin.sourc...
arubertoson/mayatest
mayatest/__main__.py
Python
mit
131
0
""" Used as e
ntry point for mayatest from commandline """ if __name__ == "__main__": from mayatest.cli import main mai
n()
RyanJenkins/ISS
ISS/migrations/0022_poster_posts_per_page.py
Python
gpl-3.0
420
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('ISS', '0021_poster_auto_subscribe'), ] operations = [ migrations.Ad
dField( model_name='poster', name='posts_per_page', field=models.PositiveSmallIntegerField(default=20),
), ]
nsdf/nsdf
benchmark/plot_profile_data.py
Python
gpl-3.0
6,981
0.008308
# plot_profile_data.py --- # # Filename: plot_profile_data.py # Description: # Author: Subhasis Ray # Maintainer: # Created: Sat Sep 6 11:19:21 2014 (+0530) # Version: # Last-Updated: # By: # Update #: 0 # URL: # Keywords: # Compatibility: # # # Commentary: # # # # # Change log: # # ...
sed' ax.set_title(title, fontsize=12) if ii % 2 == 0: ylabel = '{}\nTime (s)'.format('Fixed' if ii // 2 == 0 else 'Incremental') ax.set_ylabel(ylabel) else: ax.get_yaxis().set_visible(False) plt.setp(ax, frame_on=False) ...
col = 0 if key.compression == '0' else 1 row = 0 if key.increment == '0' else 1 ax = axes_list[row * 2 + col] ax.bar([pos], np.mean(data[key][field]), yerr=np.std(data[key][field]), color=color, ecolor='b', alpha=0.7, label=key.dialec...
JessicaNgo/TeleGiphy
tele_giphy/tele_giphy/wsgi.py
Python
mit
426
0
""" WSGI config for tele_giphy 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.10/howto/deployment/wsgi/ """ # Standard Library import os # Django from django.core.wsgi import get_wsgi_application os....
SETTINGS_MODULE", "tele_giphy.settings") applica
tion = get_wsgi_application()
x86Labs/wal-e
wal_e/blobstore/s3/calling_format.py
Python
bsd-3-clause
10,819
0
import boto import os import re import urlparse from boto import s3 from boto.s3 import connection from wal_e import log_help from wal_e.exception import UserException logger = log_help.WalELogger(__name__) _S3_REGIONS = { # A map like this is actually defined in boto.s3 in newer versions of boto # but we re...
# has never had its region detected in this CallingInfo # instan
ce. So, detect its region (this can happen without # knowing the right regional endpoint) and store it to speed # future calls. assert self.calling_format is connection.OrdinaryCallingFormat assert self.region is None assert self.ordinary_endpoint is None conn = _conn_h...
littlevgl/lvgl
scripts/release/main.py
Python
mit
1,494
0.005355
#!/usr/bin/env python import os.path from os import path from datetime import date import sys import com import release import dev import proj upstream_org_url = "https://github.com/lvgl/" workdir = "./release_tmp" proj_list = [ "lv_sim_eclipse_sdl", "lv_sim_emscripten"] def upstream(repo): return upstream_org_u...
jor")
exit(1) #os.chdir(workdir) clone_repos() release.make() for p in proj_list: proj.make(p, True) dev.make(dev_prepare) #cleanup()
google/fhir
py/google/fhir/utils/fhir_types_test.py
Python
apache-2.0
6,987
0.00458
# # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
fhir_types.is_type_or_profile_of_extension(datatypes_pb2.Extension())) def testIsTypeOrProfileOfExtension_withExtensionProfile_returnsTrue(self): """Tests that is_type_or_profile_of_extension returns True for profile.""" self.assertTrue( fhir_types.
is_type_or_profile_of_extension( fhirproto_extensions_pb2.Base64BinarySeparatorStride())) def testIsTypeOrProfileOfExtensions_withDateTime_returnsFalse(self): """Tests that is_type_or_profile_of_extension returns False for DateTime.""" self.assertFalse( fhir_types.is_type_or_profile_of_ex...
brainwane/zulip
zerver/management/commands/generate_multiuse_invite_link.py
Python
apache-2.0
1,624
0.001847
from argparse import ArgumentParser from typing import Any, List from zerver.lib.actions import do_create_multiuse_invite_link, ensure_stream from zerver.lib.management import ZulipBaseCommand from zerver.models import PreregistrationUser, Stream class Command(ZulipBaseCommand): help = "Generates invite link tha...
help='A comma-separated list of stream names.') parser.add_argument( '--referred-by', dest='referred_by', type=str, help='Email of referrer', required=True, ) def handle(self, *args: Any, **options: Any) -> None: realm = s...
red by parser streams: List[Stream] = [] if options["streams"]: stream_names = {stream.strip() for stream in options["streams"].split(",")} for stream_name in set(stream_names): stream = ensure_stream(realm, stream_name, acting_user=None) streams....
juanma1980/lliurex-scheduler
client-scheduler.install/usr/share/n4d/python-plugins/SchedulerClient.py
Python
gpl-3.0
4,262
0.056546
#!/usr/bin/env python ### # ### # -*- coding: utf-8 -*- import os,socket import threading import time from datetime import date import xmlrpclib as xmlrpc class SchedulerClient(): def __init__(self): self.cron_dir='/etc/cron.d' self.task_prefix='remote-' #Temp workaround->Must be declared on a n4d var self.cr...
sks[name][serial]: if (tasks[name][serial]['mon'].isdigit()): mon=int(tasks[name][serial]['mon']) if mon<today.month: sw_pass=True if sw_pass==False
: if (tasks[name][serial]['dom'].isdigit()): dom=int(tasks[name][serial]['dom']) if dom<today.day: sw_pass=True if sw_pass: continue self._debug("Scheduling %s"%name) fname=name.replace(' ','_') task_names[fname]=tasks[name][serial].copy() self._write_cront...
ricardosiri68/patchcap
cam/wsse.py
Python
gpl-2.0
2,243
0.001783
from base64 import b64encode from suds.wsse import UsernameToken, Token try: from hashlib import sha1, md5 except: from sha import new as sha1 class UsernameDigestToken(UsernameToken): """ Represents a basic I{UsernameToken} WS-Security token with password digest @ivar username: A username. ...
('Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0' '#PasswordDigest') s = sha1() s.update(self.raw_nonce) s.update(created.getText()) s.update(pas
sword.getText()) password.setText(b64encode(s.digest())) nonce.set('EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary') return usernametoken
medo/Pandas-Farm
master/server.py
Python
mit
761
0.00657
import os, logging from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler from master.serve
r_handler import ServerHandler from xmlrpc.client import Binary HOST = "0.0.0.0" PORT = int(os.getenv('PORT', 5555)) ENDPOINT = 'RPC2' logging.basicConfig(level=logging.INFO) class RequestHandler(SimpleXMLRPCRequest
Handler): # rpc_paths = ('RPC2',) def log_message(self, format, *args): logging.debug(format) def start(): server = SimpleXMLRPCServer((HOST, PORT), requestHandler=RequestHandler, allow_none=True, use_builtin_types=True) server.register_instance(ServerHandler()) logging.info("Server...
smartyrad/Python-scripts-for-web-scraping
beauty.py
Python
gpl-3.0
314
0.012739
import urllib import lxml.html connection = urllib.urlopen('http://www.amazon.in/s/ref=nb_sb_noss?url=search-
alias%3Daps&field-keywords=iphone') dom = lxml.html.fromstring(connection.read()) for link in dom.xpath('//li[@id="result_0"]/@data-asin'): # select the url in h
ref for all a tags(links) print link
tomislacker/python-iproute2
pyroute2/ipdb/common.py
Python
apache-2.0
272
0
# How long should we wait on EACH commit() checkpoint:
for ipaddr, # ports etc. Tha
t's not total commit() timeout. SYNC_TIMEOUT = 5 class DeprecationException(Exception): pass class CommitException(Exception): pass class CreateException(Exception): pass
rkunze/ft-robo-snap
ftrobopy/examples/ftDigiCam.py
Python
agpl-3.0
6,070
0.020428
###################################### # Example: ftDigiCam.py # Digital Camera with live # video stream to TXT display # and autofocus functionality # (c) 2016 by Torsten Stuehn # version 0.8 from 2016-02-12 ###################################### # Python2/3 'print' compat...
rom os import system import time txt = ftrobopy.ftrobopy(host ='
127.0.0.1', port = 65000, update_interval = 0.01, keep_connection_interval = 1.0) run_ave_contrast = 8 hist_minlength = 10 hist_maxlength = 20 fname_prefix = 'PICT' displayLiveStream = 1 # live video o...
beernarrd/gramps
gramps/plugins/export/exportvcard.py
Python
gpl-2.0
12,904
0.00279
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2004 Martin Hawlisch # Copyright (C) 2005-2008 Donald N. Allingham # Copyright (C) 2008 Brian G. Matherly # Copyright (C) 2010 Jakim Friant # Copyright (C) 2011 Michiel D. Nauta # # This program is free software; you can redistribut...
ython Modules # #------------------------------------------------------------------------- import sys from textwrap import TextWrapper #------------------------------------------------------------------------ # # Set up logging # #------------------------------------------------------------------------ import logging ...
--------------------------- # # Gramps modules # #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext from gramps.gen.const import PROGRAM_NAME from gramps.version import VERSION from gramps.gen.lib import Date, ...
priya-pp/Tacker
tacker/tests/unit/test_auth.py
Python
apache-2.0
4,418
0
# 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...
self.request.headers['X_ROLES'] = 'role1, role2 , role3,role4,role5
' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.roles, ['role1', 'role2', 'role3', 'role4', 'role5']) self.assertEqual(self.context.is_admin, False) def te...
sonofeft/DigiPlot
digiplot/sample_img.py
Python
gpl-3.0
72,038
0.000028
#!/usr/bin/env python # -*- coding: ascii -*- from __future__ import absolute_import from __future__ import print_function import sys import base64 # use a base64 image as default/test image TEST_IMAGE = """iVBORw0KGgoAAAANSUhEUgAAA8AAAALQCAYAAABfdxm0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz AAASdAAAEnQB3mYfeAAAIABJREFUeJzs3...
DBq1CgQEQ4dOlSsPguTn5+P2NhYzJ07FytWrIAQAh07 dkTLli2LbHvo0CGkpaXB3Nxc5/tKSon//e9/ICL8+uuvSExMfO54G
WOMFY0TYMYYq2To/79HtbjU C/F4eHjoXSDL398fZmZmzx3b8yAiDB8+HDdu3ICvry+2bt1a4j6EEGjbtq3ecvV9nsnJycq2mzdv Kvd8durUSWc7KysrtG7dusTxqIWEhOD27dvYsWMHJk2ahFatWsHCwgJCCNy+fRvz5s1D27Zt8eDB A53td+zYgcGDB8PLywvW1tYaiyalpKQAgM5HYwHQu7J0wfu0mzRporNOtWrVQEQa81WQmZkZOnbs qLOsXr168PT0BPD0S5iiqFQq/PHHHwCACRMmwNPTU+fPkCFDAAB3794tss9nERE2b...
enzzzy/netmiko
netmiko/cisco/cisco_wlc_ssh.py
Python
mit
3,082
0.004218
from __future__ import print_function from __future__ import unicode_literals import time from netmiko.ssh_connection import BaseSSHConnection from netmiko.netmiko_globals import MAX_BUFFER from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException import paramiko import socket class Ci...
eate instance of SSHClient object self.remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure appropriate for your environment) self.remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection if verbose: ...
_pre.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password, look_for_keys=use_keys, allow_agent=False, timeout=timeout) except socket.error as e: ...
PuZheng/lejian-backend
lejian/apis/tag.py
Python
mit
229
0
# -*- coding: UTF-8 -*- from .model_wrapper import ModelWrapper class TagWrapper(ModelWrapper)
: @property def spu(self): return self.sku.spu @property def vendor(self): return self.sp
u.vendor
donpiekarz/Stocker
stocker/SEP/processor.py
Python
gpl-3.0
3,868
0.002844
import csv import decimal import os import datetime from stocker.common.events import EventStreamNew, EventStockOpen, EventStockClose from stocker.common.orders import OrderBuy, OrderSell from stocker.common.utils import Stream class CompanyProcessor(object): def __init__(self, dirname, company_id): self....
n(dirname, company_id) self.company_id = company_id def get_dates(self): files = [os.path.splitext(fi)[0] for fi in os.walk(self.dirname).next()[2]] return files def get_row(self, date): filename = os.path.join(self.dirname, date) + ".csv" try: with open(fi...
if desc.startswith('TRANSAKCJA'): yield (row, self.company_id) except IndexError: pass except IOError as e: return class Processor(object): def build_stream(self, dirname_in, filename_out): self...
jhogsett/linkit
python/gaydar4.py
Python
mit
3,902
0.027166
#!/usr/bin/python import serial import time import random import sys s = None num_leds = 93 ticks = 96 sleep_time = 0.0 def flush_input(): s.flushInput() def wait_for_ack(): while s.inWaiting() <= 0: pass...
command(":::pau:clr:pau") command("6:zon:red:8:cpy")
command("5:zon:org:6:cpy") ...
google/grumpy
third_party/stdlib/json/encoder.py
Python
apache-2.0
16,692
0.001737
"""Implementation of JSONEncoder """ import re # try: # from _json import encode_basestring_ascii as c_encode_basestring_ascii # except ImportError: # c_encode_basestring_ascii = None c_encode_basestring_ascii = None # try: # from _json import make_encoder as c_make_encoder # except ImportError: # c_m...
except Key
Error: n = ord(s) if n < 0x10000: # return '\\u{0:04x}'.format(n) #return '\\u%04x' % (n,) return '\\u' + x4(n) else: # surrogate pair n -= 0x10000 s1 = 0xd800 | ((n >> 10) & 0x3ff) ...
fredrik-johansson/mpmath
mpmath/tests/test_quad.py
Python
bsd-3-clause
3,893
0.008477
import pytest from mpmath import * def ae(a, b): return abs(a-b) < 10**(-mp.dps+5) def test_basic_integrals(): for prec in [15, 30, 100]: mp.dps = prec assert ae(quadts(lambda x: x**3 - 3*x**2, [-2, 4]), -12) assert ae(quadgl(lambda x: x**3 - 3*x**2, [-2, 4]), -12) assert ae(qu...
(quadts(lambda x: x*exp(-x)*sqrt(1-exp(-2*x)), [0, inf]), pi*(1+2*log(2))/8) mp.dps = 15 # Do not reach full accuracy @pytest.mark.xfail def test_expmath_fail(): assert ae(quadts(lambda x: sqrt(tan(x)), [0, pi/2]),
pi*sqrt(2)/2) assert ae(quadts(lambda x: atan(x)/(x*sqrt(1-x**2)), [0, 1]), pi*log(1+sqrt(2))/2) assert ae(quadts(lambda x: log(1+x**2)/x**2, [0, 1]), pi/2-log(2)) assert ae(quadts(lambda x: x**2/((1+x**4)*sqrt(1-x**4)), [0, 1]), pi/8)
mfherbst/spack
var/spack/repos/builtin/packages/slepc/package.py
Python
lgpl-2.1
4,929
0.002435
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
.gz', sha256='0081ee4c4242e635a8113b32f655910ada057c59043f29af4b613508a762f3ac', destination=join_path('installed-arch-' + sys.platform + '-c-opt', 'e
xternalpackages'), when='+blopex') def install(self, spec, prefix): # set SLEPC_DIR for installation # Note that one should set the current (temporary) directory instead # its symlink in spack/stage/ ! os.environ['SLEPC_DIR'] = os.getcwd() options = [] ...
Eveler/libs
__Python__/edv/edv/imagescanner/backends/test/__init__.py
Python
gpl-3.0
751
0.007989
"""Test backend $Id$""" import os import Image from imagescanner.backends import base class ScannerManager(base.ScannerManager): def _refresh(self): self._devices = [] scanner = Scanner('test-0', "Pyscan", "Test Device") self._devices.append(scanner) c
lass Scanner(base.Scanner): def __init__(self, scanner_id, manufacturer, name): self.id = scanner_id self.manufacturer = manufacturer self.name = name def __repr__(self): return "<%s: %s - %s>" % (self.id, self.manufacturer, self.name) def scan(self, dpi=200): ...
iff') return Image.open(imgpath) def status(self): pass
ubik2/PEGAS-kRPC
kRPC/plane_error.py
Python
mit
987
0.00304
import numpy as np def plane_error(results, target): """ Computes angle between target orbital plane and actually achieved plane. :param results: Results struct as output by flight_manager (NOT flight_sim_3d). :param target: Target struct as output by launch_targeting. :return: Angle...
two orbital planes. """ inc = results.powered[results.n-1].orbit.inc lan = results.powered[results.n-1].orbit.lan Rx = np.array([[1, 0, 0], [0, np.cos(np.deg2rad(inc)), -np.sin(np.deg2rad(inc))], [0, np.sin(np.deg2rad(inc)), np.cos(np.deg2rad(inc))]]) ...
n)), 0], [0, 0, 1]]) reached = np.matmul(Rz, np.matmul(Rx, np.array([0, 0, -1]))) error = np.rad2deg(np.arccos(np.vdot(target.normal, reached))) return error
verma-varsha/zulip
zerver/webhooks/github_webhook/tests.py
Python
apache-2.0
22,570
0.004386
import ujson from mock import patch, MagicMock from typing import Dict, Optional, Text from zerver.models import Message from zerver.lib.webhooks.git import COMMITS_LIMIT from zerver.lib.test_classes import WebhookTestCase class GithubWebhookTest(WebhookTestCase): STREAM_NAME = 'github' URL_TEMPLATE = "/api/v...
omasz (3), Ben (2) and baxterthehacker (1).\n\n{}* Update README.md ([0d1a26e](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6
ba5c57fc3c7d91ac0fd1c))""".format(commits_info * 5) self.send_and_test_stream_message('push_multiple_committers', self.EXPECTED_SUBJECT_BRANCH_EVENTS, expected_message, HTTP_X_GITHUB_EVENT='push') def test_push_multiple_comitters_with_others_filtered_by_branches(self): # type: () -> None s...
gannicus-yu/pyutils
setup.py
Python
apache-2.0
546
0.001832
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by heyu on 17/3/1 """ try: from setuptools import setup except: from distutils.core import setup setup( name="pyutils", version="0.0.1", aut
hor="heyu", author_
email="gannicus_yu@163.com", description="easy and convenient tools written in Python", long_description=__doc__, install_requires=["MySQL-python", "docopt"], url="https://github.com/gannicus-yu/pyutils", packages=["myutils"], platforms=['all'], # test_suite="tests" )
TurkuNLP/CAFA3
sequence_features/process_NCBI_Taxonomy.py
Python
lgpl-3.0
3,092
0.005498
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from common_processing import * import tarfile import sys import glob def untar(ftp_link, out_folder): tar = tarfile.open(out_folder + ftp_link.split("/")[-1]) tar.extractall(path=out_folder) tar.close() def process_nodes_dmp(out_fo...
{}\t{}\t{}".format(tax_id, name_txt, name_class.split("|")[0].replace("\t", "\n")) with open(out_folder + "map_symbol2organism.tsv", "wb") as f: f.write(map_symbol2organism) def argument_parser(): parser = argparse.ArgumentParser(description="download the Taxonomy PubMed from ftp") parser.add_ar...
-o", "--out_folder", type=str, help="target folder of downloaded file") args = parser.parse_args() return args if __name__ == "__main__": args = argument_parser() print "processing Taxonomy data" ftp_download(args.ftp_link, args.out_folder) untar(args.ftp_link, args.out_folder) process_nod...
fergalmoran/Chrome2Kindle
server/reportlab/platypus/tableofcontents.py
Python
mit
19,645
0.006058
#Copyright ReportLab Europe Ltd. 2000-2004 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/platypus/tableofcontents.py __version__=''' $Id: tableofcontents.py 3627 2010-01-06 14:06:36Z rgbecker $ ''' __doc__="""Experimental class to generate...
text = '%s%s' % (dotsn * dot, pagestr) newx = availWidth - dotsn*dotw - pagestrw pagex = availWidth - pagestrw elif dot is None: text = ', ' + pagestr newx = x pagex = newx else: raise TypeError('Argument dot should either be None or an instance of basestring.'...
vas.drawText(tx) commaw = stringWidth(', ', style.fontName, style.fontSize) for p, key in pages: if not key: continue w = stringWidth(str(p), style.fontName, style.fontSize) canvas.linkRect('', key, (pagex, y, pagex+w, y+style.leading), relative=1) pagex += w + comma...
quchunguang/test
testpy3/pyqt5_tetris.py
Python
mit
10,805
0.000278
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import random from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal from PyQt5.QtGui import QPainter, QColor class Tetris(QMainWindow): def __init__(self): super().__init__()...
elf.msg2Statusbar.emit("paused") else: self.timer.start(Board.Speed, self) self.msg2Statusbar.emit(str(self.numLinesRemoved)) self.update() def paintEvent(self, event): painter = QPainter(self) rect = self.contentsRect() boardTop = rect.bottom() - Bo...
for j in range(Board.BoardWidth): shape = self.shapeAt(j, Board.BoardHeight - i - 1) if shape != Tetrominoe.NoShape: self.drawSquare(painter, rect.left() + j * self.squareWidth(), boardTop + i * ...
mjg/PyX
test/unit/test_data.py
Python
gpl-2.0
3,991
0.002255
import sys if sys.path[0] != "../..": sys.path.insert(0, "../..") import unittest import io from pyx.graph import data class DataTestCase(unittest.TestCase): def testPoints(self): mydata = data.points([[1, 2, 3], [4, 5, 6]], a=1, b=2) self.assertEqual(mydata.columndata[0], [1, 2]) se...
lumns["b"][1], "eins") self.assertEqual(mydata.columns["b"][2], "2") self.assertEqual(mydata.columns["b"][3], "x\"x") testfile = io.StringIO("""#a 0 1 2 3 4 5 6 7 8 9""") m
ydata = data.file(testfile, title="title", skiphead=3, skiptail=2, every=2, row=0) self.assertEqual(mydata.columns["row"], [4, 6, 8]) self.assertEqual(mydata.title, "title") def testSec(self): testfile = io.StringIO("""[sec1] opt1=a1 opt2=a2 val=1 val=2 [sec2] opt1=a4 opt2=a5 val=2 val=1 ...
magne-max/zipline-ja
zipline/examples/buy_test.py
Python
apache-2.0
888
0
from zipline.api import sid, symbol, order, record, get_datetime import logbook import pandas as pd log = logbook.Logger("ZiplineLog") def initialize(context): context.set_benchmark(symbol('TOPIX')) context.assets = [ symbol(sym_str) for sym_str in [ '2121', '4689', ...
# exchange_ts = pd.Timestamp(get_datetime()).tz_convert('Asia/Tokyo') # exchange_ts = pd.Timestamp(get_datetime()) log.info(pd.Timestamp(get_datetime()).tz_convert('Asia/Tokyo')) log.info(str(data[symbol('TOPIX')].p
rice)) order(symbol('4689'), -10) record(Yahoo=data[symbol('4689')].price) def analyze(context, perf): pass # print(perf.iloc[-1].T)
tzpBingo/github-trending
codespace/python/tencentcloud/iottid/v20190411/models.py
Python
mit
15,254
0.002742
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
elf.RequestId = None def _deserialize(self, params): self.Pass = params.get("Pass") self.RequestId = params.get("RequestId") class BurnTidNotifyRequest(AbstractModel): """BurnTidNotify请求参数结构体 """ def __init__(se
lf): r""" :param OrderId: 订单编号 :type OrderId: str :param Tid: TID编号 :type Tid: str """ self.OrderId = None self.Tid = None def _deserialize(self, params): self.OrderId = params.get("OrderId") self.Tid = params.get("Tid") memeb...
WGBH/FixIt
mla_game/apps/transcript/tests.py
Python
mit
2,490
0
from datetime import time from django.test import TestCase from django.core.files.uploadedfile import SimpleUploadedFile from .models import Transcript, TranscriptPhrase class TranscriptTestCase(TestCase): def setUp(self): fake_file = SimpleUploadedFile( 'not-really-a-file.txt', ...
self.assertEqual( fake_phrase.original_phrase, 'old and wrong' ) self.assertEqual( fake_phrase.time_begin, time(0, 1, 0)
) self.assertEqual( fake_phrase.time_end, time(0, 2, 10) ) self.assertEqual( fake_phrase.transcript, fake_transcript ) def tearDown(self): fake = Transcript.objects.get(name='test transcript') fake.original_tran...
miptliot/edx-platform
lms/djangoapps/shoppingcart/management/tests/test_retire_order.py
Python
agpl-3.0
2,853
0
"""Tests for the retire_order command""" from tempfile import NamedTemporaryFile from django.core.management import call_command from course_modes.models import CourseMode from shoppingcart.models import CertificateItem, Order from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_util...
ek(0) call_command('retire_order', temp.name) def _create_cart(self): """Creates a cart and adds a CertificateItem to it""" cart = Order.get_cart_for_user(UserFact
ory.create()) item = CertificateItem.add_to_order( cart, self.course_key, 10, 'honor', currency='usd' ) return cart, item
paltman/django-configurations
configurations/__init__.py
Python
bsd-3-clause
175
0
# flake8: noqa from .base import Settings, Configuration from .decorators
import pristinemethod __
version__ = '0.5' __all__ = ['Configuration', 'pristinemethod', 'Settings']
jalr/privacyidea
privacyidea/lib/policy.py
Python
agpl-3.0
57,193
0.000385
# -*- coding: utf-8 -*- # # 2016-05-07 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Add realm dropdown # 2016-04-06 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Add time dependency in policy # 2016-02-22 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Add RADI...
10 - 2014 LSE Leading Security Experts GmbH # License: AGPLv3 # contact: http://www.linotp.org # http://www.lsexperts.de # linotp@lsexperts.de # # This code is free software; you can redistribute it and/or # modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE # License as publis...
ersion 3 of the License, or any later version. # # This code 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 AFFERO GENERAL PUBLIC LICENSE for more details. # # You should have recei...
DisposaBoy/GoSublime-next
gosubl/nineo_builtins.py
Python
mit
3,455
0.041389
from . import about from . import gs from . import gsq from . import mg9 from . import nineo from . import vu import os import pprint import sublime def gs_init(_={}): g = globals() p = 'bi_' l = len(p) for nm in list(g.keys()): if nm.startswith(p): k = nm[l:].replace('__', '.').replace('_', '-') nineo.bui...
f(res, err): if err: c.fail(err) else: s = res.get('Url'
, '').strip() if s: sublime.set_clipboard(s) c.done(s + ' (url copied to the clipboard)') else: c.fail('no url received') mg9.share(vv.src(), f) def bi_gs__build_margo(c): def f(): out = mg9.build_mg() if out == 'ok': mg9.killSrv() c.done('ok') else: c.fail(out) gsq.do('GoSublime'...
thor/django-localflavor
localflavor/au/models.py
Python
bsd-3-clause
5,128
0.001755
from django.db.models import CharField from django.utils.translation import ugettext_lazy as _ from localflavor.deprecation import DeprecatedPhoneNumberField from . import forms from .au_states import STATE_CHOICES from .validators import AUBusinessNumberFieldValidator, AUCompanyNumberFieldValidator, AUTaxFileNumberF...
FileNumberField(CharField): """ A model field that checks that the value is a valid Tax File Number (TFN). A TFN is a number issued to a person by the Commissioner of Taxation and is used to verify client identity and establish their income level
s. It is a eight or nine digit number without any embedded meaning. .. versionadded:: 1.4 """ description = _("Australian Tax File Number") validators = [AUTaxFileNumberFieldValidator()] def __init__(self, *args, **kwargs): kwargs['max_length'] = 11 super(AUTaxFileNumberField...
Crystal-SDS/filter-middleware
crystal_filter_middleware/filters/storlet.py
Python
gpl-3.0
6,161
0.000812
''' A Mini-implementation of the Storlet middleware filter. @author: josep sampe ''' from swift.common.utils import get_logger from swift.common.utils import register_swift_info from swift.common.swob import Request from swift.common.utils import config_true_value from storlets.swift_middleware.handlers.base import Sw...
tFilter(object): def __init__(self, app, conf): self.app = app self.conf = conf self.exec_server = self.conf.get('execution_server') self.logger = get_logger(self.conf, log_route='storlet_filter') self.filter_data = self.conf['filter_data'] self.parameters = self.fil...
params'] self.gateway_class = self.conf['storlets_gateway_module'] self.sreq_class = self.gateway_class.request_class self.storlet_container = conf.get('storlet_container') self.storlet_dependency = conf.get('storlet_dependency') self.log_container = conf.get('storlet_logcontai...
a358003542/expython
expython/pattern/__init__.py
Python
mit
1,439
0.002429
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import UserList import logging logger = logging.getLogger(__name__) class CycleList(UserList): """ 一个无限循环输出元素的可迭代对象,如果是on-fly模式 (主要指for循环中的删除动作)推荐使用 `remove_item` 方法 """ def __init__(self, data): super().__init...
True: if self.index == len(self.data): self.index = 0 yield self.data[self.index] self.index += 1 def remove_item(self, item): """ 主要是用于 on-fly 模式的列表更改移除操作的修正, 不
是on-fly 动态模式,就直接用列表原来的remove方法即可 为了保持和原来的remove方法一致,并没有捕捉异常。 """ self.data.remove(item) self.index -= 1 def last_out_game(data, number): test = CycleList(data) count = 1 for i in test: logger.debug('testing', i) if len(test.data) <= 1: ...