repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
kcs/SOTAnaplo
log2csv.py
Python
mit
21,801
0.00555
#!/usr/bin/env python3 """Simple log converter for SOTA It inputs a simplified text log and converts it to SOTA CSV format. The input is a simplified version which allows most of the data field to be guessed by previous input. Example of input file: # lines starting with # are comments # first line contains informat...
tetime import date import os.path import argparse import json fro
m contest import Contest import country import qslinfo class LogException(Exception): def __init__(self, message, pos): self.message = message self.pos = pos # string matching functions call_prefix = r"(?:(?=.?[a-z])[0-9a-z]{1,2}(?:(?<=3d)a)?)" call = re.compile(r"(?:"+call_prefix+r"[0-9]?/)?("+...
rbeyer/scriptorium
cropsl.py
Python
apache-2.0
2,797
0.000715
#!/usr/bin/env python '''You can easily read off two sample,line coordinates from qview, but ISIS crop wants one sample,line and then offsets. This just takes two coordinates, does the math, and then calls crop.''' # Copyright 2016, 2019, Ross A. Beyer ([email protected]) # # Licensed under the Apache License, Version ...
.cub') (samp, line, nsamp, nline) = calcoffset(args.firs
t, args.second) print(crop(in_p, out_p, samp, line, nsamp, nline).args) if(args.output): # If there's a specific output filename, only do one. break if __name__ == "__main__": sys.exit(main())
absperf/wagtailapproval
runtests.py
Python
bsd-2-clause
293
0
#!/usr/bin/env python import os import sys def run(): from django.core.management import execute_from_command_line os.environ['DJANGO_SET
TINGS_MODULE'] = 'tests.app.settings' execute_from_command_line([sys.argv[0], 'test'] + sys.ar
gv[1:]) if __name__ == '__main__': run()
wolfiex/DSMACC-testing
dsmacc/examples/autoencoderminst.py
Python
gpl-3.0
2,098
0.007626
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pylab as plt import numpy as np import seaborn as sns; sns.set() import keras from keras.models import Sequential, Model from keras.layers import Dense from keras.optimizers import Adam from keras.data...
in.shape[2]) / 255 x_test = x_test.reshape(x_test.shape[0], x_test.shape[1]*x_test.shape[2]) / 255 #https://stats.stackexchange.com/questio
ns/190148/building-an-autoencoder-in-tensorflow-to-surpass-pca l_big = 512 l_mid = 128 l_lat = 2 epochs =5 m = Sequential() m.add(Dense(l_big, activation='elu', input_shape=(indim,))) m.add(Dense(l_mid, activation='elu')) m.add(Dense(l_lat, activation='linear', name="bottleneck")) m.add(Dense(l_mid, activation=...
iho/wagtail
wagtail/wagtailsnippets/blocks.py
Python
bsd-3-clause
637
0.00157
from __future__ import unicode_literals from django.utils.functional import cached_property from django.contrib.conten
ttypes.models import ContentType from wagtail.wagtailcore.blo
cks import ChooserBlock class SnippetChooserBlock(ChooserBlock): def __init__(self, target_model, **kwargs): super(SnippetChooserBlock, self).__init__(**kwargs) self.target_model = target_model @cached_property def widget(self): from wagtail.wagtailsnippets.widgets import AdminSnip...
guildai/guild-examples
noisy/noisy2.py
Python
apache-2.0
249
0.008032
import nu
mpy as np import tensorboardX as tbx x = 0.1 noise = 0.1 def f(x): return np.sin(5 * x) * (1 - np.tanh(x ** 2)) + np.random.randn() * noi
se loss = f(x) writer = tbx.SummaryWriter(".") writer.add_scalar("loss", loss) writer.close()
r-o-b-b-i-e/pootle
tests/core/management/subcommands.py
Python
gpl-3.0
6,653
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import pytest from co...
s): self.stdout.write( "Bar called with fooarg: %s" % options["fooarg"]) @provider(subcommands, sender=FooCommand) def provide_subcommands(**kwargs): return dict(bar=BarSubcommand) foo_command = FooCommand() command_calls(foo_command, "bar", "--fooarg", "BAR") o...
= "Bar called with fooarg: BAR\n" def test_command_with_subcommands_bad_args(capsys): class FooCommand(CommandWithSubcommands): pass foo_command = FooCommand() with pytest.raises(SystemExit): foo_command.run_from_argv(["", "foo", "bad", "args"]) out, err = capsys.readouterr() ass...
rpdillon/wikid
wikid/wikid.py
Python
gpl-3.0
13,569
0.004127
#!/usr/bin/env python # wikid, Copyright (c) 2010, R. P. Dillon <[email protected]> # This file is part of wikid. # # wikid 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...
mplied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import mercurial import datetime import web imp...
os import listdir from os import mkdir from os import remove from os import sep from os.path import expanduser from os.path import isdir from re import compile from re import sub from re import MULTILINE from urllib import unquote_plus from textile import textile from rest import * ###############################...
vistoyn/python-foruse
foruse/__init__.py
Python
mit
274
0.00365
# -*- coding: utf-8 -*-
__author__ = "Ildar Bikmamatov" __email__ = "[email protected]" __copyright__ = "Copyright 2016" __license__ = "MIT" __version__ = "1.0.1" from . import log from .lib import * from .error import * from .c
olors import colorf from .datelib import *
pombredanne/anitya
anitya/lib/backends/cpan.py
Python
gpl-2.0
3,025
0
# -*- coding: utf-8 -*- """ (c) 2014-2016 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon <[email protected]> Ralph Bean <[email protected]> """ import anitya.lib.xml2dict as xml2dict from anitya.lib.backends import BaseBackend, get_versions_by_regex, REGEX from anitya.lib.exceptions import AnityaPlug...
rying an RSS feed. ''' url = 'http://search.cpan.org/uploads.rdf' try: response = cls.call_url(url) except Exception: # pragma: no cover raise AnityaPluginException('Could not contact %s' % url) try: parser = xml2dict.XML2Dict() ...
items = data['RDF']['item'] for entry in items: title = entry['title']['value'] name, version = title.rsplit('-', 1) homepage = 'http://search.cpan.org/dist/%s/' % name yield name, homepage, cls.name, version
discipl/NAML
app/initPostgres.py
Python
gpl-3.0
133
0.007519
from data
base.postgresDB import init_database if __name__ == '__main__': print('Configuring PostgresSQL...')
init_database()
jerryyeezus/nlp-summarization
test.py
Python
mit
648
0.003086
from pyrouge import Rouge155 r = Rouge155() r.system_dir = "./summary" r.model_dir = "./summaries-gold/battery-life_amazon_kindle" r.system_filename_pattern = "battery-life.(\d+).summary" r.model_filename_pattern = "battery-life_amazon_kindle.[A-Z].#ID#.gold" output = r.convert_and_evaluate() print(output) output_dict...
utput) r.system_dir = "./summary" r.model_dir = "./summaries-gold/room_holiday_inn_london
" r.system_filename_pattern = "hotel_service.(\d+).summary" r.model_filename_pattern = "room_holiday_inn_london.[A-Z].#ID#.gold" output = r.convert_and_evaluate() print(output) output_dict = r.output_to_dict(output)
Bluejudy/bluejudyd
lib/broadcast.py
Python
mit
13,387
0.003364
#! /usr/bin/python3 """ Broadcast a message, with or without a price. Multiple messages per block are allowed. Bets are be made on the 'timestamp' field, and not the block index. An address is a feed of broadcasts. Feeds may be locked with a broadcast whose text field is identical to ‘lock’ (case insensitive). Bets ...
cursor.execute(sql, bindings) # Negative values (default to ignore). if value == None or value < 0: # Cancel Open Bets? if value == -
2: cursor.execute('''SELECT * FROM bets \ WHERE (status = ? AND feed_address = ?)''', ('open', tx['source'])) for i in list(cursor): bet.cancel_bet(db, i, 'dropped', tx['block_index']) # Cancel Pending Bet Matches? ...
capntransit/tract2council
tract2council.py
Python
gpl-3.0
2,643
0.005675
import sys, os, json, time from shapely.geometry import Polygon # http://toblerity.org/shapely/manual.html contains = {} intersects = {} dPoly = {} unmatched = [] TRACTCOL = 'BoroCT2010' # rename this for 2000 census def addPoly(coords): polys = [] if (isinstance(coords[0][0], float)): polys.append(P...
if (not os.path.isfile(f))
: print ("File " + f + " is not readable") exit() try: with open(tractfile) as tractfo: tractData = json.load(tractfo) except Exception: print ("Unable to read tract file " + tractfile) exit() try: with open(councilfile) as councilfo: ...
grow/grow
grow/pods/podspec.py
Python
mit
1,721
0.001162
"""Podspec helper.""" from grow.translations import locales class Error(Exception): def __init__(self, message): super(Error, self).__init__(message) self.message = message class PodSpecParseError(Error): pass class PodSpec(object): def __init__(self, yaml, pod): yaml = yaml...
liases']
for custom_locale, babel_locale in aliases.items(): normalized_babel_locale = babel_locale.lower() if locale == normalized_babel_locale: return custom_locale return locale
eawag-rdm/ckanext-hierarchy
ckanext/hierarchy/plugin.py
Python
agpl-3.0
4,054
0.00296
import ckan.plugins as p from ckanext.hierarchy.logic import action from ckanext.hierarchy import helpers fr
om ckan.lib.plugins import DefaultOrganizationForm import ckan.plugins.toolkit as tk from lucparser import LucParser import re import logging import pdb log = logging.getLogger(__name__) # This plugin is designed to work only these versions of CKAN p.toolkit.check_ckan_version(min_version='2.0') class HierarchyDisp...
pers, inherit=True) p.implements(p.IPackageController, inherit=True) # IConfigurer def update_config(self, config): p.toolkit.add_template_directory(config, 'templates') p.toolkit.add_template_directory(config, 'public') p.toolkit.add_resource('public/scripts/vendor/jstree', 'jstree...
andersk/zulip
zerver/lib/transfer.py
Python
apache-2.0
3,678
0.001631
import logging import multiprocessing import os from mimetypes import guess_type from django.conf import settings from django.core.cache import cache from django.db import connection from zerver.lib.avatar_hash import user_avatar_path from zerver.lib.upload import S3UploadBackend, upload_image_to_s3 from zerver.model...
tachment: Attachment) -> None: file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, "files", attachment.path_id) try: with open(file_path, "rb") as f: guessed_type = guess_type(attachment.file_name)[0] upload_image_to_s3( s3backend.uploads_bucket, ...
s", file_path) except FileNotFoundError: # nocoverage pass def transfer_message_files_to_s3(processes: int) -> None: attachments = list(Attachment.objects.all()) if processes == 1: for attachment in attachments: _transfer_message_files_to_s3(attachment) else: # nocoverage...
apple/swift-lldb
packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setExceptionBreakpoints.py
Python
apache-2.0
2,075
0.000964
""" Test lldb-vscode setBreakpoints request """ from __future__
import print_function import unittest2 import vscode from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil import lldbvscode_testcase class TestVSCode_setExceptionBreakpoints( lldbvscode_testcase.VSCodeTestCaseBase): mydir = TestBase.compute_m...
this test for now until we can figure out why tings aren't working on build bots @expectedFailureNetBSD @no_debug_info_test def test_functionality(self): '''Tests setting and clearing exception breakpoints. This packet is a bit tricky on the debug adaptor side since there is no...
benfinke/ns_python
nssrc/com/citrix/netscaler/nitro/resource/config/ns/nstimer.py
Python
apache-2.0
10,753
0.041012
# # Copyright (c) 2008-2015 Citrix 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 l...
lf) : ur"""Comments associated with this timer. """ try : return self._comm
ent except Exception as e: raise e @comment.setter def comment(self, comment) : ur"""Comments associated with this timer. """ try : self._comment = comment except Exception as e: raise e @property def newname(self) : ur"""The new name of the timer.<br/>Minimum length = 1. """ try : re...
LordSputnik/mutagen
tests/test_oggspeex.py
Python
gpl-2.0
2,072
0.000965
import os import shutil from mutagen._compat import cBytesIO from mutagen.ogg import OggPage from mutagen.oggspeex import OggSpeex, OggSpeexInfo, delete from tests import add from tests.test_ogg import TOggFileType from tempfile import mkstemp class TOggSpeex(TOggFileType): Kind = OggSpeex def setUp(self): ...
False self.failUnlessRaises(IOError, OggSpeexInfo, cBytesIO(page.write())) def test_vendor(self): self.failUnless( self.audio.tags.vendor.startswith("Encoded with Speex 1.1.12")) self.failUnlessRaises(KeyError
, self.audio.tags.__getitem__, "vendor") def test_not_my_ogg(self): fn = os.path.join('tests', 'data', 'empty.oggflac') self.failUnlessRaises(IOError, type(self.audio), fn) self.failUnlessRaises(IOError, self.audio.save, fn) self.failUnlessRaises(IOError, self.audio.delete, fn) ...
zhaohuaw/odoo-infrastructure
addons/infrastructure/database_type.py
Python
agpl-3.0
2,270
0.003084
# -*- coding: utf-8 -*- ############################################################################## # # Infrastructure # Copyright (C) 2014 Ingenieria ADHOC # No email # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License...
'url_example': fields.char(string='URL Example
'), 'bd_name_example': fields.char(string='BD Name Example'), 'db_back_up_policy_ids': fields.many2many('infrastructure.db_back_up_policy', 'infrastructure_database_type_ids_db_back_up_policy_ids_rel', 'database_type_id', 'db_back_up_policy_id', string='Suggested Backup Policies'), } _defaults...
avehtari/GPy
GPy/kern/src/ODE_t.py
Python
bsd-3-clause
7,626
0.026226
from .kern import Kern from ...core.parameterization import Param from paramz.transformations import Logexp import numpy as np from .independent_outputs import index_to_slices class ODE_t(Kern): def __init__(self, input_dim, a=1., c=1.,variance_Yt=3., lengthscale_Yt=1.5,ubias =1., active_dims=None, name='ode...
kYdlent[ss1,ss2] = vyt*dkyydlyt(tdist[ss1,ss2])* (-k4(ttdist[ss1,ss2])+1.)+\ vyt*kyy(tdist[ss1,ss2])*(-dk4dlyt(ttdist[ss1,ss2]) ) dkdubias[ss1,ss2] = 0
#dkYdlent[ss1,ss2] = vyt*dkyydlyt(tdist[ss1,ss2])* (-2*lyt*(ttdist[ss1,ss2])+1.)+\ #vyt*kyy(tdist[ss1,ss2])*(-2)*(ttdist[ss1,ss2]) self.variance_Yt.gradient = np.sum(dkYdvart * dL_dK) self.lengthscale_Yt.gradient = np....
mbkumar/pymatgen
pymatgen/io/tests/test_cif.py
Python
mit
43,823
0.000707
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest import warnings import numpy as np from pymatgen.io.cif import CifParser, CifWriter, CifBlock from pymatgen.io.vasp.inputs import Poscar from pymatgen import Element, Specie, Lattice, Structu...
atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_attached_hydrogens _atom_site_B_iso_or_equiv _atom_site_occupancy Fe Fe1
1 0.218728 0.750000 0.474867 0 . 1 Fe JJ2 1 0.281272 0.250000 0.974867 0 . 1 # there's a typo here, parser should read the symbol from the # _atom_site_type_symbol Fe Fe3 1 0.718728 0.750000 0.025133 0 . 1 Fe Fe4 1 0.781272 0.250000 0.525133 0 . 1 P P5 1 0.094613...
ghorejsi/hunt-the-wump
tests/map_tests.py
Python
gpl-2.0
256
0.003906
__author__ = 'petastream' import unittest from game
.map impo
rt Map class TestMap(unittest.TestCase): def setUp(self): self.map = Map() def test_generate(self): self.map.generate() if __name__ == "__main__": unittest.main()
mbkumar/pydii
examples/NiAl_mp-1487/gen_def_energy.py
Python
mit
9,115
0.012946
#!/usr/bin/env python """ This file computes the raw defect energies (for vacancy and antisite defects) by parsing the vasprun.xml files in the VASP DFT calculations for binary intermetallics, where the meta data is in the folder name """ #from __future__ import unicode_literals from __future__ import division __au...
ect.org") parser.add_argument("--mapi_key", default = None, help="Your Materials Project REST API key.\n" \ "For more info, please refer to " \ "www.materialsproject.org/opne") args = parser.parse_args() print args energy_dict = vac_antisite_d...
print key print type(key), type(value) for key2, val2 in value.items(): print type(key2), type(val2) if energy_dict: fl_nm = args.mpid+'_raw_defect_energy.json' dumpfn(energy_dict, fl_nm, cls=MontyEncoder, indent=2) def im_sol_sub_def_energy_parse(): m_descriptio...
ezequielo/diff-cover
diff_cover/tests/test_snippets.py
Python
apache-2.0
9,261
0.000216
from __future__ import unicode_literals import mock import os import tempfile from pygments.token import Token from diff_cover.snippets import Snippet from diff_cover.tests.helpers import load_fixture,\ fixture_path, assert_long_str_equal, unittest import six class SnippetTest(unittest.TestCase): SRC_TOKENS ...
'), (Token.Text, u' '), (Token.Keyword, u'return'), (Tok
en.Text, u' '), (Token.Name, u'arg'), (Token.Text, u' '), (Token.Operator, u'+'), (Token.Text, u' '), (Token.Literal.Number.Integer, u'5'), (Token.Text, u'\n'), ] FIXTURES = { 'style': 'snippet.css', 'default': 'snippet_default.html', 'inv...
dnjohnstone/hyperspy
hyperspy/_components/offset.py
Python
gpl-3.0
3,522
0.00142
# -*- coding: utf-8 -*- # Copyright 2007-2020 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
lf, x): return self._function(x, self.offset.value) def _function(self, x, o): return np.ones_like(x) * o @staticmethod def grad_offset(x): return np.ones_like(x) def estimate_parameters(self, signal, x1, x2, only_current=False): """Estimate the parameters by the two a...
for the estimation. x2 : float Defines the right limit of the spectral range to use for the estimation. only_current : bool If False estimates the parameters for the full dataset. Returns ------- bool """ super(O...
OsipovStas/ayc-2013
ayc/show.py
Python
gpl-2.0
455
0.008791
#
coding=utf-8 __author__ = 'stasstels' import cv2 import sys image = sys.argv[1] targets = sys.argv[2] # Load an color image in grayscale img = cv2.imread(image, cv2.IMREAD_COLOR) with open(targets, "r") as f: for line in f: print line (_, x, y) = line.split() cv2.circle(img, (int(x), int(y)), ...
lWindows()
suresh/notebooks
fluentpy/list_comprehension.py
Python
mit
968
0
# Fluent Python Book # List comprehensions are faster than for-loops import time from random import choices symbols = list('abcdefghijklmn') print(symbols) symbols_big = choices(symbols, k=2000000) # print(symbols_big) start = time.time() ord_list1 = [] for sym in
symbols_big: ord_list1.append(ord(sym)) # print('ord list1:', ord_list1) end = time.time() print('for loop ran in %f s' % (end - start)) start = time.time() # list comprehension ord_list2 = [ord(sym) for sym in symbols_big] # print('ord list2:', ord_list2) end = time.time() print('for loop ran in %f s' % (end - s...
mark of this list comprehension l_nums = [i for i in range(1000000)] start = time.time() sq_nums = [] for i in l_nums: sq_nums.append(i ** 2) end = time.time() print('for loop ran in %f s' % (end - start)) start = time.time() sq_nums = [i ** 2 for i in range(1000000)] end = time.time() print('list comp ran in %...
jeffknupp/kickstarter_video_two
proxy.py
Python
apache-2.0
3,925
0.000255
"""An HTTP proxy that supports IPv6 as well as the HTTP CONNECT method, among other things.""" # Standard libary imports import socket import thread import select __version__ = '0.1.0 Draft 1' BUFFER_LENGTH = 8192 VERSION = 'Python Proxy/{}'.format(__version__) HTTP_VERSION = 'HTTP/1.1' class ConnectionHandler(obje...
eturn data def method_connect(self, path): """Handle HTTP CONNECT messages.""" self._connect_target(path)
self.client.send('{http_version} 200 Connection established\n' 'Proxy-agent: {version}\n\n'.format( http_version=HTTP_VERSION, version=VERSION)) self.client_buffer = '' self._read_write() def method_others(self,...
joemarchese/PolyNanna
participants.py
Python
mit
3,229
0.007742
""" How to Use this File. participants is a dictionary where a key is the name of the participant and the value is a set of all the invalid selections for that participant. participants = {'Bob': {'Sue', 'Jim'}, 'Jim': {'Bob', 'Betty'}, } # And so on. history is a dictionary where a key is the name of ...
'Adam', 'Adrienne'}, 'Justin': {'Justin'
, 'Angela', 'Stefan'}, 'Nanna': {'Nanna', 'Jeff', 'Angela', 'Renee'}, 'Renee': {'Renee', 'Jeff', 'Angela', 'Nanna', 'Francesca', 'George'}, 'Shaina': {'Shaina', 'David'}, 'Stefan': {'Stefan', 'Angela', 'Justin', 'Amanda'}, } history = {'Adam': [(2015, 'Ju...
cysuncn/python
spark/crm/PROC_O_AFA_MAINTRANSDTL.py
Python
gpl-3.0
6,349
0.018374
#coding=UTF-8 from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_O_AFA_MAINTRANSDTL').setMaster(sys.argv[2]) sc = SparkContext(conf = conf) sc...
ntext(sc) else: sqlContext = SQLContext(sc) hdfs = sys.argv[3] dbname = sys.argv[4] #处理需要使用的日期 etl_date = sys.argv[1] #etl日期 V_DT = etl_date #上一日日期 V_DT_LD = (date(int(etl_date[0:4]), int(etl_date[4:6]), int(etl_date[6:8])) + timedelta(-1)).strftime("%Y%m%d") #月初日期 V_DT_FMD = date(int(etl_date[0:4]), int(etl_dat...
e[0:4]), int(etl_date[4:6]), int(etl_date[6:8]))).strftime("%Y-%m-%d") V_STEP = 0 ##原表 O_TX_AFA_MAINTRANSDTL = sqlContext.read.parquet(hdfs+'/O_TX_AFA_MAINTRANSDTL/*') O_TX_AFA_MAINTRANSDTL.registerTempTable("O_TX_AFA_MAINTRANSDTL") #目标表 :F_TX_AFA_MAINTRANSDTL 增量 ret = os.system("hdfs dfs -rm -r /"+dbname+"/F_TX_AFA_M...
mick-d/nipype_source
nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py
Python
bsd-3-clause
1,206
0.02073
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.slicer.filtering.denoising import GaussianBlu
rImageFilter def test_GaussianBlurImageFilter_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_
exception=dict(nohash=True, usedefault=True, ), inputVolume=dict(argstr='%s', position=-2, ), outputVolume=dict(argstr='%s', hash_files=False, position=-1, ), sigma=dict(argstr='--sigma %f', ), terminal_output=dict(mandatory=True, nohash=True, ), ) inputs ...
rochacbruno/flask_simplelogin
setup.py
Python
mit
1,254
0
# Fix for older setuptools import re import os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages def fpath(name): return os.path.join(os.path.dirname(__file__), name) d
ef read(fname): try: return open(fpath(fname), encoding='utf8').read() except TypeError: # Python 2's open doesn't have the encoding kwarg return open(fpath(fname)).read() def desc(): return read('README.md') # grep flask_simplelogin/__init__.py since python 3.x cannot # import it befor...
'".format(attrname) strval, = re.findall(pattern, file_text) return strval setup( name='flask_simplelogin', version=grep('__version__'), url='https://github.com/cuducos/flask_simplelogin/', license='MIT', author=grep('__author__'), author_email=grep('__email__'), description='Flask...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractKieshitlWordpressCom.py
Python
bsd-3-clause
642
0.029595
def extractKieshitlWordpressCom(item): ''' Parser for 'kieshitl.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower():
return None tagmap = [ ('I am a Big Villain', 'I am a Big Villain', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleas...
fix=postfix, tl_type=tl_type) return False
feigaochn/leetcode
p759_set_intersection_size_at_least_two.py
Python
mit
955
0
class Solution: def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort(key=lambda p: (p[1], p[0])) cover = [intervals[0][1] - 1] cover.append(cover[-1] + 1) for a, b in intervals[1:]: i...
elif cover[-2] < a <= cover[-1] <= b: if cover[-1] == b: cover[-1] = b - 1 cover.append(b) # print(cover) return len(cover)
sol = Solution().intersectionSizeTwo print(sol([[1, 3], [1, 4], [2, 5], [3, 5]])) print(sol([[1, 2], [2, 3], [2, 4], [4, 5]])) print(sol([[1, 10]])) print( sol([[2, 10], [3, 7], [3, 15], [4, 11], [6, 12], [6, 16], [7, 8], [7, 11], [7, 15], [11, 12]])) # 5
necozay/tulip-control
doc/genbib.py
Python
bsd-3-clause
1,618
0.001236
#!/usr/bin/env python """Generate bibliography.rst The input file is of the following form. Blank lin
es are ignored. New lines are collapsed to a single space. Besides newlines, text for each entry is copied without filtering, and thus reST syntax can be used. Note that the key line must begin with '['. [M55] G. H. Mealy. `A
Method for Synthesizing Sequential Circuits <http://dx.doi.org/10.1002/j.1538-7305.1955.tb03788.x>`_. *Bell System Technical Journal (BSTJ)*, Vol.34, No.5, pp. 1045 -- 1079, September, 1955. """ from __future__ import print_function import sys import io def print_entry(out_f, bkey, entry_text): nl = '\n' idt...
andresgomezvidal/autokey_scripts
data/General/file manager/asignaturas_actuales.py
Python
mit
200
0.015
import time t1=.3 t2=.1 path="~/Dropbox/Ingenieria/asignatura
s_actuales" time.sleep(t2) key
board.send_key("<f6>") time.sleep(t2) keyboard.send_keys(path) time.sleep(t1) keyboard.send_key("<enter>")
SoftwareHeritage/swh-web-ui
swh/web/tests/common/test_middlewares.py
Python
agpl-3.0
1,521
0.00263
# Copyright (C) 2020 The Software Heritage developers # See the AUTHORS file at the top-le
vel directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from hypothesis import given import pytest from django.test import modify_settings from swh.web.common.utils import rev
erse from swh.web.tests.strategies import snapshot @modify_settings( MIDDLEWARE={"remove": ["swh.web.common.middlewares.ExceptionMiddleware"]} ) @given(snapshot()) def test_exception_middleware_disabled(client, mocker, snapshot): mock_browse_snapshot_directory = mocker.patch( "swh.web.browse.views.sna...
divereigh/firewalld
src/firewall/core/ipset.py
Python
gpl-2.0
6,843
0.006284
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Red Hat, Inc. # # Authors: # Thomas Woerner <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License...
%s", self.__class__, self._command, " ".join(_args)) (status, ret) = runProg(self._command, _args) if status != 0: raise ValueError("'%s %s' failed: %s" % (self._command, " ".join(_args), ret)) return ret def check_name(self,...
ame) def supported_types(self): ret = { } output = "" try: output = self.__run(["--help"]) except ValueError as e: log.debug1("ipset error: %s" % e) lines = output.splitlines() in_types = False for line in lines: #print(li...
karesansui/karesansui
karesansui/tests/lib/file/testk2v.py
Python
mit
1,427
0.018921
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import unittest import tempfile from karesansui.lib.file.k2v import * class TestK2V(unittest.TestCase): _w = {'key.1':'h oge', 'ke
y.2':'fo o', 'key.3':'bar ', 'key.4':' piyo', 'key.5':'s p am'} def setUp(self): self._tmpfile = tempfile.mkstemp() fp = open(self._tmpfile[1], 'w') self._t = K2V(self._tmpfile[1]) def tearDown(self): os.unlink(self._tmpfile[1]) def test_writ...
_d = self._t.read() for i in xrange(1,6): self.assertEqual(self._w['key.%d'%i],_d['key.%d'%i]) def test_lock_sh_0(self): self.fail('TODO:') def test_lock_ex_0(self): self.fail('TODO:') def test_lock_un_0(self): self.fail('TODO:') class Su...
titilambert/home-assistant
homeassistant/components/generic_thermostat/climate.py
Python
apache-2.0
16,726
0.000837
"""Adds support for generic thermostat units.""" import asyncio import logging import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity from homeassistant.components.climate.const import ( ATTR_PRESET_MODE, CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, CURRENT_HVAC_...
_mode and old_state.state: self._hvac_mode = old_state.state else: # No previous state, try and restore defaults if self._target_temp is None: if self.ac_mode: self._target_temp = self.max_temp else:
self._target_temp = self.min_temp _LOGGER.warning( "No previously saved temperature, setting to %s", self._target_temp ) # Set default state to off if not self._hvac_mode:
Drvanon/Game
run.py
Python
apache-2.0
232
0.00431
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPS
erver from tornado.ioloop import IOLoop from game import app http_server = HTTPServer(WSGIContainer(app)) http_server.listen(5000) IOLoop.i
nstance().start()
eagafonov/screencloud
screencloud/src/3rdparty/PythonQt/examples/PyScriptingConsole/example.py
Python
gpl-2.0
331
0.009063
from PythonQt.QtG
ui import * group = QGroupBox() box = QVBoxLayout(group) push1 = QPushButton(group) box.addWidget(push1) push2 = QPushButton(group) box.addWidget(push2) check = QCheckBox(group) check.text = 'check me' group.title
= 'my title' push1.text = 'press me' push2.text = 'press me2' box.addWidget(check) group.show()
jjaviergalvez/CarND-Term3-Quizzes
search/print-path.py
Python
mit
2,943
0.011553
# ----------- # User Instructions: # # Modify the the search functio
n so that it returns # a shortest path as follows: # # [['>', 'v', ' ', ' ', ' ', ' '], # [' ', '>', '>', '>', '>', 'v'], # [' ', ' ', ' ', ' ', ' ', 'v']
, # [' ', ' ', ' ', ' ', ' ', 'v'], # [' ', ' ', ' ', ' ', ' ', '*']] # # Where '>', '<', '^', and 'v' refer to right, left, # up, and down motions. Note that the 'v' should be # lowercase. '*' should mark the goal cell. # # You may assume that all test cases for this function # will have a path from init to goal. ...
byuphamerator/phamerator-dev
phamerator/phamServer_InnoDB.py
Python
gpl-2.0
16,847
0.017985
#!/usr/bin/env python import Pyro.core import Pyro.naming import string import MySQLdb import time import random import threading try: from phamerator import * except: import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import alignmentDatabase from errorHandler import * import db_conf ...
t"): self.argDict['password'] = getpass.getpass('password: ') elif opt in ("-q", "--password"): self.argDict['password'] = arg elif opt in ("-s", "--server"): self.argDict['server'] = arg elif opt in ("-n", "--nsname"):
self.argDict['nsname'] = arg elif opt in ("-u", "--user"): self.argDict['user'] = arg elif opt in ("-d", "--database"): self.argDict['database'] = arg elif opt in ("-i", "--instances"): self.argDict['instances'] = arg elif opt in ("-l", "--logging"): self.a...
nnrcschmdt/helsinki
program/management/commands/check_automation_ids.py
Python
bsd-3-clause
1,616
0.001238
import json from os.path import join from django.conf import settings from django.core.management.base import NoArgsCommand from program.models import ProgramSlot class Command(NoArgsCommand): help = 'checks the automation_ids used by program slots against the exported' def handle_noargs(self, **options): ...
show
pv_ids = [] for programslot in ProgramSlot.objects.filter(automation_id__isnull=False): pv_ids.append(int(programslot.automation_id)) for automation_id in sorted(rd_ids.iterkeys()): if rd_ids[automation_id]['type'] == 's': continue ...
balazssimon/ml-playground
udemy/lazyprogrammer/deep-reinforcement-learning-python/atari/dqn_tf_alt.py
Python
apache-2.0
11,056
0.012663
# https://deeplearningcourses.com/c/deep-reinforcement-learning-in-python # https://www.udemy.com/deep-reinforcement-learning-in-python from __future__ import print_function, division from builtins import range # Note: you may need to update your version of future # sudo pip install -U future import copy import gym im...
== (4, 80, 80)) loss = None
total_time_training = 0 num_steps_in_episode = 0 episode_reward = 0 done = False while not done: # Update target network if total_t % TARGET_UPDATE_PERIOD == 0: target_model.copy_from(model) print("Copied model parameters to target network. total_t = %s, period = %s" % (total_t, TARGE...
tomcounsell/Cobra
apps/public/migrations/0018_auto_20141219_1711.py
Python
gpl-2.0
646
0.001548
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('public', '0017_auto_20141218_1813'), ] operations = [ migrations.RenameField( model_name='commission', ...
migrations.AlterField(
model_name='commission', name='customer', field=models.ForeignKey(related_name='commissions', to='public.Customer'), preserve_default=True, ), ]
dariemp/odoo
openerp/tools/translate.py
Python
agpl-3.0
45,371
0.003769
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
reece', 'gu': 'Gujarati_India', 'he_IL': 'Hebrew_Israel', 'hi_IN': 'Hindi', 'hu': 'Hungarian_Hungary', 'is_IS': 'Icelandic_Iceland', 'id_ID': 'Indonesian_indonesia', 'it_IT': 'Italian_Italy', 'ja_JP': 'Japanese_Japan', 'kn_IN': 'Kannada', 'km_KH': 'Khmer', 'ko_KR': 'Korean_Ko...
'Cyrillic_Mongolian', 'no_NO': 'Norwegian_Norway', 'nn_NO': 'Norwegian-Nynorsk_Norway', 'pl': 'Polish_Poland', 'pt_PT': 'Portuguese_Portugal', 'pt_BR': 'Portuguese_Brazil', 'ro_RO': 'Romanian_Romania', 'ru_RU': 'Russian_Russia', 'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro', 's...
peteboyd/lammps_interface
lammps_interface/ccdc.py
Python
mit
949
0
""" Bond order information. """ CCDC_BOND_ORDERS = { # http://cima.chem.usyd.edu.au:8080/cif/skunkworks/html/ddl1/mif/bond.html 'S': 1.0, # single (two-electron) bond or sigma bond to metal 'D': 2.0, # double (four-electron) bond 'T': 3.0, # triple (six-electron) bond 'Q': 4.0, # quadruple (eigh...
, # equivalent (delocalized double) bond 'P': 1.0, # pi bond (metal-ligand pi interaction) 'Am': 1.41, # Amide bond (non standard) 1.0: 'S', # single (two-electron) bond or sigma bond to metal 2.0: 'D', # double (fou
r-electron) bond 3.0: 'T', # triple (six-electron) bond 4.0: 'Q', # quadruple (eight-electron, metal-metal) bond 1.5: 'A', # alternating normalized ring bond (aromatic) 1.41: 'Am' # Amide bond (non standard) }
micbuz/project2
boot/manage.py
Python
apache-2.0
802
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.set
default("DJANGO_SETTINGS_MODULE", "boot.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions...
stalled and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
NorThanapon/dict-definition
definition/legacy/analyze_data.py
Python
gpl-3.0
1,265
0.001581
import codecs from nltk.tokenize import wordpunct_tokenize as tokenize data_filepath = 'output/top10kwords_2defs.tsv' def num_words_with_freq(freq, n): c = 0 for w in freq: if freq[w] == n: c = c + 1 return c defined_words = set() freq = {} total_tokens = 0 total_defs = 0 with codecs....
n tokenize(parts[3]): if t not in freq: freq[t] = 0 freq[t] = freq[t] + 1 total_tokens = total_tokens + 1 print('#word being defined: ' + str(len(defined_words))) print('#definition: ' + str(total_defs)) print('#tokens: ' + str(total_tokens)) print('vocab size: ' + s...
s_with_freq(freq, 2))) print(' - 3: ' + str(num_words_with_freq(freq, 3))) print(' - 4: ' + str(num_words_with_freq(freq, 4))) print(' - 5: ' + str(num_words_with_freq(freq, 5)))
i32baher/practicas-iss
tubeworld/video/admin.py
Python
gpl-3.0
147
0
from dja
ngo.contrib import admin # Register your models here. from .models import Video, Tag
admin.site.register(Video) admin.site.register(Tag)
kevgliss/lemur
lemur/certificates/service.py
Python
apache-2.0
17,189
0.002327
""" .. module: lemur.certificate.service :platform: Unix :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <[email protected]> """ import arrow from flask import current_app from sqlalchemy import func, or_, not_, c...
the CSR to be specified by the user if not kwargs.get('csr'): csr, private_key = create_csr(**
kwargs) csr_created.send(authority=authority, csr=csr) else: csr = str(kwargs.get('csr')) private_key = None csr_imported.send(authority=authority, csr=csr) cert_body, cert_chain, external_id = issuer.create_certificate(csr, kwargs) return cert_body, private_key, cert_chain,...
sti-lyneos/shop
tests/gtk3/test_exhibits.py
Python
lgpl-3.0
6,973
0.000574
import os import unittest from mock import patch, Mock from tests.utils import ( FakedCache, ObjectWithSignals, setup_test_env, ) setup_test_env() from softwarecenter.db.database import StoreDatabase from softwarecenter.ui.gtk3.views import lobbyview from softwarecenter.ui.gtk3.widgets.exhibits import (...
ertIs(banner.exhibits[0], exhibit) def test_exhibit_with_url(self): # available exhibit exhibit = Mock() exhibit.package_names = '' exhibit.click_url = 'http://example.com' exhibit.banner_urls = [
'banner'] exhibit.title_translated = '' sca = ObjectWithSignals() sca.query_exhibits = lambda: sca.emit('exhibits', sca, [exhibit]) with patch.object(lobbyview, 'SoftwareCenterAgent', lambda: sca): # add the banners ...
jakeh12/hackisu2018-flopper
basestation/track_chunk.py
Python
mit
264
0.003788
from helpers import HexArrayToDecimal from track_data import TrackDa
ta class TrackChunk(object): def __init__(self, raw_data): self.raw_data = raw_data self.length = HexArrayToDecimal(raw_data[4:8]) self.d
ata = TrackData(raw_data[8:])
mikeireland/pymfe
doc/conf.py
Python
mit
9,303
0.005912
# -*- coding: utf-8 -*- # # pymfe documentation build configuration file, created by # sphinx-quickstart on Wed Nov 11 12:35:11 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named
'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.todo', 'sphinx.ext.imgmath', 'sphinx.ext.viewcode', 'numpydoc' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suff...
Kronuz/Xapiand
contrib/python/cuuid/mertwis.py
Python
mit
495
0
# -*- coding: utf-8 -*- # Mersenne Twister implementation from _random import Random import six class MT19937(object): def __init__(self, seed): mt = [0] *
624 mt[0] = p = seed & 0xffffffff for mti in six.moves.range(1, 624): mt[mti] = p = (1812433253 * (p ^ (p >> 30)) + mti) & 0xffffffff mt.append
(624) self.random = Random() self.random.setstate(tuple(mt)) def __call__(self): return self.random.getrandbits(32)
hcrlab/access_teleop
cse481wi18/perception/src/perception/mock_camera.py
Python
mit
858
0
import rosbag from sensor_msgs.msg import PointCloud2 def pc_filter(topic, datatype, md5sum, msg_def, header): if datatype == 'sensor_msgs/PointCloud2': return True return False class MockCamera(object): """A MockCamera reads saved point clouds. """ def __init__(self): pass ...
lf, path): """Returns the sensor_msgs/PointCloud2 in the given bag file. Args: path: string, the path to a bag file with a single sensor_msgs/PointCloud2 in it. Returns: A sensor_msgs/PointCloud2 message, or None if there were no
PointCloud2 messages in the bag file. """ bag = rosbag.Bag(path) for topic, msg, time in bag.read_messages(connection_filter=pc_filter): return msg bag.close() return None
TuSimple/simpledet
config/ms_r50v1_fpn_1x.py
Python
apache-2.0
10,314
0.003975
from symbol.builder import add_anchor_to_arg from models.FPN.builder import MSRAResNet50V1FPN as Backbone from models.FPN.builder import FPNNeck as Neck from models.FPN.builder import FPNRoiAlign as RoiExtractor from models.FPN.builder import FPNBbox2fcHead as BboxHead from mxnext.complicate import normalizer_factory ...
roi_extractor =
RoiExtractor(RoiParam) mask_roi_extractor = RoiExtractor(MaskRoiParam) bbox_head = BboxHead(BboxParam) mask_head = MaskHead(BboxParam, MaskParam, MaskRoiParam) bbox_post_processer = BboxPostProcessor(TestParam) maskiou_head = MaskIoUHead(TestParam, BboxParam, MaskParam) detector = Detector() ...
jd23/py-deps
lib/python/snakefood/flatten.py
Python
gpl-2.0
535
0.003738
""" Read a snakefood dependencies file and output the list of all files. """ # This file i
s part of the Snakefood open source package. # See http://furius.ca/snakefood/ for licensing details. import sys from os.path import join from snakefood.depends import read_depends, flatten_depends def main(): import optparse parser = optparse.OptionParser(__doc__.strip()) opts, args = parser.parse_arg...
drel)
dennisdarwis/dugem-backend
api/serializers.py
Python
apache-2.0
3,888
0.005916
from datetime import datetime from rest_framework import serializers from rest_framework.settings import api_settings from api.models import VenueList, EventList class VenueListSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) venue_name = serializers.CharField(max_length=255...
ted_data.get('venue_contact', instance.venue_contact) instance.venue_details = validated_data.get('venu
e_details', instance.venue_details) instance.venue_city = validated_data.get('venue_city', instance.venue_city) instance.save() return instance class EventListSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) venue_id = serializers.IntegerField(allow_nul...
Zolertia/openthread
tests/scripts/thread-cert/Cert_5_2_05_AddressQuery.py
Python
bsd-3-clause
5,385
0.000557
#!/usr/bin/python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # not...
rsdn') self.nodes[REED].add_whitelist(self.nodes[LEADER].get_addr64()) self.nodes[REED].add_whitelist(self.nodes[ROUTER2].get_addr64()) self.nodes[REED].set_router_upgrade_threshold(0) self.nodes[REED].enable_whitelist() self.nodes[ROUTER2].set_panid(0xface) self.nodes[R...
lf.nodes[ROUTER2].add_whitelist(self.nodes[REED].get_addr64()) self.nodes[ROUTER2].add_whitelist(self.nodes[ED2].get_addr64()) self.nodes[ROUTER2].add_whitelist(self.nodes[ED3].get_addr64()) self.nodes[ROUTER2].enable_whitelist() self.nodes[ROUTER2].set_router_selection_jitter(1) ...
Flamacue/pretix
src/tests/base/test_settings.py
Python
apache-2.0
11,458
0.000785
from datetime import date, datetime, time from decimal import Decimal from django.core.files import File from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TestCase from django.utils.timezone import now from i18nfield.strings impo...
Equal(s
elf.global_settings.settings.test, 'foo') # Reload object self.global_settings = GlobalSettingsObject() self.assertEqual(self.global_settings.settings.test, 'foo') def test_organizer_set_explicit(self): self.organizer.settings.test = 'foo' self.assertEqual(self.organizer.se...
saukrIppl/seahub
seahub/api2/endpoints/share_links.py
Python
apache-2.0
9,155
0.000983
import logging from constance import config from dateutil.relativedelta import relativedelta from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from rest_framework i...
Share.objects.create_file_link(username, repo_id, path,
password, expire_date) if is_org_context(request): org_id = request.user.org.org_id OrgFileShare.objects.set_org_file_share(org_id, fs) elif s_type == 'd': fs = FileShare.objects.get_dir_link_by_path(username, repo_id, path) ...
woogers/volatility
volatility/plugins/registry/registryapi.py
Python
gpl-2.0
12,244
0.009801
# Volatility # Copyright (C) 2008-2013 Volatility Foundation # Copyright (C) 2011 Jamie Levy (Gleeda) <[email protected]> # # This file is part of Volatility. # # Volatility 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 Softw...
" # What exception are we expecting here? except: name = "[no name]" self.all_offsets[hive.obj_offset] = name def reg_get_currentcontrolset(self, fullname = True): ''' get the CurrentControlSet If fullname is not specif...
need to verify before using. ''' for offset in self.all_offsets: name = self.all_offsets[offset] + " " if name.lower().find("\\system ") != -1: sysaddr = hivemod.HiveAddressSpace(self.addr_space, self._config, offset) if fullname: ...
opentrials/opentrials-airflow
dags/operators/postgres_to_s3_transfer.py
Python
mpl-2.0
3,091
0.001618
from urllib.parse import urlparse import subprocess impo
rt logging im
port boto3 import airflow.hooks.base_hook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults import utils.helpers as helpers class PostgresToS3Transfer(BaseOperator): '''Dumps a Postgres database to a S3 key :param url: URL to download. (templated) :type url: str...
sputnick-dev/weboob
contrib/plugin.video.videoobmc/resources/lib/test/common_test.py
Python
agpl-3.0
2,860
0.002105
# -*- coding: utf-8 -*- from __future__ import print_function import urllib def get_addon(): pass def get_translation(key): translation = {'30000': 'Recherche', '30001': 'Recherche :', '30100': 'Télécharger', '30110': 'Information', ...
e_plus(paramsDic[param]) else: url = "%s%s%s=%s" % (url, sep, param, paramsDic[param]) sep = '&' except Exception as msg: display_error("create_param_url %s" % msg) url = None return url def add_menu_item(params={}):
print('%s => "%s"' % (params.get('name'), create_param_url(params))) def add_menu_link(params={}): print('[%s] %s (%s)' % (params.get('id'), params.get('name'), params.get('url'))) #print params.get('itemInfoLabels') #print params.get('c_items') def end_of_directory(update=False): print('********...
ebursztein/SiteFab
SiteFab/parser/mistune.py
Python
gpl-3.0
35,424
0.000056
# coding: utf-8 """ mistune ~~~~~~~ The fastest markdown parser in pure Python with renderer feature. :copyright: (c) 2014 - 2016 by Hsiaoming Yang. """ import re import inspect __version__ = '0.7.3' __author__ = 'Hsiaoming Yang <[email protected]>' __all__ = [ 'BlockGrammar', 'BlockLexer', 'In...
ules: rules = self.default_rules def manipulate(text): for key in rules: rule = getattr(self.rules, key) m = rul
e.match(text) if not m: continue getattr(self, 'parse_%s' % key)(m) return m return False # pragma: no cover while text: m = manipulate(text) if m is not False: text = text[len(m.group(0)):]...
jianghuaw/nova
nova/objects/service.py
Python
apache-2.0
22,275
0.000045
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
ersion() # Version 1.20: Added get_
minimum_version_multi() # Version 1.21: Added uuid # Version 1.22: Added get_by_uuid() VERSION = '1.22' fields = { 'id': fields.IntegerField(read_only=True), 'uuid': fields.UUIDField(), 'host': fields.StringField(nullable=True), 'binary': fields.StringField(nullable=True...
nsdont/taiga-docker
events/conf.py
Python
mit
216
0
ho
st = "0.0.0.0" secret_key = "mysecret" repo_conf = { "kwargs": {"dsn": "dbname=taiga"} } queue_conf = { "path": "taiga_events.queues.pg.EventsQueue", "kwargs": {
"dsn": "dbname=taiga" } }
tusharmakkar08/TRIE_Data_Structure
serialize.py
Python
mit
1,972
0.040061
#!/usr/bin/env python # -*- coding: utf-8 -*- # # serialize.py # # Copyright 2013 tusharmakkar08 <tusharmakkar08@tusharmakkar08-Satellite-C660> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
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 this program; if not, write to the Fre...
02110-1301, USA. # # # Importing modules import cPickle _end = '_end_' # Implementation of Trie using Dictionaries in python def make_trie(words): root=dict() for i in words : cd=root for letter in i: cd=cd.setdefault(letter,{}) cd=cd.setdefault(_end,_end) return root def in_trie(trie,word): cd=trie...
postatum/nefertari-sqla
nefertari_sqla/fields.py
Python
apache-2.0
18,442
0.000108
from sqlalchemy.orm import relationship, backref from sqlalchemy.schema import Column, ForeignKey # Since SQLAlchemy 1.0.0 # from sqlalchemy.types import MatchType from .types import ( LimitedString, LimitedText, LimitedUnicode, LimitedBigInteger, LimitedInteger, LimitedSmallInteger, Limited...
args = ('length',) # Since SQLAlchemy 1.0.0 # class MatchField(BooleanField): # _sqla_type_cls = MatchType class DecimalField(ProcessableMixin, BaseField): _sqla_type_cls = LimitedNumeric _type_unchanged_kwargs = ( 'precision', 'scale', 'decimal_return_scale', 'asdecimal', 'min_value', 'm...
_sqla_type_cls = PickleType _type_unchanged_kwargs = ( 'protocol', 'pickler', 'comparator') class SmallIntegerField(ProcessableMixin, BaseField): _sqla_type_cls = LimitedSmallInteger _type_unchanged_kwargs = ('min_value', 'max_value') class StringField(ProcessableMixin, BaseField): _sqla_t...
Eulercoder/fabulous
setup.py
Python
gpl-3.0
1,273
0.002357
__author__ = 'vikesh' import os import sys try: from setuptools import
setup except ImportError: from distutils.core import setup PYTHON3 = sys.version_info[0] > 2 required = [] if not PYTHON3: required += ['importlib>=1.0.4'] packages = ['fabulous', 'fabulous.services'] try: longdesc = open('README.md').read() except: longdesc = '' setup( name='fabulous', ve...
m/Eulercoder/fabulous', packages=packages, scripts= ['bin/fabulous'], package_data={'': ['LICENSE',], '': ['fabulous/services/*.py']}, include_package_data=True, install_requires=required, license='BSD-3-Clause', classifiers=[ 'Development Status :: 5 - Production/Stable', 'I...
sckoh/cloudfire
python/cfcapp.py
Python
mit
5,964
0.032864
# import time from flask import Flask, json, request from flask.app import setupmethod from threading import Thread class DaemonThread(Thread): def start(self): self.daemon = True super(DaemonThread, self).start() class WSConnection(object): def __init__(self, app, wsid, fid): self.app = app self.fid = fid ...
d threa
d """ self.ws_background_tasks.append(f) return f def start_bg_tasks(self): ''' start long-lived background threads ''' for fn in self.ws_background_tasks: DaemonThread(name=fn.__name__, target=fn, args=[]).start()
matevzmihalic/wlansi-store
wlansi_store/models.py
Python
agpl-3.0
1,854
0.007012
from django.conf import settings from django.db import models as django_models from django.utils.translation import ugettext_lazy as _ from cms import models
as cms_models from djangocms_utils import fields as cms_fields from shop import models as shop_models from shop.util import fields as shop_fields from simple_translation import actions CMSPLUGIN_BLOG_PLACEHOLDERS = getattr(settings, 'CMSPLUGIN_BLOG_PLACEHOLDERS', ('excerpt', 'content')) class Product(shop_models.Pro...
olderActions(), placeholders=CMSPLUGIN_BLOG_PLACEHOLDERS) class Meta: pass def get_price(self): if self.price_set.count() > 0: return self.price_set.aggregate(django_models.Sum('price')).get('price__sum') return self.unit_price class ProductTitle(django_models.Mode...
ogrady/GoodMorning
util.py
Python
gpl-3.0
6,532
0.008114
import pygame import time import functools from pygame import locals from threading import Thread from enum import Enum ''' Utility classes and exceptions. version: 1.0 author: Daniel O'Grady ''' # CONSTANTS ALARMS_FILE = "alarms.json" CONFIG_FILE = "config.cfg" LOG_FILE = "goodmorning.log" # CONFIG DEFAULTS C_D...
ygame.locals.USEREVENT, pygame.locals.NUMEVENTS) class EventDispatcher(object): ''' Listener-like dispatcher for arbitrary events. Has a list of listeners one can register to. Each dispatcher expects all of its listeners to
have a certain method it dispatches events to. ''' def __init__(self, notify_method): self._listeners = [] self._notify_method = notify_method def add_listener(self, listener): if not hasattr(listener, self._notify_method): raise DispatcherException("Listener of...
isshe/Language
Python/20161127/11_unit_test_Dict.py
Python
gpl-3.0
868
0.008065
import unittest from mydict import Dict class TestDict(unittest.TestCase):
def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) self
.assertEqual(d.b, 'test') self.assertTrue(isinstance(d, dict)) def test_key(self): d = Dict() d['key'] = 'value' self.assertEqual(d.key, 'value') def test_attr(self): d = Dict() d.key = 'value' self.assertTrue('key' in d) self.ass...
Triv90/SwiftUml
swift/common/middleware/bulk.py
Python
apache-2.0
17,862
0
# Copyright (c) 2013 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
ng = True objs_to_delete = [] if req.content_length is None and \ req.headers.get('transfer-encoding', '').lower() != 'chunked': raise HTTPBadRequest('Invalid request: no content sent.') while data_remaining: if len(objs_to_delete) > self.max_deletes_per_
reques
mnach/suds-py3k
suds/transport/options.py
Python
lgpl-3.0
2,197
0.002276
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser 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 ...
B{headers} - Extra HTTP headers. - type: I{dict} - I{str} B{http} - The I{http} protocol proxy URL. - I{str} B{https} - The I{https} protocol proxy URL. - default: {} - B{username} - The username used for http authentication. ...
- B{password} - The password used for http authentication. - type: I{str} - default: None """ def __init__(self, **kwargs): domain = __name__ definitions = [ Definition('proxy', dict, {}), Definition('timeout', (int,float), 90), ...
jedie/django-cms-tools
django_cms_tools/plugin_landing_page/app_settings.py
Python
gpl-3.0
878
0.005695
""" :create: 2018 by Jens Diemer :copyleft: 2018 by the django-cms-tools team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ from django.conf import settings from django.utils.translation import ugettext_lazy as _ # Template used to render one landing pag...
PLATE = g
etattr(settings, "LANDING_PAGE_TEMPLATE", "landing_page/landing_page.html") # redirect user, e.g.: /en/langing_page/ -> / LANDING_PAGE_HIDE_INDEX_VIEW = getattr(settings, "LANDING_PAGE_HIDE_INDEX_VIEW", True) # Always expand toolbar or all links only if current page is the landing page app? LANDING_PAGE_ALWAYS_ADD_...
wwj718/ANALYSE
common/djangoapps/terrain/stubs/lti.py
Python
agpl-3.0
12,436
0.002493
""" Stub implementation of LTI Provider. What is supported: ------------------ 1.) This LTI Provider can service only one Tool Consumer at the same time. It is not possible to have this LTI multiple times on a single page in LMS. """ from uuid import uuid4 import textwrap import urllib import re from oauthlib.oauth...
ponse = requests.post(url, data=data, headers=headers, verify=False) self.server.grade_data['TC answer'] = response.content return response def _send_lti2_outcome(self): """ Send a grade back to consumer """ payload = textwrap.dedent(""" {{ "@contex...
awesome." }} """) data = payload.format(score=0.8) return self._send_lti2(data) def _send_lti2_delete(self): """ Send a delete back to consumer """ payload = textwrap.dedent(""" { "@context" : "http://purl.imsglobal.org/ctx/lis/v2/Re...
ghchinoy/tensorflow
tensorflow/compiler/tests/sparse_to_dense_op_test.py
Python
apache-2.0
4,522
0.007077
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
on(): x = sparse_ops.sparse_to_dense(2, [4], 7).eval() self.assertAllEqual(x, [0, 0, 7, 0]) def test3d(self): with self.session(), self.test_scope(): tf_ans = _SparseToDense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1, -1) np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1 np_ans[1, 3, 0] = 1 ...
2], [3], [4], [5], [6], [7], [8], [9]], [10], [1, 2, 3, 4, 5, 6, 7, 8], -1) self.assertAllClose([-1, -1, 1, 2, 3, 4, 5, 6, 7, 8], tf_ans) def testBadShape(self): with self.session(), self.test_scope(): with self.assertRaisesWithPredicateMatch(ValueError, "must be rank 1"):...
rhg/Qwibber
gwibber/microblog/plugins/statusnet/__init__.py
Python
gpl-2.0
9,075
0.012011
import re from gwibber.microblog import network, util import gnomekeyring from oauth import oauth from gwibber.microblog.util import log, resources from gettext import lgettext as _ log.logger.name = "StatusNet" PROTOCOL_INFO = { "name": "StatusNet", "version": 1.1, "config": [ "private:secret_token", ...
== self.account["username"].lower() m["to_me"] = m["recipient"]["is_me"] return m def _result(self, data): m = self._common(data) if data["to_user_id"]: m["reply"] = {} m["reply"]["id"] = data["to_user_id"] m["reply"]["nick"] = data["to_user"] m["sender"] = {}
m["sender"]["nick"] = data["from_user"] m["sender"]["id"] = data["from_user_id"] m["sender"]["image"] = data["profile_image_url"] m["sender"]["url"] = "/".join((self.account["url_prefix"], m["sender"]["nick"])) m["url"] = "/".join((self.account["url_prefix"], "notice", str(m["mid"]))) return m ...
badboy99tw/mass
mass/scheduler/swf/__init__.py
Python
apache-2.0
12,898
0.001085
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module implements mass worker by AWS SWF. """ # built-in modules from __future__ import print_function from functools import reduce, wraps from multiprocessing import Event, Process, Queue import json import signal import socket import sys import time import trac...
.dumps(traceback.format_exc())) else: self.complete(result) def execute(self): """Execute input of SWF workflow. """ type_ = 'Job' if 'Job' in self.handler.input else 'Task' parallel = self.handler.input[type_].get('parallel', False) for i, child
in enumerate(self.handler.input[type_]['children']): priority = get_priority(self.handler.input, self.handler.priority, i) if 'Task' in child: self.execute_task(child, priority) elif 'Action' in child and not child['Action']['_whenerror']: self.execute...
lpantano/bcbio-nextgen
bcbio/variation/vardict.py
Python
mit
15,244
0.004395
"""Sensitive variant calling using VarDict. Defaults to using the faster, equally sensitive Java port: https://github.com/AstraZeneca-NGS/VarDictJava if 'vardict' or 'vardict-java' is specified in the configuration. To use the VarDict perl version: https://github.com/AstraZeneca-NGS/VarDict specify 'vardict-perl'....
else: if not _is_bed_file(target): vcfutils.write_empty_vcf(tx_out_file, config, samples=[sample]) else: cmd
+= " > {tx_out_file}" do.run(cmd.format(**locals()), "Genotyping with VarDict: Inference", {}) if num_bams > 1: # N.B. merge_variant_files wants region in 1-based end-inclusive # coordinates. Thus use bamprep.region_to_gatk vcfutils.me...
moyogo/vanilla
Lib/vanilla/vanillaBox.py
Python
mit
4,498
0.002001
from AppKit import NSBox, NSColor, NSFont, NSSmallControlSize, NSNoTitle, NSLineBorder, NSBoxSeparator from vanilla.vanillaBase import VanillaBaseObject, _breakCycles, osVersionCurrent, osVersion10_10 class Box(VanillaBaseObject): """ A bordered container for other controls. To add a control to a box, s...
lla import * class BoxDemo(object): def __init__(self):
self.w = Window((150, 70)) self.w.box = Box((10, 10, -10, -10)) self.w.box.text = TextBox((10, 10, -10, -10), "This is a box") self.w.open() BoxDemo() No special naming is required for the attributes. However, each attribute must have a unique name. ...
candidtim/vagrant-appindicator
vgapplet/machineindex.py
Python
gpl-3.0
4,627
0.00389
# Copyright 2014, candidtim (https://github.com/candidtim) # # This file is part of Vagrant AppIndicator for Ubuntu. # # Vagrant AppIndicator for Ubuntu 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 v...
NU General Public License along with Foobar. # If not, see <http://www.gnu.org/licenses/>. ''' Parsers for Vagrant machine-index file ''' import os import json from gi.repository import Gio as gio __VAGRNAT_HOME_VAR = "VAGRANT_HOME" __MACHINE_INDEX_PATH = "data/machine-index/index" # module's public interfa
ce class Machine(object): def __init__(self, id, state, directory, name): self.id = id self.state = state self.directory = directory self.name = name def isPoweroff(self): return self.state == "poweroff" def isRunning(self): return self.state == "running" ...
kubeflow/kfctl
py/kubeflow/kfctl/testing/pytests/kfctl_upgrade_test.py
Python
apache-2.0
583
0.006861
import logging import os import pytest from kubernetes import client as k8s_client from kubeflow.kfctl.testing.util import kfctl_go_test_utils as kfctl_util from
kubeflow.testing import util def test_upgrade_kubeflow(record_xml_attribute, app_path, kfctl_path, upgrade_spec_path): """Test that we can run upgrade on a Kubeflow cluster. Args: app_path: The app dir of kubeflow deployment. kfctl_path: The path to kfctl binary. upgr
ade_spec_path: The path to the upgrade spec file. """ kfctl_util.kfctl_upgrade_kubeflow(app_path, kfctl_path, upgrade_spec_path)
vlegoff/mud
menu/validate_account.py
Python
bsd-3-clause
1,181
0.000848
""" This module contains the 'validate_account' menu node. """ from textwrap import dedent from menu.character import _options_choose_characters def validate_account(caller, input): """Prompt the user to enter the received validation code.""" text = "" options = ( { "key": "b", ...
b|n to choose a different e-mail address. """.strip("\n")).format(input.strip()) else: player.db.valid = True player.attributes.remove("validation_code") text = "" options = _options_choose_characters(player) return text, optio
ns
Geosyntec/pygridtools
pygridtools/__init__.py
Python
bsd-3-clause
140
0
from .misc import * from .core import * from . impor
t iotoo
ls from . import viz from . import validate from .tests import test, teststrict
avelino/bottle-boilerplate
setup.py
Python
mit
1,673
0.000598
#!/usr/bin/env python # -*- coding:utf-8 -*- from setuptools import setup REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()] classifiers = [ "Framework :: Bottle", 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Natural Langua...
=long_description, classifiers=classifiers, keywords='bottle boilerplate startproject doc', author="Thiago Avelino", author_email="[email protected]", url=url, download_url="{0}/tarball/master".format(url), license="MIT", install_requires=REQUIREMENTS, entry_points...
oilerplate.py'], include_package_data=True, zip_safe=False)
xguse/easygv
easygv/cli/__init__.py
Python
mit
5,459
0.000733
#!/usr/bin/env python """Provide command line interface to easygv.""" # Imports import logzero from logzero import logger as log import os from pathlib import Path import appdirs from munch import Munch import click import graphviz as gv from easygv.cli import config as _config from easygv import easygv # Meta...
default='attrs') @click.option('-p', '--prefix', type=click.STRING, help="""A prefix to identify the new config file(s).""",
show_default=True, default=None) @click.pass_context def config(ctx, generate_config, kind, prefix): """Manage configuration values and files.""" factory_resets = FACTORY_RESETS default_files = {"attrs": factory_resets / 'attrs.yaml'} if generate_config: if kind == ...
rosarior/mayan
apps/sources/__init__.py
Python
gpl-3.0
7,263
0.005783
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ from common.utils import encapsulate from documents.models import Document from documents.permissions import (PERMISSION_DOCUMENT_NEW_VERSION, PERMISSION_DOCUMENT_CREATE) from navigation.api import register_links, regis...
m_list', 'famfam': 'page_add', 'children_url_regex': [r'sources/setup'], 'permissions': [PERMISSION_SOURCES_SETUP_VIEW]} upload_version = {'text': _(u'upload new version'), 'view': 'upload_version', 'args': 'object.pk', 'famfam': 'page_add', 'permissions': [PERMISSION_DOCUMENT_NEW_VERS
ION]} register_links(StagingFile, [staging_file_delete]) register_links(SourceTransformation, [setup_source_transformation_edit, setup_source_transformation_delete]) #register_links(['setup_web_form_list', 'setup_staging_folder_list', 'setup_watch_folder_list', 'setup_source_create'], [setup_web_form_list, setup_sta...
HEP-DL/root2hdf5
root2hdf5/__init__.py
Python
gpl-3.0
117
0
# -*- coding: utf-8 -*- __author__ = """Kevin Wierman""" __email__ = 'kevin.wierman@
pnnl.gov' __version__ =
'0.1.0'
akeym/cyder
cyder/api/v1/endpoints/dhcp/static_interface/__init__.py
Python
bsd-3-clause
61
0
f
rom cyder.api.v1.endpoints.dhcp.static_interfac
e import api
Fizzadar/pyinfra
pyinfra/operations/gem.py
Python
mit
1,033
0
''' Manage Ruby gem packages. (see https://rubygems.org/ ) ''' from pyinfra.api import operation from pyinfra.facts.gem import GemPackages from .util.packaging import ensure_packages @operation def packages(packages=None, present=True, latest=False, state=None, host=None): ''' Add/remove/update gem packages...
ssumes that 'gem' is installed. gem.packages( name='Install rspec', packages=['rspec'], ) ''' yield ensure_packages( host, packages, host.get_fact(GemPackages), present, install_command='gem insta
ll', uninstall_command='gem uninstall', upgrade_command='gem update', version_join=':', latest=latest, )
crisely09/horton
horton/io/molpro.py
Python
gpl-3.0
5,611
0.00303
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2016 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+"," print >> f, ' ISYM=1' print >> f, ' &END' # Write integrals and core energy for i in xrange(nactive): for j in xrange(i+1): for k in xrange(nactive): for l in ...
value = two_mo.get_element(i,k,j,l) if value != 0.0: print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, k+1, l+1) for i in xrange(nactive): for j in xrange(i+1): value = one_mo.get_element(i,j) ...
pinntech/flask-logex
tests/base.py
Python
mit
1,058
0
"""Test Logex Initization and Error Handling""" import subprocess from unittest import TestCase from samples import app, api, logex from samples import bp_app, api_v1, api_v2, bp_logex class BaseTestCase(TestCase): DEBUG = True __blueprints__ = False @classmethod def setUpClass(cls): cls.a...
s.app = bp_app cls.api = [api_v1, api_v2] cls.logex = bp_logex # App test client, config, and context cls.log_name = cls.app.name + ".log" cls.app.config['DEBUG']
= cls.DEBUG cls.ac = cls.app.app_context() cls.test_client = cls.app.test_client() cls.test_client.testing = True cls.ctx = cls.app.test_request_context() cls.ctx.push() @classmethod def tearDownClass(cls): subprocess.call(['rm', '-rf', 'logs']) def setUp(se...