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 |
|---|---|---|---|---|---|---|---|---|
gnrfan/django-mailgun-validation | mailgun_validation/exceptions.py | Python | bsd-3-clause | 44 | 0 | class | MailgunException(Exception):
pass
| |
quru/qis | src/imageserver/auxiliary/util.py | Python | agpl-3.0 | 3,767 | 0.002389 | #
# Quru Image Server
#
# Document: util.py
# Date started: 27 Mar 2018
# By: Matt Fozard
# Purpose: Auxiliary server utilities
# Requires:
# Copyright: Quru Ltd (www.quru.com)
# Licence:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the ... | _pid(proc_name, pid_val):
"""
Writes the current process ID to a hidden file in the image server file system.
Raises an IOError or OSError if the pid file cannot be written.
"""
pid_dir = os.path.dirname(_get_pidfile_path(proc_name))
if not os.path.exists(pid_dir):
| os.mkdir(pid_dir)
with open(_get_pidfile_path(proc_name), 'wt', encoding='utf8') as f:
f.write(pid_val)
def get_pid(proc_name):
"""
Returns the last value written by _store_pid() as a string,
or an empty string if _store_pid() has not been called before.
Raises an IOError or OSError if t... |
HeathKang/flasky | app/exceptions.py | Python | mit | 90 | 0 | # | !/usr/bin/python
# -*- coding: utf-8 -*-
class ValidationError(ValueError):
pa | ss
|
skrah/ndtypes | python/ndt_randtype.py | Python | bsd-3-clause | 16,372 | 0.006719 | #
# BSD 3-Clause License
#
# Copyright (c) 2017-2018, plures
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this... | Check fixed dimensions with arbitary strides
# ======================================================================
def verify_datasize(t):
"""Verify the datasize of fixed dimensions with arbitrary strides."""
if t.itemsize == 0:
return t.datasize == 0
if t.datasize % t.itemsize:
... | v < 0 for v in t.shape):
return False
if any(v % t.itemsize for v in t.strides):
return False
if 0 in t.shape:
return t.datasize == 0
imin = sum(t.strides[j]*(t.shape[j]-1) for j in range(t.ndim)
if t.strides[j] <= 0)
imax = sum(t.strides[j]*(t.shape[j]-1) for j ... |
zetaops/zengine | tests/views/jump_to.py | Python | gpl-3.0 | 692 | 0 | # -*- coding: utf-8 -*-
"""
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
# testing if we are preserving task_data between wf jumps
def main_wf(current):
current.task_data['from_main'] = True
current.output['... | task_data.get('from_jumped')
assert current.workflow.name == 'jump_to_wf'
def jumped_wf(current):
current.output['from_main'] = current.task_data['from_main']
current.task_data['from_jumped'] = True
assert current.workflow.name == 'jump_to_wf2'
def set_external_wf(current):
curr | ent.task_data['external_wf'] = 'jump_to_wf2'
|
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/pandas/tseries/tests/test_resample.py | Python | artistic-2.0 | 65,806 | 0.0031 | # pylint: disable=E1101
from datetime import datetime, timedelta
from functools import partial
from pandas.compat import range, lrange, zip, product
import numpy as np
from pandas import (Series, TimeSeries, DataFrame, Panel, Index,
isnull, notnull, Timestamp)
from pandas.core.groupby import Dat... | r(Minute(5), closed='left', label='left')
expect = s.groupby(grouper).agg(lambda x: x[-1])
assert_series_equal(result, expect)
def test_resample_how(self):
rng = date_range('1/1/2000 00:00:00', '1/1/2000 00:13:00',
freq='min', name='index')
s = Series(np.... | args = ['sum', 'mean', 'std', 'sem', 'max', 'min',
'median', 'first', 'last', 'ohlc']
def _ohlc(group):
if isnull(group).all():
return np.repeat(np.nan, 4)
return [group[0], group.max(), group.min(), group[-1]]
inds = date_range('1/1/2000',... |
9seconds/concierge | tests/test_endpoints_daemon.py | Python | mit | 3,504 | 0 | # -*- coding: utf-8 -*-
import errno
import itertools
import os
import os.path
import inotify_simple
import pytest
import concierge
import concierge.endpoints.cli as cli
import concierge.endpoints.daemon as daemon
import concierge.utils
def get_app(*params):
pars | er = cli.create_parser()
parser = | daemon.Daemon.specify_parser(parser)
parsed = parser.parse_args()
for param in params:
if param:
setattr(parsed, param.strip("-"), True)
app = daemon.Daemon(parsed)
return app
def test_create_app(cliargs_default, cliparam_systemd, cliparam_curlsh):
app = get_app(cliparam_sys... |
viggates/nova | nova/tests/api/openstack/compute/contrib/test_agents.py | Python | apache-2.0 | 10,887 | 0.003215 | # Copyright 2012 IBM Corp.
#
# 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 t... | e139be103324d04d82d8f547',
'agent_id': 3},
{'hypervisor': 'xen', 'os': 'win',
| 'architecture': 'power',
'version': '7.0',
'url': 'xxx://xxxx/xxx/xxx3',
'md5hash': 'add6bb58e139be103324d04d82d8f548',
'agent_id': 4},
]
self.assertEqual(res_dict, {'agents': agents_list})
... |
obsrvbl/kinesis-logs-reader | kinesis_logs_reader/kinesis_logs_reader.py | Python | apache-2.0 | 3,798 | 0 | # Copyright 2016 Observable Networks
#
# 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 ... | e):
stream_description = page.get('StreamDescription', {})
for shard in stream_description.get('Shards', []):
yield shard['ShardId']
def _get_shard_iterator(self, shard_id, start_time=None):
kwargs = {'StreamName': self.stream_name, 'ShardId': shard_id}
if st... | art_time
response = self.kinesis_client.get_shard_iterator(**kwargs)
return response['ShardIterator']
def _read_shard(self, shard_id):
iterator = self.shard_iterators[shard_id]
response = self.kinesis_client.get_records(ShardIterator=iterator)
self.shard_iterators[shard_id... |
xifle/home-assistant | homeassistant/components/cover/demo.py | Python | mit | 5,129 | 0 | """
Demo platform for the cover component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
from homeassistant.components.cover import CoverDevice
from homeassistant.helpers.event import track_utc_time_change
def setup_platform(hass, config, add_d... | ):
"""Track time | changes."""
if self._closing:
self._position -= 10
else:
self._position += 10
if self._position in (100, 0, self._set_position):
self.stop_cover()
self.update_ha_state()
def _listen_cover_tilt(self):
"""Listen for changes in cover tilt."... |
opennode/nodeconductor-openstack | src/waldur_openstack/openstack/tests/test_service_project_link.py | Python | mit | 3,839 | 0.003126 | from rest_framework import test, status
from waldur_core.structure.models import CustomerRole, ProjectRole
from waldur_core.structure.tests import factories as structure_factories
from . import factories
class ServiceProjectLinkPermissionTest(test.APITransactionTestCase):
def setUp(self):
self.users = {... | e': ['Invalid hyperlink - Object does not exist.']}, response.data)
def tes | t_user_cannot_revoke_service_and_project_permission_if_he_is_project_manager(self):
user = self.users['manager']
self.client.force_authenticate(user=user)
url = factories.OpenStackServiceProjectLinkFactory.get_url(self.service_project_link)
response = self.client.delete(url)
sel... |
jdmcbr/Shapely | docs/code/buffer.py | Python | bsd-3-clause | 1,095 | 0.00274 | from matplotlib import pyplot
from shapely.geometry import LineString
from descartes import PolygonPatch
from figures import SIZE, BLUE, GRAY, set_limits, plot_line
line = LineString([(0, 0), (1, 1), (0, 2), (2, 2), (3, 1), (1, 0)])
fig = pyplot.figure(1, figsize=SIZE, dpi=90)
# 1
ax = fig.add_subplot(121)
plot_li... | ch2a = PolygonPatch(dilated, fc=GRAY, ec=GRAY, alpha=0.5, zorder=1)
ax.add_patch(patch2a)
eroded = dilated.buffer(-0.3)
# GeoJSON-like data works as well
polygon = eroded.__geo_interface__
# >>> geo['type']
# 'Polygo | n'
# >>> geo['coordinates'][0][:2]
# ((0.50502525316941682, 0.78786796564403572), (0.5247963548222736, 0.8096820147509064))
patch2b = PolygonPatch(polygon, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2)
ax.add_patch(patch2b)
ax.set_title('b) erosion, join_style=1')
set_limits(ax, -1, 4, -1, 3)
pyplot.show()
|
divio/askbot-devel | askbot/tests/__init__.py | Python | gpl-3.0 | 1,266 | 0 | from askbot.tests.cache_tests import *
from askbot.tests.email_alert_tests import *
from askbot.tests.on_screen_notification_tests import *
from askbot.tests.page_load_tests import *
from askbot.tests.permission_assertion_tests import *
from askbot.tests.db_api_tests import *
from askbot.tests.skin_tests import *
from ... | sts import *
from askbot.tests.thread_model_tests import *
from askbot.tests.reply_by_email_tests import *
from askbot.tests.haystack_search_tests import *
from askbot.tests.email_parsing_tests import *
from askbot.tests.widget_tests import *
from askbot.tests.category_tree_tests import CategoryTreeTests
from askbot.te... | m askbot.tests.user_views_tests import *
from askbot.tests.utils_tests import *
from askbot.tests.view_context_tests import *
from askbot.tests.api_v1_tests import *
from askbot.tests.jive_tests import *
from askbot.tests.signal_handler_tests import *
|
linsalrob/EdwardsLab | Flinders/plot_scores_3d.py | Python | mit | 1,397 | 0.002863 | """
Plot a 3D scatter plot of the alignment scores from alignment_score.py
"""
import os
import random
import sys
import matplotlib.lines
import argparse
import matplotlib.colors
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pickle
import tkinter as tk
from tkinter import filedialog
... | ain__':
"""
parser = argparse.ArgumentParser(description="Plot a 3D scatter plot of the alignment scores from alignment_score.py")
parser.add_argument('-f', help='text separated data file output f | rom alignment_score.py', required=True)
args = parser.parse_args()
filename = args.f
"""
root = tk.Tk()
root.withdraw()
filename = filedialog.askopenfilename()
x = []
y = []
z = []
legends = ['seq1', 'seq2', '1-mer', '2-mer', '3-mer']
with open(filename, 'r') as fin:
... |
ykaneko/quantum | quantum/api/v2/base.py | Python | apache-2.0 | 29,494 | 0.000102 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 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.... | "pagination requires native sorting"))
self._allow_sorting = True
if parent:
self._parent_id_name = '%s_id' % parent['member_name']
parent_part = '_%s' % parent['member_name']
else:
self._parent_id_name = None
parent_part = ''
... | : 'get%s_%s' % (parent_part, self._collection),
self.SHOW: 'get%s_%s' % (parent_part, self._resource)
}
for action in [self.CREATE, self.UPDATE, self.DELETE]:
self._plugin_handlers[action] = '%s%s_%s' % (action, parent_part,
... |
JoseALermaIII/python-tutorials | docs/source/conf.py | Python | mit | 6,850 | 0.001898 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | The full version, including alpha/beta/rc tags
release = __version__
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# ... | ions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinxcontrib.napoleon',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify mul... |
pbugnion/bibscrape | handle_jcp.py | Python | lgpl-3.0 | 844 | 0.007109 |
"""
Hack to extract links from JCP search r | esults.
$ handle.py <file_name>
will return a link to the first result of a JCP search.
If there are no search results, gives a return code of 4. |
If there is at least one search result, prints the href in
the "<a title="Link to Article" href="..."> tag.
"""
import sys
from HTMLParser import HTMLParser
found = False
class Parser(HTMLParser):
def handle_starttag(self,tag,attrs):
global found
if tag == "a":
if ("title","Link to ... |
dnarvaez/osbuild | osbuild/utils.py | Python | apache-2.0 | 983 | 0 | # Copyright 2013 Daniel Narvaez
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | os.makedirs(path | )
except OSError:
pass
def getch():
fd = sys.stdin.fileno()
tty_attributes = termios.tcgetattr(fd)
try:
tty.setraw(fd)
return sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, tty_attributes)
|
wrobstory/sticky | sticky/core.py | Python | mit | 2,171 | 0 | # -*- coding: utf-8 -*-
"""
Sticky
-------
Python + IPython + D3
"""
from __future__ import print_function
from __future__ import division
import json
from uuid import uuid4
from IPython.core.display import display, Javascript
from IPython.html import widgets
from IPython.utils.traitlets import Unicode
from jinja2 ... | )
dom_widget.chart_id = self.chart_id
return dom_widget
def init_widget_js(self):
"""Init Widget JS"""
dom_template = ENV.get_template('sticky_dom_widget.js')
display(Javascript(dom_template.render()))
display(Javascript(self.render_template.render()))
def _set_... | s(v)
model_name = '_'.join(['model', k])
setattr(self, model_name, v)
def update(self, **kwargs):
"""Update View Model with given keywords"""
self._set_chart_attrs(**kwargs)
self.send_state()
def plot(self):
"""Plot Sticky chart"""
def render_cha... |
cocosli/antlr4 | runtime/Python2/src/antlr4/BufferedTokenStream.py | Python | bsd-3-clause | 11,959 | 0.005101 | #
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... | return EOF token
# EOF must be last token
return self.tokens[len(self.tokens)-1]
return self.tokens[i]
# Allowed derived classes to modify the behavior of operations which change
# the current stream position by adjusting the target toke | n index of a seek
# operation. The default implementation simply returns {@code i}. If an
# exception is thrown in this method, the current stream index should not be
# changed.
#
# <p>For example, {@link CommonTokenStream} overrides this method to ensure that
# the seek target is always an on-c... |
stefwalter/cockpituous | tests/doc/inkscape-export.py | Python | lgpl-2.1 | 1,516 | 0.005277 | #!/usr/bin/env python
import os
import codecs
from xml.dom import minidom
import subprocess
import sys
INKSCAPE = '/usr/bin/inkscape'
def list_layers(svg):
layers = [ ]
for g in svg.getElementsByTagName("g"):
if g.attributes.has_key("inkscape:label"):
layers.append(g.attributes["inkscape:... | --stay', action='append', default=[], help='layer to always have visible')
parser.add_argument('src', help='source SVG file.')
args = parser.parse_args()
svg = minidom.parse(open(args.src))
for layer in list_layers(svg):
export_layer(svg, os.path.dirname(args.src), layer, args.stay)
if _ | _name__ == '__main__':
main()
|
iamyangchen/xbmc-addons-chinese | plugin.video.pptv/default.py | Python | gpl-2.0 | 30,009 | 0.039897 | # -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcplugin, xbmcaddon, urllib2, urllib, re, gzip, datetime, StringIO, urlparse
try:
import json
except:
import simplejson as json
import ChineseKeyboard
# Plugin constants
__addonname__ = "PPTV视频"
__addonid__ = "plugin.video.pptv"
__addon__ = xbmcaddon.Addon(id=__addonid... | h: " + match, 3)
endstr = u"</" + name # + ">"
start = html.find(match)
end = html.find(endstr, start)
pos = html.find("<" + name, start + 1 )
log(str(start) + " | < " + str(end) + ", pos = " + str(pos) + ", endpos: " + str(end), 8)
while pos < end and pos != -1: # Ignore too early </endstr> return
tend = html.find(endstr, end + len(endstr))
if tend != -1:
end = tend
pos = html.find("<" + name, pos + 1)
log("loop: " + str(start) + " < " + str(end) + " pos = " + str... |
xuwei0455/hedge | bin/ctaBackTesting.py | Python | mit | 32,917 | 0.000522 | # -*- coding: utf-8 -*-
"""
本文件中包含的是CTA模块的回测引擎,回测引擎的API和CTA引擎一致,
可以使用和实盘相同的代码进行回测。
"""
from __future__ import division
from collections import OrderedDict
from datetime import datetime, timedelta
from itertools import product
import pymongo
from vnpy.engine.cta.ctaBase import CtaTickData, StopOrder
fro | m vnpy.engine.cta.ctaConstant import *
from vnpy.utils.vtConstant import *
from vnpy.utils.vtFunction import loadMongoSetting
from vnpy.utils.vtGateway import VtOrderData, VtTradeData
########################################################################
class BackTestingEngine(object):
| """
CTA回测引擎
函数接口和策略引擎保持一样,
从而实现同一套代码从回测到实盘。
"""
TICK_MODE = 'tick'
BAR_MODE = 'bar'
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
# 本地停止单编号计数
self.stopOrderCount = 0
# stopOrderID = STOPOR... |
armagetronad-xtw/0.4-armagetronad-xtw | batch/make/sortresources.py | Python | gpl-2.0 | 618 | 0.006472 | #!/usr/bin/python
import sys, os
foundModule = False
newPathSearch = os.path.dirname(os.path.abspath(sys.argv[0]) )
sys.path.insert(0, newPathSearch)
maxnumAttemp | ts = 10
numAttempts = 0
while not foundModule:
try:
import armabuild
import armabuild.resource
foundModule = True
print("Found armabuild!")
except:
sys.path[0] = os.path.dirname(newPathSearch)
numAttempts += 1
if numAttempts > 9:
print("Unable to find ar... | ys.exit(1)
if __name__ == "__main__":
armabuild.resource.main(sys.argv[1:])
|
CooperLuan/devops.notes | taobao/top/api/rest/WlbItemBatchQueryRequest.py | Python | mit | 390 | 0.030769 | '''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class WlbItemBatchQu | eryRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.item_ids = None
self.page_no = None
self.page_ | size = None
self.store_code = None
def getapiname(self):
return 'taobao.wlb.item.batch.query'
|
HiSPARC/station-software | user/python/Lib/test/test_codecs.py | Python | gpl-3.0 | 81,185 | 0.001552 | from test import test_support
import unittest
import codecs
import locale
import sys, StringIO
def coding_checker(self, coder):
def check(input, expect):
self.assertEqual(coder(input), (expect, len(input)))
return check
class Queue(object):
"""
queue: write bytes at one end, read bytes from th... | Humpty Dumpty had a great fall.\r\n",
"All the king's horses and all the | king's men\r",
"Couldn't put Humpty together again."]
data = ''.join(lines)
def getreader():
stream = StringIO.StringIO(data.encode(self.encoding))
return codecs.getreader(self.encoding)(stream)
# Issue #8260: Test readline() followed by read()
f... |
bitonic/troppotardi | troppotardi/lib/thumbnailer.py | Python | gpl-2.0 | 2,794 | 0.003937 | from PIL import Image
import os
from pylons import config
def resize_image(filename, max_width=None, max_height=None, crop=False):
"""Given the filename of an image in the image dir,
it resizes it"""
im = Image.open(os.path.join(config['images_dir'], filename))
(width, height) = im.size
# If ... | name = name + '_' + str(max_width) + 'x' + str(max_height)
if crop:
name += '_crop_'
name += ext
# If the thumbnail already exists, don' | t create it.
# This could be dangerous if the image could be changed, but
# the image cannot be changed right now, so it should be safe.
if not os.path.isfile(os.path.join(config['thumbs_dir'], name)):
im = resize_image(filename, max_width, max_height, crop)
im.save(os.path.join(config['thu... |
dNG-git/pas_media | src/dNG/data/media/abstract_audio.py | Python | gpl-2.0 | 1,708 | 0.000585 | # -*- coding: | utf-8 -*-
"""
direct PAS
Pyt | hon Application Services
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?pas;media
The following license agreement remains valid unless any additions or
changes are being made by direct Netware Group in a... |
cwells/franz | lib/pygments.py | Python | mit | 1,729 | 0.002895 | import importlib
from pygments.lexer import RegexLexer, bygroups
from pygments.styles import STYLE_MAP
from pygments.token import *
def load_style(full_class_string):
modulename, styleclass = full_class_string.split('::')
module = importlib.import_module("pygments.styles." + modulename)
return getattr(mo... | )(\s*)(fn)',
bygroups(Name.Function.Definition, Whitespace, Operator, Whitespace, Keyword.Reserved)),
(r'\b([a-zA-Z][a-zA-Z0-9_!?\-%$]*)(\s*)([(])', bygroups(Name.Function, Whitespace, Punctuation)),
(r'\b[a-zA-Z][a-zA-Z0-9_!?\-%$]*\b', Name),
(r'\s+([*+\-^=<>%/?]+)\s... | perator),
(r'[@().,:;\[\]]', Punctuation),
(r'[{}]', Punctuation.Braces),
(r'\s+', Whitespace)
],
'double-quote': [
(r'\{.*?\}', String.Interpol),
(r'\\.', Literal.String.Escape),
(r'[^"{}\\]+', String.Double),
(r'"', S... |
beekpr/wsgiservice | wsgiservice/resource.py | Python | bsd-2-clause | 58,294 | 0.001269 | import hashlib
import inspect
import json
import logging
import re
from xml.sax.saxutils import escape as xml_escape
import webob
from wsgiservice import xmlserializer
from wsgiservice.decorators import mount
from wsgiservice.exceptions import (MultiValidationException, ResponseException,
... | utput in the Content-Type headers. Set to None to avoid
#: sending this.
charset = 'UTF-8'
# Cache for the `data` property
_data = None
def __init__(self, request, response, path_params, application=None):
"""Constructor. Order of the parameters is not guaranteed, always
used named... | t`
:param response: Object representing the response to be sent.
:type response: :class:`webob.Response`
:param path_params: Dictionary of all parameters passed in via the
path. This is the return value of
:func:`Router.__call__`.
:... |
phaethon/scapy | kamene/layers/rtp.py | Python | gpl-2.0 | 1,435 | 0.008362 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
RTP (Real-time Transport Protocol).
"""
from kamene.packet import *
from kamene.fields import *
_rtp_payload_types ... | c', None | , 4, count_of='sync'),
BitField('marker', 0, 1),
BitEnumField('payloadtype', 0, 7, _rtp_payload_types),
ShortField('sequence', 0),
IntField('timestamp', 0),
IntField('sourcesync', 0),
FieldListField('... |
Dangetsu/vnr | Frameworks/Sakura/py/apps/reader/views/topicview.py | Python | gpl-3.0 | 12,896 | 0.01768 | # coding: utf8
# topicview.py
# 1/2/2015 jichi
if __name__ == '__main__':
import sys
sys.path.append('..')
import debug
debug.initenv()
import json
from functools import partial
from PySide.QtCore import Qt, QObject
from Qt5 import QtWidgets
from sakurakit import skevents, skqss
from sakurakit.skclass import ... | dated.connect(self._onTopicUpdated)
qml.postDataUpdated.connect(self._onPostUpdated)
qml.postDataReceived.connect(self._onPostReceived)
path = 'topic/%s' % topicId
self.topicComet.setPath(path)
if netman.manager().isOnline():
self.topicComet.setActive(True)
def | _injectBeans(self):
h = self.webView.page().mainFrame()
#h.addToJavaScriptWindowObject('bean', self._webBean)
for name,obj in self._beans:
h.addToJavaScriptWindowObject(name, obj)
@memoizedproperty
def _beans(self):
"""
return [(unicode name, QObject bean)]
"""
import coffeebean
... |
repology/repology | repology/fetchers/fetchers/rsync.py | Python | gpl-3.0 | 2,001 | 0.001 | # Copyright (C) 2017-2020 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology 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 optio... | xclude: str | None = None) -> None:
self.url = url
self.fetch_timeout = fetch_timeout
self.rsync_include = rsync_in | clude
self.rsync_exclude = rsync_exclude
def fetch(self, statepath: str, update: bool = True, logger: Logger = NoopLogger()) -> bool:
if os.path.exists(statepath) and not update:
logger.log('no update requested, skipping')
return False
args = [
'--info=s... |
xjw1001001/IGCexpansion | setup.py | Python | gpl-3.0 | 347 | 0.040346 | fr | om distutils.core import setup
setup(name = 'IGCexpansion',
version = '0.2-dev',
author = 'Xiang Ji',
url = 'https://github.com/xji3/IGCexpansion',
#download_url = 'https://github.com/xji3/Genconv/tree/master/IGCexpansion/',
packages = ['IGCexpansion',],
#long_description = open('RE... | )
|
hlt-mt/tensorflow | tensorflow/models/rnn/fbk_nmt/seq2seq_model.py | Python | apache-2.0 | 13,619 | 0.004038 | # Copyright 2015 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 a... | nd padded accordingly.
We assume that the list is sorted, e.g., [(2, 4), (8, 16)].
size: number of units in each layer of the model.
num_layers: number of layers in the model.
max_gradient_norm: gradients will be clipped to maximally this norm.
batch_size: the size of the batches used du... | the model construction is independent of batch_size, so it can be
changed after initialization if this is convenient, e.g., for decoding.
learning_rate: learning rate to start with.
learning_rate_decay_factor: decay learning rate by this much when needed.
use_lstm: if true, we use LSTM ce... |
tuna/gdanmaku | gdanmaku/danmaku.py | Python | gpl-3.0 | 3,347 | 0.000598 | #!/usr/bin/env python2
# -*- coding:utf-8 -*-
import signal
import json
import argparse
import threading
import requests
from settings import load_config
from app import GDanmakuApp
from server_selection import ServerSelectionWindow
from danmaku_ui import Danmaku
from gi.repository import Gtk, GLib, GObject
class Ma... | cept Exception as e:
print(e)
continue
self.live_danmakus[id(dm)] = dm
def on_danmaku_delete(self, dm, event):
self.live_danmakus.pop(id(dm))
def toggle_danmaku(self):
self.enabled = not self.enabled
if not self.enabled:
for _, d... | )
def on_server_selected(self, widget, server, channel, password):
thread_sub = threading.Thread(
target=self._subscribe_danmaku, args=(server, channel, password))
thread_sub.daemon = True
thread_sub.start()
self.thread_sub = thread_sub
def run(self):
GObjec... |
bgris/ODL_bgris | lib/python3.5/_pyio.py | Python | gpl-3.0 | 87,968 | 0.000739 | """
Python implementation of the io module.
"""
import os
import abc
import codecs
import errno
import array
import stat
import sys
# Import _thread instead of threading to reduce startup cost
try:
from _thread import allocate_lock as Lock
except ImportError:
from _dummy_thread import allocate_lock as Lock
if ... | a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a Buffered | Random.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
if not isinstance(file, (str, bytes, int)):
r... |
joopert/home-assistant | homeassistant/components/mobile_app/helpers.py | Python | apache-2.0 | 5,246 | 0.000762 | """Helpers for mobile_app."""
import json
import logging
from typing import Callable, Dict, Tuple
from aiohttp.web import Response, json_response
from nacl.encoding import Base64Encoder
from nacl.secret import SecretBox
from homeassistant.core import Context
from homeassistant.helpers.json import JSONEncoder
from hom... | ox.KEY_SIZE, encrypt)
def _decrypt_payload(key: str, ciphertext: str) -> Dict[str, str]:
"""Decrypt encrypted payload."""
try:
keylen, decrypt = setup_decrypt()
except OSError:
_LOGGER.warning("Ignoring encrypted payload because libsodium not installed")
return None
if key is ... | n key known")
return None
key = key.encode("utf-8")
key = key[:keylen]
key = key.ljust(keylen, b"\0")
try:
message = decrypt(ciphertext, key)
message = json.loads(message.decode("utf-8"))
_LOGGER.debug("Successfully decrypted mobile_app payload")
return message
... |
syscoin/syscoin2 | test/util/syscoin-util-test.py | Python | mit | 6,594 | 0.003185 | #!/usr/bin/env python3
# Copyright 2014 BitPay Inc.
# Copyright 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test framework for syscoin utils.
Runs automatically during `make check`.
Ca... | iff(outputData.splitlines(True),
| outs[0].splitlines(True),
fromfile=outputFn,
tofile="returned"))
logging.error(error_message)
formatting_mismatch = True
assert not... |
alexras/pylsdj | pylsdj/test_instrument.py | Python | mit | 1,954 | 0.002559 | import os
import json
from nose.tools import assert_equal
from .project import load_lsdsng
from .utils | import temporary_file
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
def _test_load_store_instrument(source_lsdsng, lsdinst_path, original_index):
proj = load_lsdsng(source_lsdsng)
proj.song.instruments.import_from_file(0x2a, lsdinst_path)
target_instr = proj.song.instruments[0x2a]
original_... | original_instr.export_to_file(tmpfile)
with open(tmpfile, 'r') as fp:
saved_inst = json.load(fp)
with open(lsdinst_path, 'r') as fp:
original_inst = json.load(fp)
assert_equal(original_inst, saved_inst)
def test_load_store_wave_instrument():
_test_load_stor... |
abn/python-bugzilla | bugzilla/rhbugzilla.py | Python | gpl-2.0 | 14,369 | 0.000974 | # rhbugzilla.py - a Python interface to Red Hat Bugzilla using xmlrpclib.
#
# Copyright (C) 2008-2012 Red Hat Inc.
# Author: Will Woods <wwoods@redhat.com>
#
# 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 ... | ch just overwrites the existing alias, we need to read
# the bug's state first to know what string to remove. Which
# we can't do, since we don't know the bug numbers at this point.
# So fail for now.
#
# The API should provide {"s | et": [...]}
# https://bugzilla.redhat.com/show_bug.cgi?id=1173114
#
# Implementation will go here when it's available
pass
pop("fixed_in", "cf_fixed_in")
pop("qa_whiteboard", "cf_qa_whiteboard")
pop("devel_whiteboard", "cf_devel_whiteboard")
... |
xifle/greensc | tools/scons/scons-local-2.0.1/SCons/Variables/PackageVariable.py | Python | gpl-3.0 | 3,612 | 0.003599 | """engine.SCons.Variables.PackageVariable
This file defines the option type for SCons implementing 'package
activation'.
To be used whenever a 'package' may be enabled/disabled and the
package path may be specified.
Usage example:
Examples:
x11=no (disables X11 support)
x11=yes (will search for the... | this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVE... | YRIGHT HOLDERS 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 OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Variables/PackageVariable.py 5134 2010/08/16 23:02:40 b... |
dstruthers/blog.darrenstruthers.net | urls.py | Python | mit | 544 | 0.012868 | from djan | go.conf.url | s import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.foo.urls')),
# Uncomment the admin/doc line bel... |
joealcorn/berth.cc | berth/wsgi.py | Python | mit | 385 | 0.002597 | """
WSGI config for berth project.
It exposes the WSGI callable as a module-level variable na | med ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTING | S_MODULE", "berth.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
w495/python-video-shot-detector | shot_detector/charts/event/base/base_event_chart.py | Python | bsd-3-clause | 6,299 | 0.005717 | # -*- coding: utf8 -*-
"""
...
"""
from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
import itertools
import logging
# PY2 & PY3 — compatibility
from builtins import map, zip
from shot_detector.handlers imp... | def processed_seq_future(self, src_event_seq, filter_seq):
"""
:param src_event_seq:
:param f | ilter_seq:
:return:
"""
func_seq = list(
filter_desc.formula.filter_objects_as_list
for filter_desc in filter_seq
)
func_seq_mapper = FuncSeqMapper(
caller=self
)
processed_seq = func_seq_mapper.map(
func_seq,
... |
palmtree5/Red-DiscordBot | redbot/cogs/audio/core/cog_utils.py | Python | gpl-3.0 | 4,323 | 0.000925 | from abc import ABC
from typing import Final
from base64 import b64decode
from io import BytesIO
import struct
from redbot import VersionInfo
from redbot.core import commands
from ..converters import get_lazy_converter, get_playlist_converter
__version__ = VersionInfo.from_json({"major": 2, "minor": 4, "micro": 0, "... | g these together!
# The license can be found in https://github.com/Devoxin/Lavalink.py/blob/master/LICENSE
class DataReader:
def __init__(self, ts):
| self._buf = BytesIO(b64decode(ts))
def _read(self, n):
return self._buf.read(n)
def read_byte(self):
return self._read(1)
def read_boolean(self):
(result,) = struct.unpack("B", self.read_byte())
return result != 0
def read_unsigned_short(self):
(result,) =... |
EnEff-BIM/EnEffBIM-Framework | SimModel_Python_API/simmodel_swig/Release/SimAppObjNameDefault_DistributionSystem_HvacSteamLoop.py | Python | mit | 9,034 | 0.00642 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... | lambda self, name: _swig_getattr(self, SimAppObjNameDefault_DistributionSystem_HvacSteamLoop_sequence, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _SimAppObjNameDefault_DistributionSystem_HvacSteamLoop.new_SimAppObjNameDefault_DistributionSystem_HvacSteamLoop_sequence(*args)
... | _SimAppObjNameDefault_DistributionSystem_HvacSteamLoop.SimAppObjNameDefault_DistributionSystem_HvacSteamLoop_sequence_assign(self, n, x)
def begin(self, *args):
return _SimAppObjNameDefault_DistributionSystem_HvacSteamLoop.SimAppObjNameDefault_DistributionSystem_HvacSteamLoop_sequence_begin(self, *args)
... |
nathanhi/deepserve | deepserve/urls.py | Python | mit | 328 | 0 | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from deepserve.blag.views import index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^markdown/', include('django_markdown.urls')),
url(r'^$', index),
url( | r'^blag/', inc | lude('deepserve.blag.urls')),
]
|
andreiavram/organizer | organizer/urls.py | Python | mit | 637 | 0.00157 | f | rom django.urls import path, include
from django.contrib import admin
from rest_framework.routers import DefaultRouter
from tasks.views import TaskItemViewSet, MainAppView, TagViewSet, ProjectViewSet, TaskCommentViewSet
admin.autodiscover()
router = DefaultRouter()
router.register(r'task', TaskItemViewSet)
router.re... | ag', TagViewSet)
router.register(r'project', ProjectViewSet)
router.register(r'comments', TaskCommentViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', MainAppView.as_view(), {}, "index"),
path('api/', include(router.urls)),
path('rest-auth/', include('rest_auth.urls'))
]
|
akrherz/iem | htdocs/plotting/auto/scripts100/p182.py | Python | mit | 6,994 | 0 | """Precip estimates"""
import datetime
import os
import numpy as np
import geopandas as gpd
from pyiem import iemre, util
from pyiem.plot import figure_axes
from pyiem.reference import state_names
from pyiem.grid.zs import CachingZonalStats
from pyiem.exceptions import NoDataFound
def get_description():
"""Retur... | )
hasdata = np.flipud | (hasdata)
today = util.mm2inch(nc.variables[ncvar][idx1, jslice, islice])
if (idx1 - idx0) < 32:
p01d = util.mm2inch(
np.sum(nc.variables[ncvar][idx0:idx1, jslice, islice], 0)
)
else:
# Too much data can overwhelm this app, need to chunk it
... |
rohitranjan1991/home-assistant | homeassistant/components/zerproc/__init__.py | Python | mit | 1,353 | 0.001478 | """Zerproc lights integration."""
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from .const import DATA_ADDRESSES, DATA_DISCOVERY_SUBSCRIPTION, DOMAIN
PLATFOR... | ntry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
# Stop discovery
unregister_discovery = hass.data[DOMAIN].pop(DATA_DISCOVERY_SUBSCRIPTION, None)
if unregister_discover | y:
unregister_discovery()
hass.data.pop(DOMAIN, None)
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
iot-salzburg/self-driving-slotcar | gym-slotcar/setup.py | Python | apache-2.0 | 185 | 0.010811 | from setuptools import setup
setup(name='gym_slotcar',
version='0.0.1',
install | _requires=['gym'] # And any other dependencies foo needs [ | add stuff like numpy etc.]
) |
aurelieladier/openturns | python/test/t_ExponentialFactory_std.py | Python | lgpl-3.0 | 1,511 | 0.000662 | #! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
distribution = Exponential(2.5, -1.3)
size = 10000
sample = distribution.getSample(size)
factory = ExponentialFactory()
estimatedDistribution = factory.build(sample)... | timatedDistribution))
sample = [[1.0]] * size
estimatedDistribution = factory.build(sample)
print("Estimated distribution=", repr(estimatedDistribution))
except:
import sys
print("t_ExponentialFactory_std.py", sys.exc_info()[0], sys.exc_info()[1] | )
|
KnightOS/packages.knightos.org | packages/config.py | Python | mit | 619 | 0.004847 | import logging
try:
from configparser import ConfigParser
except Im | portError:
# Python 2 support
from ConfigParser import ConfigParser
logger = logging.getLogger("packges.knightos.org")
logger.setLevel(logging.DEBUG)
sh = logging.StreamHand | ler()
sh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
sh.setFormatter(formatter)
logger.addHandler(sh)
# scss logger
logging.getLogger("scss").addHandler(sh)
config = ConfigParser()
config.readfp(open('config.ini'))
env = 'dev'
_cfg = lambda k: config... |
h2oai/sparkling-water | py/src/ai/h2o/sparkling/ml/algos/H2OAutoMLExtras.py | Python | apache-2.0 | 1,464 | 0.001366 | #
# 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 A | SF licenses this file to You 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
# di... | fic language governing permissions and
# limitations under the License.
#
from pyspark.sql import SparkSession
from pyspark.sql.dataframe import DataFrame
from ai.h2o.sparkling.ml.models.H2OMOJOModel import H2OMOJOModelFactory
class H2OAutoMLExtras:
def getLeaderboard(self, *extraColumns):
if len(extraC... |
valerymelou/cookiecutter-django-gulp | setup.py | Python | bsd-3-clause | 1,852 | 0.00108 | #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Our version ALWAYS matches the version of Django we support
# If Django has a new release, we branch, tag, then update this setting after the tag.
version = '1.10.1'
if sys.arg... | ges=[],
license='BSD',
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Framework :: Django :: 1.10',
'Intended Audience :: Developers',
'Natural Language :: English',
'Lic | ense :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',... |
arubertoson/piemenu | piemenu/aforms/core/main.py | Python | gpl-2.0 | 1,524 | 0.001312 |
""" Module main
Contains the main frame and implements the main window.
"""
import os
import platform
from PySide import QtCore, QtGui
import aforms
from aforms.codeeditor import CodeEditor
from aforms.codeeditor import python_highlighting
# from app import style_rc
class MainWindow(QtGui.QMainW... | f.setCentralWidget(widget)
# self._shellDock = dock = QtGui.QDockWidget(self)
# dock.setObjectName('shells')
|
# dock.setWindowTitle('Shells')
# self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock)
def setMainTitle(self):
title = 'Command System'
self.setWindowTitle(title)
def closeEvent(self, event):
# implement save config
QtGui.QMainWindow.closeEvent(self, ... |
germn/python-for-android | setup.py | Python | mit | 4,634 | 0.001079 |
import glob
from io import open # for open(..,encoding=...) parameter in python 2
from os import walk
from os.path import join, dirname, sep
import re
from setuptools import setup, find_packages
# NOTE: All package data should also be set in MANIFEST.in
packages = find_packages()
package_data = {'': ['*.tmpl',
... | Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming L | anguage :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Software Development',
'Topic :: Utilities',
],
packages=packages,
package_data=package_data,
)
|
allenai/allennlp | allennlp/modules/stacked_bidirectional_lstm.py | Python | apache-2.0 | 6,459 | 0.002632 | from typing import Optional, Tuple, List
import torch
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
from allennlp.modules.augmented_lstm import AugmentedLstm
from allennlp.modules.input_variational_dropout import InputVariationalDropout
from allennlp.common.checks import Confi... | ut probability to be used in a dropout scheme as
stated in [A Theoretically Grounded Application of Dropout in Recurrent
Neural Networks][0].
layer_dropout_probab | ility : `float`, optional (default = `0.0`)
The layer wise dropout probability to be used in a dropout scheme as
stated in [A Theoretically Grounded Application of Dropout in Recurrent
Neural Networks][0].
use_highway : `bool`, optional (default = `True`)
Whether or not to use highwa... |
jcornford/pyecog | pyecog/ndf/__init__.py | Python | mit | 880 | 0.009091 | from .ndfconverter import NdfFile
from .h5loader import H5File
from .datahandler import DataHandler
from .classifier import FeaturePreProcesser
from .classifier import Classifier
from .classifier import load_classifier
#from .bokeh_visualisation import plot
#from .bokeh_visualisation import basic_plot
from .feature_ex... | gger.addHandler(fhandler)
logger | .setLevel(logging.DEBUG) |
mikekap/batchy | tests/runloop_tests.py | Python | apache-2.0 | 9,494 | 0.002001 | import sys
from unittest.case import SkipTest
from batchy.compat import PY3
from batchy.local import RunLoopLocal
from batchy.runloop import coro_return, runloop_coroutine, deferred, future, current_run_loop, wait
from . import BaseTestCase
@runloop_coroutine()
def increment(arg):
coro_return(arg + 1)
yield
... | ependencies(self):
@run | loop_coroutine()
def coro():
yield
self.assert_equals(None, coro())
def test_local(self):
local = RunLoopLocal()
@runloop_coroutine()
def test():
local.hi = getattr(local, 'hi', 0) + 1
local.hello = 'boo'
del local.hello
... |
Aurorastation/BOREALISbot2 | core/subsystems/__init__.py | Python | agpl-3.0 | 102 | 0.009804 | from .api import API, ApiMethods
from .config import Config
__all__ | = ["API", "ApiMethods", "C | onfig"] |
theju/django-comments-apps | recaptcha_comments/fields.py | Python | mit | 3,024 | 0.010913 | from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
from d | jango.utils.translation import ugettext as _
import urllib2, urllib
VERIFY_SERVER="http://api-verify.recaptcha.net/verify"
class RecaptchaWidget(forms.Widget):
def render(self, name, value, attrs=None):
return mark_safe("""<script type="text/javascript"
src="http://api.recaptcha... | script?k=%(public_key)s"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challe... |
roy-boy/python_scripts | th_logger.py | Python | gpl-3.0 | 447 | 0.002237 | #!C:\Python27 | \
"" | "th_logger.py holds logging handler and config for the Regression test"""
import logging
from testProperty import TEST_OUTPUT_PATH
test_logger = logging.getLogger('TEST_HARNESS')
handler = logging.FileHandler(TEST_OUTPUT_PATH + 'runTest.log')
formatter = logging.Formatter('%(asctime)s %(name)-10s %(levelname)-6s %(me... |
quantopian/PenguinDome | client/submit.py | Python | apache-2.0 | 1,850 | 0 | #!/usr/bin/env python3
# Quantopian, Inc. licenses this file to you 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 ... | ta_path=collected,
exit_on_connection_error=True, logger=log)
except HTTPError as e:
if e.response.status_code == 400:
log.error('Server returned status code 400. '
'Renaming {} to {}.bad.', collected, collected)
os... |
except (HTTPError, ReadTimeout) as e:
log.error('Submit failed: {}', str(e))
log.debug('Traceback of failed submission', exc_info=sys.exc_info())
sys.exit(1)
os.unlink(collected)
log.debug('Successful submission of {}', collected)
|
MartinPaulEve/CaSSius | src/interactive.py | Python | agpl-3.0 | 15,319 | 0.000979 | #!/usr/bin/env python
from __future__ import print_function
__author__ = "Martin Paul Eve"
__email__ = "martin@martineve.com"
"""
A class to handle an interactive prompt.
Portions of this file are Copyright 2014, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of thi... | fflib import SequenceMatcher
import locale
class Interactive(Debuggable):
def __init__(self, debug):
self.debug = debug
Debuggable.__init__(self, 'Interactive Prompt Handler')
# ANSI terminal colorization code heavily inspired by pygments:
# http://dev.pocoo.org/hg/pygments-main/f... | (pygments is by Tim Hatch, Armin Ronacher, et al.)
self.COLOR_ESCAPE = "\x1b["
self.DARK_COLORS = ["black", "darkred", "darkgreen", "brown", "darkblue",
"purple", "teal", "lightgray"]
self.LIGHT_COLORS = ["darkgray", "red", "green", "yellow", "blue",
... |
wagtail/wagtail | wagtail/users/views/bulk_actions/__init__.py | Python | bsd-3-clause | 222 | 0.004505 | from .assign_role import AssignRoleBulkAction
from .delete import DeleteBulkAction
from .set_active_state import SetActiveStateBul | kAction
__all__ = ["AssignRoleBulkAction", " | DeleteBulkAction", "SetActiveStateBulkAction"]
|
SaintAttila/attila | attila/db/adodb.py | Python | mit | 18,695 | 0.002461 | """
ADODB database interface for Python
"""
# TODO: Map database to the file system interface. The FS interface already supports row-based
# reading and writing via the read_rows(), load_rows(), and save_rows() methods. However,
# those methods expect quotes and delimiters, which aren't required for row-b... | trusted=trusted,
dialect=dialect,
**kwargs
)
@classmethod
def load_config_section(cls, manager, section, *args, **kwargs):
"""
Load a class instance from a config section.
:param manager: A ConfigManager instance.
:param section: The name o... | ger, ConfigManager)
assert isinstance(manager, ConfigManager)
verify_type(section, str, non_empty=True)
server = manager.load_option(section, 'server', str)
database = manager.load_option(section, 'database', str)
driver = manager.load_option(section, 'driver', str, default=Non... |
PKU-Cloud-Lab/xLearn | python-package/xlearn/base.py | Python | apache-2.0 | 2,861 | 0.002097 | # Copyright (c) 2018 by contributors. 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... | (msg)
# type definitions
XLearnHandle = ctypes.c_void_p
if sys.version_info[0] < 3:
def c_str(string):
"""Create ctypes char * from a Python string.
Parameters
----------
string : string type
Pyrhon string.
Returns
-------
str : c_char_p
... | >>> print x.value
Hello, world!
"""
return ctypes.c_char_p(string)
else:
def c_str(string):
"""Create ctypes char * from a Python string.
Parameters
----------
string : string type
Pyrhon string.
Returns
-------
str : ... |
mljar/mljar-api-python | mljar/model/result.py | Python | apache-2.0 | 2,694 | 0.003712 | from marshmallow import Schema, fields, post_load
from .base import BaseModel
class ResultSchema(Schema):
hid = fields.Str()
experiment = fields.Str()
dataset = fields.Str()
validation_scheme = fields.Str()
model_type = fields.Str()
metric_type = fields.Str()
metric_value = fields.Number(a... | ams, status, status_detail=None, status_modify_at=None, metric_value=None,
importance=None, train_prediction_path=None, run_time=None, iters=None, train_details=None,
metric_additional=None, models_saved=None):
self.hid = hid
self.experiment = experiment
s... |
self.model_type = model_type
self.metric_type = metric_type
self.metric_value = metric_value
self.run_time = run_time
self.iters = iters
self.status = status
self.status_detail = status_detail
self.status_modify_at = status_modify_at
self.importan... |
xrootd/xrootd-test-framework | src/XrdTest/EmailNotifier.py | Python | gpl-3.0 | 7,244 | 0.007454 | #!/usr/bin/env python
#-------------------------------------------------------------------------------
#
# Copyright (c) 2011-2012 by European Organization for Nuclear Research (CERN)
# Author: Justin Salmon <jsalmon@cern.ch>
#
# This file is part of XrdTest.
#
# XrdTest is free software: you can redistribute it and/or... | re'] = 'Success'
if args['testcase']:
| args['testcase'] = 'Test case: <strong>' + \
args['testcase'] + '</strong><br />'
if args['slave']:
args['slave'] = 'Slave: <strong>' + \
args['slave'] + '</strong><br />'
if args['result'... |
morelab/labman_ud | labman_ud/extractors/zotero/admin.py | Python | gpl-3.0 | 970 | 0.008247 | # -*- encoding: utf-8 -*-
from django.contrib import admin
from .models import ZoteroExtractorLog
### ZoteroExtractorLogAdmin
####################################################################################################
class ZoteroExtractorLogAdmin(admin.ModelAdmin):
model = ZoteroExtractorLog
... | ################################################################
admin.site.register(ZoteroExtractorLog, Zote | roExtractorLogAdmin)
|
yfpeng/pengyifan-pybioc | tests/bioc/test_json_encoder.py | Python | bsd-3-clause | 1,888 | 0.00053 | import io
import tempfile
from pathlib import Path
import pytest
from bioc import BioCFileType
from bioc.biocjson.encoder import toJSON
import bioc
from bioc.biocjson import BioCJsonIterWriter
from tests.utils import assert_everything
file = Path(__file__).parent / 'everything.json'
def test_dump():
with open... | tion.documents[0])
with pytest.raises(ValueError):
writer = BioCJsonIterWriter(io. | StringIO(), level=bioc.PASSAGE)
writer.write(collection.documents[0])
with pytest.raises(ValueError):
writer = BioCJsonIterWriter(io.StringIO(), level=bioc.DOCUMENT)
writer.write(collection.documents[0].passages[0])
def test_toJSON():
with open(file, encoding='utf8') as fp:
co... |
lucemia/gcloud-python | gcloud/datastore/batch.py | Python | apache-2.0 | 10,313 | 0 | # 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 a... | `dataset_id`` does not match ours.
"""
if entity.key is None:
raise ValueError("Entity mus | t have a key")
if not _dataset_ids_equal(self._dataset_id, entity.key.dataset_id):
raise ValueError("Key must be from same dataset as batch")
_assign_entity_to_mutation(
self.mutation, entity, self._auto_id_entities)
def delete(self, key):
"""Remember a key to be d... |
vrsys/avangong | examples/avango-utils/load_pcd.py | Python | lgpl-3.0 | 3,367 | 0.005346 | # -*- Mode:Python -*-
##########################################################################
# #
# This file is part of AVANGO. #
# ... | te it and/or modify #
# it under the terms of the GNU Lesser General Public License as #
# published by the Free Software Foundation, version 3. #
# #
# AVANGO is distributed in the hope that it will be useful, ... | License for more details. #
# #
# You should have received a copy of the GNU Lesser General Public #
# License along with AVANGO. If not, see <http://www.gnu.org/licenses/>. #
# ... |
Rahul91/CommunityNewsPortal | manage.py | Python | mit | 253 | 0 | #!/usr/bin/env p | ython
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "NewsPortal.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys | .argv)
|
MingfeiPan/leetcode | dp/72.py | Python | apache-2.0 | 859 | 0.003492 | class Solution:
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
l1 = len(word1)
l2 = len(word2)
if l1 == 0 and | l2 != 0:
return l2
if l1 != 0 and l2 == 0:
return l1
matrix = [[0]*(l2+1) for i in range(0, l1+1)]
for i in range(0, l1+1):
for j in range(0, l2+1):
if i == 0:
matrix[i][j] = j
elif j == 0:
... | matrix[i][j] = matrix[i-1][j-1]
else:
matrix[i][j] = min(matrix[i][j-1], matrix[i-1][j], matrix[i-1][j-1]) + 1
return matrix[l1][l2]
|
anhstudios/swganh | data/scripts/templates/object/ship/shared_blacksun_medium_s03_tier2.py | Python | mit | 422 | 0.049763 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### M | ODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Ship()
result.template = "object/ship/shared_blacksun_medium_s03_tier2.iff"
result.attribute_template_id = -1
result.stfName("","")
#### BEGIN MODIFICATI... | ATIONS ####
return result |
junghans/espressopp | src/analysis/AnalysisBase.py | Python | gpl-3.0 | 3,450 | 0.015362 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of t... | ment()
Computes the observable and updates average and standard deviation
:rtype:
.. function:: espressopp.analysis.AnalysisBase.reset()
Resets average and standard deviation
:rtype:
"""
from espressopp import pmi
from espressopp.ParticleAccess import *
from _espressopp import analysis_Analysis... | mm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.performMeasurement(self)
def reset(self):
if not pmi._PMIComm or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup():
self.cxxclass.reset(self)
def compute(self):
if not pmi._PMIComm or pmi._MPIcomm.rank in pmi._PMI... |
dnjohnstone/hyperspy | hyperspy/drawing/_widgets/vertical_line.py | Python | gpl-3.0 | 1,544 | 0 | # -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... | ou should | have received a copy of the GNU General Public License
# along with HyperSpy. If not, see <http://www.gnu.org/licenses/>.
from hyperspy.drawing.widgets import Widget1DBase
from hyperspy.drawing.utils import picker_kwargs
class VerticalLineWidget(Widget1DBase):
"""A draggable, vertical line widget.
"""
... |
chirilo/mozillians | vendor-local/lib/python/celery/task/__init__.py | Python | bsd-3-clause | 2,664 | 0 | # -*- coding: utf-8 -*-
"""
celery.task
~~~~~~~~~~~
Creating tasks, subtasks, sets and chords.
:copyright: (c) 2009 - 2012 by Ask Solem.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from ..app import app_or_default, current_task as _current_task
from ..... | # noqa
from .control import discard_all # noqa
current = Proxy(_current_task)
def task(*args, **kwargs):
"""Decorator to create a task class out of any callable.
**Examples**
.. code-block:: python
@task
def refresh_feed(url):
return Feed.objects.get(url... | try:
return Feed.objects.get(url=url).refresh()
except socket.error, exc:
refresh_feed.retry(exc=exc)
Calling the resulting task:
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed... |
stgraber/snapcraft | snapcraft/internal/states/__init__.py | Python | gpl-3.0 | 947 | 0 | # -*- 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 hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. S... |
gwsu2008/automation | python/awscreds-custom.py | Python | gpl-2.0 | 2,552 | 0.002351 | #!/usr/local/bin/python3
import sys
import boto3
import os
from botocore.exceptions import ClientError
import json
import argparse
from botocore.utils import InstanceMetadataFetcher
from botocore.credentials import InstanceMetadataProvider
import platform
region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1')
duration... | )
params = {"RoleArn": role_arn, "RoleSessionName": session_name, "DurationSeconds": duration,}
response = sts_client.assume_role(**params).get("Credentials")
cred = | {
"Version": 1,
"AccessKeyId": response.get("AccessKeyId"),
"SecretAccessKey": response.get("SecretAccessKey"),
"SessionToken": response.get("SessionToken"),
"Expiration": response.get("Expiration").isoformat(),
}
except ClientError as ex:
... |
GeoCSBI/UTH_DB | mysite/uth_db/migrations/0012_auto_20170104_0938.py | Python | gpl-3.0 | 547 | 0.001828 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-04 09 | :38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('uth_db', '0011_auto_20170102_1649'),
]
operations = [
migrations.AlterField(
model_name='ta | ble',
name='booking',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='uth_db.Booking'),
),
]
|
gongminmin/KlayGE | glloader/autogen.py | Python | gpl-2.0 | 18,019 | 0.027249 | #!/usr/bin/env python
#-*- coding: ascii -*-
from __future__ import print_function
try:
from StringIO import StringIO
except:
from io import StringIO
GPLNotice = """// glloader
// Copyright (C) 2004-2009 Minmin Gong
//
// This program is free software; you can redistribute it and/or modify
// it under ... | in additionalsTag[0].getElementsByTagName("ext"):
if ext_tag.parentNode == additionalsTag[0]:
self.additionals.append([ext_tag.getAttribute("name")])
for one_of_tag in additionalsTag[0].getElementsByTagName("one_of"):
one_of = []
for ext in one_of_tag.getElementsByTagName("ext"):
one_of.... | te("/*\n%s*/\n\n" % GPLNotice);
header_str.write("#ifndef _GLLOADER_%s_H\n" % prefix.upper())
header_str.write("#define _GLLOADER_%s_H\n\n" % prefix.upper())
header_str.write("#ifdef __cplusplus\n")
header_str.write("extern \"C\"\n")
header_str.write("{\n")
header_str.write("#endif\n\n")
typedef_set... |
Akka47/ymcmb | ymc/urls.py | Python | gpl-2.0 | 591 | 0.001692 | from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, name='logout'),
url(r'^a... | /', include('avatar.urls')),
url(r'^$', views.video_list, name='video_list'),
url(r'^list/$', views.list, name='list'),
| url(r'^categoria/(?P<cat>[0-9]+)/$', views.categoria_list, name="ymc.views.video_categoria"),
]
|
dennisobrien/bokeh | bokeh/sampledata/commits.py | Python | bsd-3-clause | 2,129 | 0.009864 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | ---------------------------------------------------------------------------
#---------------------------------- | -------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
def _read_dat... |
weolar/miniblink49 | third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/browser_test_driver.py | Python | apache-2.0 | 4,526 | 0.001105 | # Copyright (C) 2014 Google Inc. 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 conditions and the ... | AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, O | R CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT O... |
alex/changes | changes/jobs/import_repo.py | Python | apache-2.0 | 1,505 | 0 | from __future__ import absolute_import, print_function
import logging
from datetime import datetime
from changes.config import db
from changes.models import Repository, RepositoryStatus
from changes.queue.task import tracked_task
logger = logging.getLogger('repo.sync')
@tracked_task(max_retries=None)
def import_r... | not repo:
logger.error('Repository %s not found', repo_id)
return
vcs = repo.get_vcs()
if vcs is None:
logger.warning('R | epository %s has no VCS backend set', repo.id)
return
if repo.status == RepositoryStatus.inactive:
logger.info('Repository %s is inactive', repo.id)
return
Repository.query.filter(
Repository.id == repo.id,
).update({
'last_update_attempt': datetime.utcnow(),
},... |
Sunsoo/ecogwiki | lib/bzrlib/patiencediff.py | Python | gpl-3.0 | 5,971 | 0.001507 | #!/usr/bin/env python
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#... | (None,a,b).get_grouped_opcodes(n):
if not started:
yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm)
yield '+++ %s %s%s' % (tofile, tofiledate, lineterm)
started = True
i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4 | ]
yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
for line in a[i1:i2]:
yield ' ' + line
continue
if tag == 'replace' or tag == 'delete':
... |
alexurquhart/webgis | app/pubsub.py | Python | mit | 882 | 0.006803 | from redis_conn import Redis as R
from sys import stdout
import json, time
class PubSub:
def __init__(self, channel="tweets"):
self.__P = R.pubsub(ignore_subscribe_messages=True)
self.__channel = channel
# Publish tweet to subscribers
def publish(self, tweet):
ser = tweet.seria... | elf.__channel)
data = json.dumps(ser, ensure_ascii=False)
R.publish(self.__channel, data) |
# Listen for incoming data and print to stdout
# Pause is the time between attempts to retreive messages
def listen(self, pause=0.1):
self.__P.subscribe(self.__channel)
while True:
message = self.__P.get_message()
if message:
print message["data"... |
rchakra3/x9115rc3 | hw/code/6/model/osyczka2.py | Python | gpl-2.0 | 2,597 | 0 | from model import Model
from helpers.candidate import Candidate
from helpers.decision import Decision
class Osyczka2(Model):
def __init__(self):
Model.__init__(self)
self.initialize_decs()
def initialize_decs(self):
dec = Decision('x1', 0, 10)
self.decs.append(dec)
de... | debug:
print "Failed 1"
return False
if not ((x1 + x2) <= 6):
if debug:
print "Failed 2"
return False
if not ((x2 - x1) <= 2):
if debug:
print "Failed 3"
return False
if not ((x1 - (3 ... | print "Failed 5"
return False
if not ((((x5 - 3) ** 3) + x6) >= 4):
if debug:
print "Failed 6"
return False
return True
|
scikit-nano/scikit-nano | sknano/core/crystallography/_xtal_lattices.py | Python | bsd-2-clause | 41,085 | 0.000097 | # -*- coding: utf-8 -*-
"""
=============================================================================
Crystal lattice classes (:mod:`sknano.core.crystallography._xtal_lattices`)
=============================================================================
.. currentmodule:: sknano.core.crystallography._xtal_lattic... | (self, direct_lattice, nd, offset=None):
self._direct_lattice = direct_lattice
super().__init__(
| nd=nd, cell_matrix=self._direct_lattice.cell_matrix,
orientation_matrix=self._direct_lattice.orientation_matrix,
offset=offset)
def __getattr__ |
myint/vulture | tests/test_scavenging.py | Python | gpl-3.0 | 6,238 | 0 | from wake import Vulture
def test_function_object1():
v = Vulture()
v.scan("""\
def func():
pass
a = func
""")
assert v.defined_funcs == ['func']
assert v.unused_funcs == []
def test_function_object2():
v = Vulture()
v.scan("""\
def func():
pass
func
""")
assert v.defined_funcs... | = 1
""")
assert v.defined_funcs == ['Bar']
assert v.defined_props == ['prop']
assert v.unused_props == ['prop']
assert v.defined_vars == ['prop']
def test_object_attribute():
v = Vulture(verb | ose=True)
v.scan("""\
class Bar(object):
def __init__(self):
self.a = []
""")
assert v.defined_funcs == ['Bar']
assert v.defined_vars == []
assert v.defined_attrs == ['a']
assert v.used_attrs == []
assert v.unused_attrs == ['a']
|
arvenil/resume | node_modules/node-gyp/gyp/pylib/gyp/generator/compile_commands_json.py | Python | mit | 4,591 | 0.000871 | # Copyright (c) 201 | 6 Ben Noordhuis <info@bnoordhuis.nl>. All rights reserved.
# Use of this source code is governed b | y a BSD-style license that can be
# found in the LICENSE file.
import gyp.common
import gyp.xcode_emulation
import json
import os
generator_additional_non_configuration_keys = []
generator_additional_path_sections = []
generator_extra_sources_for_rules = []
generator_filelist_paths = None
generator_supports_multiple_... |
gprMax/gprMax | gprMax/pml_updates/pml_updates_electric_HORIPML_gpu.py | Python | gpl-3.0 | 47,831 | 0.003596 | # Copyright (C) 2015-2022: The University of Edinburgh
# Authors: Craig Warren and Antonis Giannopoulos
#
# This file is part of gprMax.
#
# gprMax is free software: you can redistribute it and/or modify
# it under the terms of the GNU GenRAl Public License as published by
# the Free Software Foundation... | index to subscripts for PML PHI1 (4D) arrays
int p1 = idx / (NX_PHI1 * NY_PHI1 * NZ_PHI1);
int i1 = (idx % (NX_PHI1 * NY_PHI1 * NZ_PHI1)) / (NY_PHI1 * NZ_PHI1);
int j1 = ((idx % (NX_PHI1 * NY_PHI1 * NZ_PHI1)) % (NY_PHI1 * NZ_PHI1)) / NZ_ | PHI1;
int k1 = ((idx % (NX_PHI1 * NY_PHI1 * NZ_PHI1)) % (NY_PHI1 * NZ_PHI1)) % NZ_PHI1;
// Convert the linear index to subscripts for PML PHI2 (4D) arrays
int p2 = idx / (NX_PHI2 * NY_PHI2 * NZ_PHI2);
int i2 = (idx % (NX_PHI2 * NY_PHI2 * NZ_PHI2)) / (NY_PHI2 * NZ_PHI2);
int j2 = ((idx % (NX_PHI2 * ... |
Eric89GXL/scipy | scipy/sparse/linalg/isolve/lsmr.py | Python | bsd-3-clause | 15,128 | 0.000463 | """
Copyright (C) 2010 David Fong and Michael Saunders
LSMR uses an iterative method.
07 Jun 2010: Documentation updated
03 Jun 2010: First release version in Python
David Chin-lung Fong clfong@stanford.edu
Institute for Computational and Mathematical Engineering
Stanford University
Michael Saunders ... | norm r norm A''r'
| hdg2 = ' compatible LS norm A cond A'
pfreq = 20 # print frequency (for repeating the heading)
pcount = 0 # print counter
m, n = A.shape
# stores the num of singular values
minDim = min([m, n])
if maxiter is None:
maxiter = minDim
if show:
print(' ')
... |
nathanbjenx/cairis | cairis/test/test_RiskLevelAPI.py | Python | apache-2.0 | 5,044 | 0.007534 | # 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... | a.decode('utf-8')
else:
| responseData = rv.data
level = jsonpickle.decode(responseData)
self.assertIsNotNone(level, 'No results after deserialization')
self.assertIsInstance(level, int, 'The result is not an integer as expected')
self.assertEqual(level, 9)
url = '/api/risk_level/asset/ICT%20Application/environment/Ni... |
tuistudio/tuistudio.com | tuistudio/utils/filters.py | Python | apache-2.0 | 530 | 0.002 | # coding: utf-8
import datetime
def timesince(value):
"""Friendly time gap"""
now = datetime.datetime.now()
delta = now - value
if delta.days > 365:
return '%d年前' % | (delta.days / 365)
if delta.days > 30:
return '%d个月前' % (delta.days / 30)
if delta.days > 0:
return '%d天前' % delta.days
if delta.seconds > 3600:
return '%d小时前' % (del | ta.seconds / 3600)
if delta.seconds > 60:
return '%d分钟前' % (delta.seconds / 60)
return '刚刚' |
codefisher/codefisher_apps | online_status/templatetags/online_status_tags.py | Python | mit | 2,065 | 0.009201 | import datetime
from django.conf import settings
from django import template
from django.core.cache import cache
from online_status.status import CACHE_USERS, CACHE_PREFIX_ANONYM_USER, TIME_OFFLINE, ONLY_LOGGED_USERS, status_for_user
from django.contrib.sessions.models import Session
register = template.Library(... | ders a list of OnlineStatus instances"""
onlineusers = cache.get(CACHE_USERS, [])
onlineanonymusers = []
if not ONLY_LOGGED_USERS and not logged_only:
now = datetime.datetime.now()
sessions = Session.objects.filter(expire_date__gte = now + datetime.time | delta(0, settings.SESSION_COOKIE_AGE - TIME_OFFLINE)).values_list('session_key', flat = True)
onlineanonymusers = [x for x in [cache.get(CACHE_PREFIX_ANONYM_USER % session_key, None) for session_key in sessions] if x is not None]
onlineusers = [item for item in cache.get(CACHE_USERS, []) if item.status ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.