prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
ioninfo:doc_reviewed_at'])
db.create_index('application_submissioninfo',['doc_reviewed_at'])
def backwards(self, orm):
# Deleting field 'SubmissionInfo.doc_reviewed_at'
db.delete_column('application_submissioninfo', 'doc_reviewed_at')
db.delete_index('application_s... | ], {'related_name': "'personal_info'", 'unique': 'True', 'to': "orm['application.Applicant']"}),
'birth_date': ('django.db.models.fields.DateField', [], {}),
'ethnicity': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'id': ('django.db.models.fields.AutoField', [], ... | arField', [], {'max_length': '20'}),
'nationality': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'phone_number': ('django.db.models.fields.CharField', [], {'max_length': '35'})
},
'application.registration': {
'activation_key': ('django.db.models.f... |
#!/usr/bin/env python
""" project creation and deletion check for v3 """
# We just want to see any exception that happens
# don't want the script to die under any cicumstances
# script must try to clean itself up
# pylint: disable=broad-except
# pylint: disable=invalid-name
# pylint: disable=import-error
import argpa... | if delete_project_code == | 1:
# 1 means project deletion failed, the project still exists
# give the deletion second chance. 10 more seconds to check the
# teminating status project
delete_project(args)
delete_project_code = check_project(args)
if delete_project_code == 1:
... |
or this model."
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
... | context.update(extra_context or {})
has_file_field = self.has_file_field(form, formsets)
return self.render_change_form(request, context, form_url=form_url, add=True, has_file_field=has_file_field)
@csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, extr... | odel."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not ex... |
#!/usr/bin/env python
#
# $File: IfElseFixed.py $
#
# This file is part of simuPOP, a forward-time population genetics
# simulation environment. Please visit http://simupop.sourceforge.net
# for details.
#
# Copyright (C) 2004 - 2010 Bo Peng (bpeng@mdanderson.org)
#
# This program is free software: you can redistribut... | ave received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
| #
# This script is an example in the simuPOP user's guide. Please refer to
# the user's guide (http://simupop.sourceforge.net/manual) for a detailed
# description of this example.
#
import simuPOP as sim
pop = sim.Population(size=1000, loci=1)
verbose = True
pop.evolve(
initOps=[
sim.InitSex(),
si... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('builds', '0010_merge'),
]
operations = [
migrations.AlterField(
model_n | ame='project',
name='approved',
field=models.BooleanField(default=False, db_index=True),
preserve_default=True,
),
]
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | t it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with... | 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PyQtawesome(PythonPackage):
"""FontAwesome icons in PyQt and PySide applications"""
homepage = "https://github.com/spyder-ide/qtawesome"
url = "https://pypi.io/packages/... |
y_train)
svc_disp = plot_roc_curve(svc, X_test, y_test)
rfc_disp = plot_roc_curve(rfc, X_test, y_test, ax=svc_disp.ax_)
rfc_disp.figure_.suptitle("ROC curve comparison")
plt.show()
# %%
# Stacking Classifier and Regressor
# ---------------------------------
# :class:`~ensemble.StackingClassifier` and
# :class:`~ense... | turn pandas dataframe and thus
# properly handle datasets with heterogeneous data:
from sklearn.datasets import fetch_openml
titanic = fetch_openml('titanic', version=1, as_frame=True)
print(titanic.data.head()[['pclass', 'embarked']])
# %%
# Checking sc | ikit-learn compatibility of an estimator
# ---------------------------------------------------
# Developers can check the compatibility of their scikit-learn compatible
# estimators using :func:`~utils.estimator_checks.check_estimator`. For
# instance, the ``check_estimator(LinearSVC())`` passes.
#
# We now provide a `... |
m forces.
# Like that, langevin thermostat can still be used for non-drude
# particles
SI_temperature = 300.0
gamma_com = 1.0
kb_kjmol = 0.0083145
temperature_com = SI_temperature * kb_kjmol
# COULOMB PREFACTOR (elementary charge)^2 / (4*pi*epsilon_0) in
... | ssert_allclose(
ref_mu0_c2, eA_to_Debye * mu0_c2, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_mu0_c3, eA_to_Debye * mu0_c3, atol=atol, rtol=rtol)
np.testing.assert_allclose(
ref_mu0_bmim, eA_to_Debye * mu0_bmim, atol=atol, rtol=rtol)
pol_pf6 = []
... | gstrom / elementary charge
res = measure_pol(Efield, 0)
pol_pf6.append(res[0])
pol_bmim.append(res[1])
res = measure_pol(Efield, 1)
pol_pf6.append(res[0])
pol_bmim.append(res[1])
res = measure_pol(Efield, 2)
pol_pf6.append(res[0])
pol_bmim.appen... |
from functional_tests import FunctionalTest, ROOT, USERS
import time
from selenium.webdriver.support.ui import WebDriverWait
#element = WebDriverWait(driver, 10).until(lambda driver : driver.find_element_by_id("createFolderCreateBtn"))
class TestRegisterPage (FunctionalTest):
def setUp(self):
self.ur... | )
self.assertEqual(response_code, 200)
def test_has_right_title(self):
title = self.browser.title
#self.assertEqual(u'Net Decision Making: Registration', title)
self.assertIn('Networked Decision Making', title)
def test_put_values_in_reg... | st_name")
first_name = WebDriverWait(self, 10).until(lambda self : self.browser.find_element_by_name("first_name"))
first_name.send_keys(USERS['USER1'])
last_name = self.browser.find_element_by_name("last_name")
last_name.send_keys(USERS['USER1'])
... |
# DarkCoder
def sum_of_series(first_term, commo | n_diff, num_of_terms):
"""
Find the sum of n terms in an arithmetic progression.
>>> sum_of_series(1, 1, 10)
55.0
>>> sum_of_series(1, 10, 100)
496 | 00.0
"""
sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff)
# formula for sum of series
return sum
def main():
print(sum_of_series(1, 1, 10))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
import operator
import time
# Only the vertex (and its hamming distance is given)
# Need to find all vertices which are within a hamming distance of 2
# That means for each vertex, generate a list of 300 other vertices (24 bits + 23 + 22 + ... + 1)
# which are with hamming distance of 2 (generate vertices with 2 bit... | h b
# instead make b point to c's root. That way a's parent will be b and b's will be d
# which will now become the root of b/a and continue to be the roo | t of c thus the cluster
return
if __name__ == '__main__':
i = 0
with open('clustering_big.txt') as f:
no_v, bits = [int(x) for x in f.readline().split()]
for line in f: # read rest of lines
temp = [str(x) for x in line]
temp = [num.strip() for num in temp]
temp = filter(None, temp)
temp = ''.join(m... |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
# pygtail - a python "port" of logtail2
# Copyright (C) 2011 Brad Greenlee <brad@footle.org>
#
# Derived from logcheck <http://logcheck.org>
# Copyright (C) 2003 Jonathan Middleton <jjm@ixtab.org.uk>
# Copyright (C) 2001 Paul Slootman <paul@debian.org>
#
# This program is ... | oftware Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# al... |
# -*- coding: utf-8 -*-
"""
A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a
procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative
process.
"""
from operator import lt, sub, add, mul
de... | hapter1.exercise1_11 import f_recursive")
timer_iter = Timer(stmt="f_iterative(%(n)s)" % locals(), setup="from Chapter1.exercise1_11 import f_iterative")
print(
'Mean execution time:',
'\t-(f-recursive %(n)s): { | }'.format(timer_rec.timeit()) % locals(),
'\t-(f-iterative %(n)s): {}'.format(timer_iter.timeit()) % locals(),
sep='\n',
)
print('-' * 20)
if __name__ == '__main__':
run_the_magic()
|
__author__ = 'ronalddekker'
# imports
from xml.dom.pulldom import START_ELEMENT, parse
from xml.dom.minidom import NamedNodeMap
def segmentate_xml_file(xml_file):
# parse the file, XML event after XML event
# NOTE: the variable name 'doc' is not optimal (the variable is only a pointer to a stream of events)
... | ode.localName == "div" and node.attributes["type"].value == "act":
print(event, node.localName, node.attributes["type"].value, node.attributes.items())
segment += 1
yield(event, node, doc, segment)
# We define a function which tells the computer what to do when an act is encountere... | filename="/Users/ronalddekker/Desktop/CollateX/Elisa Files/1823_act_"):
for (event, node, doc, segment) in segmentate_xml_file(xml_file):
doc.expandNode(node)
# print("Act "+str(act)+" contains: "+str(node.toxml()))
segment_xml_file = open(filename +str(segment)+... |
import unittest
from clandestined import RendezvousHash
class RendezvousHashTestCase(unittest.TestCase):
def test_init_no_options(self):
rendezvous = RendezvousHash()
self.assertEqual(0, len(rendezvous.nodes))
self.assertEqual(1361238019, rendezvous.hash_function('6666'))
def test_... | elf.assertEqual(2, len(rendezvous.nodes))
self.assertRaises(ValueError, rendezvous.remove_node, '2')
self | .assertEqual(2, len(rendezvous.nodes))
rendezvous.remove_node('1')
self.assertEqual(1, len(rendezvous.nodes))
rendezvous.remove_node('0')
self.assertEqual(0, len(rendezvous.nodes))
def test_find_node(self):
nodes = ['0', '1', '2']
rendezvous = RendezvousHash(nodes=no... |
#!/usr/bin/env python
import ast
import atexit
from codecs import open
from distutils.spawn import find_executable
import os
import sys
import subprocess
import setuptools
import setuptools.command.sdist
from setuptools.command.test import test
HERE = os.path.abspath(os.path.dirname(__file__))
setuptools.command.sdi... | lcov', 'index.html')]))
PyTest.run_tests(self)
class CmdSt | yle(setuptools.Command):
user_options = []
CMD_ARGS = ['flake8', '--max-line-length', '120', '--statistics', NAME_FILE + ('' if PACKAGE else '.py')]
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
subprocess.call(self.CMD_ARGS)
class Cm... |
from datetime import date
from rest_framework import status as status_code
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from app.models import Passphrase, SlackUser
from pantry.models import Pantry
class PantryViewSet(viewsets.ViewSet)... | fully authenticated."}
return Response(content, stat | us=status_code.HTTP_200_OK)
@action(methods=["get"], url_path="report", detail=False)
def report(self, request):
reportDate = request.GET.get("date", date.today())
queryset = self.queryset.filter(date=reportDate).order_by("date")
content = {
"status": "success",
... |
#!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatib... | if not trans:
trans = Dummy | Transaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-29 13:51
from __future__ import unicode_literals
from django.db import | migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0054_add_field_user_to_productionform'),
]
operations = [
migrations.AddField(
model_name='applicationform',
name='requires_development',
field=models.BooleanField( | default=False, verbose_name='requires_development'),
),
]
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import pwd
import stat
import time
import os.path
import logging
def root_dir():
root_dir = os.path.split(os.path.realpath(__file__))[0]
return root_dir
def get_logger(name):
def local_date():
return str(time.strftime("%Y-%m-%d"... | ''
def wapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time() |
print("execute %s used time:%.2f s" % (func.__name__, (end - start)))
return result
return wapper
def elapsetime(ostream=sys.stdout):
'''wapper for elapse time for function'''
def decorator(func):
def wapper(*args, **kwargs):
start = time.time()
result = f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import db
from datetime imp | ort datetime
class User(db.Model):
__table_args__ = {
'mysql_engine': 'InnoDB | ',
'mysql_charset': 'utf8mb4'
}
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
openid = db.Column(db.String(32), unique=True, nullable=False)
nickname = db.Column(db.String(32), nullable=True)
realname = db.Column(db.String(32), nullable=True)
classname = db.Column(db.... |
# -*- coding: utf-8 -*-
# (c) 2015 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
from kotori.version import __VERSION__
from pyramid.config import Configurator
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
settings['SOFTWARE_VERSION'] = __VERSION__
confi... | # Addons
config.include('pyramid_jinja2')
# http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/#adding-or-overriding-a-renderer
config.add_jinja2_renderer('.html')
config.include('cornice')
# Views and routes
config.add_static_view('static/app', 'static/app', cache_max_age=0)
... | /lib', 'static/lib', cache_max_age=60 * 24)
config.add_route('index', '/')
config.scan()
return config.make_wsgi_app()
|
import logging
import os
import re
import sys
import time
import warnings
import ConfigParser
import StringIO
import nose.case
from nose.plugins import Plugin
from sqlalchemy import util, log as sqla_log
from sqlalchemy.test import testing, config, requires
from sqlalchemy.test.config import (
_create_testing_eng... | opt("--d | buri", action="store", dest="dburi",
help="Database uri (overrides --db)")
opt("--dropfirst", action="store_true", dest="dropfirst",
help="Drop all tables in the target database first (use with caution on Oracle, "
"MS-SQL)")
opt("--mockpool", action="store_true", des... |
right (c) 2013-TODAY OpenERP S.A. <http://www.openerp.com>
#
# 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 v... | ptions import AccessError
from openerp.exceptions import Validati | onError
from openerp.tools import mute_logger
class TestHolidaysFlow(TestHrHolidaysBase):
@mute_logger('openerp.addons.base.ir.ir_model', 'openerp.models')
def test_00_leave_request_flow(self):
""" Testing leave request flow """
cr, uid = self.cr, self.uid
def _check_holidays_status(h... |
# -*- coding: utf-8 -*-
# Copyright (c) 2009 - 2014 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog to enter the connection parameters.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QDialogButtonBox
from PyQt5.QtSql ... | lf.driverCombo.currentText()
if driver.startswith("QSQLITE"):
self.databaseEdit.setCompleter(self.databaseFileCompleter)
self.databaseFileButton.setEnabled(True)
else:
self.databaseEdit.setCompleter(None)
self.databaseFileButton.setEnabled(False)
... |
@pyqtSlot(str)
def on_driverCombo_activated(self, txt):
"""
Private slot handling the selection of a database driver.
@param txt text of the driver combo (string)
"""
self.__updateDialog()
@pyqtSlot(str)
def on_databaseEdit_textChanged(self, tx... |
from werkzeug.exceptions import NotFound
from werkzeug.utils import redirect
from .models import URL
from .utils import expose
from .utils import Pagination
from .utils import render_template
from .utils import url_for
from .utils import validate_url
@expose("/")
def new(request):
error = url = ""
if request... | error=error, url=url)
@expose("/display/<uid>")
def display(request, uid):
url = URL.load(uid)
if not url:
raise NotFound()
return render_template("display.html", url=url)
@expose("/u/<uid>")
def link(request, uid):
url = URL.load(uid)
if not url:
raise NotFound()
return red... | .id
return URL.wrap(data)
code = """function(doc) { if (doc.public){ map([doc._id], doc); }}"""
docResults = URL.query(code)
results = [wrap(doc) for doc in docResults]
pagination = Pagination(results, 1, page, "list")
if pagination.page > 1 and not pagination.entries:
raise NotFoun... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
cc_plugin_ncei/ncei_trajectory.py
'''
from compliance_checker.base import BaseCheck
from cc_plugin_ncei.ncei_base import TestCtx, NCEI1_1Check, NCEI2_0Check
from cc_plugin_ncei import util
from isodate import parse_duration
class NCEITrajectoryBase(BaseCheck):
_c... | 0 and CF version 1.6. You '
'can f | ind more information about the version 1.1 templates at https://www.nodc.noaa.gov/'
'data/formats/netcdf/v1.1/. This test is specifically for the trajectory feature type '
'in an Incomplete multidimensional array representation. This representation is typically '
'used for a series of data point... |
from selenium.common.exceptions import NoSuchElementException
from .base import FunctionalTest, login_test_user_with_browser
class EditPostTest(FunctionalTest):
@login_test_user_with_browser
def test_modify_post(self):
self.browser.get(self.live_server_url)
self.move_to_default_board()
... | x.clear()
contentbox.send_keys('Hello django')
self.browser.switch_to.default_content()
# 실수로 '취소' 버튼을 누른다.
self.browser.find_element_by_id('id_cancel_button').click()
# 제목과 내용이 변경되지 않고 그대로이다.
tit | lebox = self.browser.find_element_by_class_name('panel-title')
self.assertEqual(titlebox.text, 'pjango')
content = self.browser.find_element_by_class_name('panel-body')
self.assertIn('Hello pjango', content.text)
# 다시 수정 버튼을 클릭하여 내용을 수정한다.
edit_button = self.browser.find_elemen... |
from ..widget import Widget
def category_widget(value, title=None, description=None, footer=None, read_only=False, weight=1):
"""Helper function for quickly creating a category widget.
Args:
value (str): Column name of the category value.
title (str, optional): Title of widget.
descri... | t.
weight (int, optional): Weight of the category widget. Default value is 1.
Returns:
cartoframes.viz.widget.Widget
Example:
>>> category_widget(
... 'column_name',
... title='Widget title',
... description='Widget description',
... foot... | er')
"""
return Widget('category', value, title, description, footer,
read_only=read_only, weight=weight)
|
class UserInfoModel(object):
PartenaireID = 0
Mail = ""
CodeUtilisateur = ""
TypeAbonnement = ""
DateExpiration = ""
DateSouscription = ""
AccountExist = False
| def _ | _init__(self, **kwargs):
self.__dict__.update(kwargs)
def create_dummy_model(self):
self.Mail = "dummy@gmail.com"
self.CodeUtilisateur = "dummy1234"
self.AccountExist = True
self.PartenaireID = 0
|
from __future__ import absolute_import
import re
__all__ = [
'_SGML_AVAILABLE',
'sgmllib',
'charref',
'tagfind',
'attrfind',
'entityref',
'incomplete',
'interesting',
'shorttag',
'shorttagopen',
'starttagopen',
'endbracket',
]
# sgmllib is not available by default in P... | pass
else:
_SGML_AVAILABLE = 1
# sgmllib defines a number of module-level regular expressions that are
# insufficient for the XML parsing feedpar | ser needs. Rather than modify
# the variables directly in sgmllib, they're defined here using the same
# names, and the compiled code objects of several sgmllib.SGMLParser
# methods are copied into _BaseHTMLProcessor so that they execute in
# feedparser's scope instead of sgmllib's scope.
charref = ... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verify the settings that cause a set of programs to be created in
a specific build directory, and that no intermediate built fil... | irectory (through GYP_GENERATOR_FLAGS 'output_dir'), rather than
# gyp-file-specific settings (e.g. the stuff in builddir.gypi) that the other
# generators support, so this doesn't work yet for make.
# TODO(mmoss) Make also has the issue that the top-level Makefile is written to
# the "--depth" location, which is | one level above 'src', but then this test
# moves 'src' somewhere else, leaving the Makefile behind, so make can't find
# its sources. I'm not sure if make is wrong for writing outside the current
# directory, or if the test is wrong for assuming everything generated is under
# the current directory.
# Ninja and C... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Basic tests for Cerebrum.Entity.EntitySpread. """
import pytest
@pytest.fixture
def entity_spread(Spread, entity_type):
code = Spread('f303846618175b16',
entity_type,
description='Test spread for entity_type')
code.insert()
... | th different sets of spreads. """
entities = list()
spread_dist = [
(),
(entity_spread, ),
(entity_spread, entity_spread_alt, ),
(entity_spread_alt, ), ]
for spreads in spread_dist:
| try:
entry = dict()
entity_obj.populate(entity_type)
entity_obj.write_db()
for spread in spreads:
entity_obj.add_spread(spread)
entry = {
'entity_id': entity_obj.entity_id,
'entity_type': entity_obj.entity_type,... |
s', nargs=1,
help='List of phased pairs (use - for stdin).')
parser.add_argument('--buffer',
default=1000, action='store', type=int,
help='''
Number of pairs to read in before processing a batch of connected
components. The default should be a good c... | lse:
n_phase = phase2[1],phase1[1]
if n.phased:
if n.alleles != n_phase:
print >> sys.stderr, "Inconsistent ph | asing:",
print >> sys.stderr, n.alleles, "!=",
print >> sys.stderr, n_phase
print >> sys.stderr, graph[0].chrom,
print >> sys.stderr, [x.pos for x in graph]
raise InconsistentComponent
else:
n... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestHomePage(TestCase):
def test_uses_index_template(self):
response = self.client.get(reverse("home"))
self.assertTemplateUsed(re | sponse, "home/index.html")
| def test_uses_base_template(self):
response = self.client.get(reverse("home"))
self.assertTemplateUsed(response, "base.html")
|
def extract17LiterarycornerWordpressCom(item):
'''
Parser for '17literarycorner.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('King Of Hell\'s Genius Pampered Wife', | 'King Of Hell\'s Genius Pampered Wife', 'translated'),
('KOH', 'King Of Hell\'s Genius Pampered Wife', 'translated'),
('Addicted to Boundlessly Pampering You', 'Addicted to Boundlessly Pampering You', | 'translated'),
('ATBPY', 'Addicted to Boundlessly Pampering You', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item... |
#!/usr/bin/env python2
# Copyright (c) 2013-2014 The Bitcredit Core developers
# Distributed under the MIT soft | ware license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
BUILDDIR="/root/2.0/dragos/bitcredit-2.0"
EXEEXT=".exe"
# These will turn i | nto comments if they were disabled when configuring.
ENABLE_WALLET=1
ENABLE_UTILS=1
ENABLE_BITCREDITD=1
#ENABLE_ZMQ=1
|
#!/usr/bin/python
#Covered by GPL V2.0
from encoders import *
from payloads import *
# generate_dictio evolution
class dictionary:
def __init__(self,dicc=None):
if dicc:
self.__payload=dicc.getpayload()
self.__encoder=dicc.getencoder()
else:
self.__payload=payload()
self.__encoder = [lambda x: en... | ad:
dicc.append(self.__encoder.encode(i))
return dicc
def __iter__(self):
self.restart()
return self
def gen(self):
while 1:
pl=self.iter.next()
for encode in self.__encoder:
yield encode(pl)
def next(self):
return self.generator.next()
def restart(self):
self.iter=self.__payload.__i... | tor = self.gen()
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
if head is None:
return head
res = None
res_end = Non... | None
temp_end = None
i = 1
while head is not None:
next_node = head.next
# Append current node to temp list
if temp is None:
temp_end = head
head.next = temp
temp = head
if i % 2 == 0:
# Appe... | mp_end
else:
res_end.next = temp
res_end = temp_end
temp = None
i += 1
head = next_node
if temp is not None:
if res is None:
res = temp
res_end = temp_end
else:... |
#!/usr/bin/env python
"""
Copyright 2012 GroupDocs.
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... | e 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.
"""
class ChangesResponse:
"""
NOTE: This class is auto generated by the swag... | ,
'error_message': 'str',
'composedOn': 'int'
}
self.result = None # ChangesResult
self.status = None # str
self.error_message = None # str
self.composedOn = None # int
|
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Akretion
# (<http://www.akretion.com>).
#
# 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 t | he 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 ... |
from PySide import QtCore, QtGui
class MakinFrame(QtGui.QFrame):
mousegeser = QtCore.Signal(int,int)
def __init__(self,parent=None):
super(MakinFrame,self).__init__(parent)
self.setMouseTracking(True)
def setMouseTracking(self, flag):
def recursive_set(parent):
for child in parent.findChildren(QtCore.QObj... | setMouseTracking(flag)
except:
pass
recursive_set(child)
QtGui.QWidget.setMouseTracking(self,flag)
recursive_set(self)
def mouseMoveE | vent(self, me):
a = QtGui.QFrame.mouseMoveEvent(self,me)
self.mousegeser.emit(me.x(), me.y())
return a
|
#!/usr/bin/env python2
# Copyright (C) 2013-:
# Gabes Jean, naparuba@gmail.com
# Pasche Sebastien, sebastien.pasche@leshop.ch
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software withou... | continue
#if we specify a list of mountpoints to check then verify that current line is in the | list
to_check = True
if MOUNTS:
to_check = False
for mnt in MOUNTS:
if tmp[6].startswith(mnt):
to_check = True
# Maybe this mount point did not match any required mount point
if not to_check:
continue
... |
#!/usr/bin/env python
# coding: utf-8
#
# Copyright 2016, Marcos Salomão.
#
# 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 require... | se(unittest.TestCase):
""" Test Case for Purchases.
"""
| def test_purchases_statistics_by_products(self):
""" Unit test to get purchases statistics by products.
"""
# Sales list
purchasesList = []
# Mock purchase model and products models
purchasesMock = [{
'id': 1,
'product_id': 1,
... |
from sympy.core.numbers import comp, Rational
from sympy.physics.optics.utils import (refraction_angle, fresnel_coefficients,
deviation, brewster_angle, critical_angle, lens_makers_formula,
mirror_formula, lens_formula, hyperfocal_distance,
transverse_magnification)
from sympy.physics.optics.med... | ens_formula(u=u, v=oo) == -u
assert lens_formula(focal_length=oo, v=oo) is -oo
assert lens_formula(focal_length=oo, v=v) == v
assert lens_formula(focal_length=f, v=oo) == -f
assert lens_formula(focal_length=oo, u=oo) is oo
assert lens_formula(focal_length | =oo, u=u) == u
assert lens_formula(focal_length=f, u=oo) == f
raises(ValueError, lambda: lens_formula(focal_length=f, u=u, v=v))
def test_hyperfocal_distance():
f, N, c = symbols('f, N, c')
assert hyperfocal_distance(f=f, N=N, c=c) == f**2/(N*c)
assert ae(hyperfocal_distance(f=0.5, N=8, c=0.0033), ... |
import os
import numpy as np
from csv import reader
from collections import defaultdict
from common import Plate
from pprint import pprint
def hung_ji_adapter():
folder_ = 'C:/Users/ank/Desktop'
file_ = 'HJT_fittness.csv'
dose_curves = {}
with open(os.path.join(folder_, file_)) as source_file:
... | defaultdict(lambda:defaultdict(Plate))
for line in source_:
dose, time, col, row, intensity = line
| plate = dose2data_frame[dose][time]
plate.set_elt(row, col, intensity)
for dose, timedict in dose2data_frame.iteritems():
bound_tuple = [[], []]
dose_curves[dose] = bound_tuple
for time in sorted(timedict.keys()):
bound_tuple[0].append(time)
... |
from __future__ import print_function, division
from time import time
import argparse
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.datasets import fetch_20newsgroups_vectorized
from sklearn.metrics import accuracy_score
from sklearn.utils.validation import check_array
from sklearn.ensemb... | Classification performance:")
print("===========================")
print()
print("%s %s %s %s" % ("Classifier ", "train-time", "test-time",
"Accuracy"))
print("-" * 44)
for nam | e in sorted(accuracy, key=accuracy.get):
print("%s %s %s %s" % (name.ljust(16),
("%.4fs" % train_time[name]).center(10),
("%.4fs" % test_time[name]).center(10),
("%.4f" % accuracy[name]).center(10)))
print()
|
'''
SAPI 5+ driver.
Copyright (c) 2009 Peter Parente
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS... | ream, pos):
d = self._driver
if d._speaking:
d._proxy.notify('finish | ed-utterance', completed=not d._stopping)
d._speaking = False
d._stopping = False
d._proxy.setBusy(False) |
_fill_value=self._default_fill_value).__finalize__(self)
def _reindex_columns(self, columns, copy, level, fill_value, limit=None,
takeable=False):
if level is not None:
raise TypeError('Reindex by level not supported for sparse')
if notnull(fill_value):
... | mns overlap but no suffix specified: %s'
% to_rename)
def lrenamer(x):
if x in to_rename:
return '%s%s' % (x, lsuffix)
return x
de | f rrenamer(x):
if x in to_rename:
return '%s%s' % (x, rsuffix)
return x
this = self.rename(columns=lrenamer)
other = other.rename(columns=rrenamer)
else:
this = self
return this, other
def transpose(self, *arg... |
#https://raw.githubusercontent.com/AaronJiang/ProjectEuler/master/py/problem072.py
"""
Consider the fraction, n/d, where n and d are positive integers.
If n<d and HCF(n,d)=1, it is called a reduced proper fractio | n.
If we list the set of reduced proper fractions for d <= 8 in
ascending order of size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, | 3/7, 1/2, 4/7,
3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
It can be seen that there are 21 elements in this set.
How many elements would be contained in the set of reduced proper
fractions for d <= 1,000,000?
"""
# Euler totient function phi(n):
# counts the number of positive integers less than or equal
# to n ... |
"""
.. moduleauthor:: Chris Dusold <DriveLink@chrisdusold.com>
A module containing general purpose, c | ross instance hashing.
This module intends to make storage and cache checking stable accross instances.
"""
from drivelink.hash._hasher import hash
from drivelink.hash._hasher import frozen_hash
from drivelink.hash._hasher impo | rt Deterministic_Hashable
|
the
# later tests, and the tests that check for this warning fail
assert_warns(DataConversionWarning, clf.fit, X, y_)
assert_array_equal(clf.predict(T), true_result)
assert_equal(100, len(clf.estimators_))
def test_mem_layout():
# Test with different memory layouts of X and y
X_ = np.asfortra... | eater(score, 0.9)
assert_equal(clf.oob_improvement_.shape[0], clf.n_estimators)
# hard-coded regression test - change if modification in OOB computation
# FIXME: the following snippet does not yield the same results on 32 bits
# assert_array_almost_equal(clf.oob_improvement_[:5],
# ... | .externals.six.moves import cStringIO as StringIO
import sys
old_stdout = sys.stdout
sys.stdout = StringIO()
clf = GradientBoostingClassifier(n_estimators=100, random_state=1,
verbose=1, subsample=0.8)
clf.fit(X, y)
verbose_output = sys.stdout
sys.stdout ... |
# So we would bail out here for static passwords.
log.warning("No public ID in line {0!r}".format(line))
continue
serial_int = int(binascii.hexlify(modhex_decode(public_id)),
16)
if typ.lower() == "yubico otp":
... | tag = getTagName(elem_tdata)
if "ProductName" == tag:
DESCRIPTION = elem_tdata.text
log.debug("The Token with the serial %s has the "
"productname %s" % (SERIAL, DESC | RIPTION))
if "Applications" == tag:
for elem_apps in elem_tdata:
if getTagName(elem_apps) == "Application":
for elem_app in elem_apps:
tag = getTagName(elem_app)
if "Se... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 20:41:02 2017
@a | uthor: jacoblashner
"""
import numpy as np
import matplotlib.pyplot as plt
ae | = lambda nu : 1.47*10**(-7) * nu**(2.2)
ao = lambda nu : 8.7*10**(-5)*nu+3.1*10**(-7)*nu**2 + 3.0*10**(-10)*nu**3
d = .3 #cm
ee = lambda nu : (1 - np.exp(ae(nu) * d))
eo = lambda nu : (1 - np.exp(ao(nu) * d))
freqs = np.linspace(60, 240)
plt.plot(freqs, map(ae, freqs))
plt.plot(freqs, map(ao, freqs))
plt.show()
... |
import sys, os
from tempfile import TemporaryDirectory
import pytest
import multiprocessing
from spinalcordtoolbox.utils import sct_test_path, sct_dir_local_path
sys.path.append(sct_dir_local_path('scripts'))
from spinalcordtoolbox import resampling
import spinalcordtoolbox.reports.qc as qc
from spinalcordtoolbox.im... | reports.slice as qcslice
def gen_qc(args):
i, path_qc = args
t2_image = sct_test_path('t2', 't2.nii.gz')
t2_seg = sct_test_path('t2', 't2_seg-manual.nii.gz')
qc.generate_qc(fname_in1=t2_image, fname_seg=t2_seg, path_qc=path_qc, process="sct_deepseg_gm")
return True
def test_many_qc():
"""T... | iour")
with TemporaryDirectory(prefix="sct-qc-") as tmpdir:
# install: sct_download_data -d sct_testing_data
with multiprocessing.Pool(2) as p:
p.map(gen_qc, ((i, tmpdir) for i in range(5)))
|
#!/usr/bin/env python
# en | coding: utf-8
from .user import *
from .upload import *
from .post import *
from .system import *
def all():
result = []
models = []
for m in models:
result += m.__all_ | _
return result
__all__ = all()
|
from PIL import Image
import sys
def resize(img, baseheight, newname):
hpercent = (baseheight / float(img.size[1]))
wsize = int((float(img.size[0]) * float(hpercent)))
img = img.resize((wsize, baseheight), Image.ANTIALIAS)
img.save(newname)
def | makethumbnails(fname):
img = Image.open(fname)
x1 = fname.replace('.png', 'x1.png')
resize(img, 200, x1)
x15 = fname.replace('.png', 'x1.5.png')
resize(img, 300, x15)
x2 = fname.replace('.png', 'x2.png')
| resize(img, 400, x2)
|
"""
Empirical Likelihood Linear Regression Inference
The script contains the function that is optimized over nuisance parameters to
conduct inference on linear regression parameters. It is called by eltest
in OLSResults.
General References
-----------------
Owen, A.B.(2001). Empirical Likelihood. Chapman and Hall... | __(self):
pass
def _opt_nuis_regress(self, nuisance_params, param_nums=None,
endog=None, exog=None,
nobs=None, nvar=None, params=None, b0_vals=None,
stochastic_exog=None):
"""
A function that is optimized over nui... | meters to be optimized over
Returns
-------
llr : float
-2 x the log-likelihood of the nuisance parameters and the
hypothesized value of the parameter(s) of interest.
"""
params[param_nums] = b0_vals
nuis_param_index = np.int_(np.delete(np.arange(... |
import _plotly_utils.basevalidators
class SideValidator(_plotly_utils.basevali | dators.EnumeratedValidator):
def __init__(
self,
plotly_name="side",
parent_name="scattergeo.marker.colorbar.title",
**kwargs
):
super(SideValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop... | =kwargs.pop("role", "style"),
values=kwargs.pop("values", ["right", "top", "bottom"]),
**kwargs
)
|
from __future__ import absolute_import
from __future__ import division
# Copyright (c) 2010-2017 openpyxl
import math
#constants
DEFAULT_ROW_HEIGHT = 15. # Default row height measured in point size.
BASE_COL_WIDTH = 13 # in characters
DEFAULT_COLUMN_WIDTH = 51.85 # in points, should be characters
DEFAULT_LEFT_MA... |
From the ECMA Spec (4th Edition part 1)
Page setup: "Left Page Margin in inches" p. 1647
Docs from
http://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/
See also http://ms | dn.microsoft.com/en-us/library/dd560821(v=office.12).aspx
dxa: The main unit in OOXML is a twentieth of a point. Also called twips.
pt: point. In Excel there are 72 points to an inch
hp: half-points are used to specify font sizes. A font-size of 12pt equals 24 half points
pct: Half-points are used to specify font size... |
# -*- coding: utf-8 -*-
# Copyright(C) 2012 Romain Bignon
#
# This file is part of weboob.
#
# weboob 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 opti... | elf):
return u'<HousingPhoto "%s" data=%do>' % (self.id, len(self.data) if self.data else 0)
class Housing(CapBaseObject):
"""
Content of a housing.
"""
title = StringField('Title of housing')
area = DecimalField('Area of housing, in m2')
cost = DecimalField('C... | of cost')
date = DateField('Date when the housing has been published')
location = StringField('Location of housing')
station = StringField('What metro/bus station next to housing')
text = StringField('Text of the housing')
phone = StringField('Phone number to con... |
# -*- encoding:utf8 -*-
"""
使用mongodb作为缓存器
测试本地缓存
"""
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
from pymongo import MongoClient
from datetime import datetime, timedelta
from bson.binary import Binary
import zlib
import time
class MongoCache:
def __init__(self, client=None, expires=timedelt... | onnect=False)
# 使用cache作为缓存的collection
self.db = self | .client.cache
# cache过期后自动删除
self.db.webpage.create_index('timestamp', expireAfterSeconds=expires.total_seconds())
def __contains__(self, url):
try:
self[url]
except KeyError:
return False
else:
return True
def __getitem__(self, url):... |
"""
"""
import traceback
from AnyQt.QtWidgets import QWidget, QPlainTextEdit, QVBoxLayout, QSizePolicy
from AnyQt.QtGui import QTextCursor, QTextCharFormat, QFont
from AnyQt.QtCore import Qt, QObject, QCoreApplication, QThread, QSize
from AnyQt.QtCore import pyqtSignal as Signal
class TerminalView(QPlainTextEdit):
... | def flush(self):
| pass
def writeWithFormat(self, string, charformat):
self.__text.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
self.__text.setCurrentCharFormat(charformat)
self.__text.insertPlainText(string)
def writelinesWithFormat(self, lines, charformat):
self.writeWithFormat("".... |
import numpy as np
import load_data
from generative_alg import *
from keras.utils.generic_utils import Progbar
from load_data import load_word_indices
from keras.preprocessing.sequence import pad_sequences
import pandas as pa
import augment
def test_points(premises, labels, noises, gtest, cmodel, hypo_len):
p = P... | e(string, wi, len = 25):
tokens = string.split()
tokens = load_word_indices(tokens, wi.index)
return pad_sequences([tokens], maxlen = len, padding = 'pre')[0]
def find_true_examples():
models = ['8-150-2', '8-150-4', '8-150-8', '8-150-16', '8-150-32', '8-150-147' | , '6-150-8', '7-150-8' ,'9-226-8']
final_premises = set()
subset = {}
for model in models:
data = pa.read_csv('models/real' + model + '/dev1')
data = data[data['ctrue']]
neutr = data[data['label'] == 'neutral']
contr = data[data['label'] == 'contradiction']
entai... |
# -*- coding: utf-8 -*-
#
# GromacsWrapper documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 23 19:38:56 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't ... | n appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Options for ext.intersphinx
# ---------------------------
# intersphinx: reference standard lib and RecSQL
# http://sphinx.pocoo.org/latest/ext/intersphinx.html
intersphinx_mapping | = {'https://docs.python.org/': None,
'https://docs.scipy.org/doc/numpy/': None,
'https://docs.scipy.org/doc/scipy/reference/': None,
}
# Options for ext.autodoc
# -----------------------
# see http://sphinx.pocoo.org/ext/autodoc.html
# This value selects what content wi... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | foo", "operator": "In", "values": ["true"]},
]
}
]
}
}
},
"tolerations": [
{"key": "dynamic-pods... | },
show_only=["templates/jobs/create-user-job.yaml"],
)
assert "Job" == jmespath.search("kind", docs[0])
assert "foo" == jmespath.search(
"spec.template.spec.affinity.nodeAffinity."
"requiredDuringSchedulingIgnoredDuringExecution."
"nodeSelecto... |
from .google import GoogleSpeaker
fro | m .watson import WatsonSpeaker
"""
alfred
~~~~~~~~~~~~~~~~
Google tts.
"""
__all__ = [
' | GoogleSpeaker',
'WatsonSpeaker'
]
|
<rule id="{tag}-set1-rule-rule" boolean-op="or" score="0">
<expression id="{tag}-set1-rule-rule-expr"
operation="defined" attribute="attr1"
/>
<expression id="{tag}-set1-rule-rule-expr-1"
... | self.temp_cib)
self.assert_pcs_success(
self.cli_command + ["--all"],
stdout_full=dedent(
| f"""\
Meta Attrs (not yet in effect): {self.prefix}-set1
name1=value1
Rule (not yet in effect): boolean-op=and score=INFINITY
Expression: date gt 3000-01-01
Meta Attrs (expired): {self.prefix}-set2
name2=va... |
#This doesn't actually do anything, its just a gui that looks like the windows one(kinda)
from Tkinter import *
mGui=Tk()
mGui.geometry('213x240')
mGui.title('Calculator')
mGui["bg"]="#D9E3F6"
##set images
image1 = PhotoImage(file="images/mc.gif")
image2 = PhotoImage(file="images/mr.gif")
image3 = PhotoImage(file="i... | ow 6
mbutton25 = Button(image=image26,bd=0).grid(row=10,column=1,columnspan=2,padx=2,pady=2)
mbutton26 = Button(image=image27,bd=0).grid(row=10,column=3,padx=2,pady=2)
mbutton27 = Button(image=image28,bd=0).grid(row=10,column=4,padx=2,pady=2)
##menu
menubar=Menu(mGui)
filemenu= Menu(menubar)
editmenu= Menu(menubar)
he... | ilemenu.add_command(label="Standard")
filemenu.add_command(label="Basic")
filemenu.add_command(label="History")
menubar.add_cascade(label="View",menu=filemenu)
##
editmenu.add_command(label="Copy")
editmenu.add_command(label="Paste")
menubar.add_cascade(label="Edit",menu=editmenu)
##
helpmenu.add_command(label="View He... |
# # define Line class
import math
class Line(object):
def __init__(self, p1,p2):
self.p1 = p1
self.p2 = p2
def getP1(self):
return self.p1
def getP2(s | elf):
return self.p2
def getDistance(self):
euclidean_dist = math.sqrt((self.p1.getXCoord() - self.p2.getXCoord())**2 + \
(self.p1.getYCoord() - self.p2.getYCoord())**2)
return euclidean_dist
def __str__(self):
return "("+str(self.getP1()) + ', ' + \
str( | self.getP2()) + ', ' + \
'distance: '+ self.getDistance()+")"
|
DEBUG = 0
# cardinal diretions
directions = ("left","up","right","down")
# logic
maxExamined = 75000 # maximum number of tries when solving
maxMoves = 19 # maximum number of moves
cullFrequency = 75000 # number of tries per cull update
cullCutoff = 1.2 # fraction of average to cull
# grid size
gridRows = 5
gridColum... | eal","fire","dark")
orbDefaultStrength = 100
orbList = ("heal","fire","water","wood","light","dark")
# orb image URLs
orbImageURL = dict(light="img/light.png",
dark="img/dark.png",
fire="img/fire.png",
water="img/water.png",
wood="img/wood.png",
heal="img/heal.png",
bg="img/bgOrb.png"
... | ve"
tkButtonBorder = 3
tkOrbStrengthEntryWidth = 7 |
# -*- coding: utf-8 -*-
#
# EAV-Django is a reusable Django application which implements EAV data model
# Copyright © 2009—2010 Andrey Mikhaylenko
#
# This file is part of EAV-Django.
#
# EAV-Django is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Pu... | V attributes. Form fields are created
on the fly depending on Schema defined for given entity instance. If no schema
is defined (i | .e. the entity instance has not been saved yet), only static
fields are used. However, on form validation the schema will be retrieved
and EAV fields dynamically added to the form, so when the validation is
actually done, all EAV fields are present in it (unless Rubric is not defined).
"""
FIELD_CL... |
boneList[id]
if bone.parent != -1:
parentName = boneList[bone.parent].name
else:
parentName = "None"
boneStr += "%d\t%s\tparent id:%d\t(%s)\n" %(id, bone.name,
bone.parent, parentName)
boneStr += "\tscale: %... | vtx.position[0], vtx.position[1],vtx.position[2], |
vtx.boneIndex[0],vtx.boneIndex[1],vtx.boneIndex[2],vtx.boneIndex[3])
vertexStr += \
"\tnorm:(%f,%f,%f)\tweights:(%f,%f,%f,%f)\n"%\
(vtx.normal[0],vtx.normal[1],vtx.normal[2],\
vtx.weights[0],vtx.weights[1],vtx.weights[2],vtx.weights[3])
... |
expected_results_of_type(run_results, test_expectations.FAIL, "failures", tests_with_result_type_callback)
self._print_expected_results_of_type(run_results, test_expectations.FLAKY, "flaky", tests_with_result_type_callback)
self._print_debug('')
def print_workers_and_shards(self, num_workers, num_s... | name = self._port.driver_name()
if num_workers == 1:
self._print_default("Running 1 %s." % driver_na | me)
self._print_debug("(%s)." % grammar.pluralize('shard', num_shards))
else:
self._print_default("Running %d %ss in parallel." % (num_workers, driver_name))
self._print_debug("(%d shards; %d locked)." % (num_shards, num_locked_shards))
self._print_default('')
de... |
#!/usr/bin/python
from distutils.core import setup
# Remember to change in reroute/__init__.py as well!
VERSION = '1.1.1'
setup(
name='django-reroute',
version=VERSION,
description="A drop-in replacement for django.conf.urls.defaults which supports HTTP verb dispatch and view wrapping.",
long_descrip... | ='http://github.com/dnerdy/django-reroute',
keywords=['reroute', 'django', 'http', 'rest | ', 'route', 'routing', 'dispatch', 'wrapper'],
packages=['reroute'],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS... |
ynamically.
"""
import logging
import os
import re
import time
try:
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.api import validation
from google.appengine.api import yaml_object
except:
from google.appengine.api import memcache
from google.appengi... | n from the datastore.
Args:
app_version: the major version you want configuration data for.
Side Effects:
We populate memcache with whatever we find in the datastore.
Returns:
A config class instance for most recently set options or None if the
query could not c | omplete due to a datastore exception.
"""
rpc = db.create_rpc(deadline=DATASTORE_DEADLINE,
read_policy=db.EVENTUAL_CONSISTENCY)
key = _get_active_config_key(app_version)
config = None
try:
config = Config.get(key, rpc=rpc)
logging.debug('Loaded most recent conf data from dat... |
from flask import session, Blueprint
from lexos.managers import session_manager
from lexos.helpers import constants
from lexos.models.consensus_tree_model import BCTModel
from lexos.views.base import render
consensus_tree_blueprint = Blueprint("consensus-tree", __name__)
@consensus_tree_blueprint.route("/consensus-t... | _opti | on()
# Return the bootstrap consensus tree
return BCTModel().get_bootstrap_consensus_tree_plot_decoded()
|
"""
A wrap python class | of 'pbsnodes -N "note" node' command
The purpose of this class is to provide a simple API
to write some attribute and its value pairs to note attribute of cluster nodes.
"""
from __future__ import print_function
from sh import ssh
from ast import literal_eval
from types import *
from copy import deepcopy
from cloudmesh... | R
# ----------------------------------------------------------------------
# SETTING UP A LOGGER
# ----------------------------------------------------------------------
log = LOGGER(__file__)
class pbs_note_builder:
def __init__(self, user, host):
self.username = user
self.hostname = host
... |
# coding: utf8
# commentinput.py
# 5/28/2014 jichi
__all__ = 'CommentInputDialog',
if __name__ == '__main__':
import sys
sys.path.append('..')
import debug
debug.initenv()
from Qt5 import QtWidgets
from PySide.QtCore import Qt
from sakurakit import skqss
#from sakurakit.skclass import memoizedproperty
#from ... | parent=None):
super(CommentInputDialog, self).__init__(parent)
skqss.class_(self, 'texture')
self.setWindowTitle(mytr_("Update reason"))
#self.setWindowIcon(rc.icon('window-shortcuts'))
self.__d = _CommentInputDialog(self)
#self.resize(300, 2 | 50)
#self.statusBar() # show status bar
#def __del__(self):
# """@reimp"""
# dprint("pass")
def text(self): return self.__d.edit.text()
def setText(self, v): self.__d.edit.setText(v)
def type(self): # -> str
return (
'updateComment' if self.__d.updateCommentButton.isChecked() else
... |
no movies have been rated
by the user.
"""
db = cloudant_client[CL_RATINGDB]
args = {
"startkey" : 'user_{0}'.format(user_id),
"endkey" : 'user_{0}/ufff0'.format(user_id),
"include_docs" : True
}
user_r... | 'recommendations' : { movie_id, rating }
}
or, if user had not rated any movies:
{
'type' : 'als_product_features',
'pf_vals' : product_feature_values,
'pf_keys' : product_feature_keys
}
" | ""
# get recommendation_metadata document with last run details
try:
meta_db = cloudant_client[CL_RECOMMENDDB]
meta_doc = meta_db['recommendation_metadata']
meta_doc.fetch()
except KeyError:
print('recommendation_metadata doc not found in', CL_REC... |
ests
from bs4 import BeautifulSoup
from .utils import normalize_key
class Institution:
"""
Classe responsavel pela coleta de todos os daddos da instituicao no site do e-MEC.
Realiza o scraping em busca de dados detalhados da instituicao e dos cursos de cada campus.
"""
def __init__(self, code_ie... | e_ies).encode("utf-8")
ies_b64 = base64.b64encode(ies_code).decode("utf-8")
URL = (
f"http://emec.mec.gov.br/emec/consulta-ies/listar-curso-agrupado/"
f"d96957f455f6405d14c6542552b0f6eb/{ies_b64}/list/1000?no_curso="
)
try:
response = requests.get(URL... | rn False
soup = BeautifulSoup(response.content, "html.parser")
table = soup.find(id="listar-ies-cadastro")
if table is None or table.tbody is None:
return
courses = []
rows = table.tbody.find_all("tr")
if rows is None:
return
for r in ... |
#### NOTICE: THIS FILE IS AUTOGENERATED
| #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_garm_bel_iblis.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_ma... | D MODIFICATIONS ####
return result |
# -*- coding: utf-8 -*-
"""
Data about OCA Projects, with a few helper functions.
OCA_PROJECTS: dictionary of OCA Projects mapped to the list of related
repository names, based on
https://community.odoo.com/page/website.projects_index
OCA_REPOSITORY_NAMES: list of OCA repository names
"""
from github_login import l... | 'account-invoicing',
'account-fiscal-rule',
],
# 'backport': ['OCB',
# | ],
'banking': ['banking',
'bank-statement-reconcile',
'account-payment',
],
'community': ['maintainers-tools',
'maintainer-quality-tools',
'runbot-addons',
],
'connector': ['connector',
... |
stJSON
requestJSON = requestJSON["Value"]
retryMainService += 1
while retryMainService:
retryMainService -= 1
setRequestMgr = self._getRPC().putRequest(requestJSON)
if setRequestMgr["OK"]:
return setRequestMgr
errorsDict["RequestM... | if not digest["OK"]:
self.log.error(
"getDigest: unable to get digest for request", "request: '%s' %s" % (requestID, digest["Message"])
)
return digest
def getRequestStatus(self, requestID):
"""Get the request status given a request id.
:param ... | tStatus: attempting to get status for '%d' request." % requestID)
requestStatus = self._getRPC().getRequestStatus(requestID)
if not requestStatus["OK"]:
self.log.error(
"getRequestStatus: unable to get status for request",
": '%d' %s" % (requestID, requestStat... |
#!/usr/bin/python3
"""
Given a function rand7 which generates a uniform random integer in the range 1
to 7, write a function rand10 which generates a uniform random integer in the
range 1 to 10.
Do NOT use system's Math.random().
"""
# The rand7() API is already defined for you.
def rand7():
return 0
class Sol... | "
generate 7 twice, (rv1, rv2), 49 combination
assign 40 combinations for the 1 to 10 respectively
7-ary system
:rtype: int
"""
while True:
rv1 = rand7()
rv2 = rand7()
s | = (rv1 - 1) * 7 + (rv2 - 1) # make it start from 0
if s < 40: # s \in [0, 40)
return s % 10 + 1 # since I make it start from 0
|
# author David Sanchez david.sanchez@lapp.in2p3.fr
# ------ Imports --------------- #
import numpy
from Plot.PlotLibrary import *
from Catalog.ReadFermiCatalog import *
from environ import FERMI_CATALOG_DIR
# ------------------------------ #
#look for this 2FGL source
source = "2FGL J1015.1+4925"
#source = "1FHL J2158... | L")
#create a spectrum for a given catalog and compute the model+butterfly
Cat.MakeSpectrum("3FGL",1e-4,0.3)
enerbut,but,enerphi,phi = Cat.Plot("3FGL")
Cat.MakeSpectrum("2FGL",1e-4,0.3)
enerbut2FGL,but2FGL,enerphi2FGL,phi2FGL = Cat.Plot("2FGL")
Cat.MakeSpectrum("2FHL",5e-2,2)
enerbut2FHL,but2FHL,enerphi2FHL,phi2FHL... | )
dem = ener-em
dep = ep-ener
c=Cat.ReadPL('3FGL')[3]
dnde = (-c+1)*flux*numpy.power(ener*1e6,-c+2)/(numpy.power((ep*1e6),-c+1)-numpy.power((em*1e6),-c+1))*1.6e-6
ddnde = dnde*dflux/flux
#plot
import matplotlib.pyplot as plt
plt.loglog()
plt.plot(enerbut, but, 'b-',label = "3FGL")
plt.plot(enerphi,phi, 'b-')
plt.plot... |
#!/usr/bin/env python
#! -O
#
# python equivalent for grouplisten, works same way
#
#EIBD client library
#Copyright (C) 2006 Tony Przygienda, Z2 GmbH
#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 Fr... | ile 1:
(result, buf, src) = eibclient.eibclient.EIBGetAPDU_Src (con)
if len(buf) < 2:
print "Read failed"
sys.exit(1)
if (o | rd(buf[0]) & 0x3 or (ord(buf[1]) & 0xc0) == 0xc0):
print"Unknown APDU from %s" % individual2string(src)
ps = ""
if (ord(buf[1]) & 0xC0) == 0:
ps = ps + "Read"
elif (ord(buf[1]) & 0xC0) == 0x40:
ps = ps + "Response"
elif (ord(buf[1]) & 0xC0) == 0x80:
ps = ps + "Write"
else:
ps = ps + "???"... |
#!/usr/bin/python2.4
#
# Copyright 2009 Empeeric LTD. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | request = self._getURL("errors","")
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
return json['results']
def setUrllib(self, urllib):
'''Override the default urllib implementation.
Args:
... | '''
self._urllib = urllib
def _getURL(self,verb,paramVal):
if not isinstance(paramVal, list):
paramVal = [paramVal]
params = [
('version',BITLY_API_VERSION),
('format','json'),
('login',self.logi... |
urce and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the abov... | Read/Write Attributes
self._name = None
self._last_updated_by = None
self._last_updated_date = None
self._active = None
self._default_allow_ip = None
self._default_allow_non_ip = None
| self._default_install_acl_implicit_rules = None
self._description = None
self._embedded_metadata = None
self._entity_scope = None
self._policy_state = None
self._creation_date = None
self._priority = None
self._priority_type = None
self._associated_live_e... |
# redis-import-set
import sys
from csv import reader
from itertools import count, | groupby, islice
import r | edis
if __name__ == '__main__':
r = redis.Redis()
pipeline_redis = r.pipeline()
count = 0
try:
keyname = sys.argv[1]
except IndexError:
raise Exception("You must specify the name for the Set")
for k, _ in groupby(reader(sys.stdin, delimiter='\t'),
lambda x:x[0])... |
attr for attr in attribs if not attr.startswith('_')]
def default_class_attr_val(attr):
"""Return the default value for the given class attribute"""
defaults = JobScript._attributes.copy()
defaults.update(JobScript._protected_attributes)
try:
return defaults[attr]
except KeyError:
... | lass__) == ['backend', 'backends',
'cache_folder', 'cache_prefix', 'epilogue', 'filename',
'max_sleep_interval', 'prologue', 'remote', 'resources', 'rootdir',
'scp', 'shell', 'ssh', 'workdir']
for attr in get_attributes(jobscript.__class__):
if attr not | in ['resources', 'backends']:
assert getattr(jobscript, attr) == default_class_attr_val(attr)
inidata, expected_attribs, expected_resources = example_inidata()
p = tmpdir.join("default.ini")
p.write(inidata)
ini_filename = str(p)
# Setting class defaults before instantiation sets both... |
#!/usr/bin/python
# ZetCode PyGTK tutorial
#
# This example shows how to use
# the Alignment widget
#
# author: jan bodnar
# website: | zetcode.com
# last edited: February 2009
import gtk
import gobject
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_title("Alignment")
self.set_size_request(260, 150)
| self.set_position(gtk.WIN_POS_CENTER)
vbox = gtk.VBox(False, 5)
hbox = gtk.HBox(True, 3)
valign = gtk.Alignment(0, 1, 0, 0)
vbox.pack_start(valign)
ok = gtk.Button("OK")
ok.set_size_request(70, 30)
close = gtk.Button("Close")
h... |
__all__ = [" | machsuite", "shoc", "dat | atypes", "params"]
|
(i.e. in Studio)
is_author_mode = True
def handler_url(self, block, handler_name, suffix='', query='', thirdparty=False):
return reverse('preview_handler', kwargs={
'usage_key_string': str(block.scope_ids.usage_id),
'handler': handler_name,
'suffix': suffix,
... |
value of None meaning that all groups should be shown.
"""
return None
def _load_preview | _module(request, descriptor):
"""
Return a preview XModule instantiated from the supplied descriptor. Will use mutable fields
if XModule supports an author_view. Otherwise, will use immutable fields and student_view.
request: The active django request
descriptor: An XModuleDescriptor
"""
st... |
from django.db import models
from lxml import html
import requests
from ..core.models import UUIDModel
from ..teams.models import FleaOwner
STAT_VARS = [ # Should be ordered accordingly
'stat_fgpct100', 'stat_ftpct100', 'stat_3pt', 'stat_reb',
'stat_stl', 'stat_blk', 'stat_ast', 'stat_to', 'stat_pts',
]
... | (team_owner, _) = FleaOwner.objects.update_or_create( # update because active could change
url=team_owner_url,
defaults={
'name': team_owner_name,
'active': team_owner_active,
},
)
stat_from_ff = team.x... |
stat = stat_from_ff[idx].replace(',', '')
if val in ['stat_fgpct100', 'stat_ftpct100']:
stat_from_ff[idx] = int(float(stat) * 100)
else:
stat_from_ff[idx] = int(stat)
stats = dict(zip(
STAT_VARS,
... |
#############################################################################
##
## Copyright (C) 2015 The Qt Company Ltd.
## Contact: http://www.qt.io/licensing
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance wit... | ## a written agreement between you and The Qt Company. For licensing terms and
## conditions see http://www.qt.io/terms-conditions. For further information
## use the contact form at http://www.qt.io/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under | the terms of the GNU Lesser
## General Public License version 2.1 or version 3 as published by the Free
## Software Foundation and appearing in the file LICENSE.LGPLv21 and
## LICENSE.LGPLv3 included in the packaging of this file. Please review the
## following information to ensure the GNU Lesser General Public Lice... |
from sys import byteorder
from array import array
from struct import pack
from multiprocessing import Process
import unreal_engine as ue
import pyaudio
import wave
THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100
def is_silent(snd_data):
"Returns 'True' if below the 'silent' t... | nd(snd_data)
silent = is_silent(snd_data)
if silent and snd_started:
num_silent += 1
elif not silent and not snd_started:
snd_started = True
else:
num_silent = 0
if snd_started and num_silent > 30:
break
sample... | idth = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
r = normalize(r)
r = trim(r)
r = add_silence(r, 0.5)
return sample_width, r
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, ... |
# assign inputs
_skymtx, _analysisGrids, _analysisType_, _vmtxPar_, _dmtxPar_, reuseVmtx_, reuseDmtx_ = IN
analysisRecipe = None
#import honeybee
#reload(honeybee.radiance.recipe.daylightcoeff.gridbased)
#reload(honeybee.radiance.recipe.threephase.gridbased)
#reload(honeybee.radiance.recipe.fivephase.gridbased)
try:
... | ed import FivePhaseGridBased
except ImportError as e:
raise ImportError('\nFailed to import honeybee:\n\t{}'.format(e))
if _skymtx and _analysisGrids:
reuseVmtx_ = bool(reuseVmtx_)
reuseDmtx_ = bool(reuseDmtx_)
assert _analysisType_ == 0, \
ValueError('3Phase recipe currently only supports ill... | Vmtx_, reuseDmtx_)
# assign outputs to OUT
OUT = (analysisRecipe,) |
#
# nestml_error_listener.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your op... | p_index, exact, ambig_alts, configs):
if self.report_ambiguity:
msg = u"reportAmbiguity d="
msg += self.getDecisionDescription(recognizer, dfa)
msg += u": ambigAlts="
msg += AntlrUtil.str_set(self.getConflictingAlts(ambig_alts, configs))
msg += u", inp... | sages.get_syntax_warning_in_model(msg)
Logger.log_message(code=code, message=message, error_position=ASTSourceLocation(start_index, stop_index,
start_index, stop_index),
log_level=Loggi... |
# 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 th... | "all_tenants": True})
def list_services(self):
return self.client.services.list()
def list_availability_zones(self):
return self.client.availabilit | y_zones.list()
class Neutron(ResourceManager):
REQUIRED_SERVICE = consts.Service.NEUTRON
def has_extension(self, name):
extensions = self.client.list_extensions().get("extensions", [])
return any(ext.get("alias") == name for ext in extensions)
def list_networks(self):
return sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.