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 |
|---|---|---|---|---|---|---|---|---|
ugaliguy/HackerRank | Mathematics/Algebra/wet-shark-and-42.py | Python | mit | 669 | 0.017937 | # Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(raw_input())
for i in range(t):
MOD = 10**9 + 7
s = int(input())
k = s/20
rem = s%20
if rem == 0:
print (42*k - 2)%MOD
else:
print (42*k + 2*r | em)%MOD
# The following code times out on the tests
# but I think it works
#
# s = int(raw_input())%(10**9 + 7)
# # k = s/20
# # square = 2*s + k
# square = 0
# while s != 0:
# square += | 1
# if square%2 == 0 and square%42 != 0:
# s -= 1
# print "square = " + str(square) + " s = " + str(s)
# print square
|
epeios-q37/epeios | other/libs/tortoise/PYH/setup.py | Python | agpl-3.0 | 2,114 | 0.000946 | """
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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
... | ISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import setuptools
version = "0.1.1"
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="tortoise",
version=version,
author="Claude SIMON",
# ... | l="author@example.com",
description="Turtle graphics on the web.",
keywords="turtle, web",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/epeios-q37/tortoise-python",
packages=setuptools.find_packages(),
install_requires=[
... |
cournape/audiolab | audiolab/soundio/play.py | Python | lgpl-2.1 | 4,020 | 0.001493 | #
# Copyright (C) 2008 Cournapeau David <cournape@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:
#
# * Redistributions of source code must retain the above copyright
# ... | F THE POSSIBILITY OF SUCH DAMAGE.
import sys
import warnings
import numpy as np
if sys.platform[:5] = | = 'linux':
BACKEND = 'ALSA'
elif sys.platform[:6] == 'darwin':
BACKEND = 'CoreAudio'
else:
BACKEND = None
if BACKEND == 'ALSA':
try:
from audiolab.soundio._alsa_backend import AlsaDevice
except ImportError, e:
warnings.warn("Could not import alsa backend; most probably, "
... |
sebastinas/curtsies | tests/test_fmtstr.py | Python | mit | 23,147 | 0.001043 | import sys
import unittest
from curtsies.formatstring import (
FmtStr,
fmtstr,
Chunk,
linesplit,
normalize_slice,
width_aware_slice,
)
from curtsies.fmtfuncs import (
blue,
red,
green,
on_blue,
on_red,
on_green,
underline,
blink,
bold,
)
from curtsies.termform... | lf.assertEqual(a.shared_atts["fg"], FG_COLORS["blue"])
self.assertEqual(b.shared_atts["fg"], FG_COLORS["red"])
def test_immutibility_of_FmtStr(self):
a = fmtstr("hi", "blue")
b = green(a)
self.assertEqual(a.shared_atts["fg"], FG_COLORS["blue"])
self.assertEqual(b.shared_atts... | abc"))
self.assertEqual(fmtstr("abc").splice("d", 0), "d" + fmtstr("abc"))
def test_various_splices(self):
a = blue("hi")
b = a + green("bye")
c = b + red("!")
self.assertEqual(
c.splice("asdfg", 1),
blue("h") + "asdfg" + blue("i") + green("bye") + re... |
dhavalmanjaria/dma-student-information-system | document_requests/apps.py | Python | gpl-2.0 | 108 | 0 | from django.apps import AppConfig
class DocumentRequestsConfig(AppConfig):
name = 'd | ocument_requ | ests'
|
alex8866/cinder | cinder/volume/drivers/netapp/eseries/iscsi.py | Python | apache-2.0 | 35,860 | 0 | # Copyright (c) 2014 NetApp, 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... |
"""
import socket
import time
import uuid
from oslo.config import cfg
import six
from cinder import exception
from cinder.i18n import _
from | cinder.openstack.common import excutils
from cinder.openstack.common import log as logging
from cinder.openstack.common import units
from cinder import utils as cinder_utils
from cinder.volume import driver
from cinder.volume.drivers.netapp.eseries import client
from cinder.volume.drivers.netapp.options import netapp_... |
fedora-infra/the-new-hotness | hotness/responses/response_failure.py | Python | lgpl-2.1 | 6,212 | 0.001127 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This ... | return response
@classmethod
def database_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for database failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFail... | @classmethod
def notifier_error(cls, message: Any) -> "ResponseFailure":
"""
Creates response for notifier failure.
Params:
message: Message to add to this error
Returns:
ResponseFailure object
"""
response = ResponseFailure(type=ResponseFail... |
lsiemens/dockerfiles | multiuser/jupyterhub_config.py | Python | bsd-3-clause | 1,988 | 0.003521 | import os
import subprocess
config = get_config()
# Use GitHub OAuth to authenticate users
config.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator'
config.GitHubOAuthenticator.oauth_callback_url = 'https://206.12.96.12/hub/oauth_callback'
config.GitHubOAuthenticator.client_id = 'a4b7e7154c6f9d8497... | n
co | okie = subprocess.Popen(["openssl", "rand", "2049"], stdout=subprocess.PIPE)
token = subprocess.Popen(["openssl", "rand", "-hex", "129"], stdout=subprocess.PIPE)
config.JupyterHub.cookie_secret = cookie.communicate()[0][:-1]
config.JupyterHub.proxy_auth_token = token.communicate()[0][:-1]
data_mount_point = os.environ... |
scharch/zap | utilities/getListFromFasta.py | Python | gpl-3.0 | 1,174 | 0.017888 | #!/usr/bin/env python3
"""
getListFromFasta.py
This is a simple utility script for getting a list of the sequence identifiers
from a large fasta file.
Usage: getListFromFasta.py -f <seqs.fa> [ -o <output.list> ]
Options:
-f <seqs.fa> Fasta file containing the sequences.
-o <output.list> Text f... | by CAS 2018-08-28.
Copyright (c) 2011-2018 Columbia University and Vaccine Research Center, National
Institutes of Health, USA. All rights reserved.
"""
import sys
from docopt import docopt
try:
from SONAR import *
except ImportError:
find_SONAR = sys.argv[0].split("SONAR/utilitie | s")
sys.path.append(find_SONAR[0])
from SONAR import *
def main():
if arguments['-o'] != "STDOUT":
sys.stdout = open(arguments['-o'], "w")
for seq in generate_read_fasta(arguments['-f']):
print( "%s"%seq.id )
if __name__ == '__main__':
arguments = docopt(__doc__)
#log command line
logCmdLi... |
erikdejonge/python_for_kids | chapter09/opening_a_file.py | Python | gpl-2.0 | 130 | 0.023077 | #
# Place a file calle | d test.txt in the same directory as you place this program... |
#
f = open('test.txt')
s = f.read()
print(s) |
ilstreltsov/django-db-mailer | dbmail/south_migrations/0032_auto__add_signaldeferreddispatch__add_index_signaldeferreddispatch_eta.py | Python | gpl-2.0 | 16,851 | 0.007774 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django import VERSION
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SignalDeferredDispatch'
db.cre... | django.db.models.fields.DateTimeField')(db_index=True)),
| ('done', self.gf('django.db.models.fields.NullBooleanField')(default=None, null=True, blank=True)),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal(u'dbmail', ['SignalDeferredDispatch'])
# Adding index on 'Signal... |
petewarden/tensorflow | tensorflow/python/keras/engine/compile_utils_test.py | Python | apache-2.0 | 32,114 | 0.001962 | # Copyright 2019 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... | _metric.result().numpy(), 0.5)
def test_broadcast_single_loss(self):
loss_container = compile_utils.LossesContainer('mse')
y_t = [array_ops.ones((10, 1)), array_ops.zeros((10, 1))] |
y_p = [array_ops.ones((10, 1)), array_ops.ones((10, 1))]
sw = ops.convert_to_tensor_v2_with_dispatch([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
total_loss = loss_container(y_t, y_p, sample_weight=sw)
self.assertEqual(total_loss.numpy(), 0.5)
self.assertLen(loss_container.metrics, 3)
loss_metric = loss_c... |
RuiNascimento/krepo | script.module.lambdascrapers/lib/lambdascrapers/sources_ lambdascrapers/en/videoscraper.py | Python | gpl-2.0 | 2,631 | 0.006461 | # -*- coding: UTF-8 -*-
'''
videoscraper scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import json, urllib, urlparse
from resources.lib.modules import client
from resources.lib.modules import directstream
class source:
def __i... | en']
self.domains = ['localhost']
self.base_link = 'http://127.0.0.1:16735'
def movie(self, imdb, title, localtitle, aliases, year):
try:
return urllib.urlencode({'imdb': imdb, 'title': title, 'year': year})
except:
return
def tvshow(self, imdb, tvdb, t... | 'title': tvshowtitle, 'year': year})
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
return urllib.urlencode(... |
scipy/scipy | scipy/sparse/linalg/eigen.py | Python | bsd-3-clause | 1,151 | 0 | # This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.sparse.linalg` namespace for importing the functions
# included below.
import warnings
from . import _eigen
__all__ = [ # noqa: F822
'ArpackError', 'ArpackNoConvergence',
'eigs', 'eigsh', 'lobpcg', 'svds', 'arpack'... | eigen is deprecated and has no attribute "
f"{name}. Try | looking in scipy.sparse.linalg instead.")
if name in eigen_modules:
msg = (f'The module `scipy.sparse.linalg.eigen.{name}` is '
'deprecated. All public names must be imported directly from '
'the `scipy.sparse.linalg` namespace.')
else:
msg = (f"Please use `{name}... |
rocky/python3-trepan | trepan/lib/pp.py | Python | gpl-3.0 | 3,965 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2009, 2013, 2015-2016, 2020-2021 Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | hat has more than `length` items,
then truncate it to the first `length` items.
"""
if isinstance(obj, dict):
n | ew_obj = dict((k[:length], v) for k, v in sorted(obj.items()))
# We hope zzz will be appear at the end of the sorted list.
new_obj.update({"zzz...": "..."})
return new_obj
elif hasattr(obj, "__getitem__"):
return list(obj[:length]) + ["..."]
return obj
class SafePP(pprint.Prett... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/python/ops/tensor_array_grad.py | Python | bsd-2-clause | 9,083 | 0.008367 | # 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... | ted with the tf.gradients call
that is used to create the gradient TensorArray.
Args:
op_or_tensor: `Tensor` or `Operation` which is an input to a
| TensorArray*Grad call.
Returns:
A python string, the unique label associated with this particular
gradients calculation.
Raises:
ValueError: If not called within a gradients calculation.
"""
name_tokens = op_or_tensor.name.split("/")
grad_pos = [i for i, x in enumerate(name_tokens) if x.sta... |
daliwangi/bitcoin | test/functional/listtransactions.py | Python | mit | 10,471 | 0.015567 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listtransactions API."""
from test_framework.test_framework import BitcoinTestFramework
from ... | d":utxo_to_use["txid"], "vout":utxo_to_use["vout"]}]
outputs = {self.nodes[0].getnewaddress(): 0.999}
tx2 = self.nodes[1].createrawtransaction(inputs, outputs)
tx2_signed = self.nodes[1].signrawtransaction(tx2)["hex"]
txid_2 = self.nodes[1].sendrawtransaction(tx2_signed)
# .. | .and check the result
assert(not is_opt_in(self.nodes[1], txid_2))
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_2}, {"bip125-replaceable":"no"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_2}, {"bip125-replaceable":... |
avielw/kplugs | examples/1.1/undefined_func_remote.py | Python | gpl-3.0 | 432 | 0.006944 | #!/usr/bin/python2
import kplugs
try:
kernel_func = r'''
STATIC("my_helper")
def my_function():
try:
m | y_helper()
print "OK"
except word as err:
| print "Exception number: %d" % -err
raise err
def my_helper():
KERNEL_undefined_function()
'''
plug = kplugs.Plug(ip='127.0.0.1')
my_function = plug.compile(kernel_func)[0]
my_function()
finally:
kplugs.release_kplugs()
|
lhagan/phoshare | phoshare/phoshare_main.py | Python | apache-2.0 | 44,326 | 0.002572 | #!/usr/bin/env python
"""Reads iPhoto library info, and exports photos and movies."""
# Original work Copyright 2010 Google Inc.
# Modified work Copyright 2014 Luke Hagan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... | mode, check the inode.
if options.link:
export_stat = os.stat(self.export_file)
source_stat = os.stat(source_file)
if export_stat.st_in | o != source_stat.st_ino:
su.pout('Changed: %s: inodes don\'t match: %d vs. %d' %
(self.export_file, export_stat.st_ino, source_stat.st_ino))
return True
if (not options.reverse
and os.path.getmtime(self.export_file) + _MTIME_FUDGE <
os... |
gangadhar-kadam/hrerp | erpnext/hr/doctype/appraisal_rate_score_card/appraisal_rate_score_card.py | Python | agpl-3.0 | 266 | 0.011278 | # Copyright (c) 2013, We | b Notes Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.m | odel.document import Document
class AppraisalRateScoreCard(Document):
pass |
jgmanzanas/CMNT_004_15 | project-addons/product_outlet/product.py | Python | agpl-3.0 | 4,831 | 0.004763 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved
# $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
# This program is free software: you can redistribute it and/or modify
# it under the ... | GNU Affero General Public License for more deta | ils.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import fields, models, api
class product_product(models.Model):... |
vsaw/miniSSL | minissl/test/PemSamples.py | Python | mit | 991 | 0.001009 | import os.path
def __read_pem_from_res_folder(filename):
# todo document
return __read_pem_file(os.path.join(__res_folder, filename))
def __read_pem_file(file):
# todo document
with open(file, 'r') as f:
return f.read()
# find the res folder first
__base_folder = os.path.dirname(
os.pat... | .pem')
minnissl_server_key_pem = __read_pem_from_res_folder('minissl-server.key.pem')
minnissl_server_pem = __read_pem_from_res_fold | er('minissl-server.pem')
rogue_ca_pem = __read_pem_from_res_folder('rogue-ca.pem')
rogue_client_key_pem = __read_pem_from_res_folder('rogue-client.key.pem')
rogue_client_pem = __read_pem_from_res_folder('rogue-client.pem')
|
bcornwellmott/frappe | frappe/patches/v7_0/cleanup_list_settings.py | Python | mit | 586 | 0.046075 | import frappe, json
def execute():
if frappe.db.table_exists("__ListSettings"):
list_settings = frappe.db.sql("select user, doctype, data from __ListSettings", as_dict=1)
for ls in list_settings:
if ls and ls.data:
data = json.loads(ls.data)
if not data.has_key("fields") | :
continue
fields = data["fields"]
for field in fields:
if "name as" in field:
fields.remove(field)
data["fields"] = fields
frappe.db.sql("update __Li | stSettings set data = %s where user=%s and doctype=%s",
(json.dumps(data), ls.user, ls.doctype))
|
codecov/pathmap | pathmap/__init__.py | Python | apache-2.0 | 238 | 0 | # -*- coding: utf-8 -*-
from .pathmap import (
cle | an_path,
_check_ancestors,
_resolve_path,
resolve_paths,
resolve_by_method
)
from .utils import (
_extract_match
)
from .tree import Tree
__version__ = | '0.1.5'
|
google/ml_collections | ml_collections/config_flags/tests/config_path_test.py | Python | apache-2.0 | 4,017 | 0.004232 | # Copyright 2022 The ML Collections 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 applicable law or agreed... | y key update."""
test_config = mock_config.get_config()
with self.assertRaises(ValueError):
config_path.set_value('', test_config, None)
def test_field_reference_types(self):
"""Tests whether types of FieldReference fields are valid."""
test_config = fieldreference_config.get_config()
pat... | et_type(path, test_config) for path in paths]
self.assertEqual(paths_types, config_types)
@parameterized.parameters(
('float', float),
('integer', int),
('string', str),
('bool', bool),
('dict', dict),
('dict.float', float),
('dict.list', list),
('list', list),
... |
Chaffelson/whoville | whoville/cloudbreak/models/user_profile_response.py | Python | apache-2.0 | 7,516 | 0.00133 | # coding: utf-8
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud... | credential': 'CredentialResponse',
'image_catalog': 'ImageCatalogShortResponse',
'owner': 'str',
'account': 'str',
'username': 'str',
'ui_properties': 'dict(str, object)'
}
attribute_map = {
'credential': 'credential',
'image_catalog': 'imageCatalog',
... | name',
'ui_properties': 'uiProperties'
}
def __init__(self, credential=None, image_catalog=None, owner=None, account=None, username=None, ui_properties=None):
"""
UserProfileResponse - a model defined in Swagger
"""
self._credential = None
self._image_catalog = ... |
antoinecarme/sklearn2sql_heroku | tests/classification/iris/ws_iris_SGDClassifier_oracle_code_gen.py | Python | bsd-3-clause | 133 | 0.015038 | from sklearn2sql_ | heroku.tests.classification import generic as class_gen
class_gen.test_model(" | SGDClassifier" , "iris" , "oracle")
|
mogproject/artifact-cli | setup.py | Python | apache-2.0 | 822 | 0 | from setuptools import setup, find_packages
SRC_DIR = 'src'
def get_version():
import sys
sys.path[:0] = [SRC_DIR]
return __import__('artifactcli').__version__
setup(
name='artifact-cli',
| version=get_version(),
description='Private Artifact Manager using Amazon S3',
author='mogproject',
author_email='mogproj@gmail.com',
url='https://github.com/mogproject/artifact-cli',
install_requires=[
'pytz',
'python-dateutil<2.8.1, | >=2.1',
'GitPython>=0.3.5',
'boto3',
'botocore'
],
tests_require=[
'moto',
],
package_dir={'': SRC_DIR},
packages=find_packages(SRC_DIR),
include_package_data=True,
test_suite='tests',
entry_points="""
[console_scripts]
art = artifactcli.artifactcl... |
JonSteinn/Kattis-Solutions | src/Good Morning!/Python 3/main.py | Python | gpl-3.0 | 1,952 | 0.012295 | class Timers:
def __init__(self):
self.transitions = {
1: {2,4},
2: {3,5},
3: {6},
4: {5,7},
5: {6,8},
6: {9},
7: {8},
8: {9,0},
9: set(),
0: set()
}
self.all = self._gener... | s.add(as_number)
| lis.pop()
lis.pop()
# Skip curr
for n in self.transitions[curr]:
self._gen_all_helper(n,lis,s)
def find_best(self,x):
l,r = 0, len(self.all)-1
while l <= r:
m = l + (r-l)//2
if self.all[m] == x:
return x
... |
pculture/unisubs | apps/videos/tests/test_indexing.py | Python | agpl-3.0 | 3,718 | 0.000269 | # Amara, universalsubtitles.org
#
# Copyright (C) 2015 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your op... | se):
@patch_for_test('videos.models.Video.calc_search_text')
def test_index_new_video(self, mock_calc_text):
mock_calc_text.return_value = 'test text'
v = VideoFactory()
| v.update_search_index()
assert_equal(v.search_text, 'test text')
@patch_for_test('videos.models.Video.calc_search_text')
def test_update_index(self, mock_calc_text):
mock_calc_text.return_value = 'old text'
v = VideoFactory()
v.update_search_index()
mock_calc_text.... |
Kattis/problemtools | examples/different/input_format_validators/validate.py | Python | mit | 574 | 0.003484 | #!/usr/bin/env python3
from sys import stdin
import sys
import re
integer = "(0|-?[1-9]\d*)"
M | AX = 10**15
cases = 0
while True:
line = stdin.readline()
if len(line) == 0:
break
assert re.match(integer + " " + integer + "\n", line), "'%s' is not a pair of integers" % line
(n, m) = map(int, line.split())
assert 0 <= n <= MAX, "%s not in [0, %s]" % (n, MAX)
assert 0 <= m <= MAX, ... | .exit(42)
|
philrosenfield/ResolvedStellarPops | utils/__init__.py | Python | bsd-3-clause | 40 | 0 | from utils import *
from | mpfit | import *
|
rigetticomputing/pyquil | pyquil/simulation/tests/test_reference_wavefunction.py | Python | apache-2.0 | 26,274 | 0.00099 | import functools
import inspect
import random
from math import pi
from operator import mul
import numpy as np
import pytest
from pyquil.api import WavefunctionSimulator
from pyquil.gates import (
CNOT,
CPHASE,
H,
HALT,
I,
MEASURE,
MOVE,
PHASE,
RESET,
RX,
RY,
RZ,
SWA... | .0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j, |
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.0j,
0.0625 + 0.... |
whitehorse-io/encarnia | pyenv/lib/python2.7/site-packages/django/contrib/gis/db/models/functions.py | Python | mit | 15,760 | 0.002157 | from decimal import Decimal
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.gis.db.models.sql import AreaField
from django.contrib.gis.measure import (
Area as AreaMeasure, Distance as DistanceMeasure,
)
from django.core.exceptions import FieldError
from django.db.models import Fl... |
super(AsSVG, self).__init__(*expressions, **extra)
class BoundingCircle(GeoFunc):
def __init__(self, expression, num_seg=48, **extra):
super(BoundingCircle, self).__init__(*[expression, num_seg], | **extra)
class Centroid(OracleToleranceMixin, GeoFunc):
pass
class Difference(OracleToleranceMixin, GeoFuncWithGeoParam):
pass
class DistanceResultMixin(object):
def convert_value(self, value, expression, connection, context):
if value is None:
return None
geo_field = Geom... |
encukou/freeipa | ipatests/test_webui/test_config.py | Python | gpl-3.0 | 19,710 | 0 | # Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 ... | port UI_driver
from ipatests.test_webui.ui_driver import screenshot
import ipatests.test_webui.data_config as config_data
import ipatests.test_webui.data_user as user_data
import ipatests.test_webui.data_group as group_data
import pytest
try:
from sel | enium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
except ImportError:
pass
ERR_USR_SEARCH_SPACES = ("invalid 'usersearch': Leading and trailing spaces "
"are not allowed")
ERR_USR_SEARCH_INV = ("invalid 'ipausersearchfields': attribute {} not "
... |
artefactual/archivematica-storage-service | storage_service/common/management/commands/create_user.py | Python | agpl-3.0 | 2,025 | 0 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from tastypie.models import ApiKey
class Command(BaseCommand):
help = (
"C... | add_argument("--username", required=True)
parser.add_argument("--email", required=True)
parser.add_argument("--password", required=True)
parser.add_argument("--api-key", required=True)
parser.add_argument("--superuser", action="store_true", default=False)
|
def handle(self, *args, **options):
UserModel = get_user_model()
user = None
try:
user = UserModel._default_manager.get(
**{UserModel.USERNAME_FIELD: options["username"]}
)
print("User found.")
except UserModel.DoesNotExist:
... |
ozmartian/vidcutter | vidcutter/videocutter.py | Python | gpl-3.0 | 83,617 | 0.003277 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#######################################################################
#
# VidCutter - media cutter & joiner
#
# copyright © 2018 Pete Alexandrou
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... | on', 'auto'}
self.enablePBO = self.settings.value('enablePBO', 'off', type=str) in {'on', 'true'}
self.keepRatio = self.settings.value('aspectRatio', 'keep', type=str) == 'keep'
self.keepClips = self.settings.value('keepClips', 'off', type=str) in {'on', 'true'}
self.nativeDialogs = self... | ayout = self.settings.value('indexLayout', 'right', type=str)
self.timelineThumbs = self.settings.value('timelineThumbs', 'on', type=str) in {'on', 'true'}
self.showConsole = self.settings.value('showConsole', 'off', type=str) in {'on', 'true'}
self.smartcut = self.settings.value('smartcut', 'of... |
project-icp/bee-pollinator-app | src/icp/icp/settings/test.py | Python | apache-2.0 | 724 | 0 | import os
from base import * # NOQA
# TEST SETTINGS
ALLOWED_HOSTS = ['localhost']
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
|
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
SELENIUM_DEFAULT_BROWSER = 'firefox'
SELENIUM_TEST_COMMAND_OPTIONS = {'pattern': 'uitest*.py'}
DJANGO_LIVE_TEST_SERVER_ADDRESS = os.environ.get(
'DJANGO_LIVE_TEST_SERVER_ADDRESS', 'localhost:9001')
# Turn off D... | 'rest_framework.renderers.JSONRenderer',
)
}
# azaveadev@azavea.com account
POLLINATION_GOOGLE_ANALYTICS = 'UA-67319750-1'
BEEKEEPERS_GOOGLE_ANALYTICS = 'UA-67319750-1'
|
ds-hwang/chromium-crosswalk | chrome/common/extensions/docs/server2/preview.py | Python | bsd-3-clause | 4,795 | 0.013139 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This helps you preview the apps and extensions docs.
#
# ./preview.py --help
#
# There are two modes: server- and render- mode... | 'the server, e.g. apps/storage | .html. The path may optionally end '
'with #n where n is the number of times to render the page before '
'printing it, e.g. apps/storage.html#50, to use for profiling.')
parser.add_option('-s', '--stat',
help='Print profile stats at the end of the run using the given '
'profilin... |
edx/edx-val | edxval/migrations/0002_add_error_description_field.py | Python | agpl-3.0 | 464 | 0.002155 | # Generated by Django 2.2.12 on 2020-04-29 05:0 | 9
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('edxval', '0001_squashed_0016_add_transcript_credentials_model'),
]
operations = [
migrations.AddField(
model_name='video',
name='error_description',
f... | ),
]
|
KwatME/plot | plot/make_colorscale_from_colors.py | Python | mit | 172 | 0.005814 | def make_co | lorscale_from_colors(colors):
if len(colors) == 1:
colors *= 2
return tuple((i / (len(colors) - 1), color) for i | , color in enumerate(colors))
|
SVilgelm/CloudFerry | tests/lib/copy_engines/test_base.py | Python | apache-2.0 | 4,186 | 0 | # Copyright (c) 2016 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | t'])
self.assertCalledOnce(runner.run_ignoring_errors)
class VerifySpaceInDestinationCopierTestCase(test.TestCase):
def test_raises_not_enough_space(self):
fake_c | opier = mock.Mock()
fake_copier.destination_has_enough_space.return_value = False
data = mock.MagicMock()
copier = base.CopierVerifyingSpaceInDestination(fake_copier)
self.assertRaises(base.NotEnoughSpace, copier.transfer, data)
class FakeCopier(base.BaseCopier):
name = 'fake'
... |
ndparker/gensaschema | setup.py | Python | apache-2.0 | 3,688 | 0 | #!/usr/bin/env python
# -*- coding: ascii -*-
u"""
:Copyright:
Copyright 2015 - 2021
Andr\xe9 Malo or his licensors, as applicable
:License:
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
... | 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.
==================================================
GenSASchema - Static SQLAlchemy Schema Generator
==================================================
GenSASchema - Static SQLAlchemy Schema Generator.
"""
__author_... |
jelly/calibre | src/calibre/utils/soupparser.py | Python | gpl-3.0 | 4,507 | 0.000888 | __doc__ = """External interface to the BeautifulSoup HTML parser.
"""
__all__ = ["fromstring", "parse", "convert_tree"]
from lxml import etree, html
from calibre.ebooks.BeautifulSoup import \
BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString
def fromstring(data, beautifulsoup=None, makeelemen... | ent is None:
parent.text = (parent.text or '') + text
else:
element.tail = (element.tail or '') + text
# copied from ET's ElementSoup
t | ry:
from html.entities import name2codepoint # Python 3
name2codepoint
except ImportError:
from htmlentitydefs import name2codepoint
import re
handle_entities = re.compile("&(\w+);").sub
def unescape(string):
if not string:
return ''
# work around oddities in BeautifulSoup's entity handl... |
idmillington/layout | layout/datatypes/parse_dimensions.py | Python | mit | 3,882 | 0.002061 | """
This module is designed for parsing dimensions in text form and
turning them into sizes in printer's points (i.e. 72 per inch).
"""
import re
__all__ = ['DimensionError', 'parse_dimension', 'parse_dimensions']
class DimensionError(Exception): pass
def parse_dimension(text):
"""
Parses the given text into... | e: units += 1
# Work out what to do with empty units
if units == 1 and pairs[-1][1]:
# We | need to infer the units
empty_unit = _unit_lookup[pairs[-1][1]]
else:
empty_unit = 1
# Compile and return the result
result = []
for value, unit in pairs:
if unit: result.append(value * _unit_lookup[unit])
else: result.append(value * empty_unit)
return tuple(result)
... |
rboman/progs | sandbox/filemgr/pdfmanager.py | Python | apache-2.0 | 4,480 | 0.001563 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import os.path
import msvcrt
import win32clipboard
import win32con
import re
def readPdfInfo(file):
import pyPdf
# print file
f = open(file, 'rb')
try:
input = pyPdf.PdfFileReader(f)
print('"%s" has %d pages' % (file... | if ok == 'y':
try:
print('renaming "%s"' % file)
print(' to "%s"' % newfile)
os.rename(file, newfile)
except:
print("rename FAILED!")
def help():
print("\n%s [title|ca... | ltiple_replace(text, adict):
rx = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
return rx.sub(one_xlat, text)
def cleanNames():
reps = {'Fe': 'FE', 'Mpu': 'MPU', 'Ct': 'CT',
'Mri': 'MRI', '\'S': '\'s',
'R... |
lucasvo/fabfile-template | fabfile.py | Python | bsd-3-clause | 13,486 | 0.009269 | # Usage: fab <instance> <options> <action>
# e.g. fab devel deploy
# In case of "No settings_XXX present" ImportError, try setting
# "PYTHONPATH" environment variable value to current directory,
# i.e. "PYTHONPATH=. fab ch deploy"
#
# Instances: live (default)
#
# Options:
# * email: se... | ple"
env.dbcreate_password = "example"
env.recipients = [''] # An email summary is sent to all recipients in this list
env.from_email = 'Deployment Robot <robot@example.com>' # The sender field of the email summary, use the following format: Deployment Robot <robot@example.com>
|
# Fill out hosts here if you don't want to pass it as an argument for every deployment
#env.hosts = [
# '',
# ]
# Options
env.use_locales = True # Should we run compilemessages on deploy?
env.backup = True # generate DB backup
env.send_email = False # send notification emails about deployment (It's rec... |
byllyfish/faucet | faucet/watcher_conf.py | Python | apache-2.0 | 2,593 | 0.001543 | """Gauge watcher configuration."""
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2017 The Contributors
#
# Licensed under the Apac... |
dp = None # pylint: disable=invalid-name
prom_client = None
defaults = {
'name': None,
'type': None,
'dps': None,
'interval': 30,
'db': None,
'db_type': 'text',
'file': None,
'influx_db': 'faucet',
# influx database name
'infl... |
# influx username
'influx_pwd': '',
# influx password
'influx_timeout': 10,
# timeout on influx requests
'influx_retries': 3,
# attempts to retry influx request
# prometheus config
'prometheus_port': 9303,
'prometheus_addr': '127.0.0.1',
... |
eaton-lab/toytree | toytree/CanvasSetup.py | Python | bsd-3-clause | 9,455 | 0.002115 | #!/usr/bin/env python
"""
New Drawing class to create new mark and style on axes.
"""
# from copy import deepcopy, copy
from decimal import Decimal
import numpy as np
import toyplot
# from .Admixture import AdmixEdges
# for setting values from iterables
ITERABLE = (list, tuple, np.ndarray)
class GridSetup:
"... | e tip labels fit. This is a bit hackish
# still. The problem is that the 'extents' range of the rendered | text
# is not totally correct. So we add a little buffer here. Should add for
# user to be able to modify this if needed. If not using edge lengths
# th |
urfonline/api | api/applications/views.py | Python | mit | 1,609 | 0.003108 | from urllib.parse import urlparse
from django.conf import settings
from django.core.files.storage import default_storage
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.applications.models import ShowApplicationSettings
from api.shows.models import upload_to_show_cov... | ShowApplicationSettings.get_solo()
if not cfg.applications_open:
return JsonResponse({'success': False, 'message': "Show applications not open."})
if request.method == 'POST':
file = request.FILES['file']
filename = upload_to_show_cover(None, file.name)
default_storage.save(fil... | sonResponse({'success': True, 'filename': filename})
@csrf_exempt
def upload_banner(request):
if not verify_origin(request):
return JsonResponse({'success': False, 'message': "Invalid origin"})
cfg = ShowApplicationSettings.get_solo()
if not cfg.applications_open:
return JsonResponse({'suc... |
xiaoshaozi52/ansible | contrib/inventory/spacewalk.py | Python | gpl-3.0 | 8,569 | 0.012137 | #!/bin/env python
"""
Spacewalk external inventory script
=================================
Ansible has a feature where instead of reading from /etc/ansible/hosts
as a text file, it can query external programs to obtain the list
of hosts, groups the hosts are in, and even variables to assign to each host.
To use thi... | '):
org_groups[group['spacewalk_group_id']] = group['spacewalk_org_id']
except (OSError), e:
print >> sys.stderr, 'Problem executing the command "%s system-groups": %s' % \
(SW_REPORT, str(e))
sys.exit(2)
# List out the known server from Spacewalk
#------------------------------
if options.list:
# t... | for item in spacewalk_report('inventory'):
host_vars[ item['spacewalk_profile_name'] ] = dict( ( key, ( value.split(';') if ';' in value else value) ) for key, value in item.items() )
except (OSError), e:
print >> sys.stderr, 'Problem executing the command "%s inventory": %s' % \
... |
paulocsanz/graphs.c | tsp/unused/tsp.py | Python | agpl-3.0 | 2,205 | 0.002721 | from itertools import combinations
from math import sqrt
from sys import float_info
from time import time
class Graph:
def __init__(self, vertices):
self.vertex_map = {}
self.vertex_list = []
self.vertices = vertices
self.path = []
def distance(self, first, second):
if ... | node]
return graph
def B(start, subset, end, graph, path):
if | subset == set():
return graph.distance(start, end), path + [graph.vertex_list[end]]
else:
min_dist = float_info.max
final_path = path
for el in subset:
dist, _path = B(start, subset.difference({el}), el, graph, path)
dist += graph.distance(el, end)
... |
sqqqrly/pyfly | app/__init__.py | Python | mit | 405 | 0.002469 | #!/usr/bin/ | env python3
import os
import sys
from flask import Flask
from flask_breadcrumbs import Breadcrumbs
from flask_basicauth import BasicAuth
application = Flask(__name__)
application.config['BASIC_AUTH_USERNAME'] = 'admin'
application.config['BASIC_AUTH_PASSWORD'] = 'admin'
basic_auth = BasicAuth(applic | ation)
# Initialize Flask-Breadcrumbs
Breadcrumbs(app=application)
from app import views
|
egancatriona1/python-jumpstart | apps/05_weather_client/final/program.py | Python | mit | 2,255 | 0 | import requests
import bs4
import collections
WeatherReport = collections.namedtuple('WeatherReport',
'cond, temp, scale, loc')
def main():
# t = 1, 7, 'cat', [1,2,3]
# print(t)
# print(t[1])
#
# n1, n2, s, l = t
# print(n1, n2, s, l)
# return
p... | leanup_text(temp)
scale = cleanup_text(scale)
# print(condition, temp, scale, loc)
# return condition, temp, scale, loc
report = WeatherReport(cond=condition, temp=temp, scale=scale, loc=l | oc)
return report
def find_city_and_state_from_location(loc: str):
parts = loc.split('\n')
return parts[0].strip()
def cleanup_text(text: str):
if not text:
return text
text = text.strip()
return text
if __name__ == '__main__':
main()
|
mattvonrocketstein/smash | smashlib/ipy3x/utils/encoding.py | Python | mit | 2,881 | 0.00243 | # coding: utf-8
"""
Utilities for dealing with text encodings
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2012 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part... | ------------------------------------------------------
import sys
import lo | cale
import warnings
# to deal with the possibility of sys.std* not being a stream at all
def get_stream_enc(stream, default=None):
"""Return the given stream's encoding or a default.
There are cases where ``sys.std*`` might not actually be a stream, so
check for the encoding attribute prior to returnin... |
translate/terminator | project/manage.py | Python | gpl-3.0 | 969 | 0.004128 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright 2011, 2013 Leandro Regueiro
#
# This file is part of Terminator.
#
# Terminator 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 ... | eneral Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Terminator. If not, see <http://www.gnu.org/licenses/>.
import os, sys
if __name__ == "__main__":
os.environ.setdefaul | t("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
invisiblek/python-for-android | python3-alpha/python3-src/Lib/test/test_abc.py | Python | apache-2.0 | 8,256 | 0.002907 | # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Unit tests for abc.py."""
import unittest
from test import support
import abc
from inspect import isabstract
class TestABC(unittest.TestCase):
def test_abstractmethod_basics(self):
@abc.abstractmetho... | )
C1.reg | ister(int)
class MyInt(int):
pass
self.assertTrue(issubclass(MyInt, A))
self.assertTrue(issubclass(MyInt, (A,)))
self.assertIsInstance(42, A)
self.assertIsInstance(42, (A,))
def test_all_new_methods_are_called(self):
class A(metaclass=abc.ABCMeta):
... |
tomato42/tlsfuzzer | scripts/test-tls13-ecdsa-support.py | Python | gpl-2.0 | 11,344 | 0.001675 | # Author: Hubert Kario, (c) 2019
# Released under Gnu GPL v2.0, see LICENSE file for details
from __future__ import print_function
import traceback
import sys
import getopt
from itertools import chain, islice
from random import sample
from tlslite.constants import CipherSuite, AlertLevel, AlertDescription, \
... | it = None
run_exclude = set()
expected_failures = {}
last_exp_tmp = None
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, "h:p:e:x:X:n:", ["help"])
for opt, arg in opts:
if opt == '-h':
host = arg
elif opt == '-p':
port = int(arg)
elif opt == ... | run_exclude.add(arg)
elif opt == '-x':
expected_failures[arg] = None
last_exp_tmp = str(arg)
elif opt == '-X':
if not last_exp_tmp:
raise ValueError("-x has to be specified before -X")
expected_failures[last_exp_tmp] = str(arg)
... |
thinkAmi/9784798123028_GAE | chap8/tweet_handler.py | Python | apache-2.0 | 3,592 | 0.004551 | # -*- coding: utf-8 -*-
import webapp2
import os
import random
import copy
import datetime
from google.appengine.ext import db
from twitter.twitter_helper import TwitterHelper
import sentence
import word
class TweetHandler(webapp2.RequestHandler):
def get(self):
# 文章を取得する
s ... | ーブする
TwitterHelper.remove()
debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
app = webapp2.WSGIApplication([
('/cron/tweet', TweetHandler),
('/cron/ | delete', DeleteHandler),
('/cron/refollow', RefollowHandler),
('/cron/unfollow', RemoveHandler),
], debug=debug) |
polortiz4/bme590_assignment02 | tachybradycardia.py | Python | mit | 1,295 | 0.000772 | def bradycardia(hr, lowerthresh):
"""
This module determines when in the ECG data there is bradycardia
:param hr: (ndarray) heart rate- used to determine when
bradycardia occurred in ECG trace
:param lowerthresh: (int or double) lower threshold for determining
bradycardia- user input or defa... | le determines when in the ECG data there is tachycardia
:param hr: (ndarray) heart rate-
used to determine when tachycardia occurred in ECG trace
:param upperthresh: (int or double) upper threshold for determining
tachycardia- user input or default 100 bpm
:return: tachy: (ndarray) 1 for tachycar... | rthresh): # this indicates tachycardia,
# aka the heart is beating too quickly
tachy[i] = 1
return tachy
|
libavg/mtc-geneatd | geneatd/expItem.py | Python | gpl-3.0 | 2,613 | 0.010716 | #geneaTD - A multi-touch tower defense game.
#Copyright (C) 2010-2011 Frederic Kerber, Pascal Lessel, Michael Mauderer
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of th... | de).
g_player: the global player instance.
pos: the initial position.
layer: the layer to put the creature on.
team1: team 1.
team2: team 2.
exp: the exp of the item.
game: the game.
"""
Item.__init__(self, g_player, pos, layer, team1, t... |
def setAppearance(self):
"""
This method sets the appearance of the item.
"""
if (self.exp == 1):
self.node.filltexhref=os.path.join(getMediaDir(__file__, "resources"), "ep.png")
elif (self.exp == 2):
self.node.filltexhref=os.path.join(... |
sergiomb2/subdownloader | setup.py | Python | gpl-3.0 | 3,464 | 0.001155 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019 SubDownloader Developers - See COPYING - GPLv3
import argparse
import gettext
from pathlib import Path
import sys
from setuptools import find_packages, setup
from sphinx.setup_command import BuildDoc
gettext.NullTranslations().install()
import subd... | e='text/markdown',
url=subdownloader.project.WEBSITE_MAIN,
download_url=subdownloader.project.WEBSITE_RELEASES,
project_urls={
'Source Code': subdownloader.project.WEBSITE_MAIN,
'Bug Tracker': subdownloader.project.WEBSITE_ISSUES,
'Translations': subdownloader.project.WEBSITE_TRANSLA... | media',
'Topic :: Utilities',
'Environment :: Console',
'Environment :: X11 Applications :: Qt',
'Environment :: Win32 (MS Windows)',
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU General Public License... |
thrive-refugee/thrive-refugee | donors/admin.py | Python | mit | 2,727 | 0.000367 | from __future__ import absolute_import
import csv
from django.contrib import admin
from django.http import HttpResponse
from .models import Donor, Donation
class DonationInline(admin.TabularInline):
model = Donation
extra = 0
@admin.register(Donor)
class DonorAdmin(admin.ModelAdmin):
inlines = [
... | make_list)
def make_csv(self, request, queryset):
fields = ('name', 'business', 'email', 'phone', 'address', 'last_donation', 'notes')
response = HttpResponse(content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename=donors.csv'
writer = csv.DictWriter(respons... | }
row.update(vars(donor))
writer.writerow(row)
return response
make_csv.short_description = "Create CSV"
actions.append(make_csv)
@admin.register(Donation)
class DonationAdmin(admin.ModelAdmin):
date_hierarchy = 'when'
actions_on_bottom = True
list_display = 'donor'... |
xorpaul/shinken | windows/Tools/Charp_Services/Shinken_Services/install.d/tools/skonf.py | Python | agpl-3.0 | 35,347 | 0.003169 | #!/usr/bin/env python
#
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# David GUENAULT, dguenault@monitoring-fr.org
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | not supported" % (objectype)
sys.exit(2)
else:
result, confignew = cloneobject(config, objectype, directive, filters)
if not result:
print confignew
sys.exit(2)
else:
result, message = writeconfig(confignew, configfi... | print "The objectype %s has been cloned with the new attributes: %s" % (objectype, filter)
elif action == "addobject":
print "Not implemented"
sys.exit(2)
elif action == "delobject":
result, co |
jbalogh/zamboni | apps/users/models.py | Python | bsd-3-clause | 17,994 | 0.000222 | from datetime import datetime
import hashlib
import os
import random
import re
import string
import time
from django import forms, dispatch
from django.conf import settings
from django.contrib.auth.models import User as DjangoUser
from django.core import validators
from django.db import models
from django.template imp... | eld):
def clean(self, value):
if value in validators.EMPTY_VALUES:
raise forms.ValidationError(self.error_messages['required'])
try:
return UserProfile.objects.get(email=value)
except UserProfile.DoesNotExist:
raise forms.Validation | Error(_('No user with that email.'))
def widget_attrs(self, widget):
lazy_reverse = lazy(reverse, str)
return {'class': 'email-autocomplete',
'data-src': lazy_reverse('users.ajax')}
class UserProfile(amo.models.OnChangeMixin, amo.models.ModelBase):
# nickname, firstname, & las... |
miguelpedroso/neuralmind | examples/mnist_lenet2.py | Python | mit | 1,475 | 0.03322 | import gzip
import cPickle
import numpy as np
import theano
import theano.tensor as T
from neuralmi | nd import NeuralNetwork
from layers import HiddenLayer
from layers import ConvolutionLayer
from layers import FlattenLayer
import activations
def load_data(dataset):
print '... loading data'
# Load the dataset
f = gzip.open(dataset, 'rb')
train_set, valid_set, | test_set = cPickle.load(f)
f.close()
def shared_dataset(data_xy, borrow=True):
data_x, data_y = data_xy
shared_x = theano.shared(np.asarray(data_x, dtype=theano.config.floatX), borrow=borrow)
shared_y = theano.shared(np.asarray(data_y, dtype=theano.config.floatX), borrow=borrow)
return shared_x, T.cast(shar... |
kimhc6028/pathnet-pytorch | genotype.py | Python | bsd-3-clause | 1,720 | 0.002907 | import random
import numpy as np
import copy
class Genotype():
def __init__(self, L, M, N):
self.genotype = np.random.randint(0, M, (L,N))
self.L = L
self.M = M
self.N = N
def apply_mutation(self, i, j):
gene = self.genotype[i][j] + random.randint(-2, 2)
if gen... | return genotypes
def return_control(self):
return self.control_fixed
def return_control_genotype(self):
return self.control_fixed.return_genotype()
def sample(self):
return random.sample(self.genotypes, 2)
def overwrite(self, genotypes, fitnesses):
win = genotyp | es[fitnesses.index(max(fitnesses))]
lose = genotypes[fitnesses.index(min(fitnesses))]
genotype = win.return_genotype()
lose.overwrite(genotype)
lose.mutate()
|
libyal/winreg-kb | winregrc/userassist.py | Python | apache-2.0 | 7,938 | 0.007811 | # -*- coding: utf-8 -*-
"""Windows UserAssist information collector."""
import codecs
import logging
from winregrc import data_format
from winregrc import errors
from winregrc import interface
class UserAssistEntry(object):
"""UserAssist entry.
Attributes:
guid (str): GUID.
name (str): name.
value_... | alue.name, 'rot-13')
except UnicodeEncodeError:
characters = []
for character in value.name:
| if ord(character) < 128:
try:
character = codecs.decode(character, 'rot-13')
characters.append(character)
except UnicodeEncodeError:
characters.append(character)
else:
characters.append(character)
value_name = ''.join(... |
rsnakamura/theape | theape/parts/storage/tests/testscreenstorage.py | Python | mit | 1,239 | 0.003228 |
# python standard library
import unittest
# third-party
try:
from mock import patch
except ImportError:
pass
# this package
from theape.parts.storage.screenstorage import ScreenStorage
class TestScreenStorage(unittest.TestCase):
def setUp(self):
self.sys_patch = patch('sys.stdout')
s... | test_write(self):
self.storage.write('cow')
self.stdout.write.assert_called_with('cow')
return
def test_writelines(self):
lines = 'a b c d'.split()
self.storage.writelines(lines)
self.stdout.writelines.assert_called_with(lines)
return
def test_writeline(... | self.stdout.write.assert_called_with(line + '\n') |
sdrogers/ms2ldaviz | ms2ldaviz/basicviz/migrations/0003_auto_20160717_1943.py | Python | mit | 416 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
cla | ss Migration(migrations.Migration):
dependencies = [
('basicviz', '0002_auto_20160717_1939'),
]
operations = [
migrations.AlterField(
model_name='document',
name='name',
field=models.CharField(unique=T | rue, max_length=32),
),
]
|
moreati/pyscard | smartcard/Examples/wx/apdumanager/setup.py | Python | lgpl-2.1 | 1,413 | 0.002123 | #! /usr/bin/env python
"""
Setup script to build a standalone apdumanager.exe executable on windows
using py2exe. Run: python.exe setup.py py2exe, to build executable file.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
Th... | License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
pyscard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A | PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with pyscard; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from distutils.core im... |
frappe/frappe | frappe/geo/country_info.py | Python | mit | 1,972 | 0.026369 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
# all country info
import os, json, frappe
from frappe.utils.momentjs import get_all_timezones
def get_country_info(country=None):
data = get_all()
data = frappe._dict(data.get(country, {}))
if 'date_format' not in dat... | e:
translated_dict[currency] = currency_name
return translated_dict
def update():
with open(os.path.join(os.path.dirname(__file__), "currency_info.json"), "r") as nformats:
nformats = json.loads(nformats.read())
all_data = get_all()
for country in all_data:
data = all_data[country]
data["number_format"... | ency", "default"),
nformats.get("default"))["display"]
with open(os.path.join(os.path.dirname(__file__), "country_info.json"), "w") as local_info:
local_info.write(json.dumps(all_data, indent=1))
|
nathanhnew/NLNF | blog/views.py | Python | mit | 3,373 | 0.031426 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
fro... | published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
r | edirect_field_name = 'blog/post_list.html'
form_class = PostForm
model = Post
def get_context_data(self,**kwargs):
c = super(CreatePostView, self).get_context_data(**kwargs)
user = self.request.user
return c
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.title = form.... |
City-of-Bloomington/ckanext-cob | setup.py | Python | agpl-3.0 | 3,040 | 0.001316 | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.md'), encoding='utf-8') as ... | ject is
# simple. Or you can use find_packages().
| packages=find_packages(),
# List run-time dependencies here. These will be installed by pip when your
# project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files
ins... |
iceman1001/proxmark3 | client/pm3_eml2mfd.py | Python | gpl-2.0 | 661 | 0.003026 | #!/usr/bin/python
'''
# Andrei Costin <zveriu@gmail.com>, 2011
# pm3_eml2mfd.py
# C | onverts PM3 Mifare Classic emulator EML text file to MFD binary dump file
'''
from __future__ import with_statement
import sys
import binascii
def main(argv):
argc = len(argv)
if argc < 3:
print 'Usage:', argv[0], 'input.eml output.mfd'
sys.exit(1)
with file(argv[1], "r") as file_inp, fil... | data = binascii.unhexlify(line)
file_out.write(data)
if __name__ == '__main__':
main(sys.argv)
|
dongjoon-hyun/tensorflow | tensorflow/contrib/eager/python/examples/l2hmc/neural_nets.py | Python | apache-2.0 | 3,023 | 0.001654 | # 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 required by applica... | er(h)) * tf.exp(
self.coeff_transformation))
return scale, translation, transformation
def _custom_dense(units, factor=1.):
"""Custom dense layer with specified weight initialization."""
return tf.keras.layers.Dense(
units=units,
us | e_bias=True,
kernel_initializer=tf.contrib.layers.variance_scaling_initializer(
factor=factor * 2., mode='FAN_IN', uniform=False),
bias_initializer=tf.constant_initializer(0., dtype=tf.float32))
|
concentricsky/badgr-server | apps/externaltools/v1_api_urls.py | Python | agpl-3.0 | 344 | 0.005814 | # encoding: utf-8
from django.conf.urls import url
from externaltools.api import ExternalToolList, ExternalToolLaunch
urlpatterns = | [
url(r'^$', ExternalToolList.as_view(), name='v1_api_ex | ternaltools_list'),
url(r'^launch/(?P<slug>[^/]+)/(?P<launchpoint>[^/]+)$', ExternalToolLaunch.as_view(), name='v1_api_externaltools_launch'),
] |
JordanMilne/Redhawk | redhawk/common/writers/dot_writer.py | Python | bsd-2-clause | 3,490 | 0.02149 | #!/usr/bin/env python
import redhawk.common.node as N
import redhawk.common.types as T
import redhawk.utils.util as U
from . import writer
import itertools
import pygraphviz
def WriteToDot(tree):
s = DotWriter()
return s.WriteTree(tree)
def WriteToImage(tree, fmt='png', filename=None):
s = DotWriter()
s.Ad... |
fontcolor = "blue"
else:
color = "gray"
fontcolor = "black"
return self.__CreateGraphNode(label = ", ".join(label)
,shape = "box"
,color = color
,fontcolor = fontcolor
... | ,fontsize = "10")
def __CreateEmptyGraphNode(self):
""" Create an Empty Node (with style), and return its index."""
return self.__CreateGraphNode(shape='circle',
style='filled',
label="",
height... |
zbarge/zeex | zeex/ext/ftp/ftpreply.py | Python | mit | 6,888 | 0.005807 | ############################################################################
##
## Copyright (C) 2014 Moritz Warning <moritzwarning@web.de>.
## Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
## Contact: Nokia Corporation (qt-info@nokia.com)
##
## This file is part of the examp... | cellspacing="0" width="90%%">\n'
'<tr><th>Name</th><th>Size</th></tr>\n' | % (QtCore.Qt.escape(base_url), base_path))
parent = u.resolved(QtCore.QUrl(".."))
if parent.isParentOf(u):
content += (u'<tr><td><strong><a href="%s">' % parent.toString()
+ u'Parent directory</a></strong></td><td></td></tr>\n')
i = 0
for item in self.items:
... |
akshmakov/Dolfin-Fijee-Fork | test/memory/test.py | Python | lgpl-3.0 | 6,823 | 0.004104 | """Run Valgrind on all demos."""
# Copyright (C) 2008 Ilmar Wilbers
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesse | r General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN 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 ... | received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# Modified by Anders Logg 2008
# Modified by Dag Lindbo 2008
# Modified by Johannes Ring 2008
# Modified by Johan Hake 2009
#
# First added: 2008-04-08
# Last changed: 2009-05-19
import sys, os... |
mvcsantos/QGIS | python/plugins/processing/algs/qgis/CreateConstantRaster.py | Python | gpl-2.0 | 2,710 | 0.001107 | # -*- coding: utf-8 -*-
"""
***************************************************************************
CreateConstantRaster.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
******************... | FromName(self.OUTPUT)
cellsize = (layer.extent().xMaximum() - layer.extent().xMinimum()) \
/ layer.width()
w = RasterWriter(output.getCompatibleFileName(self),
layer.extent().xMinimum(),
layer.extent().yMinimum(),
l... | layer.extent().yMaximum(),
cellsize,
1,
self.crs,
)
w.matrix[:] = value
w.close()
|
thinkasoft/ProyectoRD-dev | l10n_ve_fiscal_requirements/model/invoice.py | Python | agpl-3.0 | 7,196 | 0.010839 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
###############Credits##########################... | by a Localization
@param uid: Integer value of the user
"""
context = context or {}
res = True
ru_brw = self.pool.get('res.users').browse(cr,uid,uid,context=context)
rc_obj = self.pool.get('res.company')
rc_brw = rc_obj.browse(cr, uid, ru_brw.company_id.id, conte... | er_fiscal:
res = False
return res
_inherit = 'account.invoice'
_columns = {
'nro_ctrl': fields.char('Control Number', size=32, readonly=True, states={'draft':[('readonly',False)]}, help="Number used to manage pre-printed invoices, by law you will need to put here this number to be a... |
garnertb/python-mapnik | mapnik/printing.py | Python | lgpl-2.1 | 46,084 | 0.00141 | # -*- coding: utf-8 -*-
"""Mapnik classes to assist in creating printable maps
basic usage is along the lines of
import mapnik
page = mapnik.printing.PDFPrinter()
m = mapnik.Map(100,100)
mapnik.load_map(m, "my_xml_map_description", True)
m.zoom_all()
page.render_map(m,"my_output_file.pdf")
see the documentation of... | 29000),
"a5": (0.148000, 0.210000),
"a5l": (0.2 | 10000, 0.148000),
"b5": (0.176000, 0.250000),
"b5l": (0.250000, 0.176000),
"c5": (0.162000, 0.229000),
"c5l": (0.229000, 0.162000),
"a6": (0.105000, 0.148000),
"a6l": (0.148000, 0.105000),
"b6": (0.125000, 0.176000),
"b6l": (0.176000, 0.125000),
"c6": (0.114000, 0.162000),
"c6l":... |
Skylion007/popupcad | popupcad/filetypes/__init__.py | Python | mit | 701 | 0 | # -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes.
Email: danaukes<at>seas.harvard.edu.
Please see LICENSE.txt for full license.
"""
from . import constraints
from . import classtools
from . import design
from . import popupcad_file
from . import genericlam | inate
from . import genericshapebase
from . import genericshapes
from . import laminate
from . import layer
from . import layerdef
from . import listwidgetitem
from . import material2
from . import operation
from . import operation2
from . import operationoutput
from . import program
from . import programsettings
from ... | rdata
from . import validators
|
googlefonts/glyphsLib | Lib/glyphsLib/builder/instances.py | Python | apache-2.0 | 15,647 | 0.000511 | # Copyright 2015 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 a... | om
# parameters using | `InstanceDescriptorAsGSInstance` and apply them to the
# instance UFO with `to_ufo_custom_params`.
# NOTE: customParameters are not a dict! One key can have several values
params = []
for p in instance.customParameters:
if p.name in (
"familyName",
"postscriptFontName",
... |
tomjelinek/pcs | pcs_test/tier0/lib/test_env_cib.py | Python | gpl-2.0 | 14,926 | 0.000134 | from functools import partial
from unittest import (
TestCase,
mock,
)
from lxml import etree
from pcs.common.reports import codes as report_codes
from pcs.common.tools import Version
from pcs.lib.env import LibraryEnvironment
from pcs_test.tools import fixture
from pcs_test.tools.assertions import assert_xm... | tch_mixin(
partial(mock.patch.object, LibraryEnvironment)
)
class ManageCibAssertionMixin:
def assert_raises_cib_error(self, callable_obj, message):
with self.assertRaises(AssertionError) as context_manager:
callable_obj()
self.assertEqual(str(context_manager.exception), messag... | )
def assert_raises_cib_already_loaded(self, callable_obj):
self.assert_raises_cib_error(
callable_obj, "CIB has already been loaded"
)
def assert_raises_cib_loaded_cannot_custom(self, callable_obj):
self.assert_raises_cib_error(
callable_obj, "CIB has been load... |
i-newton/AlmaNeuro | alma/util/vec_util.py | Python | apache-2.0 | 1,766 | 0 | import random
from alma.common import exception
def vector_scalar_mult(vec1, vec2):
if len(vec1) != len(ve | c2):
raise exception.SizeMustBeEqual(size1=len(vec1),
size2= | len(vec2))
m = 0
for v1, v2 in zip(vec1, vec2):
m += v1 * v2
return m
def vector_sum(vec1, vec2):
if len(vec1) != len(vec2):
raise exception.SizeMustBeEqual(size1=len(vec1),
size2=len(vec2))
result = []
for v1, v2 in zip(vec1, vec2):
... |
gfyoung/pandas | pandas/tests/indexing/test_categorical.py | Python | bsd-3-clause | 19,173 | 0.000991 | import re
import numpy as np
import pytest
from pandas.core.dtypes.common import is_categorical_dtype
import pandas as pd
from pandas import (
Categorical,
CategoricalIndex,
DataFrame,
Index,
Interval,
Series,
Timedelta,
Timestamp,
)
import pandas._testing as tm
from pandas.api.types ... | s=[0, 25, 50, 75, 100])
expected = Series([11, Interval(0, 25)], index=["value", "D"], name=10)
result = df.iloc[10]
tm.a | ssert_series_equal(result, expected)
expected = DataFrame(
{"value": np.arange(11, 21).astype("int64")},
index=np.arange(10, 20).astype("int64"),
)
expected["D"] = pd.cut(expected.value, bins=[0, 25, 50, 75, 100])
result = df.iloc[10:20]
tm.assert_frame_e... |
facebookexperimental/eden | eden/hg-server/edenscm/hgext/morestatus.py | Python | gpl-2.0 | 7,991 | 0.000626 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
"""make status give a bit more context
This extension will wrap the status command to make it show more context about
the state of the repo
"""
import... | stspredicate("merge/state"), None),
# If there were no conflicts, you may still be in an interrupted update
# state. Ideally, we should expand this update state to include the merge
# updates mentioned above, so there's a way to "continue" and | finish the
# update.
("update", fileexistspredicate("updatestate"), updatemsg),
)
def extsetup(ui):
if ui.configbool("morestatus", "show") and not ui.plain():
wrapcommand(commands.table, "status", statuscmd)
# Write down `hg update` args to show the continue command in
# interrupte... |
FeiZhan/Algo-Collection | answers/leetcode/Excel Sheet Column Number/Excel Sheet Column Number.py | Python | mit | 255 | 0 | class Solution(object):
def titleToNumber(self, s):
| """
:type s: str
:rtype: int
"""
number = 0
for i in range(len(s)):
number = number * 26 + ord(s[i]) - ord('A') + 1
| return number
|
playpauseandstop/rororo | examples/petstore/src/petstore/views.py | Python | bsd-3-clause | 1,841 | 0 | import logging
from aiohttp import web
from rororo import openapi_context, OperationTableDef
from rororo.openapi import get_validated_data, get_validated_parameters
from .data import NewPet
from .shortcuts import get_pet_or_404
logger = logging.getLogger(__name__)
# ``OperationTableDef`` is analogue of ``web.Rout... | ons.register("addPet")
async def create_pet(request: web.Request) -> web.Response:
data = get_validated_data(request)
new_pet = NewPet(name=data["name"], tag=data.get("tag"))
pet = new_pet.to_pet(len(request.app["pets"]) + 1)
request.app["pets"].append(pet)
return web.json_response(pet.to_dict())
... | or_404(request.app["pets"], pet_id)
request.app["pets"] = [item for item in request.app["pets"] if item != pet]
return web.json_response(status=204)
@operations.register("findPets")
async def list_pets(request: web.Request) -> web.Response:
with openapi_context(request) as context:
limit = context... |
guymakam/Kodi-Israel | plugin.video.israelive/resources/lib/livestreamer/session.py | Python | gpl-2.0 | 12,833 | 0.000234 | import imp
import pkgutil
import re
import sys
import traceback
from . import plugins, __version__
from .compat import urlparse, is_win32
from .exceptions import NoPluginError, PluginError
from .logger import Logger
from .options import Options
from .plugin import api
def print_small_exception(start_after):
type... | y segments from the end
to start live streams on, default: ``3``
hls-segment-attempts (int) How many attempts should be done
to download each HLS segment, default: ``3``
hls-segment-threads (int) The size of the thread pool used
... | segment connect and read
timeout, default: ``10.0``
hls-timeout (float) Timeout for reading data from
HLS streams, default: ``60.0``
http-proxy (str) Specify a HTTP proxy to use for
... |
legoktm/pythonwikibot | scripts/welcome.py | Python | mit | 3,203 | 0.038089 | #!usr/bin/python
import wiki
from wiki import userlib
import re, time, sys
reload(sys)
sys.setdefaultencoding('utf-8')
logs = {
'en':None,
'commons': 'Project:Welcome log',
}
templates = {
'en':'{{subst:welcome}} ~~~~',
'commons': '{{subst:welcome}} ~~~~',
}
logupmess = {
'en':None,
'commons': 'Bot: Updating log... | i.getURL(url)
rec = '\<a href="/w/index\.php\?title=User:(.*?)&action=edit&redlink=1"'
list = re.findall(rec, text)
userlist = []
for i in list:
userlist.append(userlib.User(wiki.Page('User:'+i)))
logpost = ''
for user in userlist:
logpost += self.doUser(user)
time.sleep(2)
self... | .quitafterrun:
print 'Sleeping %s' %self.waittime
time.sleep(self.waittime)
bot = WelcomeBot()
bot.run()
else:
sys.exit()
def doUser(self, user):
try:
usereditcount = user.editcount()
except ValueError,e:
return ''
if usereditcount < self.editcount:
print '%s doesn\'t have ... |
T-002/pycast | bin/helper/performance-profiling.py | Python | mit | 1,422 | 0.014768 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Copyright (c) 2012 Christian Schwarz
#
#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,
#distribute, sublicense, and/or sell copies of the Software, and to
#permit persons to whom the Software is furnished ... | tial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
#LIABLE FOR ANY CLAIM, DAMA... |
pradyunsg/pip | tests/unit/test_utils_subprocess.py | Python | mit | 13,355 | 0.000674 | import locale
import sys
from logging import DEBUG, ERROR, INFO, WARNING
from typing import List, Optional, Tuple, Type
import pytest
from pip._internal.cli.spinners import SpinnerInterface
from pip._internal.exceptions import InstallationSubprocessError
from pip._internal.utils.logging import VERBOSE
from pip._inter... | e:
self.spin_count += 1
def finish(self, final_status: str) -> None:
self.final_status = final_status
class TestCallSubprocess:
"""
Test call_subprocess().
"""
def check_result(
self,
capfd: pytest.CaptureFixture[str],
caplog: pytest.LogCaptureFixture,
... | ple[Optional[List[str]], List[Tuple[str, int, str]]],
expected_spinner: Tuple[int, Optional[str]],
) -> None:
"""
Check the result of calling call_subprocess().
:param log_level: the logging level that caplog was set to.
:param spinner: the FakeSpinner object passed to call_... |
mikeolteanu/livepythonconsole-app-engine | boilerplate/external/praw/__init__.py | Python | lgpl-3.0 | 81,183 | 0.000037 | # This file is part of PRAW.
#
# PRAW 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.
#
# PRAW is distributed in the hope that it will ... | oderated/',
'unread': 'message/unread/',
'unread_message': 'api/unread_message/',
'unsave': 'api/unsave/',
'upload_image': 'api/upload_sr_img',
| 'user': 'user/%s/',
'user_about': 'user/%s/about/',
'username_available': 'api/username_available/',
'vote': 'api/vote/',
'wiki_edit': 'api/wiki/edit/',
'wiki_page': ... |
omiltoro/softbrew | OMRS/views.py | Python | apache-2.0 | 9,545 | 0.00901 | from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from django.template import RequestContext,loader,Context
from django.views.generic import ListView
from django.core.context_processors import csrf
from django.contrib.auth import authentic... | tell the template registration was successful.
registered = True
#on successful registration move to the login page
return H | ttpResponseRedirect('/login')
# Invalid form or forms - mistakes or something else?
# Print problems to the terminal.
# They'll also be shown to the user.
else:
print user_form.errors, profile_form.errors
# Not a HTTP POST, so we render our form using two ModelForm inst... |
numericalalgorithmsgroup/pybobyqa | pybobyqa/tests/test_hessian.py | Python | gpl-3.0 | 7,948 | 0.003649 | """
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOU... | estMultBad(unittest.TestCase):
def runTest(self):
n = 5
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = | Hessian(n, vals=H)
# When testing for assertion errors, need lambda to stop assertion from actually happening
self.assertRaises(AssertionError, lambda: hess * 1.0)
self.assertRaises(AssertionError, lambda: hess * None)
self.assertRaises(AssertionError, lambda: hess * [float(i) for i in r... |
ravibhure/ansible | lib/ansible/modules/monitoring/grafana_dashboard.py | Python | gpl-3.0 | 11,537 | 0.002948 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017, Thierry Sallé (@tsalle)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'commu... | llé (@tsalle)"
version_added: "2.5"
short_descr | iption: Manage grafana dashboards
description:
- Create, update, delete, export grafana dashboards via API
options:
grafana_url:
required: true
description:
- Grafana url
grafana_user:
required: false
default: admin
description:
- Grafana API user
grafana_password:
required: ... |
USGSDenverPychron/pychron | pychron/pipeline/nodes/filter.py | Python | apache-2.0 | 11,866 | 0.000758 | # ===============================================================================
# Copyright 2015 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... | (PipelineFilter, self).__init__(*args, **kw)
if txt:
| self.parse_string(txt)
def generate_evaluate_func(self):
def func(edict):
attr = self.attribute
comp = self.comparator
crit = self.criterion
# val = self._get_value(item, attr)
# edict = {attr: val}
attr = attr.replace(" ",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.