commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
|---|---|---|---|---|---|---|---|
111eb59d2390a008cad5edc8e18456d42b7f7117
|
Add hearthPwnCrawler.py, for crawling deck strings from hearthPwn websize.
|
hearthPwnCrawler.py
|
hearthPwnCrawler.py
|
Python
| 0
|
@@ -0,0 +1,1549 @@
+#!/usr/bin/env python%0A# -*- encoding: utf-8 -*-%0A# Created on 2017-07-17 08:52:38 by lanhin%0A# Project: Deckstring Crawler%0A#%0A# Use this file as a pyspider script%0A# To crawl deck from http://www.hearthpwn.com/decks%0A# Refer to http://docs.pyspider.org/en/latest/Quickstart/ for more details%0A%0Afrom pyspider.libs.base_handler import *%0Aimport re%0A%0Aclass Handler(BaseHandler):%0A crawl_config = %7B%0A %7D%0A%0A @every(minutes=24 * 60)%0A def on_start(self):%0A self.crawl('http://www.hearthpwn.com/decks', callback=self.index_page)%0A%0A @config(age=10 * 24 * 60 * 60)%0A def index_page(self, response):%0A for each in response.doc('a%5Bhref%5E=%22http%22%5D').items():%0A if re.match(%22http://www.hearthpwn.com/decks/%22, each.attr.href):%0A self.crawl(each.attr.href, callback=self.detail_page)%0A if re.match(%22http://www.hearthpwn.com/decks%5C?page=%22, each.attr.href):%0A self.crawl(each.attr.href, callback=self.index_page)%0A%0A @config(priority=2)%0A def detail_page(self, response):%0A new_dict = %7B%22url%22: response.url,%0A %22title%22: response.doc('title').text(),%0A %22deckstring%22: %5Beach.attr(%22data-clipboard-text%22) for each in response.doc('%5Bdata-ga-click-event-tracking-label=%22Top%22%5D').items()%5D%5B0%5D,%0A %22date%22: %5Beach for each in response.doc('%5Bclass=%22deck-details%22%5D')('li').items()%5D%5B-1%5D.text()%0A %7D%0A if response.doc('%5Bclass=%22is-std%22%5D').text():%0A new_dict%5B'type'%5D = 'Standard'%0A else:%0A new_dict%5B'type'%5D = 'Wild'%0A return new_dict%0A
|
|
4cfc07a275a473ed14f7c99150b2f233c680d7c0
|
Add db dumping utility
|
dbcat.py
|
dbcat.py
|
Python
| 0
|
@@ -0,0 +1,219 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Aimport anydbm as dbm%0A%0Adef main():%0A for k,v in dbm.open(sys.argv%5B1%5D).iteritems():%0A print %22key: %7B0:s%7D value: %7B1:s%7D%22.format(k, v)%0A%0Aif __name__ == '__main__':%0A sys.exit(main())
|
|
1631731657af28c275b35f9b084807e4f244c334
|
debug module. initial code
|
debug.py
|
debug.py
|
Python
| 0.999675
|
@@ -0,0 +1,1253 @@
+# -*- coding: utf-8 -*-%0A# MusicPlayer, https://github.com/albertz/music-player%0A# Copyright (c) 2013, Albert Zeyer, www.az2000.de%0A# All rights reserved.%0A# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.%0A%0A# This is the debug module: tools to debug MusicPlayer.%0A# This is mostly for debugging at runtime.%0A# - memory profiling. searching for mem-leaks%0A# - runtime profiling. searching slow code paths%0A# - other bugs%0A%0A# Use socketcontrol-interactiveclient.py for interactively control.%0A# After being connected, just run %60import debug%60 and use the functions from here.%0A%0Aimport sys, os%0A%0Adef getDevelPath():%0A%09def check(path):%0A%09%09path = os.path.expanduser(path)%0A%09%09if not os.path.isdir(path): return None%0A%09%09if not os.path.isdir(path + %22/.git%22): return None%0A%09%09return path%0A%09for path in %5B%0A%09%09# send me a request to include your custom dir.%0A%09%09# if it isn't too unusual, i might add it here.%0A%09%09%22~/Programmierung/music-player%22,%0A%09%09%22~/Projects/music-player%22,%0A%09%09%22~/Coding/music-player%22,%0A%09%5D:%0A%09%09path = check(path)%0A%09%09if path: return path%0A%09return None%0A%0Adef addDevelSysPath():%0A%09%22adds your MusicPlayer development directory to sys.path%22%0A%09path = getDevelPath()%0A%09assert path, %22devel path not found%22%0A%09sys.path = %5Bpath%5D + sys.path%0A%0A
|
|
ed43384ece07bf1a02529d2f79423e96c8283443
|
Add mangling experimental sample
|
src_clang/experimental/show-mangle.py
|
src_clang/experimental/show-mangle.py
|
Python
| 0
|
@@ -0,0 +1,939 @@
+import pprint%0Aimport sys%0Aimport clang.cindex%0A%0Adef get_cursor(source, spelling):%0A %22%22%22Obtain a cursor from a source object.%0A%0A This provides a convenient search mechanism to find a cursor with specific%0A spelling within a source. The first argument can be either a%0A TranslationUnit or Cursor instance.%0A%0A If the cursor is not found, None is returned.%0A %22%22%22%0A # Convenience for calling on a TU.%0A%0A root_cursor = (source if isinstance(source, clang.cindex.Cursor)%0A else source.cursor)%0A%0A for cursor in root_cursor.walk_preorder():%0A if cursor.spelling == spelling:%0A return cursor%0A%0A return None%0A%0Asrc = '''%5C%0Aint foo(int, int);%0A'''%0A%0Atu = clang.cindex.TranslationUnit.from_source('t.cpp',%0A %5B'-x', 'c++'%5D,%0A unsaved_files=%5B('t.cpp', src)%5D)%0A%0Afoo = get_cursor(tu, 'foo')%0A%0Aprint(foo.mangled_name)%0A
|
|
0caaf977096d5936747ad4931d14041675a9864a
|
create a paths utility to better work with ceph paths
|
ceph_deploy/util/paths.py
|
ceph_deploy/util/paths.py
|
Python
| 0
|
@@ -0,0 +1,598 @@
+from os.path import join%0A%0Afrom ceph_deploy.util import constants%0A%0A%0Aclass mon(object):%0A%0A _base = join(constants.mon_path, 'ceph-')%0A%0A @classmethod%0A def path(cls, hostname):%0A return %22%25s%25s%22 %25 (cls._base, hostname)%0A%0A @classmethod%0A def done(cls, hostname):%0A return join(cls.path(hostname), 'done')%0A%0A @classmethod%0A def init(cls, hostname, init):%0A return join(cls.path(hostname), init)%0A%0A @classmethod%0A def keyring(cls, cluster, hostname):%0A keyring_file = '%25s-%25s.mon.keyring' %25 (cluster, hostname)%0A return join(constants.tmp_path, keyring_file)%0A
|
|
1aeb34f003e5d437ac55c560ef062b22e9f02c0a
|
Define health blueprint.
|
rio/blueprints/health.py
|
rio/blueprints/health.py
|
Python
| 0.000002
|
@@ -0,0 +1,134 @@
+# -*- coding: utf-8 -*-%0A%0Afrom flask import Blueprint%0A%0Abp = Blueprint('health', __name__)%0A%0A@bp.route('/')%0Adef index():%0A return 'OK'%0A
|
|
a8b48d9174ce9c30166c0c2a8011c2c40624c4bd
|
Add a spider for Planned Parenthood
|
locations/spiders/planned_parenthood.py
|
locations/spiders/planned_parenthood.py
|
Python
| 0
|
@@ -0,0 +1,1790 @@
+# -*- coding: utf-8 -*-%0Aimport scrapy%0Aimport json%0Aimport re%0A%0Afrom locations.items import GeojsonPointItem%0A%0A%0Aclass PlannedParenthoodSpider(scrapy.Spider):%0A name = %22planned_parenthood%22%0A allowed_domains = %5B%22www.plannedparenthood.org%22%5D%0A start_urls = (%0A 'https://www.plannedparenthood.org/health-center',%0A )%0A%0A def parse(self, response):%0A state_urls = response.xpath('//ul%5B@class=%22quicklist-list%22%5D/li/a/@href').extract()%0A for path in state_urls:%0A yield scrapy.Request(%0A response.urljoin(path),%0A callback=self.parse_state,%0A )%0A%0A def parse_state(self, response):%0A venue_urls = response.xpath('//ul%5B@class=%22quicklist-list%22%5D/li/p/a/@href').extract()%0A for path in venue_urls:%0A yield scrapy.Request(%0A response.urljoin(path),%0A callback=self.parse_venue,%0A )%0A%0A def parse_venue(self, response):%0A properties = %7B%0A 'addr:full': response.xpath('//*%5B@itemprop=%22streetAddress%22%5D/text()')%5B0%5D.extract(),%0A 'addr:city': response.xpath('//*%5B@itemprop=%22addressLocality%22%5D/text()')%5B0%5D.extract(),%0A 'addr:state': response.xpath('//*%5B@itemprop=%22addressRegion%22%5D/text()')%5B0%5D.extract(),%0A 'addr:postcode': response.xpath('//*%5B@itemprop=%22postalCode%22%5D/text()')%5B0%5D.extract(),%0A 'ref': response.url,%0A 'website': response.url,%0A %7D%0A%0A map_image_url = response.xpath('//img%5B@class=%22address-map%22%5D/@src')%5B0%5D.extract()%0A match = re.search(r%22center=(.*?),(.*?)&zoom%22, map_image_url)%0A lon_lat = %5B%0A float(match.group(2)),%0A float(match.group(1)),%0A %5D%0A%0A yield GeojsonPointItem(%0A properties=properties,%0A lon_lat=lon_lat,%0A )%0A
|
|
7dbf6b978d45428e6162723cfa1c985a42a096df
|
Use more pythonic "private" methods
|
tvrenamr/tvrenamr.py
|
tvrenamr/tvrenamr.py
|
#!/usr/bin/python
import logging
import os
import sys
from __init__ import get_version
from config import Config
from episode import Episode
from errors import *
from logs import start_logging
from main import TvRenamr
from options import OptionParser
log = logging.getLogger('Core')
parser = OptionParser(usage='tvr [options] <file/folder>', version='Tv Renamr %s' % get_version())
options, args = parser.parse_args()
class FrontEnd():
def __init__(self, path):
# start logging
if options.debug:
options.log_level = 10
start_logging(options.log_file, options.log_level, options.quiet)
possible_config = (
options.config,
os.path.expanduser('~/.tvrenamr/config.yml'),
os.path.join(sys.path[0], 'config.yml')
)
# get the first viable config from the list of possibles
self.config = None
for config in possible_config:
if config is not None and os.path.exists(config):
self.config = Config(config)
break
if self.config is None:
raise ConfigNotFoundException
# no path was passed in so assuming current directory.
if not path:
if options.debug:
log.debug('No file or directory specified, using '
'current directory')
path = [os.getcwd()]
# determine type
try:
file_list = self.__determine_type(path, options.recursive,
options.ignore_filelist)
except OSError:
parser.error('\'%s\' is not a file or directory. Ruh Roe!' % path)
if options.dry or options.debug:
self.__start_dry_run()
# kick off a rename for each file in the list
for details in file_list:
self.rename(details)
# if we're not doing a dry run add a blank line for clarity
if options.debug is False and options.dry is False:
log.info('')
if options.dry or options.debug:
self.__stop_dry_run()
def __determine_type(self, path, recursive=False, ignore_filelist=None):
"""
Determines which files need to be processed for renaming.
:param path: The input file or directory.
:param recursive: Do a recursive search for files if 'path' is a
directory. Default is False.
:param ignore_filelist: Optional set of files to ignore from renaming.
Often used by filtering
methods such as Deluge.
:returns: A list of files to be renamed.
:rtype: A list of dictionaries, with the keys directory and filename.
"""
filelist = []
if len(path) > 1:
# must have used wildcards
for fn in path:
filelist.append(os.path.split(fn))
return filelist
else:
if os.path.isdir(path[0]):
for root, dirs, files in os.walk(path[0]):
for fname in files:
# If we have a file we should be ignoring and skipping.
if ignore_filelist is not None and \
(os.path.join(root, fname) in ignore_filelist):
continue
filelist.append((root, fname))
# Don't want a recursive walk?
if not recursive:
break
return filelist
elif os.path.isfile(path[0]):
return [os.path.split(path[0])]
else:
raise OSError
def rename(self, details):
working, filename = details
try:
tv = TvRenamr(working, self.config, options.debug, options.dry)
episode = Episode(tv.extract_details_from_file(filename, user_regex=options.regex))
if options.show:
episode.show = options.show
if options.season:
episode.season = options.season
if options.episode:
episode.episode = options.episode
episode.title = tv.retrieve_episode_name(episode, library=options.library, canonical=options.canonical)
episode.show = tv.format_show_name(episode.show, the=options.the, override=options.show_override)
path = tv.build_path(episode, rename_dir=options.rename_dir, organise=options.organise, format=options.output_format)
tv.rename(filename, path)
except (ConfigNotFoundException,
NoMoreLibrariesException,
NoNetworkConnectionException):
if options.dry or options.debug:
self.__stop_dry_run()
exit()
except (EmptyEpisodeNameException,
EpisodeAlreadyExistsInDirectoryException,
EpisodeNotFoundException,
IncorrectCustomRegularExpressionSyntaxException,
OutputFormatMissingSyntaxException,
ShowNotFoundException,
UnexpectedFormatException,
XMLEmptyException):
pass
except Exception as err:
if options.debug:
log.critical(err)
pass
def __start_dry_run(self):
log.log(26, 'Dry Run beginning.')
log.log(26, '-' * 70)
log.log(26, '')
def __stop_dry_run(self):
log.log(26, '')
log.log(26, '-' * 70)
log.log(26, 'Dry Run complete. No files were harmed in the process.')
log.log(26, '')
def run():
# Need to capture the Deluge arguments here, before we enter rename so
# we can instead pass it as a callback to be called once we've fetched
# the required information from deluge.
if options.deluge or options.deluge_ratio:
if options.deluge and not options.deluge_ratio:
options.deluge_ratio = 0
from lib.filter_deluge import get_deluge_ignore_file_list
get_deluge_ignore_file_list(rename, options.deluge_ratio, args[0])
else:
FrontEnd(args)
if __name__ == "__main__":
run()
|
Python
| 0
|
@@ -1470,31 +1470,31 @@
= self._
-_determine_type
+build_file_list
(path, o
@@ -1747,17 +1747,16 @@
self._
-_
start_dr
@@ -2103,33 +2103,32 @@
self._
-_
stop_dry_run()%0A%0A
@@ -2140,23 +2140,23 @@
ef _
-_determine_type
+build_file_list
(sel
@@ -4720,32 +4720,51 @@
options.debug:%0A
+ exit()%0A
@@ -4769,17 +4769,16 @@
self._
-_
stop_dry
@@ -4784,35 +4784,16 @@
y_run()%0A
- exit()%0A
@@ -5302,17 +5302,16 @@
def
-_
_start_d
@@ -5429,17 +5429,16 @@
def
-_
_stop_dr
|
ffd2985514aef7dd21eb7c8276ddcf98ecdfe075
|
Fix duplicate keys
|
vint/ast/plugin/builtin_identifiers.py
|
vint/ast/plugin/builtin_identifiers.py
|
BuiltinIdentifierMap = {
'abs': True,
'acos': True,
'add': True,
'append': True,
'append': True,
'argc': True,
'argidx': True,
'argv': True,
'argv': True,
'asin': True,
'atan': True,
'atan2': True,
'browse': True,
'browsedir': True,
'bufexists': True,
'buflisted': True,
'bufloaded': True,
'bufname': True,
'bufnr': True,
'bufwinnr': True,
'byte2line': True,
'byteidx': True,
'call': True,
'ceil': True,
'changenr': True,
'char2nr': True,
'cindent': True,
'clearmatches': True,
'col': True,
'complete': True,
'complete_add': True,
'complete_check': True,
'confirm': True,
'copy': True,
'cos': True,
'cosh': True,
'count': True,
'cscope_connection': True,
'cursor': True,
'deepcopy': True,
'delete': True,
'did_filetype': True,
'diff_filler': True,
'diff_hlID': True,
'empty': True,
'escape': True,
'eval': True,
'eventhandler': True,
'executable': True,
'exists': True,
'exp': True,
'expand': True,
'extend': True,
'feedkeys': True,
'filereadable': True,
'filewritable': True,
'filter': True,
'finddir': True,
'findfile': True,
'float2nr': True,
'floor': True,
'fmod': True,
'fnameescape': True,
'fnamemodify': True,
'foldclosed': True,
'foldclosedend': True,
'foldlevel': True,
'foldtext': True,
'foldtextresult': True,
'foreground': True,
'function': True,
'garbagecollect': True,
'get': True,
'get': True,
'getbufline': True,
'getbufvar': True,
'getchar': True,
'getcharmod': True,
'getcmdline': True,
'getcmdpos': True,
'getcmdtype': True,
'getcwd': True,
'getfontname': True,
'getfperm': True,
'getfsize': True,
'getftime': True,
'getftype': True,
'getline': True,
'getline': True,
'getloclist': True,
'getmatches': True,
'getpid': True,
'getpos': True,
'getqflist': True,
'getreg': True,
'getregtype': True,
'gettabvar': True,
'gettabwinvar': True,
'getwinposx': True,
'getwinposy': True,
'getwinvar': True,
'glob': True,
'globpath': True,
'has': True,
'has_key': True,
'haslocaldir': True,
'hasmapto': True,
'histadd': True,
'histdel': True,
'histget': True,
'histnr': True,
'hlID': True,
'hlexists': True,
'hostname': True,
'iconv': True,
'indent': True,
'index': True,
'input': True,
'inputdialog': True,
'inputlist': True,
'inputrestore': True,
'inputsave': True,
'inputsecret': True,
'insert': True,
'isdirectory': True,
'islocked': True,
'items': True,
'join': True,
'keys': True,
'len': True,
'libcall': True,
'libcallnr': True,
'line': True,
'line2byte': True,
'lispindent': True,
'localtime': True,
'log': True,
'log10': True,
'map': True,
'maparg': True,
'mapcheck': True,
'match': True,
'matchadd': True,
'matcharg': True,
'matchdelete': True,
'matchend': True,
'matchlist': True,
'matchstr': True,
'max': True,
'min': True,
'mkdir': True,
'mode': True,
'nextnonblank': True,
'nr2char': True,
'pathshorten': True,
'pow': True,
'prevnonblank': True,
'printf': True,
'pumvisible': True,
'range': True,
'readfile': True,
'reltime': True,
'reltimestr': True,
'remote_expr': True,
'remote_foreground': True,
'remote_peek': True,
'remote_read': True,
'remote_send': True,
'remove': True,
'remove': True,
'rename': True,
'repeat': True,
'resolve': True,
'reverse': True,
'round': True,
'search': True,
'searchdecl': True,
'searchpair': True,
'searchpairpos': True,
'searchpos': True,
'server2client': True,
'serverlist': True,
'setbufvar': True,
'setcmdpos': True,
'setline': True,
'setloclist': True,
'setmatches': True,
'setpos': True,
'setqflist': True,
'setreg': True,
'settabvar': True,
'settabwinvar': True,
'setwinvar': True,
'shellescape': True,
'simplify': True,
'sin': True,
'sinh': True,
'sort': True,
'soundfold': True,
'spellbadword': True,
'spellsuggest': True,
'split': True,
'sqrt': True,
'str2float': True,
'str2nr': True,
'strchars': True,
'strdisplaywidth': True,
'strftime': True,
'stridx': True,
'string': True,
'strlen': True,
'strpart': True,
'strridx': True,
'strtrans': True,
'strwidth': True,
'submatch': True,
'substitute': True,
'synID': True,
'synIDattr': True,
'synIDtrans': True,
'synconcealed': True,
'synstack': True,
'system': True,
'tabpagebuflist': True,
'tabpagenr': True,
'tabpagewinnr': True,
'tagfiles': True,
'taglist': True,
'tan': True,
'tanh': True,
'tempname': True,
'tolower': True,
'toupper': True,
'tr': True,
'trunc': True,
'type': True,
'undofile': True,
'undotree': True,
'values': True,
'virtcol': True,
'visualmode': True,
'winbufnr': True,
'wincol': True,
'winheight': True,
'winline': True,
'winnr': True,
'winrestcmd': True,
'winrestview': True,
'winsaveview': True,
'winwidth': True,
'writefile': True,
}
|
Python
| 0.003202
|
@@ -90,36 +90,16 @@
: True,%0A
- 'append': True,%0A
'arg
@@ -100,32 +100,32 @@
'argc': True,%0A
+
'argidx': Tr
@@ -146,34 +146,16 @@
: True,%0A
- 'argv': True,%0A
'asi
@@ -1543,33 +1543,16 @@
: True,%0A
- 'get': True,%0A
'get
@@ -1860,37 +1860,16 @@
: True,%0A
- 'getline': True,%0A
'get
@@ -3539,32 +3539,32 @@
te_read': True,%0A
+
'remote_send
@@ -3592,36 +3592,16 @@
: True,%0A
- 'remove': True,%0A
'ren
|
0331bffc755ad4234edcca3edaf1b9697b8ae8c3
|
Create A.py
|
Google-Code-Jam/2010-Africa/A.py
|
Google-Code-Jam/2010-Africa/A.py
|
Python
| 0.000004
|
@@ -0,0 +1 @@
+%0A
|
|
c568256dac3c13f6740d2a2df5a8a848e2f7d68e
|
check in new stream settings file
|
waterbutler/core/streams/settings.py
|
waterbutler/core/streams/settings.py
|
Python
| 0
|
@@ -0,0 +1,179 @@
+from waterbutler import settings%0A%0A%0Aconfig = settings.child('STREAMS_CONFIG')%0A%0A%0AZIP_EXTENSIONS = config.get('ZIP_EXTENSIONS', '.zip .gz .bzip .bzip2 .rar .xz .bz2 .7z').split(' ')%0A
|
|
5bea532c7651faacb163745fbbf28fa4f53ba438
|
add predicting-office-space-price
|
ai/machine-learning/predicting-office-space-price/predicting-office-space-price.py
|
ai/machine-learning/predicting-office-space-price/predicting-office-space-price.py
|
Python
| 0.998153
|
@@ -0,0 +1,596 @@
+import numpy as np%0Afrom sklearn.preprocessing import PolynomialFeatures%0Afrom sklearn import linear_model%0A%0Aif __name__ == %22__main__%22:%0A (f, n) = map(int, raw_input().split())%0A x = %5B%5D%0A y = %5B%5D%0A poly = PolynomialFeatures(degree = 4)%0A for i in range(n):%0A v = map(float, raw_input().split())%0A x.append(poly.fit_transform(v%5B:-1%5D)%5B0%5D)%0A y.append(v%5B-1%5D)%0A %0A clf = linear_model.BayesianRidge()%0A clf.fit(x, y)%0A %0A tc = int(raw_input())%0A for i in range(tc):%0A v = map(float, raw_input().split())%0A print clf.predict(poly.transform(v))%5B0%5D%0A
|
|
62271f00475216b7e16aa6deb900702d52973606
|
Fix import and stylesheet stripping tests
|
third_party/tvcm/tvcm/parse_html_deps_unittest.py
|
third_party/tvcm/tvcm/parse_html_deps_unittest.py
|
#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import parse_html_deps
import re
class ParseTests(unittest.TestCase):
def test_parse_empty(self):
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse("")
self.assertEquals([], module.scripts_external)
self.assertEquals([], module.scripts_inline)
self.assertEquals([], module.stylesheets)
self.assertEquals([], module.imports)
def test_parse_none(self):
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(None)
self.assertEquals([], module.scripts_external)
self.assertEquals([], module.scripts_inline)
self.assertEquals([], module.stylesheets)
self.assertEquals([], module.imports)
def test_parse_script_src(self):
html = """<!DOCTYPE html>
<html>
<head>
<script src="polymer.min.js"></script>
<script src="foo.js"></script>
</head>
<body>
</body>
</html>"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals(['polymer.min.js', 'foo.js'], module.scripts_external);
self.assertEquals([], module.scripts_inline)
self.assertEquals([], module.stylesheets)
self.assertEquals([], module.imports)
self.assertTrue(module.has_decl)
self.assertTrue('DOCTYPE html' not in module.html_contents_without_links_and_script)
def test_parse_link_rel_import(self):
html = """<!DOCTYPE html>
<html>
<head>
<link rel="import" href="x-foo.html">
</head>
<body>
</body>
</html>"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals([], module.scripts_external);
self.assertEquals([], module.scripts_inline)
self.assertEquals([], module.stylesheets)
self.assertEquals(['x-foo.html'], module.imports)
self.assertTrue(module.has_decl)
def test_parse_script_inline(self):
html = """<polymer-element name="tk-element-proto">
<template>
</template>
<script>
tvcm.require("foo");
tvcm.require('bar');
</script>
</polymer-element>"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals([], module.scripts_external);
self.assertEquals(1, len(module.scripts_inline))
self.assertEquals([], module.stylesheets)
self.assertEquals([], module.imports)
self.assertFalse(module.has_decl)
val = module.scripts_inline[0]
val = re.sub(r"\s+", '', val)
inner_script = """tvcm.require("foo");tvcm.require('bar');"""
self.assertEquals(inner_script, val)
assert 'tvcm.require("foo");' not in module.html_contents_without_links_and_script
def test_parse_script_src_sripping(self):
html = """
<script src="blah.js"></script>
"""
module = parse_html_deps.HTMLModuleParser().Parse(html)
self.assertEquals('\n\n', module.html_contents_without_links_and_script)
def test_parse_link_rel_stylesheet(self):
html = """<polymer-element name="hi">
<template>
<link rel="stylesheet" href="frameworkstyles.css">
</template>
</polymer-element>"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals([], module.scripts_external);
self.assertEquals([], module.scripts_inline)
self.assertEquals(['frameworkstyles.css'], module.stylesheets)
self.assertEquals([], module.imports)
self.assertFalse(module.has_decl)
def test_parse_inline_style(self):
html = """
<style>
hello
</style>"""
module = parse_html_deps.HTMLModuleParser().Parse(html)
self.assertEquals(html, module.html_contents_without_links_and_script)
def test_parse_style_import(self):
html = """<polymer-element name="x-blink">
<template>
<style>
@import url(awesome.css);
</style>
</template>
</polymer-element>"""
parser = parse_html_deps.HTMLModuleParser()
self.assertRaises(lambda: parser.Parse(html))
def html_contents_basic(self):
html = """<a b="c">d</a>"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals(html, module.html_contents_without_links_and_script)
def html_contents_with_link_stripping(self):
html = """<a b="c">d</a>
<link rel="import" href="x-foo.html">"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals("""<a b="c">d</a>""",
module.html_contents_without_links_and_script)
def html_contents_with_style_link_stripping(self):
html = """<a b="c">d</a>
<link rel="stylesheet" href="frameworkstyles.css">"""
parser = parse_html_deps.HTMLModuleParser()
module = parser.Parse(html)
self.assertEquals("""<a b="c">d</a>""",
module.html_contents_without_links_and_script)
if __name__ == '__main__':
unittest.main()
|
Python
| 0.000003
|
@@ -4471,32 +4471,37 @@
e(html))%0A%0A def
+test_
html_contents_ba
@@ -4697,32 +4697,37 @@
_script)%0A%0A def
+test_
html_contents_wi
@@ -5018,32 +5018,40 @@
links_and_script
+.strip()
)%0A%0A def html_co
@@ -5043,16 +5043,21 @@
%0A%0A def
+test_
html_con
@@ -5379,24 +5379,32 @@
s_and_script
+.strip()
)%0A%0A%0A%0Aif __na
|
45fea3847e2800a920ccb06e102ebaf9a5f9a4ce
|
Add forgotten migration for newly introduced default ordering
|
tk/material/migrations/0002_auto_20170704_2155.py
|
tk/material/migrations/0002_auto_20170704_2155.py
|
Python
| 0
|
@@ -0,0 +1,2175 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.2 on 2017-07-04 19:55%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0Aimport localized_fields.fields.field%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('material', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterModelOptions(%0A name='approval',%0A options=%7B'ordering': %5B'-requested'%5D, 'verbose_name': 'Approval', 'verbose_name_plural': 'Approvals'%7D,%0A ),%0A migrations.AlterModelOptions(%0A name='goal',%0A options=%7B'ordering': %5B'name'%5D, 'verbose_name': 'Goal', 'verbose_name_plural': 'Goals'%7D,%0A ),%0A migrations.AlterModelOptions(%0A name='groupfeature',%0A options=%7B'ordering': %5B'name'%5D, 'verbose_name': 'Group feature', 'verbose_name_plural': 'Group features'%7D,%0A ),%0A migrations.AlterModelOptions(%0A name='location',%0A options=%7B'ordering': %5B'name'%5D, 'verbose_name': 'Location', 'verbose_name_plural': 'Locations'%7D,%0A ),%0A migrations.AlterModelOptions(%0A name='subject',%0A options=%7B'ordering': %5B'name'%5D, 'verbose_name': 'Subject', 'verbose_name_plural': 'Subjects'%7D,%0A ),%0A migrations.AlterField(%0A model_name='goal',%0A name='name',%0A field=localized_fields.fields.field.LocalizedField(max_length=512, required=%5B%5D, uniqueness=%5B%5D, verbose_name='name'),%0A ),%0A migrations.AlterField(%0A model_name='groupfeature',%0A name='name',%0A field=localized_fields.fields.field.LocalizedField(max_length=512, required=%5B%5D, uniqueness=%5B%5D, verbose_name='name'),%0A ),%0A migrations.AlterField(%0A model_name='location',%0A name='name',%0A field=localized_fields.fields.field.LocalizedField(max_length=512, required=%5B%5D, uniqueness=%5B%5D, verbose_name='name'),%0A ),%0A migrations.AlterField(%0A model_name='subject',%0A name='name',%0A field=localized_fields.fields.field.LocalizedField(max_length=512, required=%5B%5D, uniqueness=%5B%5D, verbose_name='name'),%0A ),%0A %5D%0A
|
|
af0486cd767564cda7259aa30a0d7c90420e226e
|
Add get json example
|
chapter2/get.py
|
chapter2/get.py
|
Python
| 0
|
@@ -0,0 +1,113 @@
+import urllib2,json%0Aresults = urllib2.urlopen('http://192.168.168.84/api.json').read()%0Ajson.loads(results)%5B'led'%5D
|
|
1acbad02071a4d1ef953bc2c0643525e5d681d54
|
Add in a script to run the linter manually
|
runlint.py
|
runlint.py
|
Python
| 0.000382
|
@@ -0,0 +1,1151 @@
+#!/usr/bin/env python%0A%0Aimport optparse%0Aimport sys%0A%0Afrom closure_linter import checker%0Afrom closure_linter import error_fixer%0Afrom closure_linter import gjslint%0A%0A%0AUSAGE = %22%22%22%25prog %5Boptions%5D %5Bfile1%5D %5Bfile2%5D...%0A%0ARun a JavaScript linter on one or more files.%0A%0AThis will invoke the linter, and optionally attempt to auto-fix style-violations on the specified JavaScript files.%0A%22%22%22%0A%0A%0Adef check_files(filenames):%0A fake_args = %5Bgjslint.__file__, '--nobeep'%5D + filenames%0A return gjslint.main(argv=fake_args) == 0%0A%0A%0Adef fix_files(filenames):%0A style_checker = checker.JavaScriptStyleChecker(error_fixer.ErrorFixer())%0A%0A for filename in filenames:%0A style_checker.Check(filename)%0A return 0%0A%0A%0Adef main():%0A parser = optparse.OptionParser(USAGE)%0A parser.add_option('--autofix',%0A dest='autofix',%0A action='store_true',%0A default=False,%0A help='Whether or not to autofix')%0A options, args = parser.parse_args()%0A if options.autofix:%0A return fix_files(args)%0A else:%0A return check_files(args)%0A%0A%0Aif __name__ == '__main__':%0A sys.exit(main())%0A
|
|
3e5d6e5dd31193f42ebddaeff856bfe53703a19e
|
Add script to get evidence sources
|
models/fallahi_eval/evidence_sources.py
|
models/fallahi_eval/evidence_sources.py
|
Python
| 0
|
@@ -0,0 +1,1187 @@
+from util import pklload%0Afrom collections import defaultdict%0Aimport indra.tools.assemble_corpus as ac%0A%0A%0Aif __name__ == '__main__':%0A # Load cached Statements just before going into the model%0A stmts = pklload('pysb_stmts')%0A%0A # Start a dictionary for source counts%0A sources_count = defaultdict(int)%0A # Count statements according to sources of evidence%0A for stmt in stmts:%0A sources = tuple(sorted(list(set(%5Bev.source_api for ev in stmt.evidence%5D))))%0A sources_count%5Bsources%5D += 1%0A%0A # Statements from databases only%0A db_only = 0%0A # Statements from reading only%0A reading_only = 0%0A # Statements from databases and reading%0A mixture = 0%0A # Database sources%0A dbs = set(%5B'bel', 'biopax', 'phosphosite', 'signor'%5D)%0A # Reader sources%0A readers = set(%5B'reach', 'trips', 'sparser', 'r3'%5D)%0A for k, v in sources_count.items():%0A d = set(k).intersection(dbs)%0A r = set(k).intersection(readers)%0A if d and r:%0A mixture += v%0A if d and not r:%0A db_only += v%0A if r and not d:%0A reading_only += v%0A%0A for k, v in sorted(sources_count.items(), key=lambda x: x%5B1%5D):%0A print(k, v)%0A
|
|
276435cc3b4f77dc16dde4a73cd930e461e1ef47
|
Implement LM in defn/lm.py
|
imaginet/defn/lm.py
|
imaginet/defn/lm.py
|
Python
| 0.001362
|
@@ -0,0 +1,2276 @@
+from funktional.layer import Layer, Dense, StackedGRU, StackedGRUH0, %5C%0A Embedding, OneHot, clipped_rectify, CrossEntropy, %5C%0A last, softmax3d, params%0Aimport funktional.context as context %0Afrom funktional.layer import params%0Aimport imaginet.task %0Afrom funktional.util import autoassign%0Aimport funktional.util as util%0Aimport theano.tensor as T%0Aimport theano%0Aimport zipfile%0Aimport numpy%0Aimport StringIO%0Aimport json%0Aimport cPickle as pickle%0A%0Aclass Decoder(Layer):%0A def __init__(self, size_vocab, size_embed, size, depth):%0A autoassign(locals())%0A self.Embed = Embedding(self.size_vocab, self.size_embed)%0A self.GRU = StackedGRUH0(self.size_embed, self.size, self.depth, activation=clipped_rectify)%0A %0A def params(self):%0A return params(self.Embed, self.GRU)%0A %0A def __call__(self, out_prev):%0A return self.GRU(self.Embed(out_prev))%0A %0Aclass LM(imaginet.task.Task):%0A def __init__(self, config):%0A autoassign(locals())%0A self.updater = util.Adam(max_norm=config%5B'max_norm'%5D, lr=config%5B'lr'%5D)%0A self.Decode = Decoder(config%5B'size_vocab'%5D, config%5B'size_embed'%5D, config%5B'size'%5D, config%5B'depth'%5D)%0A self.ToTxt = Dense(config%5B'size'%5D, config%5B'size_vocab'%5D) %0A self.inputs = %5BT.imatrix()%5D%0A self.target = T.imatrix()%0A %0A def params(self):%0A return params(self.Decode, self.ToTxt)%0A %0A def __call__(self, out_prev):%0A return softmax3d(self.ToTxt(self.Decode(out_prev)))%0A %0A def cost(self, target, prediction):%0A oh = OneHot(size_in=self.config%5B'size_vocab'%5D)%0A return CrossEntropy(oh(target), prediction)%0A%0A def args(self, item):%0A %22%22%22Choose elements of item to be passed to .loss_test and .train functions.%22%22%22%0A inp, target_v, out_prev, target_t = item%0A return (out_prev, target_t)%0A %0A def _make_representation(self):%0A with context.context(training=False):%0A rep = self.Decode(*self.inputs)%0A return theano.function(self.inputs, rep)%0A %0A def _make_pile(self):%0A with context.context(training=False):%0A rep = self.Decode.GRU.intermediate(self.Decode.Embed(*self.inputs))%0A return theano.function(self.inputs, rep)%0A %0A
|
|
bcb8615fb0d009ad4e7899b9e91701333dc56990
|
Add abyss package (#4555)
|
var/spack/repos/builtin/packages/abyss/package.py
|
var/spack/repos/builtin/packages/abyss/package.py
|
Python
| 0
|
@@ -0,0 +1,2289 @@
+##############################################################################%0A# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/llnl/spack%0A# Please also see the LICENSE file for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass Abyss(AutotoolsPackage):%0A %22%22%22ABySS is a de novo, parallel, paired-end sequence assembler%0A that is designed for short reads. The single-processor version%0A is useful for assembling genomes up to 100 Mbases in size.%22%22%22%0A%0A homepage = %22http://www.bcgsc.ca/platform/bioinfo/software/abyss%22%0A url = %22http://www.bcgsc.ca/platform/bioinfo/software/abyss/releases/2.0.2/abyss-2.0.2.tar.gz%22%0A%0A version('2.0.2', '1623f55ad7f4586e80f6e74b1f27c798')%0A%0A depends_on('mpi')%0A depends_on('boost@:1.50.0,1.53.0:')%0A depends_on('sparsehash')%0A depends_on('sqlite')%0A%0A conflicts('%5Eintel-mpi')%0A conflicts('%5Eintel-parallel-studio+mpi')%0A conflicts('%5Emvapich2')%0A conflicts('%5Espectrum-mpi')%0A%0A def configure_args(self):%0A args = %5B'--with-boost=%25s' %25 self.spec%5B'boost'%5D.prefix,%0A '--with-sqlite=%25s' %25 self.spec%5B'sqlite'%5D.prefix,%0A '--with-mpi=%25s' %25 self.spec%5B'mpi'%5D.prefix%5D%0A if self.spec%5B'mpi'%5D.name == 'mpich':%0A args.append('--enable-mpich')%0A return args%0A
|
|
418e714e3d544abc7120c7252c51493cd59081a0
|
Add custom CommentedObjectManager
|
comment_utils/managers.py
|
comment_utils/managers.py
|
Python
| 0.000001
|
@@ -0,0 +1,2178 @@
+%22%22%22%0ACustom manager which managers of objects which allow commenting can%0Ainheit from.%0A%0A%22%22%22%0A%0Afrom django.db import models%0A%0Aclass CommentedObjectManager(models.Manager):%0A %22%22%22%0A A custom manager class which provides useful methods for types of%0A objects which allow comments.%0A %0A Models which allow comments but don't need the overhead of their%0A own fully-defined custom manager should use an instance of this%0A manager as their default manager.%0A %0A Models which allow comments and which do have fully-defined custom%0A managers should have those managers subclass this one.%0A %0A %22%22%22%0A def most_commented(self, num=5, free=True):%0A %22%22%22%0A Returns the %60%60num%60%60 objects of a given model with the highest%0A comment counts, in order.%0A %0A Pass %60%60free=False%60%60 if you're using the registered comment%0A model (%60%60Comment%60%60) instead of the anonymous comment model%0A (%60%60FreeComment%60%60).%0A %0A %22%22%22%0A from django.db import backend, connection%0A from django.contrib.comments import models as comment_models%0A from django.contrib.contenttypes.models import ContentType%0A if free:%0A comment_opts = comment_models.FreeComment._meta%0A else:%0A comment_opts = comment_models.Comment._meta%0A ctype = ContentType.objects.get_for_model(self.model)%0A query = %22%22%22SELECT %25s, COUNT(*) AS score%0A FROM %25s%0A WHERE content_type_id = %25%25s%0A AND is_public = 1%0A GROUP BY %25s%0A ORDER BY score DESC%22%22%22 %25 (backend.quote_name('object_id'),%0A backend.quote_name(comment_opts.db_table),%0A backend.quote_name('object_id'),)%0A %0A cursor = connection.cursor()%0A cursor.execute(query, %5Bctype.id%5D)%0A entry_ids = %5Brow%5B0%5D for row in cursor.fetchall()%5B:num%5D%5D%0A %0A # Use %60%60in_bulk%60%60 here instead of an %60%60id__in%60%60 filter, because %60%60id__in%60%60%0A # would clobber the ordering.%0A entry_dict = self.in_bulk(entry_ids)%0A return %5Bentry_dict%5Bentry_id%5D for entry_id in entry_ids%5D%0A
|
|
f189ed9401e82e55a7b3b73ce06a8f5c642344ac
|
Add functional test file
|
functional_tests.py
|
functional_tests.py
|
Python
| 0.000001
|
@@ -0,0 +1,348 @@
+from selenium import webdriver%0Aimport unittest%0A%0Aclass Test(unittest.TestCase):%0A%0A def setUp(self):%0A self.browser = webdriver.Firefox()%0A self.browser.implicitly_wait(3) # Browser will eventually wait 3 secs%0A # for a thing to appear if needed%0A%0A def tearDown(self):%0A self.browser.quit()
|
|
09a25009965d9951614ed0702185947f796c41a0
|
Create scraper.py
|
scraper.py
|
scraper.py
|
Python
| 0.000004
|
@@ -0,0 +1,781 @@
+from lxml.html import parse%0A%0Adef main():%0A%09baseurl = 'http://www.schoolcolleges.com/school.select.php?offset=%25s&val=city=%25270%2527&select=%25s'%0A%09states = %5B%0A%09'Andhra Pradesh',%0A%09'Arunachal Pradesh',%0A%09'Assam',%0A%09'BIHAR',%0A%09'Chhattisgarh',%0A%09'Goa',%0A%09'Gujarat',%0A%09'Haryana',%0A%09'Himachal Pradesh',%0A%09'Jammu & Kashmir',%0A%09'Jharkhand',%0A%09'Karnataka',%0A%09'Kerala',%0A%09'Madhya Pradesh',%0A%09'Maharashtra',%0A%09'Manipur',%0A%09'Meghalaya',%0A%09'Mizoram',%0A%09'Nagaland',%0A%09'Odisha',%0A%09'Punjab',%0A%09'Rajasthan',%0A%09'Sikkim',%0A%09'Tamil Nadu',%0A%09'Tripura',%0A%09'Uttarakhand',%0A%09'Uttar Pradesh',%0A%09'West Bengal'%5D%0A%09n = 10%0A%09for state in states:%0A%09%09offset = str(n)%0A%09%09url = baseurl %25(offset) %25(state)%0A%09%09page = parse(url).getroot()%0A%09%09#tr21,25,29...%0A%09%09for i in xrange(21,102,4):%0A%09%09%09table = page.cssselect('tr')%5Bi%5D%0A%09%09%09data = table.cssselect('td')%0A%09%09%09%0A
|
|
691543bb43b67dd9cc9ff6d6ee6a212badd4c61e
|
add valid unicode example
|
scripts/unicode_valid.py
|
scripts/unicode_valid.py
|
Python
| 0.004751
|
@@ -0,0 +1,440 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0Aimport json%0A%0A%0Aprint(json.dumps(%7B%0A %22_meta%22: %7B%0A %22hostvars%22: %7B%0A %22not_unicode%22: %7B%22host_var%22: %22unicode here %E6%97%A5%E6%9C%AC%E8%AA%9E%22%7D%0A %7D%0A %7D,%0A %22all%22: %7B%0A %22vars%22: %7B%0A %22inventory_var%22: %22this is an inventory var %E6%97%A5%E6%9C%AC%E8%AA%9E%22%0A %7D%0A %7D,%0A %22group_%E6%97%A5%E6%9C%AC%E8%AA%9E%22: %7B%0A %22hosts%22: %5B%22not_unicode%22%5D,%0A %22vars%22: %7B%0A %22group_var%22: %22this is group_var %E6%97%A5%E6%9C%AC%E8%AA%9E%22%0A %7D%0A %7D%0A%7D))
|
|
2bc7acd167d6e18dfbc2bc2625957f2bd58fa1f5
|
Create spacial_prototype.py
|
Vision/spacial_prototype.py
|
Vision/spacial_prototype.py
|
Python
| 0.000003
|
@@ -0,0 +1,2323 @@
+import numpy as np%0Aimport math as m%0A%0A# Prototype code for the image-to-world location system. Requires numpy.%0A%0A# TODO%0Adef _inverse_perspective():%0A pass%0A%0A# Convert a global coordinate to a relative coordinate%0A# (roll, pitch, yaw) = camera_angle%0A# (x, y, z) = camera_pos, cone_pos (global coordinates)%0A# (width, height) = img_size, sensor_size (sizes)%0A# Returns a 2x1 Matrix with the %5BX Y%5D pixel of the cone%0Adef _global_to_relative(camera_angle,%0A camera_pos,%0A cone_pos,%0A focal_length,%0A img_size,%0A sensor_size):%0A%0A (a, b, c) = camera_angle%0A (X1w, Y1w, Z1w) = camera_pos%0A (X2w, Y2w, Z2w) = cone_pos%0A (img_width, img_height) = img_size%0A (sensor_width, sensor_height) = sensor_size%0A%0A wP = sensor_width / img_width; hP = sensor_height / img_height%0A d = m.sqrt((X1w - X2w)**2 + (Y1w - Y2w)**2 + (Z1w - Z2w)**2)%0A%0A df = np.array(%5B(X2w - X1w),%0A (Y2w - Y1w),%0A (Z2w - Z1w)%5D)%0A%0A ma = np.array(%5B(1, 0 , 0 ),%0A (0, m.cos(a), m.sin(a)),%0A (0, -m.sin(a), m.cos(a))%5D)%0A%0A mb = np.array(%5B(m.cos(b), 0, -m.sin(b)),%0A (0 , 1, 0 ),%0A (m.sin(b), 0, m.cos(b))%5D)%0A%0A mc = np.array(%5B( m.cos(c), m.sin(c), 0),%0A (-m.sin(c), m.cos(c), 0),%0A (0 , 0 , 1)%5D)%0A%0A cc = np.array(%5B(0, focal_length / (d * wP), 0),%0A (0, 0, focal_length / (d * hP))%5D)%0A%0A im = np.array(%5B(img_width / 2),%0A (img_height / 2)%5D)%0A%0A converted_to_camera = mc.dot(mb).dot(ma).dot(df)%0A return cc.dot(converted_to_camera) + im%0A%0A# Tiny test suite for the _global_to_relative function%0Adef _test_global_to_relative():%0A print(_global_to_relative((0, 0, 0), (0, 0, 0), (10, 2, 0), 0.01, (320, 240), (0.05, 0.05)))%0A print(_global_to_relative((0, 0, 0), (0, 0, 1), (10, 2, 0), 0.01, (320, 240), (0.05, 0.05)))%0A print(_global_to_relative((0, 0.3, 0), (0, 0, 0), (10, 2, 0), 0.01, (320, 240), (0.05, 0.05)))%0A print(_global_to_relative((0, 0, 0.3), (0, 0, 0), (10, 2, 0), 0.01, (320, 240), (0.05, 0.05)))%0A%0Aif __name__ == %22__main__%22:%0A _test_global_to_relative()%0A
|
|
785f6a4f435c68bb6336b4e42da0964cf5cbfce4
|
Add module that finds classifier training examples given a ground truth in the graph
|
hytra/jst/classifiertrainingexampleextractor.py
|
hytra/jst/classifiertrainingexampleextractor.py
|
Python
| 0.00015
|
@@ -0,0 +1,3098 @@
+'''%0AProvide methods to find positive and negative training examples from a hypotheses graph and %0Aa ground truth mapping, in the presence of multiple competing segmentation hypotheseses.%0A'''%0A%0Aimport numpy as np%0Aimport logging%0Afrom hytra.core.random_forest_classifier import RandomForestClassifier%0A%0Adef getLogger():%0A ''' logger to be used in this module '''%0A return logging.getLogger(__name__)%0A%0Adef trainDetectionClassifier(hypothesesGraph, gtFrameIdToGlobalIdsWithScoresMap, numSamples=100, selectedFeatures=None):%0A %22%22%22%0A Finds the given number of training examples, half as positive and half as negative examples, from the%0A given graph and mapping.%0A%0A Positive examples are those with the highest jaccard score, while negative examples can either %0A just not be the best match for a GT label, or also be not matched at all.%0A%0A%0A%0A **Returns**: a trained random forest%0A %22%22%22%0A # create a list of all elements, sort them by their jaccard score, then pick from both ends?%0A getLogger().debug(%22Extracting candidates%22)%0A candidates = %5B%5D%0A%0A nodeTraxelMap = hypothesesGraph.getNodeTraxelMap()%0A for node in hypothesesGraph.nodeIterator():%0A if 'JaccardScores' in nodeTraxelMap%5Bnode%5D.Features and len(nodeTraxelMap%5Bnode%5D.Features%5B'JaccardScores'%5D) %3E 0:%0A globalIdsAndScores = nodeTraxelMap%5Bnode%5D.Features%5B'JaccardScores'%5D%0A globalIdsAndScores = sorted(globalIdsAndScores, key=lambda x: x%5B1%5D)%0A bestScore = globalIdsAndScores%5B-1%5D%5B1%5D%0A candidates.append( (node, bestScore) )%0A %0A assert(len(candidates) %3E= numSamples)%0A candidates.sort(key=lambda x: x%5B1%5D)%0A%0A # pick the first and last numSamples/2, and extract their features?%0A # use RandomForestClassifier's method %22extractFeatureVector%22%0A selectedSamples = candidates%5B0:numSamples//2%5D + candidates%5B-numSamples//2-1:-1%5D%0A labels = np.hstack(%5Bnp.zeros(numSamples//2), np.ones(numSamples//2)%5D)%0A%0A # TODO: make sure that the positive examples were all selected in the GT mapping%0A%0A getLogger().debug(%22construct feature matrix%22)%0A node = selectedSamples%5B0%5D%5B0%5D%0A if selectedFeatures is None:%0A selectedFeatures = nodeTraxelMap%5Bnode%5D.Features.keys()%0A forbidden = %5B'JaccardScores', 'id', 'filename' , 'Polygon', 'detProb', 'divProb', 'com'%5D%0A forbidden += %5Bf for f in selectedFeatures if f.count('_') %3E 0%5D%0A for f in forbidden:%0A if f in selectedFeatures:%0A selectedFeatures.remove(f)%0A getLogger().info(%22No list of selected features was specified, using %7B%7D%22.format(selectedFeatures))%0A%0A rf = RandomForestClassifier(selectedFeatures=selectedFeatures)%0A features = rf.extractFeatureVector(nodeTraxelMap%5Bnode%5D.Features, singleObject=True)%0A featureMatrix = np.zeros( %5Blen(selectedSamples), features.shape%5B1%5D%5D )%0A featureMatrix%5B0, :%5D = features%0A for idx, nodeAndScore in enumerate(selectedSamples%5B1:%5D):%0A features = rf.extractFeatureVector(nodeTraxelMap%5BnodeAndScore%5B0%5D%5D.Features, singleObject=True)%0A featureMatrix%5Bidx + 1, :%5D = features%0A%0A rf.train(featureMatrix, labels)%0A%0A return rf
|
|
23f6d87b94bf0340b70b9803f1b8c712f1d88726
|
Add models in session module.
|
dataviva/apps/session/models.py
|
dataviva/apps/session/models.py
|
Python
| 0
|
@@ -0,0 +1,1356 @@
+from dataviva.apps.session.login_providers import facebook, twitter, google%0Afrom dataviva.apps.account.models import User%0Afrom dataviva.utils.encode import sha512%0Afrom flask import Blueprint, request, render_template, session, redirect, Response%0A%0Afrom flask.ext.login import login_user, logout_user%0Afrom forms import LoginForm%0A%0A%0Amod = Blueprint('session', __name__,%0A template_folder='templates',%0A url_prefix='/%3Clang_code%3E/session',%0A static_folder='static')%0A%0A%0A@mod.route('/login', methods=%5B%22GET%22, %22POST%22%5D)%0Adef login():%0A%0A form = LoginForm()%0A%0A if request.method == %22POST%22:%0A user = User.query.filter_by(email=form.email.data, password=sha512(form.password.data)).first()%0A if user:%0A if user.confirmed:%0A login_user(user, remember=True)%0A return redirect(%22/%22)%0A else:%0A return Response(%22Confirm Pending%22, status=401, mimetype='application/json', )%0A else:%0A return Response(%22Email or Password Incorrect!%22, status=400, mimetype='application/json')%0A%0A else:%0A return render_template('user/login.html', form=form)%0A%0A%0A@mod.route('/logout/')%0Adef logout():%0A session.pop('twitter_token', None)%0A session.pop('google_token', None)%0A session.pop('facebook_token', None)%0A logout_user()%0A return redirect('/')%0A
|
|
ccd1822d65f5565d4881e5a6a32b535e55cc2b50
|
Implement preview of entries for restricted users in EntryPreviewMixin
|
zinnia/views/mixins/entry_preview.py
|
zinnia/views/mixins/entry_preview.py
|
Python
| 0
|
@@ -0,0 +1,857 @@
+%22%22%22Preview mixins for Zinnia views%22%22%22%0Afrom django.http import Http404%0Afrom django.utils.translation import ugettext as _%0A%0Afrom zinnia.managers import PUBLISHED%0A%0A%0Aclass EntryPreviewMixin(object):%0A %22%22%22%0A Mixin implementing the preview of Entries.%0A %22%22%22%0A%0A def get_object(self, queryset=None):%0A %22%22%22%0A If the status of the entry is not PUBLISHED,%0A a preview is requested, so we check if the user%0A has the 'zinnia.can_view_all' permission or if%0A it's an author of the entry.%0A %22%22%22%0A obj = super(EntryPreviewMixin, self).get_object(queryset)%0A if obj.status == PUBLISHED:%0A return obj%0A if (self.request.user.has_perm('zinnia.can_view_all') or%0A self.request.user in obj.authors.all()):%0A return obj%0A raise Http404(_('No entry found matching the query'))%0A
|
|
120c93a2dd0022de5cb3a30ceffc027e69b23c3a
|
Add ProgressMonitor
|
entity_networks/monitors.py
|
entity_networks/monitors.py
|
Python
| 0
|
@@ -0,0 +1,1725 @@
+from __future__ import absolute_import%0Afrom __future__ import print_function%0Afrom __future__ import division%0A%0Aimport numpy as np%0Aimport tensorflow as tf%0A%0Afrom tqdm import tqdm%0A%0Aclass ProgressMonitor(tf.contrib.learn.monitors.EveryN):%0A%0A def __init__(self, tensor_names, every_n_steps=100, first_n_steps=1):%0A super(ProgressMonitor, self).__init__(every_n_steps, first_n_steps)%0A if not isinstance(tensor_names, dict):%0A tensor_names = %7Btensor_name: tensor_name for tensor_name in tensor_names%7D%0A self._tensor_names = tensor_names%0A self._tensor_history = %5Bnp.zeros(every_n_steps) for tensor_name in tensor_names%5D%0A self._last_step = 0%0A%0A def begin(self, max_steps=None):%0A super(ProgressMonitor, self).begin(max_steps)%0A self._progress_bar = tqdm(total=max_steps, unit='batches')%0A%0A def end(self, session=None):%0A super(ProgressMonitor, self).end(session)%0A self._progress_bar.close()%0A%0A def every_n_step_begin(self, step):%0A super(ProgressMonitor, self).every_n_step_begin(step)%0A return list(self._tensor_names.values())%0A%0A def every_n_step_end(self, step, outputs):%0A super(ProgressMonitor, self).every_n_step_end(step, outputs)%0A stats = %5B%5D%0A for (tag, tensor_name), tensor_history in zip(self._tensor_names.iteritems(), self._tensor_history):%0A tensor_history%5Bstep%25self._every_n_steps%5D = outputs%5Btensor_name%5D%0A tensor_mean = np.mean(tensor_history%5B:min(step, self._every_n_steps)%5D)%0A stats.append(%22%7B%7D: %7B:.6f%7D%22.format(tag, tensor_mean))%0A self._progress_bar.set_description(%22, %22.join(stats))%0A self._progress_bar.update(step - self._last_step)%0A self._last_step = step%0A
|
|
eec153999c3aa3dd48cd6f6a0579da61dd5f165b
|
version bump for 0.21.5.3.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.21.5.2'
|
Python
| 0
|
@@ -12,12 +12,12 @@
'0.21.5.
-2
+3
'%0A%0A
|
d9c59c8f4a3ef682db204f137292952f70e86c3c
|
version bump for 0.25.11.6.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.25.11.5'
|
Python
| 0
|
@@ -13,12 +13,12 @@
0.25.11.
-5
+6
'%0A%0A
|
fb1785179af9bd731afce3b3c4361f0e8c1cf592
|
version bump for 0.83.
|
oneflow/__init__.py
|
oneflow/__init__.py
|
VERSION = '0.82.14'
|
Python
| 0
|
@@ -12,11 +12,8 @@
'0.8
-2.14
+3
'%0A%0A
|
770ed3ea3ec2ab8d76172b85bd8b37c22517139c
|
add initial define function
|
cogs/define.py
|
cogs/define.py
|
Python
| 0.000004
|
@@ -0,0 +1,1605 @@
+import discord%0Afrom discord.ext import commands%0Afrom bs4 import BeautifulSoup%0A%0Aclass Define:%0A def __init__(self, bot):%0A self.bot = bot%0A self.aiohttp_session = bot.aiohttp_session%0A self.url = 'https://google.com/search'%0A self.headers = %7B'User-Agent':%0A 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) ' %0A 'Chrome/41.0.2228.0 Safari/537.36'%7D%0A self.parts_of_speech = %7B'noun': 'n.', 'verb': 'v.', 'adjective': 'adj.', 'adverb': 'adv.',%0A 'interjection': 'interj.', 'conjunction': 'conj.', 'preposition': 'prep.',%0A 'pronoun': 'pron.'%7D%0A self.error_cmd = bot.get_command('error')%0A%0A @commands.command(aliases=%5B'def'%5D)%0A async def define(self, ctx, word: str):%0A %22%22%22 Define a word %22%22%22%0A params = %7B'q': f'define+%7Bword%7D', 'source': 'hp'%7D%0A%0A async with self.aiohttp_session.get(self.url, params=params, headers=self.headers) as r:%0A html = await r.text()%0A%0A soup = BeautifulSoup(html, 'lxml')%0A%0A try:%0A defn = soup.find('div', attrs=%7B'data-dobid': 'dfn'%7D).span.text%0A pos = self.parts_of_speech%5Bsoup.find('div', attrs=%7B'class': 'lr_dct_sf_h'%7D).span.text%5D%0A except AttributeError:%0A print('Unable to find definition. Ensure you do not have to do a Google captcha.')%0A return await ctx.invoke(self.error_cmd, err=f'Unable to find a definition for %60%7Bword%7D%60.')%0A%0A await ctx.send(f'%7Bword%7D _%7Bpos%7D_ %7Bdefn%7D')%0A%0A%0Adef setup(bot):%0A bot.add_cog(Define(bot))%0A
|
|
fe7d8e23a6ab8d86c39ef8ede2ddafa40a7fc1fb
|
Add RIPE space lookup thread
|
irrexplorer/ripe.py
|
irrexplorer/ripe.py
|
Python
| 0
|
@@ -0,0 +1,3423 @@
+#!/usr/bin/env python%0A# Copyright (C) 2015 Job Snijders %3Cjob@instituut.net%3E%0A#%0A# This file is part of IRR Explorer%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions are met:%0A#%0A# 1. Redistributions of source code must retain the above copyright notice,%0A# this list of conditions and the following disclaimer.%0A#%0A# 2. Redistributions in binary form must reproduce the above copyright notice,%0A# this list of conditions and the following disclaimer in the documentation%0A# and/or other materials provided with the distribution.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS %22AS IS%22%0A# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE%0A# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE%0A# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE%0A# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR%0A# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF%0A# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS%0A# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN%0A# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)%0A# ARISING IN ANY WAY OUT OF THIS SOFTWARE, EVEN IF ADVISED OF THE%0A# POSSIBILITY OF SUCH DAMAGE.%0A%0Aimport radix%0Aimport time%0Aimport threading%0Aimport multiprocessing%0A%0A%0Aclass RIPELookupWorker(threading.Thread):%0A %22%22%22%0A A lookup thread specific to the BGP data, might be good%0A to merge this into the IRR lookup worker at some point.%0A %22%22%22%0A%0A def __init__(self, tree, prefixes, lookup_queue, result_queue):%0A threading.Thread.__init__(self)%0A self.tree = tree%0A self.prefixes = prefixes%0A self.lookup_queue = lookup_queue%0A self.result_queue = result_queue%0A #FIXME shipping with hardcoded data is not the nicest approach%0A for prefix in open('data/ripe-managed-space.txt').readlines():%0A self.tree.add(prefix.strip())%0A self.prefixes.append(prefix.strip())%0A%0A def run(self):%0A while True:%0A lookup, target = self.lookup_queue.get()%0A if not lookup:%0A continue%0A if lookup == %22is_covered%22:%0A result = self.tree.search_worst(target).prefix%0A self.result_queue.put(result)%0A%0A self.lookup_queue.task_done()%0A%0A%0Aclass RIPEWorker(multiprocessing.Process):%0A %22%22%22%0A FIXME: dynamically fetch & update the RIPE managed tree%0A %22%22%22%0A def __init__(self, lookup_queue, result_queue):%0A multiprocessing.Process.__init__(self)%0A self.lookup_queue = lookup_queue%0A self.result_queue = result_queue%0A self.tree = radix.Radix()%0A self.prefixes = %5B%5D%0A self.dbname = %22RIPE-AUTH%22%0A self.lookup = RIPELookupWorker(self.tree, self.prefixes,%0A self.lookup_queue, self.result_queue)%0A self.lookup.setDaemon(True)%0A self.lookup.start()%0A%0A def run(self):%0A print %22info: loaded the tree%22%0A%0Aif __name__ == %22__main__%22:%0A lookup_queue = multiprocessing.JoinableQueue()%0A result_queue = multiprocessing.JoinableQueue()%0A%0A a = RIPEWorker(lookup_queue, result_queue)%0A a.start()%0A time.sleep(1)%0A lookup_queue.put((%22is_covered%22, %22194.33.96.0/24%22))%0A lookup_queue.join()%0A print result_queue.get()%0A
|
|
a91386a802d3346c945e107aa3abd6aa5fcfe0d7
|
Solve double base palindrome
|
project_euler/036.double_palindromes.py
|
project_euler/036.double_palindromes.py
|
Python
| 0.999999
|
@@ -0,0 +1,761 @@
+'''%0AProblem 036%0A%0AThe decimal number, 585 = 10010010012 (binary), is palindromic in both bases.%0A%0AFind the sum of all numbers, less than one million, which are palindromic in %0A base 10 and base 2.%0A%0A(Please note that the palindromic number, in either base, may not include %0A leading zeros.)%0A%0A%0ASolution: Copyright 2017 Dave Cuthbert, MIT License%0A'''%0Adef is_palindrome(number):%0A if str(number) == str(number)%5B::-1%5D:%0A return True%0A%0A return False%0A%0A%0Adef solve_problem(limit):%0A palindromes = %5B%5D%0A%0A for n in range(1, limit):%0A if is_palindrome(n):%0A if is_palindrome(format(n, 'b')):%0A palindromes.append(n)%0A%0A%0A return(sum(palindromes))%0A%0A%0Aif __name__ == %22__main__%22:%0A limit = 1000000%0A print(solve_problem(limit))%0A
|
|
3096af347f1cda453eb48f7002371a49b389c568
|
use keep_lazy if available
|
django_extensions/utils/text.py
|
django_extensions/utils/text.py
|
# -*- coding: utf-8 -*-
import six
from django.utils.encoding import force_text
from django.utils.functional import allow_lazy
def truncate_letters(s, num):
"""
truncates a string to a number of letters, similar to truncate_words
"""
s = force_text(s)
length = int(num)
if len(s) > length:
s = s[:length]
if not s.endswith('...'):
s += '...'
return s
truncate_letters = allow_lazy(truncate_letters, six.text_type)
|
Python
| 0.000001
|
@@ -73,16 +73,116 @@
ce_text%0A
+try:%0A from django.utils.functional import keep_lazy%0A KEEP_LAZY = True%0Aexcept ImportError:%0A
from dja
@@ -220,16 +220,38 @@
ow_lazy%0A
+ KEEP_LAZY = False%0A
%0A%0Adef tr
@@ -526,16 +526,106 @@
urn s%0A%0A%0A
+if KEEP_LAZY:%0A truncate_letters = keep_lazy(six.text_type)(truncate_letters)%0Aelse:%0A
truncate
|
005c9d1a51793fe76c798be2f546552bb2ee2088
|
add word graph boilerplate code
|
graphs/wordgraph.py
|
graphs/wordgraph.py
|
Python
| 0.000096
|
@@ -0,0 +1,546 @@
+def gml2adjlist(G):%0A %22%22%22%0A Return a dict mapping word to adjacent nodes. G.node dict in memory%0A looks like:%0A%0A %7B0: %7B'id': 0, 'value': 0, 'label': 'agreeable'%7D,%0A 1: %7B'id': 1, 'value': 1, 'label': 'man'%7D, ... %7D%0A%0A and G.edge dict looks like:%0A%0A %7B0: %7B1: %7B%7D, 2: %7B%7D, 3: %7B%7D%7D, 1: %7B0: %7B%7D, 19: %7B%7D, 2: %7B%7D, 102: %7B%7D, ...%7D, ...%7D%0A%0A and we need:%0A%0A %7Bagreeable:%5B'man', 'old', 'person'%5D, man:%5B%5B'agreeable', 'best', 'old', ...%5D, ...%7D%0A %22%22%22%0A words = collections.OrderedDict() # keep stuff in order read from GML%0A ...%0A return words%0A
|
|
7c10150d5e667921450e8663fa9440253a495160
|
Add migration for moving recomended articles recomended section
|
gem/migrations/0014_convert_recomended_articles.py
|
gem/migrations/0014_convert_recomended_articles.py
|
Python
| 0
|
@@ -0,0 +1,2319 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0Afrom molo.core.models import ArticlePage, ArticlePageRecommendedSections%0Afrom wagtail.wagtailcore.blocks import StreamValue%0A%0A%0Adef create_recomended_articles(main_article, article_list):%0A '''%0A Creates recommended article objects from article_list%0A and _prepends_ to existing recommended articles.%0A '''%0A existing_recommended_articles = %5B%0A ra.recommended_article.specific%0A for ra in main_article.recommended_articles.all()%5D%0A ArticlePageRecommendedSections.objects.filter(page=main_article).delete()%0A%0A for hyperlinked_article in article_list:%0A ArticlePageRecommendedSections(%0A page=main_article,%0A recommended_article=hyperlinked_article).save()%0A%0A # re-create existing recommended articles%0A for article in existing_recommended_articles:%0A if article not in article_list:%0A ArticlePageRecommendedSections(%0A page=main_article,%0A recommended_article=article).save()%0A%0A%0Adef convert_articles(apps, schema_editor):%0A '''%0A Derived from https://github.com/wagtail/wagtail/issues/2110%0A '''%0A articles = ArticlePage.objects.all().exact_type(ArticlePage)%0A%0A for article in articles:%0A stream_data = %5B%5D%0A linked_articles = %5B%5D%0A for block in article.body.stream_data:%0A if block%5B'type'%5D == 'page':%0A if ArticlePage.objects.filter(id=block%5B'value'%5D):%0A linked_articles.append(ArticlePage.objects.get(%0A id=block%5B'value'%5D))%0A else:%0A # add block to new stream_data%0A stream_data.append(block)%0A%0A if linked_articles:%0A create_recomended_articles(article, linked_articles)%0A%0A stream_block = article.body.stream_block%0A article.body = StreamValue(stream_block, stream_data, is_lazy=True)%0A article.save()%0A section = article.get_parent().specific%0A section.enable_recommended_section = True%0A section.enable_next_section = True%0A section.save()%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('gem', '0013_gemsettings_moderator_name'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(convert_articles),%0A %5D%0A
|
|
909f2c9739429ea3e6954a829e0776d84714d4fd
|
Add migration
|
holonet/core/migrations/0007_auto_20150324_1049.py
|
holonet/core/migrations/0007_auto_20150324_1049.py
|
Python
| 0.000002
|
@@ -0,0 +1,476 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('core', '0006_auto_20150324_0035'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='user',%0A name='sasl_token',%0A field=models.CharField(max_length=32, verbose_name='SASL Token', unique=True),%0A preserve_default=True,%0A ),%0A %5D%0A
|
|
abd05378eb6acf742f2deff4228a0bca4492521b
|
Add example showing scraping/parsing of an HTML table into a Python dict
|
examples/htmlTableParser.py
|
examples/htmlTableParser.py
|
Python
| 0.000001
|
@@ -0,0 +1,2113 @@
+#%0A# htmlTableParser.py%0A#%0A# Example of parsing a simple HTML table into a list of rows, and optionally into a little database%0A#%0A# Copyright 2019, Paul McGuire%0A#%0A%0Aimport pyparsing as pp%0Aimport urllib.request%0A%0A%0A# define basic HTML tags, and compose into a Table%0Atable, table_end = pp.makeHTMLTags('table')%0Athead, thead_end = pp.makeHTMLTags('thead')%0Atbody, tbody_end = pp.makeHTMLTags('tbody')%0Atr, tr_end = pp.makeHTMLTags('tr')%0Ath, th_end = pp.makeHTMLTags('th')%0Atd, td_end = pp.makeHTMLTags('td')%0Aa, a_end = pp.makeHTMLTags('a')%0A%0A# method to strip HTML tags from a string - will be used to clean up content of table cells%0Astrip_html = (pp.anyOpenTag %7C pp.anyCloseTag).suppress().transformString%0A%0A# expression for parsing %3Ca href=%22url%22%3Etext%3C/a%3E links, returning a (text, url) tuple%0Alink = pp.Group(a + pp.SkipTo(a_end)('text') + a_end.suppress())%0Alink.addParseAction(lambda t: (t%5B0%5D.text, t%5B0%5D.href))%0A%0A# method to create table rows of header and data tags%0Adef table_row(start_tag, end_tag):%0A body = pp.SkipTo(end_tag)%0A body.addParseAction(pp.tokenMap(str.strip),%0A pp.tokenMap(strip_html))%0A row = pp.Group(tr.suppress()%0A + pp.ZeroOrMore(start_tag.suppress()%0A + body%0A + end_tag.suppress())%0A + tr_end.suppress())%0A return row%0A%0Ath_row = table_row(th, th_end)%0Atd_row = table_row(td, td_end)%0A%0A# define expression for overall table - may vary slightly for different pages%0Ahtml_table = table + tbody + pp.Optional(th_row('headers')) + pp.ZeroOrMore(td_row)('rows') + tbody_end + table_end%0A%0A%0A# read in a web page containing an interesting HTML table%0Awith urllib.request.urlopen(%22https://en.wikipedia.org/wiki/List_of_tz_database_time_zones%22) as page:%0A page_html = page.read().decode()%0A%0Atz_table = html_table.searchString(page_html)%5B0%5D%0A%0A# convert rows to dicts%0Arows = %5Bdict(zip(tz_table.headers, row)) for row in tz_table.rows%5D%0A%0A# make a dict keyed by TZ database name%0Atz_db = %7Brow%5B'TZ database name'%5D: row for row in rows%7D%0A%0Afrom pprint import pprint%0Apprint(tz_db%5B'America/Chicago'%5D)%0A
|
|
5aeb0e41621eeb397ea16aff22d7f4deaf8fa7a2
|
Add python play example
|
examples/python/play-url.py
|
examples/python/play-url.py
|
Python
| 0.000022
|
@@ -0,0 +1,1107 @@
+#!/usr/bin/env python%0A%0Afrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer%0Aimport urlparse%0Aimport logging%0Afrom xml.dom.minidom import Document%0A%0Alogging.basicConfig(level=logging.DEBUG)%0A%0Aclass MegaAwesomePythonServer(BaseHTTPRequestHandler):%0A%0A def do_POST(self):%0A length = int(self.headers.getheader('Content-Length'))%0A data = urlparse.parse_qs(self.rfile.read(length))%0A%0A logging.debug(%22from: %22 + data.get(%22from%22)%5B0%5D)%0A logging.debug(%22to: %22 + data.get(%22to%22)%5B0%5D)%0A%0A doc = Document()%0A response = doc.createElement('Response')%0A play = doc.createElement('Play')%0A url = doc.createElement('Url')%0A urlString = doc.createTextNode('http://www.example.com/example.wav')%0A url.appendChild(urlString)%0A play.appendChild(url)%0A response.appendChild(play)%0A doc.appendChild(response)%0A%0A self.send_response(200)%0A self.send_header('Content-Type', 'application/xml')%0A self.end_headers()%0A self.wfile.write(doc.toxml())%0A%0A%0Aserver = HTTPServer(('', 3000), MegaAwesomePythonServer)%0Aserver.serve_forever()%0A
|
|
c1f3bb8b3bc3a6685cd839df92a035298ecea2b9
|
Create compoundword.py
|
compoundword.py
|
compoundword.py
|
Python
| 0.000249
|
@@ -0,0 +1,1823 @@
+import random%0Adic1 = %5B%22life%22, %22moon%22, %22butter%22, %22fire%22, %22basket%22, %22foot%22, %22weather%22, %22earth%22, %22play%22, %22super%22, %22grand%22, %22rattle%22, %22skate%22, %22grass%22, %22eye%22, %22honey%22, %22dish%22, %22pop%22, %22book%22, %22thunder%22, %22head%22, %22glass%22, %22boot%22, %22air%22, %22baby%22, %22ham%22, %22common%22, %22sea%22, %22sand%22, %22river%22, %22tooth%22, %22town%22, %22sauce%22, %22disk%22, %22horse%22, %22rain%22, %22stone%22%5D # - week, no, north, up, down, more, along, cross, some, back, home, every, what, long, school, watch, key, under, south, any, life, black, wide, rail%0Adic2 = %5B%22guard%22, %22walk%22, %22time%22, %22light%22, %22body%22, %22flies%22, %22thing%22, %22ball%22, %22man%22, %22quake%22, %22stream%22, %22day%22, %22bone%22, %22giant%22, %22goat%22, %22mother%22, %22flower%22, %22structure%22, %22snake%22, %22board%22, %22house%22, %22hopper%22, %22made%22, %22smith%22, %22moon%22, %22washer%22, %22corn%22, %22case%22, %22fish%22, %22storm%22, %22town%22, %22maker%22, %22making%22, %22plane%22, %22sitter%22, %22person%22, %22ship%22, %22dew%22, %22drive%22, %22paste%22, %22keeper%22, %22check%22, %22woman%22,%22watch%22, %22fighter%22%5D#-ever, self, place, pan, back, down, way, shore, pick, noon, end, stone, ground, drive, road, strap%0AgoodWords = set()%0Aend = %22Maybe another time then%22%0Aprint (%22Want to know my favorite word?%22)%0Adef ask():%0A ans = input('y/n: ')%0A if ans == 'y':%0A return True%0A else:%0A return False%0Aplay = ask()%0Awhile play == True :%0A corn = random.choice(dic1)%0A dog = random.choice(dic2)%0A cornDog=corn+dog%0A if len(goodWords)%3C(len(dic1)*len(dic2)):%0A while cornDog in goodWords:%0A print (%22Hold on...%22)%0A corn = random.choice(dic1)%0A dog = random.choice(dic2)%0A cornDog=corn+dog%0A goodWords.add(cornDog)%0A print ((%22%5C'%22+cornDog+%22.%5C' %22)+(cornDog+%22 %22)*random.randint(2,4)+cornDog+%22.%22)%0A print (%22Do you want to hear another excellent word?%22)%0A play = ask()%0A else:%0A end = %22There are no more! Are you happy??%22%0A play = False%0Aprint (end)%0A
|
|
b48bd670084cd1b2e443eb284813b949edbff6ca
|
Add gunicorn config
|
linky/config/gunicorn.conf.py
|
linky/config/gunicorn.conf.py
|
Python
| 0.000001
|
@@ -0,0 +1,305 @@
+import multiprocessing%0A%0Aappname = %22linky%22%0A%0Aprocname = appname%0A%0Abind = %22unix:/tmp/%25s%22 %25 appname%0Aworkers = multiprocessing.cpu_count() * 2 + 1%0Amax_requests = 1000%0Apreload_app = True%0A%0Aaccesslog = %22/home/webapp/apps/linky/logs/access.log%22%0Aerrorlog = %22/home/webapp/apps/linky/logs/error.log%22%0Aloglevel = %22info%22%0A
|
|
19f8cf043437d3ed0feac6ce1619636189904277
|
add get_partners.py
|
sample-code/Python/get_partners.py
|
sample-code/Python/get_partners.py
|
Python
| 0.000001
|
@@ -0,0 +1,1802 @@
+'''%0A- login and get token%0A- process 2FA if 2FA is setup for this account%0A- returns all user types if user is a partner admin (or above) - else error%0A'''%0Aimport requests%0Aimport json%0A%0Aget_token_url = %22https://api.canopy.cloud:443/api/v1/sessions/%22%09%09%0Avalidate_otp_url = %22https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json%22 #calling the production server for OTP authentication%0Aget_partner_users_url = %22https://api.canopy.cloud:443/api/v1/admin/users.json%22%0Aget_partners_url = %22https://api.canopy.cloud:443/api/v1/admin/partners.json%22%0A%0A#please replace below with your username and password over here%0Ausername = 'login_name'%0Apassword = 'xxxxxxxxx'%0A%0A#please enter the OTP token in case it is enabled%0Aotp_code = '123456'%0A%0A%0A#first call for a fresh token%0Apayload = %22user%255Busername%255D=%22 + username + %22&user%255Bpassword%255D=%22 + password%0Aheaders = %7B%0A%09'accept': %22application/json%22,%0A%09'content-type':%22application/x-www-form-urlencoded%22%0A%09%7D%0A%0Aresponse = requests.request(%22POST%22, get_token_url, data=payload, headers=headers)%0A%0Aprint json.dumps(response.json(), indent=4, sort_keys = True)%0A%0Atoken = response.json()%5B'token'%5D%0Alogin_flow = response.json()%5B'login_flow'%5D%0A%0A#in case 2FA is enabled use the OTP code to get the second level of authentication%0Aif login_flow == '2fa_verification':%0A%09headers%5B'Authorization'%5D = token%0A%09payload = 'otp_code=' + otp_code%0A%09response = requests.request(%22POST%22, validate_otp_url, data=payload, headers=headers)%0A%09print json.dumps(response.json(), indent=4, sort_keys = True) #print response.text%0A%09token = response.json()%5B'token'%5D%0A%0Aheaders = %7B%0A 'authorization': token,%0A 'content-type': %22application/x-www-form-urlencoded; charset=UTF-8%22%0A %7D%0A%0Aresponse = requests.request(%22GET%22, get_partners_url, headers=headers)%0A%0Aprint json.dumps(response.json(), indent=4, sort_keys = True)%0A
|
|
355094293afbe0836304be495307155aea6c26a8
|
Create Brain_TTS.py
|
EmeraldAI/Application/Main/Brain_TTS.py
|
EmeraldAI/Application/Main/Brain_TTS.py
|
Python
| 0.000001
|
@@ -0,0 +1,1553 @@
+#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0Aimport sys%0Aimport os%0Aimport time%0Afrom os.path import dirname, abspath%0Asys.path.append(dirname(dirname(dirname(dirname(abspath(__file__))))))%0Areload(sys)%0Asys.setdefaultencoding('utf-8')%0A%0Aimport rospy%0Afrom std_msgs.msg import String%0A%0Afrom EmeraldAI.Logic.Modules import Pid%0Afrom EmeraldAI.Config.Config import *%0Afrom EmeraldAI.Logic.Audio.SoundMixer import *%0Afrom EmeraldAI.Logic.Memory.Brain import Brain as BrainMemory%0A%0Aclass BrainTTS:%0A def __init__(self):%0A %0A self.__audioPlayer = Config().Get(%22TextToSpeech%22, %22AudioPlayer%22) + %22 '%7B0%7D'%22%0A self.__usePygame = Config().GetBoolean(%22TextToSpeech%22, %22UsePygame%22)%0A%0A rospy.init_node(%22emerald_brain_tts_node%22, anonymous=True)%0A%0A rospy.Subscriber(%22/emerald_ai/io/text_to_speech/file%22, String, self.playAudio)%0A %0A%0A def playAudio(self, data):%0A dataParts = data.data.split(%22%7C%22)%0A%0A if dataParts%5B0%5D != %22TTS%22:%0A return%0A %0A # TODO%0A audioDuration = 0%0A%0A BrainMemory().Set(%22TTS.Until%22, (rospy.Time.now().to_sec() + audioDuration))%0A%0A if self.__usePygame:%0A SoundMixer().Play(dataParts%5B1%5D)%0A return%0A %0A os.system(self.__audioPlayer.format(dataParts%5B1%5D))%0A%0A%0A##### MAIN #####%0A%0Aif __name__ == %22__main__%22:%0A if(Pid.HasPid(%22Brain.TTS%22)):%0A print %22Process is already runnung. Bye!%22%0A sys.exit()%0A Pid.Create(%22Brain.TTS%22)%0A try:%0A BrainTTS()%0A except KeyboardInterrupt:%0A print %22End%22%0A finally:%0A Pid.Remove(%22Brain.TTS%22)%0A
|
|
99b0596f8bdef41e08ff04e53316ae8edaab29c4
|
Add loggers helper
|
pictures/loggers.py
|
pictures/loggers.py
|
Python
| 0.000001
|
@@ -0,0 +1,193 @@
+import logging%0A%0Alogging.basicConfig(level=logging.INFO,%0A format='%25(asctime)s %25(name)s %25(levelname)s %25(message)s')%0A%0A%0Adef logger_from(name):%0A return logging.getLogger(name)%0A
|
|
62fe7541fd1c9272616f9e7021617f2fb766bd93
|
add models placeholder for django
|
pillowtop/models.py
|
pillowtop/models.py
|
Python
| 0
|
@@ -0,0 +1,24 @@
+# placeholder for django
|
|
ec18575b2a80714db3d9f34e066d5a4b7525f17b
|
Remove the oneflow.core app, it's not yet in the repository.
|
oneflow/settings/snippets/common.py
|
oneflow/settings/snippets/common.py
|
# -*- coding: utf-8 -*-
# Django common settings for oneflow project.
# These are overridden in hostname.py specific files.
#
# Here we define the settings for the test platform.
# Production will override only the needed directives.
import os
# We need to go down 3 times because we start from
# `oneflow/settings/snippets/common.py` instead of plain `oneflow/settings.py`.
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
BASE_ROOT = os.path.dirname(PROJECT_ROOT)
ADMINS = (('Olivier Cortès', 'oc@1flow.net'), )
MANAGERS = ADMINS
REDIS_DB = 0
GRAPPELLI_ADMIN_TITLE = '1flow administration'
ALLOWED_HOSTS = []
TIME_ZONE = 'Europe/Paris'
LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = os.path.join(BASE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = '1!ps20!7iya1ptgluj@2u50)r!fvl*%+6qbxar2jn9y$@=eme!'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'raven.contrib.django.raven_compat.middleware.'
'SentryResponseErrorIdMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'oneflow.urls'
WSGI_APPLICATION = 'oneflow.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates')
)
INSTALLED_APPS = (
'raven.contrib.django.raven_compat',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
#'grappelli.dashboard',
'grappelli',
'django.contrib.admin',
'django.contrib.admindocs',
'south',
'redisboard',
'memcache_status',
'widget_tweaks',
'oneflow.core',
'oneflow.landing',
)
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '[contactor] %(levelname)s %(asctime)s %(message)s'
},
},
'handlers': {
# Send all messages to console
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
# Send info messages to syslog
# 'syslog':{
# 'level':'INFO',
# 'class': 'logging.handlers.SysLogHandler',
# 'facility': SysLogHandler.LOG_LOCAL2,
# 'address': '/dev/log',
# 'formatter': 'verbose',
# },
# Warning messages are sent to admin emails
'mail_admins': {
'level': 'WARNING',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
},
# critical errors are logged to sentry
'sentry': {
'level': 'ERROR',
#'filters': ['require_debug_false'],
'class': 'raven.contrib.django.handlers.SentryHandler',
},
},
'loggers': {
# This is the "catch all" logger
'': {
'handlers': ['console', 'mail_admins', 'sentry'], # 'syslog',
'level': 'DEBUG',
'propagate': False,
},
}
}
|
Python
| 0
|
@@ -2305,19 +2305,23 @@
low.
-core
+landing
',%0A
+#
'one
@@ -2325,23 +2325,20 @@
oneflow.
-landing
+core
',%0A)%0A%0ACA
|
6b60c56a3d86de80447fe2ab133db100af97f6d4
|
Task_2_17
|
BITs/2014/Shmireychik_S_V/task_2_17.py
|
BITs/2014/Shmireychik_S_V/task_2_17.py
|
Python
| 0.999959
|
@@ -0,0 +1,239 @@
+#%D0%97%D0%B0%D0%B4%D0%B0%D1%87%D0%B0 %E2%84%962. %D0%92%D0%B0%D1%80%D0%B8%D0%B0%D0%BD%D1%82 17%0D%0A#%D0%9A%D0%BE%D0%BC%D0%BF%D1%8C%D1%8E%D1%82%D0%B5%D1%80 %D0%B2%D1%8B%D0%B2%D0%BE%D0%B4%D0%B8%D1%82 %D0%BF%D0%BE%D0%BD%D1%80%D0%B0%D0%B2%D0%B8%D0%B2%D1%88%D0%B5%D0%B5%D1%81%D1%8F %D0%B2%D1%8B%D1%81%D0%BA%D0%B0%D0%B7%D1%8B%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5 %D0%90%D1%81-C%D0%B0%D0%BC%D0%B0%D1%80%D0%BA%D0%B0%D0%BD%D0%B4%D0%B8%0D%0A%0D%0A#%D0%A8%D0%BC%D0%B8%D1%80%D0%B5%D0%B9%D1%87%D0%B8%D0%BA %D0%A1.%D0%92.%0D%0A#29.02.2016%0D%0A%0D%0Aprint(%22%D0%9B%D1%8E%D0%B1%D0%BE%D0%B2%D1%8C - %D1%8D%D1%82%D0%BE %D1%82%D0%BE, %D1%87%D1%82%D0%BE %D0%B7%D0%B0%D0%BF%D1%80%D0%B5%D1%89%D0%B0%D0%B5%D1%82 %D1%81%D0%BB%D0%BE%D0%B2%D0%B0 %D0%B8 %D1%80%D0%B5%D1%87%D0%B8.%5Cn%22 + %22%5Ct%5Ct%5Ct%5Ct%5Ct %D0%90%D1%81-C%D0%B0%D0%BC%D0%B0%D1%80%D0%BA%D0%B0%D0%BD%D0%B4%D0%B8%22)%0D%0Ainput(%22%D0%9D%D0%B0%D0%B6%D0%BC%D0%B8%D1%82%D0%B5 %D0%95nter %D0%B4%D0%BB%D1%8F %D0%B2%D1%8B%D1%85%D0%BE%D0%B4%D0%B0.%22)
|
|
2ab86a15b956954f5de99db177a6a69b48677e2b
|
Add Webcam object
|
src/Webcam.py
|
src/Webcam.py
|
Python
| 0
|
@@ -0,0 +1,375 @@
+import cv%0A%0Aclass Webcam:%0A%09def __init__(self, cam=-1):%0A%09%09self.capture = None%0A%09%09self.camera_number = cam%0A%09%0A%09def __enter__(self):%0A%09%09self.open()%0A%09%09return self%0A%09%0A%09def __exit__(self):%0A%09%09self.close()%0A%09%0A%09def open()%0A%09%09self.capture = cv.CaptureFromCAM(self.camera_number)%0A%09%0A%09def close()%0A%09%09cv.ReleaseCapture(self.capture)%0A%09%0A%09def query_frame()%0A%09%09iplimage = cv.QueryFrame(self.capture)%0A%09%09
|
|
231943a950b49e46b86467991ca6e4c7b3505be0
|
update python learn - module
|
python/study/module-test.py
|
python/study/module-test.py
|
Python
| 0
|
@@ -0,0 +1,99 @@
+#module test%0A%0Aimport sys%0Aprint 'the sys argv list:'%0Afor i in sys.argv:%0A print i%0A%0Aprint sys.path%0A
|
|
18a5ade8fd72edcbca951240d4071f2a8fccaa48
|
fix content indexer's handling of the "file" command
|
addons/document/content_index.py
|
addons/document/content_index.py
|
# -*- 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 Affero 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 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 received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
import os
import tempfile
from subprocess import Popen, PIPE
class NhException(Exception):
pass
class indexer(object):
""" An indexer knows how to parse the content of some file.
Typically, one indexer should be instantiated per file
type.
Override this class to add more functionality. Note that
you should only override the Content or the File methods
that give an optimal result. """
def _getMimeTypes(self):
""" Return supported mimetypes """
return []
def _getExtensions(self):
return []
def _getDefMime(self, ext):
""" Return a mimetype for this document type, ideally the
closest to the extension ext. """
mts = self._getMimeTypes();
if len (mts):
return mts[0]
return None
def indexContent(self, content, filename=None, realfile = None):
""" Use either content or the real file, to index.
Some parsers will work better with the actual
content, others parse a file easier. Try the
optimal.
"""
res = ''
try:
if content != None:
return self._doIndexContent(content)
except NhException:
pass
if realfile != None:
try:
return self._doIndexFile(realfile)
except NhException:
pass
fp = open(realfile,'rb')
try:
content2 = fp.read()
finally:
fp.close()
# The not-handled exception may be raised here
return self._doIndexContent(content2)
# last try, with a tmp file
if content:
try:
fname,ext = filename and os.path.splitext(filename) or ('','')
fd, rfname = tempfile.mkstemp(suffix=ext)
os.write(fd, content)
os.close(fd)
res = self._doIndexFile(rfname)
os.unlink(rfname)
return res
except NhException:
pass
raise NhException('No appropriate method to index file')
def _doIndexContent(self,content):
raise NhException("Content not handled here")
def _doIndexFile(self,fpath):
raise NhException("Content not handled here")
def __repr__(self):
return "<indexer %s.%s>" %(self.__module__, self.__class__.__name__)
def mime_match(mime, mdict):
if mdict.has_key(mime):
return (mime, mdict[mime])
if '/' in mime:
mpat = mime.split('/')[0]+'/*'
if mdict.has_key(mpat):
return (mime, mdict[mpat])
return (None, None)
class contentIndex(object):
__logger = logging.getLogger('addons.document.content_index')
def __init__(self):
self.mimes = {}
self.exts = {}
def register(self, obj):
f = False
for mime in obj._getMimeTypes():
self.mimes[mime] = obj
f = True
for ext in obj._getExtensions():
self.exts[ext] = obj
f = True
if f:
self.__logger.debug('Register content indexer: %r', obj)
if not f:
raise Exception("Your indexer should at least suport a mimetype or extension")
def doIndex(self, content, filename=None, content_type=None, realfname = None, debug=False):
fobj = None
fname = None
mime = None
if content_type and self.mimes.has_key(content_type):
mime = content_type
fobj = self.mimes[content_type]
elif filename:
bname,ext = os.path.splitext(filename)
if self.exts.has_key(ext):
fobj = self.exts[ext]
mime = fobj._getDefMime(ext)
if content_type and not fobj:
mime,fobj = mime_match(content_type, self.mimes)
if not fobj:
try:
if realfname :
fname = realfname
else:
try:
bname,ext = os.path.splitext(filename or 'test.tmp')
except Exception:
bname, ext = filename, 'tmp'
fd, fname = tempfile.mkstemp(suffix=ext)
os.write(fd, content)
os.close(fd)
fp = Popen(['file','-b','--mime',fname], shell=False, stdout=PIPE).stdout
try:
result = fp.read()
finally:
fp.close()
mime2 = result.split(';')[0]
self.__logger.debug('File gave us: %s', mime2)
# Note that the temporary file still exists now.
mime,fobj = mime_match(mime2, self.mimes)
if not mime:
mime = mime2
except Exception:
self.__logger.exception('Cannot determine mime type')
try:
if fobj:
res = (mime, fobj.indexContent(content,filename,fname or realfname) )
else:
self.__logger.debug("Have no object, return (%s, None)", mime)
res = (mime, None )
except Exception:
self.__logger.exception("Could not index file %s (%s)",
filename, fname or realfname)
res = None
# If we created a tmp file, unlink it now
if not realfname and fname:
try:
os.unlink(fname)
except Exception:
self.__logger.exception("Could not unlink %s", fname)
return res
cntIndex = contentIndex()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Python
| 0.000008
|
@@ -5523,25 +5523,26 @@
-f
+po
p = Popen(%5B'
@@ -5598,15 +5598,8 @@
IPE)
-.stdout
%0A
@@ -5615,111 +5615,56 @@
-try:%0A result = fp.read()%0A finally: %0A fp.close()
+(result, _) = pop.communicate()%0A
%0A
|
6d64f88d5536ae14026556729433ea27b5eece61
|
fix content indexer, where no filename is supplied
|
addons/document/content_index.py
|
addons/document/content_index.py
|
# -*- 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 Affero 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 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 received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
import os
import tempfile
class NhException(Exception):
pass
from subprocess import Popen, PIPE
class indexer(object):
""" An indexer knows how to parse the content of some file.
Typically, one indexer should be instantiated per file
type.
Override this class to add more functionality. Note that
you should only override the Content or the File methods
that give an optimal result. """
def _getMimeTypes(self):
""" Return supported mimetypes """
return []
def _getExtensions(self):
return []
def _getDefMime(self, ext):
""" Return a mimetype for this document type, ideally the
closest to the extension ext. """
mts = self._getMimeTypes();
if len (mts):
return mts[0]
return None
def indexContent(self, content, filename=None, realfile = None):
""" Use either content or the real file, to index.
Some parsers will work better with the actual
content, others parse a file easier. Try the
optimal.
"""
res = ''
try:
if content != None:
return self._doIndexContent(content)
except NhException:
pass
if realfile != None:
try:
return self._doIndexFile(realfile)
except NhException:
pass
fp = open(realfile,'rb')
content2 = fp.read()
fp.close()
# The not-handled exception may be raised here
return self._doIndexContent(content2)
# last try, with a tmp file
if content:
try:
fname,ext = filename and os.path.splitext(filename) or ('','')
fd, rfname = tempfile.mkstemp(suffix=ext)
os.write(fd, content)
os.close(fd)
res = self._doIndexFile(rfname)
os.unlink(rfname)
return res
except NhException:
pass
raise NhException('No appropriate method to index file')
def _doIndexContent(self,content):
raise NhException("Content not handled here")
def _doIndexFile(self,fpath):
raise NhException("Content not handled here")
def mime_match(mime, mdict):
if mdict.has_key(mime):
return (mime, mdict[mime])
if '/' in mime:
mpat = mime.split('/')[0]+'/*'
if mdict.has_key(mpat):
return (mime, mdict[mpat])
return (None, None)
class contentIndex(object):
__logger = logging.getLogger('addons.document.content_index')
def __init__(self):
self.mimes = {}
self.exts = {}
def register(self, obj):
f = False
for mime in obj._getMimeTypes():
self.mimes[mime] = obj
f = True
for ext in obj._getExtensions():
self.exts[ext] = obj
f = True
if f:
self.__logger.debug('Register content indexer: %s', obj)
if not f:
raise Exception("Your indexer should at least suport a mimetype or extension")
def doIndex(self, content, filename=None, content_type=None, realfname = None, debug=False):
fobj = None
fname = None
mime = None
if content_type and self.mimes.has_key(content_type):
mime = content_type
fobj = self.mimes[content_type]
elif filename:
bname,ext = os.path.splitext(filename)
if self.exts.has_key(ext):
fobj = self.exts[ext]
mime = fobj._getDefMime(ext)
if content_type and not fobj:
mime,fobj = mime_match(content_type, self.mimes)
if not fobj:
try:
if realfname :
fname = realfname
else:
bname,ext = os.path.splitext(filename)
fd, fname = tempfile.mkstemp(suffix=ext)
os.write(fd, content)
os.close(fd)
fp = Popen(['file','-b','--mime',fname], shell=False, stdout=PIPE).stdout
result = fp.read()
fp.close()
mime2 = result.split(';')[0]
self.__logger.debug('File gave us: %s', mime2)
# Note that the temporary file still exists now.
mime,fobj = mime_match(mime2, self.mimes)
if not mime:
mime = mime2
except Exception:
self.__logger.exception('Cannot determine mime type')
try:
if fobj:
res = (mime, fobj.indexContent(content,filename,fname or realfname) )
else:
self.__logger.debug("Have no object, return (%s, None)", mime)
res = (mime, None )
except Exception:
self.__logger.exception("Could not index file %s (%s)",
filename, fname or realfname)
res = None
# If we created a tmp file, unlink it now
if not realfname and fname:
try:
os.unlink(fname)
except Exception:
self.__logger.exception("Could not unlink %s", fname)
return res
cntIndex = contentIndex()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Python
| 0.000001
|
@@ -5018,32 +5018,61 @@
else:%0A
+ try:%0A
@@ -5104,33 +5104,138 @@
plitext(filename
-)
+ or 'test.tmp')%0A except Exception:%0A bname, ext = filename, 'tmp'
%0A
|
db9b756dbf68fde9930da8ab6b4594fa3f1d361e
|
Fix cascades for RecurringEventOverride table
|
migrations/versions/175_fix_recurring_override_cascade.py
|
migrations/versions/175_fix_recurring_override_cascade.py
|
Python
| 0
|
@@ -0,0 +1,1273 @@
+%22%22%22fix recurring override cascade%0A%0ARevision ID: 6e5b154d917%0ARevises: 41f957b595fc%0ACreate Date: 2015-05-25 16:23:40.563050%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '6e5b154d917'%0Adown_revision = '4ef055945390'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Afrom sqlalchemy.sql import text%0A%0A%0Adef upgrade():%0A conn = op.get_bind()%0A conn.execute(text(%22set @@lock_wait_timeout = 20;%22))%0A conn.execute(text(%22SET FOREIGN_KEY_CHECKS=0;%22))%0A conn.execute(text(%22ALTER TABLE recurringeventoverride DROP FOREIGN KEY %22%0A %22%60recurringeventoverride_ibfk_2%60%22))%0A conn.execute(text(%22ALTER TABLE recurringeventoverride ADD CONSTRAINT recurringeventoverride_ibfk_2%22%0A %22 FOREIGN KEY (%60master_event_id%60) REFERENCES %60event%60 (%60id%60) ON DELETE CASCADE%22))%0A%0A%0Adef downgrade():%0A conn = op.get_bind()%0A conn.execute(text(%22set @@lock_wait_timeout = 20;%22))%0A conn.execute(text(%22SET FOREIGN_KEY_CHECKS=0;%22))%0A conn.execute(text(%22ALTER TABLE recurringeventoverride DROP FOREIGN KEY %22%0A %22%60recurringeventoverride_ibfk_2%60%22))%0A conn.execute(text(%22ALTER TABLE recurringeventoverride ADD CONSTRAINT recurringeventoverride_ibfk_2%22%0A %22 FOREIGN KEY (%60master_event_id%60) REFERENCES %60event%60 (%60id%60)%22))%0A
|
|
730548fe74dda462d7aac1e3c5ee8e8ba47f4371
|
Add script that extracts clips from HDF5 file.
|
scripts/extract_clips_from_hdf5_file.py
|
scripts/extract_clips_from_hdf5_file.py
|
Python
| 0
|
@@ -0,0 +1,1045 @@
+from pathlib import Path%0Aimport wave%0A%0Aimport h5py%0A%0A%0ADIR_PATH = Path('/Users/harold/Desktop/Clips')%0AINPUT_FILE_PATH = DIR_PATH / 'Clips.h5'%0ACLIP_COUNT = 5%0A%0A%0Adef main():%0A%0A with h5py.File(INPUT_FILE_PATH, 'r') as file_:%0A%0A clip_group = file_%5B'clips'%5D%0A%0A for i, clip_id in enumerate(clip_group):%0A%0A if i == CLIP_COUNT:%0A break%0A%0A samples, sample_rate = read_clip(clip_group, clip_id)%0A%0A print(clip_id, len(samples), samples.dtype, sample_rate)%0A%0A write_wave_file(clip_id, samples, sample_rate)%0A%0A%0Adef read_clip(clip_group, clip_id):%0A clip = clip_group%5Bclip_id%5D%0A samples = clip%5B:%5D%0A sample_rate = clip.attrs%5B'sample_rate'%5D%0A return samples, sample_rate%0A%0A%0Adef write_wave_file(i, samples, sample_rate):%0A file_name = f'%7Bi%7D.wav'%0A file_path = DIR_PATH / file_name%0A with wave.open(str(file_path), 'wb') as file_:%0A file_.setparams((1, 2, sample_rate, len(samples), 'NONE', ''))%0A file_.writeframes(samples.tobytes())%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
d5aa5aa96aad03b1bd32504b1c9d0a87c1a1c796
|
Create y=Wx+b.py
|
y=Wx+b.py
|
y=Wx+b.py
|
Python
| 0.000476
|
@@ -0,0 +1,531 @@
+import tensorflow as tf%0Aimport numpy as np%0A%0Ax_data = np.random.rand(100).astype(%22float32%22)%0Ay_data = x_data * .1 +.3%0AW = tf.Variable(tf.random_uniform(%5B1%5D, -1.0, 1.0 ))%0Ab = tf.Variable(tf.zeros(%5B1%5D))%0Ay = W * x_data + b%0A%0Aloss = tf.reduce_mean(tf.square(y - y_data ))%0Aoptimizer = tf.train.GradientDescentOptimizer(0.5)%0Atrain = optimizer.minimize(loss)%0A%0Ainit = tf.initialize_all_variables()%0A%0Asess = tf.Session()%0Asess.run(init)%0A%0Afor step in xrange(201):%0A sess.run(train)%0A if step %25 20 == 0:%0A print (step, sess.run(W), sess.run(b))%0A
|
|
a570730af71e3263af2f265a1730db3f808cd201
|
Add ex_add_noise.py
|
Python_3/Miscellaneous/ex_addnoise.py
|
Python_3/Miscellaneous/ex_addnoise.py
|
Python
| 0.00002
|
@@ -0,0 +1,1595 @@
+# Add gaussian noise to an input%0A#%0A# Copyright (C) 2016 Wayne Mogg All rights reserved.%0A#%0A# This file may be used under the terms of the MIT License%0A# (https://github.com/waynegm/OpendTect-External-Attributes/blob/master/LICENSE)%0A#%0A# Author:%09%09Wayne Mogg%0A# Date: %09%09September, 2016%0A# Homepage:%09%09http://waynegm.github.io/OpendTect-Plugin-Docs/External_Attributes/ExternalAttributes/%0A#%0A# Input: Single trace seismic data%0A# Output: Seismic data with added gaussian noise%0A#%0Aimport sys,os%0Aimport numpy as np%0A#%0A# Import the module with the I/O scaffolding of the External Attribute%0A#%0Asys.path.insert(0, os.path.join(sys.path%5B0%5D, '..'))%0Aimport extattrib as xa%0A#%0A# The attribute parameters%0A#%0Axa.params = %7B%0A%09'Inputs': %5B'Input'%5D,%0A%09'ZSampMargin' : %7B'Value': %5B-5,5%5D, 'Hidden': True, 'Symmetric': True%7D,%0A%09'Par_0' : %7B'Name': 'S/N Ratio', 'Value': 1%7D,%0A%09'Parallel' : True,%0A%09'Help' : 'http://waynegm.github.io/OpendTect-Plugin-Docs/Attributes/ExternalAttrib/'%0A%7D%0A#%0A# Define the compute function%0A#%0Adef doCompute():%0A#%0A#%09Initialise some constants from the attribute parameters %0A#%0A%09zw = xa.params%5B'ZSampMargin'%5D%5B'Value'%5D%5B1%5D - xa.params%5B'ZSampMargin'%5D%5B'Value'%5D%5B0%5D + 1%0A#%0A#%09This is the trace processing loop%0A#%0A%09while True:%0A%09%09xa.doInput()%0A%09%09data = xa.Input%5B'Input'%5D%5B0,0,:%5D%0A#%0A# Compute noise%0A#%0A%09%09vardata = np.var(data)%0A%09%09noise = np.random.randn(data.shape%5B-1%5D)%0A%09%09varnoise = np.var(noise)%0A%09%09scale = vardata/(varnoise*xa.params%5B'Par_0'%5D%5B'Value'%5D)%0A#%0A#%09Output%0A#%0A%09%09xa.Output = data + scale*noise%0A%09%09xa.doOutput()%0A#%0A# Assign the compute function to the attribute%0A#%0Axa.doCompute = doCompute%0A#%0A# Do it%0A#%0Axa.run(sys.argv%5B1:%5D)%0A %0A%0A
|
|
b72a4bb06fda18ebca91649808cd2f2c531b392e
|
Set all events to show banner text
|
migrations/versions/0060.py
|
migrations/versions/0060.py
|
Python
| 0.000003
|
@@ -0,0 +1,398 @@
+%22%22%22empty message%0A%0ARevision ID: 0060 set all show_banner_text%0ARevises: 0059 add show_banner_text%0ACreate Date: 2021-10-03 00:31:22.285217%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '0060 set all show_banner_text'%0Adown_revision = '0059 add show_banner_text'%0A%0Afrom alembic import op%0A%0A%0Adef upgrade():%0A op.execute(%22UPDATE events SET show_banner_text = True%22)%0A%0Adef downgrade():%0A pass%0A
|
|
9132678df072e0c11685aea21c04410fe699ce4f
|
Create Majority_Element.py
|
Array/Majority_Element.py
|
Array/Majority_Element.py
|
Python
| 0.000001
|
@@ -0,0 +1,611 @@
+'''%0AGiven an array of size n, find the majority element. The majority element is the element that appears more than %E2%8C%8A n/2 %E2%8C%8B times.%0A%0AYou may assume that the array is non-empty and the majority element always exist in the array.%0A'''%0A%0Aclass Solution:%0A # @param %7Binteger%5B%5D%7D nums%0A # @return %7Binteger%7D%0A def majorityElement(self, nums):%0A count = 0%0A result = 0%0A for num in nums:%0A if count == 0:%0A result = num%0A count += 1%0A elif result == num:%0A count += 1%0A else:%0A count -= 1%0A return result %0A
|
|
4b1ac6217d054bd2fe8e5e6b4cfe036e2a4d0360
|
Add a template of setup.py.
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,809 @@
+from setuptools import setup, find_packages%0Aimport os%0A%0Aversion = '0.1'%0A%0Asetup(name='flask-boilerplate',%0A version=version,%0A description='',%0A long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),%0A classifiers=%5B%0A %5D, # Get strings from http://pypi.python.org/pypi?%253Aaction=list_classifiers%0A keywords='Flask PasteScript',%0A author='Tatsuro Fujii',%0A author_email='fujiistorage@gmail.com',%0A url='https://github.com/FGtatsuro/flask-boilerplate',%0A license='MIT',%0A packages=find_packages(exclude=%5B'ez_setup', 'examples', 'tests'%5D),%0A include_package_data=True,%0A zip_safe=False,%0A install_requires=%5B%0A # -*- Extra requirements: -*-%0A %5D,%0A entry_points=%22%22%22%0A # -*- Entry points: -*-%0A %22%22%22,%0A )%0A
|
|
b1f689f82bbb6d26511b6a310be798dad1791fc5
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,295 @@
+from distutils.core import setup%0Asetup(%0Aversion='0.10',%0Aname=%22saf%22,%0Adescription=%22Python toolkit for handling Simple Annotation Framework files%22,%0Aauthor=%22Wouter van Atteveldt%22,%0Aauthor_email=%22wouter@vanatteveldt.com%22,%0Apackages=%5B%22saf%22%5D,%0Aclassifiers=%5B%0A%22License :: OSI Approved :: MIT License%22,%0A%5D,%0A)%0A
|
|
682d65f8ccf142224912daf8acfc102fc78ea78b
|
version bump and regen
|
src/robot/version.py
|
src/robot/version.py
|
# Automatically generated by 'package.py' script.
import sys
VERSION = 'trunk'
RELEASE = '20110222'
TIMESTAMP = '20110222-203831'
def get_version(sep=' '):
if RELEASE == 'final':
return VERSION
return VERSION + sep + RELEASE
def get_full_version(who=''):
sys_version = sys.version.split()[0]
version = '%s %s (%s %s on %s)' \
% (who, get_version(), _get_interpreter(), sys_version, sys.platform)
return version.strip()
def _get_interpreter():
if sys.platform.startswith('java'):
return 'Jython'
if sys.platform == 'cli':
return 'IronPython'
return 'Python'
|
Python
| 0
|
@@ -90,19 +90,19 @@
= '20110
-222
+316
'%0ATIMEST
@@ -117,18 +117,18 @@
0110
-222-203831
+316-133752
'%0A%0Ad
|
e37dae306f2dcf17e95a988b332c064fde11fb1a
|
Create setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,305 @@
+from setuptools import setup%0A%0Asetup(name='rakolighting',%0A version='0.1',%0A description='rakolighting library',%0A url='https://github.com/chrisdpa/rakolighting',%0A author='chrisdpa',%0A author_email='unknown',%0A license='MIT',%0A packages=%5B'rakolighting'%5D,%0A zip_safe=False)%0A
|
|
e1c35ee11d281692f916ebf57b38390b90501304
|
Create texted.py
|
exercises/text-editor/texted.py
|
exercises/text-editor/texted.py
|
Python
| 0.000002
|
@@ -0,0 +1,2422 @@
+import Tkinter as Tk%0Aimport tkFileDialog%0A%0A%0A# Text Editor Skeleton%0A%0Adef on_new():%0A # reset path and delete all text in the text box%0A print %22Not implemented%22%0A%0A%0Adef on_open():%0A # let user choose what file to open from a dialog (tkFileDialog)%0A # replace text in text box with text from file%0A # handle cancelling of the dialog responsibely%0A print %22Not implemented%22%0A%0A%0Adef on_save():%0A # mimic common %22save%22 behavior%0A # if the path is already set, save the file using save_file(), otherwise:%0A # let user choose a file to save the content in the text box to (tkFileDialog)%0A # make sure the path is valid (not empty), save the file using save_file()%0A print %22Not implemented%22%0A%0A%0Adef on_save_as():%0A # mimic common %22save as%22 behavior%0A # almost the same as on_save(), difference: this always opens a file dialog%0A print %22Not implemented%22%0A%0A%0Adef get_all_text():%0A # returns all text in the text box%0A # should be one line of code%0A # not neccessary but may make the code in other places nicer%0A print %22Not implemented%22%0A%0A%0Adef delete_all_text():%0A # deletes all text in the text box%0A # should be one line of code%0A # not neccessary but may make the code in other places nicer%0A print %22Not implemented%22%0A%0A%0Adef save_file(save_path, text):%0A # open file in save_path in write mode%0A # write the text to the file%0A # close the file%0A print %22Not implemented%22%0A%0A%0Adef read_file(file_path):%0A # open file in file_path%0A # return the text%0A print %22Not implemented%22%0A%0A%0A# Initialize application%0Aapp = Tk.Tk()%0Aapp.title(%22Your Title Here%22)%0A# Sets the geometry on the form widthxheight+x_pos+y_pos%0Aapp.geometry(%22200x300+300+300%22)%0A%0A# Save path, empty until file is opened or saved%0A# Used to mimic common file saving/opening behavior%0Apath = ''%0A%0A######################################################%0A# IMPLEMENT UI HERE%0A######################################################%0A%0A# MENU BAR EXAMPLE%0Amenu_bar = Tk.Menu()%0A# Set menu bar as menu for the app%0Aapp.config(menu=menu_bar)%0A# Fill menubar with %22File%22 menu%0Afilemenu = Tk.Menu(menu_bar, tearoff=0)%0Afilemenu.add_command(label=%22Exit%22, command=quit)%0Amenu_bar.add_cascade(label=%22File%22, menu=filemenu)%0A%0A# BUTTON EXAMPLE%0Abutton = Tk.Button(app, text=%22Exit%22, command=quit)%0Abutton.pack(side=Tk.BOTTOM, fill=Tk.X)%0A%0A%0A######################################################%0A%0A# Start the main event loop (i.e. run the tkinter program)%0Aapp.mainloop()%0A
|
|
d2cbe26e14e23a4482e54a74da1412c5c0c28500
|
Update package info
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name = 'fileloader',
packages = ['fileloader'],
version = '0.1',
description = 'Downloading files (support http and ftp protocols, cachinhg, allows accessing remote and local files in uniform way',
author = 'napuzba',
author_email = 'kobi@napuzba.com',
url = 'https://github.com/napuzba/FileLoader.git',
download_url = 'https://github.com/napuzba/FileLoader/archive/0.1.zip',
keywords = ['download','ftp','http'],
classifiers = [],
)
|
Python
| 0
|
@@ -152,39 +152,27 @@
es (
-support http and ftp protocols,
+http,ftp). Supports
cac
@@ -180,17 +180,20 @@
inhg
-,
+ and
allows
acce
@@ -192,17 +192,25 @@
ows
+uniform
access
-ing
+ to
rem
@@ -232,23 +232,8 @@
iles
- in uniform way
',%0D%0A
@@ -388,29 +388,29 @@
com/napuzba/
-FileL
+filel
oader/archiv
|
d6ccfdf365b8df4eefcbe1131dd8b19d184b0fa4
|
add monkey patch test for convert command.
|
bento/commands/tests/test_convert.py
|
bento/commands/tests/test_convert.py
|
Python
| 0
|
@@ -0,0 +1,451 @@
+import sys%0A%0Afrom bento.misc.testing %5C%0A import %5C%0A SubprocessTestCase%0A%0Afrom bento.commands.convert %5C%0A import %5C%0A monkey_patch%0A%0Aclass TestMonkeyPath(SubprocessTestCase):%0A def test_distutils(self):%0A monkey_patch(%22distutils%22, %22setup.py%22)%0A self.assertTrue(%22setuptools%22 not in sys.modules)%0A%0A def test_setuptools(self):%0A monkey_patch(%22setuptools%22, %22setup.py%22)%0A self.assertTrue(%22setuptools%22 in sys.modules)%0A
|
|
082c48bcd747c096abd0cd2970edb8cbb0f3d20b
|
Add contribution admin
|
features/contributions/admin.py
|
features/contributions/admin.py
|
Python
| 0
|
@@ -0,0 +1,96 @@
+from django.contrib import admin%0Afrom . import models%0A%0Aadmin.site.register(models.Contribution)%0A
|
|
24c54c1b5ed1c91d5e1aa24bf8ca6fca1cdbf6b8
|
create entry before referencing it in test mode
|
flexget/plugins/input/sonarr.py
|
flexget/plugins/input/sonarr.py
|
from __future__ import unicode_literals, division, absolute_import
from urlparse import urlparse
import logging
from requests import RequestException
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
log = logging.getLogger('sonarr')
class Sonarr(object):
schema = {
'type': 'object',
'properties': {
'base_url': {'type': 'string'},
'port': {'type': 'number', 'default': 80},
'api_key': {'type': 'string'},
'include_ended': {'type': 'boolean', 'default': True},
'only_monitored': {'type': 'boolean', 'default': True},
'include_data': {'type': 'boolean', 'default': False}
},
'required': ['api_key', 'base_url'],
'additionalProperties': False
}
def on_task_input(self, task, config):
"""
This plugin returns ALL of the shows monitored by Sonarr.
Return ended shows by default and does not return unmonitored
show by default.
Syntax:
sonarr:
base_url=<value>
port=<value>
api_key=<value>
include_ended=<yes|no>
only_monitored=<yes|no>
include_data=<yes|no>
Options base_url and api_key are required.
Use with input plugin like discover and/or cofnigure_series.
Example:
download-tv-task:
configure_series:
settings:
quality:
- 720p
from:
sonarr:
base_url: http://localhost
port: 8989
api_key: MYAPIKEY1123
discover:
what:
- emit_series: yes
from:
torrentz: any
download:
/download/tv
Note that when using the configure_series plugin with Sonarr
you are basically synced to it, so removing a show in Sonarr will
remove it in flexget as well,which good be positive or negative,
depending on your usage.
"""
parsedurl = urlparse(config.get('base_url'))
url = '%s://%s:%s%s/api/series' % (parsedurl.scheme, parsedurl.netloc, config.get('port'), parsedurl.path)
headers = {'X-Api-Key': config['api_key']}
try:
json = task.requests.get(url, headers=headers).json()
except RequestException as e:
raise plugin.PluginError('Unable to connect to Sonarr at %s://%s:%s%s. Error: %s'
% (parsedurl.scheme, parsedurl.netloc, config.get('port'),
parsedurl.path, e))
entries = []
# Dictionary based on Sonarr's quality list.
qualities = {0: '',
1: 'sdtv',
2: 'dvdrip',
3: '1080p webdl',
4: '720p hdtv',
5: '720p webdl',
6: '720p bluray',
7: '1080p bluray',
8: '480p webdl',
9: '1080p hdtv',
10: '1080p bluray'}
# Retrieves Sonarr's profile list if include_data is set to true
if config.get('include_data'):
url2 = '%s://%s:%s%s/api/profile' % (parsedurl.scheme, parsedurl.netloc, config.get('port'), parsedurl.path)
try:
profiles_json = task.requests.get(url2, headers=headers).json()
except RequestException as e:
raise plugin.PluginError('Unable to connect to Sonarr at %s://%s:%s%s. Error: %s'
% (parsedurl.scheme, parsedurl.netloc, config.get('port'),
parsedurl.path, e))
for show in json:
fg_quality = '' # Initializes the quality parameter
if show['monitored'] or not config.get('only_monitored'): # Checks if to retrieve just monitored shows
if config.get('include_ended') or show['status'] != 'ended': # Checks if to retrieve ended shows
if config.get('include_data'): # Check if to retrieve quality & path
for profile in profiles_json:
if profile['id'] == show['profileId']: # Get show's profile data from all possible profiles
current_profile = profile
fg_quality = qualities[current_profile['cutoff']['id']] # Sets profile cutoff quality as show's quality
entry = Entry(title=show['title'],
url='',
series_name=show['title'],
tvdb_id=show['tvdbId'],
tvrage_id=show['tvRageId'],
# configure_series plugin requires that all settings will have the configure_series prefix
configure_series_quality=fg_quality)
if entry.isvalid():
entries.append(entry)
else:
log.error('Invalid entry created? %s' % entry)
# Test mode logging
if task.options.test:
log.info("Test mode. Entry includes:")
log.info(" Title: %s" % entry["title"])
log.info(" URL: %s" % entry["url"])
log.info(" Show name: %s" % entry["series_name"])
log.info(" TVDB ID: %s" % entry["tvdb_id"])
log.info(" TVRAGE ID: %s" % entry["tvrage_id"])
log.info(" Quality: %s" % entry["configure_series_quality"])
continue
return entries
@event('plugin.register')
def register_plugin():
plugin.register(Sonarr, 'sonarr', api_ver=2)
|
Python
| 0
|
@@ -3854,16 +3854,41 @@
rameter%0A
+ entry = None%0A
@@ -5269,16 +5269,26 @@
if
+entry and
task.opt
@@ -5297,17 +5297,16 @@
ns.test:
-
%0A
@@ -5753,24 +5753,26 @@
%0A
+ #
continue%0A
|
65f903a1de88cee2fdd6fe16cf86aceee3545d7b
|
Add example
|
flexx/ui/examples/serve_data.py
|
flexx/ui/examples/serve_data.py
|
Python
| 0.000003
|
@@ -0,0 +1,2219 @@
+%22%22%22%0AThis example demonstrates how data can be provided to the client with the%0AFlexx asset management system.%0A%0AThere are two ways to provide data: via the asset store (%60%60app.assets%60%60),%0Aand via the session (%60%60some_model.session%60%60). In the former, the data%0Ais shared between sessions. In the latter, the data is specific for the%0Asession (the link to the data includes the session id).%0A%0ANote that %60%60add_shared_data()%60%60 and %60%60add_data()%60%60 both return the link%0Ato the data for convenience. Shared data is always served at%0A'/_data/shared/filename.ext', so we just use that explicitly here.%0A%0ASimilarly, the data provided by the server can be obtained using Ajax%0A(i.e. XMLHttpRequest).%0A%22%22%22%0A%0Aimport random%0A%0Aimport imageio%0A%0Afrom flexx import app, event, ui%0Afrom flexx.util import png%0A%0A%0A# Define names of standard images%0Aimageio_standard_images = %5B'clock.png', 'page.png', 'camera.png', 'coins.png',%0A 'hubble_deep_field.png', 'text.png', 'chelsea.png',%0A 'coffee.png', 'horse.png', 'wikkie.png', 'moon.png',%0A 'astronaut.png', 'immunohistochemistry.png'%5D%0A%0A# Randomly select a shared image%0Afname = random.choice(imageio_standard_images)%0Aimage_data = png.write_png(imageio.imread(fname))%0Aapp.assets.add_shared_data('image.png', image_data)%0A%0A%0Aclass Example(ui.Widget):%0A %0A def init(self):%0A %0A with ui.VBox():%0A %0A # Randomly select image - different between sessions%0A fname = random.choice(imageio_standard_images)%0A image_data = png.write_png(imageio.imread(fname))%0A link = self.session.add_data('image.png', image_data)%0A %0A # Create HTML with the two images%0A html = '%3Cp%3EHit F5 to reload the page (i.e. create a new session)%3C/p%3E'%0A html += '%3Cp%3EThis is session %25s%3C/p%3E' %25 self.session.id%0A html += '%3Cimg src=%22%25s%22 /%3E' %25 %22/_data/shared/image.png%22%0A html += '%3Cimg src=%22%25s%22 /%3E' %25 link%0A %0A ui.Label(text=html)%0A%0A%0Aif __name__ == '__main__':%0A # Launch the app twice to show how different sessions have different data%0A m1 = app.launch(Example, 'browser')%0A m2 = app.launch(Example, 'browser')%0A app.run()%0A
|
|
17018750ac3ea39c4fe5a96c05db2375ecd4973e
|
Add regression test for #717
|
spacy/tests/regression/test_issue717.py
|
spacy/tests/regression/test_issue717.py
|
Python
| 0.000001
|
@@ -0,0 +1,418 @@
+# coding: utf8%0Afrom __future__ import unicode_literals%0A%0Aimport pytest%0A%0A%0A@pytest.mark.xfail%0A@pytest.mark.models%0A@pytest.mark.parametrize('text1,text2', %5B(%22You're happy%22, %22You are happy%22)%5D)%0Adef test_issue717(EN, text1, text2):%0A %22%22%22Test that contractions are assigned the correct lemma.%22%22%22%0A doc1 = EN(text1)%0A doc2 = EN(text2)%0A assert doc1%5B1%5D.lemma_ == doc2%5B1%5D.lemma_%0A assert doc1%5B1%5D.lemma == doc2%5B1%5D.lemma%0A
|
|
b7efac523bab70532dd2e703f8d4175ec22b3044
|
Add output.base unit test.
|
braubuddy/tests/outputs/test_base.py
|
braubuddy/tests/outputs/test_base.py
|
Python
| 0.000001
|
@@ -0,0 +1,1486 @@
+# -*- coding: utf-8 -*-%0A%22%22%22%0ABraubuddy Base unit tests%0A%22%22%22%0A%0Aimport unittest%0Afrom braubuddy.output import base %0A%0A%0Aclass IOutput(unittest.TestCase):%0A%0A def test_map_c_to_symbol(self):%0A %22%22%22c is mapped to %C2%B0C%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('c'), '%C2%B0C')%0A%0A def test_map_C_to_symbol(self):%0A %22%22%22C is mapped to %C2%B0C%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('C'), '%C2%B0C')%0A%0A def test_map_celsius_to_symbol(self):%0A %22%22%22celsius is mapped to %C2%B0C%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('celsius'), '%C2%B0C')%0A%0A def test_map_c_to_symbol(self):%0A %22%22%22Celsius is mapped to %C2%B0C%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('Celsius'), '%C2%B0C')%0A%0A def test_map_f_to_symbol(self):%0A %22%22%22f is mapped to %C2%B0F%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('f'), '%C2%B0F')%0A%0A def test_map_F_to_symbol(self):%0A %22%22%22F is mapped to %C2%B0F%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('F'), '%C2%B0F')%0A%0A def test_map_fahrenheit_to_symbol(self):%0A %22%22%22fahrenheit is mapped to %C2%B0F%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('fahrenheit'), '%C2%B0F')%0A%0A def test_map_Fahrenheit_to_symbol(self):%0A %22%22%22Fahrenheit is mapped to %C2%B0F%22%22%22%0A self.assertEqual(%0A base.IOutput.map_temp_units_to_symbol('Fahrenheit'), '%C2%B0F')%0A
|
|
437c45509bb2f6387b83cf7d47e51ce46d1c2776
|
Add unit test
|
tests.py
|
tests.py
|
Python
| 0.000001
|
@@ -0,0 +1,473 @@
+from models import AuthenticationError,AuthenticationRequired%0Aimport trello%0Aimport unittest%0Aimport os%0A%0Aclass TestTrello(unittest.TestCase):%0A%0A%09def test_login(self):%0A%09%09username = os.environ%5B'TRELLO_TEST_USER'%5D%0A%09%09password = os.environ%5B'TRELLO_TEST_PASS'%5D%0A%09%09try:%0A%09%09%09trello.login(username, password)%0A%09%09except AuthenticationError:%0A%09%09%09self.fail(%22Could not authenticate%22)%0A%09%09except Exception as e:%0A%09%09%09self.fail(%22Unknown error: %22+str(e))%0A%0Aif __name__ == %22__main__%22:%0A%09unittest.main()%0A
|
|
fdcdfb6f710be10cdead865b09d98b4bd0c0cebd
|
Create tests.py
|
tests.py
|
tests.py
|
Python
| 0.000001
|
@@ -0,0 +1,5 @@
+pass%0A
|
|
6200bce410eb966b97a5edf2ea8efdcd94e736db
|
test script which creates a tun tunnel and prints what it received.
|
tests.py
|
tests.py
|
Python
| 0
|
@@ -0,0 +1,2332 @@
+import pytun%0Aimport logging%0Aimport select%0A%0Adef pprint_buf(buf):%0A %22%22%22 Dirty & convenient function to display the hexademical%0A repr. of a buffer.%0A %22%22%22%0A%0A DEFAULT_SIZE = 4%0A%0A def hex2(i, l = None):%0A l = l if l is not None else DEFAULT_SIZE%0A%0A h = hex(i).upper()%5B2:%5D%0A %0A if len(h) != l:%0A h = %220%22 * (l - len(h)) + h%0A %0A return h%0A%0A def displayable_char(c):%0A if ord(c) %3C 0x20:%0A c = %22.%22%0A%0A return c%0A%0A print %22 %22 * DEFAULT_SIZE,%0A for i in range(16): print hex2(i, 2),%0A print%0A%0A raws = %5B%5D%0A for i, c in enumerate(buf):%0A if i %25 16 == 0:%0A if i:%0A print %22%5Ct%22 + %22%22.join(raws)%0A raws = %5B%5D%0A%0A print hex2(i),%0A raws.append(displayable_char(c))%0A %0A print hex2(ord(c), 2),%0A%0A print %22 %22 * (15 - (i %25 16)) + %22%5Ct%22 + %22%22.join(raws)%0A%0Adef main():%0A pytun.logger.setLevel(logging.DEBUG)%0A logging.basicConfig()%0A%0A try:%0A tun = pytun.TunTunnel()%0A%0A except pytun.Tunnel.NotPermitted:%0A print%0A print %22*%22 * 80%0A print %22You do have the rights to access the file %25s.%22 %25 (pytun.TUN_KO_PATH, )%0A print %22Give the access of this file to pytun, or if you trust me,%22%0A print %22elevate this current script to root level.%22%0A print %22*%22 * 80%0A print%0A%0A raise%0A%0A print %22*%22 * 80%0A print%0A print %22OK. The tunnel '%25s' had been created.%22 %25 (tun.name, )%0A print%0A print %22If you want to play with it, first configure it.%22%0A print%0A print %221. Set up the network and set an IP%22%0A print %22 $ ifconfig %25s 192.168.42.1%22 %25 (tun.name, )%0A print%0A print %222. Add the network route%22%0A print %22 $ route add -net 192.168.42.0/24 dev %25s%22 %25 (tun.name, )%0A print%0A print %22Then, try to ping some IP in this network ...%22%0A print %22 $ ping 192.168.42.42%22%0A print%0A print %22Or do some UDP netcat magic.%22%0A print %22 $ nc 192.168.42.42 4242 -u%22%0A print%0A print %22Enjoy !%22%0A print%0A print %22*%22 * 80%0A%0A try:%0A while True:%0A buf = tun.recv()%0A%0A pytun.logger.info(%22Packet received !%22)%0A pprint_buf(buf)%0A print%0A%0A except KeyboardInterrupt:%0A print %22Keyboard interrupt. Closing.%22%0A %0A finally:%0A tun.close()%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A%0A
|
|
cc967aa97954be1614ca49489e1b97a940b2ef2b
|
Create solution.py
|
hackerrank/algorithms/sorting/easy/correctness_and_the_loop_invariant/py/solution.py
|
hackerrank/algorithms/sorting/easy/correctness_and_the_loop_invariant/py/solution.py
|
Python
| 0.000018
|
@@ -0,0 +1,318 @@
+#!/bin/python%0A%0Adef insertion_sort(L):%0A for i in xrange(1, len(L)):%0A j = i - 1%0A key = L%5Bi%5D%0A while (j %3E= 0) and (L%5Bj%5D %3E key):%0A L%5Bj+1%5D, L%5Bj%5D = L%5Bj%5D, L%5Bj + 1%5D%0A j -= 1%0A%0Am = input()%0Aar = %5Bint(i) for i in raw_input().strip().split()%5D%0Ainsertion_sort(ar)%0Aprint %22 %22.join(map(str,ar))%0A
|
|
0caeed31553dbc2a201cf5e2e50013ea946507c1
|
Add packagist.
|
plumeria/plugins/packagist.py
|
plumeria/plugins/packagist.py
|
Python
| 0
|
@@ -0,0 +1,1287 @@
+from plumeria import config%0Afrom plumeria.command import commands, CommandError%0Afrom plumeria.util import http%0Afrom plumeria.util.ratelimit import rate_limit%0A%0A%0A@commands.register(%22packagist%22, %22composer%22, category=%22Development%22)%0A@rate_limit()%0Aasync def packagist(message):%0A %22%22%22%0A Search the Packagist repository for a package.%0A%0A Example::%0A%0A /packagist discord%0A%0A Response::%0A%0A %5Cu2022 laravel-notification-channels/discord - Laravel %5B...%5D%0A %5Cu2022 socialiteproviders/discord - Discord OAuth2 Prov%5B...%5D%0A %5Cu2022 team-reflex/oauth2-discord - OAuth2 client for a%5B...%5D%0A %5Cu2022 pnobbe/oauth2-discord - Discord OAuth 2.0 Client%5B...%5D%0A%0A %22%22%22%0A q = message.content.strip()%0A if not q:%0A raise CommandError(%22Search term required!%22)%0A r = await http.get(%22https://packagist.org/search.json%22, params=%5B%0A ('q', q),%0A %5D)%0A data = r.json()%0A if len(data%5B'results'%5D):%0A return %22%5Cn%22.join(map(lambda e:%0A %22%5Cu2022 **%7Bname%7D** - %7Bdesc%7D %3C%7Burl%7D%3E%22.format(%0A name=e%5B'name'%5D,%0A desc=e%5B'description'%5D,%0A url=e%5B'url'%5D),%0A data%5B'results'%5D))%0A else:%0A raise CommandError(%22no results found%22)%0A
|
|
3b4c1ec38e4725536bb11ec04ec0624282e166c0
|
Create proxy.py
|
proxy.py
|
proxy.py
|
Python
| 0.000001
|
@@ -0,0 +1,496 @@
+import subprocess%0Aimport time%0A%0Aclass ProxyClient():%0A %0A def restart_client(self):%0A while True:%0A (status, output) = subprocess.getstatusoutput('systemctl restart tinyproxy.service')%0A if status ==0:%0A print(%22tinyproxy %E9%87%8D%E5%90%AF%E6%88%90%E5%8A%9F%22)%0A time.sleep(3600)%0A else:%0A print(%22tinyproxy %E9%87%8D%E5%90%AF%E5%A4%B1%E8%B4%A5%EF%BC%8C%E5%86%8D%E6%AC%A1%E9%87%8D%E5%90%AF%22)%0A %0Adef proxy():%0A client = ProxyClient()%0A client.restart_client()%0A %0Aif __name__ == '__main__':%0A proxy()%0A
|
|
9a1cf12d2eab79abe313cc211b697e05d4a1d3c1
|
Solve 010
|
programming_challenges/010.py
|
programming_challenges/010.py
|
Python
| 1
|
@@ -0,0 +1,927 @@
+'''%0AProblem 010%0A%0ASolutionum of the primes below 10 is 2 + 3 + 5 + 7 = 17.%0A%0AFind the sum of all the primes below two million.%0A%0ACopyright 2017 Dave Cuthbert, MIT License%0A'''%0Aimport math%0A%0A%0Adef get_primes(number):%0A while True:%0A if is_prime(number):%0A yield number%0A number += 1%0A%0A%0Adef is_prime(number): %0A if number %3E 1:%0A if number == 2:%0A return True%0A if number %25 2 == 0:%0A return False%0A for current in range(3, int(math.sqrt(number) + 1), 2):%0A if number %25 current == 0:%0A return False%0A return True%0A return False%0A%0A%0Adef solve_problem(maximum_value):%0A running_sum = 0%0A for next_prime in get_primes(2):%0A if next_prime %3C maximum_value:%0A running_sum += next_prime%0A else:%0A return running_sum%0A%0A%0Aif __name__ == %22__main__%22:%0A maximum_value = 2000000%0A print(solve_problem(maximum_value))%0A
|
|
fdcf6fe1792c462221e0c6c35c13cc23ad39a2e3
|
Create pythonhelloworld.py
|
pythonhelloworld.py
|
pythonhelloworld.py
|
Python
| 0.003233
|
@@ -0,0 +1,20 @@
+print %22hello world%22%0A
|
|
c9bbd45e3ef6f52473efa4e1a69ac5ebae81c18a
|
set norm_Steps=5 (instead of 10) since usually only 1 or 2 are required.
|
qutip/Odeoptions.py
|
qutip/Odeoptions.py
|
from __future__ import print_function
#This file is part of QuTIP.
#
# QuTIP 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.
#
# QuTIP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with QuTIP. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2011-2012, Paul D. Nation & Robert J. Johansson
#
###########################################################################
import os
class Odeoptions():
"""
Class of options for ODE solver used by :func:`qutip.mesolve` and :func:`qutip.mcsolve`.
Options can be changed either inline::
opts=Odeoptions(gui=False,order=10,.....)
or by changing the class properties after creation::
opts=Odeoptions()
opts.gui=False
opts.order=10
Returns options class to be used as options in :func:`qutip.mesolve` and :func:`qutip.mcsolve`.
Attributes
----------
atol : float {1e-8}
Absolute tolerance.
rtol : float {1e-6}
Relative tolerance.
method : str {'adams','bdf'}
Integration method.
order : int {12}
Order of integrator (<=12 'adams', <=5 'bdf')
nsteps : int {2500}
Max. number of internal steps/call.
first_step : float {0}
Size of initial step (0 = automatic).
min_step : float {0}
Minimum step size (0 = automatic).
max_step : float {0}
Maximum step size (0 = automatic)
tidy : bool {True,False}
Tidyup Hamiltonian and initial state by removing small terms.
num_cpus : int
Number of cpus used by mcsolver (default = # of cpus).
norm_tol :float
Tolerance used when finding wavefunction norm.
norm_steps : int
Max. number of steps used to find wavefunction norm to within norm_tol.
gui : bool {True,False}
Use progress bar GUI for mcsolver.
mc_avg : bool {True,False}
Avg. expectation values in mcsolver.
rhs_reuse : bool {False,True}
Reuse Hamiltonian data.
Other Parameters
----------------
rhs_filename : str
Name for compiled Cython file.
"""
def __init__(self,atol=1e-8,rtol=1e-6,method='adams',order=12,nsteps=1000,first_step=0,max_step=0,min_step=0,
mc_avg=True,tidy=True,num_cpus=0,norm_tol=1e-3,norm_steps=10,rhs_reuse=False,rhs_filename=None,gui=True):
#Absolute tolerance (default = 1e-8)
self.atol=atol
#Relative tolerance (default = 1e-6)
self.rtol=rtol
#Integration method (default = 'adams', for stiff 'bdf')
self.method=method
#Max. number of internal steps/call
self.nsteps=nsteps
#Size of initial step (0 = determined by solver)
self.first_step=first_step
#Minimal step size (0 = determined by solver)
self.min_step=min_step
#Max step size (0 = determined by solver)
self.max_step=max_step
#Maximum order used by integrator (<=12 for 'adams', <=5 for 'bdf')
self.order=order
#Average expectation values over trajectories (default = True)
self.mc_avg=mc_avg
#tidyup Hamiltonian before calculation (default = True)
self.tidy=tidy
#Use preexisting RHS function for time-dependent solvers
self.rhs_reuse=rhs_reuse
#Use filename for preexisting RHS function (will default to last compiled function if None & rhs_exists=True)
self.rhs_filename=rhs_filename
#Number of processors to use (mcsolve only)
if num_cpus:
self.num_cpus=num_cpus
if self.num_cpus>int(os.environ['NUM_THREADS']):
raise Exception("Requested number of CPU's too large. Max = "+str(int(os.environ['NUM_THREADS'])))
else:
self.num_cpus=0
#Tolerance for wavefunction norm (mcsolve only)
self.norm_tol=norm_tol
#Max. number of steps taken to find wavefunction norm to within norm_tol (mcsolve only)
self.norm_steps=norm_steps
#Use Progressbar (mcsolve only)
self.gui=gui
def __str__(self):
print("Odeoptions properties:")
print("----------------------")
print("atol: ",self.atol)
print('rtol: ',self.rtol)
print('method: ',self.method)
print('order: ',self.order)
print('nsteps: ',self.nsteps)
print('first_step: ',self.first_step)
print('min_step: ',self.min_step)
print('max_step: ',self.max_step)
print('tidy: ',self.tidy)
print('num_cpus: ',self.num_cpus)
print('norm_tol: ',self.norm_tol)
print('norm_steps: ',self.norm_steps)
print('rhs_filename: ',self.rhs_filename)
print('rhs_reuse: ',self.rhs_reuse)
print('gui: ',self.gui)
print('mc_avg: ',self.mc_avg)
return ''
|
Python
| 0.000001
|
@@ -2141,16 +2141,27 @@
ion norm
+ in mcsolve
.%0A no
@@ -2253,16 +2253,27 @@
norm_tol
+ in mcsolve
.%0A gu
@@ -2790,18 +2790,17 @@
m_steps=
-10
+5
,rhs_reu
|
fafbb9e84a63f0de1f84ce94ba8766a8fdc23f8e
|
package for the item containers
|
models/item_container.py
|
models/item_container.py
|
Python
| 0.00002
|
@@ -0,0 +1,1058 @@
+# -*- coding: utf-8 -*-%0A%0Afrom models.Model import Model%0A%0A%0Aclass item_container:%0A%09%22%22%22%0A%09Class to interact with the item containers, such as chests.%0A%09%22%22%22%0A%0A%09@staticmethod%0A%09def getAllFromIdArea(idArea):%0A%09%09itemContainerTypes = model.getTypes()%0A%09%09containers = model.loadBy(%7B'id_area': idArea%7D)%0A%09%09for k, c in enumerate(containers):%0A%09%09%09containers%5Bk%5D%5B'type_label'%5D = itemContainerTypes%5Bcontainers%5Bk%5D%5B'id_item_container_type'%5D%5D%0A%09%09return containers%0A%0A%0Aclass model(Model):%0A%09%22%22%22%0A%09Class to interact with the values in the database.%0A%09%22%22%22%0A%0A%09fields = (%0A%09%09'id_item_container',%0A%09%09'id_item_container_type',%0A%09%09'id_area',%0A%09%09'items'%0A%09)%0A%0A%09@staticmethod%0A%09def getTypes():%0A%09%09%22%22%22%0A%09%09Returns the available types as an dict with ids as keys and labels as%0A%09%09values%0A%0A%09%09@return dict the types%0A%09%09%22%22%22%0A%0A%09%09query = %22%5C%0A%09%09%09SELECT%5C%0A%09%09%09%09id_item_container_type,%5C%0A%09%09%09%09label%5C%0A%09%09%09FROM%5C%0A%09%09%09%09item_container_type%5C%0A%09%09%22%0A%0A%09%09return %7Bt%5B'id_item_container_type'%5D: t%5B'label'%5D for t in Model.fetchAllRows(query)%7D%0A%0A%0A%0Aclass exception(BaseException):%0A%09%22%22%22%0A%09Class for the exceptions concerning item containers.%0A%09%22%22%22%0A%09pass%0A
|
|
3490b1172f8df77af3963c86ce3967a6d9b4af5e
|
Add gender choices factory
|
accelerator/tests/factories/gender_choices_factory.py
|
accelerator/tests/factories/gender_choices_factory.py
|
Python
| 0.000249
|
@@ -0,0 +1,394 @@
+# MIT License%0A# Copyright (c) 2017 MassChallenge, Inc.%0A%0Afrom __future__ import unicode_literals%0A%0Afrom factory import Sequence%0Afrom factory.django import DjangoModelFactory%0A%0AGenderChoices = swapper.load_model('accelerator', 'GenderChoices')%0A%0A%0Aclass GenderChoicesFactory(DjangoModelFactory):%0A class Meta:%0A model = GenderChoices%0A name = Sequence(lambda n: %22test_choice%7B0%7D%22.format(n))%0A
|
|
44e6c6007a37dc4c9375303a6555c646618d4e38
|
add tf dadaset with generator with args
|
tensorflow_learning/tf2/tf_dataset_from_generator_args.py
|
tensorflow_learning/tf2/tf_dataset_from_generator_args.py
|
Python
| 0
|
@@ -0,0 +1,822 @@
+# -*- coding: utf-8 -*-%0D%0A'''%0D%0A @author: jeffzhengye%0D%0A @contact: yezheng@scuec.edu.cn%0D%0A @file: tf_dataset_from_generator_args.py%0D%0A @time: 2021/1/5 16:27%0D%0A @desc:%0D%0A '''%0D%0A%0D%0Aimport tensorflow as tf%0D%0Aimport numpy as np%0D%0Aimport collections%0D%0A%0D%0A%0D%0Adef movingWindow(data, window_size):%0D%0A print(type(window_size))%0D%0A window_size = int( window_size )%0D%0A buffer = collections.deque(data%5B:window_size - 1%5D, maxlen=window_size)%0D%0A for i, datum in enumerate(data%5Bwindow_size - 1:%5D):%0D%0A buffer.append(datum)%0D%0A for b in buffer:%0D%0A yield datum, b%0D%0A%0D%0A%0D%0Awindow_size = 2%0D%0Adata = np.arange(10)%0D%0A%0D%0Adataset = tf.data.Dataset.from_generator(%0D%0A movingWindow,%0D%0A args=(data, window_size),%0D%0A output_types=(np.int32, np.int32)%0D%0A)%0D%0A%0D%0Aprint(next(movingWindow(data, window_size)))%0D%0Aprint(next(iter(dataset)))%0D%0A
|
|
79637efbdda03cea88fa6a59b24a27f1d393c79f
|
Add tests for previous commit
|
corehq/util/tests/test_es_interface.py
|
corehq/util/tests/test_es_interface.py
|
Python
| 0
|
@@ -0,0 +1,1990 @@
+from django.test import SimpleTestCase%0Afrom mock import ANY, patch%0A%0Afrom corehq.apps.es.tests.utils import es_test%0Afrom corehq.elastic import SerializationError, get_es_new%0Afrom corehq.util.es.interface import ElasticsearchInterface%0A%0A%0A@es_test%0Aclass TestESInterface(SimpleTestCase):%0A%0A @classmethod%0A def setUpClass(cls):%0A super().setUpClass()%0A cls.es = get_es_new()%0A%0A def _validate_es_scan_search_params(self, scan_query, search_query):%0A %22%22%22Call ElasticsearchInterface.scan() and test that the resulting API%0A search parameters match what we expect.%0A%0A Notably:%0A - Search call does not include the %60search_type='scan'%60.%0A - Calling %60scan(..., query=scan_query, ...)%60 results in an API call%0A where %60body == search_query%60.%0A %22%22%22%0A interface = ElasticsearchInterface(self.es)%0A skw = %7B%0A %22index%22: %22et%22,%0A %22doc_type%22: %22al%22,%0A %22request_timeout%22: ANY,%0A %22scroll%22: ANY,%0A %22size%22: ANY,%0A %7D%0A with patch.object(self.es, %22search%22) as search:%0A try:%0A list(interface.scan(skw%5B%22index%22%5D, scan_query, skw%5B%22doc_type%22%5D))%0A except SerializationError:%0A # fails to serialize the Mock object.%0A pass%0A search.assert_called_once_with(body=search_query, **skw)%0A%0A def test_scan_no_searchtype_scan(self):%0A %22%22%22Tests that search_type='scan' is not added to the search parameters%22%22%22%0A self._validate_es_scan_search_params(%7B%7D, %7B%22sort%22: %22_doc%22%7D)%0A%0A def test_scan_query_extended(self):%0A %22%22%22Tests that sort=_doc is added to an non-empty query%22%22%22%0A self._validate_es_scan_search_params(%7B%22_id%22: %22abc%22%7D,%0A %7B%22_id%22: %22abc%22, %22sort%22: %22_doc%22%7D)%0A%0A def test_scan_query_sort_safe(self):%0A %22%22%22Tests that a provided a %60sort%60 query will not be overwritten%22%22%22%0A self._validate_es_scan_search_params(%7B%22sort%22: %22_id%22%7D, %7B%22sort%22: %22_id%22%7D)%0A
|
|
a9195264349b695daf02abb5cf17ced8a6a6110c
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,486 @@
+# coding=utf-8%0A%0Afrom distutils.core import setup%0A%0Asetup(%0A name='openprovider.py',%0A version='0.0.1',%0A author='Antagonist B.V.',%0A author_email='info@antagonist.nl',%0A packages=%5B'openprovider'%5D,%0A url='http://pypi.python.org/pypi/openprovider.py/',%0A license='LICENSE.rst',%0A description='An unofficial library for the OpenProvider API',%0A long_description=open('README.rst').read(),%0A install_requires=%5B%0A %22requests %3E= 2.3.0%22,%0A %22lxml %3E= 3.3.5%22%0A %5D%0A)
|
|
e8568c3fd621a37020de015fac59dfd15141b51f
|
Update praw to 3.5.0
|
setup.py
|
setup.py
|
import sys
import setuptools
from version import __version__ as version
requirements = ['tornado', 'praw==3.4.0', 'six', 'requests', 'kitchen']
# Python 2: add required concurrent.futures backport from Python 3.2
if sys.version_info.major <= 2:
requirements.append('futures')
setuptools.setup(
name='rtv',
version=version,
description='A simple terminal viewer for Reddit (Reddit Terminal Viewer)',
long_description=open('README.rst').read(),
url='https://github.com/michael-lazar/rtv',
author='Michael Lazar',
author_email='lazar.michael22@gmail.com',
license='MIT',
keywords='reddit terminal praw curses',
packages=['rtv'],
package_data={'rtv': ['templates/*', 'rtv.cfg']},
data_files=[("share/man/man1", ["rtv.1"])],
extras_require={
':python_version=="2.6" or python_version=="2.7"': ['futures']},
install_requires=requirements,
entry_points={'console_scripts': ['rtv=rtv.__main__:main']},
classifiers=[
'Intended Audience :: End Users/Desktop',
'Environment :: Console :: Curses',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: Terminals',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary',
],
)
|
Python
| 0
|
@@ -107,9 +107,9 @@
==3.
-4
+5
.0',
|
d2fd2a473747fa90183c78c0c12cd933bdc1a4b6
|
add solution for 2019 day 1 part 1
|
2019/day01/rocket.py
|
2019/day01/rocket.py
|
Python
| 0.000009
|
@@ -0,0 +1,1904 @@
+#! python3%0A%22%22%22%0Afrom: https://adventofcode.com/2019/day/1%0A%0A--- Day 1: The Tyranny of the Rocket Equation ---%0ASanta has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.%0A%0ACollect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!%0A%0AThe Elves quickly load you into a spacecraft and prepare to launch.%0A%0AAt the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.%0A%0AFuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.%0A%0AFor example:%0A%0AFor a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.%0AFor a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.%0AFor a mass of 1969, the fuel required is 654.%0AFor a mass of 100756, the fuel required is 33583.%0AThe Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.%0A%0AWhat is the sum of the fuel requirements for all of the modules on your spacecraft?%0A%0A%22%22%22%0Aimport os%0A%0Adef main():%0A %22%22%22Solve the problem!%22%22%22%0A script_dir = os.path.dirname(__file__)%0A file_path = os.path.join(script_dir, './input.txt')%0A total_fuel = 0%0A with open(file_path) as input_file:%0A for line in input_file:%0A total_fuel += int(line)//3 - 2%0A print(total_fuel)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
4f42bf42c6dcb44f7a0972bb9c00818d087c808f
|
Add file
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,505 @@
+try:%0A from setuptools import setup%0Aexcept ImportError as ex:%0A from distutils.core import setup%0A%0Apackages = %5B%0A 'bren'%0A%5D%0A%0Awith open('README.rst') as f:%0A description_text = f.read()%0A%0Ainstall_req = %5B%22pyyaml%22%5D%0A%0Asetup(%0A name='bulkrename',%0A version='1.0.0',%0A description='bulk file rename',%0A author='Michael Sonntag',%0A packages=packages,%0A test_suite='test',%0A install_requires=install_req,%0A include_package_data=True,%0A long_description=description_text,%0A license=%22BSD%22%0A)%0A
|
|
7e3a894796bb11eb77c0352d5104754086e70f8e
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,776 @@
+from setuptools import setup, find_packages%0Aimport sys, os%0A%0Aversion = '0.1'%0A%0Asetup(name='recall',%0A version=version,%0A description=%22Python High performance RPC framework based on protobuf%22,%0A long_description=%22%22%22%5C%0A%22%22%22,%0A classifiers=%5B%5D, # Get strings from http://pypi.python.org/pypi?%253Aaction=list_classifiers%0A keywords='rpc gevent',%0A author='Yaolong Huang',%0A author_email='airekans@gmail.com',%0A url='https://github.com/airekans/recall',%0A license='MIT',%0A packages=find_packages(exclude=%5B'ez_setup', 'examples', 'tests'%5D),%0A include_package_data=True,%0A zip_safe=False,%0A install_requires=%5B%0A 'gevent',%0A 'protobuf%3E=2.3'%0A %5D,%0A entry_points=%22%22%22%0A # -*- Entry points: -*-%0A %22%22%22,%0A )%0A
|
|
24bbb4fafa0732252c4d8561783826ed5eba6cff
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,539 @@
+# -*- coding: utf-8 -*-%0Afrom setuptools import setup%0A%0Asetup(name='python-voicetext',%0A version='0.1',%0A license='Apache License 2.0',%0A description='Python library of VoiceText Web API',%0A author='Yutaka Kondo',%0A author_email='yutaka.kondo@youtalk.jp',%0A url='https://github.com/youtalk/python-voicetext',%0A packages=%5B'voicetext'%5D,%0A download_url='https://github.com/youtalk/python-voicetext/releases/tag/0.1',%0A requires=%5B'requests', 'PyAudio'%5D,%0A platforms = %5B'POSIX', 'Mac OS X', 'Windows'%5D,%0A)%0A
|
|
2d3610b8b18e7028b041142461a297e91ca26efc
|
version 1.4
|
setup.py
|
setup.py
|
#!/usr/bin/env python
#
# Copyright 2012-2014 Ravello Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, print_function
import os
from setuptools import setup
version_info = {
'name': 'ravello-sdk',
'version': '1.4.dev',
'description': 'Python SDK for the Ravello API',
'author': 'Geert Jansen',
'author_email': 'geert.jansen@ravellosystems.com',
'url': 'https://github.com/ravello/python-sdk',
'license': 'Apache 2.0',
'classifiers': [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3'
]
}
if __name__ == '__main__':
setup(
package_dir = { '': 'lib' },
py_modules = ['ravello_sdk'],
**version_info
)
|
Python
| 0.000001
|
@@ -773,12 +773,8 @@
'1.4
-.dev
',%0A
|
fd3eaa3810ce82db864b3fcafe61d16ab53d85e5
|
Add simple Python web server for performance testing
|
perftest/scripts/webserver.py
|
perftest/scripts/webserver.py
|
Python
| 0.001733
|
@@ -0,0 +1,551 @@
+from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer%0A%0Aclass Handler(BaseHTTPRequestHandler):%0A def do(self):%0A self.send_response(200)%0A self.wfile.write('%7B%22headers%22:%7B%22type%22:%22type%22%7D,%22content%22:%7B%22b%22:2%7D%7D')%0A%0A def do_GET(self):%0A self.do()%0A%0A def do_POST(self):%0A self.do()%0A%0Adef main():%0A try:%0A server = HTTPServer(('', 8080), Handler)%0A print 'started httpserver...'%0A server.serve_forever()%0A except KeyboardInterrupt:%0A print '%5EC received, shutting down server'%0A server.socket.close()%0A%0Aif __name__ == '__main__':%0A main()%0A%0A
|
|
891737a86e8f7007ac6d040f3f01afc420cd8c99
|
Create 2-keys-keyboard.py
|
Python/2-keys-keyboard.py
|
Python/2-keys-keyboard.py
|
Python
| 0.999821
|
@@ -0,0 +1,1165 @@
+# Time: O(sqrt(n))%0A# Space: O(1)%0A%0A# Initially on a notepad only one character 'A' is present.%0A# You can perform two operations on this notepad for each step:%0A#%0A# Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).%0A# Paste: You can paste the characters which are copied last time.%0A# Given a number n.%0A# You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted.%0A# Output the minimum number of steps to get n 'A'.%0A#%0A# Example 1:%0A# Input: 3%0A# Output: 3%0A# Explanation:%0A# Intitally, we have one character 'A'.%0A# In step 1, we use Copy All operation.%0A# In step 2, we use Paste operation to get 'AA'.%0A# In step 3, we use Paste operation to get 'AAA'.%0A# Note:%0A# The n will be in the range %5B1, 1000%5D.%0A%0Aclass Solution(object):%0A def minSteps(self, n):%0A %22%22%22%0A :type n: int%0A :rtype: int%0A %22%22%22%0A result = 0%0A p = 2%0A # the answer is the sum of prime factors%0A while p**2 %3C= n:%0A while n %25 p == 0:%0A result += p%0A n //= p%0A p += 1%0A if n %3E 1:%0A result += n%0A return result%0A
|
|
293983d24467cbb224f29b4a6149b518fe966603
|
Add forest Predictor.
|
code/python/seizures/prediction/ForestPredictor.py
|
code/python/seizures/prediction/ForestPredictor.py
|
Python
| 0.000001
|
@@ -0,0 +1,1018 @@
+from abc import abstractmethod%0Afrom sklearn.ensemble import RandomForestClassifier%0Aimport numpy as np%0A%0A%0Aclass ForestPredictor(object):%0A %22%22%22%22%0A A simple application of RandomForestClassifier%0A%0A @author: Shaun%0A %22%22%22%0A%0A def __init__(self):%0A self.clf = RandomForestClassifier()%0A%0A @abstractmethod%0A def fit(self, X, y):%0A %22%22%22%0A Method to fit the model.%0A%0A Parameters:%0A X - 2d numpy array of training data%0A y - 1d numpy array of training labels%0A %22%22%22%0A self.clf = self.clf.fit(X, y)%0A%0A @abstractmethod%0A def predict(self, X):%0A %22%22%22%0A Method to apply the model data%0A%0A Parameters:%0A X - 2d numpy array of test data%0A %22%22%22%0A return self.clf.predict_proba(X)%5B:, 1%5D%0A%0Aif __name__ == '__main__':%0A N = 1000%0A D = 2%0A X = np.random.rand(N, D)%0A y = np.random.randint(0, 2, N)%0A%0A predictor = ForestPredictor()%0A predictor.fit(X, y)%0A%0A x = np.random.rand(1, D)%0A pred = predictor.predict(x)%0A%0A print pred%0A%0A%0A%0A%0A
|
|
c19bc112e7e13f9d63746dfd2b073edf369f8e82
|
add `setup.py`
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,1151 @@
+#!/usr/bin/env python%0Afrom __future__ import absolute_import, print_function, unicode_literals%0A%0Afrom setuptools import find_packages, setup%0A%0Aimport lu_dj_utils%0A%0A%0Awith open('README.rst') as f:%0A readme = f.read()%0A%0Apackages = find_packages()%0A%0Aclassifiers = (%0A 'Development Status :: 4 - Beta',%0A 'Intended Audience :: Developers',%0A # the FSF refers to it as %22Modified BSD License%22. Other names include%0A # %22New BSD%22, %22revised BSD%22, %22BSD-3%22, or %223-clause BSD%22%0A 'License :: OSI Approved :: BSD License',%0A 'Natural Language :: English',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2.7',%0A 'Programming Language :: Python :: 3.3',%0A 'Programming Language :: Python :: 3.4',%0A)%0A%0Asetup(%0A name=%22lu-dj-utils%22,%0A version=lu_dj_utils.__version__,%0A description='',%0A long_description=readme,%0A author='German Larrain',%0A author_email='glarrain@users.noreply.github.com',%0A url='https://github.com/lookup/lu-dj-utils',%0A packages=packages,%0A license='3-clause BSD', # TODO: verify name is correct%0A zip_safe=False,%0A classifiers=classifiers,%0A)%0A
|
|
7255a3213418fe4bb3365bd60537f7e88af0c4cd
|
Add bare-bones setup.py and build file structure
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,344 @@
+from setuptools import setup, find_packages%0A%0Asetup(name='pensieve',%0A version='0.0.1',%0A description=u%22A Python package to extract character mems from a corpus of text%22,%0A author=u%22CDIPS-AI 2017%22,%0A author_email='sam.dixon@berkeley.edu',%0A url='https://github.com/CDIPS-AI-2017/pensieve',%0A license='Apache 2.0',%0A )
|
|
73edec331031de644320927800375b9f84f6e143
|
Read requirements.txt for setup install_requires, keywords and classifiers added for PyPi
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import simiki
entry_points = {
"console_scripts": [
"simiki = simiki.cli:main",
]
}
requires = [
"Markdown",
"Pygments",
"Jinja2",
"PyYAML",
"docopt",
]
setup(
name = "simiki",
version = simiki.__version__,
url = "https://github.com/tankywoo/simiki",
author = "Tanky Woo",
author_email = "me@tankywoo.com",
description = "Simiki is a simple wiki framework, written in Python.",
license = "MIT License",
packages = find_packages(),
include_package_data=True,
install_requires = requires,
entry_points = entry_points,
)
|
Python
| 0
|
@@ -178,85 +178,44 @@
s =
-%5B%0A %22Markdown%22,%0A %22Pygments%22,%0A %22Jinja2%22,%0A %22PyYAML%22,%0A %22docopt%22,%0A%5D
+open(%22requirements.txt%22).readlines()
%0A%0Ase
@@ -461,16 +461,58 @@
thon.%22,%0A
+ keywords = %22simiki, wiki, generator%22,%0A
lice
@@ -628,16 +628,16 @@
quires,%0A
-
entr
@@ -661,10 +661,372 @@
points,%0A
+ classifiers=%5B%0A 'Development Status :: 4 - Beta',%0A 'Environment :: Console',%0A 'License :: OSI Approved :: MIT License',%0A 'Operating System :: MacOS',%0A 'Operating System :: POSIX',%0A 'Operating System :: POSIX :: Linux',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2.7',%0A %5D,%0A
)%0A
|
88a617758eb869786d0703b2b53b5a030d7e7ac2
|
Add Python 3.4 to working environments
|
setup.py
|
setup.py
|
import os, sys
from setuptools import setup, find_packages
import mongonaut
LONG_DESCRIPTION = open('README.rst').read() + "\n\n"
CHANGELOG = open('CHANGELOG.rst').read()
LONG_DESCRIPTION += CHANGELOG
version = mongonaut.__version__
if sys.argv[-1] == 'publish':
os.system("python setup.py sdist upload")
print("You probably want to also tag the version now:")
print(" git tag -a %s -m 'version %s'" % (version, version))
print(" git push --tags")
sys.exit()
setup(
name='django-mongonaut',
version=version,
description="An introspective interface for Django and MongoDB",
long_description=LONG_DESCRIPTION,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: JavaScript",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='mongodb,django',
author=mongonaut.__author__,
author_email='pydanny@gmail.com',
url='http://github.com/pydanny/django-mongonaut',
license='MIT',
packages=find_packages(exclude=['examples']),
include_package_data=True,
install_requires=['mongoengine>=0.5.2'],
zip_safe=False,
use_2to3 = True,
)
|
Python
| 0.000429
|
@@ -1067,16 +1067,65 @@
: 3.3%22,%0A
+ %22Programming Language :: Python :: 3.4%22,%0A
|
2344a5e72d7a3a31d014ca31f42023740c56d060
|
add ndncache/fieldpercent.py
|
ndncache/fieldpercent.py
|
ndncache/fieldpercent.py
|
Python
| 0
|
@@ -0,0 +1,1561 @@
+#!/usr/bin/python %0A#coding:utf-8%0A'''Function:analyze bro conn logs and print specific field percent,%0A@param: log directory%0A@param: field list analyze%0Aauthor:melon li%0Adate: 2016.03.28%0A'''%0Aimport sys%0Aimport os%0AFIELDS=%5B'ts', 'uid', 'id.orig_h', 'id.orig_p', 'id.resp_h', 'id.resp_p', %0A 'proto', 'service duration', 'orig_bytes', 'resp_bytes', 'conn_state',%0A 'local_orig','local_resp', 'missed_bytes', 'history orig_pkts', 'orig_ip_bytes', %0A 'resp_pkts', 'resp_ip_bytes', 'tunnel_parents'%5D%0A#FIELDS_PERCENT=%5B'id.orig_h', 'id.orig_p', 'id.resp_h', 'id.resp_p', %0A# 'proto', 'service duration', 'orig_bytes', 'resp_bytes', 'conn_state',%0A# 'local_orig'%5D%0ATYPES=%5B'time', 'string', 'addr', 'port', 'addr', 'port', 'enum', 'string', 'interval',%0A 'count', 'count', 'string', 'bool', 'bool', 'count', 'string', 'count', 'count',%0A 'count', 'count', 'string'%5D%0A%0Adef usage():%0A print %22Usage:%25s %3Clog_dir%3E %3Cfields%3E%22 %25 sys.argv%5B0%5D%0A print %22%5CtFor example: %25s /home/ %5C%22id.resp_p id.orig_p%5C%22%22 %25 sys.argv%5B0%5D%0A sys.exit(1)%0A%0Atry:%0A log_dir = sys.argv%5B1%5D%0A fields = sys.argv%5B2%5D%0Aexcept:%0A usage()%0A%0Aif not os.path.isdir(log_dir):%0A print %22ERROR: %25s does not exist!%22 %25 log_dir%0A usage()%0A sys.exit(2)%0A%0A%0A#print log_dir%0A#print fields%0Afiles = os.listdir(log_dir)%0Afiles = %5Belem for elem in files if elem.find('conn.log') != -1 %5D%0Afiles.sort()%0Afor f in files:%0A f_path = os.path.join(log_dir, f)%0A with open(f_path, 'r') as fp:%0A while 1:%0A line = fp.readline()%0A if not line: break%0A print line%0A
|
|
4a6d45d102c76647bc7c4ff30f4b888108dd2d7c
|
Bump version to 2.6.0.2dev
|
setup.py
|
setup.py
|
'''
Nereid
Nereid - Tryton as a web framework
:copyright: (c) 2010-2013 by Openlabs Technologies & Consulting (P) Ltd.
:license: GPLv3, see LICENSE for more details
'''
from setuptools import setup
setup(
name='Nereid',
version='2.6.0.1',
url='http://nereid.openlabs.co.in/docs/',
license='GPLv3',
author='Openlabs Technologies & Consulting (P) Limited',
author_email='info@openlabs.co.in',
description='Tryton - Web Framework',
long_description=__doc__,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Tryton',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
install_requires=[
'distribute',
'trytond_nereid',
'flask',
'wtforms',
'wtforms-recaptcha',
'babel',
'speaklater',
'Flask-Babel',
],
packages=[
'nereid',
'nereid.contrib',
'nereid.tests',
],
package_dir={
'nereid': 'nereid',
'nereid.contrib': 'nereid/contrib',
'nereid.tests': 'tests',
},
zip_safe=False,
platforms='any',
)
|
Python
| 0
|
@@ -255,17 +255,20 @@
='2.6.0.
-1
+2dev
',%0A u
|
0907e4f32e4e0bb48f4f101b520ce8f28c731d6c
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,956 @@
+from os import path%0Afrom setuptools import setup, find_packages%0A%0Ahere = path.abspath(path.dirname(__file__))%0A%0A# TODO: change to rst%0Awith open(path.join(here, 'README.md'), encoding='utf-8') as f:%0A long_description = f.read()%0A%0Asetup(%0A name='pag',%0A version='0.1.0',%0A description='A simple text-based adventure game engine.',%0A long_description=long_description,%0A url='https://github.com/allanburleson/python-adventure-game',%0A author='Allan Burleson',%0A author_email='burleson.a@icloud.com',%0A license='MIT',%0A classifiers=%5B%0A 'Development Status :: 3 - Alpha',%0A 'Intended Audience :: Developers',%0A 'Topic :: Education :: Testing',%0A 'License :: OSI Approved :: MIT License',%0A 'Programming Language :: Python :: 3.6',%0A %5D,%0A keywords='game text text-based adventure interactive-fiction',%0A packages=find_packages(exclude='tests'),%0A package_data=%7B%0A 'pag': %5B'dictionary/*.txt'%5D%0A %7D%0A)%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.