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 |
|---|---|---|---|---|---|---|---|---|
ofer43211/unisubs | apps/subtitles/admin.py | Python | agpl-3.0 | 6,564 | 0.001219 | # -*- coding: utf-8 -*-
# Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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
#... | ort_description = 'pending'
pending_collaborators.admin_order_field = 'pending_signoff_count'
def expired_pending_collaborators(self, o):
return o.pending_signoff_expired_count
expired_pending_collaborators.short_description = 'expired pending'
expired_pending_collaborators.admin_order_ | field = 'pending_signoff_expired_count'
def unexpired_pending_collaborators(self, o):
return o.pending_signoff_unexpired_count
unexpired_pending_collaborators.short_description = 'unexpired pending'
unexpired_pending_collaborators.admin_order_field = 'pending_signoff_unexpired_count'
def video... |
irl/gajim | src/common/connection_handlers_events.py | Python | gpl-3.0 | 94,929 | 0.00316 | # -*- coding:utf-8 -*-
## src/common/connection_handlers_events.py
##
## Copyright (C) 2010-2014 Yann Leboulanger <asterix AT lagaule.org>
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the ... | nimized = gajim.interface.minimized_controls[self.conn.name]
self.gc_control = minimized.get(self.jid)
def _generate_timestamp(self, tag):
tim = helpers.datetime_tuple(tag)
self.timestamp = localtime(timegm(tim))
def get_chatstate(self):
| """
Extract chatstate from a <message/> stanza
Requires self.stanza and self.msgtxt
"""
self.chatstate = None
# chatstates - look for chatstate tags in a message if not delayed
delayed = self.stanza.getTag('x', namespace=nbxmpp.NS_DELAY) is not None
if not dela... |
cnewcome/sos | sos/plugins/xen.py | Python | gpl-2.0 | 3,945 | 0 | # 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... | p -e 'vmx|svm' /proc/cpuinfo")
def setup(self):
host_type = self.determine_xen_host()
if host_type == "domU":
# we should collect /proc/xen and /sys/hypervisor
self.dom_collect_proc()
# determine if hardware virtualization support is enab | led
# in BIOS: /sys/hypervisor/properties/capabilities
self.add_copy_spec("/sys/hypervisor")
elif host_type == "hvm":
# what do we collect here???
pass
elif host_type == "dom0":
# default of dom0, collect lots of system information
... |
smurfix/HomEvenT | irrigation/rainman/models/env.py | Python | gpl-3.0 | 3,941 | 0.041921 | # -*- coding: utf-8 -*-
## Copyright © 2012, Matthias Urlichs <matthias@urlichs.de>
##
## 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 op... | {}
def list_valves(self):
return u"¦".join((d.name for d in self.valves.all()))
def refresh(sel | f):
super(EnvGroup,self).refresh()
self.env_cache = {}
def env_factor_one(self, tws, h):
p=4 # power factor, favoring nearest-neighbor
qtemp,qwind,qsun = tws
if qtemp and h.temp is None: return None
if qwind and h.wind is None: return None
if qsun and h.sun is None: return None
q=Q()
q &= Q(temp__i... |
icarito/arbio-azucar-adoptarbol | loader.py | Python | gpl-3.0 | 2,243 | 0.002675 | import csv
from dateutil.parser import parse
from adoptarbol.tree.models import Tree
def load(filename):
with open(filename, encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader)
def pos_for(field):
return header.index(field)
def float_or_none(string)... | 'coord_utm_zone_letter': row[pos_for('utm_zone')],
| 'coord_utm_zone_n': row[pos_for('utm_south')],
'coord_lat': float_or_none(row[pos_for('lat')].replace(',', '.')),
'coord_lon': float_or_none(row[pos_for('long')].replace(',', '.')),
'photo': row[pos_for('fotos')],
'diamete... |
Talvalin/server-client-python | tableauserverclient/server/endpoint/datasources_endpoint.py | Python | mit | 6,780 | 0.003835 | from .endpoint import Endpoint
from .exceptions import MissingRequiredFieldError
from .fileuploads_endpoint import Fileuploads
from .. import RequestFactory, DatasourceItem, PaginationItem, ConnectionItem
import os
import logging
import copy
import cgi
from contextlib import closing
# The maximum size of a file that c... | filepath=None):
if not datasource_id:
error = "Datasource ID undefined."
raise ValueError(error)
url = "{0}/{1}/content".format(self.baseurl, datasource_id)
with closing(self.get_request(url, parameters={'stream': True})) as server | _response:
_, params = cgi.parse_header(server_response.headers['Content-Disposition'])
filename = os.path.basename(params['filename'])
if filepath is None:
filepath = filename
elif os.path.isdir(filepath):
filepath = os.path.join(filepath,... |
PermeAgility/FrameworkBenchmarks | toolset/run-tests.py | Python | bsd-3-clause | 11,680 | 0.009589 | #!/usr/bin/env python
import argparse
import ConfigParser
import sys
import os
import multiprocessing
import itertools
import copy
import subprocess
from pprint import pprint
from benchmark.benchmarker import Benchmarker
from setup.linux.unbuffered import Unbuffered
from setup.linux import setup_util
from ast import l... | ser.add_argument('--clean', action='store_true', defau | lt=False, help='Removes the results directory')
parser.add_argument('--clean-all', action='store_true', dest='clean_all', default=False, help='Removes the results and installs directories')
# Test options
parser.add_argument('--test', nargs='+', help='names of tests to run')
parser.add_argument('--excl... |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/Cython/Compiler/Tests/TestVisitor.py | Python | gpl-2.0 | 2,228 | 0.002693 | from Cython.Compiler.ModuleNode import ModuleNode
from Cython.Compiler.Symtab import ModuleScope
from Cython.TestUtils import TransformTest
from Cython.Compiler.Visitor import MethodDispatcherTransform
from Cython.Compiler.ParseTreeTransforms import (
NormalizeTree, AnalyseDeclarationsTransform,
AnalyseExpressi... | s': 0, 'object': 0}
class Test(MethodDispatcherTransform):
def _handle_simple_method_bytes___mul__(self, | node, func, args, unbound):
calls['bytes'] += 1
return node
def _handle_simple_method_object___mul__(self, node, func, args, unbound):
calls['object'] += 1
return node
tree = self._build_tree()
Test(None)(tree)
self.as... |
OptimusGREEN/repo67beta | OGT Installer/plugin.program.ogtools/downloader.py | Python | gpl-3.0 | 2,845 | 0.011951 |
"""
Copyright (C) 2016 ECHO Wizard : Modded by TeamGREEN
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later v... | eived a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import xbmcgui
import urllib
import time
from urllib import FancyURLopener
import sys
class MyOpener(FancyURLopener):
version = "W | hosTheDaddy?"
myopener = MyOpener()
urlretrieve = MyOpener().retrieve
urlopen = MyOpener().open
AddonTitle= "[COLORgreen]OptimusGREEN Tools[/COLOR]"
dialog = xbmcgui.Dialog()
def download(url, dest, dp = None):
if not dp:
dp = xbmcgui.DialogProgress()
# dp.create("[COLORgold]Downl... |
abstract-open-solutions/l10n-italy | l10n_it_ricevute_bancarie/models/account_config.py | Python | agpl-3.0 | 2,038 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 Andrea Cometa.
# Email: info@andreacometa.it
# Web site: http://www.andreacometa.it
# Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2012 ... | self).default_get(
cr, uid, fields, context)
if res:
user = self.pool['res.users'].browse(cr, uid, uid, context)
res['due_cost_service_i | d'] = user.company_id.due_cost_service_id.id
return res
class ResCompany(models.Model):
_inherit = 'res.company'
due_cost_service_id = fields.Many2one('product.product')
|
alphagov/notifications-admin | app/extensions.py | Python | mit | 340 | 0 | from notifications_utils.clients.antivirus.antivirus_client import | (
AntivirusClient,
)
from notifications_utils.clients.redis.redis_client import RedisClient
from | notifications_utils.clients.zendesk.zendesk_client import ZendeskClient
antivirus_client = AntivirusClient()
zendesk_client = ZendeskClient()
redis_client = RedisClient()
|
taschik/ramcloud-load-manager | scripts/recoverymetrics.py | Python | isc | 32,500 | 0.003692 | #!/usr/bin/env python
# Copyright (c) 2011 Stanford University
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ... | __ = ['parseRecovery', 'makeReport']
### Utilities:
class AttrDict(dict):
"""A mapping with string keys that aliases x.y syntax to x['y'] syntax.
The attribute syntax is easier to read and type than the item syntax.
"""
def __getattr__(self, name):
if name not in self:
self[name] ... | self[name] = value
def __delattr__(self, name):
del self[name]
def assign(self, path, value):
"""
Given a hierarchical path such as 'x.y.z' and
a value, perform an assignment as if the statement
self.x.y.z had been invoked.
"""
names = path.split('.')
... |
mjg2203/edx-platform-seas | lms/djangoapps/courseware/roles.py | Python | agpl-3.0 | 7,324 | 0.001912 | """
Classes used to model the roles used in the courseware. Each role is responsible for checking membership,
adding users, removing users, and listing members
"""
from abc import ABCMeta, abstractmethod
from django.contrib.auth.models import User, Group
from xmodule.modulestore import Location
from xmodule.modulest... | ll be consider a member of the Role
"""
self._group_names = [name.lower() for name in group_names]
def has_user(self, user):
"""
| Return whether the supplied django user has access to this role.
"""
# pylint: disable=protected-access
if not user.is_authenticated():
return False
if not hasattr(user, '_groups'):
user._groups = set(name.lower() for name in user.groups.values_list('name', f... |
RincewindWizzard/gruppenkasse-gtk | src/tests/test_model.py | Python | lgpl-3.0 | 1,143 | 0.0035 | #!/usr/bin/python3
# -*- encoding: utf-8 -*-
import unittest
from model import *
from example_data import expenses, payments, participations, persons, events
kasse = Gruppenkasse.create_new()
kasse.fill_with(expenses, payments, participations)
class TestGruppenkasse(unittest.TestCase):
def setUp(self):
.... | for name in person_names:
self.assertTrue(name in persons, msg=name)
def test_events(self):
print(kasse.person_dict)
event_names = list(map(lambda p: p.name, kasse.events))
for name in event_names:
self.assertTrue(name in events, msg=name)
for name in even... | nts:
...#print(event)
def test_person(self):
for person in kasse.persons:
print(person, "\t{:5.2f}".format(person.balance / 100))
def test_payments(self):
print(kasse.payments)
if __name__ == '__main__':
unittest.main()
|
mfraezz/osf.io | api_tests/nodes/views/test_node_wiki_list.py | Python | apache-2.0 | 19,731 | 0.001977 | import mock
import pytest
from rest_framework import exceptions
from addons.wiki.models import WikiPage
from addons.wiki.tests.factories import WikiFactory, WikiVersionFactory
from api.base.settings.defaults import API_BASE
from api_tests.wikis.views.test_wiki_detail import WikiCRUDTestCase
from framework.auth.core i... | wiki_ids = [wiki['id'] for wiki in res.json['data']]
assert public_wiki._id in wiki_ids
# test_return_private_node_wikis_logged_out_user
res = app.get(private_url, expect_errors=True)
assert res.status_code == 401
assert res.json['errors'][0]['detail'] == exceptions.NotAuthent... | l
# test_return_private_node_wikis_logged_in_osf_group_member
group_mem = AuthUserFactory()
group = OSFGroupFactory(creator=group_mem)
private_project.add_osf_group(group, READ)
res = app.get(private_url, auth=group_mem.auth)
assert res.status_code == 200
wiki_ids ... |
nhquiroz/hacker-rank | python/introduction/mod-div-mod.py | Python | mit | 239 | 0 | from __future__ import division
# Read two integers from STDIN
a = int(raw_input())
b = int(raw_input())
# Print integer division, a//b
print(a // b)
# Print float d | ivision, a/b
print(a % b)
# Print | divmod of a and b
print(divmod(a, b))
|
ZenithDK/mopidy-primare | mopidy_primare/primare_serial.py | Python | apache-2.0 | 17,724 | 0 | """Primare amplier control.
This module allows you to control your Primare I22 and I32 amplifier from the
command line using Primare's binary protocol via the RS232 port on the
amplifier.
"""
from __future__ import with_statement
import binascii
import logging
import struct
import time
# from twisted.logger import ... | self.volume_set(volume)
# Setup logging so that is available
logging.basicConfig(level=logging.DEBUG)
# Private methods
def _set_device_to_known_state(self):
logger.debug('_set_device_to_known_state')
self.verbose_set(True)
self.power_on()
time.sleep(1... | self.input_set(self._source)
self.mute_set(False)
def _print_device_info(self):
self.manufacturer_get()
self.modelname_get()
self.swversion_get()
# We always get inputname last, this represents our initialization
self.inputname_current_get()
def _primare_... |
TheArbiter/Networks | lab4/lab4exercise2/exp_monitor.py | Python | gpl-3.0 | 1,212 | 0.008251 | from monitor import monitor_qlen
from subprocess import Popen, PIPE
from time import sleep, time
from multiprocessing import Process
from argparse import ArgumentParser
import sys
import os
parser = ArgumentParser(description="CWND/Queue Monitor")
parser.add_argument('--exp', '-e',
dest="exp",
... | ="Name of the Experiment",
required=True)
# Expt parameters
args = parser.parse_args()
def start_tcpprobe():
"Insta | ll tcp_pobe module and dump to file"
os.system("(rmmod tcp_probe >/dev/null 2>&1); modprobe tcp_probe full=1;")
print "Monitoring TCP CWND ... will save it to ./%s_tcpprobe.txt " % args.exp
Popen("cat /proc/net/tcpprobe > ./%s_tcpprobe.txt" %
args.exp, shell=True)
def qmon():
monitor = Proces... |
t--wagner/pymeasure | instruments/oxford_ilm.py | Python | gpl-3.0 | 1,931 | 0.004661 | # -*- coding: utf-8 -*
from pymeasure.instruments.pyvisa_instrument import PyVisaInstrument
from pymeasure.case import ChannelRead
from pymeasure.instruments.oxford import OxfordInstrument
import time
class _QxfordILMChannel(ChannelRead):
def __init__(self, instrument):
ChannelRead.__init__(self)
... | += ['fast']
@ChannelRead._readmethod
def read(self):
while True:
helium = self._instrument.query('R')
helium = helium[2:]
if len(helium) == 4:
break
return [float(helium)/10]
@property
def fast(self):
while True:
... | elif status == '2' or status == '3' or status == 'A' :
return True
else:
time.sleep(1)
pass
@fast.setter
def fast(self, boolean):
if boolean:
self._instrument.write('T1')
else:
self._instrument.write('S1')
... |
arpruss/plucker | plucker_desktop/installer/osx/application_bundle_files/Resources/parser/python/vm/PIL/MicImagePlugin.py | Python | gpl-2.0 | 2,334 | 0.002571 | #
# The Python Imaging Library.
# $Id: MicImagePlugin.py,v 1.2 2007/06/17 14:12:15 robertoconnor Exp $
#
# Microsoft Image Composer support for PIL
#
# Notes:
# uses TiffImagePlugin.py to read the actual image streams
#
# History:
# 97-01-20 fl Created
#
# Copyright (c) Secret Labs AB 1997.
... | -----
def _accept(prefix):
return prefix[:8] == MAGIC
##
# Image plugin for Microsoft' | s Image Composer file format.
class MicImageFile(TiffImagePlugin.TiffImageFile):
format = "MIC"
format_description = "Microsoft Image Composer"
def _open(self):
# read the OLE directory and see if this is a likely
# to be a Microsoft Image Composer file
try:
... |
rwl/openpowersystem | cdpsm/iec61970/wires/disconnector.py | Python | agpl-3.0 | 1,912 | 0.004184 | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# 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; version 2 dated June... | implied warranty of MERCHANDABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GN | U Affero General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#------------------------------------------------------------------------------
""" A manually operated or motor operated mechanical switching device ... |
hellysmile/django-redis-sessions-fork | redis_sessions_fork/conf.py | Python | bsd-3-clause | 932 | 0 | from __future__ import absolute_import, unicode_literals
import os
from appconf import AppConf
from django.conf import settings # noqa
class SessionRedis | Conf(AppConf):
HOST = '127.0.0.1'
PORT = 6379
| DB = 0
PREFIX = 'django_sessions'
PASSWORD = None
UNIX_DOMAIN_SOCKET_PATH = None
URL = None
CONNECTION_POOL = None
JSON_ENCODING = 'latin-1'
ENV_URLS = (
'REDISCLOUD_URL',
'REDISTOGO_URL',
'OPENREDIS_URL',
'REDISGREEN_URL',
'MYREDIS_URL',
... |
pabloalcain/lammps-python | pylammps/Computes/Compute.py | Python | gpl-3.0 | 1,563 | 0.007038 | """
Compute class
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import pylab as pl
#TODO: Take care of the looks of these plots
class Compute(object):
"""
Abstract compute class. It will never be used, but is parent of all
the different computes.
"""
def __init__(self):
"""
Construc... | np.savetxt(filename, self.value, header='; '.join(self.header))
def plot(self, filename):
| """
Plotting routine. By default we plot every column [1:] as a
function of column 0, setting labels and axis names with
self.header and save it to filename.
"""
fig, axis = pl.subplots()
for i, vec in enumerate(self.value.T[1:]):
axis.plot(self.value[:, 0], vec, label=self.header[i])
... |
pcolmant/repanier | repanier/widget/picture.py | Python | gpl-3.0 | 1,573 | 0 | from django.core.files.storage import default_storage
from django.forms import widgets
from django.urls import reverse
from repanier.const import EMPTY_STRING
from repanier.picture.const import SIZE_M
from repanier.tools import get_repanier_template_name
class RepanierPictureWidget(widgets.TextInput):
template | _name = get_repanier_template_name("widgets/picture.html")
def __init__(self, *args, **kwargs):
self.upload_to = kwargs.pop("upload_to", "pictures")
self.size = kwargs.pop("size", SIZE_M)
self.bootstrap = kwargs.pop("bootstrap", False)
super().__init__(*args, **kwargs)
def get_... | context["upload_url"] = reverse(
"repanier:ajax_picture", args=(self.upload_to, self.size)
)
if value:
context["repanier_file_path"] = file_path = str(value)
context["repanier_display_picture"] = "inline"
context["repanier_display_upload"] = "none"
... |
zebde/RobIP | iplookup.py | Python | gpl-3.0 | 6,811 | 0.000147 | """This will perform basic enrichment on a given IP."""
import csv
import json
import mmap
import os
import socket
import urllib
import dns.resolver
import dns.reversename
from geoip import geolite2
from IPy import IP
from joblib import Parallel, delayed
from netaddr import AddrFormatError, IPSet
torcsv = 'Tor_ip_li... | inputdict['country'],
inputdict['lat'],
inputdict['long'],
inputdict['tor-node']))
finally:
fhandle.close()
def main():
import argparse
PARSER = argparse.ArgumentParser()
PARSER.add_argument("-t" | ,
choices=('single', 'batch'),
required="false",
metavar="request-type",
help="Either single or batch request")
PARSER.add_argument("-v",
required="false",
metavar="value",... |
Eloston/ungoogled-chromium | utils/downloads.py | Python | bsd-3-clause | 17,917 | 0.003628 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (c) 2019 The ungoogled-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.
"""
Module for the downloading, checking, and unpacking of necessary files into the source tree.... | e)
if name == 'hashes':
hashes | _dict = {}
for hash_name in (*self._hashes, 'hash_url'):
value = self._section_dict.get(hash_name, fallback=None)
if value:
if hash_name == 'hash_url':
value = value.split(DownloadInfo.hash_url_delimiter)
... |
googleapis/python-speech | samples/generated_samples/speech_v1p1beta1_generated_speech_recognize_async.py | Python | apache-2.0 | 1,643 | 0.000609 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may | obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for... | ed code. DO NOT EDIT!
#
# Snippet for Recognize
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-speech
... |
niktre/espressopp | testsuite/pi_water/water.py | Python | gpl-3.0 | 8,192 | 0.007935 | #!/usr/bin/env python2
#
# Copyright (C) 2013-2017(H)
# Max Planck Institute for Polymer Research
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation,... | ###########################################
## IT SHOULD BE UNNECESSARY TO MAKE MODIFICATIONS BELOW THIS LINE ##
######################################################################
#types, bonds, angles, dihedrals, x, y, z, vx, vy, vz, | Lx, Ly, Lz = gromacs.read(grofile,topfile)
num_particles = len(x)
density = num_particles / (Lx * Ly * Lz)
size = (Lx, Ly, Lz)
sys.stdout.write('Setting up simulation ...\n')
system = espressopp.System()
system.rng = espressopp.esutil.RNG()
system.bc = espressopp.bc.OrthorhombicBC(system.rng, size)
system.skin = skin... |
liam2/liam2 | liam2/merge_h5.py | Python | gpl-3.0 | 4,745 | 0.000211 | # encoding: utf-8
from __future__ import absolute_import, division, print_function
import numpy as np
import tables
from liam2.data import merge_arrays, get_fields, index_table_light, merge_array_records
from liam2.utils import timed, loop_wh_progress, merge_items
__version__ = "0.4"
def get_group_fiel... | t, input2root, 'globals', output_file, 'PERIOD')
merge_group(input1root, input2root, 'entities', output_file, 'period')
input1_file.close()
input2_file.close()
output_file.close()
if __name__ == '__main__':
import sys
import platform
print("LIAM HDF5 merge | %s using Python %s (%s)\n" %
(__version__, platform.python_version(), platform.architecture()[0]))
args = sys.argv
if len(args) < 4:
print("Usage: %s inputpath1 inputpath2 outputpath" % args[0])
sys.exit()
timed(merge_h5, args[1], args[2], args[3])
|
cloudera/hue | desktop/core/ext-py/Babel-2.5.1/tests/messages/test_checkers.py | Python | apache-2.0 | 12,538 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2011 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists... | singular plural forms
def test_1_num_plurals_checkers(self):
for _locale in [p for p in PLURALS if PLURALS[p][0] == 1]:
try:
locale = Locale.parse(_locale)
except UnknownLocaleError:
# Just an alias? Not what we're testing here, let's continue
... | TestProject.
# Copyright (C) 2007 FooBar, Inc.
# This file is distributed under the same license as the TestProject
# project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2007.
#
msgid ""
msgstr ""
"Project-Id-Version: TestProject 0.1\\n"
"Report-Msgid-Bugs-To: bugs.address@email.tld\\n"
"POT-Creation-Date: 2007-04-01 15:30+0200\\... |
Mariusz1970/enigma2 | lib/python/Screens/InfoBarGenerics.py | Python | gpl-2.0 | 140,459 | 0.031426 | # -*- coding: utf-8 -*-
from Components.ActionMap import ActionMap, HelpableActionMap, NumberActionMap
from Components.Harddisk import harddiskmanager, findMountPoint
from Components.Input import Input
from Components.Label import Label
from Components.MovieList import AUDIO_EXTENSIONS
from Components.PluginComponent i... | tCache
ref = session.nav.getCurrentlyPlayingServiceOrGroup()
if (ref is not None) and (ref.type != 1):
try:
entry = resumePointCache[ref.toString()]
entry[0] = int(time()) # update LRU timestamp
return entry[1]
except KeyError:
return None
def saveResumePoints():
global resumePointCache, resumePoint... | ePointCache, f, cPickle.HIGHEST_PROTOCOL)
f.close()
except Exception, ex:
print "[InfoBar] Failed to write resumepoints:", ex
resumePointCacheLast = int(time())
def loadResumePoints():
try:
file = open('/etc/enigma2/resumepoints.pkl', 'rb')
PickleFile = cPickle.load(file)
file.close()
return PickleFile
... |
ziotom78/stripeline | stripeline/timetools.py | Python | mit | 11,654 | 0.001974 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from collections import namedtuple
from typing import List, Union
import numpy as np
from astropy.io import fits
TimeChunk = namedtuple('TimeChunk', 'start_time num_of_samples')
def split_time_range(time_length: float,
num_of_chunks: int,
... | it_into_n(10, 4)
[2 3 2 3]
>>> split_into_n(201, 2)
[100 101]
'''
assert num_of_segments > 0
assert length > num_of_segments
start_points = np.array([int(i * length / num_of_segments)
for i in range(num_of_segments + 1)])
return start_points[1:] ... | assign_toi_files_to_processes(samples_per_processes: List[int],
tod_files: List[ToiFile]):
'''Determine how to balance the load of TOI files among processes.
Given a list of samples to be processed by each MPI process, decide which
TOD and samples must be loaded by each p... |
asedunov/intellij-community | python/testData/editing/spaceDocStringStubInClass.after.py | Python | apache-2.0 | 28 | 0.071429 | class | C:
''' <caret | >
''' |
AutorestCI/azure-sdk-for-python | azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/operation_list_result.py | Python | mit | 955 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT Licen | se. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization im... | erations.
:type value: list of :class:`Operation
<azure.mgmt.containerinstance.models.Operation>`
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Operation]'},
}
def __init__(self, value=None):
self.value = value
|
HIPS/neural-fingerprint | neuralfingerprint/build_convnet.py | Python | mit | 6,508 | 0.005532 | import autograd.numpy as np
from autograd.scipy.misc import logsumexp
from features import num_atom_features, num_bond_features
from util import memoize, WeightsParser
from mol_graph import graph_from_smiles_tuple, degrees
from build_vanilla_net import build_fingerprint_deep_net, relu, batch_normalize
def fast_array... | ay_from_list([np.sum(features[idx_list], axis=0) for idx_list in idxs_list_of_lists])
def softmax(X, axis=0):
return np.exp(X - logsumexp(X, axis=axis, keepdims=True))
def matmult_neighbors(array_rep, atom_features, bond_features, get_weights):
activations_by_degree = []
| for degree in degrees:
atom_neighbors_list = array_rep[('atom_neighbors', degree)]
bond_neighbors_list = array_rep[('bond_neighbors', degree)]
if len(atom_neighbors_list) > 0:
neighbor_features = [atom_features[atom_neighbors_list],
bond_features[b... |
lizardsystem/lizard-damage | lizard_damage/migrations/0012_auto__add_field_damagescenario_customlandusegeoimage.py | Python | gpl-3.0 | 9,306 | 0.007629 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'DamageScenario.customlandusegeoimage'
db.add_column('lizard_damage_damagescenario', 'custo... | models.fields.CharField', [], {'max_length': '64'}),
'slug': ('django.db.models.fields.SlugField', [], {'db | _index': 'True', 'max_length': '50', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}),
'zip_result': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'zip_risk_a': ('dja... |
evonove/urt-tully | django-tully/manage.py | Python | mit | 803 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tully.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... | hat Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? ... | ise
execute_from_command_line(sys.argv)
|
psvnl/podb | ui_mainwindow.py | Python | gpl-3.0 | 28,313 | 0.002508 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed May 25 13:43:28 2016
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf... | ig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi( | self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 752)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/podbicon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = ... |
clarko1/Cramd | bigquery/api/getting_started_test.py | Python | apache-2.0 | 808 | 0 | # Copyright 2015, 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, s... | mplied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
|
from getting_started import main
def test_main(cloud_config, capsys):
main(cloud_config.project)
out, _ = capsys.readouterr()
assert re.search(re.compile(
r'Query Results:.hamlet', re.DOTALL), out)
|
StackStorm/st2 | st2common/st2common/persistence/rule_enforcement.py | Python | apache-2.0 | 920 | 0 | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License ... | d
# limitations under the License.
from __future__ import absolute_import
from st2common.models.db.rule_enforcement import rule_enforcement_access
from st2common.persistence.base import Access
class RuleEnforcement(Access):
impl = rule_enforcement_access
@classmethod
def _get_impl(cls):
return c... |
umrashrf/scrapy | scrapy/utils/test.py | Python | bsd-3-clause | 3,020 | 0.002649 | """
This module contains some assorted functions used in tests
"""
from __future__ import absolute_import
import os
from importlib import import_module
from twisted.trial.unittest import SkipTest
from scrapy.ex | ceptions import NotConfigured
from scrapy.utils.boto | import is_botocore
def assert_aws_environ():
"""Asserts the current environment is suitable for running AWS testsi.
Raises SkipTest with the reason if it's not.
"""
skip_if_no_boto()
if 'AWS_ACCESS_KEY_ID' not in os.environ:
raise SkipTest("AWS keys not found")
def assert_gcs_environ():
... |
csnake-org/CSnake | src/csnStandardModuleProject.py | Python | bsd-3-clause | 7,313 | 0.012033 | ## @package csnStandardModuleProject
# Definition of the methods used for project configuration.
# This should be the only CSnake import in a project configuration.
import csnUtility
import csnProject
import csnBuild
import os.path
import inspect
from csnProject import GenericProject
class StandardModuleProject(Gener... | = None, _categories = None):
if _sourceRootFolder is None:
filename = csnProject.FindFilename(1)
dirname = os.path.dirname(filename)
_sourceRootFolder = csnUtility.NormalizePath(dirname, _correctCase = False)
GenericProject.__init__(self, _name=_name, _type=_type, _s... | self.applicationsProject = None
def AddLibraryModules(self, _libModules):
"""
Adds source files (anything matching *.c??) and public include folders to self, using a set of libmodules.
It is assumed that the root folder of self has a subfolder called libmodules. The subfolders of ... |
procrastinatio/mapproxy | mapproxy/test/unit/test_collections.py | Python | apache-2.0 | 3,064 | 0.001305 | # This file is part of the MapProxy project.
# Copyright (C) 2010 Omniscale <http://omniscale.de>
#
# 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... | assert 'foo1' in lru
assert 'foo2' not in lru
def test_repr(self):
lru = LRU(10)
lru['foo1'] = 1
assert 'size=10' in repr(lru)
assert 'foo1' in repr(lru)
def test_g | etitem(self):
lru = LRU(10)
lru['foo1'] = 1
lru['foo2'] = 2
eq_(lru['foo1'], 1)
eq_(lru['foo2'], 2)
def test_get(self):
lru = LRU(10)
lru['foo1'] = 1
eq_(lru.get('foo1'), 1)
eq_(lru.get('foo1', 2), 1)
def test_get_default(self):
l... |
avoorhis/vamps-node.js | public/scripts/rdp/rdp_fasta2tax.py | Python | mit | 6,320 | 0.024525 | #!/usr/bin/env python
#########################################
#
# fasta2tax.py
#
########################################
import sys,os
import argparse
import pymysql as MySQLdb
import json
py_pipeline_path = os.path.expanduser('~/programming/py_mbl_sequencing_pipeline')
#my $rdpFile = "$inputfile.rdp";
print "... | le to execute query: $query\n";
# }
# print "Application Error: An error has occured while trying to load the data into the MySQL database. The following query was used: \"$loadQuery\".\n";
# print "The database engine reports the error as: \"".$dbh->errstr."\".\n";
# print "This is a fatal error. E... | # commit the transaction...
# my $query = "COMMIT";
# my $handle = $dbh->prepare($query) or die "Unable to prepare query: $query\n";
# $handle->execute or die "Unable to execute query: $query\n";
# }
#$DEBUG && print "DEBUG: Cleaning out tmp files...\n";
# foreach my $i ($inputfile, $rdpFile, $loadF... |
MindLoad/MonkeyManager | widgets/__init__.py | Python | gpl-3.0 | 94 | 0 | """
Project additional elements |
"""
from .menu_button impo | rt *
from .new_key_qframe import *
|
ricco386/broadcaster | RPi.PIR/setup.py | Python | bsd-3-clause | 1,382 | 0 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# This software is licensed as described in the README.rst and LICENSE
# files, which you should have received as part of this distribution.
import setuptools
# noinspection PyPep8Naming
from raspi_pir import __version__ as VERSION
DEPS = ['RPi.Sensor>=0.5.3']
CLASSIFIERS ... | ge :: Python :: 3',
'Development Status :: 4 - Beta',
'Topic :: Utilities',
'Topic :: Home Automation',
'Topic :: System :: Hardware',
'Topic :: Terminals'
]
with open("README.rst", "r") as fp:
sensor_long_description = fp.read()
setuptools.setup(
name='RPi.PIR',
version=VERSION,
a... | thor_email="richard.kellner [at] gmail.com",
url="https://github.com/ricco386/RPi",
description='PIR sensor state monitor',
long_description=sensor_long_description,
license="MIT",
packages=setuptools.find_packages(),
classifiers=CLASSIFIERS,
install_requires=DEPS,
scripts=['bin/raspi-pi... |
kernt/linuxtools | gnome3-shell/nautilus-scripts/Archiving/PlowShare-Upload.py | Python | gpl-3.0 | 6,622 | 0.056025 | #!/usr/bin/python
#requires the following:
#sudo apt-get install curl
#curl http://apt.wxwidgets.org/key.asc | apt-key add -
#sudo apt-get update
#sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-i18n
#sudo apt-get install python-gdata
import wx
import os
import sys
def pinger():
f = os.popen('ping -c 1 go... | self.param = ''
self.check=0
self.args = sys.argv[1:]
if len(self.args)==0:
self.check=1
wx.Frame.__init__(self,None,-1,'Pshare',size=(600,330))
self.panel = wx.Panel(self)
wx.StaticText(self.panel,-1,'Welcome to the Plowshare Uploader GUI.\n\nThis app lets you upload any file to any of the supported fil... | s. To proceed, please select one (or more) of the uploading sites:',pos = (30,30), size = (540,70))
wx.StaticText(self.panel,-1,'Available Sites to upload:',pos = (30,160))
self.choice_box = wx.ListBox(self.panel,-1,(30,120),(540,100),uplist, wx.LB_EXTENDED | wx.LB_HSCROLL)
wx.StaticText(self.panel,-1,'*Upload... |
geographika/mappyscript | mappyscript/__init__.py | Python | mit | 190 | 0.010526 | # for Python3 we need a f | ully qualified name import
from mappyscript._mappyscript import version, version_number, load, loads, dumps, create_request, load_map_from_params | , Layer, convert_sld |
Vladkryvoruchko/PSPNet-Keras-tensorflow | tests/test_smoke.py | Python | mit | 2,114 | 0.005676 | import os
import pytest
import numpy as np
from imageio import imread
def compare_2_images(validator_path, output_path):
val_abs_path = os.path.join(os.path.dirname(__file__), validator_path)
out_abs_path = os.path.join(os.path.dirname(__file__), output_path)
val_img = imread(val_abs_path, pilmode='RGB')... | _probs.jpg")
os.remove("tests/" + output_file_no_ext + "_seg.jpg")
os.remove("tests/" + output_file_no_ext + "_seg_blended.jpg")
os.remove("tests/" + output_file_no_ext + "_seg_read.jpg")
def test_main_flip_ade20k(cli_args_ade):
from pspnet import main
main(cli_args_ade)
compare_2_images("ade20... | t_seg.jpg", "validators/ade20k_test_seg.jpg")
compare_2_images("ade20k_test_seg_read.jpg", "validators/ade20k_test_seg_read.jpg")
clean_test_results("ade20k_test")
@pytest.mark.skip
def test_main_flip_cityscapes(cli_args_cityscapes):
"""
TODO: Add images
:param cli_args_cityscapes:
:return:
... |
bitsoffreedom/baas | baas/boem/models.py | Python | gpl-2.0 | 607 | 0.008237 | from django.db import models
# from django.contrib.gis.geoip import GeoIP
#
# g = GeoIP()
# Create your models here.
class TempM | ail(models.Model):
mailfrom = models.EmailField()
mailsubj = models.CharField(max_length=20)
mailrcvd = models.DateTimeField()
mail | hdrs = models.CharField()
class SavedMail(models.Model):
mailrcvd = models.DateTimeField()
mailhdrs = models.CharField()
organization = models.ForeignKey('Organization')
class Organization(models.Model):
emailsuffix = models.CharField(max_length=255)
class Follower(models.Model):
email = models.E... |
Habitissimo/vespapp-web | api/admin.py | Python | gpl-3.0 | 278 | 0 | from djang | o.contrib import admin
from a | pi.models import *
admin.site.register(Question)
admin.site.register(Answer)
admin.site.register(Sighting)
admin.site.register(Picture)
admin.site.register(UserComment)
admin.site.register(ExpertComment)
admin.site.register(SightingFAQ)
|
Azure/azure-sdk-for-python | sdk/formrecognizer/azure-ai-formrecognizer/tests/test_frc_identity_documents_async.py | Python | mit | 8,158 | 0.003187 | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
import functools
from io import BytesIO
from devtools_testutils.aio import recorded_by_proxy_async
from azure.core.exceptions import Servic... | _document)
assert "Method 'begin_recognize_identity_documents' is only available for API version V2_1 and up" in str(e.value)
@FormRecognizerPreparer()
@FormRecognizerClientPreparer()
@recorded_by | _proxy_async
async def test_pages_kwarg_specified(self, client):
with open(self.identity_document_license_jpg, "rb") as fd:
id_document = fd.read()
async with client:
poller = await client.begin_recognize_identity_documents(id_document, pages=["1"])
assert '1' == ... |
mwiencek/picard | picard/tagger.py | Python | gpl-2.0 | 23,746 | 0.002653 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2004 Robert Kaye
# Copyright (C) 2006 Lukáš Lalinský
#
# 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; ... | self.config.setting["file_naming_format"])
self.config.setting.remove("va_file_naming_format")
self.config.setting.remove("use_va_format")
if "va_file_naming_format" in self.config.setting\
and "use_va_format" in self.config.setting:
if self.config.... | va_format"].toBool():
remove_va_file_naming_format()
self.window.show_va_removal_notice()
elif self.config.setting["va_file_naming_format"].toString() !=\
r"$if2(%albumartist%,%artist%)/%album%/$if($gt(%totaldiscs%,1),%discnumber%-,)$num(%tracknumber%,2) %arti... |
levilucio/SyVOLT | UMLRT2Kiltera_MM/Properties/from_thesis/HMM9_if_IsolatedLHS.py | Python | mit | 2,478 | 0.010896 | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HMM9_if_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HMM9_if_IsolatedLHS.
"""
# Flag this instance as c... | r the nodes in the LHS have been matched.
# You can access a | matched node labelled n by: PreNode('n').
# To access attribute x of node n, use: PreNode('n')['x'].
# The given constraint must evaluate to a boolean expression:
# returning True enables the rule to be applied,
# returning False forbids the rule from being applied.
#=====... |
williamg/recycle | recycle/recycle.py | Python | mit | 6,538 | 0.00153 | #!/usr/bin/env python
import argparse
import logging
import os
import shutil
import sys
import glob
# Location of saved templates
SAVE_DIR = os.environ.get("RECYCLE_TEMPLATES_DIR", "~/.recycle")
try:
input = raw_input
except NameError:
pass
def should_overwrite(typeOfThing, path):
assert os.path.exists(p... | print(os | .path.normpath(SAVE_DIR) + os.sep)
def parseargs():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
new_parser = subparsers.add_parser(
"new", help="Create a new template or overwrite an existing one")
new_parser.add_argument(
"name", type=str, help="The name ... |
D4wN/brickv | src/brickv/plugin_system/plugins/ozone/ozone.py | Python | gpl-2.0 | 3,949 | 0.002026 | # -*- coding: utf-8 -*-
"""
Ozone Bricklet Plugin
Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com>
ozone.py: Ozone Bricklet Plugin Implementation
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; e... | rationLabel(QLabel):
def setText(self, text):
text = "Ozone Concentration: " + text + " ppb (parts per billion)"
super(OzoneConcentrationLabel, self).setText(text)
class Ozone(PluginBase):
def __init__(self, *args):
PluginBase.__init__(self, BrickletOzone, *args)
self.ozone = s... | lator(self.ozone.get_ozone_concentration,
self.cb_ozone_concentration,
self.increase_error_count)
self.ozone_concentration_label = OzoneConcentrationLabel('Ozone Concentration: ')
self.curre... |
daelmaselli/ovirt-vm-hot-backup | ovirt-vm-rolling-snapshot.py | Python | mit | 6,894 | 0.003046 | #!/usr/bin/python
import sys
import time
import datetime
import re
import ConfigParser
import os
from operator import attrgetter
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
conffile = scriptdir + "/ovirt-vm-rolling-snapshot.conf"
Config = ConfigParser.ConfigParser()
if not os.path.isfile(conffile):
... | if snap_status == "locked":
time.sleep(5)
sys.stdout.write('.')
sys.stdout.flush()
else:
print
break
for snapi in vm.g | et_snapshots().list():
snapi_id = snapi.get_id()
if vm.snapshots.get(id=snapi_id).description == snap_description:
snap_status = "ok"
break
else:
snap_status = "error"
if ... |
pytroll/pytroll-aapp-runner | aapp_runner/tests/test_helper_functions.py | Python | gpl-3.0 | 5,294 | 0.002456 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Pytroll developers
# Author(s):
# Adam Dybbroe <Firstname.Lastname @ smhi.se>
# 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 Foundat... | blic License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Unittesting the helper functions for the AAPP-runner.
"""
import logging
import unittest
from datetime import datetime
from unittest.mock impor... | from aapp_runner.helper_functions import check_if_scene_is_unique
from aapp_runner.read_aapp_config import AappL1Config, AappRunnerConfig
from aapp_runner.tests.test_config import (TEST_YAML_CONTENT_OK,
create_config_from_yaml)
class TestProcessConfigChecking(unittest.TestCa... |
braintree/braintree_python | tests/unit/test_resource.py | Python | mit | 3,302 | 0.000909 | from tests.test_helper import *
from braintree.resource import Resource
class TestResource(unittest.TestCase):
def test_verify_keys_allows_wildcard_keys(self):
signature = [
{"foo": [{"bar": ["__any_key__"]}]}
]
params = {
"foo[bar][lower]": "lowercase",
... | y_key__"]}]}
]
params = {
"customer_id": "value",
}
Resource.verify_keys(params, signature)
def test_verify_keys_works_with_array_param(self):
signature = [
{"customer": ["one", "two"]}
]
params = {
"customer": {
... | signature = [
{"customer": ["one", "two"]}
]
params = {
"customer": {
"invalid": "foo"
}
}
Resource.verify_keys(params, signature)
def test_verify_keys_works_with_arrays(self):
signature = [
{"add_ons": [{"u... |
yunify/qingcloud-cli | qingcloud/cli/driver.py | Python | apache-2.0 | 3,383 | 0.004138 | # =========================================================================
# Copyright 2012-present Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the Licens... | ameters]\n\n' \
+ 'Here are valid actions:\n\n' \
+ INDENT + NEWLINE.join(get_valid_acti | ons(service))
if suggest_actions:
usage += '\n\nInvalid action, maybe you meant:\n ' \
+ NEWLINE.join(suggest_actions)
parser = argparse.ArgumentParser(
prog = 'qingcloud %s' % service,
usage = usage,
)
parser.print_help()
sys.exit(-1)
def get_valid_action... |
adam111316/SickGear | sickbeard/providers/grabtheinfo.py | Python | gpl-3.0 | 6,393 | 0.002659 | # coding=utf-8
#
# This file is part of SickGear.
#
# SickGear 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.
#
# SickGear is distribu... | d incorrect' in response:
msg = u'Invalid username or password for %s. Check settings'
logger.log(msg % self.name, logger.ERROR)
return False
def _do_search(self, search_params, search_mode='eponly', epcount=0, age=0):
results = []
if not self._do_login():
... | k, re.compile('(?i)' + v)) for (k, v) in {'info': 'detail', 'get': 'download'}.items())
for mode in search_params.keys():
for search_string in search_params[mode]:
if isinstance(search_string, unicode):
search_string = unidecode(search_string)
se... |
Alcheri/Plugins | MyPing/config.py | Python | bsd-3-clause | 2,709 | 0.001477 | ###
# Copyright (c) 2004, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditi... | , SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES ( | INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWAR... |
Linhua-Sun/p4-phylogenetics | p4/NexusToken2.py | Python | gpl-2.0 | 5,196 | 0.007313 | import pf
from Var import var
import numpy,string
from Glitch import Glitch
"""A faster version of nextTok(), using memory allocated (once only)
using numpy, and using functions written in C. The slow, pure
python module is NexusToken.py. This version is about twice as fast.
Which one is used is under the control o... | henever CStrings are encountered."""
class NexusToken(object):
def __init__(self, max):
self.max = numpy.array([max], numpy.int32)
self.tokLen = numpy.array([0], numpy.int32)
self.tok = numpy.array(['x'] * int(self.max), 'c')
self.embeddedCommentLen = numpy.array([0], numpy.int32)
| self.embeddedComment = numpy.array(['x'] * int(self.max), 'c')
self.savedCommentLen = numpy.array([0], numpy.int32)
self.filePtr = None
self.nexusToken = pf.newNexusToken(var._nexus_writeVisibleComments,
var._nexus_getP4CommandComments,
... |
lordi/tickmate | analysis/tmkit/linear_regression.py | Python | gpl-3.0 | 2,249 | 0.006225 | import sqlite3
from sklearn import linear_model
import numpy as np
import pandas as pd
import datetime
import sys
conn = sqlite3.connect(sys.argv[1])
c = conn.cursor();
c.execute("select _id, name from tracks")
rows = c.fetchall()
track_names = pd.DataFrame([{'track_name': row[1]} for row in rows])
track_ids = [int... | t "Found {0} tracks.".format(track_cnt)
c.execute("select * from ticks")
last_tick = c.fetchall( | )[-1]
last_day = datetime.date(last_tick[2], last_tick[3], last_tick[4])
def window(day, n=20):
"return a matrix of the last `n` days before day `day`"
tick_date = "date(year || '-' || substr('0' || month, -2, 2) || " + \
"'-' || substr('0' || day, -2, 2))"
max_date = "date('{d.year:04d... |
andela/troupon | troupon/deals/migrations/0003_remove_advertiser_logo.py | Python | mit | 349 | 0 | # -*- coding: utf-8 -*-
from __ | future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('deals', '0002_advertiser_logo'),
]
operations = [
migrations.RemoveField(
model_name='advertiser',
n | ame='logo',
),
]
|
jordanemedlock/psychtruths | temboo/core/Library/Amazon/IAM/UpdateSigningCertificate.py | Python | apache-2.0 | 4,842 | 0.006196 | # -*- coding: utf-8 -*-
###############################################################################
#
# UpdateSigningCertificate
# Changes the status of the specified signing certificate from active to disabled, or vice versa. This action can be used to disable a user's signing certificate as part of a certificate... | ningCertificateInputSet, self)._set_input('ResponseFormat', value)
def set_Status(self, value):
"""
Set the value of the Status input for this Choreo. ((required, string) The status you want to assign to the certificate. Active means the certificate can be used for API calls to AWS, while Inactive m... | Set the value of the UserName input for this Choreo. ((optional, string) Name of the user the signing certificate belongs to.)
"""
super(UpdateSigningCertificateInputSet, self)._set_input('UserName', value)
class UpdateSigningCertificateResultSet(ResultSet):
"""
A ResultSet with methods tailo... |
pombredanne/django-rest-framework-braces | drf_braces/forms/serializer_form.py | Python | mit | 5,024 | 0.001194 | from __future__ import print_function, unicode_literals
import inspect
import six
from django import forms
from django.forms.forms import DeclarativeFieldsMetaclass
from rest_framework import serializers
from .. import fields
from ..utils import (
initialize_class_using_reference_object,
reduce_attr_dict_from... | zer), (
'{}.Meta.serializer must be a subclass of DRF serializer'
''.format(name)
)
class SerializerFormMeta(DeclarativeFieldsMetaclass):
def __new__(cls, name, bases, attrs):
try:
parents = [b for b in bases if issubclass(b, SerializerForm)]
except Name... |
# We are defining SerializerForm itself
parents = None
meta = attrs.pop('Meta', None)
if not parents or attrs.pop('_is_base', False):
return super(SerializerFormMeta, cls).__new__(cls, name, bases, attrs)
attrs['_meta'] = options = SerializerFormOptions(me... |
diofant/diofant | diofant/tests/core/test_operations.py | Python | bsd-3-clause | 1,106 | 0.000904 | import pytest
from diofant import Integer | , SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero | = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
asser... |
aipescience/django-daiquiri | daiquiri/query/__init__.py | Python | apache-2.0 | 55 | 0 | default_app_config = 'da | iquiri.query.apps.QueryCo | nfig'
|
trevorlinton/skia | gm/rebaseline_server/results.py | Python | bsd-3-clause | 22,208 | 0.005629 | #!/usr/bin/python
"""
Copyright 2013 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Repackage expected/actual GM results as needed by our HTML rebaseline viewer.
"""
# System-level imports
import argparse
import fnmatch
import json
import logging
import... | :
"""Returns True if | we should ignore expectations and actuals for a builder.
This allows us to ignore builders for which we don't maintain expectations
(trybots, Valgrind, ASAN, TSAN), and avoid problems like
https://code.google.com/p/skia/issues/detail?id=2036 ('rebaseline_server
produces error when trying to add baselin... |
goddardl/gaffer | python/GafferSceneUI/TransformUI.py | Python | bsd-3-clause | 2,347 | 0.008095 | ##########################################################################
#
# Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | nd/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWAR... | NESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR B... |
seehuhn/wisent | template.py | Python | gpl-2.0 | 10,909 | 0.006508 | # Copyright (C) 2008, 2009 Jochen Voss <voss@seehuhn.de>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | next = True
count = 0
while state != self._halting_state:
if read_next:
try:
| lookahead = tokens.next()
except StopIteration:
return (False,count,state,None)
read_next = False
token = lookahead[0]
#@ IF parser_debugprint
debug = [ ]
for s in stack:
debug.extend([str(s[0]), r... |
HyperloopTeam/FullOpenMDAO | lib/python2.7/site-packages/traits-4.3.0-py2.7-macosx-10.10-x86_64.egg/traits/protocols/__init__.py | Python | gpl-2.0 | 365 | 0 | """Trivial Interfaces and Adaptation from PyProtocols.
This package is a subset of the files from Phillip J. Eby's
PyProtocols package. They are only included here to help remove dependenc | ies
on external packages from the Traits package. The code has been reorganized to
address circular imports that were discovered when explicit relative imports
were added.
"" | "
|
rikpg/django-googlytics | test_settings.py | Python | bsd-3-clause | 510 | 0 | # -*- coding: utf | -8 -*-
#
# Minimum amount of settings to run the googlytics test suite
#
# googlytics options are often overriden during tests
GOOGLE_ANALYTICS_KEY = 'U-TEST-XXX'
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'googlytics_test.sqlite3'
}
}
INSTALLED_A... | ',
'django.contrib.contenttypes',
'googlytics',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'googlytics.context_processors.googlytics',
)
|
OpringaoDoTurno/airflow | tests/utils/test_log_handlers.py | Python | apache-2.0 | 6,367 | 0.001099 | # -*- coding: utf-8 -*-
#
# 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
... | gging_setup(self):
# file task handler is used by default.
logger = logging.getLogger(TASK_LOGGER)
handlers = logger.handlers
self.assertEqual(len(handlers), 1)
handler = handlers[0]
| self.assertEqual(handler.name, FILE_TASK_HANDLER)
def test_file_task_handler(self):
def task_callable(ti, **kwargs):
ti.log.info("test")
dag = DAG('dag_for_testing_file_task_handler', start_date=DEFAULT_DATE)
task = PythonOperator(
task_id='task_for_testing_f... |
Fbonazzi/Scripts | binary/int_to_byte.py | Python | gpl-3.0 | 471 | 0 | #!/usr/bin/env pyt | hon
# Written by Filippo Bonazzi <f.bonazzi@davide.it> 2016
#
# Convert an integer from its decimal representation into its hexadecimal
# representation.
# TODO: add argparse
import sys
import math
s = "".join(sys.argv[1].split())
for c in s:
if c not in "1234567890":
print("Bad string \"{}\"".format(s))
... | ("{0:#x}".format(a))
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | ThirdParty/LocalDev/Hydro-Quebec/PyFoam/ChangeGGIBoundary.py | Python | gpl-3.0 | 7,040 | 0.012642 | """
Application-class that implements pyFoamChangeGGIBoundary.py
Modification of GGI and cyclicGGI interface parameters in
constant/polymesh/boundary file.
Author:
Martin Beaudoin, Hydro-Quebec, 2009. All rights reserved
"""
from PyFoam.Applications.PyFoamApplication import PyFoamApplication
from PyFoam.RunDicti... | .parser.add_option("--shadowPatch",
action="store",
dest="shadowPatch",
default=None,
help='Name of the shadowPatch')
self.parser.add_option("--shadowName",
... | default=None,
help='Name of the shadowPatch. Deprecated. Use --shadowPatch instead')
self.parser.add_option("--zone",
action="store",
dest="zone",
default=None,
... |
splunk/eventgen | splunk_eventgen/lib/eventgentoken.py | Python | apache-2.0 | 23,368 | 0.002225 | # TODO: Handle timestamp generation for modinput and set sample.timestamp properly for timestamp replacement
import datetime
import json
import os
import pprint
import random
import re
import time
import uuid
import six.moves.urllib.error
import six.moves.urllib.parse
import six.moves.urllib.request
from splunk_event... | ime/latestTime not proper
else:
logger.error(
(
"Earliest specifier '%s', value '%s' is greater than latest specifier '%s'"
+ "value '%s' for sample '%s'; will not replace"
... | % (s.earliest, earliestTime, s.latest, latestTime, s.name)
)
return old
# earliest/latest not proper
else:
logger.error(
"Earliest or latest specifier were not set; will not replace"
)
... |
edb1rd/BTC | plugins/trustedcoin.py | Python | gpl-3.0 | 25,459 | 0.003928 | #!/usr/bin/env python
#
# Electrum - Lightweight Bitcoin Client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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 y... | code)
if response.headers.get('content-type') == 'application/json':
re | turn response.json()
else:
return response.text
def get_terms_of_service(self, billing_plan='electrum-per-tx-otp'):
"""
Returns the TOS for the given billing plan as a plain/text unicode string.
:param billing_plan: the plan to return the terms for
"""
... |
Nikola-K/django-template | users/migrations/0001_initial.py | Python | mit | 3,082 | 0.004218 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-02 18:22
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependenc... | ng them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 30 characters or fewer | . Letters, digits and @/./+/-/_ only.', max_length=30, unique=True, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.')], verbose_name='username')),
('first_name', models.CharField(blank=True,... |
lightbulb-framework/lightbulb-framework | examples/test_custom_api_native_example_1.py | Python | mit | 1,286 | 0.012442 | from lightbulb.api.api_nativ | e import LightBulb
import base64
lightbulbapp = LightBulb()
path = "/test/env/bin/lightbulb" #Path to binary
configuration_A = {'TESTS_FILE_TYPE': 'None', 'ALPHABET': '32-57,58-64,65-126', 'SEED_FILE_TYPE': 'FLEX', 'TESTS_FILE': 'None','DFA1_MINUS_DFA2': 'True', 'SAVE': 'False', 'HANDLER': 'None', 'SEED_FILE': '{li... | TESTS_FILE_TYPE': 'None', 'ALPHABET': '32-57,58-64,65-126', 'SEED_FILE_TYPE': 'FLEX', 'TESTS_FILE': 'None','DFA1_MINUS_DFA2': 'True', 'SAVE': 'False', 'HANDLER': 'None', 'SEED_FILE': '{library}/regex/BROWSER/html_p_attribute.y'}
handlerconfig_A = {'WSPORT': '5000','WBPORT': '5080', 'BROWSERPARSE': 'True', 'DELAY': '50'... |
USGSDenverPychron/pychron | pychron/core/ui/qt/keybinding_editor.py | Python | apache-2.0 | 4,794 | 0.001043 | # ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | Y KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==================================================================== | ===========
# ============= enthought library imports =======================
from __future__ import absolute_import
from PySide import QtGui, QtCore
from traits.trait_types import Event
from traitsui.api import View, UItem
from traitsui.basic_editor_factory import BasicEditorFactory
from traitsui.editors.api import T... |
shimarin/discourse-ja-translation | yaml2csv.py | Python | gpl-2.0 | 1,474 | 0.00882 | #!/usr/bin/python2.7
import sys
import csv
import yaml
import codec | s
TO_BE_TRANSLATED_MARK = "***TO BE TRANSLATED***"
def collect(result, node, prefix=None):
for key,value in node.items():
new_prefix = (key if prefix == None else prefix + "." + key)
if isinstance(value, dict):
collect(result, value, new_prefix)
else:
result[new_pr... | lt[row[0]] = row[1].decode("utf-8")
return result
def flatten(namespace=None,old_csv=None):
namespace = "" if namespace == None else namespace + "."
en_src = yaml.load(open("%sen.yml" % namespace))
ja_src = yaml.load(open("%sja.yml" % namespace))
en = {}
collect(en, en_src["en"])
ja = {}
... |
hazelcast/hazelcast-python-client | hazelcast/proxy/pn_counter.py | Python | apache-2.0 | 12,287 | 0.002442 | import functools
import logging
import random
from hazelcast.future import Future
from hazelcast.proxy.base import Proxy
from hazelcast.cluster import VectorClock
from hazelcast.protocol.codec import (
pn_counter_add_codec,
pn_counter_get_codec,
pn_counter_get_configured_replica_count_codec,
)
from hazelca... | ract(self, delta):
"""Subtracts the given value from the curr | ent value and returns the previous value.
Args:
delta (int): The value to subtract.
Returns:
hazelcast.future.Future[int]: The previous value.
Raises:
NoDataMemberInClusterError: if the cluster does not contain any data members.
ConsistencyLostE... |
cprogrammer1994/ModernGL | tests/test_code_style.py | Python | mit | 587 | 0 | import os
import unittest
import moderngl
import pycodestyle
c | lass TestCase(unittest.TestCase):
def test_style(self):
config_file = os.path.join(os.path.dirname(__file__), '..', 'tox.ini')
style = pycodestyle.StyleGuide(config_file=config_file, ignore='E402')
check = style.check_files([
os.path.join(os.path.dirname(__file__), '../moderngl/_... | f __name__ == '__main__':
unittest.main()
|
blackice5514/QuickAp | menu/showSubMenu.py | Python | gpl-3.0 | 20,613 | 0.027119 | import time
from menu.ncolor import *
from menu.showMainMenu import *
from command.shell import *
from write.dnsmasq_write import *
class Sub_Menu():
dns_message = """ you can add a redirect entry in this menu or edit the dnsmasq configuration
file located in""" + color.BLEU + """ '/etc/redirect/dnsmasq.hos... | f the access point is " + color.VERT + "'" + crypt + "'" + color.ENDC)
print("")
print("%53s" % ("current options" + color.ENDC))
print("%61s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%38s" % ("(1) WPA2. | "))
print("%44s" % ("(2) WPA (TKIP)."))
print("%47s" % ("(3) WEP (64 bits)."))
print("%45s" % ("(4) no security."))
print("%44s" % ("(5) main menu.\n"))
while True:
NameChoice = input(color.BLEU + "security > " + color.ENDC)
pwd = ""
... |
fboers/jumeg | examples/connectivity/plot_shuffle_time_slices.py | Python | bsd-3-clause | 2,449 | 0.008575 | """
====================================================
Shuffle channels' data in the time domain and plot.
====================================================
"""
# Author: Eberhard Eich
# Praveen Sripad
#
# License: BSD (3-clause)
import numpy as np
import os.path as op
import mne
from jumeg.j... | shflchanlist)
procdperm = mne.io.Raw(permname, preload=True)
figraw = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick)
axisraw = figraw.gca()
axisraw.set_ylim([-300., -250.])
# procdnr.plot_psd(fmin=0.,fmax=300., color=(0,0,1), picks=shflpick)
figshfl = p... | |
liuguanyu/evparse | lib/hunantv/entry.py | Python | gpl-3.0 | 3,213 | 0.006225 | # -*- coding: utf-8 -*-
# entry.py, part for evparse : EisF Video Parse, evdh Video Parse.
# entry: evparse/lib/hunantv
# version 0.1.0.0 test201505151816
# author sceext <sceext@foxmail.com> 2009EisF2015, 2015.05.
# copyright 2015 sceext
#
# This is FREE SOFTWARE, released under GNU GPLv3+
# please see README.md an... | ut WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Gene | ral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# import
import re
from .. import error
from . import get_base_info
from . import get_video_info
# global vars
# version of thi... |
vhavlena/appreal | netbench/pattern_match/bin/library/bdz.py | Python | gpl-2.0 | 9,513 | 0.01356 | from b_hash import b_hash
from b_hash import NoData
from jenkins import jenkins
from h3_hash import h3_hash
from jenkins import jenkins_fast, jenkins_wrapper
from graph import *
from collections import deque
from bitstring import BitArray
import math
class bdz(b_hash):
"""Class for perfect hash function generated... | )
#If it is not in the queue, put it there
if used[position] == False:
queue.append(position)
queue_list.append(position)
used[posi | tion] = True
self.hyper = hyper
return queue_list
def _found_g(self,v,ed,vi):
"""This function computes value of the g array for given vertex. It uses plus operation."""
s = [self.g[s1] for s1 in self.hyper.get_edge(ed).get_vertices()]
sum1 = sum(s)-s[vi];
self.g[v]... |
FernanOrtega/DAT210x | Module3/notes/histogram_example.py | Python | mit | 446 | 0.008969 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 20:4 | 7:53 2017
@author: fernando
"""
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.read_csv("/home/fernando/CoursePythonDS/DAT210x/Module3/Datasets/wheat.data")
print df.describe()
df[df.groove>5].asymmetry.plot.hist(alpha=0.3, normed=True)
df[df.gr | oove<=5].asymmetry.plot.hist(alpha=0.5, normed=True)
plt.show() |
frankosan/pypers | pypers/steps/mothur/MothurSummarySeqs.py | Python | gpl-3.0 | 3,305 | 0.014221 | from pypers.core.step import Step
from pypers.steps.mothur import Mothur
import os
import json
import re
import glob
class MothurSummarySeqs(Mothur):
"""
Summarizes the quality of sequences in an unaligned or aligned fasta-formatted sequence file.
"""
spec = {
'name' : 'MothurSummarySeqs',
... | 'output_summary',
'type' : 'file',
'value' : '*.summary',
'descr': 'output summary filename'
},
{
| 'name' : 'output_log',
'type' : 'file',
'value' : '*.log.txt',
'descr': 'output summary logfile with tile summary table'
}
]
},
'requirements' : {
'cpus' : '8'
... |
appium/appium | sample-code/python/test/conftest.py | Python | apache-2.0 | 1,108 | 0.002708 | import pytest
import datetime
import os
from helpers import ensure_dir
def pytest_configure(config):
if no | t hasattr(config, 'input'):
current_day = '{:%Y_%m_%d_%H_%S}'.format(datetime.datetime.now())
ensure_dir(os.path.join(os.path.dirname(__file | __), 'input', current_day))
result_dir = os.path.join(os.path.dirname(__file__), 'results', current_day)
ensure_dir(result_dir)
result_dir_test_run = result_dir
ensure_dir(os.path.join(result_dir_test_run, 'screenshots'))
ensure_dir(os.path.join(result_dir_test_run, 'logcat'))
... |
fs714/concurrency-example | asynchronous/py36/asyncio/async_test.py | Python | apache-2.0 | 868 | 0.002304 | # import asyncio
#
# async def compute(x, y):
# print("Compute %s + %s ..." % (x, y))
# await asyncio.sleep(1.0)
# return x + y
#
# async def print_sum(x, y):
# for i in range(10):
# result = await compute(x, y)
# print("%s + %s = %s" % (x, y, result))
#
# loop = asyncio.get_event_loop()... | m):
i = 0
while True:
if i > num:
return
print('{}: Before loop {}'.format(who, i))
await asyncio.sleep(1)
i += 1
loop = asyncio.get_event_loop()
asyncio.ensure_future(display_date('AAA', 4))
asyncio.ensure_future(d | isplay_date('BBB', 6))
loop.run_forever()
|
CCI-MOC/GUI-Backend | core/migrations/0012_remove_null_from_many_many.py | Python | apache-2.0 | 1,573 | 0.006357 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
import django.contrib.auth.models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_atmosphere_user_manager_updat | e'),
]
operations = [
migrations.AlterField(
model_name='allocationstrategy', name='refresh_behaviors', field=models.ManyToManyField(
to='core.RefreshBehavior', blank=True), ), migrations.AlterField(
model_name='allocationstrategy', name='rules_behaviors', field=... | ), migrations.AlterField(
model_name='machinerequest', name='new_machine_licenses', field=models.ManyToManyField(
to='core.License', blank=True), ), migrations.AlterField(
model_name='project', name='applications', field=models.ManyToManyField(
related_name='proje... |
nirmeshk/oh-mainline | vendor/packages/webob/setup.py | Python | agpl-3.0 | 2,150 | 0.00186 | from setuptools import setup
version = '1.4'
testing_extras = ['nose', 'coverage']
docs_extras = ['Sphinx']
setup(
name='WebOb',
version=version,
description="WSGI request and response object",
long_description="""\
WebOb provides wrappers around the WSGI request environment, and an
object to help c... | aster#egg=WebOb-dev>`_ with
``pip install WebOb==dev`` (or ``easy_install WebOb==dev``).
* `WebOb reference <http://docs.webob.org/en/latest/reference.html>`_
* `Bug tracker <https://github.com/Pylons/webob/issues>`_
* `Browse source code <https://github.com/Pylons/webob>`_
* `Mailing list <http://bit.ly/paste-users>`... | us :: 6 - Mature",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Programming Language ::... |
eddie-dunn/pytest-typehints | setup.py | Python | bsd-3-clause | 1,385 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import os
import codecs
from setuptools import setup
def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name | ='pytest-typehints',
version='0.1.0',
author='Edward Dunn Ekelund',
author_email='edward.ekelund@gmail.com',
maintainer='Edward Dunn Ekelund',
maintainer_email='edward.ekelund@gmail.com',
license='BSD-3',
url='https://github.com/eddie-dunn/pytest-typehints',
description='Pytest plugin th... | .2'],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'Topic :: Software Development :: Testing',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Pyth... |
vahidR/test-builder | tests/test_utils.py | Python | gpl-2.0 | 1,040 | 0.005769 | """
Copyright (C) 2014 Vahid Rafiei (@vahid_r)
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... | Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import unittest
from testbuilder.utils import get_version
class TestUtilsModuleFunctions(unittest.TestCase):
""" This is a test skeleton for module-level functions at the utils | module"""
def test_version(self):
self.assertEquals("0.9", get_version(), "The current version should be 0.9")
if __name__ == "__main__":
unittest.main() |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/amqp/serialization.py | Python | agpl-3.0 | 16,315 | 0 | """
Convert between bytestreams and higher-level AMQP types.
2007-11-05 Barry Pederson <bp@barryp.org>
"""
# Copyright (C) 2007 Barry Pederson <bp@barryp.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Fr... | self.input.read(4))[0]
return self.input.read(slen).decode('utf-8')
def r | ead_table(self):
"""Read an AMQP table, and return as a Python dictionary."""
self.bitcount = self.bits = 0
tlen = unpack('>I', self.input.read(4))[0]
table_data = AMQPReader(self.input.read(tlen))
result = {}
while table_data.input.tell() < tlen:
name = table... |
miurahr/translate | translate/storage/poxliff.py | Python | gpl-2.0 | 14,579 | 0.000549 | #
# Copyright 2006-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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 ... | ):
super().setsource(source, sourcelang)
else:
target = self.target
for unit in self.units:
| try:
self.xmlelement.remove(unit.xmlelement)
except ValueError:
pass
self.units = []
for s in source.strings:
newunit = xliff.xliffunit(s)
# newunit.namespace = self.namespace #XX... |
otadmor/Open-Knesset | lobbyists/scrapers/lobbyist.py | Python | bsd-3-clause | 5,096 | 0.002747 | # encoding: utf-8
from bs4 import BeautifulSoup
from okscraper.base import BaseScraper
from okscraper.sources import UrlSource, ScraperSource
from okscraper.storages import ListStorage, DictStorage
from lobbyists.models import LobbyistHistory, Lobbyist, LobbyistData, LobbyistRepresent, LobbyistRepresentData
from perso... | l(), key=lambda represent: represent.id)
if represent_ids != last_represent_ids:
last_lobbyist_data = None
return last_lobbyist_data
def commit(self):
super(LobbyistScraperDictStorage, self).commit()
data = self._data
source_id = data['id']
data['... | lf._get_represents_data(source_id)
full_name = '%s %s' % (data['first_name'], data['family_name'])
q = Lobbyist.objects.filter(source_id=source_id, person__name=full_name)
if q.count() > 0:
lobbyist = q[0]
else:
lobbyist = Lobbyist.objects.create(person=Person.obj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.