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 |
|---|---|---|---|---|---|---|---|---|
Clinical-Genomics/housekeeper | alembic/versions/619fe6fe066c_update_cascading_rules.py | Python | mit | 554 | 0.01083 | """update cascading rules
Revision ID: 619fe6fe066c
Revises: 73ea6c072986
Create Date: 2017-03-15 10:51:12.494508
"""
# revision identifiers, used by Alembic.
revision = "619fe6fe066 | c"
down_revision = "73ea | 6c072986"
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### ... |
rwl/PyCIM | CIM14/IEC61970/Meas/LimitSet.py | Python | mit | 2,248 | 0.002669 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, | free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# de | al in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice an... |
umitproject/network-admin | netadmin/reportmeta/urls.py | Python | agpl-3.0 | 1,723 | 0.004643 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# 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 Sof... | et_report'),
url(r'^list/(?P<object_type>host|network)/$', 'reportmeta_list', name='reportmeta_list'),
url(r'^new/(?P<object_type>host|network)/$', 'reportmeta_new', name="reportmeta_new"),
url(r'^new/(?P<object_type>host|network)/(?P<object_id>\d+)/$', 'reportmeta_new_from_object', name="reportmeta_new"),
... | me="reportmeta_update"),
url(r'^delete/(?P<object_id>\d+)/$', 'reportmeta_delete', name="reportmeta_delete"),
)
|
Azure/azure-sdk-for-python | sdk/azurestack/azure-mgmt-azurestack/azure/mgmt/azurestack/models/__init__.py | Python | mit | 5,480 | 0.000547 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | om ._models_py3 import OsDiskImage
from ._models_py3 import Product
from ._models_py3 import ProductLink
from ._models_py3 import ProductList
from ._models_py3 import ProductLog
from ._models_py3 import ProductProperties
from ._models_py3 import Registration
from ._models_py3 import Registra... | rackedResource
from ._models_py3 import VirtualMachineExtensionProductProperties
from ._models_py3 import VirtualMachineProductProperties
except (SyntaxError, ImportError):
from ._models import ActivationKeyResult # type: ignore
from ._models import CloudManifestFileDeploymentData # type: ignore
f... |
sangwook236/general-development-and-testing | sw_dev/python/ext/test/high_performance_computing/spark/pyspark_database.py | Python | gpl-2.0 | 5,564 | 0.028936 | #!/usr/bin/env python
from pyspark.sql import SparkSession
import pyspark.sql.types as types
import pyspark.sql.functions as func
import traceback, sys
# REF [site] >> https://spark.apache.org/docs/latest/sql-programming-guide.html#jdbc-to-other-databases
def sqlite_jdbc():
spark = SparkSession.builder.appName('sql... | der.appName('sqlite-jdbc') \
# .config('spark.jars', 'sqlite-jdbc-3.23.1.jar') \
# .getOrCreate()
spark.sparkContext.setLogLevel('WARN')
# REF [site] >> https://spark.apache.org/docs/latest/sql-programming-guide.html#pyspark-usage-guide-for-pandas-with-apache-arrow
# Enable Arrow-based columnar data transfers.
s... | 'url', 'jdbc:sqlite:iris.db') \
.option('driver', 'org.sqlite.JDBC') \
.option('dbtable', 'iris') \
.load()
elif False:
# REF [site] >> https://www.sqlite.org/inmemorydb.html
#db_url = 'jdbc:sqlite::memory:' # In-memory DB.
db_url = 'jdbc:sqlite::memory:?cache=shared' # Shared in-memory DB.
#db_url ... |
interlegis/saap | config/rest_framework/templatetags/rest_framework.py | Python | gpl-3.0 | 13,251 | 0.001207 | from __future__ import absolute_import, unicode_literals
import re
from collections import OrderedDict
from django import template
from django.template import loader
#from django.urls import NoReverseMatch, reverse
from django.core.urlresolvers import reverse
from django.utils import six
from django.utils.encoding im... | k_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
elif isinstance(value, list):
if any([isinstance(item, (list, dict)) for item in value]):
template = loader.get_template('rest_framework/admin/list_value.html')
else:
template = loader.get_templat... | :
template = loader.get_template('rest_framework/admin/dict_value.html')
context = {'value': value}
return template.render(context)
elif isinstance(value, six.string_types):
if (
(value.startswith('http:') or value.startswith('https:')) and not
re.search(r'\s'... |
timvaillancourt/mongodb_consistent_backup | mongodb_consistent_backup/Upload/__init__.py | Python | apache-2.0 | 1,026 | 0.008772 | from Upload import Upload # NOQA
def config(parser):
parser.add_argument("--upload.method", dest="upload.method", default='none', choices=['gs', 'rsync', 's3', 'none'],
help="Uploader method (default: none)")
parser.add_argument("--upload.remove_uploaded", dest="upload.remove_uploaded... | default: false)")
parser.add_argument("--upload.retries", dest="upload.retries", default=5, type=int,
help="Number of times to retry upload attempts (default: 5)")
parser.add_argument("--upload.threads", dest="upload.threads", default=4, type=int,
help="Number of ... | help="Limit uploaded file names to those matching a regular expression. (default: none)")
return parser
|
BogusCurry/picup-it | picupwebapp/picupwebapp/picture/tools.py | Python | bsd-3-clause | 3,826 | 0.007318 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Image processing tools.
"""
from unidecode import unidecode
from django.conf import settings
import StringIO
try:
from PIL import Image, ImageOps, ImageFilter
except ImportError:
import Image
import ImageOps
import os.path
import shutil
from PIL import Image... | posY = 0
| resizedImage = resizedImage.filter(ImageFilter.SMOOTH)
resizedImage = resizedImage.filter(ImageFilter.SMOOTH_MORE)
resizedImage = resizedImage.filter(ImageFilter.BLUR)
imagefile = StringIO.StringIO()
resizedImage.save(imagefile,'JPEG')
imagefile.seek(0)
return imagefile
def image_smar... |
bks/veusz | veusz/windows/mainwindow.py | Python | gpl-2.0 | 53,469 | 0.001234 | # -*- coding: utf-8 -*-
# Copyright (C) 2003 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# 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 ... | ck)
# make the console window a dock
self.console = consolewindow.ConsoleWindow(self.document,
self)
self.console.hide()
self.interpreter = self.console.interpreter
self.addDockWidget(qt4.Qt.BottomDockWidgetArea, self.console)
... | a label for the picker readout
self.pickerlabel = qt4.QLabel(statusbar)
self._setPickerFont(self.pickerlabel)
statusbar.addPermanentWidget(self.pickerlabel)
self.pickerlabel.hide()
# plot queue - how many plots are currently being drawn
self.plotqueuecount = 0
s... |
ilogue/niprov | niprov/exceptions.py | Python | bsd-3-clause | 89 | 0 |
class NiprovError(Exception):
| pass
class UnknownFileError(NiprovErr | or):
pass
|
CityPulse/CP_Resourcemanagement | wrapper_dev/romania_weather/romaniaweather_aw.py | Python | mit | 9,102 | 0.003406 | # coding=utf-8
__author__ = 'Marten Fischer (m.fischer@hs-osnabrueck.de)'
from virtualisation.wrapper.abstractwrapper import AbstractComposedWrapper, AbstractWrapper
from virtualisation.sensordescription import SensorDescription
from virtualisation.wrapper.history.csvhistory import CSVHistoryReader
from virtualisation... | s.path.join("historicdata", "weatherAW-%s.csv" % self.sensorDescription.sensorID), "rU"), delimiter=';')
self.historyparser = CSVParser(self, self.historyreader.headers)
except Exception as e:
Log.e(e)
self. | historyreader = None
super(InternalWeatherAWWrapper, self).start()
class RomanianWeatherAWWrapper(AbstractComposedWrapper):
def __init__(self):
super(RomanianWeatherAWWrapper, self).__init__()
basesensordescription = SensorDescription()
basesensordescription.namespace = "http://ict... |
NORCatUofC/rainapp | csos/models.py | Python | mit | 694 | 0 | from django.db import models
class RiverOutfall(models.Model):
name = models.TextField()
lat = models.FloatField(null=True)
lon = models.FloatField(null=True)
class RiverCso(models.Model):
r | iver_outfall = models.ForeignKey("RiverOutfall")
open_time = models.DateTimeField()
close_time = models.DateTimeField()
class LakeOutfall(models.Model):
name = models.TextField()
lat = models.FloatField(null=True)
lon = models.FloatField(null=True)
class LakeReversal(models.Model):
lake_outf... | TimeField()
millions_of_gallons = models.FloatField()
|
sai9/weewx-gitsvn | bin/weewx/drivers/te923.py | Python | gpl-3.0 | 39,957 | 0.001652 | #!/usr/bin/env python
# $Id$
# Copyright 2013 Matthew Wall
# See the file LICENSE.txt for your full rights.
#
# Thanks to Sebastian John for the te923tool written in C (v0.6.1):
# http://te923.fukz.org/
# Thanks to Mark Teel for the te923 implementation in wview:
# http://www.wviewweather.com/
"""Classes and funct... | s of each sensor is checked every ho | ur
This implementation polls the station for data. Use the polling_interval to
control the frequency of polling. Default is 10 seconds.
The manual says that a single bucket tip is 0.03 inches. In reality, a single
bucket tip is between 0.02 and 0.03 in (0.508 to 0.762 mm). This driver uses
a value of 0.02589 in (... |
jonpetersen/transitfeed-1.2.12 | build/scripts-2.7/unusual_trip_filter.py | Python | apache-2.0 | 5,999 | 0.010502 | #!/usr/bin/python
# Copyright (C) 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... | sage = \
'''%prog [options] <GTFS.zip>
Sets the trip_type for trips that have an unusual pattern for a route.
<GTFS.zip> is overwritten with the modifed GTFS file unless the --output
option is used.
For more information see
http://code.google.com/p/googletransitdatafeed/wiki/UnusualTripFilter
'''
p | arser = util.OptionParserLongError(
usage=usage, version='%prog '+transitfeed.__version__)
parser.add_option('-o', '--output', dest='output', metavar='FILE',
help='Name of the output GTFS file (writing to input feed if omitted).')
parser.add_option('-m', '--memory_db', dest='memory_db', action='store... |
vichoward/python-neutronclient | neutronclient/tests/unit/test_name_or_id.py | Python | apache-2.0 | 5,590 | 0 | # Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | ient, "request")
path = getattr(self.client, "networks_path")
self.client.httpclient.request(
test_cli20.end_url(path, "fields=id&id=" + _id), 'GET',
body=None,
headers=mox.ContainsKeyV | alue('X-Auth-Token', test_cli20.TOKEN)
).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll()
returned_id = neutronV20.find_resourceid_by_name_or_id(
self.client, 'network', _id)
self.assertEqual(_id, returned_id)
def test_get_id_from_id_then_name_empty(self)... |
HiSchoolProject/BackSchool | manage.py | Python | lgpl-3.0 | 1,016 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hischool.settings")
# Add the "core" and "extensions" folders to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "extensions"))
sys.path.insert(0, os.path.join(os.... | on 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? Did you "
"forget to activate a virtual environ | ment?"
)
raise
execute_from_command_line(sys.argv)
|
jodal/comics | comics/comics/tehgladiators.py | Python | agpl-3.0 | 765 | 0 | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Teh Gladiators"
language = "en"
url = "http://www.tehgladiators.c | om/"
start_date = "2008-03-18"
rights = "Uros Jojic & Borislav Grabovic"
class Crawler(CrawlerBase):
history_capable_days = 90
| schedule = "We"
time_zone = "Europe/Belgrade"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.tehgladiators.com/rss.xml")
for entry in feed.for_date(pub_date):
page = self.parse_page(entry.link)
url = page.src('img[alt^="Teh Gladiators Webcomic"]')
... |
JuezUN/INGInious | inginious/frontend/plugins/analytics/analytics_collection_manager.py | Python | agpl-3.0 | 2,152 | 0 | class AnalyticsCollectionManagerSingleton:
""" This Singleton class manages the DBs analytics collection. """
__instance = None
@staticmethod
def get_instance(db=None):
""" Static access method. """
if not AnalyticsCollectionManagerSingleton.__instance:
AnalyticsCollectionM... | """ get data from DB according the filters """
results | = self.db.analytics.aggregate([
{
"$match": filters
},
{
"$project": {
"username": 1,
"service": 1,
"date": 1,
"course_id": 1
}
}
])
... |
MatthewCox/PyMoronBot | pymoronbot/modules/admin/Admin.py | Python | mit | 5,227 | 0.001531 | # -*- coding: utf-8 -*-
"""
Created on Feb 09, 2018
@author: Tyranic-Moron
"""
from twisted.plugin import IPlugin
from pymoronbot.moduleinterface import IModule
from pymoronbot.modules.commandinterface import BotCommand, admin
from zope.interface import implementer
import re
from collections import OrderedDict
from ... | n <subcommand> for subcommand help.".format(u'/'.join(self.subCommands.keys()),
self.bot.commandChar)
def _unrecognizedSubcommand(self, subCommand):
return u"unrecognized subcommand '{}', " \
u"available subcommand... | mmand, u', '.join(self.subCommands.keys()))
def execute(self, message):
if len(message.ParameterList) > 0:
subCommand = message.ParameterList[0].lower()
if subCommand not in self.subCommands:
return IRCResponse(ResponseType.Say,
sel... |
Mafarricos/Mafarricos-modded-xbmc-addons | plugin.video.streamajoker/resources/site-packages/streamajoker/__init__.py | Python | gpl-2.0 | 92 | 0 | from streamajok | er.plugin import plugin
from streamajoker import common, cm | d, library, index
|
flynx/pli | pli/persistance/sql/shelve.py | Python | bsd-3-clause | 2,359 | 0.038576 | #=======================================================================
__version__ = '''0.0.01'''
__sub_version__ = '''20070108034250'''
__copyright__ = '''(c) Alex A. Naanou 2003'''
#-----------------------------------------------------------------------
import pli.pattern.mixin.mapping as mapping
#-----------... | ==========================================
# vim:set ts=4 s | w=4 nowrap :
|
kaplun/harvesting-kit | harvestingkit/ftp_utils.py | Python | gpl-2.0 | 11,930 | 0.001676 | # -*- coding: utf-8 -*-
##
## This file is part of Harvesting Kit.
## Copyright (C) 2014 CERN.
##
## Harvesting Kit 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 ... | folder: string
"""
current_folder = self._ftp.pwd()
#creates the necessary folders on
#the server if they don't exist
folders = folder.split('/')
for fld in folders:
try:
self.cd(fld)
except error_perm: # folder does not exist
... | rom the server.
:param filename: the file to be deleted.
:type filename: string
"""
try:
self._ftp.delete(filename)
except error_perm: # target is either a directory
# either it does not exist
try:
current_fold... |
leighpauls/k2cro4 | content/test/data/layout_tests/LayoutTests/http/tests/websocket/tests/hybi/handshake-fail-by-more-protocol-header_wsh.py | Python | bsd-3-clause | 712 | 0.004213 | from mod_pywebsocket import handshake
from mod_pywebsocket.handshake.hybi import compute | _accept
def web_socket_do_extra_handshake(request):
msg = 'HTTP/1.1 101 Switching Protocols\r\n'
msg += 'Upgrade: websocket\r\n'
msg += 'Connection: Upgrade\r\n'
msg += 'Sec-WebSocket-Accept: %s\r\n' % compute_accept(request.headers_in['Sec-WebSocket-Key'])[0]
msg += 'Sec-WebSocket-Protocol: Match... | ise handshake.AbortedByUserException('Abort the connection') # Prevents pywebsocket from sending its own handshake message.
def web_socket_transfer_data(request):
pass
|
pigeonflight/strider-plone | docker/appengine/google/appengine/tools/devappserver2/application_configuration.py | Python | mit | 19,480 | 0.009138 | #!/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... |
import os
import os.path
import random
import string
import threading
import types
from google.appengine.api import appinfo
from google.appengine.api import appinfo_includes
from google | .appengine.api import backendinfo
from google.appengine.api import dispatchinfo
from google.appengine.tools.devappserver2 import errors
# Constants passed to functions registered with
# ModuleConfiguration.add_change_callback.
NORMALIZED_LIBRARIES_CHANGED = 1
SKIP_FILES_CHANGED = 2
HANDLERS_CHANGED = 3
INBOUND_SERVICE... |
khalibartan/Antidote-DM | Antidotes DM/Downloader/Credits.py | Python | gpl-2.0 | 3,631 | 0.007436 | # -*- coding: cp1252 -*-
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, di... | /></p>\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt; font-weight:600; font-style:italic;\">Utkarsh Gupta</span></p>\n"
"<p align=\"center\" sty | le=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Backend and extractor Development</span></p>\n"
"<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;... |
danieljwest/mycli | tests/test_naive_completion.py | Python | bsd-3-clause | 1,653 | 0.00363 | from __future__ import unicode_literals
import pytest
from prompt_toolkit.completion import Completion
from prompt_toolkit.document impor | t Document
@pytest.fixture
def completer():
import mycli.sqlcompleter as sqlcompleter
return sqlcompleter.SQLCompleter(smart_completion=False)
@pytest.fixture
def complete_event():
from mock import Mock
return Mock()
def test_empty_string_completion(completer, complete_event):
text = ''
posit... | n),
complete_event))
assert result == set(map(Completion, completer.all_completions))
def test_select_keyword_completion(completer, complete_event):
text = 'SEL'
position = len('SEL')
result = set(completer.get_completions(
Document(text=text, cursor_position=position),
complete... |
bmccann/examples | mnist_hogwild/main.py | Python | bsd-3-clause | 2,352 | 0.001276 | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from train import train
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, de... | =2, metavar='N',
help='how many training processes to use (default: 2)')
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2... | rd(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = F.relu(self.fc2(x))
return F.log_softmax(x)
if __name__ ==... |
thegazelle-ad/gazelle-server | deployment-resources/http-error-static-pages/5xx-static-html-generator.py | Python | mit | 815 | 0.008589 | import os, errno
# Create build folder if it doesn't exist
def get_path(relative_path):
cur_dir = os.path.dirname(__file__)
return os.path.join(cur_dir, relative_path)
try:
os.makedirs(get_path('build'))
except OSError as e:
if e.errno != errno.EEXIST:
raise
template = open(get_path('./5xx.template... |
for i in range(12):
numString = str(i) if i >= 10 else '0{}'.format(i)
fileName = './build/5{}.html'.format(numString)
outputFile = open(get_path(fileName), 'w')
htmlString = templateString.replace('{ERROR_CODE_PLACEHOLDER}', '5{}'.format(numString))
| outputFile.write(htmlString)
outputFile.close()
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyQt4/QtGui/QIntValidator.py | Python | gpl-2.0 | 1,504 | 0.009973 | # encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python3/dist-packages/PyQt4/QtGui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
from .QValidator import QValidator
class QIntValidator(QValidator):
"""
QIntValidator(QObject parent=None)
... | pass
def setRange(self, p_int, p_int_1): # real | signature unknown; restored from __doc__
""" QIntValidator.setRange(int, int) """
pass
def setTop(self, p_int): # real signature unknown; restored from __doc__
""" QIntValidator.setTop(int) """
pass
def top(self): # real signature unknown; restored from __doc__
""" QInt... |
serge-sans-paille/pythran | pythran/analyses/optimizable_comprehension.py | Python | bsd-3-clause | 1,008 | 0 | """
OptimizableComp finds whether a comprehension can be optimized.
"""
from pythran.analyses.identifiers import Identifiers
from pythran.passmanager import NodeAnalysis
class OptimizableComprehension(NodeAnalysis):
"""Find whether a comprehension can be optimized."""
def __init__(self):
self.result ... | ension, self).__init__(Identifiers)
def check_comprehension(self, iters):
targets = {gen.target.id for gen in iters}
o | ptimizable = True
for it in iters:
ids = self.gather(Identifiers, it)
optimizable &= all(((ident == it.target.id) |
(ident not in targets)) for ident in ids)
return optimizable
def visit_ListComp(self, node):
if (self.check_comprehen... |
TwilioDevEd/api-snippets | notifications/rest/credentials/update-credential/update-credential.7.x.py | Python | mit | 707 | 0 | # NOTE: This example uses the next generation Twilio helper library - for more
# informat | ion on how to download and install this version, visit
# https://www.twilio.com/docs/libraries/python
import os
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secure
account = os.environ['TWILIO_ACCOUNT_SID']
token =... | XXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.update(friendly_name="MyCredential",
sandbox=True)
print(credential.friendly_name)
|
markovmodel/PyEMMA | pyemma/coordinates/tests/test_pipeline.py | Python | lgpl-3.0 | 7,347 | 0.002178 |
# This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA 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 vers... | p.set_element(0, reader_gen)
assert hasattr(kmeans, '_chunks')
p.parametrize()
out2 = kmeans.get_output()
self.assertFalse(np.array_equal(out1, out2), "Data source changed, so should the resulting clusters.")
def test_discretizer(self):
reader_gen = DataInMemory(data=s... | api.discretizer(reader_gen)._chain[-1].get_output()
api.discretizer(reader_gen, transform=api.tica())._chain[-1].get_output()
api.discretizer(reader_gen, cluster=api.cluster_uniform_time())._chain[-1].get_output()
api.discretizer(reader_gen, transform=api.pca(), cluster=api.cluster_regspac... |
stanford-futuredata/macrobase | tools/bench/contextual/contextual_execute_workflows.py | Python | apache-2.0 | 12,283 | 0.002198 | import argparse
import json
import os
from time import strftime
testing_dir = "workflows"
batch_template_conf_file = "contextual_batch_template.conf"
streaming_template_conf_file = "contextual_streaming_template.conf"
default_args = {
"macrobase.analysis.minOIRatio": 3.0,
"macrobase.analysis.minSupport": 0.5,
... | e.split("Number of itemsets:")[1].strip()
num_itemsets = int(line | )
elif "iterations" in line:
line = line.split(
"Number of iterations in MCD step:")[1].strip()
num_iterations = int(line)
elif "Tuples / second w/o itemset mining" in line:
line = line.split("Tuples / se... |
marxin/youtube-dl | youtube_dl/extractor/tnaflix.py | Python | unlicense | 2,854 | 0.002803 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
fix_xml_ampersands,
)
class TNAFlixIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tnaflix\.com/(?P<cat_id>[\w-]+)/(?P<display_id>[\w-]+)/video(?P<id>\d+)'
_TITLE_REGEX = r... | o_relative_url(self._html_search_regex(
self._CONFIG_REGEX, webpage, 'flashvars.config'), 'http:')
| cfg_xml = self._download_xml(
cfg_url, display_id, note='Downloading metadata',
transform_source=fix_xml_ampersands)
thumbnail = cfg_xml.find('./startThumb').text
formats = []
for item in cfg_xml.findall('./quality/item'):
video_url = re.sub('speed=\d+', 'sp... |
mishbahr/djangocms-twitter2 | djangocms_twitter/migrations/0001_initial.py | Python | bsd-3-clause | 2,646 | 0.003779 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import connected_accounts.fields
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('connected_accounts', '0001_initial'),
('cms', '0001_initial'),
]
... | bed a timeline for Tweets from an individual user, a u | ser's favorites or any search query or hashtag.", max_length=50, verbose_name='Available Timelines', choices=[('user', 'User Timeline'), ('favorites', 'Favorites'), ('search', 'Search Query')])),
('show_avatar', models.BooleanField(default=True, help_text='Shows or hides the avatar image.', verbose_name... |
datagutten/comics | comics/core/models.py | Python | agpl-3.0 | 4,089 | 0 | import datetime
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from comics.core.managers import ComicManager
class Comic(models.Model):
LANGUAGES = (
... | lf.comic.slug,
'year': self.pub_date.year,
'month': se | lf.pub_date.month,
'day': self.pub_date.day,
})
def get_ordered_images(self):
if not getattr(self, '_ordered_images', []):
self._ordered_images = list(self.images.order_by('id'))
return self._ordered_images
# Let all created dirs and files be writable by the group
... |
npinto/Oger | Oger/gradient/__init__.py | Python | gpl-3.0 | 1,376 | 0.003634 | """
This subpackage contains nodes and trainers for gradient based learning.
Its purpose is to automate backpropagation and gradient calculation for models
that can be trained using gradient methods. This allows complex architectures
to be trained using external optimizers that can use gradient and loss
information.
... | are currently supported are the PerceptronNode and the
ERBMNode. Examples of optimization algorithms that have been wrapped into
trainer objects are gradient descent, RPROP, conjugate gradient and BFGS.
The 'models' package contains some pre-defined architectures that use the
gradient package for training.
"""
from... | entDescentTrainer, LBFGSBTrainer)
from models import (MLPNode, AutoencoderNode)
del gradient_nodes
del trainers
del models
__all__ = ['GradientExtensionNode', 'BackpropNode', 'GradientPerceptronNode', 'GradientRBMNode',
'CGTrainer', 'BFGSTrainer', 'RPROPTrainer', 'GradientDescentTrainer', 'LBFGSBTrainer', '... |
geodynamics/burnman | burnman/tools/chemistry.py | Python | gpl-2.0 | 8,056 | 0.000372 | # This file is part of BurnMan - a thermoelastic and thermodynamic toolkit
# for the Earth and Planetary Sciences
# Copyright (C) 2012 - 2021 by the BurnMan team, released under the GNU
# GPL v2 or later.
# This module provides higher level chemistry-related functions.
from __future__ import absolute_import
import nu... | nent_formula, assemblage, reference_assemblage):
"""
Parameters
----------
component_formula: dictionary
Chemical formula for which to compute the relative fugacity.
assemblage: burnman.Composite object
se | t_method and set_state should already have been used.
reference_assemblage: burnman.Composite object
set_method and set_state should already have been used.
Returns
-------
relative_fugacity : float
Value of the fugacity of the component in the assemblage
... |
brentjens/pyautoplot | test/testf0seqnrcalculation.py | Python | gpl-3.0 | 6,014 | 0.011141 | """
Example usage:
python3 testf0seqnrcalculation.py 548659 \
../testdata/sample_data_548659/L548659.parset \
../testdata/sample_data_548659/file-sizes.txt \
../testdata/sample_data_548659/f0seqnr-sizes.txt
"""
import os
import sys
sys.path.append("../scripts")
import create_html
def test... | d, in_parset_path, in_file_sizes_path, in_f0seqnr_sizes_path):
result = True
parset = create_html.parset_summary(in_sas_id, in_parset_path)
file_sizes_dict | = create_html.parse_file_sizes(in_file_sizes_path)
analysed_file_sizes_dict = create_html.file_size_analysis(parset, file_sizes_dict)
highest_file_size_mb = analysed_file_sizes_dict['max_ms_size_mb'].max()
f0seqnr_sizes_dict = create_html.parse_file_sizes(in_f0seqnr_sizes_path, os.path.dirname)
f0... |
stevens4/rover3 | lowLevelLibrary.py | Python | gpl-2.0 | 9,709 | 0.009888 |
from Adafruit_ADS1x15 import ADS1x15 as A2DObject
from functools import partial
# create AI channel objects
class aiChannel:
def __init__(self,confDict):
#open connection on physicalChannel
self.name = confDict['labelText']
self.i2cAddress = confDict['i2cAddress']
self.connectionT... | n = clockFunct
self.currentState = False
GPIO.setup(self.physChanNum,GPIO.OUT)
initState = confDict['initState'] in ['True']
self.setState(initState)
| self.interlockState = False
initInterlockState = confDict['initInterlockState'] in ['True']
self.setInterlockState(initInterlockState)
self.interlocks = {}
self.confDict = confDict
# initialize interlock configparser object, read in
self.interlockC... |
anchore/anchore-engine | tests/functional/clients/standalone/package_list/__init__.py | Python | apache-2.0 | 1,723 | 0.001741 | import pytest
#
# Preloaded fixtures, with pytest.param that allows a nicer repr when the test runs, instead of the
# default which slaps the whole (giant) dictionary, making output unreadable.
#
def package_path(path):
"""
Produce a recognizable path name for a package. For the input of:
/usr/lib/node_... | = []
for field in fields | :
params += [
pytest.param(
path,
metadata,
field,
id="field={} element={}".format(
repr(field), repr(path.split("/")[-1])
),
)
for path... |
mdrumond/tensorflow | tensorflow/python/layers/core_test.py | Python | apache-2.0 | 19,327 | 0.008072 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | nse = core_layers.Dense(4, name='my_dense')
with self.assertRaises(ValueError):
dense(inputs)
inputs = array_ops.placeholder(
dtype=dtypes.float32, shape=[None, None, None])
dense = core_layers.Dense(4, name='my_dense')
with self.assertRaises(ValueError):
dense(inputs)
inputs =... | dense = core_layers.Dense(4, name='my_dense')
dense(inputs)
inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, None, 3])
dense = core_layers.Dense(4, name='my_dense')
dense(inputs)
@test_util.run_in_graph_and_eager_modes()
def testActivation(self):
dense = core_layers.Dense(2, a... |
elhoim/openioc_scan | openioc_scan.py | Python | gpl-2.0 | 105,288 | 0.006468 | # openioc_scan Volatility plugin
# based on ioc_writer (https://github.com/mandiant/ioc_writer) and pyioc (https://github.com/jeffbryner/pyioc)
# Copyright (c) 2014 Takahiro Haruyama (@cci_forensics)
# http://takahiroharuyama.github.io/
import volatility.utils as utils
import volatility.obj as obj
import volatility.de... | lity.commands as commands
import volatility.plugins.common as common
import volatility.plugins.netscan as netscan
import volatility.plugins.overlays.windows.tcpip_vtypes as tcpip_vtypes
import volatility.plugins.registry.hivelist as hivelist
import volatility.plugins.registry.shimcache as shimcache
import volatility.p... | latility.plugins.filescan as filescan
import volatility.plugins.privileges as privileges
import volatility.plugins.ssdt as ssdt
import volatility.plugins.mftparser as mftparser
import volatility.plugins.malware.malfind as malfind
import volatility.plugins.malware.impscan as impscan
import volatility.plugins.malware.psx... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/gslb/gslbsite_binding.py | Python | apache-2.0 | 3,701 | 0.032694 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
return None
except Exception as e :
raise e
@classmethod
def get(self, service, sitename) :
ur""" Use this API to fetch gslbsite_binding resource.
"""
try :
if type(sitename) is not list :
obj = gslbsite_binding()
obj.sitename = sitename
response = obj.get_resource(service)
else :
... | name)) :
obj[i].sitename = sitename[i];
response[i] = obj[i].get_resource(service)
return response
except Exception as e:
raise e
class gslbsite_binding_response(base_response) :
def __init__(self, length=1) :
self.gslbsite_binding = []
self.errorcode = 0
self.message = ""
self.severity = ... |
vavavr00m/pymine | util/base58.py | Python | apache-2.0 | 1,596 | 0.017544 | #!/usr/bin/env python
##
## Copyright 2009 Adriana Lukas & Alec Muffett
##
## 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 requi... | ibuted under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
## | implied. See the License for the specific language governing
## permissions and limitations under the License.
##
"""docstring goes here""" # :-)
# spec: http://www.flickr.com/groups/api/discuss/72157616713786392/
__b58chars = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
__b58base = len(__b58chars) #... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | Python | gpl-3.0 | 21,732 | 0.002761 | # This file is part of xmpp-backends (https://github.com/mathiasertl/xmpp-backends).
#
# xmpp-backends 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 l... | mppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if ... | ersion:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
|
Gurulhu/Reborn | features/chat/markov_creation_snippets.py | Python | mit | 895 | 0.086034 | f = open("taylor.txt")
lines = f.read().split("\n")
f.close()
words = []
for i in lines:
words.extend( i. | split(" ") )
words = pd.Dataframe( words )
words = words[0].unique()
db = {}
for word in words:
db.update( { word : { "_word" : word } } )
db.update( {"_begin" : {"_word" : "_begin" } } )
for i in lines:
line = i.split(" ")
try:
n = db["_begin"][line[0]]
except:
n = 0
db["... | j-1]].update( { line[j] : n + 1 } )
l = len( line ) - 1
try:
n = db[ line( l ) ]["_end"]
except:
n = 0
db[ line[ l ]].update( {"_end" : n + 1} )
print( line, line[l] )
result = collection.insert_many( [db[i] for i in db.keys() ] )
|
south-coast-science/scs_dfe_eng | src/scs_dfe/gas/scd30/pca9543a.py | Python | mit | 1,642 | 0.003654 | """
Created on 19 Nov 2020
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Two-Channel I2C-Bus Switch With Interrupt Logic and Reset
https://www.ti.com/product/PCA9543A
"""
from scs_host.bus.i2c import I2C
# ------------------------------------------------------------------------------------------------... | --------------------------------------------------------------------------------------------
def enable | (self, ch0, ch1):
ch0_en = 0x01 if ch0 else 0x00
ch1_en = 0x02 if ch1 else 0x00
ctrl = ch1_en | ch0_en
try:
I2C.Sensors.start_tx(self.__addr)
I2C.Sensors.write(ctrl)
finally:
I2C.Sensors.end_tx()
def read(self):
try:
... |
E2i9/Virdi_Server | functions/set_vagas_apto.py | Python | agpl-3.0 | 1,071 | 0.004669 | import psycopg2.extensions
from operator import add
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
with psycopg2.connect(database="reserva", user="cezar") as conn_pg:
with conn_pg.cursor() as conn_pgs:
conn_pgs.execute("sel... | e = (%s);", (apto,))
_vaga = conn_pgs4.fetchone()
with conn_pg.cursor() as conn_pgs5:
conn_pgs5.execute("update | occ_apto set vaga_carro_id = (%s) where name = (%s);", (_vaga, apto,))
|
jacknjzhou/neutron | neutron/services/qos/qos_plugin.py | Python | apache-2.0 | 7,356 | 0.000136 | # Copyright (c) 2015 Red Hat 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... | utron.services.qos.notification_drivers import manager as driver_mgr
LOG = logging.getLogger(__name__)
class QoSPlugin(qos.QoSPluginBase):
"""Implementation of the Neutron QoS Service Plugin.
This class implements a Quality of Service plugin that
provides quality of service parameters over ports and
... | ).__init__()
self.notification_driver_manager = (
driver_mgr.QosServiceNotificationDriverManager())
@db_base_plugin_common.convert_result_to_dict
def create_policy(self, context, policy):
policy = policy_object.QosPolicy(context, **policy['policy'])
policy.create()
s... |
vesta33/aa-test | MyClip.py | Python | gpl-2.0 | 212 | 0.023585 | __author__ = 'anastas | sias'
import os
#python MyClip.py kopeerib clipboardi programmi output
def addToClipBoard():
command = 'python Isikukood_new.py | clip'
| os.system(command)
#example
addToClipBoard() |
bczmufrn/frequencia | frequencia/calendario/models.py | Python | mit | 326 | 0.030675 | from django.db import models
from frequencia.core.base | model import basemodel
class FeriadoCalendarioAcademico(basemodel):
nome = models.CharField('Nome | ', max_length=100)
data = models.DateField('Data')
def __str__(self):
return self.nome
class Meta:
verbose_name = 'Feriado'
verbose_name_plural = 'Feriados'
|
petrushev/txplaya | txplaya/player.py | Python | gpl-3.0 | 13,214 | 0.001059 | from decimal import Decimal
from collections import deque
import gc
from uuid import uuid4
from operator import itemgetter
import json
from twisted.internet import reactor
from twisted.internet.task import deferLater
from twisted.python import log
from txplaya.library import Library
from txplaya.lastfm import getScro... |
def currentTrack(self):
if self._currentUid is None:
return None
return self._reg[self._currentUid]
def start(self, position=None):
if self._reg == {}:
raise Playlis | tError, 'Empty playlist'
if position >= len(self._reg) or position < 0:
raise PlaylistError, 'Position out of bounds'
if position is None:
position = 0
keys = sorted(self._order.keys())
dposition = keys[position]
trackUid = self._order[dposition]
... |
MounirMesselmeni/django | django/core/validators.py | Python | bsd-3-clause | 15,107 | 0.00278 | from __future__ import unicode_literals
import re
from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text
from django.utils.functional import SimpleLazyObject
from django.utils.ipv6 import is_vali... | code=self.code)
url = value
integer_validator = RegexValidator(
_lazy_re_compile('^-?\d+\Z'),
message=_('Enter a valid integer.'),
code='invalid',
)
def validate_integer(value):
return integer_validator(value)
@deconstructible
class EmailValidator(object):
message = _('Enter a valid... | r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string
re.IGNORECASE)
domain_regex = _lazy_re_compile(
# max length for domain name labels is 63 characters ... |
plotly/plotly.py | packages/python/plotly/plotly/validators/funnel/marker/colorbar/_bgcolor.py | Python | mit | 429 | 0.002331 | import _ | plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bgcolor", parent_name="funnel.marker.colorbar", **kwargs
):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=par... | **kwargs
)
|
onlyjus/pyqtgraph | pyqtgraph/opengl/GLViewWidget.py | Python | mit | 18,189 | 0.009071 | from ..Qt import QtCore, QtGui, QtOpenGL, USE_PYQT5
from OpenGL.GL import *
import OpenGL.GL.framebufferobjects as glfbo
import numpy as np
from .. import Vector
from .. import functions as fn
##Vector = QtGui.QVector3D
ShareWidget = None
class GLViewWidget(QtOpenGL.QGLWidget):
"""
Basic widget for displayin... | m(self, item):
self.items.remove(item)
item._setView(None)
self.update()
def | initializeGL(self):
self.resizeGL(self.width(), self.height())
def setBackgroundColor(self, *args, **kwds):
"""
Set the background color of the widget. Accepts the same arguments as
pg.mkColor().
"""
self.opts['bgcolor'] = fn.mkColor(*args, **kwds)
s... |
traceguide/api-php | vendor/apache/thrift/lib/py/src/transport/TTransport.py | Python | mit | 11,455 | 0.011349 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | sport Factory"""
def getTransport(self, trans):
return trans
class TBufferedTransportFactory:
"""Factory transport that builds buffered transports"""
def getTransport(self, trans):
buffered = TBufferedTransport(trans)
return buffered
class TBuffere | dTransport(TTransportBase, CReadableTransport):
"""Class that wraps another transport and buffers its I/O.
The implementation uses a (configurable) fixed-size read buffer
but buffers all writes until a flush is performed.
"""
DEFAULT_BUFFER = 4096
def __init__(self, trans, rbuf_size=DEFAULT_BUFFER):
s... |
jptrosclair/webpush | src/ftpstore.py | Python | unlicense | 2,104 | 0.001426 | import ftplib
import os
import datastore
class FtpStore(datastore.DataStore):
def progress(self, block):
self.trans_total += len(block)
datastore.DataStore.progress(self, self.trans_total, self.file_size_total)
def exists(self, file):
if file == "" or file == "/" or file == "./":
... | if f == os.path.basename(file):
return True
except ftplib.error_perm:
pass
return False
def makedirs(self, path):
if path == "" or | path == "/" or path == "./":
return
if not self.exists(os.path.dirname(path)):
self.makedirs(os.path.dirname(path))
if not self.exists(path):
self.ftp.mkd(path)
def store(self, file):
self.time = None
if self.exists(file):
s... |
danielnyga/pracmln | python2/pracmln/__init__.py | Python | bsd-2-clause | 1,458 | 0 | # (C) 2012-2015 by Daniel Nyga
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distrib... | ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from mln.base import MLN
from mln.database import Database
from mln.constants import *
from mlnlearn import MLNLearn
from mlnlearn import MLNLearn as learn
from mlnquery impo... | om mlnlearn import QUERY_PREDS
from mlnlearn import EVIDENCE_PREDS
from utils.project import mlnpath
from utils.project import PRACMLNConfig
|
EndPointCorp/lg_ros_nodes | lg_mirror/scripts/touch_router_node.py | Python | apache-2.0 | 1,992 | 0.002008 | #!/usr/bin/env python3
from functools import partial
import rospy
import sys
from lg_mirror.touch_router import TouchRouter
from lg_common.helpers import on_new_scene, load_director_message
from lg_msg_defs.msg import EvdevEvents, RoutedEvdevEvents, StringArray
from lg_common.helpers import handle_initial_state
from ... | route_topic,
StringArray,
queue_size=10,
subscriber_listener=SubscribeListener(new_listener_cb)
)
# Hacky callback to parse the initial scene.
def h | andle_initial_scene_msg(msg):
d = load_director_message(msg)
router.handle_scene(publish_active_routes, d)
handle_initial_state(handle_initial_scene_msg)
rospy.Service(route_topic, TouchRoutes, router.handle_service_request)
scene_cb = partial(router.handle_scene, publish_active_routes)
... |
django-bmf/django-bmf | djangobmf/contrib/location/serializers.py | Python | bsd-3-clause | 507 | 0 | #!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from djangobmf.serializers import ModuleSerializer
from rest_framework import serializers
class WarehouseSerial | izer(ModuleSerializer):
class Meta:
fields = (
'name',
)
cla | ss LocationSerializer(ModuleSerializer):
warehouse_name = serializers.ReadOnlyField(source='warehouse.name')
class Meta:
fields = (
'name',
'warehouse_name',
)
|
joshand/CICO | cico_meraki.py | Python | mit | 16,220 | 0.004747 | import requests
# https://github.com/kennethreitz/grequests/issues/103
from gevent import monkey
def stub(*args, **kwargs): # pylint: disable=unused-argument
pass
monkey.patch_all = stub
import grequests
import os
import json
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
meraki_ap... | f matchval == net[comp_id1]:
kid1 = net["id"]
if kid1 not in content_dict:
content_dict[kid1] = {}
content_dict[kid1]["info"] = net
| content_dict[kid1][content_key] = inlist
break
else:
# this is a dictionary of lists. if the match is present in this dictionary, continue parsing
if matchval in json.dumps(comp_list[net][comp_id1]):
... |
ywangd/stash | lib/mlpatches/tests/sp_test.py | Python | mit | 1,266 | 0 | # -*- coding: utf-8 -*-
"""subprocess tests."""
from __future__ import print_function
import subprocess
_stash = globals()["_stash"]
text = _stash.text_color
# exit test
print(text("starting exit test...", "yellow"))
try:
subprocess.check_call("exit 0")
print(text(" 0 OK", "green"))
except subprocess.CalledPr... | t(text(" 1 OK", "green"))
# parent I/O
print(text("\nstarting parent I/O test...", "yellow"))
print(" please check for I/O")
subprocess.call("man readme")
# output test
print(text("\nstarting check_output test...", "yellow"))
string = "Test"
try:
output = subprocess.check_output("echo " + string)
if output.e... | "))
else:
print(text(" 0 OK", "green"))
except subprocess.CalledProcessError:
print(text(" 0 ERROR", "red"))
try:
output = subprocess.check_output("gci wasd")
print(text(" 1 ERROR", "red"))
except subprocess.CalledProcessError:
print(text(" 1 OK", "green"))
|
yudingding6197/fin_script | debug/recover/s7_try_recover.py | Python | gpl-2.0 | 12,051 | 0.047465 | #!/usr/bin/env python
# -*- coding:gbk -*-
import sys
import re
import os
import string
import datetime
import platform
import shutil
import getopt
import pandas as pd
sys.path.append('.')
from internal.handle_realtm import *
from internal.common_inf import *
from internal.realtime_obj import *
from internal.output_ge... | (props[3]),2)
pre_close = round(float(props[9]),2)
volume = int(props[8])
o_percent = (open-pre_close)*100/pre_close
c_percent = (price-pre_clos | e)*100/pre_close
h_percent = (high-pre_close)*100/pre_close
l_percent = (low-pre_close)*100/pre_close
open_percent = spc_round2(o_percent,2)
change_percent = spc_round2(c_percent,2)
high_zf_percent = spc_round2(h_percent,2)
low_df_percent = spc_round2(l_percent,2)
stk_list = [0, 0]
count = 0
stat =... |
iulian787/spack | var/spack/repos/builtin/packages/r-combinat/package.py | Python | lgpl-2.1 | 598 | 0.003344 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. S | ee the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RCombinat(RPackage):
"""routines for combinatorics"""
homepage = "https://cloud.r-project.org/pa | ckage=combinat"
url = "https://cloud.r-project.org/src/contrib/combinat_0.0-8.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/combinat/"
version('0.0-8', sha256='1513cf6b6ed74865bfdd9f8ca58feae12b62f38965d1a32c6130bef810ca30c1')
|
ZhangXinNan/tensorflow | tensorflow/contrib/optimizer_v2/rmsprop_test.py | Python | apache-2.0 | 18,899 | 0.010635 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ype=dtype.as_numpy_dtype)
if use_resource:
var0 = resource_variable_ops.ResourceVariable(var0_np)
var1 = resource_variable_ops.ResourceVariable(var1_np)
else:
var0 = variables.Variable(var0_np)
var1 = variables.Variable(var1_np)
grads0 = constant_op.constant(grads0_np)... | cay,
momentum=momentum,
epsilon=epsilon,
centered=centered)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
mg0 = opt.get_slot(var0, "mg")
self.assertEqual(mg0 is not None, centered)
mg1 = opt.... |
antoinecarme/pyaf | tests/artificial/transf_Quantization/trend_LinearTrend/cycle_5/ar_/test_artificial_128_Quantization_LinearTrend_5__100.py | Python | bsd-3-clause | 270 | 0.085185 | import py | af.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend | ", cycle_length = 5, transform = "Quantization", sigma = 0.0, exog_count = 100, ar_order = 0); |
ytisf/PyExfil | pyexfil/network/QUIC/quic_client.py | Python | mit | 6,330 | 0.004265 |
import sys
import time
import socket
import struct
import random
import hashlib
import urllib2
from Crypto import Random
from Crypto.Cipher import AES
# from itertools import izip_longest
# Setting timeout so that we won't wait forever
timeout = 2
socket.setdefaulttimeout(timeout)
limit = 256*256*256*256 - 1
def ... | of 255.\n")
return 1
header = "\x0c" # Public Flags
header += self.sequence # Adding CID
header += count_id # Packet Count
return header
def _getFileContent(self, file_path):
try:
f = open(file_path, ... | ata = f.read()
f.close()
sys.stdout.write("[+]\tFile '%s' was loaded for exfiltration.\n" % file_path)
return data
except IOError, e:
sys.stderr.write("[-]\tUnable to read file '%s'.\n%s.\n" % (file_path, e))
return 1
def sendFile(self, file_path)... |
Haynie-Research-and-Development/jarvis | deps/lib/python3.4/site-packages/Cryptodome/SelfTest/Cipher/test_OCB.py | Python | gpl-2.0 | 25,029 | 0.00032 | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... | crypt":
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
result = getattr(cipher, func)(b(""))
self.assertEqual(result, b(""))
def test_either_encrypt_or_decrypt(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
c | ipher.encrypt(b("xyz"))
self.assertRaises(TypeError, cipher.decrypt, b("xyz"))
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.decrypt(b("xyz"))
self.assertRaises(TypeError, cipher.encrypt, b("xyz"))
def test_data_must_be_bytes(self):
cipher = AES.n... |
jonstacks13/ilo-utils | ilo_utils/utils.py | Python | bsd-3-clause | 1,788 | 0 | import socket
import threading
from xml.etree import ElementTree
import requests
class PortScan(threading.Thread):
def __init__(self, ip, port, timeout=2):
threading.Thread.__init__(self)
self.ip = ip
self.port = port
self.timeout = timeout
self.open = False
def run(s... | run(self):
url = 'http://{}/xmldata?item=all'.format(self.host)
try:
self.resp = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
pass
except requests.exceptions.ConnectionError:
pass
else:
if self.resp.st... | self.success = True
tree = ElementTree.fromstring(self.resp.content)
hsi = tree.find('HSI')
if hsi is not None:
self.serial = hsi.find('SBSN').text.strip()
self.model = hsi.find('SPN').text.strip()
mp = tree.fin... |
jvrsantacruz/XlsxWriter | xlsxwriter/test/worksheet/test_sparkline07.py | Python | bsd-2-clause | 14,757 | 0.002168 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ..helperfunctions import _xml_to_list
from ...worksheet import Worksheet
class TestAss... | <c r="C6">
<v>3</v>
</c>
<c r="D6">
<v | >-1</v>
</c>
<c r="E6">
<v>0</v>
</c>
</row>
<row r="7" spans="1:5" x14ac:dyDescent="0.25">
<c r="A7">
<v>-2</v>
</c>
... |
blamarvt/dhcpz | setup.py | Python | apache-2.0 | 662 | 0.042296 | #!/usr/bin/python
from setuptools import setup
setup(
name = "dhcpz",
version = "0.2.0",
author = [
"Nicholas VonHollen",
"Brian Lamar"
],
author_email = [
"nicholas.vonhollen@rackspace.com",
| "brian.lamar@rackspace.com",
],
license = "Apache License 2.0",
packages = ['dhcpz', 'dhcpz.handlers'],
package_dir = {"":"src/py"},
install_requires = ['gevent', 'netifaces'],
data_files = [
('/etc', ['conf/dhcpz.conf']),
('/etc/init.d', ['src/init | .d/dhcpz']),
('/usr/bin', ['src/bin/dhcpz']),
],
)
|
elbeardmorez/quodlibet | quodlibet/quodlibet/ext/events/searchprovider.py | Python | gpl-2.0 | 5,620 | 0 | # -*- coding: utf-8 -*-
# Copyright 2013 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) an... | date(description),
"gicon": ENTRY_ICON,
}, signature="ss")
metas.append(meta)
return metas
@dbus.service.method(IFACE, in_signature="sasu")
def ActivateResult(self, identifier, terms, timestamp):
songs = | get_songs_for_ids(app.library, [identifier])
if not songs:
return
if app.player.go_to(songs[0], True):
app.player.paused = False
@dbus.service.method(IFACE, in_signature="asu")
def LaunchSearch(self, terms, timestamp):
try:
app.window.browser.filter... |
uclouvain/osis_louvain | base/views/learning_units/detail.py | Python | agpl-3.0 | 2,249 | 0.001335 | ############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core bu... | nse as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR ... | ublic License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
############################################################################
from django.contrib.auth.decorator... |
skygate/CodeSamples | python/abstract_base_classes/base.py | Python | unlicense | 507 | 0 | import abc
class BaseBroker(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get | _contact_url(self, email):
""" Gets contact's profile URL from CRM """
pass
@abc.abstractmethod
def create_contact(self, email, first_name, last_name):
"""
Creates contact in CRM. and returns contact's URL
:param email Contact's email
:param first_name ... | ame
"""
pass
|
sixfeetup/cloud-custodian | c7n/filters/offhours.py | Python | apache-2.0 | 21,487 | 0.000558 | # Copyright 2015-2017 Capital One Services, 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 ... | es not *exactly* match the hour specified in the policy, nothing will be
done at all.
As a result of this, if custodian stops an instance or suspends an ASG and you
need to start/resume it, you can safe | ly do so manually and custodian won't touch
it again until the next day.
ElasticBeanstalk, EFS and Other Services with Tag Value Restrictions
====================================================================
A number of AWS services have restrictions on the characters that can be used
in tag values, such as `Elast... |
tqchen/tvm | tests/python/relay/test_backend_compile_engine.py | Python | apache-2.0 | 9,932 | 0.001208 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | nv2d_nchw(outs)
@autotvm.register_topi_compute("test/conv2d_2")
def _compute_conv2d_2(cfg, input, filter, strides, padding, dilation, out_dtype):
re | turn topi.nn.conv2d_nchw(input, filter, strides, padding, dilation, out_dtype)
@autotvm.register_topi_schedule("test/conv2d_2")
def _schedule_conv2d_2(cfg, outs):
return topi.generic.schedule_conv2d_nchw(outs)
def _compute_conv2d_3(input, filter, strides, padding, dilation, out_dtype):
return topi.nn.conv2d... |
kubeflow/pipelines | components/aws/sagemaker/tests/unit_tests/tests/ground_truth/test_ground_truth_component.py | Python | apache-2.0 | 8,622 | 0.00116 | from common.sagemaker_component import SageMakerJobStatus
from ground_truth.src.sagemaker_ground_truth_spec import SageMakerGroundTruthSpec
from ground_truth.src.sagemaker_ground_truth_component import (
SageMakerGroundTruthComponent,
)
from tests.unit_tests.tests.ground_truth.test_ground_truth_spec import (
Gr... | nWorkersPerDataObject": 1,
"TaskTimeLimitInSeconds": 180,
"TaskAvailabilityLifetimeInSeconds": 30,
"MaxConcurrentTaskCount": 10,
| "AnnotationConsolidationConfig": {
"AnnotationConsolidationLambdaArn": ""
},
"PublicWorkforceTaskPrice": {
"AmountInUsd": {
"Dollars": 0,
"Cents": 0,
... |
facundoq/ipim | tp1/py/tp.py | Python | gpl-3.0 | 10,677 | 0.013206 | from pylab import *
from math import exp, sqrt
from image import *
from filters import *
from nibabel import load
import numpy
import image_processing
import image as img
import os
# This module generates
class C:
#a Config class, just a collection of constants
output_dir = '../report/img/results/'
input... | bilateral= results['bilateral']
bilateral = bilateral[bilateral[:, 4] == sigmaD]
bilateral = bilateral[bilateral[: | , 5] == sigmaR]
label = 'Bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (sigmaD,sigmaR)
style=C.markers[C.bilateral_sigmaRs.index(sigmaR)]+C.colors[C.bilateral_sigmaDs.index(sigmaD)]+'-'
plot(bilateral[:, 3], bilateral[:, column_y],style,label=label )
legend(loc=2)
sa... |
jasonhejna/raspberrytraffic | makeimage.py | Python | mit | 1,014 | 0.016765 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class browser(QWebView):
def __init__(self, parent=None):
super(browser, self).__init__(parent)
self.setFixedSize(1920, 1080)
self.timerScreen = QT | imer()
| self.timerScreen.setInterval(17000)
self.timerScreen.setSingleShot(True)
self.timerScreen.timeout.connect(self.takeScreenshot)
self.loadFinished.connect(self.timerScreen.start)
self.load(QUrl("file:///home/pi/index1.html"))
def takeScreenshot(self):
image = QImag... |
saurabhkumar1989/programming_question_python | questions/integer_number.py | Python | apache-2.0 | 58 | 0.068966 |
a = 1224
while a:
| temp = a%10
print temp
a = a//10
| |
istinspring/imscrape-template | api.py | Python | mit | 143 | 0 | from utils.api_factory import ApiFac | tory
api = ApiFactory.get_instance()
if __name__ == '__main__':
api.run(host='0.0. | 0.0', port=8000)
|
mjumbewu/django-model-filters | example_project/settings.py | Python | bsd-3-clause | 5,060 | 0.002174 | # Django settings for example project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'... | h not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this ins... | can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers a... |
michaelorr/helga-spook | setup.py | Python | gpl-3.0 | 1,038 | 0.004817 | from setuptools import setup, find_packages
from helga_spook import __version | __ as version
setup(name='helga-spook',
version=version,
description=('prints nsa buzzwords'),
classifiers=['Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General | Public License v3 (GPLv3)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat :: Internet Relay Chat'],
keywords='irc ... |
CIGIHub/django-icontact-integration | setup.py | Python | gpl-2.0 | 1,167 | 0 | import os
from setuptools import setup
from setuptools import find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='i... | ',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/H... | Content',
],
)
|
dlintott/gns3-ppa | setup.py | Python | gpl-2.0 | 14,696 | 0.010207 | #!/usr/bin/env python
# vim: expandtab ts=4 sw=4 sts=4 fileencoding=utf-8:
"""Setup script for the GNS3 packages."""
import sys, os, shutil, platform
sys.path.append('./src')
from distutils.core import setup, Extension
from glob import glob
# current version of GNS3
VERSION = "0.8.6"
try:
# delete previous build... | IX",
"GNS3.Ui.ConfigurationPages.Page_ASA",
"GNS3.Ui.ConfigurationPages.Page_AWP",
"GNS3.Ui.ConfigurationPages.Page_JunOS",
... | ges.Page_IDS",
"GNS3.Ui.ConfigurationPages.Page_Qemu",
"GNS3.Ui.ConfigurationPages.Page_VirtualBox",
"GNS3.Ui.ConfigurationPages.Page_DecorativeNode",
... |
pywbem/pywbemtools | tests/unit/pywbemcli/test_connection_repository.py | Python | apache-2.0 | 32,125 | 0.000062 | # -*- coding: utf-8 -*-
# (C) Copyright 2020 IBM Corp.
# (C) Copyright 2020 Inova Development 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.apac... | file = CONNECTION_REPO_TEST_FILE_PATH
if os.path.isfile(file):
os.remove(file)
file = CONNECTION_REPO_TEST_FILE_PATH + '.bak'
if os.path.isfile(file):
os.remove(file)
file = CONNECTION_REPO_TEST_FILE_PATH + '.tmp'
if os.path.isfile(file):
| os.remove(file)
# The yield causes the remainder of this fixture to be executed at the
# end of the test.
yield
file = CONNECTION_REPO_TEST_FILE_PATH
if os.path.isfile(file):
os.remove(file)
file = CONNECTION_REPO_TEST_FILE_PATH + '.bak'
if os.path.isfile(file):
os.remove(f... |
hcpss-banderson/py-tasc | optionresolver.py | Python | mit | 1,993 | 0.018565 | import optparse, yaml, json
class OptionResolver(object):
"""Resolve user input options"""
def __init__(self):
self.parser = optparse.OptionParser()
s | elf.set_options()
def set_options(self):
"""Use optparser to manage options"""
self.parser.add_option(
"--manifest", "-m",
help | = "The location of the manifest file.",
default = "./manifest.yml")
self.parser.add_option(
"--destination", "-d",
help = "Where to assemble the code.",
default = ".")
self.parser.add_option(
"--extra-parameters", "-e", ... |
pythonvietnam/pbc082015 | vumanhcuong/Day3/khonghieu.py | Python | gpl-2.0 | 204 | 0.019608 | #Ba | i tap ve nha | ngay 3 (20150827)
a = raw_input ("Nhap vao 1 chuoi so:")
#print "So nay:", a
print "So ki tu a la:", a.count("a")
print "So ki tu b la:", a.count("b")
print "So ki tu c la:", a.count("c") |
ergo/ziggurat_foundations | ziggurat_foundations/migrations/versions/46a9c4fb9560_pass_col_sizes.py | Python | bsd-3-clause | 594 | 0.003367 | " | ""make password hash field bigger
Revision ID: 46a9c4fb9560
Revises: 5c84d7260c5
Create Date: 2011-12-20 17:59:16.961112
"""
from __future__ import unicode_literals
import sqlalchemy as sa
from alembic import op
# downgrade revision identifier, used by Alembic.
revision = "46a9c4fb9560"
down_revision = "5c84d7260c5... | type_=sa.Unicode(256), existing_type=sa.Unicode(40)
)
def downgrade():
pass
|
BlogomaticProject/Blogomatic | opt/blog-o-matic/usr/lib/python/Bio/SCOP/Raf.py | Python | gpl-2.0 | 12,101 | 0.019337 | # Copyright 2001 by Gavin E. Crooks. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
# Gavin E. Crooks 2001-10-10
"""ASTRAL RAF (Rapid Access Format) Sequence Maps.
The ASTRAL... | 'EFC':'C', 'FLA':'A', 'FME':'M', 'GGL':'E',
'GLZ':'G', 'GMA':'E', 'GSC':'G', 'HAC':'A', 'HAR':'R',
'HIC':'H', 'HIP':'H', 'HMR':'R', 'HPQ':'F', 'HTR':'W',
'HYP':'P', 'IIL':'I', 'IYR':'Y', 'KCX':'K', 'LLP':'K',
'LLY':'K', 'LTR':'W', 'LYM':'K', 'LYZ':'K', 'MAA':'A',
'MEN':'N', 'MHS':'H', 'MIS':'S', | 'MLE':'L', 'MPQ':'G',
'MSA':'G', 'MSE':'M', 'MVA':'V', 'NEM':'H', 'NEP':'H',
'NLE':'L', 'NLN':'L', 'NLP':'L', 'NMC':'G', 'OAS':'S',
'OCS':'C', 'OMT':'M', 'PAQ':'Y', 'PCA':'E', 'PEC':'C',
'PHI':'F', 'PHL':'F', 'PR3':'C', 'PRR':'A', 'PTR':'Y',
'SAC':'S', 'SAR':'G', 'SCH':'C', 'SCS':'C', 'SCY':'C',
... |
mhcrnl/PmwTkEx | src/Pmw/Pmw_1_3/tests/CounterDialog_test.py | Python | apache-2.0 | 2,577 | 0.001552 | import Tkinter
import Test
import Pmw
Test.initialise()
c = Pmw.CounterDialog
kw_1 = {
'counter_labelpos': 'n',
'counter_buttonaspect': 2.0,
'counter_autorepeat': 0,
'counter_initwait': 1000,
'counter_padx': 5,
'counter_pady': 5,
'counter_repeatrate': 20,
'label_text' : 'Counter:',
... | ('entry_insertborderwidth', 0),
('entry_insertofftime', 400),
('entry_insertontime', 700),
('entry_insertwidth', 3),
('entryfield_invalidcommand', Test.callback),
| ('entry_show', '*'),
('entry_background', 'red'),
(c.setentry, '69', 1),
('entry_justify', 'right'),
('entry_justify', 'center'),
('entry_justify', 'left'),
('label_text', 'Label'),
('entry_relief', 'raised'),
('entry_relief', 'sunken'),
('entry_state', 'disabled'),
('entry_state... |
fxstein/ISYlib-python | ISY/_isyclimate.py | Python | bsd-2-clause | 1,533 | 0.001305 | """
This is a subfile for IsyClass.py
These funtions are accessable via the Isy class opj
"""
__author__ = 'Peter Shipley <peter.shipley@gmail.com>'
__copyright__ = "Copyright (C) 2013 Peter Shipley"
__license__ = "BSD"
import time
##
## Climate funtions
##
def load_clim(self):
""" Load climate data from ISY ... | def clim_get_val(self, prop):
pass
def clim_query(self):
""" returns dictionary of climate info """
if not self.climateinfo:
self.load_clim()
#
# ADD CODE to check self.cachetime
#
return self.climateinfo
def clim_iter(self):
""" Iterate though climate values
args:
... | an iterator over the climate values
"""
if not self.climateinfo:
self.load_clim()
k = self.climateinfo.keys()
for p in k:
yield self.climateinfo[p]
# Do nothing
# (syntax check)
#
if __name__ == "__main__":
import __main__
print(__main__.__file__)
print("syntax ok")
ex... |
square/pants | tests/python/pants_test/engine/test_engine.py | Python | apache-2.0 | 2,994 | 0.007348 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from pants.base.exce... | engine.attempts))
context, | goals = engine.attempts[0]
self.assertEqual(self.context, context)
self.assertEqual(self.as_goals(*goal_names), goals)
def test_execute_success(self):
engine = self.RecordingEngine()
result = engine.execute(self.context, self.as_goals('one', 'two'))
self.assertEqual(0, result)
self.assert_att... |
awakenting/gif_fitting | fitgif/Filter_Rect_LogSpaced.py | Python | gpl-3.0 | 7,817 | 0.024562 | import numpy as np
from scipy.signal import fftconvolve
from . import Tools
from .Filter import Filter
class Filter_Rect_LogSpaced(Filter) :
"""
This class defines a function of time expanded using log-spaced rectangular basis functions.
A filter f(t) is defined in the form f(t) = sum_j b_j*rect_j(t),
... | functions increase exponentially (log-spacing).
This class is used to define both the spike-triggered current eta(t) and the spike-triggered
movement of the firing threshold gamma(t).
"""
def __init__(self, length=1000.0, binsize_lb=2.0, binsiz | e_ub=1000.0, slope=7.0):
Filter.__init__(self)
self.p_length = length # ms, filter length
self.p_binsize_lb = binsize_lb # ms, min size for bin
self.p_binsize_ub = binsize_ub # ms, max size for bin
self.p_slope = slope #... |
bdh1011/cupeye | venv/lib/python2.7/site-packages/whoosh/sorting.py | Python | bsd-3-clause | 41,932 | 0.000191 | # Copyright 2011 Matt Chaput. All rights reserved.
#
# 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 a... | ss:`whoosh.searching.Searcher` object passed to the ``categorizer``
method may be a composite searcher (that is, wrapping a multi-reader), but
categorizers ar | e always run **per-segment**, with segment-relative document
numbers.
The collector will call a categorizer's ``set_searcher`` method as it
searches each segment to let the cateogorizer set up whatever segment-
specific data it needs.
``Collector.allow_overlap`` should be ``True`` if the ca... |
aabdulwahed/wms | app/api/urls.py | Python | apache-2.0 | 161 | 0.006211 | from django.conf.urls import include, url
from .views import UpdateStatus
urlpatte | rns = [
url(r'^update/$', UpdateStatus.as_v | iew(), name='update status'),
] |
117111302/jenkinsapi | examples/how_to/query_a_build.py | Python | mit | 893 | 0 | from __future__ import print_function
from jenkinsapi.view import View
from jenkinsapi.jenkins import Jenkins
J = Jenkins('http://localhost:8080')
print(J.items())
j = J['foo']
j = J.get_job("foo")
b = j.get_last_build()
print(b)
mjn = b.get_master_job_name()
print(mjn)
EMPTY_JOB_CONFIG = '''\
<?xml version='1.0' en... | am>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers class="vector"/>
<concurrentBuild>false</concurrentBuild>
<builders/>
<publishers/>
<buildWrappers/ | >
</project>
'''
new_job = J.create_job(name='foo_job', config=EMPTY_JOB_CONFIG)
|
yiwen-luo/LeetCode | Python/the-maze-ii.py | Python | mit | 1,267 | 0.003946 | # Time: O(max(r, c) * wlogw)
# Space: O(w)
class Solution(object):
def shortestDistance(self, maze, start, destination):
"""
:type maze: List[List[int]]
:type start: List[int]
:type destination: List[int]
:rtype: int
"""
start, destination = | tuple(start), tuple(destination)
def neighbors(maze, node):
for | dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]:
cur_node, dist = list(node), 0
while 0 <= cur_node[0]+dir[0] < len(maze) and \
0 <= cur_node[1]+dir[1] < len(maze[0]) and \
not maze[cur_node[0]+dir[0]][cur_node[1]+dir[1]]:
cur_no... |
ltowarek/budget-supervisor | third_party/saltedge/test/test_currencies_api.py | Python | mit | 831 | 0 | # coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: su | pport@saltedge.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.api.currencies_api import CurrenciesApi # noqa: E501
from swagger_client.rest import ApiException
class TestCurrenciesApi(uni... | get(self):
"""Test case for currencies_get
List of currencies # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.