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 |
|---|---|---|---|---|---|---|---|---|
gotche/django-basic-project | project_name/project_name/settings/base.py | Python | apache-2.0 | 1,387 | 0.000721 | import os
from configurations import values
from django.conf import global_settin | gs
class DjangoSettings(object):
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = values.SecretValue()
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
| 'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',... |
JamesMura/sentry | tests/sentry/web/frontend/test_create_organization.py | Python | bsd-3-clause | 1,205 | 0 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.models import Organization, OrganizationMember
from sentry.testutils import TestCase
class CreateOrganizationTest(TestCase):
@fixture
def path(self):
return reverse('sentry-create... | n_as(self.user)
resp = self.client.post(self.path, {
'name': 'bar',
})
assert resp.status_code == 302
org = Or | ganization.objects.get(name='bar')
assert OrganizationMember.objects.filter(
organization=org,
user=self.user,
role='owner',
).exists()
assert org.team_set.exists()
redirect_uri = reverse('sentry-create-project', args=[org.slug])
assert resp... |
laurencium/CausalInference | tests/test_tools.py | Python | bsd-3-clause | 1,433 | 0.028611 | from nose.tools import *
import numpy as np
import causalinference.utils.tools as t
def test_convert_to_formatting( | ):
entry_types = ['string', 'float', 'integer', 'float']
ans = ['s', '.3f', | '.0f', '.3f']
assert_equal(list(t.convert_to_formatting(entry_types)), ans)
def test_add_row():
entries1 = ('Variable', 'Mean', 'S.d.', 'Mean', 'S.d.', 'Raw diff')
entry_types1 = ['string']*6
col_spans1 = [1]*6
width1 = 80
ans1 = ' Variable Mean S.d. Mean S.d. Raw di... |
GeotrekCE/Geotrek-admin | geotrek/common/translation.py | Python | bsd-2-clause | 470 | 0 | from modeltranslation.translator import translator, TranslationOptions
from geotrek.common.models | import TargetPortal, Theme, Label
class ThemeTO(TranslationOptions):
fields = ('label', )
class TargetPortalTO(TranslationOptions):
fields = ('title', 'description')
class LabelTO(TranslationOptions):
fields = ('name', 'advi | ce')
translator.register(Theme, ThemeTO)
translator.register(TargetPortal, TargetPortalTO)
translator.register(Label, LabelTO)
|
7kbird/chrome | android_webview/tools/webview_licenses.py | Python | bsd-3-clause | 13,334 | 0.011999 | #!/usr/bin/python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Checks third-party licenses for the purposes of the Android WebView build.
The Android tree includes a snapshot of Chromium in orde... | exp shorter
excluded_dirs_list.append('third_party')
# VCS dirs
excluded_dirs_list.append('.git')
excluded_dirs_l | ist.append('.svn')
# Build output
excluded_dirs_list.append('out/Debug')
excluded_dirs_list.append('out/Release')
# 'Copyright' appears in license agreements
excluded_dirs_list.append('chrome/app/resources')
# Quickoffice js files from internal src used on buildbots. crbug.com/350472.
excluded_dirs_list.a... |
isard-vdi/isard | engine/engine/engine/services/db/downloads.py | Python | agpl-3.0 | 1,652 | 0.001211 | from engine.services.db import close_rethink_connection, new_rethink_connection
from engine.services.log import *
from rethinkdb import r
def get_media(id_media):
r_conn = new_rethink_connection()
d = r.table("media").get(id_media).run(r_conn)
close_rethink_connection(r_conn)
return d
def get_down... |
r.table("media")
.get_all(r.args(["DownloadStarting", "Downloading"]), index="status")
| .pluck("id", "path", "isard-web", "status")
.run(r_conn)
)
except r.ReqlNonExistenceError:
d = []
close_rethink_connection(r_conn)
return d
def update_status_table(table, status, id_table, detail=""):
r_conn = new_rethink_connection()
detail = str(detail)
d = {"s... |
dmwelch/Py6S | setup.py | Python | gpl-3.0 | 2,575 | 0.014757 | #!/usr/bin/env python
# This file is part of Py6S.
#
# Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file.
#
# Py6S is free software: you can redistribute it and/or modify
# i | t under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Py6S is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHA | NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Py6S. If not, see <http://www.gnu.org/licenses/>.
import os
from setuptools import setup
PROJECT_ROOT = os.path.dirn... |
mrnamingo/vix4-34-enigma2-bcm | lib/python/Screens/PluginBrowser.py | Python | gpl-2.0 | 17,217 | 0.027531 | from boxbranding import getImageVersion
from urllib import urlopen
import socket
import os
from enigma import eConsoleAppContainer, eDVBDB
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.PluginComponent import plugins
from Components.PluginList import PluginList, PluginEnt... | (Setup, "pluginbrowsersetup")
def saveListsize(self):
listsize = self["list"].instance.size()
self.listWidth = listsize.width()
self.listHeight = listsize.height()
def createSummary(self):
return PluginBrowserSummary
| def selectionChanged(self):
item = self["list"].getCurrent()
if item:
p = item[0]
name = p.name
desc = p.description
else:
name = "-"
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def checkWarnings(self):
if len(plugins.warnings):
text = _("Some plugins are not available:\n")... |
tpeek/django-imager | imagersite/imager_images/migrations/0006_auto_20150729_1539.py | Python | mit | 729 | 0.002743 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('imager_images', '0005_auto_20150728_0129'),
]
operations = [
migrations. | AlterField(
model_name='album',
name='privacy',
field=models.CharField(max_length=64, choices=[(b'Private', b'Private'), (b'Shared', b'Shared'), (b'Public', b'Public')]),
),
migrations.AlterField(
model_name='photo',
name='privacy',
... | ),
]
|
MTG/essentia | test/src/unittests/streaming/test_tensortopool.py | Python | agpl-3.0 | 7,481 | 0.002673 | #!/usr/bin/env python
# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... | ected one.
# Found values will be trimmed to | fit the expected shape.
# No remaining frames.
numberOfFrames = 43
found, expected = self.identityOperation(patchSize=numberOfFrames,
lastPatchMode='repeat')
self.assertAlmostEqualMatrix(found, expected, 1e-8)
# Some remaining fr... |
inventree/InvenTree | InvenTree/stock/migrations/0068_stockitem_serial_int.py | Python | mit | 390 | 0 | # Generated by Django 3.2.5 on 2021-11-09 23:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stock', '0067_al | ter_stockitem_part'),
]
operations = [
migrations. | AddField(
model_name='stockitem',
name='serial_int',
field=models.IntegerField(default=0),
),
]
|
tiffanyjaya/kai | vendors/pdfminer.six/pdfminer/pdfdevice.py | Python | mit | 5,469 | 0.001828 |
from .pdffont import PDFUnicodeNotDefined
from . import utils
## PDFDevice
##
class PDFDevice(object):
def __init__(self, rsrcmgr):
self.rsrcmgr = rsrcmgr
self.ctm = None
return
def __repr__(self):
return '<PDFDevice>'
def close(self):
return
def set_ctm(s... | font, fontsize, scaling, rise, cid):
return 0
## TagExtractor
##
class TagExtractor(PDFDevice):
def __init__(self, rsrcmgr, outfp, codec='utf-8'):
PDFDevice.__init__(self, rsrcmgr)
self.outfp = outfp
self.codec = codec
self.pageno = 0
| self._stack = []
return
def render_string(self, textstate, seq):
font = textstate.font
text = ''
for obj in seq:
obj = utils.make_compat_str(obj)
if not isinstance(obj, str):
continue
chars = font.decode(obj)
for cid in... |
sebp/scikit-survival | doc/conf.py | Python | gpl-3.0 | 12,460 | 0.001926 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# scikit-survival documentation build configuration file
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a... | me = "doc/" + env.doc2path(env.docname, base=None) %}
{% set notebook = env.doc2path(env.docname, base=None)|replace("user_guide/", "notebooks/") %}
{% set branch = 'master' if 'dev' in env.config.release else 'v{}'.format(env.config.release) %}
.. raw:: html
<div class | ="admonition note" style="line-height: 150%;">
This page was generated from
<a class="reference external" href="https://github.com/sebp/scikit-survival/blob/{{ branch|e }}/{{ docname|e }}">{{ docname|e }}</a>.<br/>
Interactive online version:
<span style="white-space: nowrap;"><a href="https://m... |
chenjj/dionaea | modules/python/scripts/ihandlers.py | Python | gpl-2.0 | 5,570 | 0.024237 | #********************************************************************************
#* Dionaea
#* - catches bugs -
#*
#*
#*
#* Copyright (C) 2010 Markus Koetter & Tan Kean Siong
#* Copyright (C) 2009 Paul Baecher & Markus Koetter & Mark Schloesser
#*
#* This prog... | ng
for client in g_dionaea.config()['modules']['python']['logxmpp']:
conf = g_dionaea.config()['modules']['python']['logxmpp'][client]
if 'resource' in conf:
resource = conf['resource']
else:
resource = ''.join([choice(string.ascii_letters) for i in range(8)])
print("client %s \n\tserver %s:%s use... | resource, conf['muc'], conf['config']))
x = dionaea.logxmpp.logxmpp(conf['server'], int(conf['port']), conf['username'], conf['password'], resource, conf['muc'], conf['config'])
g_handlers.append(x)
if "nfq" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.nfq
g_handlers.... |
OpnSrcConstruction/OSCbashRCs | .ipython/profile_debug/ipython_config.py | Python | unlicense | 23,357 | 0.014043 | # Configuration file for ipython.
#------------------------------------------------------------------------------
# InteractiveShellApp(Configurable) configuration
#------------------------------------------------------------------------------
## A Mixin for applications that start InteractiveShell instances.
#
# ... | 3.5.2 (default, Nov 23 2017, 16:37:01) \nType 'copyright', 'credits' or 'license' for more information\nIPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.\n"
## The part of the banner to be printed after the profile
#c.InteractiveShell.b | anner2 = ''
## Set the size of the output cache. The default is 1000, you can change it
# permanently in your config file. Setting it to 0 completely disables the
# caching system, and the minimum value accepted is 3 (if you provide a value
# less than 3, it is reset to 0 and a warning is issued). This limit is ... |
donhoffman/pi-keypad-controller | src/door_latch.py | Python | gpl-2.0 | 4,286 | 0.0028 | import datetime
import logging
import sqlite3
import time
from os import environ
import relays
class Latch:
DIGIT_TIMEOUT = 60
LOCKOUT_TIMEOUT = 300
LOCKOUT_THRESHOLD = 5
VALID_CH = set('0123456789#*')
def __init__(self, latch_id, latch_index):
self._logger = logging.getLogger(__name__)... | 'Too may attempts. Lockout for %s seconds', int(self.LOCKOUT_TIMEOUT))
self._invalid_count = 0
self._time_end_lockout = time.time() + self.LOCKOUT_TIMEOUT
return False
#Note: we don't lock out on permission issues
#Valid user. Check per... | row[0])
c.execute('''
SELECT enabled, use_timeout, not_before, not_after
FROM permissions WHERE name=? AND keypad_id=?''', (name, self._latch_id))
row = c.fetchone()
if not row:
logging.error('User \'%s\' has no permissions.', name)
... |
ArcherSys/ArcherSys | skulpt/src/lib/pythonds/graphs/adjGraph.py | Python | mit | 3,004 | 0.015313 | #
# adjGraph
#
# Created by Brad Miller on 2005-02-24.
# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.
#
import sys
import os
import unittest
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
... | lf.dist = sys.maxsize
self.pred = None
| self.disc = 0
self.fin = 0
# def __lt__(self,o):
# return self.id < o.id
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def setColor(self,color):
self.color = color
def setDistance(self,d):
self.dist = d
def setPred... |
MungoRae/home-assistant | tests/components/device_tracker/test_init.py | Python | apache-2.0 | 29,746 | 0.000034 | """The tests for the device tracker component."""
# pylint: disable=protected-access
import asyncio
import json
import logging
import unittest
from unittest.mock import call, patch
from datetime import datetime, timedelta
import os
from homeassistant.components import zone
from homeassistant.core import callback, Stat... | = mock_warning.call_args
assert 'Duplicate device IDs' in args[0], \
'Duplicate device IDs warning expected'
def test_setup_without_yaml_file(self):
"""Test with no YAML file."""
with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass... | """Test the adding of unknown devices to configuration file."""
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
scanner.come_home('DEV1')
with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, {... |
jkatzer/flask-restless | flask_restless/views.py | Python | agpl-3.0 | 72,094 | 0.000236 | """
flask.ext.restless.views
~~~~~~~~~~~~~~~~~~~~~~~~
Provides the following view classes, subclasses of
:class:`flask.MethodView` which provide generic endpoints for interacting
with an entity of the database:
:class:`flask.ext.restless.views.API`
Provides the endpoints for each of the ... | is Microsoft Internet Explorer 8 or 9.
.. note::
We have no way of knowing if the user agent is lying, so we just make
our best guess based on the information provided.
"""
# request.user_agent.version comes as a string, so we have to parse it
version = lambda ua: tuple(int(d) for d in... | == 'msie'
and (8, 0) <= version(request.user_agent) < (10, 0))
def create_link_string(page, last_page, per_page):
"""Returns a string representing the value of the ``Link`` header.
`page` is the number of the current page, `last_page` is the last page in
the pagination, and `per_page` is the ... |
diogo149/CauseEffectPairsPaper | configs/max_aggregate_only.py | Python | mit | 7,294 | 0.001508 | import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlati | on, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeucl | idean
from sklearn.preprocessing import LabelBinarizer
from sklearn.linear_model import Ridge, LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, RandomForestClassifier, GradientBoosti... |
seecr/meresco-components | test/_http/pathfiltertest.py | Python | gpl-2.0 | 3,628 | 0.002756 | ## begin license ##
#
# "Meresco Components" are components to build searchengines, repositories
# and archives, based on "Meresco Core".
#
# Copyright (C) 2007-2009 SURF Foundation. http://www.surf.nl
# Copyright (C) 2007 SURFnet. http://www.surfnet.nl
# Copyright (C) 2007-2010 Seek You Too (CQ2) http://www.cq2.nl
# C... | th(self):
f = PathFilter('/path')
f.addObserver(self.interceptor)
consume(f.handleRequest(path='/other/path'))
self.assertEqual(0, len(self.interceptor.calledMethods))
def testPaths(self):
f = PathFilter(['/pat | h', '/other/path'])
f.addObserver(self.interceptor)
consume(f.handleRequest(path='/other/path'))
self.assertEqual(1, len(self.interceptor.calledMethods))
def testExcludingPaths(self):
f = PathFilter('/path', excluding=['/path/not/this'])
f.addObserver(self.interceptor)
... |
PabloCastellano/nodeshot | nodeshot/ui/default/tests/selenium.py | Python | gpl-3.0 | 50,260 | 0.005611 | from __future__ import absolute_import
from time import sleep
from django.core.urlresolvers import reverse
from django.test import TestCase
from nodeshot.core.base.tests import user_fixtures
from nodeshot.core.nodes.models import Node
from nodeshot.ui.default import settings as local_settings
from selenium import we... | t_until_ajax_complete(10, 'Timeout')
def _reset(self):
""" reset and reload browser (clear localstorage and go to index) """
self._hashchange('#/')
self.browser.execute_script('l | ocalStorage.clear()')
self.browser.delete_all_cookies()
self.browser.refresh()
self._wait_until_ajax_complete(10, 'Timeout')
def _login(self, username='admin', password='tester', open_modal=True):
if open_modal:
# open sign in modal
self.browser.find_element_... |
dexy/cashew | example/classes1.py | Python | mit | 748 | 0.012032 | ### "imports"
from example.classes import Data
### "other-imports"
import csv
import json
from example.utils import tempdir
### "csv-subclass"
class Csv(Data):
"""
CSV type.
"""
aliases = ['csv']
def present(self):
with tempdir():
with open("dictionary.csv", "w") as f:
... | JSON type.
"""
| aliases = ['json']
def present(self):
return json.dumps(self.data)
|
Johnzero/erp | openerp/addons/hr_timesheet/wizard/hr_timesheet_sign_in_out.py | Python | agpl-3.0 | 8,655 | 0.006009 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | tate': fields.related('emp_id', 'state', string='Current state', type='char', required=True, readonly=True),
'date': fields.datetime('Starting Date'),
'server_date': fields.datetime('Current Date', readonly=True),
'emp_i | d': fields.many2one('hr.employee', 'Employee ID')
}
def view_init(self, cr, uid, fields, context=None):
"""
This function checks for precondition before wizard executes
@param self: The object pointer
@param cr: the current row, from the database cursor,
@par... |
xuru/pyvisdk | pyvisdk/enums/event_category.py | Python | mit | 239 | 0 |
############### | #########################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
EventCategory = Enum(
'error',
'info', |
'user',
'warning',
)
|
vegitron/django-handlebars-i18n | setup.py | Python | apache-2.0 | 284 | 0.007042 | #!/usr/bin/env python
from distutils.core import setup
setup(name='Django-Handlebars-I18N',
version='1.0',
description='Tools for using django translations in handlebars templa | tes, and making it easier to use translations.' | ,
install_requires=['importlib'],
)
|
petrmikheev/miksys | miksys_soft/pack_usb.py | Python | gpl-3.0 | 662 | 0.009063 | #!/usr/bin/python
#coding: utf8
import sys, struct
data_size = 2*1024*1024
if len(sys.argv) != 3:
print 'Using: ./pack_usb.py input.bin output.bin'
sys.exit(0)
fin = file(sys.argv[1], 'rb')
data = fin.read()
print 'Size: %d bytes' % len(data)
if len(data) > data_size-2:
print 'Error: too | big'
sys.exit(0)
data += b'\xa5'*(data_size-2-len(data))
fout = file(sys.argv[-1], 'wb')
fout.write(data)
checksum = sum([struct.unpack('<H', data[i:i+2])[0] for i in range(0, len(data), 2)]) % 0x10000
#fout.write(b'\0'*(data_size-2-len(d | ata)))
print 'Checksum: 0x%04x' % checksum
fout.write(struct.pack('<H', (0x1aa55-checksum)%0x10000))
fout.close()
|
jib/aws-analysis-tools | instances.py | Python | mit | 6,405 | 0.02217 | #!python
import re
import sys
import logging
import boto.ec2
from texttable import Texttable
from pprint import PrettyPrinter
from optparse import OptionParser
PP = PrettyPrinter( indent=2 )
###################
### Arg parsing
###################
parser = OptionParser("usage: %prog [options]" )
parser.add_... | help="Exclude instances with | these names (regex)" )
parser.add_option( "-t", "--type", default=None,
help="Include instances with these types only (regex)" )
parser.add_option( "-T", "--exclude-type", default=None,
help="Exclude instances with these types (regex)" )
parser.add_option( "-z", "--zon... |
rahulunair/nova | nova/conductor/tasks/base.py | Python | apache-2.0 | 1,651 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | d_reraise_exception():
self.rollback(ex)
return wrap
@six.add_metaclass(abc.ABCMeta)
class TaskBase(object):
def __init__(self, context, instance):
self.context = context
self.instance = instance
@rollback_wrapper
def execute(self):
"""Run task's logic, writte... | turn self._execute()
@abc.abstractmethod
def _execute(self):
"""Descendants should place task's logic here, while resource
initialization should be performed over __init__
"""
pass
def rollback(self, ex):
"""Rollback failed task
Descendants should implement ... |
wood-galaxy/FreeCAD | src/Mod/Fem/FemTools.py | Python | lgpl-2.1 | 29,560 | 0.004432 | # ***************************************************************************
# * *
# * Copyright (c) 2015 - Przemo Firszt <[email protected]> *
# * Copyright (c) 2015 - Bernd Hahnebach <[email protected]> *
# * ... | ied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * | *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA ... |
mizahnyx/panda3dplanetgen | mecha01/character_controller.py | Python | bsd-3-clause | 66 | 0 | class CharacterContr | oller():
def __init__(sel | f):
pass
|
Itxaka/st2 | st2tests/st2tests/fixturesloader.py | Python | apache-2.0 | 13,382 | 0.002167 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | ict
all_fixtures[fixture_type] = loaded_fixtures
return all_fixtures
def load_models(self, fixtures_pack='generic', fixtures_dict=None):
"""
Loads fixtures specified in fixtures_dict as db models. This method must be
used for fixtures that h | ave associated DB models. We simply want to load the
meta as DB models but don't want to save them to db.
fixtures_dict should be of the form:
{
'actions': ['action-1.yaml', 'action-2.yaml'],
'rules': ['rule-1.yaml'],
'liveactions': ['execution-1.yaml']
... |
nicholasRutherford/nBodySimulator | examples/figureEight.py | Python | mit | 669 | 0.007474 | from nBody.src.body import Body
from nBody.src.nBodySimulator import NBodySimulator
time_step = 0.01
frame_step = 1
length = 20
plot_size = 1.5
file_name = 'figure_eight.mp4'
# X | Y Xv Yv Mass
b1 = Body( 0.9700436, -0.24308753, 0.4666203685, 0.43236573, 1.0)
b2 = Body( -0.9700436, 0.24308753, 0.4666203685, 0.43236573, 1.0)
b3 = Body( 0.0, 0.0, -2*0.4666203685, -2*0. | 43236573, 1.0)
bodies = [b1, b2, b3]
sim = NBodySimulator(bodies)
sim.setG(1)
sim.run(bodies, time_step=time_step, frame_step=frame_step,
length=length, plot_size=plot_size, file_name=file_name)
|
novoid/Memacs | memacs/git.py | Python | gpl-3.0 | 7,503 | 0.001466 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2019-11-06 15:23:39 vk>
import logging
import os
import sys
import time
from orgformat import OrgFormat
from memacs.lib.memacs import Memacs
from memacs.lib.orgproperty import OrgProperties
class Commit(object):
"""
class for representing one co... | lf.__em | pty = False
if line != "":
whitespace = line.find(" ")
tag = line[:whitespace].upper()
value = line[whitespace:]
self.__properties.add(tag, value)
if tag == "AUTHOR":
self.__set_author_timestamp(line)
def add_body(self, line):
... |
openstack/swift | test/unit/container/test_reconciler.py | Python | apache-2.0 | 96,529 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | .register('DELETE', container_path,
swob.HTTPConflict, {}, '')
# simple account listing entry
container_data = {'name': container}
account_listing_data.append(container_data)
# register account response
account_lis... | =' |
phiros/nepi | src/nepi/execution/runner.py | Python | gpl-3.0 | 6,329 | 0.009164 | #
# NEPI, a framework to manage network experiments
# Copyright (C) 2013 INRIA
#
# 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 3 of the License, or
# (at your ... | alue, but it can be several).
metric = compute_metric_callback(ec, run)
:type compute_metric_callback: function
:param evaluate_convergence_callback: User defined function invoked after
computing the metric on each run, to evaluate the experiment was
... | the compute_metric_callback up to the current run, and decided
whether the metrics have statistically converged to a meaningful value
or not. It must return either True or False.
stop = evaluate_convergence_callback(ec, run, metrics)
If stop is True, t... |
MTG/essentia | src/python/essentia/algorithms.py | Python | agpl-3.0 | 5,502 | 0.007997 | # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), either version 3 of the ... | Decrease):
def configure(self, blockSize, | sampleRate = 44100, **kwargs):
essentia.Decrease.configure(self, range = (blockSize-1.0)/sampleRate)
setattr(essentia, 'AudioDecrease', AudioDecrease)
# SpectralCentroid
class SpectralCentroid(essentia.Centroid):
def configure(self, sampleRate = 44100, **kwargs):
essentia.... |
sniperganso/python-manilaclient | manilaclient/v2/share_servers.py | Python | apache-2.0 | 3,246 | 0 | # Copyright 2014 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | ict 'backend_details' to separated strings
# as next:
# +---------------------+------------------------------------+
# | Property | Value |
# +------------- | --------+------------------------------------+
# | details:instance_id |35203a78-c733-4b1f-b82c-faded312e537|
# +---------------------+------------------------------------+
for k, v in six.iteritems(server._info["backend_details"]):
server._info["details:%s" % k] = v
return s... |
amd77/parker | inventario/models.py | Python | gpl-2.0 | 7,559 | 0.005558 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import models
from django.apps import apps
from empresa.models import Empresa
import json
import os
import tempfile
import datetime
import requests
class Parking(models.Model):
empresa = models.OneToOneField(Empresa)
... | r = requests.get(self.abre_url)
return r.status_code == 200
def abresiempre(self):
if self.abresiempre_post:
r = requests.post(self.abresiempre_url, data=json.loads(self.abresiempre_post))
else:
r = requests.get(self.abresiempre_url)
return r.status_code == 2... | elf.cierra_post))
else:
r = requests.get(self.cierra_url)
return r.status_code == 200
def __unicode__(self):
return "{} ({} de {})".format(self.slug, "entrada" if self.entrada else "salida", self.parking.nombre)
class Meta:
verbose_name = 'barrera'
verbose_n... |
astrand/pyobfuscate | test/testfiles/power.py | Python | gpl-2.0 | 40 | 0 |
import sys
x = 2
| y = | x**2
sys.exit(y)
|
warrenatmindset/DjangoFlowApp | questionnaires/migrations/0002_auto_20171113_0933.py | Python | mit | 440 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017 | -11-13 09:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('questionnaires', '0001_initial'),
]
operations = [
migrat | ions.RenameModel(
old_name='AttentionRelatedCognitiveErrors',
new_name='AttentionRelatedCognitiveError',
),
]
|
ricoen/drip_boot | drip_boot.py | Python | gpl-3.0 | 1,411 | 0.002126 | from sklearn import tree
import pyfirmata
import time
import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import acc... | s
moisture = array[:,:]
temp = [30, 30, 25, 25]
magic = tree.DecisionTreeClassifier()
magic = magic.fit(moisture, temp)
pin= 13
port = 'COM3'
board = pyfirmata.Arduino(port)
a = input('moisture? \n')
b = input('t | emp? \n')
data = int(a)
if b.lower() >= '30':
temp = 30
elif b.lower() <= '30':
temp = 25
else:
print('kondisi anomali, harap periksa alat')
c = magic.predict([[data, temp]])
if c == 30:
d = 'Siram'
board.digital[pin].write(1)
else:
d = 'Tidak perlu disiram'
board.digital[pin... |
ESS-LLP/frappe | frappe/data_migration/doctype/data_migration_connector/connectors/calendar_connector.py | Python | mit | 8,438 | 0.028206 | from __future__ import unicode_literals
import frappe
from frappe.data_migration.doctype.data_migration_connector.connectors.base import BaseConnection
import googleapiclient.discovery
import google.oauth2.credentials
from googleapiclient.errors import HttpError
import time
from datetime import datetime
from frappe.uti... | t_traceback(), "GCalendar Synchronization Error")
def get_events(self, remote_objectname, filters, page_length):
page_token = None
results = []
events = {"items": []}
while True:
try:
events = self.gcalendar.events().list(calendarId=self.account.gcalendar_id, maxResults=page_length,
singleEvents=F... | ue, syncToken=self.account.next_sync_token or None).execute()
except HttpError as err:
if err.resp.status in [410]:
events = self.gcalendar.events().list(calendarId=self.account.gcalendar_id, maxResults=page_length,
singleEvents=False, showDeleted=True, timeMin=add_years(None, -1).strftime('%Y-%m-%dT%... |
johnmgregoire/vanDover_CHESS | ui_highlowDialog.py | Python | bsd-3-clause | 2,451 | 0.00408 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\JohnnyG\Documents\XRDproject_Python_11June2010Release backup\highlowDialog.ui'
#
# Created: Mon Jun 14 16:20:37 2010
# by: PyQt4 UI code generator 4.5.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 impor... | .setObjectName("lowSpinBox")
self.highSpinBox = QtGui.QDoubleSpinBox(highlowDialog)
self.highSpinBox.setGeometry(QtCore.QRect(100, 40, 62, 20))
self.highSpinBox.setMinimum(-1000000.0)
self.highSpinBox.setMaximum(1000000.0)
self.highSpinBox.setObjectName("highSpinBox")
sel... | ry(QtCore.QRect(20, 20, 71, 16))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(highlowDialog)
self.label_2.setGeometry(QtCore.QRect(100, 20, 76, 16))
self.label_2.setObjectName("label_2")
self.retranslateUi(highlowDialog)
QtCore.QObject.connect(self.butto... |
ericholscher/django | django/utils/datetime_safe.py | Python | bsd-3-clause | 2,751 | 0.002908 | # Python's datetime strftime doesn't handle dates before 1900.
# These classes override date and datetime to support the formatting of a date
# through its full "proleptic Gregorian" date range.
#
# Based on code submitted to comp.lang.python by Andrew Dalke
#
# >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was... | )
year = year + off
# Move to around the year 2000
year = year + ((2000 - year) // 28) * 28
timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year))
s2 = time.strftime(fmt, (year+28,) + timetuple[1:])
sites2 = _findall(s2, str(year+28... | year + s[site+4:]
return s
|
petr-devaikin/commonview | web/env_settings.py | Python | gpl-2.0 | 395 | 0.022785 | from os import environ
def load_env(app):
if 'DATABASE_URI' in environ: app.config['DATABASE_URI'] = environ.get('DATABASE_URI')
if 'INSTA_ID' in environ: app.config['INSTA_ID'] = environ.get('INSTA_ID')
if 'INSTA_SECR | ET' in environ: app.config['INSTA_SECRET'] = environ.get('INSTA_SECRET')
if 'SECRET_KEY' in environ: app | .config['SECRET_KEY'] = environ.get('SECRET_KEY')
|
tseaver/google-cloud-python | spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client_config.py | Python | apache-2.0 | 2,633 | 0 | config = {
"interfaces": {
"google.spanner.admin.database.v1.DatabaseAdmin": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
... | "timeout_millis | ": 3600000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"GetDatabase": {
"timeout_millis": 30000,
"retry_codes_name": "idempotent",
"retry_params_name": "defau... |
rohitranjan1991/home-assistant | homeassistant/components/progettihwsw/switch.py | Python | mit | 2,686 | 0.000372 | """Control switches."""
from datetime import timedelta
import logging
from ProgettiHWSW.relay import Relay
import async_timeout
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_p... | itch
self._name = name
async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
await self._switch.control(True)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs | ):
"""Turn the switch off."""
await self._switch.control(False)
await self.coordinator.async_request_refresh()
async def async_toggle(self, **kwargs):
"""Toggle the state of switch."""
await self._switch.toggle()
await self.coordinator.async_request_refresh()
@p... |
helfertool/helfertool | src/badges/views/settings.py | Python | agpl-3.0 | 4,316 | 0.000463 | from django.conf import settings as django_settings
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.cache import never_cache
from helfertool.utils... | quest)
# check if badge system is active
if not event.badges:
return notactive(request)
# roles
roles = event.badge_settings.badgerole_set.all()
# designs
designs = event.badge_settings.badgedesign_set.all()
# forms for defaults
defaults_form = Ba | dgeDefaultsForm(request.POST or None,
instance=event.badge_settings.defaults,
settings=event.badge_settings,
prefix='event')
job_defaults_form = BadgeJobDefaultsForm(request.POST or None, event=event,
... |
turbokongen/home-assistant | tests/components/zha/conftest.py | Python | apache-2.0 | 6,990 | 0.001144 | """Test configuration for the ZHA component."""
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
import pytest
import zigpy
from zigpy.application import ControllerApplication
import zigpy.config
import zigpy.group
import zigpy.types
from homeassistant.components.zha import DOMAIN
import homeassist... | ice register."""
with patch.object( | hass.services, "async_register"), patch.object(
hass.services, "has_service", return_value=True
):
yield hass
|
charbeljc/maintainer-tools | oca/tools/check_contrib.py | Python | agpl-3.0 | 4,010 | 0.000249 | #!/usr/bin/python
from __future__ import division
import subprocess
import itertools
import operator
import argparse
import os.path as osp
import sys
from oca_ | projects import OCA_PROJECTS, url
def get_contributions(projects, since, merges):
cmd = ['git', 'log', '--pretty=format:%ai %ae']
if since is not None:
cmd += ['--since', since]
if merges:
cmd += ['--merges']
if isinstance(projects, (str, unicode)):
projects = [projects]
fo... | status = subprocess.call(['git', 'clone', '--quiet',
url(repo), repo])
if status != 0:
sys.stderr.write("%s not found on github\n" % repo)
continue
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=repo... |
mkacik/bcc | tools/btrfsslower.py | Python | apache-2.0 | 9,760 | 0.001025 | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# btrfsslower Trace slow btrfs operations.
# For Linux, uses BCC, eBPF.
#
# USAGE: btrfsslower [-h] [-j] [-p PID] [min_ms]
#
# This script traces common btrfs file operations: reads, writes, opens, and
# syncs. It measures the time spent in ... | urrent_pid_tgid();
u32 pid = id >> 32; // PID is higher part
| valp = entryinfo.lookup(&id);
if (valp == 0) {
// missed tracing issue or filtered
return 0;
}
// calculate delta
u64 ts = bpf_ktime_get_ns();
u64 delta_us = (ts - valp->ts) / 1000;
entryinfo.delete(&id);
if (FILTER_US)
return 0;
// populate output struct
u3... |
eustislab/horton | horton/io/test/test_molecule.py | Python | gpl-3.0 | 3,917 | 0.001532 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2015 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | IOData(coordinates=np.array([[1, 2], [2, 3]]))
with assert_raises(Type | Error):
IOData(numbers=np.array([[1, 2], [2, 3]]))
with assert_raises(TypeError):
IOData(numbers=np.array([2, 3]), pseudo_numbers=np.array([1]))
with assert_raises(TypeError):
IOData(numbers=np.array([2, 3]), coordinates=np.array([[1, 2, 3]]))
with assert_raises(TypeError):
I... |
youtube/cobalt | starboard/android/x86/cobalt/configuration.py | Python | bsd-3-clause | 2,386 | 0.002096 | # Copyright 2017-2021 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | filter.TestFilter(target, test) for test in tests)
return filters
# A map of failing or crashing tests per target
__FILTERED_TESTS = { # pylint: disable=invalid-name
| 'graphics_system_test': [
test_filter.FILTER_ALL
],
'layout_tests': [ # Old Android versions don't have matching fonts
'CSS3FontsLayoutTests/Layout.Test'
'/5_2_use_first_available_listed_font_family',
'CSS3FontsLayoutTests/Layout.Test'
'/5_2_use_specified_f... |
vikramvgarg/libmesh | doc/statistics/libmesh_citations.py | Python | lgpl-2.1 | 2,350 | 0.001702 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
# Number of "papers using libmesh" by year.
#
# Note 1: this does not count citations "only," the authors must have actually
# used libmesh in part of their work. Therefore, these counts do not include
# things like Wolfgang citing us in his pap... | ata[0::2]
# Extract the publication counts from the data array
n_papers = data[1::2]
# The number of data points
N = len(xlabels);
# Get a reference to the figure
fig = plt.figure()
# 111 is equivalent to Matlab's subplot(1,1,1) command
ax = fig.add_subplot(111)
# Create an x-axis for plotting
x = np.linspace(1, N... | = 0.8
# Make the bar chart. Plot years in blue, preprints and theses in green.
ax.bar(x[0:N-1], n_papers[0:N-1], width, color='b')
ax.bar(x[N-1:N], n_papers[N-1:N], width, color='g')
# Label the x-axis
plt.xlabel('T=PhD, MS, and BS Theses')
# Set up the xtick locations and labels. Note that you have to offset
# th... |
Dubrzr/dsfaker | dsfaker/generators/__init__.py | Python | mit | 220 | 0 | # -*- coding | : utf-8 -*-
from .base import *
from .utils import *
from .distributions import *
from .autoincrement import *
from .date import *
from .series import *
from .timeseries import *
from .trigonometric impo | rt *
|
Keisuke69/libcloud | libcloud/compute/types.py | Python | apache-2.0 | 3,992 | 0.002004 | # 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 use ... | ICHOSTS_UK1 = 19
ELASTICHOSTS_UK2 = 20
ELASTICHOSTS_US1 = 21
EC2_AP_SOUTHEAST = 22
RACKSPACE_UK = 23
BRIGHTBOX = 24
CLOUDSIGMA = 25
EC2_AP_NORTHEAST = 26
NIMBUS = 27
BLUEBOX = 28
GANDI = 29
OPSOURCE = 30
OPENSTACK = 31
SKALICLOUD = 32
SERVERLOVE = 33
NINEFO | LD = 34
TERREMARK = 35
EC2_US_WEST_OREGON = 36
CLOUDSTACK = 37
class NodeState(object):
"""
Standard states for a node
@cvar RUNNING: Node is running
@cvar REBOOTING: Node is rebooting
@cvar TERMINATED: Node is terminated
@cvar PENDING: Node is pending
@cvar UNKNOWN: Node state... |
plamut/ggrc-core | src/ggrc_risk_assessments/migrations/versions/20160804101106_4d4b04a5b9c6_fix_tracking_columns.py | Python | apache-2.0 | 771 | 0.005188 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Fix tracking columns (SLOW!)
Create Date: 2016-08-04 10:11:06.471654
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
from ggrc.migrati... | d4b04a5b9c6'
down_revision = '5b29b4becf8'
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
upgrade_tables("ggrc_risk_assessments")
def downgrade():
"""Downgrade database schema and/or data back to the previous revisi | on."""
downgrade_tables("ggrc_risk_assessments")
|
tobiasgehring/qudi | hardware/spectrometer/spectrometer_dummy.py | Python | gpl-3.0 | 3,308 | 0.002721 | # -*- coding: utf-8 -*-
"""
This module contains fake spectrometer.
Qudi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Qudi is distribute... | icon vacancy spectrum at liquid helium temperatures.
"""
_connectors = {'fitlogic': 'FitLogic'}
def on_activate(self):
""" Activate module.
"""
self._fitLogic = self.get_connector('fitlogic')
self.exposure = 0.1
def on_deactivate(self):
""" Deactivate module.
... | spectrum.
@return ndarray: 1024-value ndarray containing wavelength and intensity of simulated spectrum
"""
length = 1024
data = np.empty((2, length), dtype=np.double)
data[0] = np.arange(730, 750, 20/length)
data[1] = np.random.uniform(0, 2000, length)
lor... |
HenryHu/pybbs | Login.py | Python | bsd-2-clause | 4,609 | 0.004339 | from UtmpHead import UtmpHead
import Config
from Log import Log
class Login:
def __eq__(self, other):
if (other == None):
return (self._loginid == 0)
return (self._loginid == other._loginid)
def __ne__(self, other):
return not self.__eq__(other)
def __init__(self, logi... | ne):
userid = self.get_userid()
if (userid == None or userid == ''):
raise Exception("illegal call to list_add")
node = Login.list_head()
if (node == None):
# empty list -> single element
self.set_listprev(self)
self.set_listnext(self)... | erid().lower() >= userid.lower()):
# insert at head
self.set_listprev(node.list_prev())
self.set_listnext(node)
node.set_listprev(self)
self.list_prev().set_listnext(self)
UtmpHead.SetListHead(self._loginid)
return True
count =... |
metacloud/python-cinderclient | cinderclient/v2/contrib/list_extensions.py | Python | apache-2.0 | 1,439 | 0 | # Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except | in compliance with the | License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either expres... |
bweck/cssbot | cssbot/process.py | Python | mit | 4,907 | 0.034848 |
#
# Copyright (C) 2011 by Brian Weck
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
import pymongo, time
from . import log, config, reddit, queue
import utils
#
# match configured magic words by author or by mod
#
class Matcher:
matched_items = []
#
def __init__(se... | d"], thread["data"]["title | "].replace("\n", " "), thread["data"]["author"])
#
authorized_authors = self.authorized_authors( thread["data"]["author"] )
self.log.debug("authorized_authors = %s", authorized_authors)
# get the latest copy of the thread
resp = self.reddit.get_comments( thread["data"]["id"] )
if ... |
neuroidss/nupic.research | tests/regions/location_region_test.py | Python | agpl-3.0 | 11,848 | 0.005149 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ses in the rhombus encoded by a
bump.
:type inverseReadoutResolution: int
:type anchorInputSize: int
:param anchorInputSize:
The number of input bits in the anchor input.
.. note::
(*) This function will only add the 'sensor' and 'candidates' regions when
'anchorInputSize' is greater than zero... | ocation.path_integration_union_narrowing.createRatModuleFromReadoutResolution`
"""
net = Network()
# Create simple region to pass motor commands as displacement vectors (dx, dy)
net.addRegion("motor", "py.RawValues", json.dumps({
"outputWidth": 2
}))
if anchorInputSize > 0:
# Create simple region... |
valohai/valohai-cli | valohai_cli/utils/hashing.py | Python | mit | 377 | 0 | import hashlib
from typing import BinaryIO
def get_fp_sha256(fp: BinaryIO) -> str:
"""
Get the SHA-256 checksum of the data in the file `fp`.
:return: hex | string
"""
fp.seek(0)
hasher = hashlib.sha256()
| while True:
chunk = fp.read(524288)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
|
hareevs/pgbarman | tests/test_output.py | Python | gpl-3.0 | 36,915 | 0 | # Copyright (C) 2013-2016 2ndQuadrant Italia Srl
#
# This file is part of Barman.
#
# Barman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free | Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Barman 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 m... | gnu.org/licenses/>.
import mock
import pytest
from barman import output
from barman.infofile import BackupInfo
from barman.utils import pretty_size
from testing_helpers import build_test_backup_info, mock_backup_ext_info
def teardown_module(module):
"""
Set the output API to a functional state, after testin... |
mozillazg/django-simple-projects | projects/admin_readonly_model/admin_readonly_model/wsgi.py | Python | mit | 417 | 0.002398 | """
WSGI config for admin_readonly_model project.
It exposes the WSGI callable as a module-level variable named ``app | lication``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin_readonly_model.settings")
applic | ation = get_wsgi_application()
|
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.util/src/openmdao/util/typegroups.py | Python | mit | 558 | 0 | import array
import numbers
real_types = [numbers. | Real]
int_types = [numbers.Integral]
iterable_types = [set, list, tuple, array.array]
try:
import numpy
except ImportError:
pass
else:
real_types.extend([numpy.float32, numpy.float64])
int_types.extend([numpy.int32, numpy.int64])
iterable_types.append(numpy.ndarray)
# use these with isinstance to ... | tuple(iterable_types)
|
fsquillace/golpy | mvc.py | Python | gpl-2.0 | 431 | 0.00232 | """
MVC Design Pattern
@author: Filippo Squillace
@date: 03/12/2011
"""
class | Observer:
def update(*args, **kwargs):
raise NotImplementedError
class Observable:
def __init__(self):
self.observers = []
pass
def register(self, observer):
self.observers.append(observer)
def notify(self, *args, **kwargs):
fo | r obs in self.observers:
obs.update(args, kwargs)
|
OpenSystemsLab/rethinkengine | tests/test_fields.py | Python | bsd-2-clause | 5,550 | 0 | from rethinkengine.fields import *
import unittest2 as unittest
class PrimaryKeyFieldTestCase(unittest.TestCase):
def test_default(self):
f = ObjectIdField()
self.assertEqual(f._default, None)
with self.assertRaises(TypeError):
ObjectIdField(default='')
def test_required... | 492b-a1db-ad8a3b8abcefa'))
def test_wrong_chars(self):
f = ObjectIdField()
self.assertFalse(f.is_valid('zzzzzzzz-3327-492b-a1db-ad8a3b8abcef'))
def test_wro | ng_type(self):
f = ObjectIdField()
self.assertFalse(f.is_valid(123))
class StringFieldTestCase(unittest.TestCase):
def test_default(self):
f = StringField()
self.assertEqual(f._default, None)
f = StringField(default='foo')
self.assertEqual(f._default, 'foo')
d... |
datosgobar/pydatajson | tests/test_federation.py | Python | mit | 38,400 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import os
import re
import json
try:
from mock import patch, MagicMock, ANY
except ImportError:
from unittest.mock import patch, MagicMock, ANY
from .context import pydatajson
from pydatajson.federation import *
from pydatajson.... | qual(self.catalog_id + '_' + self.dataset_id, harvested_id)
def test_harvest_catalog_with_no_optional_parametres(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'package_update':
self.assertTrue(
data_dict['id'].startswith(
... | g_id + '_'))
self.assertTrue(
data_dict['name'].startswith(
self.catalog_id + '-'))
self.assertEqual(self.catalog_id, data_dict['owner_org'])
return data_dict
else:
return []
mock_portal.retur... |
csudmath/ma3ecg | source/conf.py | Python | gpl-2.0 | 7,658 | 0.004576 | # -*- coding: utf-8 -*-
#
# Développement d'une application web de création de quiz documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 29 18:28:40 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values... | ,
'author': "Cédric Donner",
'date': "Version 2016-2017",
'title': "Mathématiques 3ECG",
'release' : "",
'releasename' : "",
'fontpkg': '\\usepackage{times}',
'babel': '\\usepackage[francais]{babel}',
'figure_align': 'H',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source... | n class]).
latex_documents = [
('index', 'ma3ecg.tex', u'Mathématiques 3ECG',
u'Cédric Donner', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chap... |
hyperNURb/ggrc-core | src/ggrc_risk_assessments/migrations/versions/20150716192442_5b29b4becf8_add_slug_to_risk_assessment.py | Python | apache-2.0 | 1,107 | 0.007227 |
"""add slug to risk_assessment
Revision ID: 5b29b4becf8
Revises: cd51533c624
Create Date: 2015-07-16 19:24:42.473531
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5b29b4becf8'
down_revision = 'cd51533c624'
_table_name = "risk_assessments"
_column_name = ... | _table_name,
sa.Column(_column_name, sa.String(length=250), nullable=True)
)
op.execute("UPDATE {table_name} SET slug = CONCAT('{prefix}', id)".format(
table_name=_table_name,
prefix=_slug_prefix
))
op.alter_column(
_table_name,
_column_name,
existing_type=sa.String(l... | nstraint(_constraint_name, _table_name, [_column_name])
def downgrade():
""" Remove slug column from task group tasks """
op.drop_constraint(_constraint_name, _table_name, type_="unique")
op.drop_column(_table_name, _column_name)
|
morgenst/PyAnalysisTools | PyAnalysisTools/base/Modules.py | Python | mit | 2,275 | 0.00044 | from builtins import object
from PyAnalysisTools.base import _logger
from PyAnalysisTools.base.YAMLHandle import YAMLLoader
from PyAnalysisTools.AnalysisTools.FakeEstimator import MuonFakeEstimator # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder # noqa: F401
from PyAnalysisTools.Ana... | of calling object
:type callee: object
:return: list of initialised modules
:rtype: list
"""
modules = []
if not isinstance(config_files, list):
config_files = [config_files]
try:
for cfg_file in config_files:
if cfg_file is None:
continue
... | += build_module_instances(config, callee)
except TypeError:
_logger.warning("Config files not iterable")
return modules
def build_module_instances(config, callee):
"""
Construct a specific module instance from a config. If the callee is needed for the initialisation needs to be
passed and ... |
eProsima/Fast-DDS | test/performance/video/video_tests.py | Python | apache-2.0 | 5,555 | 0.00162 | # Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
#
# 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... | -r',
'--frame_rate',
help='Frame rate of the video [Hz]',
required=False,
default='30'
)
p | arser.add_argument(
'-t',
'--test_duration',
help='The duration of the test [s]',
required=False,
default=2
)
parser.add_argument(
'-s',
'--security',
action='store_true',
help='Enables security (Defaults: disable)',
required=False
... |
immenz/pyload | module/plugins/hooks/RestartSlow.py | Python | gpl-3.0 | 2,111 | 0.018001 | # -*- coding: utf-8 -*-
import pycurl
from module.plugins.Hook import Hook
class RestartSlow(Hook):
__name__ = "RestartSlow"
__type__ = "hook"
__version__ = "0.04"
__config__ = [("free_limit" , "int" , "Transfer speed threshold in kilobytes" , 100 ),
(... | eriodical(self):
if not self.pyfile.plugin.req.dl:
return
if self.getConfig("safe_mode") and not self.pyfile.plugin.resumeDownload:
time = 30
limit = 5
else:
type = "premium" if self.pyfile.plugin.premium else "free"
time = max(30, ... | for chunk in self.pyfile.plugin.req.dl.chunks \
if chunk.id not in self.info['chunk'] or self.info['chunk'][chunk.id] is not (time, limit)]
for chunk in chunks:
chunk.c.setopt(pycurl.LOW_SPEED_TIME , time)
chunk.c.setopt(pycurl.LOW_SPEED_LIMIT, limit)
sel... |
flowersteam/naminggamesal | naminggamesal/tools/efficient_minimal_ng.py | Python | agpl-3.0 | 4,257 | 0.03876 |
import numpy | as np
import random
import time
from collections import defaultdict
from memory_profiler import memory_usage
def stop_condition(T,pop,Tmax,monitor_T):
if T == monitor_T:
print(memory_usage())
return (T >= Tmax) or (T>0 and len(pop) == 1)
def new_stop_condition(T,pop,Tmax,monitor_T):
if T == monitor_T:
#print(... | d1']) == 1)
def pop_add(ag,pop):
s = pop['d1'][ag]+1
pop['d1'][ag] = s
if s > 1:
pop['d2'][s-1].remove(ag)
pop['d2bis'][s-1]-=1
if pop['d2bis'][s-1] == 0:
del pop['d2bis'][s-1]
del pop['d2'][s-1]
pop['d2bis'][s]+=1
pop['d2'][s].add(ag)
pop['N'] += 1
def pop_rm(ag,pop):
s = pop['d1'][ag]-1
if s > 0... |
niekas/Hack4LT | src/hack4lt/templatetags/utils.py | Python | bsd-3-clause | 123 | 0 | from django import template
register = template.Library()
@register.filter
def value(value, key):
return value | [key]
| |
maxdl/Vesicle.py | vesicle/version.py | Python | mit | 444 | 0 | import os.path
import sys
version = "1.1.3"
date = ("June", "11", "2018")
title = "Vesicle"
author = "Max Larsson"
email = "[email protected]"
homepage = "www.liu.se/medfak/forskning/larsson-max/software"
if hasattr(sys, 'frozen'):
if '_MEIP | ASS2' in os.environ:
path = os.envi | ron['_MEIPASS2']
else:
path = sys.argv[0]
else:
path = __file__
app_path = os.path.dirname(path)
icon = os.path.join(app_path, "ves.ico")
|
lhilt/scipy | scipy/stats/tests/test_morestats.py | Python | bsd-3-clause | 70,469 | 0.000298 | # Author: Travis Oliphant, 2002
#
# Further enhancements and tests added by numerous SciPy developers.
#
from __future__ import division, print_function | , absolute_import
import warnings
import numpy as np
from numpy.random import RandomState
from numpy.testing import (assert_array | _equal,
assert_almost_equal, assert_array_less, assert_array_almost_equal,
assert_, assert_allclose, assert_equal, assert_warns)
import pytest
from pytest import raises as assert_raises
from scipy._lib._numpy_compat import suppress_warnings
from scipy import stats
from .common_tests import check_named_results
... |
sayoun/workalendar | workalendar/tests/test_asia.py | Python | mit | 17,173 | 0 | from datetime import date
from workalendar.tests import GenericCalendarTest
from workalendar.asia import HongKong, Japan, Qatar, Singapore
from workalendar.asia import SouthKorea, Taiwan, Malaysia
class HongKongTest(GenericCalendarTest):
cal_class = HongKong
def test_year_2010(self):
""" Interestin... | Boxing Day
def test_chingming_festival(self):
# This is the same as the Taiwan test, just different spelling
# Could move this into a Core test
self.assertI | n(date(2005, 4, 5), self.cal.holidays_set(2005))
self.assertIn(date(2006, 4, 5), self.cal.holidays_set(2006))
self.assertIn(date(2007, 4, 5), self.cal.holidays_set(2007))
self.assertIn(date(2008, 4, 4), self.cal.holidays_set(2008))
self.assertIn(date(2010, 4, 5), self.cal.holidays_set(20... |
brunobord/critica | apps/admin/sites.py | Python | gpl-3.0 | 2,410 | 0.007469 | # -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.admin.sites import AdminSite
from django import http, template
from django.shortcuts import render_to_response
from django.template import RequestContex | t
from django.utils.translation import ugettext_lazy, ugettext as _
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import login_required
# Basic admin
# ------------------------------------------------------------------------------
class BasicAdminSite(AdminSite):
"""
... | te using the
register() method, and the root() method can then be used as a Django view function
that presents a full admin interface for the collection of registered models.
BasicAdminSite is a basic Django admin with lightweight customizations.
"""
index_template = 'basic_admin/index.htm... |
DuVale/snapboard | setup.py | Python | bsd-3-clause | 2,058 | 0.00243 | #!/usr/bin/python
from distutils.core import setup
setup(
name='snapboard',
version='0.2.1',
author='Bo Shi',
maintainer='SNAPboard developers',
maintainer_email='[email protected]',
url='http://code.google.com/p/snapboard/',
description='Bulletin board application for Djang... | ssigned to custom groups of users
* Group administration can be delegated to end users on a per-group basis
* Moderators for each forum
* User preferences
* Watched topics
* Abuse reports
* User and IP address bans that don't automatically spread to other Django
applications within the pro... | SNAPboard requires Django 1.0.''',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: New BSD License',
'Operating System :: OS Independent',
'... |
dmlc/tvm | python/tvm/contrib/tedd.py | Python | apache-2.0 | 27,567 | 0.001306 | # 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... | src = Source(dot_string)
display(SVG(src.pipe(format="svg")))
if output_dot_string:
return dot_string
return None
def dump_json(sch, need_range):
"""Serialize data for visualization from a schedule in JSON format.
Parameters
----------
sch : schedule
| The schedule object to serialize
Returns
-------
json : string
Serialized JSON string
"""
def encode_itervar(itervar, stage, index, range_map):
"""Extract and encode IterVar visualization data to a dictionary"""
ivrange = range_map[itervar] if range_map is not None and ite... |
kaynfiretvguru/Eldritch | plugin.program.echowizard/resources/lib/modules/extract.py | Python | gpl-2.0 | 2,897 | 0.022092 | """
Copyright (C) 2016 ECHO Wizard
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 3 of the License, or
(at your option) any later version.
This program is dis... | tem in zin.infolist():
count += 1
update = count / nFiles * 100
dp.update(int(update),'','','[COLOR dodgerblue][B]' + str(item.filename) + '[/B][/COLOR]')
try:
zin.extract(item, _out)
except Exception, e:
print str(e)
... | _in, _out, dp):
zin = zipfile.ZipFile(_in, 'r')
nFiles = float(len(zin.infolist()))
count = 0
skin_selected = 0
#try:
for item in zin.infolist():
count += 1
update = count / nFiles * 100
dp.update(int(update),'','','[COLOR dodgerblue][B]' + str(item.filename) + '[/B][/COLOR]')
if "userdata/skin" in ... |
Dawny33/Code | Code_Forces/Contest 277/A.py | Python | gpl-3.0 | 66 | 0.045455 | T = input()
if T%2==0:
print T | /2
else:
print ((T-1)/2)-T | |
daikeren/opbeat_python | tests/instrumentation/python_memcached_tests.py | Python | bsd-3-clause | 2,007 | 0 | from functools import partial
from django.test import TestCase
import mock
import memcache
import opbeat
from tests.contrib.django.django_tests import get_client
class InstrumentMemcachedTest(TestCase):
def setUp(self):
self.client = get_client()
opbeat.instrumentation.control.instrument(self.cli... | nd_transaction(None, "test")
transactions, traces = self.client.instrumentation_store.get_all()
expected_signatures = ['transaction', 'test_memcached',
'Client.set', 'Client.get',
'Client.get_multi']
self.assertEqual(set([t['signat... | so we can just test them
sig_dict = dict([(t['signature'], t) for t in traces])
traces = [sig_dict[k] for k in expected_signatures]
self.assertEqual(traces[0]['signature'], 'transaction')
self.assertEqual(traces[0]['kind'], 'transaction')
self.assertEqual(traces[0]['transaction... |
zooniverse/aggregation | experimental/algorithms/test.py | Python | apache-2.0 | 475 | 0.027368 | import cv2
import numpy as np
fi | lename = '/home/greg/Databases/images/0c9a02a8-2b7d-484e-ba18-e35d33800774.jpeg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
# Threshold for an... | 2.imwrite('/home/greg/1.jpg',img) |
cxxgtxy/tensorflow | tensorflow/python/keras/saving/saved_model/json_utils_test.py | Python | apache-2.0 | 2,675 | 0.002243 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | elf.assertAllEqual(loaded['key1'].rank, None)
self.assertAllEqual(loaded['key2'][0].as_list(), [None])
self.assertAllEqual(loaded['key2'][1].as_list(), [3, None, 5])
def test_encode_decode_tuple(self):
metadata = {
'key1': (3, 5),
'key2': [(1, (3, 4)), (1,)]}
string = json_utils.Encod... | ed.keys()), {'key1', 'key2'})
self.assertAllEqual(loaded['key1'], (3, 5))
self.assertAllEqual(loaded['key2'], [(1, (3, 4)), (1,)])
def test_encode_decode_type_spec(self):
spec = tensor_spec.TensorSpec((1, 5), dtypes.float32)
string = json_utils.Encoder().encode(spec)
loaded = json_utils.decode(st... |
timmahrt/ProMo | examples/pitch_morph_to_pitch_contour.py | Python | mit | 2,635 | 0 | '''
Created on Jun 29, 2016
This file shows an example of morphing to a pitch tier.
In f0_morph.py, the target pitch contour is extracted in the
script from another file. In this example, the pitch tier
could come from any source (hand sculpted or generated).
WARNING: If you attempt to morph to a pitch track that ha... | ch_and_intensity
from praatio import dataio
from promo impor | t f0_morph
from promo.morph_utils import utils
from promo.morph_utils import interpolation
# Define the arguments for the code
root = os.path.abspath(join('.', 'files'))
praatEXE = r"C:\Praat.exe" # Windows paths
praatEXE = "/Applications/Praat.app/Contents/MacOS/Praat" # Mac paths
minPitch = 50
maxPitch = 350
st... |
arunkgupta/gramps | gramps/gui/widgets/validatedcomboentry.py | Python | gpl-2.0 | 8,370 | 0.007168 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008 Zsolt Foldvari
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) ... | as_frame_changed(self):
has_frame = self.get_property('has-frame')
| self._entry.set_has_frame(has_frame)
def _is_in_model(self, data):
"""Check if given data is in the model or not.
@param data: data value to check
@type data: depends on the actual data type of the object
@returns: position of 'data' in the model
@re... |
mythmon/kitsune | kitsune/customercare/tests/test_badges.py | Python | bsd-3-clause | 1,176 | 0 | from datetime import date
from kitsune.customercare.badges import AOA_BADGE
from kitsune.customercare.tests import ReplyFactory
from kitsune.kbadge.tests import BadgeFactory
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFac | tory
from kitsune.customercare.badges import register_signals
class TestAOABadges(TestCase):
def setUp | (self):
# Make sure the badges hear this.
register_signals()
def test_aoa_badge(self):
"""Verify the KB Badge is awarded properly."""
# Create the user and badge.
year = date.today().year
u = UserFactory()
b = BadgeFactory(
slug=AOA_BADGE['slug'].... |
patricmutwiri/pombola | pombola/projects/views.py | Python | agpl-3.0 | 504 | 0.007937 | import models
import pombola.core.models
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, redirect
def in_place(requ | est, slug):
place = get_object_or_404( pombola.core.models.Place, slug=slug)
projects = place.project_set
return render_to_response(
'projects/in_place.html',
{
'place': place,
'projects': projects,
| },
context_instance=RequestContext(request)
)
|
textbook/flash_services | tests/test_auth.py | Python | isc | 391 | 0 | from flash_services.auth import BasicAu | thHeaderMixin
from flash_services.core import Service
class BasicAuthParent(BasicAuth | HeaderMixin, Service):
def update(self): pass
def format_data(self, data): pass
def test_basic_auth():
service = BasicAuthParent(username='username', password='password')
assert service.headers['Authorization'] == 'Basic dXNlcm5hbWU6cGFzc3dvcmQ='
|
daGrevis/daGrevis.lv | dagrevis_lv/legacy/routers.py | Python | mit | 438 | 0 | class LegacyRouter(object):
def db_for_read(self, model, **hints):
| if model._meta.app_label == "legacy":
return "legacy"
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == "legacy":
return "legacy"
return None
def allow_relation(self, obj1, obj2, **hints):
return False
d | ef allow_syncdb(self, db, model):
return False
|
davy39/eric | Plugins/CheckerPlugins/CodeStyleChecker/Ui_CodeStyleCheckerDialog.py | Python | gpl-3.0 | 18,215 | 0.005215 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCheckerDialog.ui'
#
# Created: Tue Nov 18 17:53:57 2014
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, Qt... | )
self.verticalLayout.addWidget(self.storeDefaultButton)
self.resetDefaultButton = QtWidgets.QPushButton(self.filterFrame)
self.resetDefaultButton.setObjectName("resetDefaultButton")
self.verticalLayout.addWidget(self.resetDefaultButton)
self.gridLayout.addLayout(self.verticalLay... | t.addWidget(self.label, 1, 0, 1, 1)
self.excludeMessagesEdit = E5ClearableLineEdit(self.filterFrame)
self.excludeMessagesEdit.setObjectName("excludeMessagesEdit")
self.gridLayout.addWidget(self.excludeMessagesEdit, 1, 1, 1, 1)
self.excludeMessagesSelectButton = QtWidgets.QToolButton(self... |
5agado/intro-ai | src/test/housePricing.py | Python | apache-2.0 | 2,178 | 0.015611 | from util import utils
import os
import numpy as np
from mpl_toolkits.mplot3d import *
from sklearn import linear_model
F = None #num of features
N = None #num of training samples
T = None #num of test samples
def readData(filename):
filePath = os.path.join(utils.getResourcesPath(), filename)
... | test.append(line)
return data, test
def gradientDescent(features, values, nIter = 500, lRate = 0.001):
X = np.append(features, np.ones((len(features),1)), axis=1) #dummy column for intercept weight
weights = np.random.random(X.shape[1]) #consider intercept weight
history = []
for _ in range(... | #errors2 = [(values[i]-np.dot(weights,X[i]))*X[i] for i in range(N)]
errors = (values - pred)* X[:, i]
weights[i] += lRate * errors.sum()
#necessary 1/n factor??
e = sum([(values[i]-np.dot(weights,X[i]))**2 for i in range(N)])
history.append... |
BTA-BATA/electrum-bta-master | lib/wallet.py | Python | gpl-3.0 | 72,921 | 0.00314 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 3 of the License, or
# (at... | self.data[key] = copy.deepcopy(value)
elif key in self.data:
self.data.pop(key)
if save:
self.write()
def write(self):
assert not threading.currentThread() | .isDaemon()
temp_path = "%s.tmp.%s" % (self.path, os.getpid())
s = json.dumps(self.data, indent=4, sort_keys=True)
with open(temp_path, "w") as f:
f.write(s)
f.flush()
os.fsync(f.fileno())
# perform atomic write on POSIX systems
try:
... |
deapplegate/wtgpipeline | OLDadam_THESIS_CRN_performance_metrics.py | Python | mit | 7,803 | 0.045752 | #! /usr/bin/env python
#adam-predecessor# this derives from adam_THESIS_CRN_number_of_masks.py
from matplotlib.pylab import *
import astropy
from glob import glob
import scipy.ndimage
import os
import pymorph
import skimage
from skimage import measure
from skimage import morphology
import mahotas
import sys ; sys.path.... | Nrate)
|
seeings=['seeing<=0.6','0.6<seeing<0.7','seeing>=0.7']
import astropy.table as tbl
Seeings=['Seeing$\leq 0\\arcsecf6$','$0\\arcsecf6<$Seeing$<0\\arcsecf7$','Seeing$\geq0\\arcsecf7$']
tab=tbl.Table(data=[Seeings , pure, compp , compm ],names=['Seeing Range','Purity per mask','Completeness per pixel','Completeness per ... |
LarsDu/DeepNucDecomp | scripts/ExtractGff3.py | Python | gpl-3.0 | 962 | 0.017672 | import gflags
import sys
import os
#Go one directory up and append to path to access the deepdna packa | ge
#The following statement is equiv to sys.path.append("../")
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__),os.path.pardir)))
FLAGS = gflags.FLAGS
gflags.DEFINE_string('genome_file','',"""A genome reference file in fasta format""")
gflags.DEFINE_string('gff3_file','',"""GFF3 annotation f... | e""")
def main(argv):
#Parse gflags
try:
py_file = FLAGS(argv) # parse flags
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
test_parser = Gff3Parser(FLAGS.gff3_file,FLAGS.feature)
for _ in range(20):
print t... |
FedoraScientific/salome-paravis | test/VisuPrs/Vectors/A0.py | Python | lgpl-2.1 | 1,491 | 0.002683 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at yo | ur option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of ... | # See http://www.salome-platform.org/ or email : [email protected]
#
# This case corresponds to: /visu/Vectors/A0 case
# Create Vectors for all data of the given MED file
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.