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 |
|---|---|---|---|---|---|---|---|---|
TomConlin/dipper | dipper/utils/TestUtils.py | Python | bsd-3-clause | 2,394 | 0.000418 | import logging
import io
from pathlib import Path
from rdflib import URIRef, RDF
from dipper.graph.RDFGraph import RDFGraph
LOG = logging.getLogger(__name__)
class TestUtils:
@staticmethod
def test_graph_equality(turtlish, graph):
"""
:param turtlish: file path or string of triples in turtl... | )
headless_ttl = ''
try:
if Path(turtlish).exists():
headless_ttl = Path(turtlish).read_text() |
else:
raise OSError
except OSError:
if isinstance(turtlish, str):
headless_ttl = turtlish
else:
raise ValueError("turtlish must be filepath or string")
turtle_string = prefixes + headless_ttl
mock_file = io.Str... |
nitzmahone/ansible | test/sanity/code-smell/ansible-requirements.py | Python | gpl-3.0 | 898 | 0.002227 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import sys
def read_file(path):
try:
with open(path, 'r') as f:
return f.read()
except Exception as ex: # pylint: disable=broad-except
print('%s:%d:%d: unable to read required file %... | sible_test/_data/requirements/ansible.txt'
original_requirements = read_file(ORIGINAL_FILE)
vendored_requirements = read_file(VENDORED_COPY)
if original_requirements is not | None and vendored_requirements is not None:
if original_requirements != vendored_requirements:
print('%s:%d:%d: must be identical to %s' % (VENDORED_COPY, 0, 0, ORIGINAL_FILE))
if __name__ == '__main__':
main()
|
henrymp/coursebuilder | modules/dashboard/unit_lesson_editor.py | Python | apache-2.0 | 31,883 | 0.000157 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | ss_name='spli | t-from-main-group')
class CourseOutlineRights(object):
"""Manages view/edit rights for course outline."""
@classmethod
def can_view(cls, handler):
return cls.can_edit(handler)
@classmethod
def can_edit(cls, handler):
return roles.Roles.is_course_admin(handler.app_context)
@c... |
krocat/ToonHA | toon/switch.py | Python | apache-2.0 | 2,141 | 0 | """
Support for Eneco Slimmer stekkers (Smart Plugs).
This provides con | trols for the z-wave smart plugs Toon can control.
"""
impor | t logging
from homeassistant.components.switch import SwitchDevice
import custom_components.toon as toon_main
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Setup discovered Smart Plugs."""
_toon_main = hass.data[toon_main.TOON_HANDLE]
... |
xiaoqiangwang/CSDataQuick | tools/fixup_qtcreator.py | Python | gpl-2.0 | 9,584 | 0.003861 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script re-constucts the Qt Creator installation to include Qt libraries, plugins, QtQuick.
Windows:
|-- bin
| |-- qt.conf -> Prefix=..
| |-- qt dlls
| |-- csdataquick executibles
| |-- csdataquick dlls
| |-- qt-creator executibles... | =True)
parser = argparse.ArgumentParser(description='Fixup Qt and Qt Creator for packaging')
parser.add_argument('--target', required=True, help='target path')
pars | er.add_argument('--qtcreator', help='qt creator path')
parser.add_argument('--qmake', required=True, help='qmake file path')
args = parser.parse_args(sys.argv[1:])
qtcreator_path = args.qtcreator
target_path = args.target
qmake = args.qmake
bin_dir = os.path.join(target_path, 'bin')
lib_dir = os.path.join(target_path... |
Keeper-Security/Commander | unit-tests/helper.py | Python | mit | 1,017 | 0 | from data_vault import VaultEnvironment
class KeeperApiHelper:
_expected_commands = []
_vault_env = VaultEnvironment()
@staticmethod
def communicate_expect(actions):
# type: (list) -> None
KeeperApiHelper._expected_commands.clear()
KeeperApiHelper._expected_commands.extend(act... | 'result_code': '',
'message': ''
}
action = KeeperApiHelper._expected_commands.pop(0)
if callable(action):
props = act | ion(request)
if type(props) == dict:
rs.update(props)
return rs
if type(action) == str:
if action == request['command']:
return rs
raise Exception()
|
aleksclark/replfs | nosetests/basic_operations_tests.py | Python | bsd-3-clause | 469 | 0.004264 | import os
import shutil
class BasicOperations_TestClass:
TEST_ROOT =' __test_root__'
def setUp(self):
self.regenerate_root
print(self.TEST_ROOT)
assert os.path.isdir(self.TEST_ROOT)
def te | arDown(self):
return True
def test_test(self):
assert self.bar == 1
def regenerate_root(self):
if os.path.isdir(self.TEST_ROOT):
| shutil.rmtree(self.TEST_ROOTT)
os.makedirs(self.TEST_ROOT)
|
Nikea/VisTrails | vistrails/packages/rpy/__init__.py | Python | bsd-3-clause | 2,002 | 0.021978 | ################################################### | ############################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rig | hts reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "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, ... |
ttm/socialLegacy | tests/legacy/testAnim2.py | Python | mit | 714 | 0.004202 | # Import everything needed to edit video clips
from moviepy.edit | or import *
# Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60
clip = VideoFileClip("myHolidays.mp4").subclip(50,60)
# Reduce the audio volume (volume x 0.8)
clip = clip.volumex(0.8)
# Generate a text clip. You can customize the font, color, etc.
txt_clip = TextClip("My Holidays 2013",fontsize=70,color... | video clip
video = CompositeVideoClip([clip, txt_clip])
# Write the result to a file (many options available !)
video.write_videofile("myHolidays_edited.webm")
|
nmarley/dash | test/functional/bip9-softforks.py | Python | mit | 12,924 | 0.004643 | #!/usr/bin/env python3
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP 9 soft forks.
Connect to a single node.
regtest lock-in with 108/144 block signalling
activation a... | _bip9_status(bipName)['statistics']['count'], 0)
tmpl = self.nodes[0].getblocktemplate({})
assert(bipName not in tmpl['rules'])
assert_equal(tmpl['vbavailable'][bipName], bitno)
assert_equal(tmpl['vbrequired'], 0)
assert(tmpl['version'] & activated_version)
# Test 3
... | cks(57, activated_version) # 0x20000001 (signalling ready)
test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not)
test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
test_blocks = self.generate_blocks(10, 4, test_bl... |
hammerhorn/hammerhorn-jive | igo/cjh/files.py | Python | gpl-2.0 | 2,267 | 0.003088 | #!/usr/bin/python
import glob, os
from cjh.cli import Cli, ListPrompt
from cjh.lists import ItemList
class Fileman(object):
@classmethod
def pwd(cls, getstr=False):
"""
Emulate 'pwd' command
"""
string = os.getcwd()
if getstr:
return string
else: pr... | r_lis | t) + len(file_list) + 1 > Cli.height():
Cli.less(string)
else: Cli.write(string.strip())
else:
return dir_list + file_list
|
peri-source/peri | peri/runner.py | Python | mit | 29,237 | 0.001163 | """
Basically I'm trying to cover 4 options, one of each:
(Previously featured state?, Use previous positions?)
---------------------------------------------------------
(no, no) = get_initial_featuring
(yes, no) = get_particle_featuring
(yes, yes) = translate_featuring
(no, yes) = f... | emaker, feature_rad, actual_rad=None,
im_name=None, tile=None, invert=True, desc='', use_full_path=False,
featuring_params | ={}, statemaker_kwargs={}, **kwargs):
"""
Completely optimizes a state from an image of roughly monodisperse
particles.
The user can interactively select the image. The state is periodically
saved during optimization, with different filename for different stages
of the optimization.
Parame... |
maurov/xraysloth | sloth/collects/datagroup_xan.py | Python | bsd-3-clause | 767 | 0.009126 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""DataGroupXanes: work with XANES data sets
============================================
- DataGroup
- DataGroup1D
- DataGroupXanes
"""
from .datagroup import MODNAME
from .datagroup1D import DataGroup1D
class DataGroupXanes(DataGroup1D):
"""DataGroup for XANES... | e):
"""utility to perform wrapped operation | s on a list of XANES data
groups"""
return DataGroupXanes(kwsd=kwsd, _larch=_larch)
def registerLarchPlugin():
return (MODNAME, {'datagroup_xan' : datagroup_xan})
if __name__ == '__main__':
pass
|
quattor/aquilon | lib/aquilon/aqdb/model/address_assignment.py | Python | apache-2.0 | 6,715 | 0.000596 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | ('dns_records', 'fqdn')
network = relation(Network, innerjoin=True,
backref=backref('assignments', passive_deletes=True,
order_by=[ip]))
__table_args__ = (UniqueConstraint(interface_id, ip),
UniqueConstraint(interface_id, labe... | 'polymorphic_identity': 'standard'}
@property
def logical_name(self):
"""
Compute an OS-agnostic name for this interface/address combo.
BIG FAT WARNING: do _NOT_ assume that this name really exist on the
host!
There are external systems like DSDB that... |
johnbelamaric/themis | vendor/github.com/grpc-ecosystem/grpc-opentracing/python/examples/trivial/trivial_client.py | Python | apache-2.0 | 1,218 | 0 | from __future__ import print_function
import time
import argparse
import grpc
from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel
import command_line_pb2
def run():
parser = argparse.ArgumentParser()
parser.ad... | 'param': 1,
},
'logging': True,
},
service_name='trivial-client')
tracer = config.initialize_tracer()
tracer_interceptor = open_tracing_client_interceptor(
tracer, log_payloads=args.log_payloads)
channel = grpc.insecure_channel('localhost:50051')
cha... | Hello, hello'))
print(response.text)
time.sleep(2)
tracer.close()
time.sleep(2)
if __name__ == '__main__':
run()
|
knuu/competitive-programming | yukicoder/yuki279.py | Python | mit | 91 | 0 | from collections im | port Counter
c = Counter(input())
print(min(c['t'], c['r'], c['e']//2))
| |
AndroidOpenDevelopment/android_external_chromium_org | build/linux/install-arm-sysroot.py | Python | bsd-3-clause | 2,718 | 0.008462 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script to install ARM root image for cross building of ARM chrome on linux.
This script can be run manually but is more often ru... | y designed for building trusted NaCl code. The image
will normally need to be rebuilt every time chrome's build dependancies are
changed.
Steps to rebuild the arm sysroot image:
- cd $SRC/native_client
- | ./tools/trusted_cross_toolchains/trusted-toolchain-creator.armel.precise.sh \
UpdatePackageLists
- ./tools/trusted_cross_toolchains/trusted-toolchain-creator.armel.precise.sh \
BuildJail $SRC/out/arm-sysroot.tar.gz
- gsutil cp -a public-read $SRC/out/arm-sysroot.tar.gz \
nativeclient-archive2/toolchain/$NA... |
samihuc/PolyglotDB | polyglotdb/corpus/__init__.py | Python | mit | 328 | 0 | from .context import CorpusContext
from .audio import AudioContext
from .importable import ImportContext
from .lexical import LexicalContext
from .pause | import PauseContext
from .utterance import UtteranceContext
from .structured import StructuredContext
from .syllabic import SyllabicC | ontext
from .spoken import SpokenContext
|
iakov/RHVoice | site_scons/site_tools/newlines.py | Python | gpl-3.0 | 816 | 0.035539 | from SCons.Script import *
def exists(env):
return (env["PLATFORM"]=="win32")
def ConvertNewlines(target,source,env):
for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
... | ne
def generate(env):
env["BUILDE | RS"]["ConvertNewlines"]=Builder(action=ConvertNewlines,suffix=".txt")
env["BUILDERS"]["ConvertNewlinesB"]=Builder(action=ConvertNewlinesB,suffix=".txt")
|
City-of-Helsinki/smbackend | services/views.py | Python | agpl-3.0 | 1,229 | 0 | import requests
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf impo | rt csrf_exempt
from django.views.decorators.http import require_http_methods
@csrf_exempt
@require_http_methods(["POST"])
def post_service_request(request):
payload = request.POST.copy()
outgoing = payload.dict()
if outgoing.get("internal_feedback", False):
if "internal_feedback" in outgoing:
... | s.OPEN311["API_KEY"]
outgoing["api_key"] = api_key
url = settings.OPEN311["URL_BASE"]
session = requests.Session()
# Modify parameters for request in case of City of Turku
if "smbackend_turku" in settings.INSTALLED_APPS:
outgoing.pop("service_request_type")
outgoing.pop("can_be_publ... |
dimagi/commcare-hq | corehq/apps/ota/tests/test_claim.py | Python | bsd-3-clause | 4,929 | 0.00142 | from uuid import uuid4
from django.test import TestCase
from casexml.apps.case.clean | up import claim_case, get_first_claim
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.util import post_case_blocks
from corehq.apps.case_search.models import CLAIM_CASE_TYPE
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.ot | a.utils import get_restore_user
from corehq.apps.users.models import CommCareUser
from corehq.form_processor.exceptions import CaseNotFound
from corehq.form_processor.models import CommCareCase
DOMAIN = 'test_domain'
USERNAME = 'lina.stern@ras.ru'
PASSWORD = 'hemato-encephalic'
# https://en.wikipedia.org/wiki/Lina_Ste... |
hvdwolf/pyExifToolGUI | scripts/petgfunctions.py | Python | gpl-3.0 | 115,680 | 0.00593 | # -*- coding: utf-8 -*-
# petgfunctions.py - This python "helper" script holds a lot of functions
# Copyright (c) 2012-2014 Harry van der Wolf. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public Licence as published
# by... | toolprog) or ("Exiftool.exe" in self.exiftoolprog) or not self.exiftoolprog:
#self.exiftool_dir = os.path.join(self.realfile_dir, "exiftool", "exiftool.exe")
#self.exiftoolprog = self.exiftool_dir + "\exiftool.exe"
| if not os.path.isfile(self.exiftoolprog):
configure_message = "exiftool is missing or incorrectly configured in Preferences!\n"
configure_message += "This tool is an absolute must have!\nPlease set the correct location or install exiftool first.\n\n"
configure_message +... |
Faraaz54/python_training_problems | basic_python/write_file.py | Python | mit | 123 | 0.00813 | t | ext = 'this is a sample file\nnew line'
savefile = open('newtext', 'w')
savefile.write(text)
savefile | .close()
|
dersphere/plugin.video.moviemazer | default.py | Python | gpl-2.0 | 19,585 | 0.00337 | # Moviemazer XBMC Addon
# written by Tristan Fischer (sphere)
#
# If you have suggestions or problems: write me.
#
# Mail: sphere@dersphere.de
#
# Special Thanks to the website www.moviemaze.de
# Import Python stuff
import urllib
import urllib2
import re
import os
import sys
import time
from shutil import copyfile
#... | chtrailer = re.compile('generateDownloadLink\("([^"]+_([0-9]+)\.(?:mov|mp4)\?down=1)"\)').findall(languageblock)
| for trailerurl, resolution in matchtrailer:
trailer = {'trailername': trailername,
'duration': duration,
'language': language,
'resolution': resolution,
'date': date,
... |
Dudy/newsletterman | src/EmailHandlerV1.py | Python | apache-2.0 | 1,058 | 0.014178 | #!/usr/bin/env python
import webapp2
import logging
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from MailMessage import MailMessage
# the email domain of this app is @pomis-newsletterman.appspotmail.com
class EmailHandlerV1(InboundMailHandler):
... | ndb.Model.allocate_ids(size = 1, parent = service_key)[0]
mail_message_key = ndb.Key(MailMessage, new_id, parent = service_key)
persistent_mail_message = MailMessage(parent = mail_message_key, mime_message = mime_message)
| persistent_mail_message.put()
app = webapp2.WSGIApplication([EmailHandlerV1.mapping()], debug=True)
|
DylanMcCall/rhythmbox-songinfo-context-menu | plugins/artsearch/musicbrainz.py | Python | gpl-2.0 | 4,454 | 0.014594 | # -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*-
#
# Copyright (C) 2009 Jonathan Matthew <jonathan@d14n.org>
#
# This program is free softwar | e; 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, or (at your option)
# any later version.
#
# The Rhythmbox authors hereby grant permission for non-GPL compatible
# GStreamer plugins to be used and distribut... | ou may extend this exception to your version of the code, but you are not
# obligated to do so. If you do not wish to do so, delete this exception
# statement from your version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHAN... |
elainenaomi/sciwonc-dataflow-examples | dissertation2017/Experiment 2/instances/11_2_wikiflow_1sh_1s_annot/sessioncompute_2/SessionCompute_2.py | Python | gpl-3.0 | 2,784 | 0.001796 | #!/usr/bin/env python
from sciwonc.dataflow.DataStoreClient import DataStoreClient
import ConfigDB_SessionCompute_2
import pprint
# connector and config
client = DataStoreClient("mongodb", ConfigDB_SessionCompute_2)
config = ConfigDB_SessionCompute_2
# according to config
dataList = client.getData() # return an array... | ECONDS
else:
if float(doc["timestamp"]) <= end_time:
end_time = float(doc["timestamp"]) + ONE_HOUR_IN_SECONDS
| count += 1
else:
new_doc = {}
new_doc["start time"] = start_time
new_doc["end time"] = end_time
new_doc["duration"] = (end_time - start_time)
new_doc["editio... |
RyanHope/AutobahnPython | examples/asyncio/wamp/rpc/decorators/frontend.py | Python | mit | 2,365 | 0 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# 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 with... |
res = yield from self.call(proc, 2, 3)
print("{}: {}".format(proc, res))
except Exception as e:
print("Something went wrong: {}".format(e))
self.leave()
| def onDisconnect(self):
asyncio.get_event_loop().stop()
if __name__ == '__main__':
runner = ApplicationRunner(
environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"),
u"crossbardemo",
debug=False, # optional; log even more details
)
runner.run(Component)
|
timpalpant/KaggleTSTextClassification | scripts/plot_feature_distributions.py | Python | gpl-3.0 | 2,179 | 0.005048 | #!/usr/bin/env python
'''
Plot distribution of each feature,
conditioned on its bfeature type
'''
import argparse
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from common import *
from information import utils
from scipy.stats import itemfreq
nbins = 100
def opts():
parse... | ate(cfs.T):
print "...ffeature %d" % j
fi | g = plt.figure()
h = np.zeros(nbins)
not_nan = f[np.logical_not(np.isnan(f))]
f_min = not_nan.min()
f_max = not_nan.max()
x = np.linspace(f_min, f_max, nbins)
dx = (f_max - f_min) / nbins
for idx in indices:
h_new, bins = np.histogram(f[idx], range=(f_... |
eljost/pysisyphus | tests_staging/test_matched_rmsd/test_matched_rmsd.py | Python | gpl-3.0 | 816 | 0 | #!/usr/bin/env python3
import os
from pathlib import Path
import numpy as np
from pysisyphus.helpers import geom_from_xyz_file
from pysisyphus.sto | castic.align import matched_rmsd
THIS_DIR = Path(os.path.dirname(os.path.realpath(__file__)))
def test_matched_rmsd():
| geom1 = geom_from_xyz_file(THIS_DIR / "eins.xyz")
# Calling with the identical geometries should return RMSD of 0.
min_rmsd, (geom1_matched, geom2_matched) = matched_rmsd(geom1, geom1)
np.testing.assert_allclose(min_rmsd, 0.0, atol=1e-10)
np.testing.assert_allclose(geom1_matched.coords, geom2_matched... |
nansencenter/nansat | nansat/tests/test_nansat.py | Python | gpl-3.0 | 34,081 | 0.00355 | # ------------------------------------------------------------------------------
# Name: test_nansat.py
# Purpose: Test the Nansat class
#
# Author: Morten Wergeland Hansen, Asuka Yamakawa, Anton Korosov
#
# Created: 18.06.2014
# Last modified:24.08.2017 14:00
# Copyright: (c) NERSC
# Licence... | matplotlib
import matplotlib.pyplot as plt
except ImportError:
MATPLOTLIB_IS_INSTALLED = False
else:
MATPLOTLIB_IS_INSTALLED = True
from nansat import Nansat, Domain, NSR
from nansat.utils import gdal
import nansat.nansat
from nansat.exceptions import NansatGDALError, WrongMapperError, NansatReadError
fr... | tBase):
def test_open_gcps(self):
n = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
self.assertEqual(type(n), Nansat)
self.assertEqual(n.vrt.dataset.GetProjection(), '')
self.assertTrue((n.vrt.dataset.GetGCPProjection().startswith('GEOGCS["WGS 84",')))
... |
dnarvaez/sourcestamp | setup.py | Python | apache-2.0 | 1,161 | 0 | # Copyright 2013 Daniel Narvaez
#
# 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 writi... | se :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 2",
"Topic :: Software Development :: Build Tools"]
setup(name="sourcestamp",
version="0.1",
description="Compute timestamp for a source code tree",
author="Daniel Narvaez",
author_... | ez/sourcestamp",
classifiers=classifiers,
ext_modules=[Extension("sourcestamp", ["src/sourcestamp.c"])])
|
tseaver/google-cloud-python | talent/google/cloud/talent_v4beta1/gapic/tenant_service_client_config.py | Python | apache-2.0 | 1,782 | 0 | config = {
"interfaces": {
"google.cloud.talent.v4beta1.TenantService": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
"init... |
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"UpdateTenant": {
"timeout_millis": 60000,
| "retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"DeleteTenant": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
}... |
yamstudio/Codeforces | 200/281A - Word Capitalization.py | Python | gpl-3.0 | 43 | 0 | x = raw_input()
print x[0].upper() | + x[1:]
| |
ruuk/script.web.viewer2 | lib/webviewer/bs4/element.py | Python | gpl-2.0 | 61,200 | 0.001307 | import collections
import re
import sys
import warnings
from bs4.dammit import EntitySubstitution
DEFAULT_OUTPUT_ENCODING = "utf-8"
PY3K = (sys.version_info[0] > 2)
whitespace_re = re.compile("\s+")
def _alias(attr):
"""Alias one attribute name to another for backward compatibility"""
@property
def alias... | ne of these objects.
"""
def __new__(cls, original_value):
obj = unicode.__new__(cls, original_value)
obj.original_value = original_value
return obj
def encode(self, e | ncoding):
return encoding
class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution):
"""A generic stand-in for the value of a meta tag's 'content' attribute.
When Beautiful Soup parses the markup:
<meta http-equiv="content-type" content="text/html; charset=utf8">
The value of t... |
filias/django | tests/forms_tests/field_tests/test_uuidfield.py | Python | bsd-3-clause | 971 | 0.00103 | from __future__ import unicode_literals
import uuid
from django.forms import UUIDField, ValidationError
from django.test import SimpleTestCase
class UUIDFieldTest(SimpleTestCase):
def test_uuidfield_1(self):
field = UUIDField()
value = field.clean('550e8400e29b41d4a716446655440000')
sel... | d4a716446655440000'))
def test_uuidfield_2(self):
field = UUIDField(required=False)
value = field.clean('')
self.assertEqual(value, None)
def test_uuidfield_3(self):
field = UUIDField()
with self.assertRaises(ValidationError) as cm:
field.clean('550e8400')
... | 4(self):
field = UUIDField()
value = field.prepare_value(uuid.UUID('550e8400e29b41d4a716446655440000'))
self.assertEqual(value, '550e8400e29b41d4a716446655440000')
|
xiaoslzhang/pyyingyu | yingyu/yingyu_baidu.py | Python | apache-2.0 | 1,682 | 0.003567 | # coding=utf-8
import asyncio
import random
import json
import hashlib
import aiohttp
import as | ync_timeout
import sys
class BaiduTranslate:
lang_auto = 'auto'
lang_zh = 'zh'
| lang_en = 'en'
timeout = 20
api_addr = 'http://fanyi-api.baidu.com/api/trans/vip/translate'
def __init__(self, loop=None):
self.appid = '20171009000086968'
self.secret = 'vZ36FjnZ91FoLJwe5NrF'
if loop is None:
self.async = False
self.loop = asyncio.get_event... |
realizeapp/realize-core | plugins/fitbit/models.py | Python | agpl-3.0 | 1,974 | 0.007092 | from core.plugins.lib.proxies import MetricProxy, SourceProxy
from core.plugins.lib.models import PluginDataModel
from core.plugins.lib.fields import Field, ListField, DateTimeField, FloatField, IntegerField
from core.plugins.lib.scope import Scope, ZonePerm, BlockPerm
class BaseFitbitModel(PluginDataModel):
metri... | tric_proxy = MetricProxy(name="calories")
class WaterModel(BaseFitbitModel):
metric_proxy = MetricProxy(name="water")
MODEL_DICT = {
"activities/steps": StepModel,
"activities/distance": DistanceModel,
"sleep/timeInBed": TimeInBedModel,
"sleep/minutesAsleep": MinutesAsleepModel,
"body/weight":... | ncyModel,
"activities/activityCalories": ActivityCaloriesModel,
"sleep/startTime": SleepStartTimeModel,
"foods/log/caloriesIn": CaloriesInModel,
"activities/calories": CaloriesModel,
"foods/log/water": WaterModel
}
|
carlgao/lenga | images/lenny64-peon/usr/share/python-support/python-mysqldb/MySQLdb/cursors.py | Python | mit | 16,782 | 0.003158 | """MySQLdb Cursors
This module implements Cursors of various types for MySQLdb. By
default, MySQLdb uses the Cursor class.
"""
import re
insert_values = re.compile(r"\svalues\s*(\(((?<!\\)'.*?\).*(?<!\\)?'|.)+?\))", re.IGNORECASE)
from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \
Databa... | is the parameter above and n is the position of t | he parameter
(from zero). Once all result |
dannybrowne86/django-holidays | holidays/holidays/admin.py | Python | mit | 720 | 0.009722 | from django.contrib import admin
from holidays.models import (Holiday, StaticHoliday,
NthXDayHoliday, NthXDayAfterHoliday, CustomHoliday)
class HolidayAdmin(admin.ModelAdmin):
pass
class StaticHolidayAdmin(admin.ModelAdmin):
pass
class NthXDayHolidayAdmin(adm | in.ModelAdmin):
pass
class NthXDayAfterHolidayAdmin(admin.ModelAdmin):
pass
class CustomHolidayAdmin(admin.ModelAdmin):
pass
admin.site.register(Holiday, HolidayAdmin)
admin.site.register(StaticHoliday, StaticHolidayAdmin)
admin.site.register(NthXDayHoliday, NthXDayHolidayAdmin)
admin.site.re... | Admin)
admin.site.register(CustomHoliday, CustomHolidayAdmin)
|
potatolondon/centaur | views.py | Python | bsd-3-clause | 4,150 | 0.002892 | from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from django.utils.importlib import import_module
from djangae.core.pa... | xt import db
from google.appengine.ext.deferred import defer
from .models import Error, Event
import calendar
def get_permission_decorator():
if getattr(settings, 'CENTAUR | _PERMISSION_DECORATOR', None):
module, decorator = settings.CENTAUR_PERMISSION_DECORATOR.rsplit('.', 1)
return getattr(import_module(module), decorator)
return user_passes_test(lambda u: u.is_superuser)
permission_decorator = get_permission_decorator()
def timestamp(datetime):
""" Returns UTC... |
greenoaktree/pfp | pfp/native/__init__.py | Python | mit | 1,639 | 0.026236 | import functools
import pfp.interp
def native(name, ret, interp=None, send_interp=False):
"""Used as a decorator to add the decorated function to the
pfp interpreter so that it can be used from within scripts.
:param str name: The name of the function as it will be exposed in template scripts.
:param pfp.fields.... | terp._int3:
interp.debugger = PfpDbg(interp)
interp.debugger.cmdloop()
"""
def native_decorator(func):
@functools.wraps(func)
def native_wrapper(*args, **kwargs):
return func(*args, **kwargs)
pfp.interp.PfpInterp.add_native(name, func, ret, interp=interp, send_interp=send_interp)
return native_w... | pfp.interp.PfpInterp.add_predefine(template)
|
sanja7s/SR_Twitter | src_graph/plot_degree_assortativity.py | Python | mit | 1,447 | 0.032481 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
plot the results from the files igraph_degree_assort_study and degree_assortativity
'''
from igraph import *
import os
import numpy as np
import matplotlib.pyplot as plt
#########################
IN_DIR = '/home/sscepano/Projects7s/Twitter-workspace/ALL_SR'
img_out_pl... | '7MODeg_assort_study.weighted_edge_list', 'r')
DA = []
TH = []
for line in f:
if line.startswith('stats for'):
th = float(line.split()[-1])
TH.append(th)
if line.startswith('The network is'):
da = float(line.split()[-1])
DA.append(da)
th_last = th
f2 = open('plot_da_0.2.txt', 'r')
for line in ... | .tab', 'w')
for i in range(len(TH)):
f3.write(str(TH[i]) + '\t' + str(DA[i]) + '\n')
return TH, DA
def plot_DA(xaxis, da):
x = np.array(xaxis)
y = np.array(da)
plt.plot(x, y, 'c')
plt.grid(True)
plt.title('SR network')
#plt.legend(bbox_to_anchor=(0, 1), bbox_transform=plt.gcf().transFigure)
plt.ylabel('d... |
int3l/dungeons-and-pythons | main.py | Python | mit | 155 | 0.019355 | from dung | eon.dungeon import Dungeon
def main():
testdungeon = Dungeon('level1.txt')
p | rint(testdungeon)
if main.__name__ == '__main__':
main() |
oubiga/respect | respect/main.py | Python | bsd-3-clause | 2,305 | 0.000434 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from getpass import getpass
from datetime import datetime
import pprint
from docopt import docopt
import requests
from .spelling import spellchecker
from .dispatch import dispatch
from .utils import login, validate_usernam... | rmation.
-r <rep> --repos <rep> Number of repositories [default: ].
-f <foll> --followers <foll> Number of followers [default: ].
-l <lang> | --language <lang> Language name [default: ].
'''
args = docopt(parse_respect_args.__doc__, argv=args)
return args
def main():
"""
Main entry point for the `respect` command.
"""
args = parse_respect_args(sys.argv[1:])
if validate_username(args['<username>']):
print("p... |
mrcslws/nupic.research | src/nupic/research/frameworks/pytorch/hooks/hook_manager.py | Python | agpl-3.0 | 5,818 | 0.001375 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | er unregister
# hooks through these handles.
self._hook_handles = tracked_vals[1]
# These are the filtered modules that | will be tracked.
self.tracked_modules = tracked_vals[2]
# Keep track of whether tracking is on.
self._tracking = False
@property
def tracking(self):
return self._tracking
def __enter__(self):
"""Start tracking when `with` is called."""
self.start_tracking(... |
Kotaimen/georest | georest/view/utils.py | Python | bsd-2-clause | 1,423 | 0.000703 | # -*- encoding: utf-8 -*-
__author__ = 'pp'
__date__ = '6/25/14'
"""
georest.view.utils
~~~~~~~~~~~~~~~~~
helper/mixin things for views
"""
import sys
from functools import wraps
from flask import request
from .exceptions import InvalidRequest
from ..geo import GeoException
def get_json_content():
... | request.if_match)
return etag
def catcher(f):
"""catching uncatched errors, and filling the traceback"""
@wraps(f)
def decorator(*args, **kwargs):
try:
return f(*args, **kwargs)
except GeoException as e:
if not e.traceback:
e.traceback = ... | return decorator
|
joe-eklund/cs460 | bene/lab2/src/transfer.py | Python | gpl-3.0 | 4,724 | 0.013124 | import sys
from sim import Sim
from node import Node
from link import Link
from transport import Transport
from tcp import TCP
from network import Network
import optparse
import os
import subprocess
class AppHandler(object):
def __init__(self,filename, directory):
self.filename = filename
self.di... | int
if not result:
print "File transfer correct!"
else:
print "File transfer failed. Here is the diff:"
print
print result
sys.exit()
def run(self):
# parameters
Sim.scheduler.reset()
Sim.set_debug('AppHandler')
... | up routes
n1 = net.get_node('n1')
n2 = net.get_node('n2')
n1.add_forwarding_entry(address=n2.get_address('n1'),link=n1.links[0])
n2.add_forwarding_entry(address=n1.get_address('n2'),link=n2.links[0])
# setup transport
t1 = Transport(n1)
t2 = Transport(n2)
... |
SRabbelier/Melange | thirdparty/google_appengine/google/net/proto/ProtocolBuffer.py | Python | apache-2.0 | 14,205 | 0.017247 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ise ProtocolBufferEncodeError, '\n\t'.join(dbg)
self.OutputUnchecked(e)
return
def OutputUnchecked(self, e):
raise AbstractMethod
def OutputPartial(self, e):
raise AbstractMethod
def Parse(self, d):
self.Clear()
self.Merge(d)
return
def Merge(self, d):
self.TryMer | ge(d)
dbg = []
if not self.IsInitialized(dbg):
raise ProtocolBufferDecodeError, '\n\t'.join(dbg)
return
def TryMerge(self, d):
raise AbstractMethod
def CopyFrom(self, pb):
if (pb == self): return
self.Clear()
self.MergeFrom(pb)
def MergeFrom(self, pb):
raise AbstractMethod... |
ruiminshen/yolo-tf | parse_darknet_yolo2.py | Python | lgpl-3.0 | 6,342 | 0.002841 | """
Copyright (C) 2017, 申瑞珉 (Ruimin Shen)
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, either version 3 of the License, or
(at your option) any later version.
This program is distributed i... |
import pandas as pd
import tensorflow as tf
import model.yolo2.inference as inference
import utils
def transpose_weights(weights, num_anchors):
ksize1, ksize2, channels_ | in, _ = weights.shape
weights = weights.reshape([ksize1, ksize2, channels_in, num_anchors, -1])
coords = weights[:, :, :, :, 0:4]
iou = np.expand_dims(weights[:, :, :, :, 4], -1)
classes = weights[:, :, :, :, 5:]
return np.concatenate([iou, coords, classes], -1).reshape([ksize1, ksize2, channels_in,... |
polypmer/scrape | new-york-times/nytimes-scrape.py | Python | mit | 1,833 | 0.004364 | model_search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.response-format?" + \
"[q=search term&" + \
"fq=filter-field:(filter-term)&additional-params=values]" + \
"&api-key=9key"
"""http://api.nytimes.com/svc/search/v2/articlesearch.json?q=terrorism+OR+t... | ggressive for looping in order to overcome the ten article limit. instead search each key word PER JOUR, and then concat the jsons into a nice pandas dataframe, and then eventually a csv.
"""
months_list = ["%.2d" % i for i in range(1,2)]
days_list = ["%.2d" % i for i in range(1,32)]
json_files = []
print(months_ | list)
for x in months_list:
month_s = x
month_e = x
for y in days_list:
day_s = y
day_e = str(int(y)+1).zfill(2)
year_s = "1990"
year_e = "1990"
start = year_s + month_s + day_s
end = year_e + month_e + day_e
dates = "&begin_date="+start+"&end_date="+e... |
danielquinn/paperless | src/documents/templatetags/customisation.py | Python | gpl-3.0 | 865 | 0 | import os
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag()
def custom_css():
theme_path = os.path.join(
settings.MEDIA_ROOT,
"overrides.css"
)
| if os.path.exists(theme_path):
return mark_safe(
'<link rel="stylesheet" type="text/css" href="{}" />'.format(
os.path.join(set | tings.MEDIA_URL, "overrides.css")
)
)
return ""
@register.simple_tag()
def custom_js():
theme_path = os.path.join(
settings.MEDIA_ROOT,
"overrides.js"
)
if os.path.exists(theme_path):
return mark_safe(
'<script src="{}"></script>'.format(
... |
queirozfcom/spam-filter | case3_naive_normal.py | Python | mit | 8,514 | 0.009396 | import numpy as np
import scipy.stats as stats
import sys
# lib eh a nossa biblioteca criada para este trabalho
import lib.naive_bayes as nb
import lib.preprocessing as prep
import lib.validation as valid
import lib.normalization as normal
from config.constants import *
def case3(output=True):
accuracy_in_eac... | precision_spam = number of correctly evaluated instances as spam/
# number of spam instances
#
#
# in order to avoid divisions by zero in case nothing wa | s found
if(is_spam == 0):
precision_spam = 0
else:
precision_spam = correctly_is_spam/is_spam
#recall_spam = number of correctly evaluated instances as spam/
# number of evaluated instances como spam
#
#
# in order to avoid divisio... |
hryamzik/ansible | lib/ansible/modules/packaging/os/rhsm_repository.py | Python | gpl-3.0 | 7,912 | 0.00316 | #!/usr/bin/python
# Copyright: (c) 2017, Giovanni Sciortino (@giovannisciortino)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | diff_before += "Repository '%s' is enabled for this system\n" % repo['id']
diff_after += "Repository '%s' is disabled for this system\n" % repo['id']
results.append("Repository '%s' is disabled for this system" % repo['id'])
rhsm_arguments += ['--disable',... | diff_before += "Repository '%s' is disabled for this system\n" % repo['id']
diff_after += "Repository '%s' is enabled for this system\n" % repo['id']
results.append("Repository '%s' is enabled for this system" % repo['id'])
rhsm_arguments += ['--ena... |
rtnpro/test-your-code | test_your_code/examples/factorial/test_factorial.py | Python | gpl-2.0 | 386 | 0.005181 | im | port u | nittest
from factorial import fact
class TestFactorial(unittest.TestCase):
"""
Our basic test class
"""
def test_fact(self):
"""
The actual test.
Any method which starts with ``test_`` will considered as a test case.
"""
res = fact(5)
self.assertEqual(re... |
funkring/fdoo | addons-funkring/at_account/wizard/invoice_attachment_wizard.py | Python | agpl-3.0 | 2,242 | 0.005352 | # -*- coding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | uid, ids[0])
invoice_id = util.active_id(context, "account.invoice")
if not invoice_id:
raise osv.except_osv(_("Error!"), _("No invoice found"))
report_obj = self.pool.get("ir.actions.report.xml")
data=base64.decodestring(wizard.document)
data = report_aeroo.fixPdf... | id, "account.invoice", invoice_id, report_name="account.report_invoice", datas=base64.encodestring(data), context=context, origin="account.invoice.attachment.wizard"):
raise osv.except_osv(_("Error!"), _("Unable to import document (check if invoice is validated)"))
return { "type" : "ir.actions.act_... |
andreamartire/gmpy | test3/gmpy_test_thr.py | Python | lgpl-3.0 | 3,614 | 0.010238 | # partial unit test for gmpy2 threaded mpz functionality
# relies on Tim Peters' "doctest.py" test-driver
import gmpy2 as _g, doctest, sys, operator, gc, queue, threading
from functools import reduce
__test__={}
def _tf(N=2, _K=1234**5678):
"""Takes about 100ms on a first-generation Macbook Pro"""
for i in ra... | : break
task()
def _test_thr(Ntasks=5, Nthreads=1):
q = queue.Queue()
funcs = (_tf, 1), (factorize, 4), (elemop, 2)
for i in range(Ntasks):
for f, n in funcs:
for x in range(n):
q.put(f)
for i in range(Nthreads):
q.put(None)
thrs = [DoOne(q) f... | for t in thrs: t.start()
for t in thrs: t.join()
if __name__=='__main__':
_test(1)
|
Mlieou/leetcode_python | leetcode/python/ex_244.py | Python | mit | 791 | 0.002528 | class WordDistance(object):
def __init__(self, words):
"""
initialize your data structure here.
:type words: List[str]
"""
self.word_dict = {}
for idx, w in enumerate(words):
self.word_dict[w] = self.word_dict.get(w, []) + [idx]
def shortest... | urn min(abs(i - j) for i in self.word_dict[word1] for j in | self.word_dict[word2])
# Your WordDistance object will be instantiated and called as such:
# wordDistance = WordDistance(words)
# wordDistance.shortest("word1", "word2")
# wordDistance.shortest("anotherWord1", "anotherWord2") |
appuio/ansible-role-openshift-zabbix-monitoring | vendor/openshift-tools/ansible/roles/lib_gcloud/build/ansible/gcloud_iam_sa.py | Python | apache-2.0 | 2,675 | 0.003364 | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam servicetaccount'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str',
... | rval, state="list")
module.exit_json(changed=False, results=api_rval['results'], state="list")
########
# Delete
########
if state == 'absent':
if gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a delete.')
... | te="absent")
if state == 'present':
########
# Create
########
if not gcloud.exists():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed a create.')
# Create it here
api_rval = gcloud.create_service_... |
sharad1126/owtf | framework/db/resource_manager.py | Python | bsd-3-clause | 3,759 | 0.004256 | from framework.db import models
from framework.config import config
from framework.dependency_management.dependency_resolver import BaseComponent
from framework.dependency_management.interfaces import ResourceInterface
from framework.lib.general import cprint
import os
import logging
from framework.utils import FileOpe... | for Type, Name, Resource in resources:
self.db.session.add(models.Resource(resource_type=Type, resource_name=Name, resource=Resource))
self.db.session.commit()
def GetResourcesFromFile(self, resource_file | ):
resources = set()
ConfigFile = FileOperations.open(resource_file, 'r').read().splitlines() # To remove stupid '\n' at the end
for line in ConfigFile:
if '#' == line[0]:
continue # Skip comment lines
try:
Type, Name, Resource = line.split... |
icyflame/batman | scripts/template.py | Python | mit | 14,372 | 0.000348 | #!/usr/bin/python
# -*- coding: utf-8 -*-
r"""
Very simple script to replace a template with another one.
It also converts the old MediaWiki boilerplate format to the new format.
Syntax: python template.py [-remove] [xml[:filename]] oldTemplate [newTemplate]
Specify the template on the command line. The program will... | ashington state]], start
python pwb.py templa | te "Cities in Washington" "Cities in Washington state"
Move the page [[Template:Cities in Washington]] manually afterwards.
If you have a template called [[Template:test]] and want to substitute it only
on pages in the User: and User talk: namespaces, do:
python pwb.py template test -subst -namespace:2 -namespa... |
CanaimaGNULinux/canaimagnulinux.wizard | canaimagnulinux/wizard/browser/socialnetwork.py | Python | gpl-2.0 | 3,378 | 0.000296 | # -*- coding: utf-8 -*-
from canaimagnulinux.wizard.interfaces import IChat
from canaimagnulinux.wizard.interfaces import ISocialNetwork
from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _
from collective.beaker.interfaces import ISession
from collective.z3cform.wizard import wizard
from plone impor... | if not data.get('twitter', None):
twitter = member.getProperty('twitter')
if type(twitter).__name__ == 'object':
twitter = None
data['twitter'] = twitter
if not data.get('instagram', None):
instagram = member.getProperty('instagram')
... | facebook = member.getProperty('facebook')
if type(facebook).__name__ == 'object':
facebook = None
data['facebook'] = facebook
def apply(self, context, initial_finish=False):
data = self.getContent()
return data
def applyChanges(self, data):
... |
DarioGT/OMS-PluginXML | org.modelsphere.sms/lib/jython-2.2.1/Lib/macpath.py | Python | gpl-3.0 | 6,978 | 0.005589 | """Pathname and path-related operations for the Macintosh."""
import os
from stat import *
__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","islink","exists","isdir","isfile",
"walk","exp... |
try:
st = os.stat(s)
except os.error:
return 0
return 1
# Return the longest prefix of all list elements.
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
prefix = m[0]
for item in m:
f... | )):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0: return ''
break
return prefix
def expandvars(path):
"""Dummy to retain interface-compatibility with other operating systems."""
return path
def expanduser(path):
... |
asedunov/intellij-community | python/testData/resolve/ReferenceInDocstring.py | Python | apache-2.0 | 114 | 0.017544 | from datetime import datetime
def foo(p):
"""Foo
:param datetime p: a datetime
| <ref>
"" | " |
chilleo/ALPHA | raxmlOutputWindows/matplotlibCustomBackend/customFormlayout.py | Python | mit | 20,667 | 0.000919 | # -*- coding: utf-8 -*-
"""
formlayout
==========
Module creating Qt form dialogs/layouts to edit various type of parameters
formlayout License Agreement (MIT License)
------------------------------------------
Copyright (c) 2009 Pierre Raybaut
Permission is hereby granted, free of charge, to any person
obtaining ... | r.isValid()
def update_text(self, color):
self.lineedit.setText(mcolors.to_hex(color.getRgbF(), keep_alpha=True))
def text(self):
return self.lineedit.text()
def font_is_installed(font):
"""Check if font is installed"""
return [fam for fam in QtGui.QFontDatabase().families()
... | t_type(fam) == font]
def tuple_to_qfont(tup):
"""
Create a QFont from tuple:
(family [string], size [int], italic [bool], bold [bool])
"""
if not (isinstance(tup, tuple) and len(tup) == 4
and font_is_installed(tup[0])
and isinstance(tup[1], int)
and isinstan... |
andoniaf/DefGrafana.py | graf2png.py | Python | gpl-3.0 | 1,737 | 0.000576 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from PIL import Image
def graf2png(weburl, username, password, timeout, imgname, hwin, wwin, onlypanel):
driver = webdriver.PhantomJS()
driver.set_window_size(hwin, wwin)
... | sea 'panel-fullscreen',
# esta es la clase que tiene por defecto los paneles cuando
# generas un enlace para compartir. (Share Panel > Link > Copy)
if (onlypanel):
panel = driver.find_element_by_cl | ass_name('panel-fullscreen')
plocation = panel.location
psize = panel.size
left = plocation['x']
top = plocation['y']
right = plocation['x'] + psize['width']
bottom = plocation['y'] + psize['height']
pimg = Image.open(imgname)
pimg = pimg.crop((left, top... |
jnsebgosselin/WHAT | gwhat/brf_mod/kgs_brf.py | Python | gpl-3.0 | 4,831 | 0.000414 | # -*- coding: utf-8 -*-
# Copyright © 2014-2018 GWHAT Project Contributors
# https://github.com/jnsebgosselin/gwhat
#
# This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox).
# Licensed under the terms of the GNU General Public License.
# ---- Standard library imports
import os
import csv
import sys
... |
count += 1
elif count in [2, 3]:
dataf[-1].extend([float(i) for i in row[0].split()])
count += 1
elif count == 4:
| dataf[-1].extend([float(i) for i in row[0].split()])
count = 1
# Remove non valid data.
dataf = [row for row in dataf if row[4] > -999]
# Format data into numpy arrays
dataf = np.array(dataf)
lag = dataf[:, 1]
A = dataf[:, 4]
err = dataf[:, 5]
return lag, A, err
if __n... |
powervm/pypowervm | pypowervm/tasks/hdisk/_fc.py | Python | apache-2.0 | 19,741 | 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... | s LPARs. The stale LPAR's storage mappings
can cause hdisk discovery to fail because it thinks the hd | isk is already in
use.
Retry conditions: The scrub-and-retry will be triggered if:
o dev_name is None; or
o status is anything other than DEVICE_AVAILABLE or FOUND_ITL_ERR. (The
latter is acceptable because it means we discovered some, but not all, of
the ITLs. This is okay as long as dev... |
maelnor/cinder | cinder/openstack/common/rpc/amqp.py | Python | apache-2.0 | 25,306 | 0.00004 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2011 - 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
... | f pooled:
self.connection = connection_pool.get()
else:
self.connection = connection_pool.connection_cls(
| conf,
server_params=server_params)
self.pooled = pooled
def __enter__(self):
"""When with ConnectionContext() is used, return self"""
return self
def _done(self):
"""If the connection came from a pool, clean it up and put it back.
If it did not ... |
chetan51/nupic | tests/integration/nupic/opf/opf_checkpoint_test/experiments/non_temporal_multi_step/base.py | Python | gpl-3.0 | 14,616 | 0.003626 | # ----------------------------------------------------------------------
# Copyright (C) 2012 Numenta Inc. All rights reserved.
#
# The information and source code contained herein is the
# exclusive property of Numenta Inc. No part of this software
# may be used, reproduced, stored or distributed in any form,
# w... | NSOR_AUTO_RESET)
'sensorAutoReset' : None,
},
'spEnable': True,
'spParams': {
# SP diagnos | tic output verbosity control;
# 0: silent; >=1: some info; >=2: more info;
'spVerbosity' : VERBOSITY,
'globalInhibition': 1,
# Number of cell columns in the cortical region (same number for
# SP and TP)
# (see also tpNCellsPerCol)
'co... |
ThibaultGigant/Crosswords | run.py | Python | gpl-3.0 | 101 | 0 | # -*- coding: utf-8 -*-
from ihm.main_window import launch
i | f __name__ == '__main__':
| launch()
|
ewandor/home-assistant | homeassistant/components/cover/abode.py | Python | apache-2.0 | 1,326 | 0 | """
This component provides HA cover support for Abode Security System.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.abode/
"""
import logging
from homeassistant.components.abode import AbodeDevice, DOMAIN as ABODE_DOMAIN
from homeassistant.comp... | deDevice, CoverDevice):
"""Representation of an Abode cover."""
@property
def is_closed(self):
"""Return true if cover is closed, else False."""
return not self._device.is_open
def close_cover(self, **kwargs):
"""Issue cl | ose command to cover."""
self._device.close_cover()
def open_cover(self, **kwargs):
"""Issue open command to cover."""
self._device.open_cover()
|
gravitee-io/jenkins-scripts | src/main/python/package_bundles.py | Python | apache-2.0 | 19,869 | 0.003372 | import os
import re
import shutil
import zipfile
import requests
import json
from shutil import copy2
from urllib.request import urlretrieve, urlopen
# Input parameters
version_param = os.environ.get('RELEASE_VERSION')
is_latest_param = True if version_param == "master" else False
# build constants
m2repo_path = '/m2... | ['name'] != "gravitee-policy-core":
url = get_download_url("io.gravitee.policy", policy['name'], policy['version'], "zip")
paths.append(
download(policy['name'], '%s/%s-%s.zip' % (policies_path, policy['name'], policy['version']), url))
return paths
def download_management_... | ent-api-standalone-distribution-zip",
v, "zip")
return download(mgmt_ |
botswana-harvard/edc-rdb | bcpp_rdb/dataframes/ccc.py | Python | gpl-2.0 | 1,163 | 0.00086 | import pandas as pd
from sqlalchemy import create_engine
from bcpp_rdb.private_settings import Rdb
class CCC(object):
"""CDC data for close clinical cohort."""
def __init__(self):
self.engine = create_engine('postgresql://{user}:{password}@{host}/{db}'.format(
user=Rdb.user, password=Rd... | return """select ssid as cdcid, oc_study_id as subject_identifier,
appt_date from dw.oc_crf_ccc_enrollment"""
def sql_refused(self):
"""
* If patient is from BCPP survye, oc_study_id is a BHP identifier.
* ssid is the CDC allocated identifier of format NNN-NNNN.
"""
... | appt_date from dw.oc_crf_ccc_enrollment"""
|
evasilchenko/castle | core/info.py | Python | mit | 536 | 0.001866 |
class Information(object): |
def __init__(self, pygame):
self.pygame = pygame
self.display_fps = False
def _show_fps(self, clock, screen):
font = self.pygame.font.SysFont('Calibri', 25, True, False)
text = font.render("fps: {0:.2f}".format(clock.get_fps()), True, (0, 0, 0))
screen.blit(text, [0, 0]... | lay_fps
|
smorante/continuous-goal-directed-actions | guided-motor-primitives/src/roman14_primitive.py | Python | mit | 5,788 | 0.023151 | #!/usr/bin/env python
from __future__ import division
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import linalg
import csv
import codecs
import copy
def comparison(trajOne, trajTwo):
segmentOne=np.array(trajOne)
segmentTwo=np.... | aveToCSV(primitives, tau, xi):
fileName='db_var/db_ | '+ 'tau' +str(tau) + '_xi'+ str(xi)
# to write in CSV
with open(fileName, 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_MINIMAL)
for k in range(len(primitives)):
wr.writerow(primitives[k])
# to replace '"'
contents = codecs.open(fileName, encoding='utf-8').read(... |
omoju/Fundamentals | Data/twitterDataAnalysis/info_gain.py | Python | gpl-3.0 | 3,353 | 0.037578 |
import os
import sys
import numpy as np
import math
def findBinIndexFor(aFloatValue, binsList):
#print "findBinIndexFor: %s" % aFloatValue
returnIndex = -1
for i in range(len(binsList)):
thisBin = binsList[i]
if (aFloatValue >= thisBin[0]) and (aFloatValue < thisBin[1]):
returnIndex = i
break
return ... | at
# Computes Kullback-Leibler divergence between
# P(X,Y) and P(X)
def conditional_entropy(joint_prob_dist, xVals, yVals):
returnFloat = None
h_acc = 0
margin | al_y_dist = getYMarginalDist(joint_prob_dist)
for x in xVals:
for y in yVals:
joint_xy = 0
marginal_y = 0
if not x in joint_prob_dist or y not in joint_prob_dist[x]:
joint_xy = 0
else:
joint_xy = joint_prob_dist[x][y]
if not y in marginal_y_dist:
marginal_y = 0
else:
marginal_y =... |
pligor/predicting-future-product-prices | 04_time_series_prediction/models/model_34_price_history_autoencoder.py | Python | agpl-3.0 | 22,721 | 0.004181 | from __future__ import division
import numpy as np
import tensorflow as tf
from cost_functions.huber_loss import huber_loss
from data_providers.data_provider_33_price_history_autoencoder import PriceHistoryAutoEncDataProvider
from interfaces.neural_net_model_interface import NeuralNetModelInterface
from mylibs.batch_n... | cs):err(train)=%.4f,acc(train)=%.2f,err(valid)=%.2f,acc(valid)=%.2f, ' % \
# (epoch + 1, runTime, train_error, train_accuracy, valid_error, valid_accuracy)
print 'End Epoch %02d (%.3f secs): err(train) = %.6f' % (
| epoch + 1, runTime, train_error)
dynStats.gatherStats(train_error=train_error)
else:
# if (epoch + 1) % 1 == 0:
valid_error = self.validateEpoch(
sess=sess,
data_provider=valid_data,... |
kyoren/https-github.com-h2oai-h2o-3 | h2o-py/tests/testdir_algos/deeplearning/pyunit_demoDeeplearning.py | Python | apache-2.0 | 1,322 | 0.04236 | import sys
sys.path.insert(1,"../../../")
import h2o, tests
def deepLearningDemo():
# Training data
train_data | = h2o.import_file(path=tests.locate("smalldata/gbm_test/ecology_model.csv"))
train_data = train_data.drop('Site')
train_data | ['Angaus'] = train_data['Angaus'].asfactor()
print train_data.describe()
train_data.head()
# Testing data
test_data = h2o.import_file(path=tests.locate("smalldata/gbm_test/ecology_eval.csv"))
test_data['Angaus'] = test_data['Angaus'].asfactor()
print test_data.describe()
test_data.head()
# Run GBM
... |
zvezdan/pip | tests/functional/test_download.py | Python | mit | 17,722 | 0 | import os
import textwrap
import pytest
from pip._internal.status_codes import ERROR
from tests.lib.path import Path
def fake_wheel(data, wheel_path):
data.packages.join(
'simple.dist-0.1-py2.py3-none-any.whl'
).copy(data.packages.join(wheel_path))
@pytest.mark.network
def test_download_if_request... | --no-index', '--find-links', data.find_links,
'--no-deps',
'--dest', '.',
'--platform', 'linux_x86_64',
'fake'
)
assert (
Path('scratch') / 'fake-1.0-py2.py3-none-any.whl'
in result.files_created |
)
def test_download_specific_platform_fails(script, data):
"""
Confirm that specifying an interpreter/platform constraint
enforces that ``--no-deps`` or ``--only-binary=:all:`` is set.
"""
fake_wheel(data, 'fake-1.0-py2.py3-none-any.whl')
result = script.pip(
'download', '--no-in... |
romanvm/WsgiBoostServer | benchmarks/test_app.py | Python | mit | 1,229 | 0.003255 | from bottle import route, default_app
app = default_app()
data = {
"id": 78874,
"seriesName": "Firefly",
"aliases": [
"Serenity"
],
"banner": "graphical/78874-g3.jpg",
"seriesId": "7097",
"status": "Ended",
"firstAired": "2002-09-20",
"network": "FOX (US)",
"networkId": "... | Id": "EP00524463",
"added": "",
"addedBy": None,
"siteRating": 9.5,
"siteRatingCount": 472,
}
@route('/api')
def api():
| return data
|
jdf76/plugin.video.youtube | resources/lib/youtube_plugin/kodion/constants/__init__.py | Python | gpl-2.0 | 526 | 0 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2014-2016 bromix (plugin.v | ideo.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
from . import const_settings as setting
from . import const_localize as localize
from . import const_sort_methods as sort_method
from . import const_content_... | ['setting', 'localize', 'sort_method', 'content_type', 'paths']
|
iptvgratis/TUPLAY | resources/tools/epg_formulatv.py | Python | gpl-3.0 | 24,492 | 0.007035 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# beta.1 EPG FórmulaTV.com
# License: GPL (http://www.gnu.org/licenses/gpl-3.0.html)
#------------------------------------------------------------
# Gracias a la librería plugintools de Jesús (www.mimediacenter.info)
#----------------... | epg_channel
elif channel == "axn" or channel == "axn hd":
channel = "axn"
epg_channel = epg_formulatv(params, channel)
return epg_channel
elif channel == "axn white":
channel = "axn white"
epg_channel = epg_formulatv(params, channel)
return epg_ch... | el)
return epg_channel
elif channel == "bio":
channel = "bio"
epg_channel = epg_formulatv(params, channel)
return epg_channel
elif channel == "calle 13" or channel == "calle 13 hd":
channel = "calle 13"
epg_channel = epg_formulatv(params, chan... |
pycket/pycket | pycket/prims/general.py | Python | mit | 75,231 | 0.004878 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
#import struct
from pycket import impersonators as imp
from pycket import values, values_string
from pycket.cont import continuation, loop_label, call_cont
from pycket.arity import Arity
from pycket import values_parameter
from pycket impor... | parameter.W_Parameterization),
("hash?", W_HashTable),
("cpointer?", W_CPointer),
("ctype?", W_CType),
("continuation-prompt-tag?", values.W_ContinuationPromptTag),
("logger?", values.W_Logger),
("log-receiver?", values.W_LogReciever),
("evt?", values.W_Evt),
... | ,
("port?", values.W_Port),
("security-guard?", values.W_SecurityGuard),
# FIXME
("will-executor?", values.W_WillExecutor),
("bytes-converter?", values.W_Impossible),
("fsemaphore?", values.W_Impossible),
("thread-group?", values.W_Impossible),
("udp?", va... |
ProjectSWGCore/NGECore2 | scripts/static_spawns/naboo/theed.py | Python | lgpl-3.0 | 1,499 | 0.02068 | import sys
from resources.datatables import Options
from resources.datatables import StateStatus
def addPlanetSpawns(core, planet):
stcSvc = core.staticService
objSvc = core.ob | jectService
#junkdealer
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5694), float(6.5), float(4182), float(0.707), float(-0.707))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5717), float(6.5), float(4159), float(0.71), float(0.71))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), flo... | float(0.71), float(0.71))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5147), float(6.5), float(4158), float(0.71), float(0.71))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5114), float(6.5), float(4161), float(0.71), float(-0.71))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(... |
timercrack/pydatacoll | pydatacoll/utils/__init__.py | Python | apache-2.0 | 755 | 0 | #!/usr/bin/env pytho | n
#
# Copyright 2016 timercrack
#
# 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 writin... |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def str_to_number(s):
try:
if not isinstance(s, str):
return s
return int(s)
except ValueError:
return f... |
thisisshi/cloud-custodian | c7n/resources/ebs.py | Python | apache-2.0 | 57,596 | 0.00026 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from collections import Counter
import logging
import itertools
import json
import time
from botocore.exceptions import ClientError
from concurrent.futures import as_completed
from dateutil.parser import parse as parse_date
from c7n.action... | matches = []
f | or snap in snapshots:
if snap['SnapshotId'] not in ami_snaps:
matches.append(snap)
return matches
@Snapshot.filter_registry.register('cross-account')
class SnapshotCrossAccountAccess(CrossAccountAccessFilter):
permissions = ('ec2:DescribeSnapshotAttribute',)
def process(self, resourc... |
stefantalpalaru/django-bogofilter | bogofilter/forms.py | Python | bsd-3-clause | 216 | 0.009259 | from django_comments.forms import CommentForm
from bogofilter.mo | dels import BogofilterComment
import time
class BogofilterCommentForm(CommentForm):
def get_comment_model(self):
| return BogofilterComment
|
cloud-engineering/xfc-email-notifier | snippets/snippet_notfication.py | Python | mit | 939 | 0.015974 | import subprocess
import pynotify
import time
def notify_with_subprocess(title, message):
subprocess.Popen(['notify-send', title, message])
return
def notify_with_pynotify(title, message):
pynotify.init("Test")
notice = pynotify.Notification(title, message)
notice.show()
return
def update_wit... | tion(notification=Non | e, action=None, data=None):
print "It worked!"
pynotify.init("app_name")
n = pynotify.Notification("Title", "body")
n.set_urgency(pynotify.URGENCY_NORMAL)
n.set_timeout(100)
n.show()
#n.add_action("clicked","Button text", callback_function, None)
#n.update("Notification", "Update for you")
#n.show()
... |
AdamDynamic/TwitterMetrics | CreateJson.py | Python | gpl-2.0 | 2,191 | 0.016431 | #!/usr/bin/env python
# Creates and saves a JSON file to update the D3.js graphs
import MySQLdb
import MySQLdb.cursors
import json
import Reference as r
import logging
def CreateSentimentIndex(NegativeWords, PositiveWords, TotalWords):
''' Creates a sentiment value for the word counts'''
if TotalWords... |
def OutputJsonFile(InputDictionary):
'''Saves a dictionary to an output file in a JSON format'''
JsonOutput = json.dumps(InputDictionary)
OutputFileName = 'json/twittermetric | s_sentiment.js'
FileOutput = open(OutputFileName,'w')
print >> FileOutput, JsonOutput
return True
def CreateJsonFile():
'''Extracts data from the database and saves a JSON file to the server'''
FN_NAME = "CreateJsonFile"
dbDict = MySQLdb.connect(
... |
jkonecny12/anaconda | pyanaconda/modules/payloads/source/repo_files/repo_files_interface.py | Python | gpl-2.0 | 1,434 | 0.001395 | #
# DBus interface for payload Repo files image source.
#
# Copyright (C) 2020 Red Hat, Inc.
#
# Th | is copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expresse... | ITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Ha... |
iskandr/brainmets | data.py | Python | apache-2.0 | 7,077 | 0.046489 | import pandas as pd
import numpy as np
import sklearn.preprocessing
from sklearn.linear_model import LinearRegression, LogisticRegression
FILENAME = 'BrainMets.xlsx'
MONTHS_TO_LIVE = 9
N_TRAIN = 250
def categorical_indices(values):
"""
When we have a categorical feature like 'cancer type', we want to transform its ... | # df['Brain Tumor Sx'] = categorical_indices(brain_tumor_sx)
return df
def get_expert_predictions(df):
expert_predictions = {}
experts = [
'Prediction(Cleveland Clinic)',
' Prediction (Lanie Francis)',
'Prediction(Flickinger)',
'Prediction(Loefler',
'Prediction(Knisely)',
'Prediction(Lunsford)', ... | ction(friedman)',
'Prediction(Stupp)',
'Prediction(Rakfal)',
'Prediction(Rush)',
' Prediction( Kondziolka)'
]
for expert in experts:
expert_predictions[expert] = df[expert]
return expert_predictions
def feature_selection(df, Y, training_set_mask):
Y_training = Y[training_set_mask]
df_training = df.... |
wimmuskee/ontolex-db | format/namespace.py | Python | mit | 343 | 0 | # -*- coding: utf-8 -*-
from rdflib import Namespace
ONTOLEX = Namespace("http://www.w3.org/ns/lemon/ontolex#")
LEXINFO = Namespace("http://www.lexinfo.net/ontology/2.0/lexin | fo#")
DECOMP = Namespace("http://www.w3.org/ns/lemon/de | comp#")
ISOCAT = Namespace("http://www.isocat.org/datcat/")
LIME = Namespace("http://www.w3.org/ns/lemon/lime#")
|
k3yavi/alevin | testing/src-py/Utilities.py | Python | gpl-3.0 | 3,040 | 0.000987 | '''
'''
import sys
import os
import gzip
import regex
# 'borrowed' from CGAT - we may not need this functionality
# ultimately. When finalised, if req., make clear source
def openFile(filename, mode="r", create_dir=False):
'''open file called *filename* with mode *mode*.
gzip - compressed files are recognized... | atch(whitelisted_barcode) or comp_regex2.match(whitelisted_barcode):
near_matches.add(whitelisted_barcode)
if len(near_matches) > limit:
return near_matches
return near_matches
# partially 'borrowed' from CGAT - we may not need this functionality
# ultimately. When fina | lised, if req., make clear source
def FastqIterator(infile):
'''iterate over contents of fastq file.'''
while 1:
line1 = infile.readline()
if not line1:
break
if not line1.startswith('@'):
raise ValueError("parsing error: expected '@' in line %s" % line1)
... |
jodal/comics | comics/comics/partiallyclips.py | Python | agpl-3.0 | 375 | 0 | from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "PartiallyClips"
language = "en"
url = "ht | tp://partiallyclips.com/"
start_date = | "2002-01-01"
rights = "Robert T. Balder"
active = False
class Crawler(CrawlerBase):
def crawl(self, pub_date):
pass
|
bitcraft/pyglet | contrib/scene2d/tests/scene2d/SPRITE_OVERLAP.py | Python | bsd-3-clause | 2,162 | 0 | # !/usr/bin/env python
"""Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pygl... | elif self.right > 320:
self.right = 320
p['dx'] = -p['dx']
if self.bottom < 0:
self.bottom = 0
p['dy'] = -p['dy']
elif self.top > 320:
self.top = 320
p['dy'] = -p['dy']
class SpriteOverlapTest(unittest.T | estCase):
def test_sprite(self):
w = pyglet.window.Window(width=320, height=320)
image = Image2d.load(ball_png)
ball1 = BouncySprite(0, 0, 64, 64, image, properties=dict(dx=10, dy=5))
ball2 = BouncySprite(288, 0, 64, 64, image,
properties=dict(dx=-10, d... |
valasek/taekwondo | manage.py | Python | gpl-3.0 | 801 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "itf.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensur | e that the
# issue is really that 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 ... | activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
arseneyr/essentia | test/src/unittest/standard/test_scale.py | Python | agpl-3.0 | 2,054 | 0.003408 | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation ... | le()(input)
self.assertEqualVector(output, input)
def testClipping(self):
inputSize = 1024
maxAbsValue= 10
factor = 1
input = [n + maxAbsValue for n in | range(inputSize)]
expected = [maxAbsValue] * inputSize
output = Scale(factor=factor, clipping=True, maxAbsValue=maxAbsValue)(input)
self.assertEqualVector(output, expected)
def testInvalidParam(self):
self.assertConfigureFails(Scale(), { 'maxAbsValue': -1 })
suite = allTest... |
simon-r/PyParticles | pyparticles/pset/rebound_boundary.py | Python | gpl-3.0 | 2,289 | 0.042813 | # PyParticles : Particles simulation in python
# Copyright (C) 2012 Simone Riva
#
# 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 late... | received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import pyparticles.pset.boundary as bd
class ReboundBoundary( bd.Bounda | ry ):
def __init__( self , bound=(-1,1) , dim=3 ):
self.set_boundary( bound , dim )
self.set_normals()
def set_normals( self ):
self.__N = np.zeros( ( 2*self.dim , self.dim ) )
#print( self.__N )
if self.dim >= 2 :
self.__N... |
hammurabi13th/haopy | hao.py | Python | mit | 12,161 | 0.068167 | #!/usr/bin/python3
from urllib.parse import urlencode
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from argparse import ArgumentParser
from threading import Thread
import re
class HackAlunoOnline:
def __init__( self , matricula , full_search = False ):
# Exibicao default de matricula/... | full_search ):
# dados contato
self.dados_contato_html = self._get_aluno_online_html( '/recadastramento_dados_contato/recadastramento_dados_contato.php' )
self.telef | one = self._extract_telefone()
self.email = self._extract_email()
self.endereco = self._extract_endereco()
self.cep = self._extract_cep()
# dados pessoais
self.dados_pessoais_html = self._get_aluno_online_html( '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.