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
jittat/ku-eng-direct-admission
application/migrations/0030_add_doc_reviewed_at_to_submission_info.py
Python
agpl-3.0
9,283
0.009049
# -*- coding: utf-8 -*- from south.db import db from django.db import models from adm.application.models import * class Migration: def forwards(self, orm): # Adding field 'SubmissionInfo.doc_reviewed_at' db.add_column('application_submissioninfo', 'doc_reviewed_at', orm['application....
', [], {'primary_key': 'True'}), 'national_id': ('django.db.models.fields.CharField', [], {'max_length': '20'}), 'nationality': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'phone_number': ('django.db.models.fields.CharField', [], {'max_length': '35'}) }, ...
'applicant': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'registrations'", 'to': "orm['application.Applicant']"}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}...
blrm/openshift-tools
scripts/monitoring/cron-send-project-operation.py
Python
apache-2.0
5,158
0.003296
#!/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...
ct(args) if delete_project_code == 1: logger.info('project deletion failed in 20s') # start the test logger.info("project does not exists, going to create it") create_project(args) create_project_code = check_project(args) if create_project_code == 0: # 0 means p...
# project creation succeed, then delete the project delete_project(args) delete_project_code = check_project(args) 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 ...
thomasgilgenast/spqr-nonrel
filetransfers/admin.py
Python
bsd-3-clause
13,542
0.001625
from urllib import urlencode from django import forms, template from django.contrib.auth.admin import csrf_protect_m from django.contrib.admin import helpers from django.contrib.admin.util import unquote from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied fro...
queryset=inline.queryset(request)) formsets.append(formset) adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)), self.prepopulated_fields, self.get_readonly_fields(request), model_admin=self) media = self.media + adminForm.med...
instances, formsets): fieldsets = list(inline.get_fieldsets(request)) readonly = list(inline.get_readonly_fields(request)) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, readonly, model_admin=self) inline_admin_formsets.appen...
BoPeng/simuPOP
docs/IfElseFixed.py
Python
gpl-2.0
1,537
0.003904
#!/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...
heme=sim.RandomMating(), postOps=sim.IfElse(verbose, ifOps=[ sim.Stat(alleleFreq=0), si
m.PyEval(r"'Gen: %3d, allele freq: %.3f\n' % (gen, alleleFreq[0][1])", step=5) ], begin=10), gen = 30 )
frigg/frigg-hq
frigg/builds/migrations/0011_auto_20150223_0442.py
Python
mit
444
0
# -*- c
oding: 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_name='project', name='approved', ...
]
EmreAtes/spack
var/spack/repos/builtin/packages/py-qtawesome/package.py
Python
lgpl-2.1
1,760
0
############################################################################## # 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...
ftware Fo
undation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # ...
glemaitre/scikit-learn
examples/release_highlights/plot_release_highlights_0_22_0.py
Python
bsd-3-clause
10,115
0.002472
""" ======================================== Release Highlights for scikit-learn 0.22 ======================================== .. currentmodule:: sklearn We are pleased to announce the release of scikit-learn 0.22, which comes with many bug fixes and new features! We detail below a few of the major features of this r...
(random_state=0) with TemporaryDirectory(prefix="sklearn_cache_") as tmpdir: estimator = make_pipeline( KNeighborsTransformer(n_neighbors=10, mode='distance'), Isomap(n_neighbors=10, metric='precomputed'), memory=tmpdir) estimator.fit(X) # We can decrease the number of neighbors an...
--------------------------------- # We now support imputation for completing missing values using k-Nearest # Neighbors. # # Each sample's missing values are imputed using the mean value from # ``n_neighbors`` nearest neighbors found in the training set. Two samples are # close if the features that neither is missing a...
hmenke/espresso
testsuite/python/drude.py
Python
gpl-3.0
10,864
0.004602
# Copyright (C) 2010-2018 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later v...
["BMIM_C1"] + \ masses["BMIM_C2"] + masses["BMIM_C3"] box_center = 0.5 * np.array(3 * [box_l]) system.min_global_cut = 3.5 #Place Particles dmol = 5.0 #Test Anion pos_pf6 = box_center + np.array([0, dmol, 0
]) system.part.add(id=0, type=types["PF6"], pos=pos_pf6, q=charges[ "PF6"], mass=masses["PF6"], fix=[1, 1, 1]) pos_com = box_center - np.array([0, dmol, 0]) system.part.add(id=2, type=types["BMIM_C1"], pos=pos_com + [ 0, -0.527, 1.365], q=charges[...
NewGlobalStrategy/NetDecisionMaking
fts/test_0aregister.py
Python
mit
2,323
0.021093
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...
keys(USERS['PASSWORD1']) register_button = self.browser.find_element_by_css_selector("#submit_record__row input") register_button.click() #hopefully to help gae get data sorted for next test #t
ime.sleep(10) #element = WebDriverWait(driver, 10).until(lambda driver : driver.find_element_by_id("createFolderCreateBtn")) body = WebDriverWait(self, 10).until(lambda self : self.browser.find_element_by_tag_name('body')) #body = self.browser.find_element_by_tag_name('body') self.assertIn...
TheAlgorithms/Python
maths/sum_of_arithmetic_series.py
Python
mit
482
0.002075
# DarkCoder def sum_of_series(first_term, common_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) 49600.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()
ajayhk/algorithms
greedy/k-clustering-hamming.py
Python
apache-2.0
6,457
0.038098
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...
t1[:y] + '0' + vert1[y+1:] # flip the second bit h_list.append(vert2) # this is all the items with the second bit also flipped #print vert2 return h_list def parent(key): return vert_union_parent[key] def root(key): while (vert_union_parent[key] != key): key = parent(key) return vert_union_parent[...
ef union(key1, key2): root_key2 = root(key2) vert_union_parent[root_key2] = root(key1) # Put the root of the first one as the parent of the second one's root # this avoids the issue of union of two vertices whose parents are different from their roots # for example b is a's root and c is d's root. When we union a...
mariodebian/server-stats-system-agent
sssa/pygtail.py
Python
gpl-2.0
6,429
0.002489
#!/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 ...
gfile>.offset).") cmdline.add_option("--paranoid", "-p", action="store_true", help="Update the offset file every time we read a line (as opposed to" " only when we reach the end of the file).") options, args = cmdline.parse_args() if (len(args) != 1): cmdline.error("Please pro...
paranoid=options.paranoid) for line in pygtail: sys.stdout.write(line) if __name__ == "__main__": main()
aoyono/sicpy
Chapter1/exercises/exercise1_11.py
Python
mit
1,681
0.002974
# -*- 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...
add( add(a, mul(2, b)), mul(3, c) ), a, b, sub(count, 1), ) return f_iter(2, 1, 0, n) def run_the_magic(): N = 5 from timeit import Timer for n in range(N + 1): print('n = %(n)s' % locals()) prin...
s)' % locals(), f_recursive(n), sep='\n') print('(f-iterative %(n)s)' % locals(), f_iterative(n), sep='\n') timer_rec = Timer(stmt="f_recursive(%(n)s)" % locals(), setup="from Chapter1.exercise1_11 import f_recursive") timer_iter = Timer(stmt="f_iterative(%(n)s)" % locals(), setup="from Chapter...
DiXiT-eu/collatex-tutorial
unit8/sydney-material/integration/xml_segmentation.py
Python
gpl-3.0
1,298
0.006163
__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 n
ame 'doc' is not optimal (the variable is only a pointer to a stream of events) doc = parse(xml_file) print(str(doc)) # doc = DOMEventStream segment = 0 for event, node in doc: if event == START_ELEMENT and node.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 encountered. def segmentate_xml_f...
ewdurbin/clandestined-python
clandestined/test/test_rendezvous_hash.py
Python
mit
5,256
0.00019
import unittest from clandestined import RendezvousHash class RendezvousHashTestCase(u
nittest.TestCase): def test_init_no_options(self): rendezvous = RendezvousHash() self.assertEqual(0, len(rendezvous.nodes)) self.assertEqual(1361238019, rendezvous.hash_function('6666')) def test_init(self): nodes = ['0', '1', '2'] rendezvous = RendezvousHash
(nodes=nodes) self.assertEqual(3, len(rendezvous.nodes)) self.assertEqual(1361238019, rendezvous.hash_function('6666')) def test_seed(self): rendezvous = RendezvousHash(seed=10) self.assertEqual(2981722772, rendezvous.hash_function('6666')) def test_add_node(self): rend...
Robpol86/jira-context
setup.py
Python
mit
4,088
0.00318
#!/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...
raise ValueError('Failed to obtain metada
ta from package/module.') return everything class PyTest(test): TEST_ARGS = ['--cov-report', 'term-missing', '--cov', NAME_FILE, 'tests'] def finalize_options(self): test.finalize_options(self) setattr(self, 'test_args', self.TEST_ARGS) setattr(self, 'test_suite', True) def ...
waitress-andela/waitress
waitress/pantry/viewsets.py
Python
mit
3,247
0.000924
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)...
ady." return Response(content, status=status_code.HTTP_406_NOT_ACCEPTABLE) content["message"] = f"{user.firstname} has successfully tapped." user_pantry_session = Pantry(user=user) user_pantry_session.save() return Response(content, status=status_code.HTTP_200_OK) @act...
def auth(self, request): passphrase = request.POST.get("passphrase", "") if not passphrase: content = {"status": "failed", "message": "Passphrase not supplied"} return Response(content, status=status_code.HTTP_400_BAD_REQUEST) exists = Passphrase.exists(passphrase) ...
pli3/e2-openwbif
plugin/controllers/views/mobile/channels.py
Python
gpl-2.0
7,404
0.013236
#!/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...
e unless self.awake() was ca
lled if not trans: trans = DummyTransaction() _dummyTrans = True else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ...
efornal/pulmo
app/migrations/0055_applicationform_requires_development.py
Python
gpl-3.0
523
0.001912
# -
*- 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( ...
cwlseu/recipes
pyrecipes/utils.py
Python
gpl-3.0
2,631
0.009502
#! /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"...
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, **kwar...
start = time.time() result = func(*args, **kwargs) end = time.time() print >> ostream, "execute %s used time:%.2f s" % (func.__name__, (end - start)) return result return wapper return decorator def is_readable(path, user): user_info = pwd.getp...
15klli/WeChat-Clone
main/models/user.py
Python
mit
1,617
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import db from datetime import 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(3...
ealname=None, classname=None, sex=None, province=None, city=None, country=None, headimgurl=None, regtime=None): self.openid = openid self.nickname = nickname self.realname = realname self.classname = classname self.sex = sex se
lf.province = province self.city = city self.country = country self.headimgurl = headimgurl self.regtime = regtime def __repr__(self): return '<openid %r>' % self.openid def save(self): db.session.add(self) db.session.commit() return self de...
daq-tools/kotori
kotori/frontend/app.py
Python
agpl-3.0
843
0
# -*- 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...
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', 's
tatic/app', cache_max_age=0) config.add_static_view('static/lib', 'static/lib', cache_max_age=60 * 24) config.add_route('index', '/') config.scan() return config.make_wsgi_app()
obeattie/sqlalchemy
lib/sqlalchemy/test/noseplugin.py
Python
mit
6,603
0.004695
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...
The class being examined by the selector """ if not issubclass(cls, testing.TestBase): return False else: if (hasat
tr(cls, '__whitelist__') and testing.db.name in cls.__whitelist__): return True else: return not self.__should_skip_for(cls) def __should_skip_for(self, cls): if hasattr(cls, '__requires__'): def test_suite(): return 'ok' test_suite.__...
odoousers2014/odoo
addons/hr_holidays/tests/test_holidays_flow.py
Python
agpl-3.0
10,541
0.003226
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (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...
self.assertEqual(holiday_status.virtual_remaining_leaves, vrl, 'hr_holidays: wrong type days computation') # HrUser creates some holiday statuses -> crash because only HrManagers should do this with self.assertRaises(AccessError): self.holidays_status_dum...
days_status.create(cr, self.user_hruser_id, { 'name': 'UserCheats', 'limit': True, }) # HrManager creates some holiday statuses self.holidays_status_0 = self.hr_holidays_status.create(cr, self.user_hrmanager_id, { 'name': 'WithMeetingType', ...
davy39/eric
SqlBrowser/SqlConnectionDialog.py
Python
gpl-3.0
3,950
0.00481
# -*- 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 ...
ui import E5FileDialog from .Ui_SqlConnectionDialog import Ui_SqlConnectionDialog import Utilities import UI.PixmapCache class SqlConnectionDialog(QDialog, Ui_SqlConnectionDialog): """ Class implementing a dialog to enter the connection parameters. """ def __init__(self, pa
rent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super(SqlConnectionDialog, self).__init__(parent) self.setupUi(self) self.databaseFileButton.setIcon(UI.PixmapCache.getIcon("open.png")) self....
mitsuhiko/werkzeug
examples/couchy/views.py
Python
bsd-3-clause
2,120
0
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...
l: raise NotFound() return redirect(url.target, 301) @expose("/list/", defaults={"page": 1}) @expose("/list/<int:page>") def list(request, page): def wrap(doc): data = doc.value data["_id"] = doc.id return URL.wrap(data) code = """function(doc) { if (doc.public){ map([d
oc._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 NotFound() return render_template("list.html", pagination=pagination) def not_found(reque...
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_trajectory.py
Python
apache-2.0
7,802
0.004747
#!/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...
_recommended_attributes(self, dataset): ''' Feature type specific check of global recommended attributes. :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended global attributes') # Check ...
ion', 'time_coverage_resolution']: attr_value = getattr(dataset, attr, '') try: parse_duration(attr_value) recommended_ctx.assert_true(True, '') # Score it True! except Exception: recommended_ctx.assert_true(False, '{} should exist and...
cjh5414/kboard
kboard/functional_test/test_post_edit.py
Python
mit
4,015
0.00086
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() ...
ent_by_tag_name('h3').text self.assertIn('글 수정', self.browser.title) self.assertIn('글 수정', header_text) # 작성되어 있던 게시글의 제목인 'pjango'가 보인다. titlebox = self.browser.find_element_by_id('id_post_title') self.assertEqual(titlebox.get_attribute('value'), 'pjango') # 'django'로 ...
게시글의 내용은 'Hello pjango'으로 보인다. contentbox = self.get_contentbox() self.assertEqual(contentbox.text, 'Hello pjango') # 'Hello django'로 수정한다. contentbox.clear() contentbox.send_keys('Hello django') self.browser.switch_to.default_content() # 실수로 '취소' 버튼을 누른다. ...
CartoDB/cartoframes
cartoframes/viz/widgets/category_widget.py
Python
bsd-3-clause
1,071
0.003735
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...
ription text widget placed under widget title. footer (str, optional): Footer text placed on the widget bottom. read_only (boolean, optional): Interactively filter a category by selecting it in the widget. Set to "False" by default. weight (int, optional): Weight of the category widget...
.. 'column_name', ... title='Widget title', ... description='Widget description', ... footer='Widget footer') """ return Widget('category', value, title, description, footer, read_only=read_only, weight=weight)
NextINpact/LaPresseLibreSDK
python_django/sdk_lpl/models/UserInfosModel.py
Python
mit
439
0
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
eleonrk/SickRage
lib/feedparser/sgml.py
Python
gpl-3.0
2,683
0.003727
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...
?=[<>])|.*?(?=[<>])''') def search(self, target, index=0): match = self.endbracket.match(target, index) if match is not None: # Returning a new object in the calling thread's context # resolves a thread-safety. return EndBracketMatch(match)...
nit__(self, match): self.match = match def start(self, n): return self.match.end(n) endbracket = _EndBracketRegEx()
Jet-Streaming/gyp
test/builddir/gyptest-default.py
Python
bsd-3-clause
2,759
0.004712
#!/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 files get created outside of that build directory hierarchy even when referred to with deeply-nested ../../.. paths. """ import TestGyp # TODO(mmoss): Make only supports (theoretically) a single, global build # directory (through GYP_GENERATOR_FLAGS 'output_dir'), rather than ...
unioslo/cerebrum
testsuite/tests/test_core/test_core_Entity/test_EntitySpread.py
Python
gpl-2.0
4,894
0
#!/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() ...
ead, entity_spread_alt): entity.delete_spread(entity_spread) assert not entity.has_spread(entity_spread) assert entity
.has_spread(entity_spread_alt) def test_list_spreads(entity, entity_type, entity_spread, entity_spread_alt): columns = ['spread_code', 'spread', 'description', 'entity_type', 'entity_type_str'] all_spreads = entity.list_spreads() assert len(all_spreads) >= len((entity_spread, entity_spread...
mailund/read-phaser
phase_haplotypes.py
Python
gpl-3.0
8,417
0.011049
import sys import argparse parser = argparse.ArgumentParser(description=''' Phase haplotypes from phased pairs. ''') parser.add_argument('pairs', nargs=1, help='List of phased pairs (use - for stdin).') parser.add_argument('--buffer', default=1000, action='store', type=int, ...
else: n.component = component for _,_,src in n.in_edges: dfs(src) for _,_,dst in n.out_edges: dfs(dst) dfs(node) loci = nodes.keys() loci.sort() component = 0 for locus in loci: node = nodes...
component += 1 components = [ list() for i in xrange(component) ] for locus in loci: node = nodes[locus] components[node.component].append(node) return components def split_components(components, max_src): '''Split a list of components in those that are done and those that ar...
janusnic/dj-21v
unit_02/mysite/home/test.py
Python
mit
439
0.009112
# -*- 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(response, "home/index.html") def test_uses_base_template(self): r...
et(reverse("home")) self.assertTemplateUsed(response, "base.html")
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extract17LiterarycornerWordpressCom.py
Python
bsd-3-clause
1,613
0.022939
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 ...
() in item['title'].lower(): return buildReleaseMessageWithType(item, name, vol, chp, frag=fr
ag, postfix=postfix, tl_type=tl_type) return False
dragosbdi/bitcredit-2.0
qa/pull-tester/tests_config.py
Python
mit
413
0.016949
#!/usr/bin/env
python2 # Copyright (c) 2013-2014 The Bitcredit Core developers # Distributed under the MIT software 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 into comments if they were disabled when c...
ITD=1 #ENABLE_ZMQ=1
GHubgenius/wfuzz-1
dictio.py
Python
gpl-2.0
1,098
0.054645
#!/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 = [l
ambda x: encoder().encode(x)] self.restart() def count (self): return self.__payload.count() * len(self.__encoder) def setpayload(self,payl): self.__payload = payl self.restart() def setencoder(self,encd): self.__encoder=encd self.generator = self.gen() def getpayload (self): return self.__payload...
__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.__iter__() self.generator...
huanqi/leetcode-python
swap_nodes_in_pairs/solution2.py
Python
bsd-2-clause
1,177
0
# 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...
res = temp res_end = temp_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...
temp_end else: res_end.next = temp res_end = temp_end return res
liosha2007/temporary-groupdocs-python3-sdk
groupdocs/models/ChangesResponse.py
Python
apache-2.0
1,137
0.007916
#!/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...
ense. """ class ChangesResponse: """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): self.swaggerTy
pes = { 'result': 'ChangesResult', 'status': 'str', 'error_message': 'str', 'composedOn': 'int' } self.result = None # ChangesResult self.status = None # str self.error_message = None # str self.composedOn = None # int
bealdav/OpenUpgrade
addons/analytic/migrations/8.0.1.1/pre-migration.py
Python
agpl-3.0
1,314
0
# -*- 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 the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied wa...
e details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import pooler, SUPERUSER_ID from openerp.openupgrade import...
imakin/PersonalAssistant
GameBot/src_py/makinreusable/makinframe.py
Python
mit
610
0.04918
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...
ouseMoveEvent(self, me): a = QtGui.QFrame.mouseMoveEvent(self,me
) self.mousegeser.emit(me.x(), me.y()) return a
naparuba/check-linux-by-ssh
check_disks_by_ssh.py
Python
mit
7,141
0.009803
#!/usr/bin/env python2 # Copyright (C) 2013-: # Gabes Je
an, 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 without restriction, including without limitation # the rights to u...
hom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT ...
salomax/livremarketplace
app_test/purchase_test.py
Python
apache-2.0
4,115
0.002674
#!/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...
st': 9, 'quantity': 40 }] # Iterate purchases mock for x in purchasesMock: # Create purchase mock purchase = Mock(spec_set=purchaseModel.PurchaseModel()) purchase.key = Mock(spec_set=ndb.Key('PurchaseModel', x['id'])) # C...
rchase.product.get = Mock(return_value=purchase.product) # Net total value purchase.cost = x['cost'] purchase.quantity = x ['quantity'] # Append to list purchasesList.append(purchase) # Mock list method purchaseModel.list = MagicMock...
kaushik94/sympy
sympy/physics/optics/tests/test_utils.py
Python
bsd-3-clause
7,792
0.003208
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...
s_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...
= symbols('si, so') assert transverse_magnification(si, so) == -si/so assert transverse_magnification(30, 15) == -2
chiffa/TcanAnalyzer
src/adapters.py
Python
bsd-3-clause
1,131
0.001768
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: source_ = reade...
= 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]...
RPGOne/Skynet
scikit-learn-0.18.1/benchmarks/bench_20newsgroups.py
Python
bsd-3-clause
3,555
0
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_sco
re from sklearn.utils.validation import check_array from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB ESTIMATORS = { ...
(n_estimators=100, max_features="sqrt", min_samples_split=10), "extra_trees": ExtraTreesClassifier(n_estimators=100, max_features="sqrt", min_sample...
thisismyrobot/gedit-pytts
src/pyttsx/drivers/sapi5.py
Python
bsd-2-clause
5,041
0.005356
''' 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...
se self._speaking = False self._stopping = False # initial rate self._rateWpm = 200 self.setProperty('voice', self.getProperty('voice')) def destroy(self): self._tts.EventInterests = 0
def say(self, text): self._proxy.setBusy(True) self._proxy.notify('started-utterance') self._speaking = True self._tts.Speak(unicode(text), 19) def stop(self): if not self._speaking: return self._proxy.setBusy(True) self._stopping = True ...
andyraib/data-storage
python_scripts/env/lib/python3.6/site-packages/pandas/sparse/frame.py
Python
apache-2.0
30,372
0.000099
""" Data structures for sparse float data. Life is made simpler by dealing only with float64 data """ from __future__ import division # pylint: disable=E1101,E1103,W0231,E0202 from numpy import nan from pandas.compat import lmap from pandas import compat import numpy as np from pandas.types.missing import isnull, not...
s.util.decorators import Append
er import pandas.core.ops as ops _shared_doc_kwargs = dict(klass='SparseDataFrame') class SparseDataFrame(DataFrame): """ DataFrame containing sparse floating point data in the form of SparseSeries objects Parameters ---------- data : same types as can be passed to DataFrame index : arr...
paulmcquad/projecteuler
0-100/problem72.py
Python
gpl-3.0
1,185
0.014346
#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 fraction. If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get: 1/8, 1...
# this problem equals to: find the sum of phi(2), phi(3), ...phi(1000000) from Helper import isPrime limit = 1000001 totients = range(limit) # [0,1,2,..,1000000] for i in range(2, limit): # for (i=2; i<limit; i++) if isPrime(
i): totients[i] = i - 1; for j in range(2*i, limit, i): totients[j] *= (1.0 - 1.0 / i) print sum(totients) - 1
cdusold/DriveLink
drivelink/hash/__init__.py
Python
mit
357
0.002801
""" .. modu
leauthor:: Chris Dusold <DriveLink@chrisdusold.com> A module containing general purpose, cross 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 import Deterministic_Hashable
zaxtax/scikit-learn
sklearn/ensemble/tests/test_gradient_boosting.py
Python
bsd-3-clause
39,945
0.000075
""" Testing for the gradient boosting module (sklearn.ensemble.gradient_boosting). """ import warnings import numpy as np from itertools import product from scipy.sparse import csr_matrix from scipy.sparse import csc_matrix from scipy.sparse import coo_matrix from sklearn import datasets from sklearn.base import clo...
assert_raises(ValueError, lambda X, y: GradientBoostingClassifier( loss='deviance').fit(X, y), X, [0, 0, 0, 0]) def test_loss_function(): assert_raises(ValueError, GradientBoostingClassifier(loss='ls').fit, X, y) assert_raises(ValueE...
GradientBoostingClassifier(loss='quantile').fit, X, y) assert_raises(ValueError, GradientBoostingClassifier(loss='huber').fit, X, y) assert_raises(ValueError, GradientBoostingRegressor(loss='deviance').fit, X, y) assert_raises(ValueError, Gra...
wheldom01/privacyidea
privacyidea/lib/importotp.py
Python
agpl-3.0
20,360
0.00059
# -*- coding: utf-8 -*- # # 2017-01-23 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Avoid XML bombs # 2016-07-17 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Add GPG encrpyted import # 2016-01-16 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Add PSKC import ...
g_bin) password = modhex_encode(password_bin) return password class ImportException(Exception): def __init__(self, description):
self.description = description def __str__(self): return ('{0!s}'.format(self.description)) def getTagName(elem): match = re.match("^({.*?})(.*)$", elem.tag) if match: return match.group(2) else: return elem.tag @log_with(log) def parseOATHcsv(csv): ''' (#653...
MillerCMBLabUSC/lab_analysis
apps/4f_model/Memos/A2/plots.py
Python
gpl-2.0
658
0.018237
#!/u
sr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Nov 20 20:41:02 2017 @author: 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() plt.plot(freqs, map(ee, freqs)) plt.plot(freqs, map(eo, freqs)) plt.show() print "ae: ",...
neuropoly/spinalcordtoolbox
testing/api/test_qc_parallel.py
Python
mit
1,038
0.00578
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...
z') 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(): """Test many qc images can be made in parallel""" if multiprocessing.cpu_count() < 2: pytest.skip("Can't...
with multiprocessing.Pool(2) as p: p.map(gen_qc, ((i, tmpdir) for i in range(5)))
luke0922/MarkdownEditor
application/models/__init__.py
Python
gpl-2.0
255
0.003922
#!/usr/bin/env python # encoding: 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()
ejegg/FractalEditorSite
util/image.py
Python
gpl-3.0
519
0.001927
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 = fnam...
e(img, 400, x2)
DonBeo/statsmodels
statsmodels/emplike/elregress.py
Python
bsd-3-clause
3,091
0.002588
""" 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...
axis=1) wts = np.ones(nobs) * (1. / nobs) x0 = np.zeros(est_vect.shape[1]).reshape(-1, 1) try: eta_star = self._modif_newton(x0, est_vect, wts)
denom = 1. + np.dot(eta_star, est_vect.T) self.new_weights = 1. / nobs * 1. / denom # the following commented out code is to verify weights # see open issue #1845 #self.new_weights /= self.new_weights.sum() #if not np.allclose(self.new_weights.sum(), 1., rtol=...
plotly/python-api
packages/python/plotly/plotly/validators/scattergeo/marker/colorbar/title/_side.py
Python
mit
569
0
import _plotly_utils.basevalidators class SideValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="side", parent_name="scattergeo.marker.colorbar.title", **kwargs ): super(SideValidator, self).__init__( plotly_name=pl...
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "style"), values=kwargs.pop("values", ["right", "top", "bottom"]), **kwargs )
171121130/SWI
venv/Lib/site-packages/openpyxl/utils/units.py
Python
mit
2,629
0.005325
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...
(value) inch = EMU_to_inch(emu) return inch_to_dxa(inch) def pixels_to_EMU(value): """1 pixel = 9525 EMUs""" return int(value * 9525) def EMU_to_pixels(value): return round(value / 9525)
def cm_to_EMU(value): """1 cm = 360000 EMUs""" return int(value * 360000) def EMU_to_cm(value): return round(value / 360000, 4) def inch_to_EMU(value): """1 inch = 914400 EMUs""" return int(value * 914400) def EMU_to_inch(value): return round(value / 914400, 4) def pixels_to_points(value, ...
eirmag/weboob
weboob/capabilities/housing.py
Python
agpl-3.0
3,610
0.007202
# -*- 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...
" City. """ name = StringField('Name of city') class ICapHousing(IBaseCap): """ Capability of websites to search housings. """ def search_housings(self, query): """ Search housings. :param query: search query :type query: :class:`Query` :rtype: ...
raise NotImplementedError() def get_housing(self, housing): """ Get an housing from an ID. :param housing: ID of the housing :type housing: str :rtype: :class:`Housing` or None if not found. """ raise NotImplementedError() def search_city(self, ...
basicworld/pycrawler
mongo_cache.py
Python
mit
1,791
0.006908
# -*- 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...
3, link_regex='/(index|view)',
max_urls=-1, cache=MongoCache())
cheral/orange3
Orange/canvas/application/outputview.py
Python
bsd-2-clause
6,738
0
""" """ 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): ...
color, weight, background and font properties. """ charformat = QTextCharFormat(baseformat) if color is not None: charforma
t.setForeground(color) if background is not None: charformat.setBackground(background) if font is not None: charformat.setFont(font) else: font = update_font(baseformat.font(), weight, italic, underline) charformat.setFont(font) return charformat def update_font(base...
jstarc/deep_reasoning
visualize.py
Python
mit
3,189
0.014111
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...
mises = premises else: final_premises &= premises final_premises = list(final_premises) with open('results/ext_examples.txt', 'w') as fi: for i in range(len(final_premises)): premise = final_premi
ses[i] fi.write(premise + '\n') for m in models: fi.write(m + '\n') for l in range(3): filtered = subset[m][l][subset[m][l]['premise'] == premise] for f in range(len(filtered)): hypo = filtered['hypo'...
PicoCentauri/GromacsWrapper
doc/sphinx/source/conf.py
Python
gpl-3.0
6,547
0.005346
# -*- 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 ...
. extensions = ['sphinx.ext.au
todoc', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.txt' # The master toctree document. master_doc = 'index' # General substitutions. project = u'GromacsWrapper' copyright = u'2...
dhuang/incubator-airflow
chart/tests/test_create_user_job.py
Python
apache-2.0
3,564
0.001684
# 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...
otations = jmespath.search("metadata.annotations", docs[0]) assert "fiz" in job_annotations assert "fuz" == job_annotations["fiz"] def test_should_create_valid_affinity_tolerations_and_node_selector(self): d
ocs = render_chart( values={ "createUserJob": { "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ ...
lowdev/alfred
speaker/tts/__init__.py
Python
gpl-3.0
169
0
from .google import GoogleSpeaker from .
watson import WatsonSpeaker """ alfred ~~~~~~~~~~~~~~~~ Google tts. """ __all__ = [ 'GoogleSp
eaker', 'WatsonSpeaker' ]
tomjelinek/pcs
pcs_test/tier1/test_cib_options.py
Python
gpl-2.0
32,976
0.000667
from textwrap import dedent from unittest import TestCase from lxml import etree from pcs_test.tools.assertions import AssertPcsMixin from pcs_test.tools.cib import get_assert_pcs_effect_mixin from pcs_test.tools.misc import get_test_resource as rc from pcs_test.tools.misc import ( get_tmp_file, skip_unless_c...
_op) write_data_to_tmpfile(str(xml_manip), self.temp_cib) self.assert_pcs_success(
self.cli_command, stdout_full=dedent( f"""\ Meta Attrs: {self.prefix}-set1 score=10 name1={self.prefix}1 name2={self.prefix}2 Meta Attrs: {self.prefix}-setA name1={self.prefix}A ...
covxx/Random-Python-Stuff
WindowsCalc.py
Python
mit
4,314
0.034771
#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...
utton(image=image16,bd=0).grid(row=8,column=1,padx=2,pady=2) mbutton15 = Button(image=image17,bd=0).grid(row=8,column=2,padx=2,pady=2) mbutton16 = Button(image=image18,bd=0).g
rid(row=8,column=3,padx=2,pady=2) mbutton17 = Button(image=image19,bd=0).grid(row=8,column=4,padx=2,pady=2) mbutton18 = Button(image=image20,bd=0).grid(row=8,column=5,padx=2,pady=2) ####row 5 mbutton19 = Button(image=image21,bd=0).grid(row=9,column=1,padx=2,pady=2) mbutton20 = Button(image=image22,bd=0).grid(row=9,colu...
jskye/car-classifier-research
src/hyp.verification.tools/py/Line.py
Python
mit
564
0.019504
# # 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(self): 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()) + '...
discomethod/pad-helper
constants.py
Python
gpl-2.0
1,240
0.046774
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 gridColumns = 6 # text strings textCalculateCurrentCombos = "Calculate Damage" textClose = "Close" textDamageDisplayAmount = "Total: " textChoosePaint = "Choose a color to paint:" textSolve = "Solve" textTitle = "Puzzle and Dragons Helper" # orbs orbDefault = "light" orbDefaultConfig = ("heal",...
eal","wood","dark","wood","water","light","light","dark","heal","heal","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...
omusico/eav-django
eav/forms.py
Python
lgpl-3.0
5,690
0.003517
# -*- 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...
DateWidget}, 'many': lambda schema: { 'widget': CheckboxSelectMultiple if len(schema.get_choices()) <= 5 else FilteredSelectMultiple(schema.title, is_stacked=False) }, } def __init__(self, data=None, *args, **kwargs): super(BaseDyna...
self).__init__(data, *args, **kwargs) self._build_dynamic_fields() def check_eav_allowed(self): """ Returns True if dynamic attributes can be added to this form. If False is returned, only normal fields will be displayed. """ return bool(self.instance)# and self.inst...
lispascal/lolblender
dumpContents.py
Python
gpl-3.0
10,499
0.015049
#!/bin/python3.1 # ##### BEGIN GPL LICENSE BLOCK ##### # # lolblender - Python addon to use League of Legends files into blender # # 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 ...
else: for material in materials: materialStr += \ "name:%s\nstartVertex:%d\tnumVertices:%d\nstartIndex:%d\tnumIndices:%d\n\n" %\
(bytes.decode(material.name).strip('\x00'),material.startVertex, \ material.numVertices, material.startIndex, material.numIndices) indexStr = "" if(options['PRINT_INDICES']): for indx in indices: indexStr += "%d\n" %(indx[0],) vertexStr = "" if(options['PRINT_...
hgl888/crosswalk-android-extensions
build/idl-generator/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/views/printing.py
Python
bsd-3-clause
20,171
0.003322
# Copyright (C) 2010, 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions an...
debug-rwt-logging', action='store_true', default=False, help='print timestamps and debug information for run-webkit-tests itself'), optparse.make_option('--details', action='store_true', default=False, help='print detailed results for every test'), ...
--quiet', action='store_true', default=False, help='run quietly (errors, warnings, and progress only)'), optparse.make_option('--timing', action='store_true', default=False, help='display test times (summary plus per-test w/ --verbose)'), optpars...
dnerdy/django-reroute
setup.py
Python
mit
982
0.002037
#!/usr/bin/python from distutils.core import setup # Remember to change in reroute/__init__.py as well! VERSION = '1.1.1' setup( name='dj
ango-reroute', version=VERSION, description="A drop-in replacement for django.conf.urls.defaults which supports HTTP verb dispatch and view wrapping.", long_description=open('README.rst').read(), author='Mark Sandstrom', author_email='mark@deliciouslynerdy.com', url='http://github.com/dnerdy/d
jango-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 ...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/google/appengine/api/conf.py
Python
bsd-3-clause
11,771
0.008156
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
lidationError( 'Expected scalar value for parameter: %s, but found %.100r which ' 'is type %s' % (key, value, type(value).__name__)) return value class _ParameterDict(validation.ValidatedDict): """This class validates the parameters dictionary in YAMLConfiguration. Keys must look like no...
AMLConfiguration. """ KEY_VALIDATOR = _ValidParameterName() VALUE_VALIDATOR = _Scalar() class YAMLConfiguration(validation.Validated): """This class describes the structure of a conf.yaml file. At the top level the file should have a params attribue which is a mapping from strings to scalars. For exampl...
WheatonCS/Lexos
lexos/views/consensus_tree.py
Python
mit
1,164
0
from flask import session, Blueprint from lexos.managers import session_manager from lexos.helpe
rs 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-tree", methods=["GET"]) def consensus_tree() -> str: """Gets the consensus tree page. :re...
n: session["analyoption"] = constants.DEFAULT_ANALYZE_OPTIONS if "bctoption" not in session: session["bctoption"] = constants.DEFAULT_BCT_OPTIONS # Return the consensus tree page return render("consensus-tree.html") @consensus_tree_blueprint.route("/consensus-tree/graph", methods=["POST"]...
rajpushkar83/cloudmesh
cloudmesh/pbs/pbs_note.py
Python
apache-2.0
4,485
0.001115
""" 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...
mperature': '10.2', 'service': 'hpc'" # kvpair_list = ", ".join([": ".join(map(lambda x: "'".join(["", str(x), ""]), [key, prev_note[key]])) for key in sorted(prev_note.keys())]) # snote =
"".join(['{', kvpair_list, '}']) # sshnote = '"'.join(["", snote, ""]) # try get the dict string with json dumps sshnote = json.dumps(curr_note) # update the note attribute in memory to real node command = " ".join(["pbsnodes -N", sshnote, node_label]) str_ssh = "@".joi...
Dangetsu/vnr
Frameworks/Sakura/py/apps/reader/dialogs/commentinput.py
Python
gpl-3.0
3,917
0.012254
# 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 ...
, q): self._createUi(q) def _createUi(self, q): self.edit = QtWidgets.QLineEdit() skqss.class_(self.edit, 'normal') grid = QtWidgets.QGridLayout() r = 0 self.updateCommentButton = QtWidgets.QRadioButton(mytr_("Update reason")) self.updateCommentButton.setChecked(True) self.commentBut...
.QButtonGroup(q) g.addButton(self.updateCommentButton) g.addButton(self.commentButton) grid.addWidget(create_label(tr_("Property")), r, 0) for i,b in enumerate(g.buttons()): grid.addWidget(b, r, i+1) r += 1 self.appendButton = QtWidgets.QRadioButton(tr_("Append")) self.appendButton.se...
snowch/movie-recommender-demo
web_app/app/dao.py
Python
apache-2.0
12,507
0.006796
from datetime import datetime import time import os, json import requests import urllib from . import app from app.cloudant_db import cloudant_client from app.redis_db import get_next_user_id from typing import List, Dict, Optional from cloudant.document import Document from cloudant.database import CloudantDatabase C...
print('recommendation_metadata d
oc not found in', CL_RECOMMENDDB) raise RecommendationsNotGeneratedException timestamp_str = doc['timestamp_utc'] import dateutil.parser return dateutil.parser.parse(timestamp_str) @staticmethod def get_recommendations_or_product_features(user_id: str) -> Dict: """...
pavanad/emec-api
emec/emec.py
Python
mit
8,481
0.001061
# -*- conding: utf-8 -*- import base64 import json from unicodedata import normalize import requests 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 da...
except Exception as error: print(f"{error}") return 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.tbod...
url_list = r.td.a["href"].split("/") code_course = url_list[len(url_list) - 1] course_details = self.__parse_course_details(code_course) if course_details: courses += course_details self.data_ies["courses"] = courses r...
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_dressed_garm_bel_iblis.py
Python
mit
447
0.04698
#### 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/s
hared_dressed_garm_bel_iblis.iff" result.attribut
e_template_id = 9 result.stfName("npc_name","human_base_male") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
osvalr/maintainer-tools
tools/oca_projects.py
Python
agpl-3.0
5,555
0.00018
# -*- 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...
], 'community': ['maintainers-tools', 'maintainer-quality-tools', 'runbot-addons', ], 'connector': ['connector', 'connector-ecommerce', ], 'account edge connector': ['connector-accountedge'], 'connect...
'connector-prestashop'], 'connector sage': ['connector-sage-50'], 'crm sales marketing': ['sale-workflow', 'crm', 'partner-contact', 'sale-financial', 'sale-reporting', 'co...
DIRACGrid/DIRAC
src/DIRAC/RequestManagementSystem/Client/ReqClient.py
Python
gpl-3.0
28,083
0.002635
""" :mod: ReqClient .. module: ReqClient :synopsis: implementation of client for RequestDB using DISET framework """ import os import time import random import json import datetime # # from DIRAC from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Utilities.List import randomize, fromChar from DIRAC.Core.Ut...
etRequest(requestID) if not getRequest["OK"]: self.log.error("getRequest: unable to get request", "'%s' %s" % (requestID, getRequest["Message
"])) return getRequest if not getRequest["Value"]: return getRequest return S_OK(Request(getRequest["Value"])) @ignoreEncodeWarning def getBulkRequests(self, numberOfRequest=10, assigned=True): """get bulk requests from RequestDB :param self: self refere...
algorhythms/LeetCode
470 Implement Rand10() Using Rand7().py
Python
mit
773
0
#!/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...
9 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
qpiel/python_estimation_source
Example/ExReadFermiCatalog.py
Python
gpl-3.0
1,737
0.039724
# 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...
akeSpectrum("2FGL",1e-4,0.3) enerbut2FGL,but2FGL,enerphi2FGL,phi2FGL = Cat.Plot("2FGL") Cat.MakeSpectrum("2FHL",5e-2,2) enerbut2FHL,but2FHL,enerphi2FHL,phi2FHL = Cat.Plot("2FHL") #
read DATA Point em,ep,flux,dflux = Cat.GetDataPoints('3FGL') #energy in TeV since the user ask for that in the call of Cat ener = numpy.sqrt(em*ep) 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 =...
Makki1/old-svn
avr/sketchbook/GiraRM_Debug/freebus/freebus_ets/software/freebus-ets/eibnet/grouplisten.py
Python
gpl-3.0
2,687
0.040194
#!/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...
) except (Exception), e: print e for i in sys.argv[2:]: dest = readgaddr (i) if (eibclient.eibclient.EIBOpenT_Group (con, dest, 0) == -1): print "Connect failed" sys.exit(1)
; if con == None: print "Open failed"; sys.exit(1); while 1: (result, buf, src) = eibclient.eibclient.EIBGetAPDU_Src (con) if len(buf) < 2: print "Read failed" sys.exit(1) if (ord(buf[0]) & 0x3 or (ord(buf[1]) & 0xc0) == 0xc0): print"Unknown APDU f...
poeks/twitterbelle
lib/bitly.py
Python
apache-2.0
7,225
0.01301
#!/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...
res.append(item['shortKeywordUrl']) if len(res) == 1: return res[0] else: return res def expand(self,shortURL): """ Given a bit.ly url or hash, return long source url """ request = self._getURL("expand",shortURL) result = ...
f._fetchUrl(request) json = simplejson.loads(result) self._CheckForError(json) return json['results'][string.split(shortURL, '/')[-1]]['longUrl'] def info(self,shortURL): """ Given a bit.ly url or hash, return information about that page, such as ...
nuagenetworks/vspk-python
vspk/v6/nuegressauditacltemplate.py
Python
bsd-3-clause
21,660
0.008726
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyrigh...
E USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .fetchers import NUPermissionsFetcher from .fetchers import NUMetadatasFetcher from .fetchers import NUEgressAuditACLEntryTemplatesFetcher from .fetchers import NUGlobalMetadatasFetcher from bambou import NURESTObject class N...
essAuditACLTemplate(NURESTObject): """ Represents a EgressAuditACLTemplate in the VSD Notes: An egress audit policy is a set of rules defining how network traffic is monitored and mirrored from a domain for Audit purposes """ __rest_name__ = "egressauditacltemplate" __resource_name...
unbracketed/RedLine
redline/examples/redis-import-set_groupby.py
Python
mit
554
0.018051
# redis-import-set import sys from
csv import reader from itertools import count, groupby, islice import redis 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, _ i...
line_redis.execute()
goerz/clusterjob
tests/test_inifile.py
Python
mit
10,660
0.001689
from textwrap import dedent import inspect from collections import OrderedDict from clusterjob import JobScript import pytest import logging try: from ConfigParser import Error as ConfigParserError except ImportError: from configparser import Error as ConfigParserError # built-in fixtures: tmpdir # pytest-captu...
of object or class""" return sorte
d([k for (k, v) in inspect.getmembers(obj, inspect.isroutine)]) # isroutine works in Python 2 and Python 3, while ismethod does not work in # Python 3 if obj is a class (since the methods are not *bound*) def get_attributes(obj, hidden=False): """Get list of attributes of object""" methods = get_metho...
HPPTECH/hpp_IOSTressTest
Refer/Alignment.py
Python
mit
995
0.009045
#!/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(...
ize_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") hbox.add(ok) hbox.add(close) halign = gtk.Alignment(1, 0, 0, 0) halign.add(hbox) vbox.pack_start(halign, False, False, 3) self.add(vbox) self.connect("destroy", gtk.main_quit) self.show_all() ...
andrewfu0325/gem5-aladdin
sweeps/benchmarks/__init__.py
Python
bsd-3-clause
55
0
__
all__ = ["machsuite", "shoc", "datatypes", "params"
]
eduNEXT/edunext-platform
cms/djangoapps/contentstore/views/preview.py
Python
agpl-3.0
13,137
0.00236
# lint-amnesty, pylint: disable=missing-module-docstring import logging from functools import partial from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponseBadRequest from django.urls import reverse from django.utils.translation import ...
est_token, wrap_fragment, wrap_xblock, wrap_xblock_aside, xblock_loc
al_resource_url ) from xmodule.contentstore.django import contentstore from xmodule.error_module import ErrorBlock from xmodule.exceptions import NotFoundError, ProcessingError from xmodule.modulestore.django import ModuleI18nService, modulestore from xmodule.partitions.partitions_service import PartitionService from x...
lightning18/rcj-leaderboards
leaderboards/leagues/models.py
Python
mit
3,288
0.002433
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', ] ...
eTimeField(auto_now=True) class FleaLeague(UUIDModel): name = models.CharField(max_length=128) url = models.URLField(unique=True, null=False, blank=False) division = models.ForeignKey('RedditLeagueDivision', related_name='leagues') last_updated = models.DateTimeField(auto_now=True) def fetch_leag...
) # MOVE THIS for memoization to work self.name = tree.xpath('//*[@id="top-bar"]/ul/li[2]/text()')[0] # Fetch teams teams = tree.xpath('//*[@id="table_0"]/tr') for team in teams: team_name = team.xpath('td/div[contains(@class, "league-name")]/a/text()')[0] team...
martyone/sailfish-qtcreator
tests/system/suite_tools/tst_git_first_commit/test.py
Python
lgpl-2.1
4,000
0.00875
############################################################################# ## ## 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...
Lv3 included in the packaging of this file. Please review th
e ## following information to ensure the GNU Lesser General Public License ## requirements will be met: https://www.gnu.org/licenses/lgpl.html and ## http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ## ## In addition, as a special exception, The Qt Company gives you certain additional ## rights. These rights ar...
jbecke/VR-Vendor
AmazonCompetition/Content/Scripts/record.py
Python
mit
3,740
0.004813
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...
snd_data, seconds): "Add silence to the start and end of 'snd_data' of length 'seconds' (float)" r = array('h', [0 for i in range(int(seconds*RATE))]) r.extend(snd_data) r.extend([0 for i in range(int(seconds*RATE))]) return r def record(): """ Record a word or words from the micro...
with 0.5 seconds of blank sound to make sure VLC et al can play it without getting chopped off. """ p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=1, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE) num_silent = 0 snd_started = Fa...
ladybug-analysis-tools/honeybee-plus
plugin/src/fivephasegbrecipe_node.py
Python
gpl-3.0
906
0.007726
# 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: ...
diance.recipe.fivephase.gridbased import FivePhaseGridBased except ImportError as e: raise Im
portError('\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 illuminance simulation.') analysisRecipe = FivePhaseGridBased( ...
kperun/nestml
pynestml/frontend/nestml_error_listener.py
Python
gpl-2.0
4,293
0.003261
# # 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...
stop_index, prediction, configs): if self.report_ambiguity: msg = u"reportContextSensitivity d=" msg += self.getDecisionDescription(recognizer, dfa) msg += u", input='" msg += recognizer.getTokenStre
am().getText((start_index, stop_index)) msg += u"'" code, message = Messages.get_syntax_warning_in_model(msg) Logger.log_message(code=code, message=message, error_position=ASTSourceLocation(start_index, stop_index, ...
group-policy/rally
tests/ci/osresources.py
Python
apache-2.0
8,981
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
objects.Endpoint(**kwargs) self.clients = osclients.Clients(endpoint) def _deduplicate(self, lst): """Change list duplicates to make all items unique. >>> resources._deduplicate(["a", "b", "c", "b", "b"]) >>> ['a', 'b', 'c', 'b (duplicate 1)', 'b (duplicate 2)' """ ...
while try_value in deduplicated_list: ctr += 1 try_value = "%s (duplicate %i)" % (value, ctr) value = try_value deduplicated_list.append(value) return deduplicated_list def list(self): managers_classes = discover.iters...