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 |
|---|---|---|---|---|---|---|---|---|
beiko-lab/timeclust | ananke/_cluster.py | Python | gpl-3.0 | 14,320 | 0.004921 | import sys
import argparse
import multiprocessing
from functools import partial
from math import sqrt
import h5py as h5
import numpy as np
from scipy.sparse import vstack, coo_matrix
from scipy.stats.mstats import gmean
from sklearn.cluster import DBSCAN
from ._database import TimeSeriesData
# Calculate the slopes,... | alized time-series
"""
mean = np.mean(x)
sd = np.std(x)
if sd == 0:
z = np.zeros_like(x)
else:
z = (x - mean)/sd
return z
def normalize_simple(matrix, mask):
"""Normalizes a matrix by columns, and then by rows. With multiple
time-series, the data are normalized to the wi... | me-series matrix of abundance counts. Rows are sequences, columns
are samples/time-points.
mask: list or np.array
List of objects with length matching the number of timepoints, where
unique values delineate multiple time-series. If there is only one
time-series in the data set, it's ... |
jmborr/confinedBSA | simulation/silica/amorphous_from_md/confineBSA/poretop/carve_silica.py | Python | mit | 11,095 | 0.003155 | #!/usr/bin/env/python
from __future__ import print_function
import MDAnalysis as mda
from MDAnalysis.analysis.distances import contact_matrix
import numbers
import operator
def contact_sample(siatom, sample, vdw_radii, overlap=1.0):
"""
Checks if atom of silica is in contact with the protein+water system
... | node_a = self.nodes[i]
for j in indices:
if i == j:
continue
node_b = self.nodes[j]
node_a.in | sert_neighbor(node_b)
def get_state_i(self, state_attribute, invert=False, atype=None):
"""
:param state_attribute: attribute of node ('overlaps', or 'removed')
:param invert: consider the negative of the value of the state_attribute
:param atype: atom type, all types if None
... |
tensorflow/agents | tf_agents/environments/suite_mujoco_test.py | Python | apache-2.0 | 2,182 | 0.003666 | # coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | tEqual((6,), env.action_spec().shape)
def testGinConfig(self):
gin.parse_config_file(
test_utils.test_src_dir_path('environments/configs/suite_mujoco.gin')
)
env = suite_mujoco.load()
self.assertIsInstance(env, py_environment.PyEnvironment)
se | lf.assertIsInstance(env, wrappers.TimeLimit)
if __name__ == '__main__':
test_utils.main()
|
zuBux/homepage | app/views.py | Python | gpl-2.0 | 2,716 | 0.011046 | from flask import Flask, render_template, request, session, flash, redirect, url_for
from datetime import datetime
from models import Post, Category
from forms import PostForm, LoginForm
from app import app, db
import hashlib
@app.route('/')
def index():
return render_template('index.html', nodict={})
@app.route(... | , 'POST'])
def login():
form = LoginForm()
error = None
if request.method == 'POST':
hash_pass = hashlib.sha256(request.form['password']).hexdigest()
print "got it"
| if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif hash_pass != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('blog'))
return render_templa... |
InterestingLab/elasticmanager | indices/urls.py | Python | mit | 77 | 0 | # from | django.conf.urls import url
# from . import views
url | patterns = [
]
|
asttra/pysces | setup.py | Python | bsd-3-clause | 9,707 | 0.023797 | #!/usr/bin/env python
"""
PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net)
Copyright (C) 2004-2015 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved,
Brett G. Olivier (bgoli@users.sourceforge.net)
Triple-J Group for Molecular Cell Physiology
Stellenbosch University, South Af... | con61subd.f'),os.path.join(extpath,'dpcon61.f'),os.path.join(extpath,'dpcon61w.f')])
mymodules.append(pitcon)
#mydata_files.append((os.path.join('pysces','pitcon'), [os.path.join(local_path, 'pysces', 'pitcon','readme.txt'), os.path.join(local_path, 'pysces', 'pitcon','readme.txt')]))
else:
print '\nSkippin... | os.path.exists(os.path.join(local_path, 'pysces', 'nleq2','nleq2.f')) and nleq2_byteorder_override:
## print 'INFO: using user supplied nleq2.f'
## else:
## if os.sys.byteorder == 'little':
## shutil.copyfile(os.path.join(extpath,'nleq2_little.f'), os.path.join(extpath,'nleq2.f'))
... |
heraldmatias/dew | django-sunat/src/upc/sunat/admin.py | Python | gpl-2.0 | 532 | 0.011278 | __author__ = 'herald olivares'
# -*- coding: utf-8 -*-
fro | m django.contrib import admin
from upc.sunat.models import Person, Concept, Debt
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'ruc', 'phone', 'type')
class ConceptAdmin(adm | in.ModelAdmin):
pass
class DebtAdmin(admin.ModelAdmin):
list_display = ('concept', 'person', 'period', 'tax_code', 'resolution_number', 'amount')
admin.site.register(Person, PersonAdmin)
admin.site.register(Concept, ConceptAdmin)
admin.site.register(Debt, DebtAdmin)
|
petezybrick/iote2e | iote2e-pyclient/src/iote2epyclient/ws/loginvo.py | Python | apache-2.0 | 1,031 | 0.00485 | # Copyright 2016, 2017 Peter Zybrick and others.
#
# 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 ag... | e is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations u | nder the License.
"""
LoginVo
:author: Pete Zybrick
:contact: pzybrick@gmail.com
:version: 1.0.0
"""
class LoginVo(object):
'''
Login Value Object
'''
def __init__(self, loginName, passwordEncrypted, sourceName, optionalFilterSensorName=None ):
self.loginName = loginName
self.passwo... |
aldryn/aldryn-redirects | aldryn_redirects/__init__.py | Python | bsd-3-clause | 109 | 0 | # -*- cod | ing: | utf-8 -*-
__version__ = '1.3.7'
default_app_config = 'aldryn_redirects.apps.AldrynRedirects'
|
vgamula/sp | server/accounts/tests/test_views.py | Python | mit | 912 | 0 | from server.tests import BaseAsyncTestCase, unittest_run_loop
class AccountViewsTestCase(BaseAsyncTestCase):
@unittest_run_loop |
async def test_simple_test_view(self):
resp = await self.client.get('/test')
assert resp.status == 200
assert await resp.text() == 'Test response'
@unittest_run_loop
async def test_simple_test_view_1(self):
resp = await self.client.get('/test')
assert resp.status ==... | elf.client.get('/test')
assert resp.status == 200
assert await resp.text() == 'Test response'
@unittest_run_loop
async def test_simple_test_view_3(self):
resp = await self.client.get('/test')
assert resp.status == 200
assert await resp.text() == 'Test response'
|
bat-serjo/vivisect | vtrace/tests/test_expressions.py | Python | apache-2.0 | 851 | 0 | import vtrace.tests as vt_tests
breakpoints = {
'windows': 'ntdll.NtTerminateProcess',
'linux': 'libc.exit',
'freebsd': 'libc.exit',
}
class VtraceExpressionTest(vt_tests.VtraceProcessTest):
def test_vtrace_sym(self):
plat = self.trace.getMeta('Platform')
symname = breakpoints.get(pla... | lf.trace.parseExpression(libname)
addEntry = self.trace.parseExpression(libname + " | + 5")
# grab a symbol in the library and compare offsets against that?
self.assertTrue(entry + 5 == addEntry)
|
QuLogic/meson | mesonbuild/coredata.py | Python | apache-2.0 | 52,406 | 0.003301 | # Copyright 2012-2021 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agree... | 019', 'xcode']
default_yielding = False
# Can't bind this near the class method it seems, sadly.
_T = T.TypeVar('_T')
class MesonVersionMismatchException(MesonException):
'''Build directory generated with Meson version is incompatible with current version'''
def __init__(self, old_version: str, current_vers... | er().__init__('Build directory has been generated with Meson version {}, '
'which is incompatible with the current version {}.'
.format(old_version, current_version))
self.old_version = old_version
self.current_version = current_version
class UserOptio... |
jeremyletang/slut | slut.py | Python | unlicense | 9,623 | 0.006651 | #!/usr/bin/python
import requests
import argparse
import subprocess
import time
import json
import signal
import sys
import os
AdminToken=''
BackupFolderPath='./backup'
CookieFilePath='cookies.txt'
SavedFilesDB='.slut-bak.json'
TeamInfoDb='.team-bak.json'
LsDb='.ls-bak.json'
UserDb='.user-bak.json'
TeamName=''
shoul... | :
lst.append(f)
return lst
def get_all_files_list(pages_count, should_update):
# if data already exist
if not should_update:
if os.path.exists(ls_db_path()):
with open(ls_db_path(), 'rb') a | s f:
j = json.loads(f.read())
return j
# else retrieve data
print 'retrieving list of all available files ({} pages)'.format(pages_count)
files = []
for p in range(1, pages_count+1):
if should_exit:
return []
files = files + get_files_for_page... |
littleweaver/django-argus | argus/migrations/0006_auto_20140310_1718.py | Python | bsd-3-clause | 1,256 | 0.000796 | # encoding: utf8
from django.db import models, migrations
def copy_manualness(apps, schema_editor):
Transaction = apps.get_model("argus", "Transaction")
fractions = Transaction.objects.filter(split='manual',
share__fraction_is_manual=True)
fractions.update(split=... | model_name='sha | re',
name='fraction_is_manual',
),
]
|
darkman66/langcodes | test_multithread.py | Python | mit | 758 | 0.011873 | # -*- coding: utf-8; -*-
"""
This file implements | testing ing langcodes module for multithreaded env
Problem is still there if you try to acccess that module from m | ultiple places at once
"""
import threading
from twisted.internet import reactor
from langcodes.tag_parser import parse_tag
from langcodes import standardize_tag
def parseMe(i, tag):
print i, parse_tag(tag)
def stopMe():
reactor.stop()
def startProcessing():
for i, tag in enumerate(('en_US', 'en', 'en_... |
eyaler/tensorpack | examples/Saliency/CAM-resnet.py | Python | apache-2.0 | 5,641 | 0.001595 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: CAM-resnet.py
import cv2
import sys
import argparse
import numpy as np
import os
import multiprocessing
import tensorflow as tf
from tensorpack import *
from tensorpack.dataflow import dataset
from tensorpack.tfutils import optimizer, gradproc
from tensorpack.tfu... | , trainable=False)
opt = tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True)
gradprocs = [gradproc.ScaleGradient(
[('co | nv0.*', 0.1), ('group[0-2].*', 0.1)])]
return optimizer.apply_grad_processors(opt, gradprocs)
def get_data(train_or_test):
# completely copied from imagenet-resnet.py example
isTrain = train_or_test == 'train'
datadir = args.data
ds = dataset.ILSVRC12(datadir, train_or_test, shuffle=isTrain)
... |
jasonleaster/Machine_Learning | SVM/svm.py | Python | gpl-2.0 | 9,610 | 0.004162 | """
Programmer : EOF |
E-mail : jasonleaster@163.com
File : svm.py
Date : 2015.12.13
You know ... It's hard time but it's not too bad to say give up.
"""
import numpy
class SVM:
def __init__(self, Mat, Tag, C = 2, MAXITER = 200):
self._Mat = numpy.array(Mat)
self._Tag = numpy.array(Tag).flatt... | .SampleDem = self._Mat.shape[0]
self.SampleNum = self._Mat.shape[1]
# Castiagte factor
self.C = C
# Each sample point have a lagrange factor
self.alpha = numpy.array([0.0 for i in range(self.SampleNum)])
# The expected weight vector which we want the ma... |
ecohealthalliance/EpiTator | epitator/structured_data_annotator.py | Python | apache-2.0 | 5,239 | 0.002481 | #!/usr/bin/env python
from __future__ import absolute_import
from .annotator import Annotator, AnnoTier, AnnoSpan
import re
import pyparsing as pypar
def word_token_regex(disallowed_delimiter):
return pypar.Regex(r"[^\s\n" + re.escape(disallowed_delimiter) + r"]+")
pypar.ParserElement.setDefaultWhitespaceChars(... | ess() +
row * (2, None)).setResultsName("delimiter:" + separator)
key_value_list_parser.parseWithTabs()
class StructuredDataAnnotator(Annotator):
"""
Annotates tables and key value lists embedded in documents.
"""
def annotate(self, doc):
doc_text_len = len(doc.text)
def crea... | _doc(start, end, label=None, metadata=None):
return AnnoSpan(
start,
min(doc_text_len, end),
doc,
label=label,
metadata=metadata).trimmed()
spans = []
value_spans = []
for token, start, end in table_pars... |
kiddinn/plaso | tests/containers/windows_events.py | Python | apache-2.0 | 1,527 | 0.004584 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Windows event data attribute containers."""
import unittest
import uuid
from plaso.containers import windows_events
from tests import test_lib as shared_test_lib
class WindowsDistributedLinkTrackingEventDataTest(shared_test_lib.BaseTestCase):
"""Tes... | dress',
'origin', 'parser', 'uuid']
attribute_names = sorted(attribute_container.GetAttributeNames())
self.assertEqual(attribute_names, expected_attribute_names)
class WindowsVolumeEventDataTest(shared_test_lib.BaseTestCase):
"""Tests for the Windows volume event data attribute container."""
de... | teNames function."""
attribute_container = windows_events.WindowsVolumeEventData()
expected_attribute_names = [
'_event_data_stream_row_identifier', 'data_type', 'device_path',
'origin', 'parser', 'serial_number']
attribute_names = sorted(attribute_container.GetAttributeNames())
self.... |
ifearcompilererrors/fle_redesign | fle_redesign/apps/radpress/tests/__init__.py | Python | mit | 324 | 0 | from dja | ngo.conf import settings
from radpress.tests.base import BaseTest, RestructuredtextTest
from radpress.tests.md import MarkdownTest
if 'django.contrib.admin' in settings.INSTALLED_APPS:
from radpress.tests.admin import AdminTest
else:
print("`django.contrib.admin` is not installed, passed admin tests...")
| |
EDRN/labcas-backend | common/src/main/python/gov/nasa/jpl/edrn/labcas/client/examples/upload_hanash.py | Python | apache-2.0 | 1,674 | 0.015532 | # Example Python script to upload Hanash data
from gov.nasa.jpl.edrn.labcas.labcas_client import LabcasClient
if __name__ == '__main__':
# datasetId must match the directory name where the data is staged on the server: $LABCAS_STAGING/$datasetId
datasetId = 'FHCRCHanashAnnexinLamr'
labcasClient =... | 'ProtocolName':'Validation of Protein Markers for Lung Cancer Using CARET Sera and Proteomics Techniques',
'LeadPI':'Samir Hanash',
'DataCustodian':'Ji Qiu',
'DataCustodianEmail':'djiqiu@fhcrc.org',
'CollaborativeGroup':'Lung and Upper Aerodigestive',
... | ung',
'SiteName':'Fred Hutchinson Cancer Research Center (Biomarker Developmental Laboratories)',
'SiteShortName':'FHCRC',
'QAState':'Accepted',
'PubMedId':'http://www.ncbi.nlm.nih.gov/pubmed/18794547',
'DateDatasetFrozen':'2007/05/29'... |
gibil5/openhealth | models/order/__init__.py | Python | agpl-3.0 | 535 | 0.005607 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
#from . import report_order_line
#from . import | order_report_nex # Estado de Cuenta - Used by Patient - Moved
from . import report_sale_product
from . import order_admin
from . import ticket
from . import order
from . import order_business
from . import order_controller
from . import order_extra
from . import order_line
from . import order_line_pl
from ... | losing
from . import card
|
fpeder/pyXKin | xkin/calib_params.py | Python | bsd-2-clause | 1,484 | 0.003369 | #!/usr/bin/env python
# -*-: coding: utf-8 -*-
import numpy as np
depth_cal = np.array([5.9421434211923247e+02,
5.9104053696870778e+02,
3.3930780975300314e+02,
2.4273913761751615e+02,
-2.6386489753128833e-01,
... | -1.9922302173693159e-03,
1.4371995932897616e-03,
9.1192465078713847e-01])
T = np.array([1.9985242312092553e-02,
-7.4423738761617583e-04,
-1.0916736334336222e-02])
R = np.array([[9.9984628826577793e-01,
1.2635359098409581e-0... | 79535e-02],
[1.7470421412464927e-02,
1.2275341476520762e-02,
9.9977202419716948e-01]])
calib = {'depth':depth_cal, 'rgb':rgb_cal, 'T':T, 'R':R}
import pickle
pickle.dump(calib, open('calib.pck', 'wb'))
|
h2oai/h2o-3 | h2o-py/tests/testdir_apis/Data_Manipulation/pyunit_h2oH2OFrame_levels.py | Python | apache-2.0 | 683 | 0.01757 | from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.utils.typechecks import assert_is_type
from random import randrange
import numpy as np
def | h2o_H2OFrame_levels():
"""
Python API test: h2o.frame.H2OFrame.levels()
"""
python_lists = np.random.randint(-2,2, (10000,2))
h2oframe = h2o.H2OFrame(python_obj=python_lists, column_types=['enum', 'enum'])
clist = h2oframe.levels()
assert_is_type(clist, list) # check return type
as... | OFrame_levels)
|
clemus90/competitive-programming | hackerRank/crackingTheCodingInterview/time_complexity_primality.py | Python | mit | 622 | 0.033762 | def checkPrime(primes, test):
i = 0
isPrime = True
while(i<= len(primes) | and primes[i]<= int(test ** (1/2))):
if(test % primes[i] == 0):
isPrime = False
break
i+=1
return isPrime
primes = [2]
i = 3
lastTest = int((2 * (10**9))**(1/2)) #Square Root of 2 * 10 ^9
#build an array of primes up to the lastTest
while(i<=lastTest):
if(checkPrime(primes, i)):
primes.appe... | e" if test in primes else "Not prime")
else:
print("Prime" if checkPrime(primes, test) else "Not prime")
|
sagiss/sardana | src/sardana/taurus/qt/qtgui/extra_macroexecutor/sequenceeditor/model.py | Python | lgpl-3.0 | 14,281 | 0.002311 | #!/usr/bin/env python
##############################################################################
##
## This file is part of Sardana
##
## http://www.sardana-controls.org/
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Sardana is free software: you can redistribute it and/or modify
## it und... | from_qvariant(value, str)) |
self.emit(Qt.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index)
while True:
index = index.parent()
node = self.nodeFromIndex(index)
if isinstance(node, macro.MacroNode):
self.emit(Qt.SIGNAL("d... |
er432/TASSELpy | TASSELpy/test/net/maizegenetics/analysis/association/associationTestSuite.py | Python | bsd-3-clause | 472 | 0.006356 | import unittest
from TASSELpy.TASSELbridge import TASSELbridge
from TASSELpy.test.net.maizegenetics.analysis.association.FixedEffectLMPlugin import easy_GLMTest
class associationTestSuite(unittest.TestSuite):
def __init__(self):
| super(associationTestSuite, self).__init__()
self.addTest(unittest.makeSuite(easy_GLMTest))
if __name__ == "__main__":
runner = unittest.TextTestRunner()
runner.run(association | TestSuite())
TASSELbridge.stop()
|
yunlzheng/tomatodo | tt/application.py | Python | mit | 1,854 | 0.001618 | # coding: utf-8
import os
from os.path import abspath, dirname
import tornado.web
import tornado.httpserver
im | port tornado.ioloop
from tornado.log import app_log
from | tornado.options import define, options
from mongoengine import connect
from tt.handle import MainHandler, MongoBackboneHandler, LoginHandler, RegisterHandler, LogoutHandler
PROJECT_DIR = dirname(dirname(abspath(__file__)))
TEMPLATE_DIR = os.path.join(PROJECT_DIR, 'templates')
STATIC_DIR = os.path.join(PROJECT_D... |
pi19404/robosub-1 | src/movement/physical/fuzzy_logic_defuzzifier.py | Python | gpl-3.0 | 1,604 | 0.004364 | # COPYRIGHT: Robosub Club of the Palouse under the GPL v3
import argparse
import time
import os
import sys
| from copy import deepcopy
from random import random
sys.path.append(os.path.abspath("../.."))
from util.communication.grapevine import Communicator
# TODO: This module should take the fuzzy sets produced by
# movement/stabilization and should translate them into raw digital
# values that can be sent over the serial in... | but it shouldn't. microcontroller_interface.py should figure out how
# to send data over the serial interface and how to receive data over
# the serial interface. Anything that is beyond that scope, such as
# translating a magnitude into a raw value, should be moved into this
# module.
def main(args):
com = Commu... |
isudox/leetcode-solution | python-algorithm/leetcode/problem_38.py | Python | mit | 1,320 | 0 | """38. Count and Say
https://leetcode.com/problems/count-and-say/description/
The count-and-say sequen | ce is the sequence of integers with the first five
terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as " | one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the n^th term of the
count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a
string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4... |
imiolek-ireneusz/eduActiv8 | game_boards/game017.py | Python | gpl-3.0 | 14,410 | 0.002984 | # -*- coding: utf-8 -*-
import math
import os
import pygame
import random
import sys
import classes.board
import classes.extras as ex
import classes.game_driver as gd
import classes.level_controller as lc
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.... |
dc_img_src = os.path.join('unit_bg', "universal_r2x1_dc.png")
else:
dc_img_src = None
| if self.mainloop.scheme.dark:
self.bg_color_active = ex.hsv_to_rgb(hue, 255, 200)
self.bg_color_done = ex.hsv_to_rgb(hue, 255, 55)
bg_img_src = os.path.join('unit_bg', "universal_r2x1_bg_s150.png")
for i in range(self.abc_len):
if self.lang.has_uc:
... |
johanesmikhael/ContinuityAnalysis | slice_visualization_ui.py | Python | mit | 1,409 | 0.002129 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'slice_visualization.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_slice_visualization_gui(object):
def setupUi(self, slice_v... | self.statusbar.setObjectName("statusbar")
slice_visualization_gui.setStatusBar(self.statusbar)
self.retranslateUi(slice_visualization_gui)
QtCore.QMetaObject.connectSlotsByName(sli | ce_visualization_gui)
def retranslateUi(self, slice_visualization_gui):
_translate = QtCore.QCoreApplication.translate
slice_visualization_gui.setWindowTitle(_translate("slice_visualization_gui", "MainWindow"))
|
mclois/iteexe | twisted/internet/_posixserialport.py | Python | gpl-2.0 | 2,116 | 0.016541 | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Serial Port Protocol
"""
# system imports
import os, errno
# dependent on pyserial ( http://pyserial.sf.net/ )
# only tested w/ 1.18 (5 Dec 2002)
import serial
from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
from serial im... |
self.protocol.makeConnection(self)
self.startReading()
def fileno(self):
return self._serial.fd
def writeSomeData(self, data):
"""Write some data to the serial device.
"""
try:
return os.write(self.fileno(), data)
except IOError, io:
... | except OSError, ose:
if ose.errno == errno.EAGAIN:
# I think most systems use this one
return 0
raise
def doRead(self):
"""Some data's readable from serial device.
"""
return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived)
... |
Bugfry/exercises | exercism/python/rna-transcription/dna.py | Python | mit | 129 | 0.015504 | def to_rna(strain):
mapping = {"G": "C" | , "C": "G", "A": "U", "T": "A"}
return "".join(map(lambda c: ma | pping.get(c), strain))
|
Firefly-Automation/Firefly | Firefly/automation/nest_eco_window/metadata.py | Python | apache-2.0 | 862 | 0.00348 | AUTHOR = 'Zachary Priddy. (me@zpriddy.com)'
TITLE = 'Nest Eco Window'
METADATA = {
'title': TITLE,
'author': AUTHOR,
'commands': [],
'interface': {
'devices': {
"windows": {
'context': 'Windows that will trigger this automation.',
'type': 'deviceList',
'filter': {... | 'request': ['contact']
}
},
},
'send_messages': {
"send": {
'context': 'Send message when chaning the mode of the Nest.',
'type': 'boolean'
}
},
'delays': | {
'delayed': {
'context': 'Time to delay after window closes before changing Nest mode. (seconds)',
'type': 'number'
},
'initial': {
'context': 'Time to delay after window opens before changing Nest mode. (seconds)',
'type': 'number'
}
}
}
} |
Jokeren/neon | neon/visualizations/data.py | Python | apache-2.0 | 7,474 | 0.002944 | # ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... | ecast from pixels of u8u8u8u8 to u32
bokeh_img = np.dstack([img_data, 255 * np.ones((img_h, img_w), np.uint8)])
final_image = bokeh_img.reshape(img_h, img_w * (C + 1)).view(np.uint32)
return final_image
def h5_deconv_data | (filename):
"""
Read deconv visualization data from hdf5 file.
Arguments:
filename (str): Filename with hdf5 deconv data
Returns:
list of lists. Each inner list represents one layer, and consists of
tuples (fm, deconv_data)
"""
ret = list()
with h5py.File(filename, ... |
wcy940418/CRNN-end-to-end | src/test.py | Python | mit | 1,976 | 0.034919 | from __future__ import print_function
from model import CRNN, CtcCriterion
from dataset import DatasetLmdb
import os
import tensorflow as tf
import numpy as np
class Conf:
def __init__(self):
self.nClasses = 36
self.trainBatchSize = 100
self.testBatchSize = 200
self.maxIteration = 1000
self.displayInterval ... | t2Char(n):
if n >= 0 and n <=9:
c = chr(n + 48)
elif n >= 10 and n<= 35:
c = chr(n + 97 - 10)
elif n == 36:
c = ''
return c
def convertSparseArrayToStrs(p):
print(p[0].shape, p[1].shape, p[2].shape)
print(p[2][0], p[2][1])
results = []
labels = []
for i in range(p[2][0]):
results.append([36 for x in ... | range(len(results)):
label = ''
for j in range(len(results[i])):
label += labelInt2Char(results[i][j])
labels.append(label)
return labels
if __name__ == '__main__':
gConfig = Conf()
sess = tf.InteractiveSession()
weights = None
if os.path.isfile(gConfig.modelParFile+'.index'):
weights = gConfig.model... |
kpech21/Greek-Stemmer | greek_stemmer/closets/rules.py | Python | lgpl-3.0 | 7,944 | 0.008683 | # -*- coding: utf-8 -*-
# extracted rules for stemming
rules = {
'verbs': {
'irregular': {
'type_1': ['ΕΙΜΑΙ', 'ΕΙΣΑΙ', 'ΕΙΝΑΙ', 'ΕΙΜΑΣΤΕ', 'ΕΙΣΤΕ', 'ΕΙΣΑΣΤΕ'],
'type_2': ['ΗΜΟΥΝ', 'ΗΣΟΥΝ', 'ΗΤΑΝΕ', 'ΗΜΟΥΝΑ', 'ΗΣΟΥΝΑ', 'ΗΜΑΣΤΕ', 'ΗΣΑΣΤΕ', 'ΗΜΑΣΤΑΝ', 'ΗΣΑΣΤΑΝ', 'ΗΤΑΝ',
... | 'ΕΣΤΑΤΟΙ', 'ΑΙΤΕΡΟΙ', 'ΑΙΤΕΡΩΝ',
'ΑΙΤΕΡΗΣ', 'ΑΙΤΕΡΑΣ', 'ΟΥΜΕΝΟΥ', 'ΟΥΜΕΝΟΣ', 'ΟΥΜΕΝΗΣ', 'ΟΥΜΕΝΩΝ', 'ΟΥΜΕΝΕΣ', 'ΟΜΕΝΟΥΣ',
'ΕΣΤΑΤΩΝ', 'ΕΣΤΕΡΟΝ', 'ΗΜΕΝΟΥΣ', 'ΟΥΣΤΑΤΗ', 'ΟΥΣΤΑΤΑ', 'ΕΣΤΕΡΟΝ', 'ΟΥΣΤΑΤΟ', 'ΩΤΕΡΟΥΣ',
'ΩΤΑΤΟΥΣ', 'ΥΤΕΡΕΣ', 'ΩΜΕΝΟΥ', 'ΟΤΑΤΩΝ', ... | 'ΥΤΑΤΩΝ', 'ΥΤΕΡΗΣ', 'ΟΜΕΝΟΣ',
'ΟΤΕΡΟΙ', 'ΟΤΕΡΩΝ', 'ΥΤΑΤΟΣ', 'ΥΤΑΤΟΥ', 'ΕΣΤΑΤΑ', 'ΥΤΑΤΗΣ', 'ΟΤΕΡΟΣ', 'ΟΤΕΡΟΥ', 'ΥΤΑΤΕΣ',
'ΟΤΕΡΕΣ', 'ΥΤΕΡΟΙ', 'ΥΤΕΡΩΝ', 'ΑΙΤΕΡΟ', 'ΟΤΕΡΗΣ', 'ΥΤΕΡΟΣ', 'ΑΙΤΕΡΗ', 'ΑΙΤΕΡΑ', 'ΜΕΝΟΥΣ',
'ΥΤΕΡΟΥ', 'ΩΜΕΝΗΣ', 'ΩΜΕΝΩΝ', 'ΩΜΕΝΕΣ', ... |
Tomsod/gemrb | gemrb/GUIScripts/iwd/CharGen.py | Python | gpl-2.0 | 92,820 | 0.040509 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003-2005 The GemRB Project
#
# 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 opt... | ontrol (2)
ClassButton.SetState (IE_GUI_BUTTON_DISABLED)
ClassButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ClassPress)
ClassButton.SetText (11959)
AlignmentButton = CharGenWindow.GetControl (3)
AlignmentButton.SetState (IE_GUI_BUTTON_DISABLED) |
AlignmentButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AlignmentPress)
AlignmentButton.SetText (11958)
AbilitiesButton = CharGenWindow.GetControl (4)
AbilitiesButton.SetState (IE_GUI_BUTTON_DISABLED)
AbilitiesButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AbilitiesPress)
AbilitiesButton.SetText (11960)
SkillsButton = Ch... |
brandonw/personal-site | docs/conf.py | Python | bsd-3-clause | 7,764 | 0.007728 | # -*- coding: utf-8 -*-
#
# Personal Site documentation build configuration file, created by
# sphinx-quickstart.
#
# 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 ... | = False
# -- Options for Texinfo output ------------------------------------------------ |
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'personal-site', u'Personal Site Documentation',
u'Brandon Waskiewicz', 'Personal Site',
'My personal website.','Miscellan... |
miso-belica/jusText | justext/paragraph.py | Python | bsd-2-clause | 1,667 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import re
from .utils import normalize_whitespace
HEADINGS_PATTERN = re.compile(r"\bh\d\b")
class Paragraph( | object):
"""Object representing one block of text in HTML."""
def __init__(self, path):
self.dom_path = path.dom
self.xpath = path.xpath
self.text_nodes = []
self.chars_count_in_links = 0
self.tags_count = 0
s | elf.class_type = "" # short | neargood | good | bad
@property
def is_heading(self):
return bool(HEADINGS_PATTERN.search(self.dom_path))
@property
def is_boilerplate(self):
return self.class_type != "good"
@property
def text(self):
text = "".join(self.text_nodes)
... |
Lamecarlate/gourmet | gourmet/gtk_extras/timeEntry.py | Python | gpl-2.0 | 4,398 | 0.012278 | ### Copyright (C) 2005 Thomas M. Hinkle
### Copyright (C) 2009 Rolf Leggewie
###
### This library 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) an... | tk.Window()
vb = gtk.VBox()
hb = gtk.HBox()
l=gtk.Label('_Label')
l.set_use_underline(True)
l.set_alignment(0,0.5)
hb.pack_start(l)
te=TimeEntry()
import sys
te.connect('changed',lambda w: sys.stderr.write('Time value: %s'%w.get_value()))
l.set_mnemonic_w | idget(te)
hb.pack_start(te,expand=False,fill=False)
vb.add(hb)
qb = gtk.Button(stock=gtk.STOCK_QUIT)
vb.add(qb)
l.show()
hb.show()
qb.show()
te.show()
vb.show()
qb.connect('clicked',lambda *args: w.hide() and gtk.main_quit() or gtk.main_quit())
w.add(vb)
w.show()
w.co... |
quantumlib/OpenFermion-Cirq | openfermioncirq/variational/ansatzes/swap_network_trotter_hubbard.py | Python | apache-2.0 | 10,098 | 0.000891 | # 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
# distribu... | in arXiv:1507.08969,
but corresponds to a different ordering for simulating the Hami | ltonian
terms.
"""
def __init__(self,
x_dim: float,
y_dim: float,
tunneling: float,
coulomb: float,
periodic: bool=True,
iterations: int=1,
adiabatic_evolution_time: Optional[float]=None,
... |
queirozfcom/spam-filter | lib/validation.py | Python | mit | 269 | 0.02974 | def val | idate_cross_validation(rounds,train_to_test_ratio):
# the number of turns must be exactly equal to the number
# of "parts" you'll split your data into
res = rounds * (1 - train_to_test_ratio)
# comparando floats na marra.
ass | ert ( abs(res - 1) < 0.0001 )
|
buck06191/BayesCMD | bayescmd/abc/dtaidistance/__init__.py | Python | gpl-2.0 | 771 | 0.005188 | import logging
logger = logging.getLogger("be.kuleuven.dtai.distance")
from . import dtw
try:
from . import dtw_c
except ImportError:
import os
# Try to compile automatically
# try:
# import numpy as np
# import pyximport
# pyximport.install(setup_args={'include_dirs': n | p.get_include()})
# from . import dtw_c
# except ImportError:
dtaidistance_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)
logger.warning("\nDTW C variant not available.\n\n" +
"If you want to use the C libraries (not required, depends on cython), " +
... | "then run `cd {};python3 setup.py build_ext --inplace`.".format(dtaidistance_dir))
dtw_c = None
__version__ = "0.1.6"
|
numericube/twistranet | twistranet/core/caches.py | Python | agpl-3.0 | 1,772 | 0.009029 | """
Various caching help functions and classes.
"""
from django.core.cache import cache
DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long.
USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not.
class _AbstractCache(object):
... | or_id = useraccount_or_id.id
super(UserAccountCache, self).__init__("UA%d" % useraccount_or_id)
# Online information
def get_online(self): return self._get("online", False)
def set_online(self, v): return self._set("online", | v)
online = property(get_online, set_online)
|
PowerDNS/pdns | regression-tests.recursor-dnssec/test_KeepOpenTCP.py | Python | gpl-2.0 | 2,856 | 0.001401 | import dns
import os
import socket
import struct
from recursortests import RecursorTest
class testKeepOpenTCP(RecursorTest):
_confdir = 'KeepOpenTCP'
_config_template = """dnssec=validate
packetcache-ttl=10
packetcache-servfail-ttl=10
auth-zones=authzone.example=configs/%s/authzone.zone""" % _confdir
@c... | RecursorConfig(confdir)
def sendTCPQueryKeepOpen(cls, sock, query, timeout=2.0):
try:
wire = query.to_wire()
sock.send(struct.pack("!H", len(wire)))
sock.send(wire)
data = sock.recv(2)
if data:
(datalen,) = struct.unpack("!H", data... | t socket.timeout as e:
print("Timeout: %s" % (str(e)))
data = None
except socket.error as e:
print("Network error: %s" % (str(e)))
data = None
message = None
if data:
message = dns.message.from_wire(data)
return message
de... |
KWARC/mwetoolkit | bin/combine_freqs.py | Python | gpl-3.0 | 12,449 | 0.01952 | #!/usr/bin/python
# -*- coding:UTF-8 -*-
################################################################################
#
# Copyright 2010-2012 Carlos Ramisch, Vitor De Araujo
#
# combine_freqs.py is part of mwetoolkit
#
# mwetoolkit is free software: you can redistribute it and/or modify
# it under the terms of the... | d counts. The
| list contains as many elements as there are frequency sources in the
candidates list.
@return A tuple cotaining (combined_count, backed_off). The former is a
float containing the combined count using a given method, the latter is
a boolean flag that indicates that the com... |
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/shirt/shared_shirt_s16.py | Python | mit | 478 | 0.031381 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS | MAY BE LOST IF DONE IMPROPERLY
#### PLEA | SE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/shirt/shared_shirt_s16.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","shirt_s16")
#### BEGIN MODIFICATIONS ####
result.max_condi... |
zvolsky/akce | controllers/keys.py | Python | agpl-3.0 | 1,007 | 0.004965 | # -*- coding: utf-8 -*-
@auth.requires_membership('admin')
def starts():
grid = SQLFORM.grid(db.typ_zacatku,
showbuttontext=False)
return dict(grid=grid)
@auth.requires_membership('admin')
def contacts():
grid = SQLFORM.grid(db.typ_kontaktu,
showbuttontext=F... | uires_membership('admin')
def places():
grid = SQLFORM.grid(db | .typ_mista,
showbuttontext=False)
return dict(grid=grid)
@auth.requires_membership('admin')
def links():
grid = SQLFORM.grid(db.typ_odkaz,
showbuttontext=False)
return dict(grid=grid)
@auth.requires_membership('admin')
def uploads():
grid = SQLFORM.grid(... |
liaozhida/liaozhida.github.io | _posts/pythonbak/Atest.py | Python | apache-2.0 | 1,140 | 0.073345 | # -*- coding: utf-8 -*-
import json
import os
import re
def jsonTokv():
file = open('zhihu_cookies', 'r')
try:
cookies = json.load(file)
# print len(cookies)
e | xcept ValueError,e:
print 'cache-cookie is None'
cookiesStr = ''
for key in cookies:
cookiesStr += key+'='+cookies[key]+';'
print c | ookiesStr[0:-1]
return cookiesStr[0:-1]
def jsonDelete():
draftData = {
"do": "saveArticle",
"type": "1",
"title": "如何正确的发布md",
"text": "# 这是标题",
"weibo": "0",
"blogId": "0",
"aticleId": "",
"id": "",
"tags[]": "1040000000366352",
"url": ""
}
del draftData['do']
print draftData
def... |
ashishthedev/gae-django-skeleton | src/project_name/settings/gae.py | Python | mit | 2,540 | 0.009449 | #!/usr/bin/env python
import os
# Load production settings when running on GAE or SETTINGS_MODE is prod
# else, load loc | al setting | s
if (os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine') or os.getenv('SETTINGS_MODE') == 'prod'):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.production")
from production import *
########## DATABASE CONFIGURATION
# TODO: Enter your application id below. If you... |
UltrosBot/Ultros3K | src/ultros/networks/irc/connectors/plain.py | Python | artistic-2.0 | 310 | 0.003226 | # coding=utf-8
import asyncio
from ultros.networks.irc.connectors.base import BaseIRCConnector
__author__ = "Gareth Coles"
class PlainIRCConnector(BaseIRCConnector | ):
async def do_connect(self):
transport | , _ = await asyncio.get_event_loop().create_connection(lambda: self, self.host, self.port)
|
jtpaasch/armyguys | armyguys/aws/ecs/taskdefinition.py | Python | mit | 3,013 | 0 | # -*- coding: utf-8 -*-
"""Utilities for working with ECS task definitions."""
import json
import os
from .. import client as boto3client
def create(profile, contents=None, filepath=None):
"""Upload a task definition to ECS.
Args:
profile
A profile to connect to AWS with.
cont... | erDefinitions"] = data.get("containerDefinitions")
params["volumes"] = data.get("volumes")
if params["volumes"] is None:
params["volumes"] = []
return client.register_task_definition(**params)
def delete(profile, name):
"""Delete an ECS task definition.
Args:
profile
... | e to connect to AWS with.
name
The full name, i.e., family:revision.
Returns:
The data returned by boto3.
"""
client = boto3client.get("ecs", profile)
params = {}
params["taskDefinition"] = name
return client.deregister_task_definition(**params)
def get_arns(prof... |
spulec/moto | tests/test_dax/test_dax.py | Python | apache-2.0 | 19,374 | 0.001032 | """Unit tests for dax-supported APIs."""
import boto3
import pytest
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from moto import mock_dax
from moto.core import ACCOUNT_ID
# See our Development Tips on writing tests for hints on how to write good tests:
# http://docs... | eArn="arn:sth:aws:else",
)
err = exc.value.response["Error"]
err["Code"].should.equal("InvalidParameterValueException")
err["Message"].should.equal(
"Fourth colon (region/namespace delimiter) not found: arn:sth:aws:else"
)
@mock_dax
def test_create_cluster_invalid_arn_no_namespace():
... | e_cluster(
ClusterName="1invalid",
NodeType="dax.t3.small",
ReplicationFactor=3,
IamRoleArn="arn:sth:aws:else:eu-west-1",
)
err = exc.value.response["Error"]
err["Code"].should.equal("InvalidParameterValueException")
err["Message"].should.equal(
... |
keras-team/keras | keras/integration_test/gradient_checkpoint_test.py | Python | apache-2.0 | 6,728 | 0.012931 | # Copyright 2020 The TensorFlow Author | s. 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, softw... | ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import gc
import tensorflow.compat.v2 as tf
from tensorflow.python.framework import test_util a... |
webjunkie/python-social-auth | social/apps/django_app/default/migrations/0003_alter_email_max_length.py | Python | bsd-3-clause | 548 | 0 | # -*- coding: utf-8 -*-
fro | m __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
from social.utils import setting_name
EMAIL_LENGTH = getattr(settings, setting_name('EMAIL_LENGTH'), 254)
class Migration(migrations.Migration):
dependencies = [
('default', '0002_add_relat | ed_name'),
]
operations = [
migrations.AlterField(
model_name='code',
name='email',
field=models.EmailField(max_length=EMAIL_LENGTH),
),
]
|
ecell/ecell3 | ecell/frontend/model-editor/ecell/ui/model_editor/NestedListEditor.py | Python | lgpl-3.0 | 4,695 | 0.017891 | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#:::::::::::::::::::::::::::::::::::::::... | port os
import os.path
import sys
import gtk
impo | rt gobject
from ecell.ui.model_editor.Utils import *
from ecell.ui.model_editor.Constants import *
from ecell.ui.model_editor.ModelEditor import *
from ecell.ui.model_editor.ViewComponent import *
class BadNestedList( Exception ):
def __init__( self, badString ):
self.args = "%s\n cannot be parsed as nest... |
peiwei/zulip | zerver/views/__init__.py | Python | apache-2.0 | 58,738 | 0.006742 | from __future__ import absolute_import
from typing import Any
from django.utils.translation import ugettext as _
from django.conf import settings
from django.contrib.auth import authenticate, login, get_backends
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponseForb... | ent, \
split_email_to_domain, resolve_email_to_domain, email_to_username, get_realm, \
completely_open, get_unique_open_realm, remote_user_to_email, email_allowed_for_realm
from zerver.lib.actions import do_change_password, do_change_full_name, d | o_change_is_admin, \
do_activate_user, do_create_user, \
internal_send_message, update_user_presence, do_events_register, \
get_status_dict, do_change_enable_offline_email_notifications, \
do_change_enable_digest_emails, do_set_realm_name, do_set_realm_restricted_to_domain, \
do_set_realm_invite_req... |
citrix-openstack-build/os-brick | os_brick/tests/test_exception.py | Python | apache-2.0 | 2,260 | 0 |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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... | oftware
# d | istributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import six
from os_brick import exception
from os_brick.tests impo... |
bitcoinfees/bitcoin-feemodel | feemodel/tests/test_txrate.py | Python | mit | 6,229 | 0 | from __future__ import division
import os
import unittest
import threading
import logging
from random import expovariate, random
from math import log
from feemodel.tests.config import (test_memblock_dbfile as dbfile, txref,
tmpdatadir_context)
from feemodel.txmempool import MemBlock... | tr = RectEstimator(maxsamplesize=100000)
print("Starting estimation from generated...")
tr.start(self.gen_blockrange, dbfile=self.tmpdbfile)
print("Rect estimation from generated:")
print("===============================")
print("Test:")
| print(repr(tr))
print(tr)
print("Ref:")
print(repr(txref))
print(txref)
# _dum, byterates = tr.get_byterates(feerates=FEERATES)
testbyteratefn = tr.get_byteratefn()
# for test, target in zip(byterates, txref_rates):
for fe... |
sutartmelson/girder | girder/models/setting.py | Python | apache-2.0 | 15,828 | 0.001516 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... | e governing permissions and
# limitations under the License.
###############################################################################
from collections import OrderedDict
import cherrypy
import pymongo
import six
from ..constants import GIRDER_ROUTE_ID, GIRDER_STATIC_ROUTE_ID, SettingDefault, Sett | ingKey
from .model_base import Model, ValidationException
from girder import logprint
from girder.utility import config, plugin_utilities, setting_utilities
from girder.utility.model_importer import ModelImporter
from bson.objectid import ObjectId
class Setting(Model):
"""
This model represents server-wide co... |
rembo10/headphones | lib/beets/__init__.py | Python | gpl-3.0 | 1,380 | 0 | # This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (th | e
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, | and to
# permit persons to whom 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.
import confuse
from sys import stderr
__version__ = '1.6.0'
__author__ = 'Ad... |
mbi/django-rosetta | rosetta/storage.py | Python | mit | 4,395 | 0.00182 | import hashlib
import importlib
import time
from django.conf import settings
from django.core.cache import caches
from django.core.exceptions import ImproperlyConfigured
from .conf import settings as rosetta_settings
cache = caches[rosetta_settings.ROSETTA_CACHE_NAME]
class BaseRosettaStorage(object):
def __in... |
if self.request.session['rosetta_cache_storage_key_prefix' | ] != self._key_prefix:
raise ImproperlyConfigured(
"You can't use the CacheRosettaStorage because your Django Session storage doesn't seem to be working. The CacheRosettaStorage relies on the Django Session storage to avoid conflicts."
)
# Make sure we're not using Dummy... |
jricardo27/travelhelper | travelhelper/apps/core/templatetags/__init__.py | Python | bsd-3-clause | 93 | 0 | """
Template Tag | s go in this directory
Load modules in templates with {% loa | d badger %}
"""
|
oghm2/hackdayoxford | cellcounter/main/management/commands/loadcsv.py | Python | mit | 1,153 | 0.026886 | from django.core.management.base import BaseCommand, CommandError
from cellcounter.main.models import CellImage, SimilarLookingGroup, CellType
import csv
class dialect(csv.Dialect):
pass
class Command(BaseCommand):
args = '<csvfile1 csvfile2 ...>'
help = 'Loads images and descriptions from specified csv f... | lename in args:
file_ = csv.DictReader(open(filename), dialect="excel-tab")
for line in file_:
try:
celltype = CellType.objects.get(readable_name = line["CellType"] | )
except:
print "Cell Type not found:" + line["CellType"]
ci = CellImage(title = line["Title"],
description = line["Description"],
file = line["Filename"],
thumbnail_lef... |
sdispater/orator | tests/support/test_collection.py | Python | mit | 8,036 | 0.000622 | # -*- coding: utf-8 -*-
from .. import OratorTestCase
from orator.support.collection import Collection
class CollectionTestCase(OratorTestCase):
def test_first_returns_first_item_in_collection(self):
c = Collection(["foo", "bar"])
self.assertEqual("foo", c.first())
def test_last_returns_las... | )
self.asser | tEqual({"john": "foo", "jane": "bar"}, c.lists("email", "name"))
self.assertEqual(["foo", "bar"], c.pluck("email").all())
def test_map(self):
c = Collection([1, 2, 3, 4, 5])
self.assertEqual([3, 4, 5, 6, 7], c.map(lambda x: x + 2).all())
def test_merge(self):
c = Collection([1,... |
aureooms/checkio | elementary/02-index-power.py | Python | agpl-3.0 | 49 | 0.102041 | inde | x_power=lambda a,n:a[n]**n if n<len | (a)else-1
|
spiderbit/canta-ng | event/keyboard_event.py | Python | gpl-3.0 | 3,140 | 0.003822 | #! /usr/bin/python -O
# -*- coding: utf-8 -*-
#
# CANTA - A free entertaining educational software for singing
# Copyright (C) 2007 S. Huchler, A. Kattner, F. Lopez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published b... | t[1] == soya.sdl | const.K_LSHIFT:
# self.shift = False
# elif event[1] == soya.sdlconst.K_RCTRL \
# or event[1] == soya.sdlconst.K_LCTRL:
# self.ctrl = False
# elif event[1] == soya.sdlconst.K_RALT \
# or event[1] == s... |
takeflight/wagtailvideos | wagtailvideos/fields.py | Python | bsd-3-clause | 2,114 | 0.001419 | from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms.fi | elds import FileField
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
class WagtailVideoField(FileField):
def __init__(self, *args, **kwargs):
super(WagtailVideoField, self).__init__(*args, **kwargs)
# Get max upload size from sett... | max_upload_size_text = filesizeformat(self.max_upload_size)
# Help text
if self.max_upload_size is not None:
self.help_text = _(
"Maximum filesize: %(max_upload_size)s."
) % {
'max_upload_size': max_upload_size_text,
}
# Err... |
richardliaw/ray | streaming/python/tests/test_operator.py | Python | apache-2.0 | 1,294 | 0 | from ray.streaming import function
from ray.streaming import operator
from ray.streaming.operator import OperatorType
from ray.streaming.runtime impor | t gateway_client
def test_create_operator_with_func():
map_func = function.SimpleMapFunction(lambda x: x)
map_operator = operator.create_operator_with_func(map | _func)
assert type(map_operator) is operator.MapOperator
class MapFunc(function.MapFunction):
def map(self, value):
return str(value)
class EmptyOperator(operator.StreamOperator):
def __init__(self):
super().__init__(function.EmptyFunction())
def operator_type(self) -> OperatorType:... |
bluecube/pysystemfan | pysystemfan/status_server.py | Python | mit | 2,693 | 0.003713 | from . import config_params
from . import util
import http.server
import threading
import json
import logging
logger = logging.getLogger(__name__)
_not_set = object()
class StatusServer(config_params.Configurable):
_params = [
("port", _not_set, "Port where to serve the status page. Default is to not ru... | ddress)
self._thread.start()
def stop(self):
logger.debug("Waiting for server to shut down")
self._server.shutdown()
self._thread.join()
logger.inf | o("Server stopped")
|
maferelo/saleor | saleor/product/migrations/0018_auto_20161212_0725.py | Python | bsd-3-clause | 582 | 0.001718 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-12 13:25
from __future__ import unicode_literals
from django.db import migrations
from django.utils.text import slugify
def create_slugs(apps, schema_editor):
Value = apps.get_model("product", "AttributeChoiceValue")
for | value in Value.objects.all():
value.slug = slugify(value.display)
value.save()
class Migration(migrations.Migration):
dependencies = [("product", "0017_attributechoicevalue_slug")]
opera | tions = [migrations.RunPython(create_slugs, migrations.RunPython.noop)]
|
larsyencken/cjktools | cjktools/resources/zhuyin_table.py | Python | bsd-3-clause | 2,155 | 0.000464 | # -*- coding: utf-8 -*-
#
# zhuyin_table.py
# cjktools
#
"""
An interface to the zhuyin <-> pinyin table.
"""
from functools import partial
from . import cjkdata
from cjktools.common import get_stream_context, stream_codec
def _default_stream():
return open(cjkdata.get_resource('tables/zhuyin_pinyin_conv_tab... | text(istream) as istream:
table = {}
for zhuyin, pinyin in parse_lines(istream):
table[pinyin] = zhuyin
return table
def get_all_pinyin(istream=None):
| """ Returns a list of all pinyin """
with _get_stream_context(istream) as istream:
all_pinyin = ['r']
for zhuyin, pinyin in parse_lines(istream):
all_pinyin.append(pinyin)
return all_pinyin
def pinyin_regex_pattern(istream=None):
""" Returns a pinyin regex pattern, with optio... |
jgeewax/gcloud-python | scripts/verify_included_modules.py | Python | apache-2.0 | 6,286 | 0 | # Copyright 2016 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 or agreed to in writing, ... | Python module rather than a file path.
rel_path = rel_path.replace(os.path.sep, '.')
if mod_name == '__init__':
result.append(rel_path[:-len('.__init__')])
else:
result.append(rel_path)
return result
def verify_modules(build_... | ts to ``_build``.
"""
object_inventory_relpath = os.path.join(build_root, 'html', 'objects.inv')
mock_uri = ''
inventory = fetch_inventory(SphinxApp, mock_uri,
object_inventory_relpath)
sphinx_mods = set(inventory['py:module'].keys())
public_mods = set()
for... |
casawa/mdtraj | mdtraj/utils/unit/standard_dimensions.py | Python | lgpl-2.1 | 2,307 | 0.002167 | #!/bin/env python
"""
Module simtk.unit.standard_dimensions
Definition of principal dimensions: mass, length, time, etc.
This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roa... | THORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__author__ = "Christopher M. Bruns"
__version__ = "0.6"
from .bas... | ##############
mass_dimension = BaseDimension('mass')
length_dimension = BaseDimension('length')
time_dimension = BaseDimension('time')
temperature_dimension = BaseDimension('temperature')
amount_dimension = BaseDimension('amount')
charge_dimension = BaseDimension('charge')
luminous_intensity_dimension = BaseDimension... |
pinac0099/dynamic-bus-scheduling | tests/mongodb_database_connection_test.py | Python | mit | 29,881 | 0.002577 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
- LICENCE
The MIT License (MIT)
Copyright (c) 2016 Eleftherios Anagnostopoulos for Ericsson AB (EU FP7 CityPulse Project)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software... | _stop_waypoints_document: {
'_id', 'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
'ending_bus_stop': {'_id', 'osm_id', 'name', 'poin | t': {'longitude', 'latitude'}},
'waypoints': [[edge_document]]
}
edge_document: {
'_id', 'starting_node': {'osm_id', 'point': {'longitude', 'latitude'}},
'ending_node': {'osm_id', 'point': {'longitude', 'latitude'}},
'max_speed', 'road_type', 'way_id', 'traffic_density'
}
node_document: {
'_id', 'os... |
projectatomic/osbs-client | osbs/api.py | Python | bsd-3-clause | 57,765 | 0.002043 | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals, absolute_import
from collections import namedtuple
import json
import logging
import... | raise
# Convert anything else to OsbsException
# Python 3 has implicit exception chaining and enhanced
# reporting, so you get the original traceback as well as
# the one or | iginating here.
# For Python 2, let's do that explicitly.
raise OsbsException(cause=ex, traceback=sys.exc_info()[2])
return catch_exceptions
_REQUIRED_PARAM = object()
logger = logging.getLogger(__name__)
LogEntry = namedtuple('LogEntry', ['platform', 'line'])
def validate_arrangement... |
DESHRAJ/fjord | fjord/analytics/tests/test_views.py | Python | bsd-3-clause | 16,139 | 0 | import json
import logging
from datetime import date, datetime, timedelta
from elasticsearch.exceptions import ConnectionError
from nose.tools import eq_
from pyquery import PyQuery
from django.contrib.auth.models import Group
from django.http import QueryDict
from fjord.analytics import views
from fjord.base.tests ... | .search.tests import ElasticTestCase
logger = logging.getLogger(__name__)
class TestDashboardView(ElasticTestCase):
client_class = LocalizingClient
de | f setUp(self):
super(TestDashboardView, self).setUp()
# Set up some sample data
# 4 happy, 3 sad.
# 2 Windows XP, 2 Linux, 1 OS X, 2 Windows 7
now = datetime.now()
# The dashboard by default shows the last week of data, so
# these need to be relative to today. The... |
daureg/illalla | twitter_helper.py | Python | mit | 8,052 | 0.000994 | #! /usr/bin/python2
# vim: set fileencoding=utf-8
"""Functions used in twitter scrapper main code."""
import functools
from timeit import default_timer as clock
from time import sleep
import utils as u
import cities
import pytz
import ujson
import logging
from datetime import datetime, timedelta
import re
CHECKIN_URL =... | 'coordinates')
city = None
if not loc:
# In that case, we would have to follow the link to know whether the
# checkin falls within our cities but tha | t's too costly so we drop it
# (and introduce a bias toward open sharing users I guess)
return None
lon, lat = loc['coordinates']
city = find_town(lat, lon, CITIES_TREE)
if not (city and city in cities.SHORT_KEY):
return None
tid = u.get_nested(tweet, 'id_str')
urls = u.get_n... |
SuperNovaPOLIUSP/supernova | aeSupernova/login/migrations/0001_initial.py | Python | agpl-3.0 | 1,436 | 0.002089 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | options={
'db_table': b'user_log',
'managed': True,
},
bases=(models.Model,),
),
migrations.CreateModel(
| name='Session',
fields=[
('idsession', models.AutoField(serialize=False, primary_key=True, db_column=b'idSession')),
('start', models.DateTimeField(db_column=b'start')),
('end', models.DateTimeField(null=True, db_column=b'end', blank=True)),
... |
mbedmicro/pyOCD | test/json_lists_test.py | Python | apache-2.0 | 7,561 | 0.003174 | # pyOCD debugger
# Copyright (c) 2006-2015 Arm Limited
# SPDX-License-Identifier: Apache-2.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... | p:
print("PASSED")
else:
did_pass = False
print("FAILED")
return | did_pass
result = JsonListsTestResult()
print("\n\n----- TESTING PROBES LIST -----")
out = subprocess.check_output(['pyocd', 'json', '--probes'])
data = json.loads(out)
test_count += 2
if validate_basic_keys(data):
test_pass_count += 1
if validate_boards(data):
test_pass_c... |
astromme/classify-handwritten-characters | predict.py | Python | mit | 1,285 | 0.003113 | import tensorflow as tf
import numpy as np
import sys
from libgnt.character_index import character_index
from utils.show_tf_image import show_tf_image
from utils.array_top_n_indexes import array_top_n_indexes
import os
def main():
if len(sys.argv) < 3:
print("usage: predict.py MODEL PNG_FILE")
sys.... | edictions[0], 5)]
print(top_5_predictions)
# show_tf_image(input_arr, f'"{os.path.basename(png_filename)}" predictions: {top_5_predictions}')
if __name__ == "__main__":
| main()
|
grindylow/tut2 | doc/conf.py | Python | gpl-3.0 | 5,052 | 0.000198 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# TUT2 documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 28 20:04:59 2018.
#
# 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
# autog... | eme
# further. For a list of op | tions available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html... |
HeavenMin/PlantImageRecognition | deepLearning/verifyResult.py | Python | apache-2.0 | 1,141 | 0.004382 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AUTHOR : MIN
PURPOSE : verify the accuracy of the model
VERSION : 0.1
DATE : 3.2017
"""
__author__ = 'Min'
import tensorflow as tf, sys
# path of the graph model
graph | Path = sys.argv[1]
# path of the model labels
labelPath = sys.argv[2]
# path of the image need to be identified
imagePath = sys.argv[3]
# read in the image
imageData = tf.gfile.FastGFile(imagePath, 'rb').read()
# loads label file
labelLines = [line.rstrip() for line | in tf.gfile.GFile(labelPath)]
with tf.gfile.FastGFile(graphPath, 'rb') as f:
graphDef = tf.GraphDef()
graphDef.ParseFromString(f.read())
_ = tf.import_graph_def(graphDef, name = '')
with tf.Session() as sess:
softmaxTensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(s... |
Haabb/pwnfork | pwn/shellcode/misc/fork.py | Python | mit | 910 | 0.00989 | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'am... | os in ['linux', 'freebsd']:
return _fork_amd64(parent, child)
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(parent, child):
code = """
push SYS_fork
pop rax
syscall
test rax, rax
jne %s
""" % parent
if child is not None:
... | code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
|
lamenezes/agendi | core/urls.py | Python | apache-2.0 | 542 | 0 | from django.core.urlresolvers import reverse_lazy
from django.conf.urls import url
from django.contrib.auth import views
from core.views import HomeView, UserAuthView, UserCreateView
urlpatterns = [
url(r'^$',
HomeV | iew.as_view(),
name='home'),
url(r'^login/$',
UserAuthView.as_view(),
name='login'),
url(r'^logout/$',
views.logout,
{'next_page': reverse | _lazy('core:home')},
name='logout'),
url(r'^signup/$',
UserCreateView.as_view(),
name='signup'),
]
|
eduNEXT/edunext-platform | import_shims/lms/bulk_email/apps.py | Python | agpl-3.0 | 368 | 0.008152 | """Deprecated import support. | Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('bulk_email.apps', 'lms.djangoapps.bulk_email.apps')
from lms.djangoapps.bulk_e... | |
roshchupkin/VBM | scripts/python/nii2np.py | Python | gpl-2.0 | 6,005 | 0.024147 | import sys
from timer import Timer
import os
import pandas as pd
import nipy
import numpy as np
import re
import argparse
def get_images_list(path, regexp, number_images=None):
im_list=[]
dir_list=os.listdir(path)
if regexp=="NO":
im_list=dir_list
return dir_list
reg=re.compile(regex... | ata.append(np.load( os.path.join(path_4d, str(region_code) +'_'+str(p) + ".npy" ) ) )
print str(region_code) +'_' +str(p) + ".npy"
p+=1
except:
break
reg | ression_data=np.concatenate(regression_data)
print "Region {}, regression data size {}, will be split by {} voxels chunks ".format(region_code,regression_data.shape, split_size)
sample_size, number_voxels=regression_data.shape
d=number_voxels/split_size
r=number_voxels-d*split_size
if d!=0:
... |
youtube/cobalt | third_party/llvm-project/lldb/scripts/utilsOsType.py | Python | bsd-3-clause | 3,130 | 0.003514 | """ Utility module to determine the OS Python running on
--------------------------------------------------------------------------
File: utilsOsType.py
Overview: Pyth | on module to supply functions and an enumeration to
help determine the platform type, bit size and OS currently
being used.
--------------------------------------------------------------------------
"""
# Python modules:
import sys # Provide system information
# Third... | lement a 'C' style enumeration type.
# Gotchas: None.
# Authors: Illya Rudkin 28/11/2013.
# Changes: None.
#--
if sys.version_info.major >= 3:
from enum import Enum
class EnumOsType(Enum):
Unknown = 0
Darwin = 1
FreeBSD = 2
Linux = 3
NetBSD = 4
Windows = 5
... |
kslundberg/pants | src/python/pants/backend/jvm/tasks/jvm_compile/jvm_compile_global_strategy.py | Python | apache-2.0 | 28,551 | 0.009422 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import itertools
imp... | ing, targets). Attempts to create as few chunks as
possible, under the constraint that targets with | different compile settings cannot be in the
same chunk, and dependencies must be in the same chunk or an earlier chunk than their
dependees.
Detects impossible combinations/dependency relationships with respect to the java target and
source level, and raising errors as necessary (see targets_to_compil... |
funa1g/TextAnalyzer | analyze.py | Python | apache-2.0 | 636 | 0.001572 | import arg | parse
from lib import TextAnalyzer
def main(file_path: str):
"""execute TextAnalyzer
"""
analyzer = TextAnalyzer()
analyzer.read(file_path)
analyzer.execute()
if __name__ == "__main__":
# execute only if run as a script
parser = argparse.ArgumentParser(description='Analyzing text')
pa... | th', metavar='f', type=str,
help='analyzing text file path')
parser.add_argument('-T', dest='text', metavar='T', type=str,
required=False, help='analyzing text')
args = parser.parse_args()
main(args.text_file_path)
|
MungoRae/home-assistant | tests/components/climate/test_generic_thermostat.py | Python | apache-2.0 | 30,816 | 0 | """The tests for the generic_thermostat."""
import asyncio
import datetime
import pytz
import unittest
from unittest import mock
import homeassistant.core as ha
from homeassistant.core import callback
from homeassistant.setup import setup_component, async_setup_component
from homeassistant.const import (
ATTR_UNIT... | 30)
self.hass.block_till_done()
self.assertEqual(1, len(self.calls))
call = | self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_set_target_temp_heater_off(self):
"""Test if target temperature turn heater off."""
self._setup_switch(True)
... |
patflick/tsppi | src/bpscore_benchmark.py | Python | mit | 3,882 | 0.000773 | #!/usr/bin/env python3
#
# This script executes different GO BPScore algorithms
# in order to compare their run times.
# for timing
import time
# for the data connection
import pappi.sql
from pappi.data_config import *
# import the GO association loading function
from pappi.go.utils import load_go_associations_sql
... | P_FILE, self.con,
True))
self.init_time.ap | pend(time.time() - start)
def benchmark_scorers(self, nGenes):
# get a set of genes with the given size
benchmark_genes = set(self.genes[0:nGenes])
# score the gene set with all scorers
score_time = []
for scorer in self.scorers:
start = time.time()
s... |
czechmark/neurioToCSV | neurioToCSV.py | Python | gpl-2.0 | 4,657 | 0.018037 | #!/usr/bin/env python
"""
Copyright [2016] [Mark Petschek mark@petschek.com]
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 la... | if entireDay:
stime = datetime.datetime.now() - datetime.timedelta(hours=dHrs)
etime = stime + datetime.timedelta(days=1)
| else:
stime = datetime.datetime.now() - datetime.timedelta(days=1)
etime = stime+datetime.timedelta(days=1)
#nuerio uses UTC, so we need to convert localtime to UTC and
#format the strings that neurio expects
stime = stime.replace(tzinfo=ltz)
etime = etime.repl... |
ray-project/ray | rllib/train.py | Python | apache-2.0 | 9,901 | 0.000202 | #!/usr/bin/env python
import argparse
import os
from pathlib import Path
import yaml
import ray
from ray.tune.config_parser import make_parser
from ray.tune.progress_reporter import CLIReporter, JupyterNotebookReporter
from ray.tune.result import DEFAULT_RESULTS_DIR
from ray.tune.resources import resources_to_json
fr... | amework specifier.",
)
parser.add_argument(
"-v", action="store_true", help="Whether to use INFO level logging."
)
parser.add_argument(
"-vv", action=" | store_true", help="Whether to use DEBUG level logging."
)
parser.add_argument(
"--resume",
action="store_true",
help="Whether to attempt to resume previous Tune experiments.",
)
parser.add_argument(
"--trace",
action="store_true",
help="Whether to attempt ... |
lkash/test | tests/test-perf2.py | Python | bsd-3-clause | 590 | 0.00339 | #!/usr/bin/env python
import time
import unittest
import dpkt
class TestPerf(unittest.TestCase):
rounds = 10000
def setUp(self):
self.start = time.time()
def tearDown(self):
print self.rounds / (time.time() - self.start), 'rounds/s'
def test_pack(self):
for i in xrange(self... | (dpkt.ip.IP())
print 'pack:',
def test_unpack(self):
buf = st | r(dpkt.ip.IP())
for i in xrange(self.rounds):
dpkt.ip.IP(buf)
print 'unpack:',
if __name__ == '__main__':
unittest.main()
|
bitmazk/cmsplugin-video-gallery | manage.py | Python | mit | 294 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault | ('DJANGO_SETTINGS_MODULE',
'video_gallery.tests.south_settings')
from django.core.management import execute_from_command_line
execute_from_com | mand_line(sys.argv)
|
github-borat/cinder | cinder/volume/drivers/netapp/eseries/client.py | Python | apache-2.0 | 14,901 | 0.000067 | # Copyright (c) 2014 NetApp, Inc.
# 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... | t.endswith('/'):
self._endpoint = '%s/' % self._endpoint
return urlparse.urljoin(self._endpoint, path.lstrip('/'))
def _invoke(self, method, path, data=None, use_system=True,
timeout=None, verify=False, **kwargs):
"""Invokes end point for resource on path."""
par... | 'v': verify, 'k': kwargs}
LOG.debug("Invoking rest with method: %(m)s, path: %(p)s,"
" data: %(d)s, use_system: %(sys)s, timeout: %(t)s,"
" verify: %(v)s, kwargs: %(k)s." % (params))
url = self._get_resource_url(path, use_system, **kwargs)
if self._content_ty... |
evernote/pootle | pootle/apps/pootle_app/management/commands/test_checks.py | Python | gpl-2.0 | 3,548 | 0.001691 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013 Evernote Corporation
#
# This file is part of Pootle.
#
# 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 L... | ilure
from django.core.management.base import NoArgsCommand, CommandError
from pootle_misc.checks import ENChecker, get_qualitychecks
from pootle_store.models import Unit
class Command(NoArgsCommand):
help = "Tests qua | lity checks against string pairs."
shared_option_list = (
make_option('--check', action='append', dest='checks',
help='Check name to check for'),
make_option('--source', dest='source', help='Source string'),
make_option('--unit', dest='unit', help='Unit id'),
mak... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.