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 |
|---|---|---|---|---|---|---|---|---|
huaweiswitch/neutron | neutron/plugins/ml2/drivers/huawei/config.py | Python | apache-2.0 | 1,533 | 0 | # Copyright (c) 2013 OpenStack Foundation
#
# 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 ... | t('hostaddr',
default='',
help=_('IP address of Huawei Switch.'
'This is required field.')),
cfg.StrOpt('p | ortname',
default='',
help=_('The name of port connection to Huawei Switch.'
'This is required field.'))
]
cfg.CONF.register_opts(HUAWEI_DRIVER_OPTS, "ml2_huawei")
|
tweemeterjop/thug | thug/DOM/W3C/HTML/HTMLElement.py | Python | gpl-2.0 | 2,479 | 0.002824 | #!/usr/bin/env python
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import bs4 as BeautifulSoup
import logging
from thug.DOM.W3C.Element import Element
from thug.DOM.W3C.Style.CSS.ElementCSSInlineStyl... | handler( | node)
for node in list(soup.body.children):
self.tag.append(node)
name = getattr(node, 'name', None)
if name is None:
continue
handler = getattr(log.DFT, 'handle_%s' % (name, ), None)
if handler:
handler(node)
... |
sslavic/kafka | tests/kafkatest/tests/streams/streams_broker_compatibility_test.py | Python | apache-2.0 | 8,381 | 0.00358 | # 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 use ... | w/ EOS-alpha works for older brokers 0.11 (or newer)
- Streams w/ EOS-beta works for older brokers 2.5 (or newer)
- Streams fails fast for older brokers 0.10.0, 0.10.2, and 0.10.1
- Streams w/ EOS-beta fails fast for older brokers 2.4 or older
"""
input = "brokerCompatibilitySourceTopic"
output... | _(self, test_context):
super(StreamsBrokerCompatibility, self).__init__(test_context=test_context)
self.zk = ZookeeperService(test_context, num_nodes=1)
self.kafka = KafkaService(test_context,
num_nodes=1,
zk=self.zk,
... |
vtemian/kruncher | utils/decorators/require.py | Python | apache-2.0 | 703 | 0.015647 | from functools import wraps
from flask import request
from utils.exceptions impor | t HttpBadRequest
class require(object):
def __init__(self, *requires):
self.requires = requires
def get_arguments(self):
if request.method in ['POST', 'PUT']:
return request.data
return request.args
def __call__(self, f):
@wraps(f)
def decorated(*args, **kwargs):
errors = []
... | if param not in arguments:
errors.append('%s is required' % param)
if errors:
raise HttpBadRequest("\n".join(errors))
result = f(*args, **kwargs)
return result
return decorated
|
xianjunzhengbackup/code | http/django/mysite/mysite/settings.py | Python | mit | 3,096 | 0.001292 | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib. | auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation... |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/appflow/appflowaction.py | Python | apache-2.0 | 13,493 | 0.036537 | #
# 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... | erscore (_) character, and must contain only ASCII alphanumeric, underscore, hash (#), period (.), space, colon (:), at
(@), equals (=), and hyphen (-) characters.
The following requirement applies only to the NetScaler CLI:
If the name includes one or more spaces, enclose the name in double or single quotation ... | name = newname
except Exception as e:
raise e
@property
def hits(self) :
"""The number of times the action has been taken.
"""
try :
return self._hits
except Exception as e:
raise e
@property
def referencecount(self) :
"""The number of references to the action.
"""
try :
return self._r... |
swiftstack/swift-metadata-sync | test/integration/test_metadata_sync.py | Python | apache-2.0 | 5,118 | 0 | # Copyright (c) 2012-2021, NVIDIA CORPORATION.
# SPDX-License-Identifier: Apache-2.0
import elasticsearch
import json
import logging
import os
import random
import string
import swiftclient
import unittest
import utils
class MetadataSyncTest(unittest.TestCase):
ES_HOST = 'https://localhost:9200'
ES_VERSION =... | dex:
index = ''.join([
random.choice(string.ascii_lowercase) for _ in range(8)])
if self.es_conn.indices.exists(index):
self.es_conn.indices.delete(index)
self.es_conn.in | dices.create(index, include_type_name=False)
self.indices.append(index)
return index
def setUp(self):
self.logger = logging.getLogger('test-metadata-sync')
self.logger.addHandler(logging.StreamHandler())
self.client = swiftclient.client.Connection(
'http://localh... |
edeposit/edeposit.amqp.models | src/edeposit/amqp/models/riv.py | Python | mit | 932 | 0.001135 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
# Variables ===================================================================
#: Categories used to choose RIV
RIV_CATEGORIES = [
(1, "společenské,... | umělecké vědy (SHVa)"),
(2, "společenské vědy (SHVb)"),
(3, "společenské vědy (SHVc)"),
(4, "technické a informatické vědy"),
(5, "zemědělské vědy (rostlinná výroba, živočišná výroba a potravinářství)"),
(6, "vědy o Zemi"),
(7, "matematické vědy"),
(8, "fyzikální vědy (pouze pilíř II.)"),
... | choose category
RIV_CAT_IDS = [
row[0]
for row in RIV_CATEGORIES
]
|
vmrob/needy | needy/commands/clean.py | Python | mit | 1,074 | 0.004655 | from __future__ import print_function
from .. import command
from ..needy import ConfiguredNeedy
class CleanCommand(command.Command):
def name(self):
| return 'clean'
def add_parser(self, group):
short_description = 'clean a need'
parser = group.add_parser(self.name(), description=short_description.capitalize()+'.', help=short_description)
parser.add_argument('l | ibrary', default=None, nargs='*', help='the library to clean. shell-style wildcards are allowed').completer = command.library_completer
parser.add_argument('-f', '--force', action='store_true', help='ignore warnings')
parser.add_argument('-b', '--build-directory', action='store_true', help='only clean b... |
skitazaki/python-clitool | clitool/config.py | Python | apache-2.0 | 3,300 | 0.000303 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Configuration loader to support multi file types along with environmental
variable ``PYTHON_CLITOOL_ENV``. Default variable is
:const:`clitool.DEFAULT_RUNNING_MODE` (``development``).
Supported file types are:
* ini/cfg
* json
* yaml (if "pyyaml_" is installed)
.. _... | = env or \
os.environ.get(RUNNING_MODE_ENVKEY, DEFAULT_RUNNING_MODE)
if e in self.config:
return self.config[e]
logging.warn("Environment '%s' was not found.", e)
def flip(self):
""" Provide flip view to compare how key/value pair is defined in each
environme... | ups = self.config.keys()
tabular = {}
for g in groups:
config = self.config[g]
for k in config:
r = tabular.get(k, {})
r[g] = config[k]
tabular[k] = r
return tabular
# vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
|
zephinzer/cs4243 | mac.homograph.py | Python | mit | 3,290 | 0.009119 | #!/usr/bin/python
### dependencies
import os, sys
# may need to remove for windows systems
sys.path.append('/usr/local/lib/python2.7/site-packages')
import cv2, numpy as np
from matplotlib import pyplot
class ClicksCaptor:
FIELD_DISPLAY_NAME = 'Field'
coords = []
nClicks = 0
## get the videoCoords wit... | i,w,h,r,c,cc = readVideo( | 'input.avi')
print '[WIDTH] ', w
print '[HEIGHT]', h
print '[RATE] ', r
print '[FRAMES]', c
print '[FOURCC]', cc
o = extractBackground(i,c)
class ClicksCaptor:
FIELD_DISPLAY_NAME = 'Field'
coords = []
nClicks = 0
nMaxClicks = None
def __init__(self, nMaxClicks):
self.nMaxClicks = nMaxCli... |
jamilatta/opac | opac/tests/test_interface_TOC.py | Python | bsd-2-clause | 8,985 | 0.00112 | # coding: utf-8
import flask
from flask import url_for
from .base import BaseTestCase
from . import utils
class TOCTestCase(BaseTestCase):
# TOC
def test_the_title_of_the_article_list_when_language_pt(self):
"""
Teste para verificar se a interface do TOC esta retornando o título no
... | el Artículo En Portugués", 'language': 'es'},
{'name': "Article Title In Portuguese", 'language': 'en'}
]
utils.makeOneArticle({
'issue': issue,
'title': 'Article Y',
'translated_titles': translated_titles
})
... | rnal.url_segment,
url_seg_issue=issue.url_segment)
}
set_locale_url = url_for('main.set_locale', lang_code='en')
response = c.get(set_locale_url, headers=header, follow_redirects=True)
self.assertEqual(200, response.status_code)
self.ass... |
includeos/includeos-tools | bombardment/bombardment.py | Python | apache-2.0 | 8,263 | 0.008229 | #!/usr/bin/env python
import subprocess
import re
import os
import sys
import argparse
import commands
from multiprocessing import Process, Queue
# Module import of openstack control script
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
sys.path.append('../openstack_con... | ot_replies"),
"connection_rate": output.group("conn_rate"),
"reply_rate_avg": output.group("reply_rate_avg")
}
q.put(results)
return
def cleanup(ssh_target):
"""Will make su | re no httperf processes are running on the ssh_host"""
command = "ssh {0} -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ' \
pkill httperf '".format(ssh_target)
commands.getstatusoutput(command)
return
# Fire a single burst of ARP requests
def ARP_burst(burst_size = BURST_S... |
ctrlaltdel/neutrinator | vendor/dogpile/cache/backends/__init__.py | Python | gpl-3.0 | 856 | 0 | from dogpile.cache.region import register_backend
register_backend(
"dogpile.cache.null", "dogpile.cache.backends.null", "NullBackend")
register_backend(
"dogpile.cache.dbm", "dogpile.cache.backends.file", "DBMBackend")
register_backend(
"dogpile.cache.pylibmc", "dogpile.cache.backends.memcached",
"Pyl... | d")
register_backend(
"dogpile.cache.memory_pickle", "dogpile.cache.backends.memory",
"MemoryPickleBackend")
register_backend(
"dogpile.cache.redis", "dogpile.cache.backends.redis", " | RedisBackend")
|
scikit-learn-contrib/imbalanced-learn | imblearn/over_sampling/_random_over_sampler.py | Python | mit | 9,497 | 0.000316 | """Class to perform random over-sampling."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# License: MIT
from collections.abc import Mapping
from numbers import Real
import numpy as np
from scipy import sparse
from sklearn.utils import check_array, check_random_state
from sklear... | ampling_strategy)
self.random_state = random_state
self.shrinkage = shrinkage
def _check_X_y(self, X, y):
y, binarize_y = | check_target_type(y, indicate_one_vs_all=True)
X, y = self._validate_data(
X,
y,
reset=True,
accept_sparse=["csr", "csc"],
dtype=None,
force_all_finite=False,
)
return X, y, binarize_y
def _fit_resample(self, X, y):
... |
borysiasty/QGIS | tests/src/python/test_qgsserver_accesscontrol.py | Python | gpl-2.0 | 10,893 | 0.002295 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsServer.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__autho... | )
cls._server_iface = cls._server.serverInterface()
cls._accesscontrol = RestrictedAccessControl(cls._server_iface)
cls._server_iface.registerAccessControl(cls._accesscontrol, | 100)
@classmethod
def tearDownClass(cls):
"""Run after all tests"""
del cls._server
cls._app.exitQgis()
def setUp(self):
super().setUp()
self.testdata_path = unitTestDataPath("qgis_server_accesscontrol")
data_file = os.path.join(self.testdata_path, "hellow... |
mzeinstra/Europeana-20th-century-gap | scrape.py | Python | mit | 2,441 | 0.045473 | import sys, requests, json, csv
key = "&wskey=<API KEY HERE>
api = "http://www.europeana.eu/api/v2/search.json?"
terms = ['proxy_dc_date','date']
types = ['IMAGE','TEXT']
#including year
from_year = 1700
#until but excluding
to_year = 2016
def getResults(term, types, conditions):
global errors
global key
globa... | total = int(result['totalResults'])
return total
except:
errors.append([api + query + key, sy | s.exc_info()[0]])
return 0
except:
errors.append([api + query + key, sys.exc_info()[0]])
return 0
def getCount(term, type, year):
'''
just YYYY
YYYY-DD-MM and YYYY-MM-DD, starts with YYYY-
DD-MM-YYYY and MM-DD-YYYY, ends with -YYYY
quotes "YYYY"
brackets (YYYY)
bracket date (YYYY-DD-MM) & (YYYY-MM-DD)
... |
dynamiq-md/dynamiq_samplers | dynamiq_samplers/tools.py | Python | lgpl-2.1 | 1,216 | 0.003289 | import numpy as np
class GaussianFunction(object):
def __init__(self, x0, alpha, normed | =True):
self.x0 = np.array(x0)
self.alpha = np.array(alpha)
self.sigma = 1.0/np.sqrt(2.0*self.alpha)
if normed:
self.norm = np.prod(np.sqrt(self.alpha / np.pi))
else:
self.norm = 1.0
assert(self.x0.shape == self.alpha.shape)
self._internal ... | ple` and returns it as a properly drawn sample
sample = np.zeros_like(self._internal)
self.set_array_to_drawn_sample(sample)
return sample
def set_array_to_drawn_sample(self, array):
# TODO: I think this can be significantly sped up for large systems
n_dofs = len(self.sigma)... |
mhils/mitmproxy | test/mitmproxy/test_certs.py | Python | mit | 9,062 | 0.001104 | import os
from pathlib import Path
from cryptography import x509
from cryptography.x509 import NameOID
import pytest
from mitmproxy import certs
from ..conftest import skip_windows
# class TestDNTree:
# def test_simple(self):
# d = certs.DNTree()
# d.add("foo.com", "foo")
# d.add("bar.co... | assert repr(c2) == "<Cert(cn='www.inode.co.nz', altnames=['www.inode.co.nz', 'inode.co.nz'])>"
assert c1 != c2
def test_convert(self, tdata):
with open(tdata.path("mitmproxy/net/data/text_cert"), "rb") as f:
d = f.read()
c = certs.Cert.from_pem(d)
assert c == certs... | lename,name,bits", [
("text_cert", "RSA", 1024),
("dsa_cert.pem", "DSA", 1024),
("ec_cert.pem", "EC (secp256r1)", 256),
])
def test_keyinfo(self, tdata, filename, name, bits):
with open(tdata.path(f"mitmproxy/net/data/{filename}"), "rb") as f:
d = f.read()
c =... |
jwhui/openthread | tests/scripts/thread-cert/pktverify/packet_verifier.py | Python | bsd-3-clause | 14,791 | 0.002434 | #!/usr/bin/env python3
#
# Copyright (c) 2019, The OpenThread Authors.
# 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
# ... | _vars = {}
self._add_initial_vars()
def add_vars(self, **vars):
"""
Add | new variables.
:param vars: The new variables.
"""
self._vars.update(vars)
@property
def vars(self):
"""
:return: the dict of all variables
"""
return self._vars
def add_common_vars(self):
"""
Add common variables that is needed by m... |
salvacarrion/orange3-recommendation | orangecontrib/recommendation/tests/coverage/__init__.py | Python | bsd-2-clause | 108 | 0.009259 | fro | m orangecontrib.recommendation.tests.coverage.base_tests \
import TestRatingModels, TestRankingModel | s |
defivelo/db | apps/challenge/migrations/0008_qualification_helpers.py | Python | agpl-3.0 | 576 | 0.001736 | from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migrati | on(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('challenge', '0007_auto_20150902_1636'),
]
operations = [
migrations.AddField(
model_name='qualification',
name='helpers',
field=models.ManyToM... | ,
),
]
|
vitasoa/OpenERP-7.0-Magento | magentoerpconnect_options_active/__openerp__.py | Python | agpl-3.0 | 1,388 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Markus Schneider
# Copyright 2014 initOS GmbH & Co. KG
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
... | ils.
#
# You should have received a copy of the GNU Aff | ero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Magento Connector Option Active Products',
'version': '1.0.0',
'category': 'Connector',
'depends': ['magentoerpconnect',
... |
Onirik79/aaritmud | data/proto_items/flora/flora_item_rename-04-piantina.py | Python | gpl-2.0 | 422 | 0.004739 | # -*- coding: utf-8 -*-
def on_next_stage(old_entity, new_entity, choised_attr, entities):
if not old_entity.specials or 'ancestors' not in old_entity.specials:
new_entity.specials['ancestors']='False'
else:
print ">>>>>>> passo di qui!"
pr | int old_entity.special | s
for special in old_entity.specials:
new_entity.specials[special] = old_entity.specials[special]
|
waylan/mkdocs | mkdocs/tests/config/config_options_tests.py | Python | bsd-2-clause | 31,081 | 0.000515 | import os
import sys
import unittest
from unittest.mock import patch
import mkdocs
from mkdocs.config import config_options
from mkdocs.config.base import Config
from mkdocs.tests.base import tempdir
class OptionallyRequiredTest(unittest.TestCase):
def test_empty(self):
option = config_options.Optional... | llyRequired(required=True)
value = option.validate(2)
self.assertEqual(2, value)
def test_default(self):
option = config_options.OptionallyRequired(default=1)
value = option.validate(None)
self.assertEqual(1, value)
def test_replace_default(self):
option = con... | f.assertEqual(2, value)
class TypeTest(unittest.TestCase):
def test_single_type(self):
option = config_options.Type(str)
value = option.validate("Testing")
self.assertEqual(value, "Testing")
def test_multiple_types(self):
option = config_options.Type((list, tuple))
... |
MartinPyka/Pam-Utils | pamutils/__init__.py | Python | gpl-2.0 | 88 | 0.011364 | #pamutils init.py |
import pam2nest
import nest_vis
import network
__version__ = '0.1 | .0'
|
pybursa/homeworks | a_berezovsky/hw1/task05.py | Python | gpl-2.0 | 560 | 0.004425 | # -*- coding: utf-8 -*-
"""
Задание 5: определение типа.
УСЛОВ | ИЕ:
функция, которая принимает объект и выводит строку с наименованием типа этого объекта.
Пример:
typer(666) == "int"
typer("666") == "str"
typer(typer) == "function"
"""
def typer(variable):
return type(variable).__name__
if __na | me__ == '__main__':
print "666 type is %s" % typer(666)
print "\"666\" type is %s" % typer("666")
print "task5 type is %s" % typer(typer) |
kura/kura.io | plugins/headerid/__init__.py | Python | mit | 24 | 0 | fr | om .headerid import * | |
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/bx_python-0.7.1-py2.7-linux-x86_64.egg/EGG-INFO/scripts/maf_truncate.py | Python | apache-2.0 | 766 | 0.023499 | #!/usr/bin/python2.7
"""
Pass through blocks from a maf file until a certain number of columns
have been passed.
usage: %prog -c cols < maf > maf
"""
import sys
from bx.align import maf
from optparse import OptionParser
def __main__():
# Parse command line arguments
parser = OptionParser()
parser.add... | ( "-c", "--cols", action="store" )
( opti | ons, args ) = parser.parse_args()
maf_reader = maf.Reader( sys.stdin )
maf_writer = maf.Writer( sys.stdout )
if not options.cols: raise "Cols argument is required"
cols = int( options.cols )
count = 0
for m in maf_reader:
maf_writer.write( m )
count += m.text_size
... |
PermutaTriangle/PermStruct | permstruct/exhaustive.py | Python | bsd-3-clause | 1,013 | 0.01382 | from __future__ import print_function
from permstruct import RuleSet
from .functions import populate_rule_set
fro | m permstruct.dag import DAG
from permuta.misc import ProgressBar
import sys
def exhaustive(settings):
for k,v in enumerate(settings.sets):
settings.logger.log(repr(tuple([k,v.description if v is not None else 'None'])))
rules | = RuleSet(settings)
rule_cnt = 0
settings.logger.log('Generating rules')
populate_rule_set(settings, rules)
settings.logger.log('Found %d rules, %d of which are valid, %d of which are distinct' % (
rules.total_rules,
sum( len(v) for k, v in rules.rules.items() ),
... |
google-research/language | language/labs/consistent_zero_shot_nmt/utils/common_utils.py | Python | apache-2.0 | 1,241 | 0 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | m __future__ import division
from __future__ import print_function
# Attention types.
ATT_LUONG = "luong"
ATT_LUONG_SCALED = " | luong_scaled"
ATT_BAHDANAU = "bahdanau"
ATT_BAHDANAU_NORM = "bahdanau_norm"
ATT_TYPES = (ATT_LUONG, ATT_LUONG_SCALED, ATT_BAHDANAU, ATT_BAHDANAU_NORM)
# Encoder types.
ENC_UNI = "uni"
ENC_BI = "bi"
ENC_GNMT = "gnmt"
ENC_TYPES = (ENC_UNI, ENC_BI, ENC_GNMT)
# Decoder types.
DEC_BASIC = "basic"
DEC_ATTENTIVE = "attentiv... |
rahulguptakota/paper-To-Reviewer-Matching-System | train2.py | Python | mit | 5,164 | 0.009682 | from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors im... | nel='rbf', probability=True)
clf1.fit(X,Y)
print(clf1.feature_importances_)
scores = cross_val_score | (clf2, X, Y, cv=40)
print("20 fold acuuracy is %0.2f (+/- %0.2f)"%(scores.mean(), scores.std()*2) )
eclf = VotingClassifier(estimators=[('dt', clf1), ('knn', clf2), ('svc', clf3)])
# clf1 = clf1.fit(X_train,y_train)
# clf2 = clf2.fit(X_train,y_train)
# clf3 = clf3.fit(X_train,y_train)
eclf = eclf.fit(X_train,y_train)
... |
fiber-space/pip | tests/functional/test_freeze.py | Python | mit | 15,857 | 0 | import sys
import os
import re
import textwrap
import pytest
from doctest import OutputChecker, ELLIPSIS
from tests.lib import _create_test_package, _create_test_package_with_srcdir
distribute_re = re.compile('^distribute==[0-9.]+\n', re.MULTILINE)
def _check_output(result, expected):
checker = OutputChecker()... | ript.pip(
'freeze', '-f', '%s#egg=pip_test_package' % repo_dir,
expect_stderr=True,
)
expected = textwrap.dedent(
"""
-f %(repo)s#egg=pip_test_package...
-e git+...#egg=version_pkg
...
""" % {'repo': r | epo_dir},
).strip()
_check_output(result.stdout, expected)
# Check that slashes in branch or tag names are translated.
# See also issue #1083: https://github.com/pypa/pip/issues/1083
script.run(
'git', 'checkout', '-b', 'branch/name/with/slash',
cwd=repo_dir,
expect_stderr=T... |
Mirantis/mos-horizon | openstack_dashboard/test/integration_tests/steps.py | Python | apache-2.0 | 1,572 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | .driver,
test_case.CONFIG)
test_case.login_pg.go_to_login_page()
test_case.create_demo_user()
test_case.home_pg = test_case.login_pg.login(test_case.TEST_USER_NAME,
test_case.TEST_PASSWORD)
test_case.home_pg.... | miss(messages.SUCCESS))
test_case.assertFalse(
test_case.home_pg.find_message_and_dismiss(messages.ERROR))
yield
if test_case.home_pg.is_logged_in:
test_case.home_pg.log_out()
else:
LOGGER.warn("{!r} isn't logged in".format(test_case.TEST_USER_NAME))
|
bcorbet/SickRage | sickbeard/providers/thepiratebay.py | Python | gpl-3.0 | 13,315 | 0.003755 | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 Lic... | ry:
myParser = NameParser(showObj=self.show)
parse_result = myParser.parse(fileName)
except (InvalidNameException, InvalidShowException):
return None
logge | r.log(u"Season quality for " + title + " is " + Quality.qualityStrings[quality], logger.DEBUG)
if parse_result.series_name and parse_result.season_number:
title = parse_result.series_name + ' S%02d' % int(parse_result.season_number) + ' ' + self._reverseQuality(
quality)
re... |
wdonahoe/fluxes | LGR_fluxes.py | Python | mit | 2,057 | 0.038892 | #!/usr/bin/python
import os
import sys
import subprocess
import optparse
import time
import platform
SCRIPT_NAME = "LGR_flu | xes.R"
platform = platform.system() != "Windows"
def run(foldername, start, end, graph, t, large):
""" Execute SCRIPT_NAME with time series parameters.
Arguments:
filename -- the name o | f the data file. csv format.
graph -- do you want associated plots?
start -- start date in dd/mm/yyyy format.
end -- end date in dd/mm/yyyy format.
t -- length of the measurement.
"""
if platform:
try:
subprocess.call(["./" + SCRIPT_NAME] + [str(v) for k, v in sorted(locals().items())])
except OSError ... |
semiautomaticgit/SemiAutomaticClassificationPlugin | maininterface/classtovectorTab.py | Python | gpl-3.0 | 4,478 | 0.027691 | # -*- coding: utf-8 -*-
'''
/**************************************************************************************************************************
SemiAutomaticClassificationPlugin
The Semi-Automatic Classification Plugin for QGIS allows for the supervised classification of remote sensing images,
provid... | -29
copyright : (C) 2012-2021 by Luca Congedo
email : ing.congedoluca@gmail.com
**************************************************************************************************************************/
/********** | ****************************************************************************************************************
*
* This file is part of Semi-Automatic Classification Plugin
*
* Semi-Automatic Classification Plugin is free software: you can redistribute it and/or modify it under
* the terms of the GNU Gene... |
3n73rp455/api | api/urls.py | Python | gpl-3.0 | 1,232 | 0.000812 | """api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import url, inclu... | k_jwt.views import refresh_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^auth/', include('rest_auth.urls')),
url(r'^auth/register/', include('rest_auth.registration.urls')),
url(r'^auth/refresh-token/', refresh_jwt_token),
url(r'^api/v1/core/', include('core.urls', namespace='co... |
rombie/contrail-controller | src/container/kube-manager/kube_manager/vnc/vnc_kubernetes.py | Python | apache-2.0 | 25,127 | 0.003025 | #
# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
#
"""
VNC management for kubernetes
"""
import gevent
from gevent.queue import Empty
import requests
import socket
import argparse
import uuid
from cStringIO import StringIO
from cfgm_common import importutils
from cfgm_common import vnc_cgitb
from ... | rlay via global link local services. TCP flows established on
# link local services will be torn down by vrouter, if there is no
# activity for configured(or default) timeout. So disable flow timeout
# on these connections, so these flows will persist.
#
# Note: The way to | disable flow timeout is to set timeout to max
# possible value.
#
if self.args.nested_mode is '1':
for cassandra_server in self.args.cassandra_server_list:
cassandra_port = cassandra_server.split(':')[-1]
flow_aging_manager.create_flow_aging_time... |
hdm-dt-fb/rvt_model_services | commands/qc_no_ws/bokeh_qc_graphs.py | Python | mit | 6,329 | 0.002528 | # -*- coding: utf-8 -*-
""" bokeh_qc_graphs.py
Usage:
bokeh_qc_graphs.py [options]
<project_code>
Arguments:
project_code unique project code consisting of 'projectnumber_projectModelPart'
like 456_11 , 416_T99 or 377_S
Options:
-h, --help ... | graph_x_range = topic_figure.x_range
# glyphs
# print(len(cds.column_names))
for i, col_name in enumerate(csv_topic.columns):
if topic in col_name:
# print(col_name)
csv_topic["color"] = colors[i]
name_list = [col_name[2:] for ... | y=csv_topic[col_name].values,
name=name_list,
count=csv_topic[col_name].values,
time=csv_topic.index.strftime("%Y-%m-%d %H:%M:%S... |
WildCAS/CASCategorization | journal/tests/test_persons.py | Python | apache-2.0 | 353 | 0 | from django.test import TestCase
from journal.tests. | factories import StudentFactory
class StudentTestCase(TestCase):
"""Tests for the Student models"""
d | ef test_student(self):
"""Test to ensure that Students can be created properly"""
student = StudentFactory.build()
self.assertEqual(student.personal_code, '123456')
|
mzdaniel/oh-mainline | vendor/packages/kombu/kombu/tests/test_transport_pyamqplib.py | Python | agpl-3.0 | 806 | 0 | from kombu.tests.utils import unittest
from kombu.transport import pyamqplib
from kombu.connection import BrokerConnection
class MockConnection(dict):
def __setattr__(self, key, value):
self[key] = value
class test_amqplib(unittest.TestCase):
def test_default_port(self):
class Transport(... | onnect()
self.assertEqual(c["host"],
"127.0.0.1:%s" % (Transport.default_port, ))
def test_custom_port(self):
| class Transport(pyamqplib.Transport):
Connection = MockConnection
c = BrokerConnection(port=1337, transport=Transport).connect()
self.assertEqual(c["host"], "127.0.0.1:1337")
|
aplanas/kmanga | scraper/scraper/middlewares.py | Python | gpl-3.0 | 10,942 | 0.000183 | # -*- coding: utf-8 -*-
#
# (c) 2018 Alberto Planas <aplanas@gmail.com>
#
# This file is part of KManga.
#
# KManga 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 you... | (self, settings):
self.error_codes = {
int(x) fo | r x in settings.getlist('SMART_PROXY_ERROR_CODES')
}
self.retry_error_codes = {
int(x) for x in settings.getlist('RETRY_HTTP_CODES')
}
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def process_request(self, request, spider):
#... |
google/openhtf | test/core/monitors_test.py | Python | apache-2.0 | 3,303 | 0.00545 | # Copyright 2016 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 agre... | ll made.')
self.assertEqual(
1, first_meas[1], msg="And it should be the monitor func's return val")
def testPlugs(self):
q = queue.Queue()
@plugs.plug(empty=EmptyPlug)
def monitor(test, empty):
del test # Unused.
del empty | # Unused.
q.put(2)
return 2
@monitors.monitors('meas', monitor, poll_interval_ms=100)
def phase(test):
del test # Unused.
while q.qsize() < 2:
time.sleep(0.1)
phase(self.test_state)
name, first_meas, _ = self.test_state.mock_calls[0]
assert name == 'test_api.measu... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/unittests/test_affine_channel_op.py | Python | apache-2.0 | 4,621 | 0.000433 | # Copyright (c) 2018 PaddlePaddle 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 app... | = [2, 3, 3, 100]
self.C = 100
self.layout = 'NHWC'
def test_check_grad_stopgrad_dx(self):
return
def test_check_grad_stopgrad_dscale_dbias(self):
return
class TestAffineChannel2D(TestAffineChannelOp):
def init_test_case(self):
self.shape = [2, 100]
self.C ... | turn
def test_check_grad_stopgrad_dscale_dbias(self):
return
# TODO(qingqing): disable unit testing for large shape
#class TestAffineChannelNCHWLargeShape(TestAffineChannelOp):
# def init_test_case(self):
# self.shape = [4, 128, 112, 112]
# self.C = 128
# self.layout = 'NCHW'
#
# ... |
ido-ran/ran-smart-frame2 | web/server/lib/uritemplate/api.py | Python | mit | 1,911 | 0 | """
uritemplate.api
===============
This module contains the very simple API provided by uritemplate.
"""
from uritemplate.template import URITemplate
def expand(uri, var_dict=None, **kwargs):
"""Expand the template with the given parameters.
:param str uri: The templated URI to expand
:param di | ct var_dict: Optional dictionary with variables and values
:param kwargs: Alternative way to pass argum | ents
:returns: str
Example::
expand('https://api.github.com{/end}', {'end': 'users'})
expand('https://api.github.com{/end}', end='gists')
.. note:: Passing values by both parts, may override values in
``var_dict``. For example::
expand('https://{var}', {'v... |
Comunitea/alimentacion | automatic_update_cost_from_bom/__openerp__.py | Python | agpl-3.0 | 1,451 | 0.006901 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2004-2012 Pexego Sistemas Informáticos All Rights Reserved
# $Omar Castiñeira Saavedra$ <omar@pexego.es>
#
# This program is free software: you can redistribute it and/or modify
# it ... | ###########################################
{
"name" : "Automatic update cost from BOMs",
"description" : """Cron job to automate update product cost from BOMs""",
"version" : "1.0",
"author" : "Pexego",
"depends" : ["base", "product", "product_extended"],
"category" : "Mrp/Product",
"init_... | product_category_view.xml", "product_view.xml"],
'demo_xml': [],
'installable': True,
'active': False,
}
|
anhstudios/swganh | data/scripts/templates/object/tangible/food/crafted/shared_drink_double_dip_outer_rim_rumdrop.py | Python | mit | 488 | 0.045082 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DON | E IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/food/crafted/shared_drink_double_dip_outer_rim_rumdrop.iff"
result.attribu | te_template_id = 5
result.stfName("food_name","double_dip_outer_rim_rumdrop")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
rsjohnco/rez | src/rez/tests/test_resources_.py | Python | gpl-3.0 | 9,241 | 0.000649 | """
test core resource system
"""
from rez.tests.util import TestBase
from rez.utils.resources import Resource, ResourcePool, ResourceHandle, \
ResourceWrapper
from rez.utils.schema import Required
from rez.exceptions import ResourceError
import rez.vendor.unittest2 as unittest
from rez.vendor.schema.schema import ... | self.assertTrue(obi_.resource is obi.resource)
# accessing 'name' should not cause a resource data load
self.assertEq | ual(obi.name, "obi")
self.assertFalse(obi.is_loaded)
# accessing an attrib should cause resource's data to load
self.assertEqual(obi.colors, set(["black", "white"]))
self.assertEqual(obi.resource.validations, dict(colors=1))
self.assertTrue(obi.is_loaded)
# accessing sa... |
ofek/hatch | tests/utils/test_structures.py | Python | mit | 1,699 | 0.000589 | import os
from hatch.utils.structures import EnvVars
def get_random_name():
return os.urandom(16).hex().upper()
class TestEnvVars:
def test_restoration(self):
num_env_var | s = len(os.environ)
with EnvVars():
os.environ.clear()
assert len(os.environ) == num_env_vars
def test_set(self):
env_var = get_random_name()
with EnvVars( | {env_var: 'foo'}):
assert os.environ.get(env_var) == 'foo'
assert env_var not in os.environ
def test_include(self):
env_var = get_random_name()
pattern = f'{env_var[:-2]}*'
with EnvVars({env_var: 'foo'}):
num_env_vars = len(os.environ)
with Env... |
angr/cle | cle/backends/pe/relocation/__init__.py | Python | bsd-2-clause | 1,415 | 0.002827 | import os
import logging
import importlib
import archinfo
from collections import defaultdict
from ...relocation import Relocation
ALL_RELOCATIONS = defaultdict(dict)
complaint_log = set()
path = os.path.dirname(os.path.abspath(__file__))
l = logging.getLogger(name=__name__)
def load_relocations():
for filename ... | rror:
continue
for item_name in dir(module):
if item_name not in archinfo.defines:
continue
item = getattr(module, item_name)
if not isinstance(item, type) or not issubclass(item, Relocation):
continue
ALL_RELOCATIONS[... |
if r_type == 0:
return None
try:
return ALL_RELOCATIONS[arch][r_type]
except KeyError:
if (arch, r_type) not in complaint_log:
complaint_log.add((arch, r_type))
l.warning("Unknown reloc %d on %s", r_type, arch)
return None
load_relocations()
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/contrib/staticfiles/storage.py | Python | bsd-3-clause | 2,080 | 0.001923 | import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage i | mport FileSystemStorage
from django.utils.importlib import import_module
from django.contrib.staticfiles import utils
class StaticFilesStorage(FileSystemStorage):
"""
Standard file system storage for static files.
The defaults for ``location`` and ``base_url`` are
``STATIC_ROOT`` and ``STATIC_URL``.... | def __init__(self, location=None, base_url=None, *args, **kwargs):
if location is None:
location = settings.STATIC_ROOT
if base_url is None:
base_url = settings.STATIC_URL
if not location:
raise ImproperlyConfigured("You're using the staticfiles app "
... |
david415/tahoe-lafs | src/allmydata/scripts/tahoe_mkdir.py | Python | gpl-2.0 | 1,660 | 0.001205 |
import urllib
from allmydata.scripts.common_http import do_http, check_http_error
from allmydata.scripts.common import get_alias, DEFAULT_ALIAS, UnknownAliasError
from allmydata.util.encodingutil import quote_output
def mkdir(options):
nodeurl = options['node-url']
aliases = options.aliases
where = option... | if not nodeurl.endswith("/"):
nodeurl += "/"
if where:
try:
rootcap, path = get_alias(aliases, where, DEFAULT_ALIAS)
except UnknownAliasError, e:
e.display(stderr)
return 1
if not where or not path:
# create a new unlinked directory
... | + "uri?t=mkdir"
if options["format"]:
url += "&format=%s" % urllib.quote(options['format'])
resp = do_http("POST", url)
rc = check_http_error(resp, stderr)
if rc:
return rc
new_uri = resp.read().strip()
# emit its write-cap
print >>stdout,... |
simone-campagna/rubik | rubik/filename.py | Python | apache-2.0 | 2,441 | 0.004506 | #!/usr/bin/env python3
#
# Copyright 2014 Simone Campagna
#
# 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 ... | IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# S | ee the License for the specific language governing permissions and
# limitations under the License.
#
__author__ = "Simone Campagna"
import re
from .py23 import BASE_STRING
class Filename(object):
def __init__(self, init):
if isinstance(init, Filename):
filename = init._filename
elif... |
golismero/golismero | golismero/api/data/resource/url.py | Python | gpl-2.0 | 15,148 | 0.006403 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Universal Resource Locator (URL).
"""
__license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: contact@golismero-project.com
This program is free software; you can redistri... | post_data = '&'.join(
'%s=%s' % ( quote(k, safe=''), quote(v, safe='') )
for (k, v) in sorted(post_params.iteritems())
)
else:
post_data = to_utf8(post_params)
post_params = None
else:
po... | hod = method
self.__post_data = post_data
self.__post_params = post_params
self.__referer = parse_url(referer).url if referer else None
# Call the parent constructor.
super(URL, self).__init__(url)
# Increment the crawling depth by one.
self.depth += ... |
ppaez/arithmetic | editor-gtk.py | Python | gpl-2.0 | 2,609 | 0.022997 | #! /usr/bin/env python
import sys
import os
import gtk
from arithmetic import Parser
class Editor(object):
'A minimal editor'
def __init__(self):
# path to UI file
scriptPath = os.path.split( sys.argv[0] )[0]
uiFilePath = os.path.join( scriptPath,'editor.ui' )
self.builder = ... | ''
for i in range( self.countLines( textBuffer ) ):
self.parseLine( i, textBuffer, variables=self.variables, functions=self.functions )
def countLines( self, textBuffer ):
''
return textBuffer.get_line_count()
def readLine( self, i, textBuffer ):
''
iter_st... | uffer.get_iter_at_line( i )
iter_end.forward_to_line_end()
return textBuffer.get_text( iter_start, iter_end )
def writeResult( self, i, textBuffer, start, end, text ):
'Write text in line i of lines from start to end offset.'
# Delete
if end > start:
# ha... |
jthidalgojr/greengov2015-TeamAqua | TeamAqua/views.py | Python | mit | 1,091 | 0.0055 | from django.http import HttpResponse
from django.shortcuts import render
from django.views import generic
import api.soql
import json
from api.soql import *
# Create your views here.
def indexView(request):
context = {
"vehicleAgencies": getUniqueValuesWithAggregate("gayt-taic", "agency", "max(postal... | vehicleFuelTypes": getUniqueValues("gayt-taic", "fuel_type"),
"buildingAgencies": getUniqueValues("24pi | -kxxa", "department_name")
}
return render(request,'TeamAqua/index.html', context=context)
def getUniqueValues(resource, column):
query = (
api.soql.SoQL(resource)
.select([column])
.groupBy([column])
.orderBy({column: "ASC"})
)
jsonString = query.execute()
... |
jantman/pytest_django | docs/conf.py | Python | bsd-3-clause | 7,985 | 0.007264 | # -*- coding: utf-8 -*-
#
# pytest-django documentation build configuration file, created by
# sphinx-quickstart on Tue May 1 10:12:50 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. | If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an ... |
KT26/PythonCourse | 2. Introducing Lists/6.py | Python | mit | 380 | 0.018421 | # Created by P | yCharm Pro Edition
|
# User: Kaushik Talukdar
# Date: 27-03-2017
# Time: 05:25 PM
fastfood = ["momo", "roll", "chow", "pizza"]
print(fastfood)
print("\n")
#print one element using pop()
#output the popped element
print(fastfood.pop() + "\n")
#print the new list with less elem... |
iogf/nerdirc | nerdlib/plugins/wake/wake.py | Python | gpl-2.0 | 445 | 0.004494 | def chmsg(event, server, view):
""" Everytime someone types on a channel this method is called
It gets the channel name and the win(that one which we have added in the ujoin event.
It gets t | he window with the same method server.getName.
"""
ch = event['channel'].lower()
win = view.get_win((server.getName(), ch))
msg = event['msg']
if server.nick in m | sg:
win.update()
win.deiconify()
|
EasyDonate/EasyDonate | EasyDonate/ORM.py | Python | gpl-3.0 | 7,304 | 0.034912 | from sqlalchemy import Column, String, Integer, Float, ForeignKey, PrimaryKeyConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, validates, backref
import time, json
DecBase = declarative_base()
class Server(DecBase):
__tablename__ = 'ezdonate_servers'
id = ... | ers'
id = Column(Integer, primary_key=True, autoincrement=True)
serv_id = Column(Integer, ForeignKey('ezdonate_servers.id', ondelete='CASCADE'), nullable=False)
server = relationship('Server', backref=backref('subs', cascade='all,delete | ', lazy='joined'))
steamid = Column(String(32))
item_id = Column(Integer, ForeignKey('ezdonate_items.id', ondelete='CASCADE'))
item = relationship('Item', backref=backref('purchasers', cascade='all,delete', lazy='joined'))
expires = Column(Integer)
def __init__(self, serv_id, steamid, item_id, expires):
self.se... |
robertjoosten/rjSkinningTools | scripts/skinningTools/utils/undo.py | Python | gpl-3.0 | 428 | 0 | from maya import cmds
__all__ = [
"UndoChunkContext"
]
class UndoChunkContext(object):
"""
The undo context is used to combine a chain of | commands into one undo.
Can be used in combination with the "with" statement.
with UndoChunkContext():
# | code
"""
def __enter__(self):
cmds.undoInfo(openChunk=True)
def __exit__(self, *exc_info):
cmds.undoInfo(closeChunk=True)
|
MusicVisualizationUMass/TeamNameGenerator | src/musicvisualizer/pipeline/models/grayscottmodel.py | Python | mit | 75 | 0 | '''
grayscottmodel.py: simul | ate Gray Scott mo | del of reaction diffusion
'''
|
JioCloud/horizon | openstack_dashboard/dashboards/project/data_processing/cluster_templates/panel.py | Python | apache-2.0 | 917 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | ashboards.project import dashboard
class ClusterTemplate | sPanel(horizon.Panel):
name = _("Cluster Templates")
slug = 'data_processing.cluster_templates'
permissions = ('openstack.services.data_processing',)
dashboard.Project.register(ClusterTemplatesPanel)
|
vineodd/PIMSim | GEM5Simulation/gem5/tests/gem5/__init__.py | Python | gpl-3.0 | 1,633 | 0 | # Copyright (c) 2017 Mark D. Hill and David A. Wood
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# n | otice, this | list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of i... |
genius1611/Keystone | keystone/test/__init__.py | Python | apache-2.0 | 4,496 | 0.000222 | import os
import sys
import subprocess
import tempfile
import time
import unittest2 as unittest
TEST_DIR = os.path.abspath(os.path.dirname(__file__))
BASE_DIR = os.path.abspath(os.path.join(TEST_DIR, '..', '. | .'))
def execute(cmd, raise_error=True):
"""
Executes a command in a subprocess. Returns a tuple
of (exitcode, out, err), where out is the string output
from stdout and err is the string output from stderr when
executing the command.
| :param cmd: Command string to execute
:param raise_error: If returncode is not 0 (success), then
raise a RuntimeError? Default: True)
"""
env = os.environ.copy()
# Make sure that we use the programs in the
# current source directory's bin/ directory.
env['PATH'] = os... |
yohanko88/gem5-DC | src/sim/SubSystem.py | Python | bsd-3-clause | 2,797 | 0.000358 | # Copyright (c) 2014 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | istributions of source code must retain the above copyright
# notice, | this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names... |
canvasnetworks/canvas | website/drawquest/activities.py | Python | bsd-3-clause | 1,939 | 0.002063 | from website.apps.activity.base_activity import BaseActivity
class WelcomeActivity(BaseActivity):
TYPE = 'welcome'
class StarredActivity(BaseActivity):
TYPE = 'starred'
FORCE_ANONYMOUS = False
@classmethod
def from_sticker(cls, actor, comment_sticker):
comment = comment_sticker.comment
... | olute_url_for_image_type('activity'),
'comment_id': comment_details.id,
'quest_id': comment.parent_comment_id,
}
return cls(data, actor=actor)
class PlaybackActivity(BaseActivity):
| TYPE = 'playback'
FORCE_ANONYMOUS = False
@classmethod
def from_comment(cls, actor, comment):
comment_details = comment.details()
data = {
'thumbnail_url': comment_details.reply_content.get_absolute_url_for_image_type('activity'),
'comment_id': comment_details.id,
... |
GNOME/orca | test/keystrokes/firefox/object_nav_descriptions_down.py | Python | lgpl-2.1 | 6,661 | 0.00015 | #!/usr/bin/python
"""Test of line navigation output of Firefox."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
#sequence.append(WaitForDocLoad())
sequence.append(PauseAction(5000))
# Work around some new quirk in Gecko that causes this test to fail if
# run via the test harness rather t... | Black checkbox check box'",
" VISIBLE: '< > Title of the Black checkbox ', cursor=1",
"SPEECH OUTPUT: 'Title of the Black checkbox check box not checked.'"]))
sequence.append(utils.StartRecordingAction())
| sequence.append(KeyComboAction("Down"))
sequence.append(utils.AssertPresentationAction(
"9. Line Down",
["BRAILLE LINE: 'Black'",
" VISIBLE: 'Black', cursor=1",
"SPEECH OUTPUT: 'Black'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Down"))
sequence.append(util... |
pacoqueen/ginn | ginn/formularios/logviewer.py | Python | gpl-2.0 | 17,683 | 0.006298 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) 2005-2014 Francisco José Rodríguez Bogado, #
# <pacoqueen@users.sourceforge.net> #
# ... | DEBUG":
# Información de depuración.
color = "light grey"
elif "login" in texto.lower():
# LOGIN | con éxito.
color = "orange"
elif "Acceso err" in texto:
# LOGIN fallido.
color = "indian red"
elif "logout" in texto.lower():
# LOGOUT.
color = "yellow4"
elif "CONSUMO" in texto and "FIBRA" in texto:
... |
alito/smallpotato | tools/makebookfrompgn.py | Python | gpl-2.0 | 3,770 | 0.007162 | #!/usr/bin/env python
#coding: utf8
"""
Restore the saved list of documents that were being read
"""
from __future__ import print_function, absolute_import, division
import sys, os
import logging
import subprocess
DefaultExecutable = 'smallpotato'
DefaultBook = 'book.opn'
DefaultMaxPly = 20
class EngineConnector(ob... | ind('.')
if dot >= 0:
move = move[dot + 1:].strip()
if | move == '':
continue
self.process.stdin.write('sp_sanmove %s\n' % move)
currentply += 1
if currentply > self.maxPly:
break
def main(args):
from argparse import ArgumentParser
from simplelogger impo... |
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/script.audio.spotimc.smallplayer/default.py | Python | gpl-2.0 | 3,422 | 0.009936 | '''
Copyright 2011 Mikel Azkolain
This file is part of Spotimc.
Spotimc is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Spotimc ... | bs_dir, "PyspotifyCtypes.egg"))
sys.path.insert(0, os.path.join(libs_dir, "PyspotifyCtypesProxy.egg"))
#And perform the rest of the import statements
from envutils import set_library_paths
from skinutils import reload_skin
from skinutils.fonts import FontManager
from skinutils.includ... | rary_paths('resources/dlls')
#Install custom fonts
fm = FontManager()
skin_dir = os.path.join(__addon_path__, "resources/skins/DefaultSkin")
xml_path = os.path.join(skin_dir, "720p/font.xml")
font_dir = os.path.join(skin_dir, "fonts")
fm.install_file(xml_path, font_dir)
#I... |
goulu/Goulib | tests/test_Goulib_interval.py | Python | lgpl-3.0 | 8,146 | 0.030935 | #!/usr/bin/env python
# coding: utf8
from nose.tools import assert_equal
from nose import SkipTest
#lines above are inserted automatically by pythoscope. Line below overrides them
from Goulib.tests import *
from Goulib.interval import *
class TestInInterval:
def test_in_interval(self):
assert... | def test_intersect(self):
assert_equal(intersect([1,3],[2,4]),True)
assert_e | qual(intersect([3,1],(4,2)),True)
assert_equal(intersect((1,2),[2,4]),False)
assert_equal(intersect((5,1),(2,3)),True)
class TestIntersection:
def test_intersection(self):
assert_equal(intersection([1,3],(4,2)),(2,3))
assert_equal(intersection([1,5],(3,2)),(2,3))
ass... |
bobandbetty/assassins | assassins/users/migrations/0001_initial.py | Python | mit | 3,152 | 0.004124 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-20 06:42
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependenc... | atus')),
('is_active', models.BooleanField(default=True, help_text='Designa | tes whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('profile_picture_url', models.CharField(max_length=200)),
... |
google/picatrix | picatrix/notebook_init.py | Python | apache-2.0 | 1,081 | 0.002775 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | S" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Initialization module for picatrix magics.
When starting a new notebook using picatrix it is enou | gh to do
from picatrix import notebook_init
notebook_init.init()
And that would register magics and initialize the notebook to be able
to take advantage of picatrix magics and helper functions.
"""
# pylint: disable=unused-import
from picatrix import helpers, magics
from picatrix.lib import state
def init():
... |
google-research/google-research | rouge/tokenizers.py | Python | apache-2.0 | 1,661 | 0.004214 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License a | t
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific langu | age governing permissions and
# limitations under the License.
"""Library containing Tokenizer definitions.
The RougeScorer class can be instantiated with the tokenizers defined here. New
tokenizers can be defined by creating a subclass of the Tokenizer abstract class
and overriding the tokenize() method.
"""
import ... |
m0tive/fsm | site_scons/site_tools/doxygen/doxygen_norton_2007-12-20.py | Python | mit | 6,137 | 0.023464 | # vim: set et sw=3 tw=0 fo=awqorc ft=python:
#
# Astxx, the Asterisk C++ API and Utility Library.
# Copyright (C) 2005, 2006 Matthew A. Nicholson
# Copyright (C) 2006 Tim Blechmann
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License ... | sources.extend(glob.glob("/".join([node, pattern])))
sources = map( lambda path: env.File(path), sources )
return sources
def DoxySourceScanCheck(node, env):
"""Check if we should scan this file"""
return os.path.isfile(node.path)
def DoxyEmitter(source, target, env):
"""Doxyg | en Doxyfile emitter"""
# possible output formats and their default values and output locations
output_formats = {
"HTML": ("YES", "html"),
"LATEX": ("YES", "latex"),
"RTF": ("NO", "rtf"),
"MAN": ("YES", "man"),
"XML": ("NO", "xml"),
}
data = DoxyfileParse(source[0].get_content... |
pacocampo/Backend | semana2/list.py | Python | gpl-3.0 | 105 | 0.009524 | lista = [1, 3, 5, 20, 50, 100]
print([x**2 for x in lista])
print([x for x in lista if x | < 50 and x > 2]) | |
scheib/chromium | third_party/wpt_tools/wpt/tools/webtransport/h3/capsule.py | Python | bsd-3-clause | 3,709 | 0.00027 | from enum import IntEnum
from typing import Iterator, Optional
# TODO(bashi): Remove import check suppressions once aioquic dependency is
# resolved.
from aioquic.buffer import UINT_VAR_MAX_SIZE, Buffer, BufferReadError # type: ignore
class CapsuleType(IntEnum):
# Defined in
# https://www.ietf.org/archive/i... | psule of an unknown type.
:param data the payload
"""
self.type = type
self.data = data
def encode(self) -> bytes:
"""
Encodes this H3Capsule and return t | he bytes.
"""
buffer = Buffer(capacity=len(self.data) + 2 * UINT_VAR_MAX_SIZE)
buffer.push_uint_var(self.type)
buffer.push_uint_var(len(self.data))
buffer.push_bytes(self.data)
return buffer.data
class H3CapsuleDecoder:
"""
A decoder of H3Capsule. This is a stre... |
basement-labs/osmapa-garmin | osmapa/boundaries.py | Python | gpl-2.0 | 2,693 | 0.004458 | """
OpenStreetMap boundary generator.
Author: Andrzej Talarczyk <andrzej@talarczyk.com>
Based on work of Michał Rogalski (Rogal).
License: GPLv3.
"""
import os
import platform
import shutil
def clean(src_dir):
"""Remove target files.
Args:
src_dir (string): path to the directory from which target... | s:
bin_dir (string): path to a directory holding compilation tools
src_dir (string): path to a directory with source data
pbf_filename (string): source PBF file
Raises:
Exception: [description]
Returns:
int: 0 if succes.
"""
ret = -1
if p | latform.system() == 'Windows':
ret = os.system("start /low /b /wait {binarki}/osmconvert.exe {dane_osm}/{pbf_filename} --out-o5m >{dane_osm}/poland.o5m".format(
binarki=bin_dir, dane_osm=src_dir, pbf_filename=pbf_filename))
ret = os.system("start /low /b /wait {binarki}/osmfilter.exe {dane_o... |
kntem/webdeposit | modules/bibworkflow/lib/tasks/simplified_data_tasks.py | Python | gpl-2.0 | 1,455 | 0.008935 | ## This file is part of Invenio.
## Copyright (C) 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Inv... | data test functions - NOT FOR XML """
from inveni | o.bibworkflow_config import CFG_OBJECT_STATUS
def task_a(a):
def _task_a(obj, eng):
"""Function task_a docstring"""
eng.log.info("executing task a " + str(a))
obj.data += a
return _task_a
def task_b(obj, eng):
"""Function task_b docstring"""
eng.log.info("executing task b")
... |
tensorflow/lingvo | lingvo/tasks/asr/input_generator.py | Python | apache-2.0 | 6,359 | 0.005189 | # Lint as: python3
# Copyright 2018 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 ... | one):
"""Builds an input batch.
Args:
batch_size: batch size to use, defaults to infeed batch size.
features_list: Use this list to build the batch.
bucket_keys: If None, bucket_keys[i] is the bucketing key of the i-th
sample.
Re | turns:
py_utils.NestedMap with feature names as keys and tensors as values.
"""
p = self.params
batch = py_utils.NestedMap()
batch.bucket_keys = bucket_keys
(utt_ids, tgt_ids, tgt_labels, tgt_paddings, src_frames,
src_paddings) = features_list
if not py_utils.use_tpu():
batch... |
live4thee/zstack-utility | apibinding/setup.py | Python | apache-2.0 | 797 | 0.003764 | from setuptools import setup, find_packages
import sys, os
version = '2.3.0'
setup(name='apibinding',
version=version,
description="ZStack API Python bindings library",
long_description="""\
ZSt | ack API Python bindings library""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='zstack api python message',
author='Frank Zhang',
author_email='xing5820@gmail.com',
url='http://zstack | .org',
license='Apache License 2',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
dontnod/weblate | weblate/trans/views/js.py | Python | gpl-3.0 | 9,337 | 0.000107 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2019 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... | exc.__class__.__name__,
str(exc)
)
return JsonResponse(data=response)
@require_POST
def translate(request, unit_id, service):
"""AJAX handler for translating."""
if service not in MACHINE_TRANSLATION_SERVICES:
raise Http404('Invalid service specified')
unit = get_o... | rals()[0]
)
@require_POST
def memory(request, unit_id):
"""AJAX handler for translation memory."""
unit = get_object_or_404(Unit, pk=int(unit_id))
query = request.POST.get('q')
if not query:
return HttpResponseBadRequest('Missing search string')
return handle_machinery(request, 'webla... |
sevas/csxj-crawler | tests/datasources/parser_tools/test_media_utils.py | Python | mit | 4,676 | 0.004705 | """
Test suite for the embedded <script> extraction
"""
from BeautifulSoup import BeautifulSoup
from nose.tools import raises, eq_
from csxj.datasources.parser_tools import media_utils
from csxj.datasources.parser_tools import twitter_utils
from tests.datasources.parser_tools import test_twitter_utils
def make_soup(... | agged_URL = media_utils.extract_tagged_url_from_embedded_script(soup.script, self.netloc, self.internal_sites)
expected_tags = set(['twitter widget', 'twitter profile', 'script', 'external', 'embedded'])
eq_(tagged_URL.tags, expected_tags)
@raises(ValueError)
def test_embedded_javascript_code(... | """ The embedded <script> extraction raises a ValueError when processing a <script> tag with arbitrary Javascript code inside """
js_content = """<script type='text/javascript'>var pokey='penguin'; </script>"""
soup = make_soup(js_content)
media_utils.extract_tagged_url_from_embedded_script... |
phillipemoreira/HackerRank | Python/Introduction/3_IfElse.py | Python | mit | 275 | 0.018182 | #Problem link: https://www.hackerrank.com/challenges/py-if- | else
#!/bin/python
import sys
N = int(input().strip()) |
if (N % 2 > 0):
print("Weird")
elif (N >= 2 and N <=5):
print("Not Weird")
elif (N >= 6 and N <=20):
print("Weird")
else:
print("Not Weird") |
BeATz-UnKNoWN/python-for-android | python3-alpha/python3-src/Lib/test/test_tk.py | Python | apache-2.0 | 651 | 0.006144 | from test import support
# Skip test if _tkinte | r wasn't built.
support.import_module('_tkinter')
# Skip test if tk cannot be initialized.
from tkinter.test.support import check_tk_availability
check_tk_availability()
from tkinter.test import runtktests
def test_main(enable_gui=False):
if enable_gui:
if support.use_resources is None:
suppo... | ntktests.get_tests(text=False, packages=['test_tkinter']))
if __name__ == '__main__':
test_main(enable_gui=True)
|
charlesthk/python-mailchimp | mailchimp3/entities/automationactions.py | Python | mit | 1,368 | 0.005117 | # coding=utf-8
"""
The Automations API endpoint actions
Note: This is a paid feature
Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/automations/
"""
from __future__ import unicode_literals
from mailchimp3.baseapi import BaseApi
class AutomationActions(BaseApi):
"""
Actions ... | def start(self, workflow_id):
"""
Start all emails in an Automation workflow.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
"""
self.workflow_id = workflow_id
return self._mc_client._post(url=self._build_path(w... | ))
|
neurospin/pylearn-epac | test/bug_joblib/test_joblib_2000fts.py | Python | bsd-3-clause | 1,126 | 0.01421 | from joblib import Parallel, delayed
from epac import Methods
import numpy as np
from sklearn import datasets
from sklearn.svm import SVC
X, y = datasets.make_classification(n_samples=500,
n_features=200000,
| n_informative=2,
random_state=1)
methods = Methods(*[SVC(C=1, kernel='linear'), SVC(C=1, kernel='rbf')])
data = {"X":X, 'y':y, "methods": methods}
# X = np.random.random((500, 200000))
def map_func(data):
from sklearn.cross_validation import Strat... | tifiedKFold(y=data['y'], n_folds=3)
# kfold = cross_validation.KFold(n=data.X.shape[0], n_folds=3)
# svc = SVC(C=1, kernel='linear')
for train, test in kfold:
# svc.fit(data['X'][train], data['y'][train])
# svc.predict(data['X'][test])
data['methods'].run(X=data["X"][train], y=data['y'][train])
... |
gnarph/DIRT | dirtgui/document_grid.py | Python | mit | 5,149 | 0.001359 | import utilities.file_ops as file_ops
|
from PyQt4 impor | t QtGui, QtCore
from dirtgui.document_util import document_match_util as match_util
NEXT_TT = u'Move to next match within this document'
PREV_TT = u'Move to prevous match within this document'
class DocumentGrid(QtGui.QGridLayout):
"""
Creates a grid with Location, Title, Author, and Text READ-only display
... |
supersu097/Mydailytools | po_new_generate.py | Python | gpl-3.0 | 1,794 | 0.001672 | #!/usr/bin/env python
# coding=utf-8
# Created by sharp.gan at 2017-01-08
import os
import argparse
import subprocess
# Assume that you already installed the dependency of GNU-gettext, or you need to
# resolve this using your system package management tool such as `sudo apt
# install gettext`
# main process of reslo... | help='The new translation .PO filename you want, by default is'
' fr_django.po')
args = parser.parse_args()
print('Now we start to process, wait~')
process(args.new)
clean()
print('\nThe new .PO translation file of {} is alread | y in your '
'current directory, please check!'.format(args.new))
|
cathyyul/sumo-0.18 | tools/net/netstats.py | Python | gpl-3.0 | 1,975 | 0.002532 | #!/usr/bin/env python
"""
@file netstats.py
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-08-13
@version $Id: netstats.py 14425 2013-08-16 20:11:47Z behrisch $
Prints some information about a given network
SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
Copyright (C) 2009-2013 DLR... | t(sys.argv[1])
values = {}
values["netname"] = "hallo"
values["edgesPerLaneNumber"] = {}
values["edgeLengthSum"] = 0
values["laneLengthSum"] = 0
values["edgeNumber"] = len(net._edges)
values["nodeNumber"] = len(net._nodes)
for e in net._edges:
values["edgeLengthSum"] = values["edgeLengthSum"] + e._length
value... | values["edgesPerLaneNumber"][len(e._lanes)] = 0
values["edgesPerLaneNumber"][len(e._lanes)] = values["edgesPerLaneNumber"][len(e._lanes)] + 1
renderHTML(values)
renderPNG(values)
|
tbarbugli/django_email_multibackend | setup.py | Python | isc | 4,819 | 0.000208 | #!/usr/bin/env python
from distutils.util import convert_path
from django_email_multibackend import __version__, __maintainer__, __email__
from fnmatch import fnmatchcase
import os
import sys
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
s... | es=excluded_directories)
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: | GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development... |
ucsb-seclab/ictf-framework | scoring_ictf/scoring_ictf/simple_lru_cache.py | Python | gpl-2.0 | 1,388 | 0.002161 | from collections import OrderedDict
class LRUCache(object):
def __init__(self, capacity):
self.max_capacity = capacity
self.cached = OrderedDict()
def __contains__(self, k):
return k in self.cached
def __getitem__(self, item):
return self.get(item)
def __setitem__(sel... | ef set(self, k, v):
self.cached[k] = v
if len(self.cached) > self.max_capacity:
return self.cached.popitem(last=False) # FIFO behavior
return None
def func_args_to_cache_key(args, kwargs):
return tuple(args), tuple(kwargs.items())
def lru_cache_decorator(capacity=32, cache=No... | def wrapped_f(*args, **kwargs):
key = func_args_to_cache_key(args, kwargs)
if key in cache:
return cache.get(key)
val = f(*args, **kwargs)
cache.set(key, val)
return val
wrapped_f.uncached = f
wrapped_f.cache = cache
... |
minixalpha/SourceLearning | webpy/src/web/wsgiserver/ssl_builtin.py | Python | apache-2.0 | 2,589 | 0.005407 | """A library for integrating Python's builtin ``ssl`` l | ibrary with CherryPy.
The ssl module must be importable for SSL functionalit | y.
To use this module, set ``CherryPyWSGIServer.ssl_adapter`` to an instance of
``BuiltinSSLAdapter``.
"""
try:
import ssl
except ImportError:
ssl = None
from cherrypy import wsgiserver
class BuiltinSSLAdapter(wsgiserver.SSLAdapter):
"""A wrapper for integrating Python's builtin ssl module with CherryP... |
apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/tagesschau.py | Python | unlicense | 4,945 | 0.00182 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import parse_filesize
class TagesschauIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?tagesschau\.de/multimedia/(?:sendung/ts|video/video)(?P<id>-?[0-9]+)\.html'
_TESTS = [{
... | r'''(?x)
Video:\s*(?P<vcodec>[a-zA-Z0-9/._-]+)\s*&\#10;
(?P<width>[0-9]+)x(?P<height>[0-9]+)px&\#10;
(?P<vbr>[0-9]+)kbps&\#10;
Audio:\s*(?P<abr>[0-9]+)kbps,\s*(?P<audio_desc>[A-Za-z\.0-9]+)&\#10;
Gr&... | 'format_note': m.group('audio_desc'),
'vcodec': m.group('vcodec'),
'width': int(m.group('width')),
'height': int(m.group('height')),
'abr': int(m.group('abr')),
'vbr': int(m.group('vbr')),
... |
Piasy/proxy-searcher | service/service/views.py | Python | mit | 233 | 0.025751 | #!/usr/bin/env python
#-* | - coding: utf-8 -*-
from django.http import HttpResponse
import service.api
def api_available(request):
return HttpResponse(service.api.get_proxy())
def hello(request):
return HttpResponse(" | Hello world!") |
rekbun/project-euler | src/python/problem39.py | Python | apache-2.0 | 235 | 0.123404 | def f(n):
cnt=0
for a in range(1,n-3):
for b in range(a,n-3):
c =n- | a-b
| if(c>b):
if((a*a+b*b)==c*c):
cnt+=1
return cnt
ans=0
num=0
for i in range(1000,100,-1):
val= f(i)
if(val>ans):
ans=val
num=i
print num
|
bitcrystal/buildtools-BaseTools | Source/Python/Ecc/Check.py | Python | bsd-2-clause | 71,517 | 0.004041 | ## @file
# This file is used to define checkpoints used by ECC tool
#
# Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. T... | r F in Filenames:
# if os.pa | th.splitext(F)[1] in ('.c', '.h'):
# FullName = os.path.join(Dirpath, F)
# c.CheckFuncLayoutName(FullName)
for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
c.CheckFuncLayoutName(FullName)
# Check whether the functio... |
Psycojoker/hackeragenda | authentication/views.py | Python | gpl-3.0 | 408 | 0.004902 | from d | jango.contrib.auth import views as auth
def login(request):
return auth.login(request, template_name="registration/login.haml")
def password_change(request):
return auth.password_change(request, template_name="registration/password_change_form.haml")
def password_change_done(request):
return auth.pass... | me="registration/password_change_done.haml")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.