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 |
|---|---|---|---|---|---|---|---|---|
waseem18/oh-mainline | vendor/packages/twisted/twisted/internet/test/test_sigchld.py | Python | agpl-3.0 | 6,400 | 0.002344 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet._sigchld}, an alternate, superior SIGCHLD
monitoring API.
"""
import os, signal, errno
from twisted.python.log import msg
from twisted.trial.unittest import TestCase
from twisted.internet.fdesc import setNonBlock... | rue if the SIGCHLD handler is SIG_DFL,
false otherwise.
"""
self.assertTrue(self.isDefaultHandler())
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
self.assertFalse(self.isDefaultHandler())
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
self.assertTrue(self.isDefaul... | .signal(signal.SIGCHLD, lambda *args: None)
self.assertFalse(self.isDefaultHandler())
def test_returnOldFD(self):
"""
L{installHandler} returns the previously registered file descriptor.
"""
read, write = self.pipe()
oldFD = self.installHandler(write)
self.a... |
rwl/PyCIM | CIM15/IEC61970/Generation/Production/FossilFuel.py | Python | mit | 7,612 | 0.004992 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS 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.
from CIM15.... | ilFuel(IdentifiedObject):
"""The fossil fuel consumed by the non-nuclear thermal generating units, e.g., coal, oil, gasThe fossil fuel consumed by the non-nuclear thermal generating units, e.g., coal, oil, gas
"""
def __init__(self, fuelSulfur=0.0, fuelCost=0.0, fossilFuelType="oil", lowBreakpointP=0.0, fu... |
sserrot/champion_relationships | venv/Lib/site-packages/win32/Demos/service/pipeTestServiceClient.py | Python | mit | 4,134 | 0.008224 | # A Test Program for pipeTestService.py
#
# Install and start the Pipe Test service, then run this test
# either from the same machine, or from another using the "-s" param.
#
# Eg: pipeTestServiceClient.py -s server_name Hi There
# Should work.
from win32pipe import *
from win32file import *
from win32event import *
... | ze, len(data)))
def stressThread(server, numMessages, wait):
| try:
try:
for i in range(numMessages):
r = CallPipe(CallNamedPipe, ("\\\\%s\\pipe\\PyPipeTest" % server, "#" * 512, 1024, NMPWAIT_WAIT_FOREVER))
except:
traceback.print_exc()
print("Failed after %d messages" % i)
finally:
SetEvent(wait)... |
abilian/abilian-core | demo/config.py | Python | lgpl-2.1 | 1,105 | 0 | class Config:
# specific (for this development instance)
# SERVER_NAME = 'localhost:5000'
SQLALCHEMY_DATABASE_URI = "sqlite:///data.db"
ANTIVIRUS_CHECK_REQUIRED = False
SECRET_KEY = "toto"
# develop settings
DEBUG = True
ASSETS_DEBUG = True
DEBUG_TB_ENABLED = True
# TEMPLATE_DEB... | S_EXCEPTIONS = True
# uncomment if you don't want to use system timez | one
# CELERY_TIMEZONE = 'Europe/Paris'
|
f-prettyland/angr | angr/sim_state.py | Python | bsd-2-clause | 30,608 | 0.003921 | #!/usr/bin/env python
import functools
import itertools
import contextlib
import weakref
import logging
l = logging.getLogger("angr.sim_state")
import claripy
import ana
from archinfo import arch_from_id
from .misc.ux import deprecated
def arch_overrideable(f):
@functools.wraps(f)
def wrapped_f(self, *args,... | lverModeError):
ip_str = repr(self.regs.ip)
return "<SimState @ %s>" % ip_str
#
# Easier access to some properties
#
@property
def ip(self):
"""
Get the instruction pointer expression, tri | gger SimInspect breakpoints, and generate SimActions.
Use ``_ip`` to not trigger breakpoints or generate actions.
:return: an expression
"""
return self.regs.ip
@ip.setter
def ip(self, val):
self.regs.ip = val
@property
def _ip(self):
"""
Get th... |
addgene/research | toolkit/parameters.py | Python | gpl-3.0 | 2,405 | 0.003742 | ########## recombination.py parameters
class Recombination_Parameters(object):
# Change these two values to the folders you prefer - use an absolute path e.g. /Users/Harry/fastq-data and
# /Users/Harry/csv-data or a path relative to the tools directory.
# You may use the same folder for input and output.
... | AIL = 10
seed_sequences = {
"loxP": "ATAACTTCGTATAGCATACATTATAC | GAAGTTAT",
"lox2272": "ATAACTTCGTATAGGATACTTTATACGAAGTTAT",
}
########## serotypes.py parameters
class Serotypes_Parameters(object):
# Change these two values to the folders you prefer - use an absolute path e.g. /Users/Harry/fastq-data and
# /Users/Harry/csv-data or a path relative to the tools... |
frreiss/tensorflow-fred | tensorflow/python/eager/benchmarks/resnet50/resnet50_test.py | Python | apache-2.0 | 16,160 | 0.008168 | # Copyright 2017 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... | 'block0 | mp': (2, 64, 55, 55),
'block1': (2, 256, 55, 55),
'block2': (2, 512, 28, 28),
'block3': (2, 1024, 7, 7),
'block4': (2, 2048, 1, 1),
}
else:
block_shapes = {
'block0': (2, 112, 112, 64),
'block0mp': (2, 55, 55, 64),
'block1': (2, 55, 5... |
snsokolov/contests | codeforces/574A_bear.py | Python | unlicense | 2,847 | 0.000702 | #!/usr/bin/env python3
# 574A_bear.py - Codeforces.com/problemset/problem/574/A Bear program by Sergey 2015
import unittest
import sys
###############################################################################
# Bear Class
###############################################################################
class Be... | # Sample test
test = "2\n7 6"
self.assertEqual(Bear(test).calculate(), "0")
# My tests
test = "4\n0 1 1 1"
self.assertEqual(Bear(test).calculate(), "2")
# Time limit test
self.time_limit_test(100)
def time_limit_test(self, nmax):
""" Timelim... | puts
test = str(nmax) + "\n"
test += "0 "
nums = [1000 for i in range(nmax-1)]
test += " ".join(map(str, nums)) + "\n"
# Run the test
start = timeit.default_timer()
d = Bear(test)
calc = timeit.default_timer()
d.calculate()
stop = timeit.d... |
gentoo/webapp-config | WebappConfig/ebuild.py | Python | gpl-2.0 | 6,937 | 0.010379 | #!/usr/bin/python -O
#
# /usr/sbin/webapp-config
# Python script for managing the deployment of web-based
# applications
#
# Originally written for the Gentoo Linux distribution
#
# Copyright (c) 1999-2007 Authors
# Released under v2 of the GNU GPL
#
# Author(s) Stuart Herbert
# ... | def show_post(self, filename, ptype, server = None):
| '''
Display one of the post files.
'''
post_file = self.__sourced + '/' + filename
OUT.debug('Check for instruction file', 7)
if not os.path.isfile(post_file):
return
self.run_vars(server)
post_instructions = open(post_file).readlines()
... |
capybaralet/Sequential-Generation | TestImpGPSI_MNIST.py | Python | mit | 18,331 | 0.004582 | ##################################################################
# Code for testing the variational Multi-Stage Generative Model. #
##################################################################
# basic python
import numpy as np
import numpy.random as npr
import cPickle
# theano business
import theano
import th... | ts=None)
p_sip1_given_zi.init_biases(0.0)
################
# p_x_given_si #
################
params = {}
shared_config = [s_dim]
output_config = [x_dim, x_dim]
params['shared_config'] = shared_config
params['output_config'] = output_config
params['activation'] = relu_actfun
p... | .0
params['build_theano_funcs'] = False
p_x_given_si = HydraNet(rng=rng, Xd=x_in_sym, \
params=params, shared_param_dicts=None)
p_x_given_si.init_biases(0.0)
#################
# q_zi_given_xi #
#################
params = {}
shared_config = [(x_dim + x_dim), 500, 500]
top_... |
adamcharnock/django-hordak | hordak/migrations/0008_auto_20161209_0129.py | Python | mit | 353 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-09 01:29
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migr | ation):
dependencies = [("hordak", "0007_auto_20161209_0111")]
operations = [
migratio | ns.RenameField("Account", "has_statements", "is_bank_account")
]
|
sadolit/pafy | pafy.py | Python | gpl-3.0 | 8,660 | 0.000577 | #!/usr/bin/python
''' Python API for YouTube
Copyright (C) 2013 nagev
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... | ),
| '82': ('640x360-3D', 'mp4'),
'84': ('1280x720-3D', 'mp4'),
'100': ('640x360-3D', 'webm'),
'102': ('1280x720-3D', 'webm')}
def __init__(self, streammap, opener, title="ytvid"):
if not streammap.get("sig", ""):
streammap['sig'] = [_decrypt_signature(streammap['s'][0... |
makos/sshchan-oop | chan_mark.py | Python | gpl-3.0 | 1,058 | 0.004726 | """
Markup class allows the use of easy-to-write characters to style the text
instead of using escape codes.
==text== --> reverse video
'''text''' --> bold
~~text~~ --> strik | ethrough
Copyright (c) 2015
makos <https://github.com/makos>, chibi <http://neetco.de/chibi>
under GNU GPL v3, see LICENSE for details
"""
import re
class Marker():
def esc(self, input_text):
input_text = input_text.replace('\033', '\\033')
return input_text
def demarkify(self, input_text... | e.sub(
'~~(?P<substring>.*?)~~', '\033[0;9m\g<substring>\033[0m',
output_text)
# bold
output_text = re.sub(
'\'\'\'(?P<substring>.*?)\'\'\'', '\033[0;1m\g<substring>\033[0m',
output_text)
# rv
output_text = re.sub(
'==(?P<substr... |
nharsch/django-scheduler | schedule/feeds/atom.py | Python | bsd-3-clause | 22,525 | 0.002042 | from django.utils.six.moves.builtins import str
#
# django-atompub by James Tauber <http://jtauber.com/>
# http://code.google.com/p/django-atompub/
# An implementation of the Atom format and protocol for Django
#
# For instructions on how to use this module to generate Atom feeds,
# see http://code.google.com/p/django-... | ate.minute, date.second)
# based on django.utils.feedgenerator.get_tag_uri
def get_tag_uri(url, date):
"Creates a TagURI. See http://diveintomark.org/archives/2 | 004/05/28/howto-atom-id"
tag = re.sub('^http://', '', url)
if date is not None:
tag = re.sub('/', ',%s-%s-%s:/' % (date.year, date.month, date.day), tag, 1)
tag = re.sub('#', '/', tag)
return 'tag:' + tag
# based on django.contrib.syndication.feeds.Feed
class Feed(object):
VALIDATE = True... |
cgchemlab/chemlab | src/tests/test_topology_reader.py | Python | gpl-3.0 | 2,938 | 0.003744 | # Copyright (C) 2016
# Jakub Krajniak (jkrajniak at gmail.com)
#
# This file is part of ChemLab
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (... | chemlab.gromacs_topology
class TestTopologyReader(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.topol_file = 'topol.top'
cls.gt = chemlab.gromacs_topology.GromacsTopology(cls.topol_file, generate_exclusions=True)
cls.gt.read()
def test_replicated_molecules(self):
... | .gt.gt.molecules:
mol_atoms = len(self.gt.gt.molecules_data[mol_name]['atoms'])
expected_nr_atoms += nmols * mol_atoms
self.assertEqual(total_nr_atoms, expected_nr_atoms)
total_nr_bonds = len(self.gt.bonds)
expected_nr_bonds = 0
for mol_name, nmols in sel... |
samn/spectral-workbench | webserver/public/lib/bespin-0.9a2/lib/dryice/path.py | Python | gpl-3.0 | 33,721 | 0.000919 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | ur
# decis | ion by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
""" pa... |
lino-framework/xl | lino_xl/lib/humanlinks/__init__.py | Python | bsd-2-clause | 1,211 | 0.004129 | # Copyright 2014-2015 Rumma & Ko Ltd
#
# License: GN | U Affero General Public License v3 (see file COPYING for details)
"""Defines "parency links" between two "persons", and a user interface
to manage them.
This module is probably useful in combination with
:mod:`lino_xl.lib.households`.
.. autosummary::
:toctree:
choicelist | s
models
"""
from lino.api import ad, _
class Plugin(ad.Plugin):
"Extends :class:`lino.core.plugin.Plugin`."
verbose_name = _("Parency links")
## settings
person_model = 'contacts.Person'
"""
A string referring to the model which represents a human in your
application. Default valu... |
moehle/investor_lifespan_model | investor_lifespan_model/__init__.py | Python | mit | 282 | 0 | from investor_lifespan_model.investor import Investor
f | rom investor_lifespan_model.market import Market
from investor_lifespan_model.insurer import Insurer
from | investor_lifespan_model.lifespan_model import LifespanModel
from investor_lifespan_model.mortality_data import π, G, tf
|
ActiveState/code | recipes/Python/137551_Using_RegObj_Automatiaccess_MSW/recipe-137551.py | Python | mit | 1,024 | 0.03125 | RegObj.dll is an ActiveX server--and, hence, has an automation interface--that is available with documentation in
the distribution file known as RegObji.exe, from the following page:
http://msdn.microsoft.com/vbasic/downloads/addins.asp
To provide early binding for RegObj use
>>> from win32com.client impo... | om win32con import HKEY_CLASSES_ROOT
>>> gencache.EnsureModule('{DE10C540-810E-11CF-BBE7-444553540000}', 0, 1, 0)
>>> regobj = Dispatch ( 'RegObj.Registry' )
>>> HKCR = regobj.RegKeyFromHKey ( HKEY_CLASSES_ROOT )
>>> PythonFileKey = HKCR.ParseKeyName('Python.File\Shell\Open\command')
>>> PythonFileKey.Value
u'J:\\P... | '
|
VitalPet/c2c-rd-addons | hr_timesheet_product/__openerp__.py | Python | agpl-3.0 | 1,555 | 0.020579 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2012 ChriCar Beteiligungs- und Beratungs- Gm | bH (<http://www.camptocamp.at>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program... | t will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. ... |
slaweet/autoskola | main/geography/management/commands/add_places.py | Python | mit | 985 | 0.00203 | from django.core.management.base import BaseCommand, CommandError
from geography.models import Place
class Command(BaseCommand):
help = u"""Add new places"""
usage_str = 'USAGE: ./manage.py a | dd_places map_name STATE|CITY|RIVER|LAKE|... [difficulty]'
def handle(self, *args, **options):
if len(args) < 2:
raise CommandError(self.usage_str)
if not args[1] in Place.PLACE_TYPE_SLUGS:
ra | ise CommandError(self.usage_str)
place_type = self.Place.PLACE_TYPE_SLUGS[args[1]]
map_name = args[0]
state_file = open(map_name.lower() + ".txt")
states = state_file.read()
ss = states.split("\n")
for s in ss:
place = s.split("\t")
if(len(place) =... |
floemker/django-wiki | src/wiki/plugins/notifications/migrations/0001_initial.py | Python | gpl-3.0 | 881 | 0.00227 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_nyt', '0006_auto_20141229_1630'),
('wiki', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ArticleSubscription',
fields=[
... | ('subscription', models.OneToOneField(to='django_nyt.Subscription', on_delete=models.CASCADE)),
],
options={
},
bases=('wiki.articleplugin',),
),
migrations.AlterUniqueTogether(
name='articlesubscription',
unique_together=set([('sub... | 'articleplugin_ptr')]),
),
]
|
Smart-Torvy/torvy-home-assistant | homeassistant/components/cover/vera.py | Python | mit | 1,970 | 0 | """
Support for Vera cover - curtains, rollershutters etc.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.vera/
"""
import logging
from homeassistant.components.cover import CoverDevice
from homeassistant.components.vera import (
VeraDevice, V... | lf.current_cover_position > 0:
return False
else:
return True
def open_cover(self, **kwargs):
"""Open the cover."""
self.vera_device.open()
def close_cover(self, **kwargs):
"""Close the cover."""
self.vera_device.close()
def stop... | ice.stop()
|
702nADOS/sumo | tools/assign/costMemory.py | Python | gpl-3.0 | 7,283 | 0.00151 | # -*- coding: utf-8 -*-
"""
@file costMemory.py
@author Jakob Erdmann
@author Michael Behrisch
@date 2012-03-14
@version $Id: costMemory.py 22608 2017-01-17 06:28:54Z behrisch $
Perform smoothing of edge costs across successive iterations of duaIterate
SUMO, Simulation of Urban MObility; see http://sumo.dlr.d... | y = self.current_interval[id]
self.errors.append(edgeMemory.cost - cost)
edgeMemory.update(
cost, self.memory_weight, self.new_weight, self.pessimism)
# if id == "4.3to4.4":
# with open('debuglog', 'a') as f:
... | f.current_interval[id] = EdgeMemory(cost)
def load_costs(self, dumpfile, iteration, weight):
# load costs from dumpfile and update memory according to weight and
# iteration
if weight <= 0:
sys.stderr.write(
"Skipped loading of costs because the weight was %s but... |
Ledoux/ShareYourSystem | Pythonlogy/ShareYourSystem/Standards/Tutorials/Sumer/Test.py | Python | mit | 388 | 0.025773 | #<ImportSpecificModules>
import Shar | eYourSystem as SYS
#</ImportSpecificModules>
#print(SYS.SumClass().insert('Parameter').hdfview().HdformatedConsoleStr)
#print(SYS.SumClass().insert('Result').hdfview().HdformatedConsoleStr)
#print(SYS.Sum.attest_insert())
#print(SYS | .Sum.attest_retrieve())
#print(SYS.Sum.attest_find())
#print(SYS.Sum.attest_recover())
#print(SYS.Sum.attest_scan())
|
Digilent/u-boot-digilent | tools/dtoc/test_dtoc.py | Python | gpl-2.0 | 28,025 | 0.000178 | #!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2012 The Chromium OS Authors.
#
"""Tests for the dtb_platdata module
This includes unit tests for some functions and functional tests for the dtoc
tool.
"""
import collections
import os
import struct
import sys
import tempfile
import unittest... | l((['rockchip_rk3399_sdhci_5_1',
'arasan_sdhci_5_1', 'third']),
get_compat_name(node))
def test_empty_file(self):
"""Test output from a device tree file with no nodes"""
dtb_file = get_dtb_file('dtoc_test_empty.dts')
output = tools.GetOutpu... | = infile.read().splitlines()
self.assertEqual(HEADER.splitlines(), lines)
self.run_test(['platdata'], dtb_file, output)
with open(output) as infile:
lines = infile.read().splitlines()
self.assertEqual(C_HEADER.splitlines() + [''] +
C_EMPTY_POPULATE_... |
monikagrabowska/osf.io | kinto/tests/test_config.py | Python | apache-2.0 | 6,371 | 0 | import codecs
import mock
import os
import tempfile
import unittest
from time import strftime
import six
from kinto import config
from kinto import __version__
class ConfigTest(unittest.TestCase):
def test_transpose_parameters_into_template(self):
self.maxDiff = None
template = "kinto.tpl"
... | 'cache_url': redis_url + '/2',
'permission_url': redis_url + '/3',
'kinto_version': __version__,
'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z')
})
@mock.patch('kinto.config.render_template')
def test_init_memory_values(self, mocked_render_t... | self.assertDictEqual(kwargs, {
'secret': kwargs['secret'],
'storage_backend': 'kinto.core.storage.memory',
'cache_backend': 'kinto.core.cache.memory',
'permission_backend': 'kinto.core.permission.memory',
'storage_url': '',
'cache_url': '',
... |
shenfei/oj_codes | leetcode/python/n85_Maximal_Rectangle.py | Python | mit | 1,123 | 0.001781 |
def max_rectangle(heights):
res = 0
heights.append(0)
stack = [0]
for i in range(1, len(heights)):
while stack and heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i if not stack else i - stack[-1] - 1
res = max(res, h * w)
stack.append(i... | n matrix[0]]
ans = max_rectangle(heights)
for i in range(1, m):
for j in range(n):
heights[j] = 0 if matrix[i][j] == '0' else heights[j] + 1
ans = max(ans, max_rectangle(heights))
return ans
if __name__ == "__main__":
sol = Solution()
M = [['1', '... | '],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']]
print(sol.maximalRectangle(M))
|
Alignak-monitoring-contrib/alignak-checks-nrpe | alignak_checks_nrpe/__init__.py | Python | agpl-3.0 | 200 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
| # Frederic Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Checks pack for NRPE monitored Linux hosts/services
"" | "
|
puttarajubr/commcare-hq | custom/tdh/sqldata.py | Python | bsd-3-clause | 25,506 | 0.004822 | from sqlagg.columns import SimpleColumn
from sqlagg.filters import BETWEEN, IN, EQ
from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn
from corehq.apps.reports.sqlreport import SqlData, DataFormatter, TableDataFormat, DatabaseColumn
from custom.tdh.reports import UNNECESSARY_FIELDS, CHILD_HEAD... | tory'
title = 'Newborn Consultation History'
@property
def columns(self):
return EnrollChild().columns + NewbornClassification(
config=self.config).columns + NewbornTreatment().columns
@property
def headers(self):
return DataTablesHeader(*EnrollChild().headers + Newborn... | return EnrollChild().group_by + NewbornClassification(
config=self.config).group_by + NewbornTreatment().group_by
@property
def rows(self):
return merge_rows(NewbornClassification(config=self.config), EnrollChild(), NewbornTreatment())
class NewbornConsultationHistoryComplete(BaseSq... |
RoyNexus/python | homework6.py | Python | unlicense | 3,193 | 0.003758 | import numpy as np
import copy
import datetime as dt
import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.DataAccess as da
import QSTK.qstkstudy.EventProfiler as ep
from bollinger import Bollinger
"""
Accepts a list of symbols along with start and end date
Returns the Event Matrix which is a pandas Datamatrix
E... | filer(df_events, d_data, i_lookback=20, i_lookforward=20,
| s_filename='BollingerStudy.pdf', b_market_neutral=True, b_errorbars=True,
s_market_sym='SPY')
|
matthew-brett/pyblio | Pyblio/Style/Generic.py | Python | gpl-2.0 | 5,843 | 0.023105 | # This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# 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 t... | table)
table [s] = key
skeys.append (s)
return table, skeys
def standard_date (entry, coding):
(text, month, day) = entry.format (coding)
if month: text = "%s/%s" % (month, text)
if day : text = "%s/%s" % (day, text)
return text
def last_first_full_authors (entry, co... |
def first_last_full_authors (entry, coding):
return author_desc (entry, coding, 0, -1)
def full_authors (entry, coding):
return author_desc (entry, coding, 0, 0)
def initials_authors (entry, coding):
return author_desc (entry, coding, 1, 0)
def first_last_initials_authors (entry, coding):
return a... |
FOSSEE/eSim | src/frontEnd/DockArea.py | Python | gpl-3.0 | 13,847 | 0 | from PyQt5 import QtCore, QtWidgets
from ngspiceSimulation.pythonPlotting import plotWindow
from ngspiceSimulation.NgspiceWidget import NgspiceWidget
from configuration.Appconfig import Appconfig
from modelEditor.ModelEditor import ModelEditorclass
from subcircuit.Subcircuit import Subcircuit
from maker.makerchip impor... | or.
- Python Plotting.
- Ngspice Editor.
- Kicad to Ngspice Editor.
- Subcircuit Editor.
- Modelica editor.
"""
def __init__(self):
"""This act as constructor for class DockArea."""
QtWidgets.QMainWindow.__init__(self)
self.obj_appconfig = Appconf... | self.welcomeWidget = QtWidgets.QWidget()
self.welcomeLayout = QtWidgets.QVBoxLayout()
self.welcomeLayout.addWidget(Welcome()) # Call browser
# Adding to main Layout
self.welcomeWidget.setLayout(self.welcomeLayout)
dock[dockName].setWidget(self.welcomeWid... |
ismailsunni/inasafe | safe/gis/vector/union.py | Python | gpl-3.0 | 12,362 | 0 | # coding=utf-8
"""Clip and mask a hazard layer."""
import logging
from qgis.core import (
QgsGeometry,
QgsFeatureRequest,
QgsWkbTypes,
QgsFeature,
)
from safe.definitions.fields import hazard_class_field, aggregation_id_field
from safe.definitions.hazard_classifications import not_exposed_class
from... | ored due to '
'invalid geometry.'))
# the remaining bit of inFeatA's geometry
# if there is nothing left, this will just silently fail and we
# are good
diff_geom = QgsGeometry(geom)
if len(list_intersecting_b) != 0:
... | one or \
diff_geom.isEmpty() or not diff_geom.isGeosValid():
# LOGGER.debug(
# tr('GEOS geoprocessing error: One or more input '
# 'features have invalid geometry.'))
pass
if diff_geom is not ... |
cwlinkem/linkuce | modeltest_runner.py | Python | gpl-2.0 | 2,993 | 0.033077 | import os
import glob
import subprocess
def expand_path(path):
return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
def is_file(path):
if not path:
return False
if not os.path.isfile(path):
return False
return True
def arg_is_file(path):
try:
if not is_file(path):
raise
... | mary using flags. The standard 24 models used'
'in MrBayes and BIC summary with 95% credible set are defaults.')
FILE_FORMATS = ['ne | x']
parser = argparse.ArgumentParser(description = description)
parser.add_argument('input_files', metavar='INPUT-SEQ-FILE',
nargs = '+',
type = arg_is_file,
help = ('Input sequence file(s) name '))
parser.add_argument('-o', '--out-format',
type = str,
choices = ['nex', 'fasta', 'phy'],
help = ('The form... |
renebentes/Python4Zumbis | Exercícios/Lista IV/questao01.py | Python | mit | 350 | 0 | # coding=utf-8
impo | rt random
lista = []
for x in range(10):
numero = random.randint(1, 100)
if x == 0:
maior, menor = numero, numero
elif numero > maior:
maior = numero
elif numero < menor:
menor = numero
lista.append(numero)
lista.sort()
print(lista)
print("Maior: %d" % | maior)
print("Menor: %d" % menor)
|
centrologic/django-codenerix-products | codenerix_products/migrations/0012_productunique_caducity.py | Python | apache-2.0 | 516 | 0.001938 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-04-26 12:20
from | __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('codenerix_products', '0011_auto_20180202_0826'),
]
operations = [
migrations.AddField(
| model_name='productunique',
name='caducity',
field=models.DateField(blank=True, default=None, null=True, verbose_name='Caducity'),
),
]
|
gistic/PublicSpatialImpala | tests/benchmark/report-benchmark-results.py | Python | apache-2.0 | 35,471 | 0.013307 | #!/usr/bin/env python
# Copyright (c) 2014 Cloudera, Inc. All rights reserved.
#
# This script provides help with parsing and reporting of perf results. It currently
# provides three main capabilities:
# 1) Printing perf results to console in 'pretty' format
# 2) Comparing two perf result sets together and displaying c... | ies
"""
def add_result(query_result):
"""Add query to the dictionary.
Automatically finds the path in the nested dictionary and adds the result to the
appropriate list.
TODO: This method is hard to reason about, so it needs to be made more streamlined.
"""
def get_key(level_num):
"... | "Build a key for a particular nesting level.
The key is built by extracting the appropriate values from query_result.
"""
level = list()
# In the outer layer, we group by workload name and scale factor
level.append([('query', 'workload_name'), ('query', 'scale_factor')])
# In the m... |
mdrumond/tensorflow | tensorflow/contrib/eager/python/network_test.py | Python | apache-2.0 | 3,454 | 0.002606 | # Copyright 2017 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... | S" 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future... |
thelabnyc/django-oscar-wfrs | src/wellsfargo/connector/client.py | Python | isc | 6,228 | 0.000963 | from datetime import timedelta
from requests.auth import HTTPBasicAuth
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.core.cache import cache
from ..settings import (
WFRS_GATEWAY_COMPANY_ID,
WFRS_GATEWAY_ENTITY_ID,
WFRS_GATEWAY_API_HOST,
WFRS_GATEWAY_CO... | j = encrypt_pickle(key_obj)
# Store it in Django's cache for later
cache.set(
self.cache_key, encrypted_obj, key_obj.ttl, version=self.cache_version
| )
def generate_api_key(self):
url = "https://{host}/token".format(host=self.api_host)
auth = HTTPBasicAuth(self.consumer_key, self.consumer_secret)
cert = (self.client_cert_path, self.priv_key_path)
req_data = {
"grant_type": "client_credentials",
"sco... |
PythonProgramming/Pandas-Basics-with-2.7 | pandas 8 - Standard Deviation.py | Python | mit | 486 | 0.010288 | import pandas | as pd
from pandas import DataFrame
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
#print df.head()
df['STD'] = pd.rolling_std(df['Close'], 25, min_periods=1)
ax1 = plt.subplot(2, 1, 1)
df['Close'].plot(... | Deviation')
plt.show()
|
camptocamp/QGIS | python/plugins/processing/ProcessingPlugin.py | Python | gpl-2.0 | 5,606 | 0.004281 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ProcessingPlugin.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... | f.configAction = QAction(QIcon(":/processing/images/config.png"),
QCoreApplication.translate("Processing", "Options and configuration"),
interface.iface.mainWindow())
self.configAction.triggered.connect(self.openConfig)
self.menu.addAction(self.configAction)
se | lf.resultsAction = QAction(QIcon(":/processing/images/results.png"),
QCoreApplication.translate("Processing", "&Results viewer"),
interface.iface.mainWindow())
self.resultsAction.triggered.connect(self.openResults)
self.menu.addAction(self.resultsAction)
menuBar = interf... |
zhaogaolong/oneFinger | alarm/admin.py | Python | apache-2.0 | 150 | 0 | from django.contrib import admi | n
import models
# Register your models here.
admin.site.register(models.UserProfile)
admin.site | .register(models.Event)
|
dotmanila/pyxbackup | tests/all_test.py | Python | gpl-2.0 | 835 | 0.019162 | #!/usr/bin/python
import sys
import pyxbackup as pxb
import pytest
def test__parse_port_param():
assert(pxb._parse_port_param('27017,27019')) == True
assert(pxb.xb_opt_remote_nc_port_min) == 27017
assert(pxb.xb_opt_remote_nc_port_max) == 27019
assert(pxb._parse_port_param('27017, 27019')) == True
... | am('abcde, ')) == False
assert(pxb._parse_port_param('9999, ')) == False
assert(pxb._parse_port_param('9999 ')) == False
assert(pxb._parse_port_param('9999')) == True
assert(pxb.xb_opt_remote_nc_port_min) == 9999
assert(pxb.xb_opt_remote_nc_port_max) == 9999
def test__xb_version():
assert(pxb._... | t(pxb._xb_version(verstr = '2.2.13', tof = True)) == 2.2 |
sileht/pifpaf | pifpaf/drivers/ceph.py | Python | apache-2.0 | 5,134 | 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... | if version < pkg_resources.parse_version("0.94.0"):
wait_for_line = "journal close"
else:
wait_for_line = "done with init"
osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line)
if version >= pkg_resources.parse_version("12.0.0"):
self._exec(ceph_op... | s + ["osd", "set-backfillfull-ratio", "0.95"])
self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"])
# Wait it's ready
out = b""
while b"HEALTH_OK" not in out:
ceph, out = self._exec(ceph_opts + ["health"], stdout=True)
if b"HEALTH_ERR" in out:
... |
codemedic/retext | retext.py | Python | gpl-3.0 | 1,988 | 0.017606 | #!/usr/bin/env python3
# ReText
# | Copyright 2011-2012 Dmitry Shachnev
# 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) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR... |
SKIRT/PTS | modeling/build/construct.py | Python | agpl-3.0 | 25,266 | 0.00661 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | ion"]
# Component with MAPPINGS template (geometry defined above)
elif "sfr" in component.parameters: #set_stellar_component_mappings(ski, component)
# Set template for MAPPINGS
sed_template = | "Mappings"
# Get SED properties
metallicity = component.parameters.metallicity
compactness = component.parameters.compactness
pressure = component.parameters.pressure
covering_factor = component.parameters.covering_factor
# Get normalization
... |
insiderr/insiderr-app | app/modules/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py | Python | gpl-3.0 | 19,942 | 0.001254 | # -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749.grant_types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import unicode_literals, absolute_import
import json
import logging
from modules.oauthlib import common
from modules.oauthlib.uri_validate import is_absolute_uri
from .base import GrantTypeBase
fr... | User- | | Authorization |
| Agent -+----(B)-- User authenticates --->| Server |
| | | |
| -+----(C)-- Authorization Code ---<| |
+-|----|---+ ... | C) | |
| | | |
^ v | |
+---------+ | |
| |>---(D)-- Authorization Code ---------' |
... |
andreas-koukorinis/ambhas | ambhas/amsr2.py | Python | lgpl-2.1 | 3,408 | 0.010857 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 11:30:24 2013
@author: Sat Kumar Tomer
@email: satkumartomer@gmail.com
@website: www.ambhas.com
"""
import numpy as np
import h5py
import os
import datetime as dt
def extract_smc(h5_file, lat, lon):
"""
Extract Soil Moisture Content fro... | , '%Y%m%d'))
return h5_dates
def extract_orbit(h5_file):
asc = []
for h5_f in h5_file:
f = h5py.File(h5_f, "r")
if f.attrs['OrbitDirection'][0] == 'Ascending':
asc.append(True)
elif f.attrs['OrbitDirection'][0] == 'Descending':
asc.append(False)
else... | n asc
if __name__ == "__main__":
import glob
h5_file = '/home/tomer/amsr2/data/h5/GW1AM2_20130722_01D_EQMD_L3SGSMCHA1100100.h5'
h5_file = glob.glob('/home/tomer/amsr2/data/h5/GW1AM2_201?????_01D*.h5')
h5_file.sort()
h5_file = h5_file[:5]
lat = [8, 38]
lon = [68, 98]
sm = extract_smc(h... |
open-power-ref-design/opsmgr | plugins/devices/powernode/opsmgr/plugins/devices/powernode/PowerNodePlugin.py | Python | apache-2.0 | 5,846 | 0.002737 | # Copyright 2016, IBM US, 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... | clude_name=["self"])
def get_architecture(self):
return None
@entry_exit(exclude_index=[0, 1], exclude_name=["self", "new_password"])
def change_device_password(self, new_password):
"""Update the password of the ipmi default user on the BMC of the openpower server.
"""
_meth... | r()
cmd_parms = [self.IPMI_TOOL, "-I", "lanplus", "-H", self.host, "-U", self.userid,
"-P", self.password, "user", "set", "password", user_number, new_password]
(rc, _stdout, stderr) = execute_command(" ".join(cmd_parms))
if rc != 0:
logging.error("%s::ipmi passw... |
matty-jones/MorphCT | morphct/definitions.py | Python | gpl-3.0 | 419 | 0.002387 | import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEST_ROOT = os.path.join(os.path.dirname(PR | OJECT_ROOT), "tests")
SINGLE_ORCA_RUN_FILE = os.path.join(PROJECT_ROOT, "code", "single_core_run_orca.py")
SINGLE_RUN_MOB_KMC_FILE = os.path.join(
PROJECT_ROOT, "code", "single_core_run_ | mob_KMC.py"
)
SINGLE_RUN_DEVICE_KMC_FILE = os.path.join(
PROJECT_ROOT, "code", "single_core_run_device_KMC.py"
)
|
lukleh/TwistedBot | twistedbot/botentity.py | Python | mit | 16,437 | 0.000973 |
import math
import config
import utils
import packets
import logbot
import fops
import blocks
import behavior_tree as bt
from axisbox import AABB
log = logbot.getlogger("BOT_ENTITY")
class BotObject(object):
def __init__(self):
self.velocities = utils.Vector(0.0, 0.0, 0.0)
self.direction = ut... | al
self._action = self.action
self.is_jumping = False
self.hold_position_flag = True
def set_xyz(self, x, y, z):
self._x = x
self._y = y
self._z = z
self._aabb = AABB.from_player_coords(self.position)
@property
def x(self):
return self._x
... | elf.z)
@property
def position_grid(self):
return utils.Vector(self.grid_x, self.grid_y, self.grid_z)
@property
def position_eyelevel(self):
return utils.Vector(self.x, self.y_eyelevel, self.z)
@property
def y_eyelevel(self):
return self.y + config.PLAYER_EYELEVEL
... |
npalko/uRPC | python/urpc/__init__.py | Python | bsd-3-clause | 78 | 0.012821 | import Decimal_pb2
import Log_pb2
import uRPC_pb2
import client
impo | rt | server |
maurodoglio/taar | tests/test_hybrid_recommender.py | Python | mpl-2.0 | 3,508 | 0.000285 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Test cases for the TAAR Hybrid recommender
"""
from taar.recommenders.hybrid_recommender import CuratedRecommender
... | )
conn.Object(TAAR_WHITELIST_BUCKET, TAAR_WHITELIST_KEY).put(
Body=json.dumps(mock_data)
)
return ctx
def install_ensemble_fixtures(ctx):
ctx = install_mock_ensemble_data(ctx)
factory = MockRecommenderFactory()
ctx["recommender_factory"] = factory
ctx["recommender_map"] = {
... | borative": factory.create("collaborative"),
"similarity": factory.create("similarity"),
"locale": factory.create("locale"),
}
ctx["ensemble_recommender"] = EnsembleRecommender(ctx.child())
return ctx
@mock_s3
def test_curated_can_recommend(test_ctx):
ctx = install_no_curated_data(test_... |
cathywu/flow | tests/slow_tests/test_baselines.py | Python | mit | 2,809 | 0 | import unittest
import os
from flow.benchmarks.baselines.bottleneck0 import bottleneck0_baseline
from flow.benchmarks.baselines.bottleneck1 import bottleneck1_baseline
from flow.benchmarks.baselines.bottleneck2 import bottleneck2_baseline
from flow.benchmarks.baselines.figureeight012 import figure_eight_baseline
from ... | leneck0_baseli | ne(num_runs=1, render=False)
# TODO: check that the performance measure is within some range
def test_bottleneck1(self):
"""
Tests flow/benchmark/baselines/bottleneck1.py
"""
# run the bottleneck to make sure it runs
bottleneck1_baseline(num_runs=1, render=False)
... |
h2020-westlife-eu/VRE | api/migrations/0010_auto_20160121_1536.py | Python | mit | 4,758 | 0.002102 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0009_dummyprovider'),
]
o... | },
),
migrations.CreateModel(
name='ExternalJobPortalSubmissionStateChange',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('created_at', models.DateTimeField(auto_now_add=True... | (max_length=256, choices=[(b'EXTERNAL_SUBMISSION_RUNNING', b'Running'), (b'EXTERNAL_SUBMISSION_FAILED', b'FAILED'), (b'EXTERNAL_SUBMISSION_PENDING', b'Pending'), (b'EXTERNAL_SUBMISSION_PENDING_SUBMISSION', b'Submission in progress'), (b'EXTERNAL_SUBMISSION_SUCCESS', b'Succeeded')])),
('external_submissi... |
github/codeql | python/ql/test/3/query-tests/Classes/equals-hash/equals_hash.py | Python | mit | 1,147 | 0.012206 | #Equals and hash
class Eq(object):
def __init__(self, data):
self.data = data
def __eq__(self, other):
return self.data == other.data
class Ne(object):
def __init__(self, data):
self.data = data
def __ne__(self, other):
return self.data != other.data
class Hash(obj... | bject):
__hash__ = None
class EqOK1(Unhashable1) | :
def __eq__(self, other):
return False
def __ne__(self, other):
return True
class Unhashable2(object):
#Not the idiomatic way of doing it, but not uncommon either
def __hash__(self):
raise TypeError("unhashable object")
class EqOK2(Unhashable2):
def __eq__... |
pferreir/indico-backup | bin/utils/db_log.py | Python | gpl-3.0 | 5,979 | 0.004014 | # -*- coding: utf-8 -*-
# #
# #
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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; ei... | p()
def prettify_params(args):
args = pprint.pformat(args)
return indent(highlight(args, PythonLexer(), Terminal256Formatter(style='native'))).rstrip()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-p', dest='port', type=int, default=logging.handlers.DE | FAULT_TCP_LOGGING_PORT,
help='The port to bind the UDP listener to')
parser.add_argument('-t', dest='traceback_frames', type=int, default=1,
help='Number of stack frames to show (max. 3)')
parser.add_argument('--setup-help', action='store_true', help='Explain how ... |
nagyistoce/devide.johannes | install_packages/ip_vtk58.py | Python | bsd-3-clause | 9,776 | 0.004603 | # Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import config
from install_package import InstallPackage
import os
import re
import shutil
import sys
import utils
BASENAME = "VTK"
GIT_REPO = "http://vtk.org/VTK.git"
GIT_TAG = "v5.8.0"
VTK_BASE_VERSION = "vtk-5.8"
# this... | RAP_PYTHON=ON " % (self.inst_dir,
config.PYTHON_EXECUTABLE,
config.PYTHON_LIBRARY,
config.PYTHON_INCLUDE_PATH)
ret = utils.cmake_command(self.build_dir, self.sourc | e_dir,
cmake_params)
if ret != 0:
utils.error("Could not configure VTK. Fix and try again.")
def build(self):
posix_file = os.path.join(self.build_dir,
'bin/libvtkWidgetsPython.so')
nt_file = os.path.join(self.build_dir, 'bin... |
rahulunair/nova | nova/tests/unit/virt/powervm/test_mgmt.py | Python | apache-2.0 | 7,781 | 0 | # Copyright 2015, 2018 IBM Corp.
#
# 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 require... | stically, first glob would return e.g. .../host0/.../host0/...
# but it doesn't matter for test purposes.
mock_glob.side_effect = [[scanpath], [devlink]]
mgmt.discover_vscsi_disk(mapping)
mock_glo | b.assert_has_calls(
[mock.call(scanpath), mock.call('/dev/disk/by-id/*' + udid[-32:])])
mock_writefile.assert_called_once_with(scanpath, 'a', '- - -')
mock_realpath.assert_called_with(devlink)
@mock.patch('retrying.retry', autospec=True)
@mock.patch('glob.glob', autospec=True)
@... |
tomeshnet/node-list | ci/scripts/kml/main.py | Python | gpl-3.0 | 3,457 | 0.001736 | # This file is formatted with black.
# https://github.com/psf/black
import os
import json
import subprocess
import sys
import simplekml
ALT_MODE = simplekml.AltitudeMode.absolute # Absolute altitude means from sea floor
# Current commit
if os.environ.get("TRAVIS"):
COMMIT = os.environ["TRAVIS_COMMIT"]
else:
... | d-pushpin.png"
pnt = folder.newpoint(
name=node["name"],
altitudemode=ALT_MODE,
coords=[(node["longitude"], node["latitude"], node["altitude"])],
| visibility=vis,
description=get_desc(node),
snippet=simplekml.Snippet(), # Empty snippet
)
pnt.style.iconstyle.icon.href = icon_url
kml.save("../../build/tomeshnet-node-list-kml.kml")
|
QEDK/AnkitBot | UAA/UAA.py | Python | epl-1.0 | 680 | 0.010294 | #! /usr/bin/python
import sys, localconfig, platform, time
#OS Runtime comments
if platform.system() == "Windows":
sys.path.append(localconfig.winpath)
| print "You are running the AnkitBot UAA Modu | le for Windows. Sponsored by DQ. :)"
else:
sys.path.append(localconfig.linuxpath)
print "You are running the AnkitBot UAA Module for Linux. Sponsored by DQ. :)"
import wikipedia
import globalfunc as globe
override = False
if not globe.startAllowed(override):
print "Fatal - System Access Denied."... |
oscaro/django | tests/template_tests/test_nodelist.py | Python | bsd-3-clause | 2,315 | 0.00216 | from unittest import TestCase
from django.template import Context, Template, VariableNode
from django.test import override_settings
class NodelistTest(TestCase):
def test_for(self):
template = Template('{% for i in 1 %}{{ a }}{% endfor %}')
vars = template.nodelist.get_nodes_by_type(VariableNode... | n five %}{% badsimpletag %}{% endfor %}{% endfor %}', (38, 57)),
('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)),
]
context = Context({
'range': range(5), |
'five': 5,
})
for source, expected_error_source_index in tests:
template = Template(source)
try:
template.render(context)
except (RuntimeError, TypeError) as e:
error_source_index = e.django_template_source[1]
... |
Alex-Ian-Hamilton/sunpy | sunpy/map/sources/tests/test_cor_source.py | Python | bsd-2-clause | 977 | 0.004094 | """Test cases for STEREO Map subclasses.
This particular test file pertains to CORMap.
@Author: Pritish C. (VaticanCameos)
"""
import os
import glob
from sunpy.map.sources.stereo import CORMap
from sunpy.map import Map
import sunpy.data.test
path = sunpy.data.test.rootdir
fitspath = glob.glob(os.path.join(path, "cor... | can be a MapMeta object."""
assert cor.is_datasource_for(cor.data, cor.meta)
def test_measurement():
"""Tests the measurement property of the CORMap object."""
assert cor.measurement == "white-l | ight"
def test_observatory():
"""Tests the observatory property of the CORMap object."""
assert cor.observatory == "STEREO A"
|
Sodki/ansible | lib/ansible/plugins/filter/core.py | Python | gpl-3.0 | 17,081 | 0.003396 | # (c) 2012, Jeroen Hoekx <jeroen@hoekx.be>
#
# This file is part of Ansible
#
# Ansible 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.... | tstring = "$%s$%s" % (cryptmethod[hashtype],salt)
encrypted = crypt.crypt(password, saltstring)
else:
if hashtype == 'b | lowfish':
cls = passlib.hash.bcrypt
else:
cls = getattr(passl |
thismachinechills/awful.py | awful.py | Python | gpl-3.0 | 1,950 | 0.004103 | from sa_tools.base.magic import MagicMixin
from sa_tools.inbox import Inbox
from sa_tools.session import SASession
from sa_tools.index import Index
import os
import pickle
import sys
def py_ver() -> str:
return str(sys.version_info.major)
class APSession(object):
def __init__(self, username: str, passwd: s... | def _get_session(self, save_session: bool=True) -> SASession:
backup_exists = os.path.exists(self._session_bak)
# session = None
if backup_exists:
session = self._load_session()
else:
session = SASession(self.username, self.p | asswd)
if save_session:
self._save_session(session)
return session
def _load_session(self) -> None:
with open(self._session_bak, 'rb') as old_session:
print("Loading from backup: " + self._session_bak)
session = pickle.load(old_session)
... |
orlandi/connectomicsPerspectivesPaper | participants_codes/aaagv/directivity.py | Python | mit | 2,853 | 0 | # Authors: Aaron Qiu <zqiu@ulg.ac.be>,
# Antonio Sutera <a.sutera@ulg.ac.be>,
# Arnaud Joly <a.joly@ulg.ac.be>,
# Gilles Louppe <g.louppe@ulg.ac.be>,
# Vincent Francois <v.francois@ulg.ac.be>
#
# License: BSD 3 clause
from __future__ import division, print_function, absolute_import
... | 0.4 * X[i - 3, j])
X_new = np.diff(X_new, axis=0)
thresh1 = X_new < threshold * 1
thresh2 = X_new >= threshold * 1
X_new[thresh1] = 0
X_new[thresh2] = pow(X_new[thresh2], 0.9)
# Score directivity
n_jobs, starts = _partition_X(X, n_jobs)
all_counts = Parallel(n_jo... | i + 1])
for i in range(n_jobs))
count = np.vstack(list(chain.from_iterable(all_counts)))
return scale(count - np.transpose(count))
|
lewischeng-ms/pox | pox/forwarding/l2_ofcommand_learning.py | Python | gpl-3.0 | 5,023 | 0.014334 | # Copyright 2011 Kyriakos Zarifis
# Copyright 2008 (C) Nicira, Inc.
#
# This file is part of POX.
#
# POX 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) ... | D the entry
# send/wait for Barrier
# sendBufferedPacket(bufid)
else:
# haven't learned destination MAC. Flood
ofcommand.floodPacket(con, inport, packet, b | uf, bufid)
'''
add arp cache timeout?
# Timeout for cached MAC entries
CACHE_TIMEOUT = 5
def timer_callback():
"""Responsible for timing out cache entries. Called every 1 second.
"""
global st
curtime = time()
for con in st.keys():
for entry in ... |
plotly/python-api | packages/python/plotly/plotly/validators/indicator/_delta.py | Python | mit | 1,527 | 0 | import _plotly_utils.basevalidators
class DeltaValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="delta", parent_name="indicator", **kwargs):
super(DeltaValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | ue to compute the delta.
| By default, it is set to the current value.
relative
Show relative change
valueformat
Sets the value formatting rule using d3
formatting mini-language which is similar to
those of Python. See
https://git... |
muccg/rdrf | rdrf/rdrf/migrations/0082_auto_20181106_1100.py | Python | agpl-3.0 | 461 | 0 | # -*- coding: utf-8 -*-
# Gen | erated by Django 1.10.8 on 2018-11-06 11:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rdrf', '0081_clinicaldata_active'),
]
operations = [
migrations.AlterField(
model_name='surv... | ,
),
]
|
CenterForOpenScience/modular-file-renderer | mfr/extensions/codepygments/render.py | Python | apache-2.0 | 3,749 | 0.0008 | import os
import chardet
from humanfriendly import format_size
import pygments
import pygments.lexers
import pygments.lexers.special
import pygments.formatters
from pygments.util import ClassNotFound
from mako.lookup import TemplateLookup
from mfr.core import extension
from mfr.extensions.codepygments import settings... | les larger than {} are not rendered. Please download '
'the file to view.'.format(format_size(settings.MAX_SIZE, binary=True)),
file_size=file_size,
max_size=settings.MAX_SIZE,
extension=self.metadata.ext,
)
with open(self.file_path, '... | self.TEMPLATE.render(base=self.assets_url, body=body)
@property
def file_required(self):
return True
@property
def cache_result(self):
return True
def _render_html(self, fp, ext, *args, **kwargs):
"""Generate an html representation of the file
:param fp: File point... |
ttitto/python | Basics/SampleExam/MostCommonCharacter/paint_bottles.py | Python | mit | 196 | 0.015306 | import sys
from math import ceil
de | f main():
AREA = 1.76
w = float(input())
h = flo | at(input())
print(ceil(w * h / AREA))
if __name__ == "__main__":
sys.exit(int(main() or 0)) |
potassco/clingo | examples/clingo/expansion/main.py | Python | mit | 3,702 | 0.006483 | #!/usr/bin/env python
import json
import sys
import argparse
from clingo import Control, Number
class App:
def __init__(self, args):
self.control = Control()
self.args = args
self.horizon = 0
self.objects = 0
self.end = None
def show(self, model):
if not s... | self.control.get_const("n").number
else:
self.end = self.args.maxobj
while self.objects < self.end:
self.ground(True)
while True:
ret = self.control.solve(on_model=self.show)
if self.args.stats:
args = {"s | ort_keys": True, "indent": 0, "separators": (',', ': ')}
stats = {}
for x in ["step", "enumerated", "time_cpu", "time_solve", "time_sat", "time_unsat", "time_total"]:
stats[x] = self.control.statistics[x]
for x in ["lp", "ctx", "solvers... |
inspirehep/inspire-dojson | inspire_dojson/cds/__init__.py | Python | gpl-3.0 | 1,112 | 0 | # -*- coding: utf-8 -*-
#
# This | file is part of INSPIRE.
# Copyright (C) 2014-2017 CERN.
#
# INSPIRE 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.
#
# INSPIRE 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 Gene... |
tahpee/detest | detest/detest/settings.py | Python | mit | 2,968 | 0.000337 | """
Django settings for detest project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login/'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'loggin... | neno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
},
'detest': {
'handlers... |
hackBCA/missioncontrol | application/mod_user/controllers.py | Python | mit | 3,822 | 0.026688 | from application import CONFIG, app
from .models import *
from flask import current_app, session
from flask.ext.login import login_user, logout_user, current_user
from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed
import bcrypt
import re
import sendgrid
i... | y_changed.send(current_app._get_current_object(), identity = AnonymousIdentity())
def tokenize_email(email):
return ts.dumps(email, salt = CONFIG["EMAIL_TOKENIZER_SALT"])
def detokenize_email(token):
return ts.loads(token, salt = CONFIG["EMAIL_TOKENIZER_SALT"], max_age = 86400)
def send_recovery_email(email):
u... | raise UserDoesNotExistError
token = tokenize_email(email)
message = sendgrid.Mail()
message.add_to(email)
message.set_from("noreply@hackbca.com")
message.set_subject("hackBCA III - Account Recovery")
message.set_html("<p></p>")
message.add_filter("templates", "enable", "1")
message.add_filter("templat... |
Emilv2/mandarinrecording | registration/apps.py | Python | agpl-3.0 | 107 | 0 | from django.apps import AppConfig |
class Userr | egistrationConfig(AppConfig):
name = 'userregistration'
|
aqisnotliquid/minder2 | app/murmur/views.py | Python | mit | 2,492 | 0.014045 | import utils
from flask import render_template, redirect, request, session, url_for, json, jsonify
from . import murmurbp
from .User import User
# User Views
@murmurbp.route("/users", methods = ['GET'])
def get_all_users():
u = User()
ul = utils.obj_to_dict(u.get_all())
data = [{'UserId': k, 'UserName': v... | ls", methods = ['POST'])
def add_channel():
c = Channel()
name = request.form['channelName']
parent = request.form['parent']
new_channel = c.add_channel(name, parent)
data = utils.obj_to_dict(new_channel)
resp = jsonify(data)
return resp | , 200
@murmurbp.route("/channels/<int:id>", methods = ['DELETE'])
def delete_channel(id):
c = Channel()
c.delete(id)
return jsonify(), 201
from .ACLGroup import ACL, Group
# ACL and Group Views
@murmurbp.route("/acls/<int:channel_id>", methods = ['GET'])
def get_all_acls(channel_id):
a = ACL()
d... |
carvalhomb/tsmells | src/viz/gui/TDockable.py | Python | gpl-2.0 | 1,659 | 0.007836 | #
# This file is part of TSmells
#
# TSmells 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) any later version.
#
# TSmells is distributed in the hope ... | tFrameBounds(self):
return Rectangle(50, 50, 300, 600)
def getDirectionPreference(self):
''' prefer vertical orientation '''
return 2 # vertical, see com.hp.hpl.guess.ui.MainUIWindow.java
def opening(self, state):
self.visible = state
def attaching(self, state):
pa... | w(self,gjf):
self.myParent = gjf
|
TheTimmy/spack | var/spack/repos/builtin/packages/py-wrapt/package.py | Python | lgpl-2.1 | 1,546 | 0.000647 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | s for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTI... |
nonZero/OpenCommunity | src/communities/legacy_mapping.py | Python | bsd-3-clause | 574 | 0.002227 | #encoding: utf-8
from __future__ import unicode_literals
TITLE_TO_SLUG = {
'איגוד הביטקוין': 'bitcoin-org-il',
'אליאב': 'eliav',
'* בדיקות פרודקשיין *': 'production-test',
'בי״ס עמית': 'amit',
'הבר קיימא': 'barkayma',
'הסדנא לידע ציבורי': 'hasadna',
'הפורום לממשל פתוח': 'open-government',
'התנועה לאיכות השלטון... | ': 'o | pen-community',
}
|
P1R/cinves | TrabajoFinal/tubo350cm/2-DbvsFreq/tubo2huecos/DbvsFreq-Ampde0.1v-2huequitos.py | Python | apache-2.0 | 511 | 0.078278 | #!/usr/bin/env python2.7
import numpy as np
import matplotlib.pyplot as plt
Freq=np.array([30,40,45,50,53,55,60,65,70,80,90,95,98,100,110,120])
Db=np.array([70.5,78.6,83.2,88.4,87.5,86. | 7,85.2,83.9,85.1,88,95.7,100.4,100.4,99.2,94.7,94.9])
plt.xlabel('Frecuencia')
plt.ylabel('Decibel')
plt.title('DecibelvsFreq a 0.1volts')
#for i in range(len(Freq)):
# | plt.text(Freq[i],Db[i], r'$Freq=%f, \ Db=%f$' % (Freq[i], Db[i]))
plt.axis([0, 330, 50, 130])
plt.plot(Freq,Db,'bo',Freq,Db,'k')
plt.grid(True)
plt.show()
|
ThisIsSoSteve/Project-Tensorflow-Cars | plot_course_data.py | Python | mit | 2,616 | 0.006116 | #import os
import pickle
import glob
#import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
#from data_control_no_images.read import Read
listing = glob.glob('F:/Project_Cars_Data/1lap-fullspeed/Watkins Glen International - Short Circuit' + '/*.pkl')
x = []
y = []
throttle = []
raw_throttle = []
... | .mParticipantInfo[0].mCurrentLapDistance == 0.0:
continue
position = project_cars_ | state.mParticipantInfo[0].mWorldPosition
x.append(round(position[0]))
y.append(round(position[2]))
throttle.append(controller_state['right_trigger']/255)# 0 - 255
brake.append(controller_state['left_trigger']/255) #0 - 255
steering.append(controller_state['thumb_lx']/32767) #-32... |
yugangzhang/chxanalys | chxanalys/chx_libs.py | Python | bsd-3-clause | 9,246 | 0.025741 | """
Dec 10, 2015 Developed by Y.G.@CHX
yuzhang@bnl.gov
This module is for the necessary packages for the XPCS analysis
"""
from IPython.core.magics.display import Javascript
from skbeam.core.utils import multi_tau_lags
from skimage.draw import line_aa, line, polygon, ellipse, circle
from modest_image import Modes... | $b$','$e$','$a$','$m$','$l$','$i$','$n$', '$e$',
'8', '1', '3', '2', '4', '+', 'x', '_', '|', ',', '1',]
markers = np.array( markers *100 )
markers = ['o', 'D', 'v', '^', '<', '>', 'p', 's', 'H',
| 'h', '*', 'd',
'8', '1', '3', '2', '4', '+', 'x', '_', '|', ',', '1',]
markers = np.array( markers *100 )
colors = np.array( ['darkorange', 'mediumturquoise', 'seashell', 'mediumaquamarine', 'darkblue',
'yellowgreen', 'mintcream', 'royalblue', 'springgreen', 'sl... |
yunhaowang/IDP-APA | utilities/py_idpapa_sam2gpd.py | Python | apache-2.0 | 3,045 | 0.042365 | #!/usr/bin/env python
import sys,re,time,argparse
def main(args):
# print >>sys.stdout, "Start analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S")
convert(args.input,args.output)
# print >>sys.stdout, "Finish analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S")
def extract_exon_length_from_cigar(cigar):
cigar_m = ["... | start site of alignment
6. end site of alignment
7. MAPQ
8. Number of nucleotides that are softly-clipped by aligner; left_right
9. exon count
10. exon start set
11. exon end set'''
parser = argparse.ArgumentParser(description="Function: convert sam to gpd.",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
p... | pe=argparse.FileType('w'),required=True,help="Output: gpd file")
args = parser.parse_args()
return args
if __name__=="__main__":
args = do_inputs()
main(args)
|
oscarcbr/cellery | cellery/ecp.py | Python | gpl-3.0 | 11,283 | 0.042808 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ecp.py part of cellery (ceRNAs linking inference)
#
# Copyright 2016 Oscar Bedoya Reina <obedoya@igmm-linux-005>
#
# 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
# th... | ,pntrCnts)).start()
lECPVlsAVlsBGlbl = []#store global results
for cnt in range(cntVlABPrs):
if cnt%50==0:
print 'Running calculations on pair %s out of %s'%(cnt, \
cntVlABPrs)
lECPVlsAVlsB = qOutRslts.get()
lECPVlsAVlsBGlbl.extend(lECPVlsAVlsB)
for t in xrange(nThrds):
qInJobs.put('STOP')
#----------... |
#~ create array: aMrnVlsDtA in rows, aMrnVlsDtB in columns.
for vlsAPos,vlsBPos,ECP in lECPVlsAVlsBGlbl:
aECPVlsAVlsB[vlsAPos,vlsBPos] = ECP
if sqlFl:
mkSqlFlECP(lECPVlsAVlsBGlbl,sqlFl,aANmsA,aANmsB)
return aECPVlsAVlsB
########################################################
#~ Make a sqlite3 database for E... |
alexforencich/verilog-ethernet | tb/test_ptp_clock_cdc_64.py | Python | mit | 5,957 | 0.000671 | #!/usr/bin/env python
"""
Copyright (c) 2019 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merg... | ABLE 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.
"""
from myhdl import *
import os
import ptp
module = 'ptp_clock_cdc'
testbench = 'test_%s_64' % module
srcs = []
srcs.append("../rtl/%s.v" % ... |
ezarowny/url-condenser | url_condenser/condensed_urls/migrations/0002_condensedurl_visited_count.py | Python | mit | 456 | 0 | # -*- coding: utf-8 -*-
# | Generated by Django 1.9.1 on 2016-01-19 06:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('condensed_urls', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='conde... | |
openstack/nomad | cyborg/objects/base.py | Python | apache-2.0 | 6,515 | 0 | # Copyright 2017 Huawei Technologies Co.,LTD.
# All Rights Reserved.
#
# Licensed under the Apache License, Ver | sion 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... | CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Cyborg common internal object model"""
import netaddr
from oslo_utils import versionutils
from oslo_versionedobjects import base as object_base
from cybo... |
pmghalvorsen/gramps_branch | gramps/gui/editors/edittaglist.py | Python | gpl-2.0 | 4,483 | 0.003792 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2010 Nick Hall
#
# 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)... | -----------------------------------------------------------------
WIKI_HELP_PAGE = '%s_-_Entering_and_Editing_Data:_Detailed_-_part_3' % \
URL_MANUAL_PAGE
WIKI_HELP_SEC = _('manual|Tags')
#-------------------------------------------------------------------------
... | anagedWindow):
"""
Dialog to allow the user to edit a list of tags.
"""
def __init__(self, tag_list, full_list, uistate, track):
"""
Initiate and display the dialog.
"""
ManagedWindow.__init__(self, uistate, track, self)
self.namemodel = None
top = self.... |
dalejung/trtools | trtools/core/tests/test_topper.py | Python | mit | 8,499 | 0.004118 | from unittest import TestCase
import pandas as pd
import pandas.util.testing as tm
import numpy as np
import trtools.core.topper as topper
import imp
imp.reload(topper)
arr = np.random.randn(10000)
s = pd.Series(arr)
df = tm.makeDataFrame()
class TestTopper(TestCase):
def __init__(self, *args, **kwargs):
... |
# make sure ascending is still respected
bn_res = topper.bn_topn(arr, 10, ascending=True)
pd_res = s.order(ascending=True)[-10:]
tm.assert_almost_equal(bn_res, pd_res.values)
# bottom defaults asc=True
bn_res = topper.bn_topn(arr, -10)
pd_res = s.order()[:10]
... | ected
bn_res = topper.bn_topn(arr, -10, ascending=False)
pd_res = s.order()[:10][::-1]
tm.assert_almost_equal(bn_res, pd_res.values)
def test_test_ndim(self):
"""
Make sure topn and topargn doesn't accept DataFrame
"""
try:
topper.topn(df, 1)
... |
RTHMaK/RPGOne | circleci-demo-python-flask-master/app/auth/views.py | Python | apache-2.0 | 6,044 | 0 | from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..models import User
from ..email import send_email
from .forms import LoginForm, RegistrationForm, ChangePasswordForm,\
... | commit()
token = user.generate_confirmation_token()
send_email(user.email, 'Confirm Your Account',
'auth/email/confirm', user=user, | token=token)
flash('A confirmation email has been sent to you by email.')
return redirect(url_for('auth.login'))
return render_template('auth/register.html', form=form)
@auth.route('/confirm/<token>')
@login_required
def confirm(token):
if current_user.confirmed:
return redirect(url_f... |
jjdmol/LOFAR | SubSystems/LAPS_CEP/test/startPythonFromMsg.py | Python | gpl-3.0 | 725 | 0.015172 | #!/usr/bin/python
import sys
from LAPS.MsgBus.Bus import Bus
# Create queue with a unique name
# insert message
# receive msg
# delete queue
if __name__ == "__main__":
# If invoked directly, parse command line arguments for logger information
| # and pass the rest to the run() method defined above
# --------------------------------------------------------------------------
try:
unique_queue_name = sys.argv[1]
except:
print "Not enough command line arguments: this test needs a unique queue name"
exi... | s.send(parset,"Observation123456") |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.3/Lib/distutils/cmd.py | Python | mit | 19,279 | 0.004201 | """distutils.cmd
Provides the Command class, the base class for the command classes
in the distutils.command package.
"""
# This module should be kept compatible with Python 1.5.2.
__revision__ = "$Id: cmd.py,v 1.34 2003/02/20 02:10:08 gvanrossum Exp $"
import sys, os, string, re
from types import *
from distutils.... | 'sub_commands' as a class attribute; it's a list of
# (command_name : string, predicate : unbound_method | string | None)
# tuples, where 'predicate' is a method of the parent command that
# determines whether the corresponding command is applicable in the
# current situation. (Eg. we "install_heade... | ' is usually defined at the *end* of a class, because
# predicates can be unbound methods, so they must already have been
# defined. The canonical example is the "install" command.
sub_commands = []
# -- Creation/initialization methods -------------------------------
def __init__ (self, dist):
... |
evancich/apm_motor | modules/waf/waflib/ConfigSet.py | Python | gpl-3.0 | 8,007 | 0.037842 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2010 (ita)
"""
ConfigSet: a special dict
The values put in :py:class:`ConfigSet` must be lists
"""
import copy, re, os
from waflib import Logs, Utils
re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M)
class ConfigSet(object):
"""
A dict that honor ... | te, to provide a kind of transaction support::
env = ConfigSet()
env.stash()
try:
env.append_value('CFLAGS', '-O3')
call_some_method(env)
finally:
env.revert()
The history is kept in a stack, and is lost during the serialization by :py:meth:`ConfigSet.store`
"""
orig = self.table
tbl =... | [orig]
def revert(self):
"""
Reverts the object to a previous state. See :py:meth:`ConfigSet.stash`
"""
self.table = self.undo_stack.pop(-1)
|
TeamEOS/external_chromium_org | tools/perf/benchmarks/scheduler.py | Python | bsd-3-clause | 1,116 | 0.006272 | # Copyright 2014 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.
from telemetry import test
from measurement | s import smoothness
import page_sets
@test.Disabled('linux') # crbug.com/368767
class SchedulerToughSchedulingCases(test.Test):
"""Measures rendering statistics while interacting with pages that have
challenging scheduling properties.
https://docs.google.com/a/chromium.org/document/d/
17yhE5Po9By0sCdM1y... | t = page_sets.ToughSchedulingCasesPageSet
# Pepper plugin is not supported on android.
@test.Disabled('android', 'win') # crbug.com/384733
class SchedulerToughPepperCases(test.Test):
"""Measures rendering statistics while interacting with pages that have
pepper plugins"""
test = smoothness.Smoothness
page_se... |
UltracoldAtomsLab/labhardware | projects/gwmultilog/quickplot.py | Python | mit | 1,511 | 0.023825 | import numpy as np
import pylab as pl
import sys
sys.path.append('../../lablib')
import ourgui
def smoothList(list,strippedXs=False,degree=10):
if strippedXs==True: return Xs[0:-(len(list)-(len(list)-degree+1))]
smoothed=[0]*(len(list)-degree+1)
for i in range(len(smoothed)):
smoothed[i]=sum(list[i... | ge(window):
i=i-degree+1
frac=i/float(window)
gauss=1/(np.exp((4*(frac))**2))
weightGauss.append(gauss)
weight=np.array(weightGauss)*weight
smoothed=[0.0]*(len(list)-window)
for i in range(len(smoothed)):
smoothed[i]=sum(np.array(list[i:i+window])*weight)/sum(... | loadtxt(filename,
delimiter=",",
dtype=dtypes,
)
date = data['date']
date -= date[0]
scale = 60
date /= scale
pl.plot(date, data['value'], '.')
degree = 200
sdataG = smoothListGaussian(data['value'], degree=degree)
sdateG = date[degree:(-degree+1)]
sdata = smoothL... |
ioram7/keystone-federado-pgid2013 | build/passlib/passlib/handlers/bcrypt.py | Python | apache-2.0 | 13,180 | 0.003794 | """passlib.bcrypt -- implementation of OpenBSD's BCrypt algorithm.
TODO:
* support 2x and altered-2a hashes?
http://www.openwall.com/lists/oss-security/2011/06/27/9
* deal with lack of PY3-compatibile c-ext implementation
"""
#=============================================================================
# imports
... | =======================
# class attrs
#===================================================================
#--GenericHandler--
name = "bcrypt"
setting_kwds = ("salt", "rounds", "ident")
checksum_size = 31
chec | ksum_chars = bcrypt64.charmap
#--HasManyIdents--
default_ident = u("$2a$")
ident_values = (u("$2$"), IDENT_2A, IDENT_2X, IDENT_2Y)
ident_aliases = {u("2"): u("$2$"), u("2a"): IDENT_2A, u("2y"): IDENT_2Y}
#--HasSalt--
min_salt_size = max_salt_size = 22
salt_chars = bcrypt64.charmap
... |
openregister/food-premises-demo | fsa_approved_premises/frontend/views.py | Python | mit | 4,293 | 0.002795 | import collections
import jinja2
import requests
from flask import (
current_app,
Blueprint,
render_template,
request,
jsonify,
abort
)
frontend = Blueprint('frontend', __name__, template_folder='templates')
headers = {"Content-type": "application/json"}
@jinja2.contextfilter
@frontend.app_t... | resp = requests.get(url, headers=headers)
if resp.status_code != 200:
abort(resp.status_code)
current_app.logger.info(resp.json())
return jsonify(resp.json())
@frontend.route('/premises/<int:id>')
def premises(id):
premises_register = current_app.config['PREMISES_REGISTER']
| poao_premises_register = current_app.config['POAO_PREMISES_REGISTER']
address_register = current_app.config['ADDRESS_REGISTER']
food_category_register = current_app.config['FOOD_ESTABLISHMENT_CATEGORY_REGISTER']
try:
premises_url = '%s/premises/%d.json' % (premises_register, id)
resp = r... |
kylebegovich/ProjectEuler | Python/Progress/Problem719.py | Python | gpl-3.0 | 1,757 | 0.007968 | from math import log10, floor
# N = 12
N = 101
# N = 1000001
def n_squares(n):
return [i**2 for i in range(2, n)]
# print(n_squares(11))
# print(n_squares(100))
##### This block from stackoverflow:
# https://stackoverflow.com/questions/37023774/all-ways-to-partition-a-string
import itertools
memo = {}
def mu... |
def allPartitions(s):
# if s in memo:
# return memo[s]
n = len(s)
cuts = list(range(1,n))
for k in range(1, n):
for cutpoints in itertools.combinations(cuts,k):
yield multiSlice(s,cutpoints)
##### En | d block
# print(list(allPartitions([int(i) for i in str(1234)])))
def list_sum(num_list):
outer_sum = 0
for sub_list in num_list:
inner_sum = 0
power = 1
for digit in sub_list[::-1]:
inner_sum += power * digit
power *= 10
outer_sum += inner_sum
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.