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 |
|---|---|---|---|---|---|---|---|---|
rgs1/zk_shell | zk_shell/tests/test_watcher.py | Python | apache-2.0 | 633 | 0 | # -*- coding: utf-8 -*-
""" watcher test cases """
from .shell_test_case import ShellTestCase
from zk_shell.watcher import ChildWatcher
class WatcherTestC | ase(ShellTestCase):
""" test watcher """
def test_add_update(self):
watcher = ChildWatcher(self.client, print_func=self.shell.show_output)
path = "%s/watch" % self.tests_path
self.shell.onecmd("create %s ''" % path)
watcher.add(path, | True)
# update() calls remove() as well, if the path exists.
watcher.update(path)
expected = "\n/tests/watch:\n\n"
self.assertEquals(expected, self.output.getvalue())
|
citiufpe/citi-webplate | project_name/settings/test.py | Python | mit | 360 | 0 | from .base import *
DEBUG = True
db_url = 'sqlite:///{}'.format(os.path.join(BASE_DIR, 'test.sqlite3'))
def | ault_db = dj_database_url.config(default=db_url, conn_max_age=None)
DATABASES['default'].update(default_db)
PASSWORD_HASHE | RS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
|
yprez/django-useful | test_project/test_project_py2/settings.py | Python | isc | 1,842 | 0.001086 | # Django settings for test_project project.
DEBUG = True
TEMPLAT | E_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGER | S = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
}
TIME_ZONE = 'Etc/UTC'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 't^4dt#fkxftpborp@%lg*#h2wj%vizl)#pkkt$&0f7b87rbu6y'
TEMPLATE_LOADERS = (
'django.temp... |
ygol/odoo | addons/stock/tests/test_product.py | Python | agpl-3.0 | 4,949 | 0.001819 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Author: Leonardo Pistone
# Copyright 2015 Camptocamp SA
from odoo.addons.stock.tests.common2 import TestStockCommon
from odoo.tests.common import Form
class TestVirtualAvailable(TestStockCommon):
def setUp(self)... | gn()
self.picking_out_2.action_assign()
self.assertAlmostEqual(32.0, self.product_3.virtual_available)
def test_with_owner(self):
prod_context = self.product_3.with_context(owner_id=self.user_stock_user.partner_id.id)
self.assertAlmostEqual(10.0, prod_context.virtual_available)
... | on_assign()
self.assertAlmostEqual(5.0, prod_context.virtual_available)
def test_free_quantity(self):
""" Test the value of product.free_qty. Free_qty = qty_on_hand - qty_reserved"""
self.assertAlmostEqual(40.0, self.product_3.free_qty)
self.picking_out.action_confirm()
self... |
abhikeshav/ydk-py | core/samples/bgp_netconf.py | Python | apache-2.0 | 4,063 | 0.002461 | #!/usr/bin/env python
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apac... | .get_config(session, Datastore.candidate, multi_filter)
multi_payload_actual = codec.encode(codec_provider, multi_entity_read)
assert multi_payload_expected == m | ulti_payload_actual
def init_logging():
import logging
logger = logging.getLogger("ydk")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setForm... |
biocyberman/bcbio-nextgen | bcbio/ngsalign/novoalign.py | Python | mit | 6,281 | 0.003184 | """Next-gen sequencing alignment with Novoalign: http://www.novocraft.com
For BAM input handling this requires:
novoalign (with license for multicore)
samtools
"""
import os
import subprocess
from bcbio import bam, utils
from bcbio.ngsalign import alignprep, postalign
from bcbio.pipeline import config_utils
from ... | config_utils.get_program("novoalign", data["config"])
resources = config_utils.get_resources("novoalign", data["config"])
num_cores = data["config"]["algorithm"].get("num_cores", 1)
max_mem = resources.get("memory", "1G")
extra_novo_args = " ".join(_novoalign_args_from_config(data["config"]))
rg_inf... | l_file is None or not utils.file_exists(final_file)):
with tx_tmpdir(data) as work_dir:
with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file):
tx_out_prefix = os.path.splitext(tx_out_file)[0]
cmd = ("unset JAVA_HOME && "
... |
bruecksen/isimip | isi_mip/pages/migrations/0013_formpage_button_name.py | Python | mit | 500 | 0.002 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-25 15:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0012_auto_20160519_1740'),
]
operations = [
migrations.AddField(
... | field=models.CharField(default='Subm | it', max_length=500, verbose_name='Button name'),
),
]
|
oxagast/hashnet | stratum-mining-proxy/mining_libs/stratum_listener.py | Python | gpl-2.0 | 7,466 | 0.008438 | import time
import binascii
import struct
from twisted.internet import defer
from stratum.services import GenericService
from stratum.pubsub import Pubsub, Subscription
from stratum.custom_exceptions import ServiceException, RemoteServiceException
from jobs import JobRegistry
import stratum.logger
log = stratum.log... | extranonce2, ntime, nonce, *args):
if self._f.client == None or not self._f.client.connected:
raise SubmitException("Upstream not connected")
session = self.connection_ref().get_session()
tail = session.get('tail')
if tail == None:
raise SubmitException("Connect... | ld self._f.rpc('mining.submit', [worker_name, job_id, tail+extranonce2, ntime, nonce]))
except RemoteServiceException as exc:
response_time = (time.time() - start) * 1000
log.info("[%dms] Share from '%s' REJECTED: %s" % (response_time, worker_name, str(exc)))
raise SubmitExce... |
gkaramanolakis/adsm | adsm/feature_extraction.py | Python | gpl-3.0 | 3,139 | 0.021982 | import librosa
import numpy as np
import help_functions
def extract_mfccdd(fpath, n_mfcc=13, winsize=0.25, sampling_rate=16000):
'''
Compute MFCCs, first and second derivatives
:param fpath: the file path
:param n_mfcc: the number of MFCC coefficients. Default = 13 coefficients
:param winsize: the ... | osa.feature.delta(mfccs)
deltadeltas = librosa.feature.delta(deltas)
mfccdd = np.concatenate((mfccs, deltas, deltadeltas), axis=1)
return mfccdd
def extract_multiple_features(fpath, n_mfcc=13, sampling_rate=16000):
chroma_feature = librosa.feature.chroma_stft(fpath, sampling_rate) # 12
mfcc_feature... | re.mfcc(fpath, sampling_rate, n_mfcc=n_mfcc) # default = 20
rmse_feature = librosa.feature.rmse(fpath) # 1
spectral_centroid_feature = librosa.feature.spectral_centroid(fpath, sampling_rate) #1
spectral_bandwidth_feature = librosa.feature.spectral_bandwidth(fpath, sampling_rate) #1
#spectral_contrast_fe... |
mjirik/discon | discon/discon_tools.py | Python | mit | 600 | 0.003333 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
from loguru import logger
from pathlib import Path
def check_meta_yaml_for_noarch(fn:Path, text=None):
import re
logger.debug("C | hecking for noarch")
if text is None:
with open(fn, "rt") as fl:
text = fl.read()
mo = re.search(r"\n\s*noarch_python:\s*True", text)
if mo:
logger.info("Detected conda noarch python")
return True
mo = re.search(r"\n\s*noarch:\s*python", text)
if mo:
logg... | lse
|
alfredodeza/potasio | potasio/controllers/root.py | Python | bsd-3-clause | 411 | 0 | from pecan import expose, conf
from potasio.controllers.dashboards import DashboardController
class RootController(object):
@expose(template='index.html')
def index(self | ):
dashboards = conf.dashboards.to_dict()
return dict(
dashboards=dashboards.keys()
)
@expose()
def _lookup(self, name, *remainder):
r | eturn DashboardController(name), remainder
|
dvor85/kmotion | bin/reboot_cam.py | Python | gpl-3.0 | 523 | 0.001912 | #!/usr/bin/env python
import os
import sys
def usage():
print "{0} <feed>".format(os.path.basename(__file__))
if __name__ == '__main__':
kmotion_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(kmotion_dir)
from core.camera_lost import CameraLost
feed = ''
... | .argv[1]
cam_lost = | CameraLost(kmotion_dir, feed)
if cam_lost.reboot_camera():
sys.exit()
else:
usage()
sys.exit(1)
|
nhsb1/PatternTargetFinder | ptf.py | Python | gpl-3.0 | 3,499 | 0.025722 | from argparse import ArgumentParser
from yahoo_finance import Share
import pyperclip
import urllib2
from bs4 import BeautifulSoup
currentrelease = 'Pattern Target Finder 1.2'
#v1.2 - Added get earnings date function
#v1.1 - Get's current delayed price from Yahoo_Finance
# Allowed you to override price -p 123
# Copi... | ve.
def getArgs():
parser = ArgumentParser(description = currentrelease)
parser.add_argument("-t", "--ticker", required=False, dest="ticker", help="t | icker for lookup", metavar="ticker")
parser.add_argument("-p", "--price", required=False, dest="price", help="specify price", metavar="price")
parser.add_argument("-rh", "--high", required=True, dest="high", help="recent high", metavar="high")
parser.add_argument("-rl", "--low", required=True, dest="low", h... |
jdevesa/gists | gists/gists.py | Python | mit | 12,061 | 0 | # Copyright (c) 2012 <Jaume Devesa (jaumedevesa@gmail.com)>
#
# 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, modi... | ted output
print result_formatted
def __add_list_parser(subparsers):
""" Define the subparser to handle the 'list' functionality.
:param subparsers: the subparser entity
"""
# Add the subparser to handle the list of gists
parser_list = subparsers. | add_parser("list", help="list a user's Gists")
parser_list.add_argument("-u", "--user", help=USER_MSG)
group1 = parser_list.add_mutually_exclusive_group()
group1.add_argument("-p", "--private", help="""return the private gists
besides the public ones. Needs authentication""",
... |
chromium/chromium | third_party/tensorflow-text/src/tensorflow_text/python/keras/layers/todense_test.py | Python | bsd-3-clause | 8,393 | 0.002264 | # coding=utf-8
# Copyright 2021 TF.Text 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 ag... | sgd",
loss="mse",
metrics=["accuracy"],
run_eagerly=testing_utils.should_run_ | eagerly())
output = model.predict(input_data)
self.assertAllEqual(output, expected_output)
def SKIP_test_ragged_input_with_padding(self):
input_data = get_input_dataset(
tf.ragged.constant([[[1, 2, 3, 4, 5]], [[2], [3]]]))
expected_output = np.array([[[1., 2., 3., 4., 5.],
... |
rave-engine/rave | tests/support/filesystem.py | Python | bsd-2-clause | 4,963 | 0.006045 | import os
import codecs
from io import StringIO
from pytest import fixture
from rave import filesystem
class DummyProvider:
def __init__(self, files):
self.files = files;
def list(self):
return self.files
def has(self, filename):
return filename in self.list()
def open(self,... | stem.NotAFile(filename)
return DummyFile(self, filename)
def isfile(self, filename):
return self.has(filename) and '.' in filena | me
def isdir(self, filename):
return self.has(filename) and not self.isfile(filename)
class FaultyProvider(DummyProvider):
def __init__(self, files, faulty_files, err=filesystem.FileNotFound):
super().__init__(files)
self.faulty_files = faulty_files
self.error_class = err
... |
reddec/pika | pika/adapters/select_connection.py | Python | bsd-3-clause | 21,137 | 0.000378 | """A connection adapter that tries to use the best polling method for the
platform pika is running on.
"""
import os
import logging
import socket
import select
import errno
import time
from operator import itemgetter
from collections import defaultdict
import threading
import pika.compat
from pika.compat import dictk... | ""
try:
read_sock, write_sock = socket.socketpair()
except AttributeError:
LOGGER.debug("Using custom socketpair for interrupt")
read_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
read_sock.bind(('localhost', 0))
write_sock = socket.... | g(0)
write_sock.setblocking(0)
return read_sock, write_sock
def read_interrupt(self, interrupt_sock,
events, write_only): # pylint: disable=W0613
""" Read the interrupt byte(s). We ignore the event mask and write_only
flag as we can ony get here if there's da... |
spellrun/Neural-Photo-Editor | gan/sample_ian.py | Python | mit | 5,521 | 0.011411 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from collections import OrderedDict
import imp
import time
import logging
import itertools
import os
import numpy as np
from path import Path
import theano
import theano.tensor as T
import lasagne
from fuel.datasets import CelebA
from gan.util import (
... | tanh(tfuncs['sample'](Z[7*i:7*(i+1),:]))),axis=0)
for i in range(3) ], axis=0)
# Get all images
images = np.append(samples, interp, axis=0)
# Plot images
pics_dir = os.path.join(res_dir, "pics")
if not os.path.isdir(pics_dir):
os.makedirs(pics_dir)
img_fna... | =='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('config_path', type=Path, help='config .py file')
parser.add_argument('-w', "--weights-file", help='weights file')
args = parser.parse_args()
main(args)
|
pmghalvorsen/gramps_branch | gramps/plugins/gramplet/repositorydetails.py | Python | gpl-2.0 | 5,196 | 0.002694 | # Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011 Nick Hall
#
# 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 late... | .join(lines))
def display_url(self, repo, url_type):
"""
Display an url of the given url type.
"""
for url in repo.get_url_list():
if url.get_type() == url_type:
self.add_row(str(url_type), url.get_path())
def display_empty(self):
"""
... | y an empty row to separate groupd of entries.
"""
label = Gtk.Label(label='')
label.modify_font(Pango.FontDescription('sans 4'))
label.show()
rows = self.table.get_property('n-rows')
rows += 1
self.table.resize(rows, 2)
self.table.attach(label, 0, 1, rows,... |
archetipo/server-tools | users_ldap_groups/users_ldap_groups_operators.py | Python | agpl-3.0 | 2,298 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2012 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | uals(LDAP | Operator):
def check_value(self,
ldap_entry,
attribute, value,
ldap_config,
company,
logger):
return (attribute in ldap_entry[1] and
unicode(value) == unicode(ldap_entry[1][attribute]))
clas... |
aronsky/home-assistant | tests/components/modern_forms/test_init.py | Python | apache-2.0 | 1,806 | 0.000554 | """Tests for the Modern Forms integration."""
from unittest.mock import MagicMock, patch
from aiomodernforms import ModernFormsConnectionError
from homeassistant.components.modern_forms.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from home... | an_entry = entity_registry.async_get("fan.modernformsfan_fan")
assert fan_entry
light_entry = entity_registry.async_get("light.modernformsfan_lig | ht")
assert light_entry is None
|
mhvk/astropy | astropy/cosmology/tests/test_utils.py | Python | bsd-3-clause | 2,328 | 0.001289 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from math import inf
import pytest
import numpy as np
from astropy.cosmology.utils import inf_like, vectorize_if_needed, vectorize_redshift_method
from astropy.utils.exceptions import AstropyDeprecationWarning
def test_vectorize_redshift_method():
... | [4, 9])
@pytest.mark.parametrize("arr, expected",
[(0.0, inf), # float scalar
(1, inf), # integer scalar should give float o | utput
([0.0, 1.0, 2.0, 3.0], (inf, inf, inf, inf)),
([0, 1, 2, 3], (inf, inf, inf, inf)), # integer list
])
def test_inf_like(arr, expected):
"""
Test :func:`astropy.cosmology.utils.inf_like`.
All inputs should give a float output... |
felixbuenemann/sentry | src/sentry/rules/actions/notify_event.py | Python | bsd-3-clause | 1,345 | 0.000743 | """
sentry.rules.actions.notify_event
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from sentry.plugins import plugins
from sentry.rules.actions.base import EventAct... | ort NotificationPlugin
results = []
for plugin in plugins.for_project(self.project, version=1):
if not isinstance(plugin, NotificationPlugin):
continue
results.append(plugin)
for plugin in plugins.for_project(self.project, version=2):
for | notifier in (safe_execute(plugin.get_notifiers) or ()):
results.append(notifier)
return results
def after(self, event, state):
group = event.group
for plugin in self.get_plugins():
if not safe_execute(plugin.should_notify, group=group, event=event):
... |
CCS-Tech/duck-blocks | db_create.py | Python | gpl-3.0 | 475 | 0.004211 | from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database_repos | itory')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, | api.version(SQLALCHEMY_MIGRATE_REPO)) |
sujitbehera27/MyRoboticsProjects-Arduino | src/resource/Python/examples/Adafruit16CServoDriver.py | Python | apache-2.0 | 529 | 0.009452 | # The Adafruit16CServoDriver API is supported through Jython
servo1 = Runtime.createAndStart("servo1", "Servo")
pwm = Runtime.createAndStart("pwm", "Adafruit16CServoDriver")
pwm.connect("COM12")
# attach servo1 to pin 0 on the servo driver
pwm.attach(servo1, 0)
servo1.broadcastState()
servo1.moveTo(0)
sleep(1... | ervo1.moveTo(90)
sle | ep(1)
servo1.moveTo(180)
sleep(1)
servo1.moveTo(90)
sleep(1)
servo1.moveTo(0)
sleep(1)
servo1.moveTo(90)
sleep(1)
servo1.moveTo(180)
sleep(1)
servo1.moveTo(90)
sleep(1)
servo1.moveTo(0)
|
a-tal/pyweet | pyweet/settings.py | Python | bsd-3-clause | 259 | 0 | """Pywe | et runtime settings."""
import os
class Settings(object):
"""Basic settings object for pyweet."""
API = "rgIYSFIeGBxVXOPy22QzA"
API_SECRET = "VX7ohOHpJm1mXlGX6XS08JcT4Vp8j83QhRNo | 1SVRevb"
AUTH_FILE = os.path.expanduser("~/.pyweet")
|
hholzgra/maposmatic | www/maposmatic/views.py | Python | agpl-3.0 | 26,128 | 0.004785 | # coding: utf-8
# maposmatic, the web front-end of the MapOSMatic city map generation system
# Copyright (C) 2009 David Decotigny
# Copyright (C) 2009 Frédéric Lehobey
# Copyright (C) 2009 Pierre Mauduit
# Copyright (C) 2009 David Mentré
# Copyright (C) 2009 Maxime Petazzoni
# Copyright (C) 2009 Thomas Petazzoni... | form.cleaned_data.get('paper_width_mm')
job.paper_height_mm = form.cleaned_data.get('paper_height_mm')
job.status = 0 # Submitted
if www.settings.SUBMITTER_IP_LIFETIME != 0:
job.submitterip = request.META['REMOTE_ADDR']
else:
job.submitter... | anguage')
job.index_queue_at_submission = (models.MapRenderingJob.objects
.queue_size())
job.nonce = helpers.generate_nonce(models.MapRenderingJob.NONCE_SIZE)
job.save()
files = request.FILES.getlist('uploadfile')
... |
tedye/leetcode | Python/leetcode.156.binary-tree-upside-down.py | Python | mit | 822 | 0.001217 | # Definition for a binary tree node.
# class TreeNode(object):
# def __ini | t__(self, | x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
leftbone = [root]
rightbone = [... |
sjl767/woo | py/pre/toys.py | Python | gpl-2.0 | 3,537 | 0.035906 | from minieigen import *
from woo.dem import *
import woo.core, woo.models
from math import *
import numpy
class PourFeliciter(woo.core.Preprocessor,woo.pyderived.PyWooObject):
'''Showcase for custom packing predicates, and importing surfaces from STL.'''
_classTraits=None
_PAT=woo.pyderived.PyAttrTrait # ... | [In2_Truss_ElastMat()]),
woo.core.PyRunner(self.plotEvery,'S.plot.ad | dData(i=S.step,t=S.time,total=S.energy.total(),relErr=(S.energy.relErr() if S.step>1000 else 0),**S.energy)'),
]
S.lab.dynDt.maxRelInc=1e-6
S.trackEnergy=True
S.plot.plots={'i':('total','**S.energy')}
return S
|
Donkyhotay/MoonPy | zope/app/dtmlpage/interfaces.py | Python | gpl-3.0 | 1,715 | 0.000583 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... | erfaces
$Id: interfaces.py 39064 2005-10-11 18:40:10Z philikon $
"""
__docformat__ = 'restructuredtext'
import zope.schema
from zope.interface import Interface, Attribute
from zope.app.i18n import ZopeMessageFactory as _
class IDTMLPage(Interface):
"""DTML Pages are a persistent implementation of DTML."""
d... | """Get the source of the page template."""
source = zope.schema.Text(
title=_(u"Source"),
description=_(u"""The source of the dtml page."""),
required=True)
class IRenderDTMLPage(Interface):
content_type = Attribute('Content type of generated output')
def render(request, *args,... |
spillai/procgraph | src/procgraph_pil/pil_operations.py | Python | lgpl-3.0 | 1,746 | 0.006873 | import numpy as np
from procgr | aph import COMPULSORY
from procgraph import simple_block
from .pil_conversions import Image_from_array
__all__ = ['resize']
@simple_block
def pil_zoom(value, factor=COMPULSORY):
""" Zooms by a given factor """
# TODO: RGBA?
shape = value.shape[:2]
shape2 = (int(factor * shape[0]), int(factor * shape... | result = np.asarray(image.convert("RGB"))
return result
@simple_block
def resize(value, width=None, height=None):
'''
Resizes an image.
You should pass at least one of ``width`` or ``height``.
:param value: The image to resize.
:type value: image
... |
altair-viz/altair | altair/examples/scatter_with_loess.py | Python | bsd-3-clause | 755 | 0.005298 | """
Scatter Plot with LOESS Lines
-----------------------------
This example shows how to add a trend line to a scatter plot using
the LOESS transform (LOcally Estimated Scatterplot Smoothing).
"""
# category: scatter plots
import altair as alt
import pandas as pd
import numpy as np
|
np.random.seed(1)
source = pd.DataFrame({
'x': np.arange(100),
'A': np.random.randn(100).cumsum(),
'B': np.random.randn(100).cumsum(),
'C': np.random.randn(100).cumsum(),
})
base = alt.Chart(source).mark_circle(opacity=0.5).transform_fold(
fold=['A', 'B', 'C'],
as_=['category', 'y']
).encode... | t.Color('category:N')
)
base + base.transform_loess('x', 'y', groupby=['category']).mark_line(size=4)
|
grengojbo/satchmo | satchmo/apps/satchmo_utils/thumbnail/utils.py | Python | bsd-3-clause | 9,086 | 0.005393 | from django.conf import settings
from django.core.cache import get_cache
from django.db.models.fields.files import ImageField
from livesettings import config_value
from satchmo_utils.thumbnail.text import URLify
#ensure config is loaded
import satchmo_utils.thumbnail.config
import fnmatch
import logging
import os
imp... | Get file content from cache.
If modification time differ return None and delete
data from cache.
"""
cached = image_cache.get(path, default)
if cached is None:
return None
mtime, value = cached
if (not os.path.isfile(path)) or (os.path.getmtime(path) != mtime): # file is ch... | che
# remove thumbnails if exists
base, ext = os.path.splitext(os.path.basename(path))
basedir = os.path.dirname(path)
for file in fnmatch.filter(os.listdir(basedir), _THUMBNAIL_GLOB % (base, ext)):
os.remove(os.path.join(basedir, file))
return None
else:
... |
blindman/nhl-logo-scraper | tests/test_cli.py | Python | mit | 604 | 0.004967 | """Tests for the main nhlscraper CLI module"""
from subprocess import PIPE, getoutput
from unittest import TestCase
from nhl_logo_scraper import __version__ as VERSION
class TestHel | p(TestCase):
def test_returns_usage_information(self):
output = getoutput("nhlscraper -h")
self.assertTrue('Usage:' in output)
output = getoutput("nhlscraper --help")
self.assertTrue('Usage:' in output)
class TestVersion(TestCase):
def test_returns_version_information(self):
... | t.strip(), VERSION);
|
tersmitten/ansible | lib/ansible/modules/cloud/azure/azure_rm_functionapp_facts.py | Python | gpl-3.0 | 6,027 | 0.002323 | #!/usr/bin/python
#
# Copyright (c) 2016 Thomas Stringer, <tomstr@microsoft.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | mal
host_name_ssl_states:
| - name: myfunctionapp.azurewebsites.net
ssl_state: Disabled
host_type: Standard
- name: myfunctionapp.scm.azurewebsites.net
ssl_state: Disabled
host_type: Repository
server_farm_id: /subscriptions/.../resourceGroups/ansible-rg/providers/Microsoft.Web... |
espressopp/espressopp | src/Tensor.py | Python | gpl-3.0 | 3,339 | 0.000299 | # Copyright (C) 2012,2013
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of the G... | f x, y and z are
specified."""
if len(args) == 1:
arg0 = args[0]
if isinstance(arg0, Tensor):
return arg0
elif hasattr(arg0, '__iter__') and len(arg0) == 3:
return Tensor(*args)
elif len(args) == 3:
return Tensor(*args) |
raise TypeError("Specify x, y and z.")
def toTensor(*args):
"""Try to convert the arguments to a Tensor, returns the argument,
if it is already a Tensor."""
if len(args) == 1 and isinstance(args[0], Tensor):
return args[0]
else:
return Tensor(*args)
|
CellModels/tyssue | tests/utils/test_connectivity.py | Python | gpl-2.0 | 2,530 | 0 | import numpy as np
from tyssue import Sheet, Monolayer
from tyssue.generation import three_faces_sheet, extrude
from tyssue.utils import connectivity
from tyssue.config.geometry import bulk_spec
def test_ef_connect():
data, specs = three_faces_sheet()
sheet = Sheet("test", data, specs)
ef_connect = conne... | data, specs = three_faces_sheet()
sheet = Sheet("test", data, specs)
ffc = connectivity.face_face_connectivity(sheet, exclud | e_opposites=False)
expected = np.array([[0, 2, 2], [2, 0, 2], [2, 2, 0]])
np.testing.assert_array_equal(ffc, expected)
ffc = connectivity.face_face_connectivity(sheet, exclude_opposites=True)
expected = np.array([[0, 2, 2], [2, 0, 2], [2, 2, 0]])
np.testing.assert_array_equal(ffc, expected)
mo... |
p4lang/behavioral-model | mininet/1sw_demo.py | Python | apache-2.0 | 3,488 | 0.008601 | #!/usr/bin/env python3
# Copyright 2013-present Barefoot Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | w_addr = ["10 | .0.%d.1" % n for n in range(num_hosts)]
for n in range(num_hosts):
h = net.get('h%d' % (n + 1))
if mode == "l2":
h.setDefaultRoute("dev eth0")
else:
h.setARP(sw_addr[n], sw_mac[n])
h.setDefaultRoute("dev eth0 via %s" % sw_addr[n])
for n in range(num_... |
combatopera/pym2149 | ymtests/__init__.py | Python | gpl-3.0 | 707 | 0.001414 | # Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li | cense as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi | thout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
|
saurabh6790/erpnext | erpnext/patches/v4_0/create_custom_fields_for_india_specific_fields.py | Python | gpl-3.0 | 1,704 | 0.032277 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field_if_values_exist
| def execute():
frappe.reload_doc("stock", "doctype", "purchase_receipt")
frappe.reload_doc("hr", "doctype", "employee")
frappe.reload_doc("Payroll", "doctype", "salary_slip")
india_specific_fields = {
"Purchase Receipt": [{
"label": "Supplier Shipment No",
"fieldname": "challan_no",
| "fieldtype": "Data",
"insert_after": "is_subcontracted"
}, {
"label": "Supplier Shipment Date",
"fieldname": "challan_date",
"fieldtype": "Date",
"insert_after": "is_subcontracted"
}],
"Employee": [{
"label": "PAN Number",
"fieldname": "pan_number",
"fieldtype": "Data",
"insert_after"... |
dstahlke/qitensor | qitensor/experimental/__init__.py | Python | bsd-2-clause | 84 | 0 | from . i | mport cartan_decompose
from . import stabiliz | ers
from . import noncommgraph
|
minlexx/pyevemon | esi_client/models/get_corporations_corporation_id_structures_service.py | Python | gpl-3.0 | 4,135 | 0.001693 | # coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online
OpenAPI spec version: 0.4.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class GetCorporationsCorporationIdStructuresService(object):
... | value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint... | CorporationsCorporationIdStructuresService):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
buchuki/programming_lab | programming_lab/classlist/forms.py | Python | gpl-3.0 | 1,349 | 0.008154 | # This file is part of Virtual Programming Lab.
#
# Virtual Programming Lab 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.
#
# Virtu... | et=forms.CheckboxSelectMultiple) |
def __init__(self, queryset, *args, **kwargs):
super(ApproveRequestForm, self).__init__(*args, **kwargs)
self.fields['requests'].queryset = queryset
|
theflofly/tensorflow | tensorflow/python/saved_model/function_deserialization.py | Python | apache-2.0 | 14,043 | 0.008047 | # 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... | eCoder()
function_spec = _deserialize_function_spec(saved_function.function_spec,
coder)
def restored_function_body(*args, **kwargs):
"""Calls a restored function."""
# This is the format of function.graph.structured_input_signature. At this
# point, the arg... | be called without input
# conversions. This allows one to pick a more specific trace in case there
# was also a more expensive one that supported tensors.
for allow_conversion in [False, True]:
for function_name in saved_function.concrete_functions:
function = concrete_functions[function_name... |
adityahase/frappe | frappe/core/doctype/installed_application/installed_application.py | Python | mit | 278 | 0.007194 | # -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license informat | ion, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class InstalledApp | lication(Document):
pass
|
orione7/Italorione | channels/guardarefilm.py | Python | gpl-3.0 | 11,213 | 0.002409 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# streamondemand.- XBMC Plugin
# Canal para piratestreaming
# http://blog.tvalacarta.info/plugin-xbmc/streamondemand.
# ------------------------------------------------------------
import re
import sys
import urlparse
from core impo... | il="http://xbmc-repo-ackbarr.googlecode.com/svn/trunk/dev/skin.cirrus%20extended%20v2/extras/moviegenres/New%20TV%20Shows.png"),
Item(channel=__channel__,
| title="[COLOR yellow]Cerca Serie TV...[/COLOR]",
action="search",
extra="serie",
thumbnail="http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search")]
return itemlist
def categorias(item):
logger.info("streamondemand.guardarefilm categor... |
b12io/orchestra | orchestra/bots/sanitybot.py | Python | apache-2.0 | 3,750 | 0 | from django.db.models import Max
from django.db.models import Q
from django.utils import timezone
from pydoc import locate
from orchestra.core.errors import SanityBotError
from orchestra.models import Project
from orchestra.models import SanityCheck
from orchestra.models import WorkflowVersion
from orchestra.utils.not... | et(check.check_slug, {})
.get('repetition_seconds'))
now = timezone.now()
seconds_none_or_rep_sec_lt = (max_created_at is None) or (
(seconds is not None) and (
(now - max_created_at).total_seconds() > seconds))
if seconds_none_or_rep_sec_lt:
... | project, sanity_checks, check_configurations)
for sanity_check in sanity_checks:
config = check_configurations.get(sanity_check.check_slug)
if config is None:
raise SanityBotError(
'No configuration for {}'.format(sanity_check.check_slug))
handlers = config.ge... |
Vaan5/piecewisecrf | piecewisecrf/slim/variables_test.py | Python | mit | 16,163 | 0.011075 | # 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 agree... | s.variable('b', [5])
self.assertEquals([a], variables.get_variables(suffix='a'))
self.assertEquals([b], variables.get_variables(suffix='b'))
def testGetVariableWithSingleVar(self):
with self.test_session():
with tf.variable_scope('parent'):
a = variables.variable('child', [5])
sel... | with tf.variable_scope('parent'):
a = variables.variable('child', [5])
with tf.variable_scope('child'):
variables.variable('grandchild1', [7])
variables.variable('grandchild2', [9])
self.assertEquals(a, variables.get_unique_variable('parent/child'))
def testGetVariableThro... |
jrichte43/ProjectEuler | Problem-0081/solutions.py | Python | gpl-3.0 | 949 | 0.007376 |
__problem_title__ = "Path sum: two ways"
__problem_url___ = "https://projecteuler.net/problem=81"
__problem_description__ = "In the 5 by 5 matrix below, the minimal path sum from the top left to | " \
"the bottom right, by , is indicated in bold red and is equal to 2427. " \
"Find the minimal path sum, in (right click and "Save Link/Target " \
"As..."), a 31K text file containing a 80 by 80 matrix, from the top " \
| "left to the bottom right by only moving right and down."
import timeit
class Solution():
@staticmethod
def solution1():
pass
@staticmethod
def time_solutions():
setup = 'from __main__ import Solution'
print('Solution 1:', timeit.timeit('Solution.solution1()', setup=s... |
y-sira/atcoder | ddcc2017-qual/b.py | Python | mit | 79 | 0 | a, b, | c, d = map(int, input().split())
print(a * 1728 + b * 144 + | c * 12 + d)
|
kaarl/pyload | module/plugins/crypter/BitshareComFolder.py | Python | gpl-3.0 | 522 | 0.011494 | # -*- coding: utf-8 -*-
from module.plugins.internal.Dead | Crypter import DeadCrypter
class BitshareComFolder(DeadCrypter):
__name__ = "BitshareComFolder"
__type__ = "crypter"
__version__ = "0.10"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?bitshare\.com/\?d=\w+'
__config__ = [("activated", "bool", "Activated", True)]
__descr... | ahoo.it")]
|
goshow-jp/Kraken | Python/kraken/ui/HAppkit_Editors/editor_widgets/nested_editor.py | Python | bsd-3-clause | 3,053 | 0.005568 | import json
from PySide import QtCore, QtGui
from ..fe import FE
from ..widget_factory import EditorFactory
from ..base_editor import BaseValueEditor
from ..core.value_controller import MemberController
class NestedEditor(BaseValueEditor):
def __init__(self, valueController, parent=None):
super(NestedEd... | ame, widget):
# widget.set | SizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
label = QtGui.QLabel(name, self)
# label.setMaximumWidth(200)
# label.setContentsMargins(0, 5, 0, 0)
# label.setMinimumWidth(60)
# label.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
... |
Nik0l/UTemPro | ML/Clustering.py | Python | mit | 10,761 | 0.008642 | __author__ = 'nb254'
import numpy as np
import pandas as pd
from sklearn import cluster
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
from sklearn.neighbors import kneighbors_graph
import ClusteringPrediction as cp
import ClusteringSaveResults as csr
import DataPreprocessing as dp
... | , affinity_propagation, plot_sample_si | ze, clust['exp'])
if clust['clustering_type'] == 'ward':
# connectivity matrix for structured Ward
connectivity = kneighbors_graph(data, n_neighbors=10, include_self=False)
# make connectivity symmetric
connectivity = 0.5 * (connectivity + connectivity.T)
ward = cluster.Aggl... |
inter-rpm/dns-interface | main.py | Python | gpl-3.0 | 650 | 0.009231 | #!/usr/bin/env python
# coding=utf-8
import sys
from flask import Flask, request, jsonify
import simplejson as json
import | handlers
app = Flask(__name__)
api_list = {
'api/dns': u'get dns',
'api/update': u'update domain information',
}
@app.ro | ute("/", methods = ['GET', 'POST'])
def index():
return jsonify(api_list)
@app.route("/api/dns", methods=['GET', 'POST'])
def dns():
body = request.json
ip = request.remote_addr
data = handlers.DNSHandler(ip, body)
return jsonify(data)
@app.route("/api/update", methods=['GET', 'POST'])
def update(... |
leilihh/nova | nova/scheduler/rpcapi.py | Python | apache-2.0 | 5,246 | 0.000953 | # Copyright 2013, Red Hat, 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 agr... | cctxt = self.client.prepare()
| cctxt.cast(ctxt, 'run_instance', **msg_kwargs)
def prep_resize(self, ctxt, instance, instance_type, image,
request_spec, filter_properties, reservations):
instance_p = jsonutils.to_primitive(instance)
instance_type_p = jsonutils.to_primitive(instance_type)
reservations_p... |
tysonholub/twilio-python | tests/integration/api/v2010/account/test_connect_app.py | Python | mit | 7,437 | 0.003765 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holod | eck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ConnectAppTestCase(IntegrationTestCase):
def test_fetch_request(self):
self.holodeck.mock(Response(500, ''))
with self.assertRaises(TwilioException):
self.client.api.... | .connect_apps(sid="CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()
self.holodeck.assert_has_request(Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ConnectApps/CNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json',
))
def test_fet... |
ULHPC/modules | easybuild/easybuild-easyblocks/easybuild/easyblocks/w/wps.py | Python | mit | 14,921 | 0.003418 | ##
# Copyright 2009-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | self.wrfdir, line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s script: %s", self.compile_script, err)
# libpng dependency check
libpng = get_ | software_root('libpng')
zlib = get_software_root('zlib')
if libpng:
paths = [libpng]
if zlib:
paths.insert(0, zlib)
libpnginc = ' '.join(['-I%s' % os.path.join(path, 'include') for path in paths])
libpnglib = ' '.join(['-L%s' % os.path.join... |
SimbaService/Simba | server/scripts/probe/swift.py | Python | apache-2.0 | 8,605 | 0.023707 | #!/usr/bin/python
import probe_config as conf
import socket
import re
import os
import tempfile
import shutil
class Swift:
def __init__(self, myname, is_storage):
self.myname = myname
print "Myname = " + self.myname
self.allnodes = conf.swift_nodes
print "all nodes=" + str(self.allnodes)
self.all_ips = [so... | home/swift')
def _configure_rsync(self):
s="""
uid = swift
gid = swift
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
address = %s
[account]
max connections = 2
path = /srv/node/
read only = false
lock file = /var/lock/account.lock
[container]
max connections = 2
path = /srv/node/
read only = false... | ck/container.lock
[object]
max connections = 2
path = /srv/node/
read only = false
lock file = /var/lock/object.lock
""" % self.my_ip
with open('/etc/rsyncd.conf', 'w') as outfile:
outfile.write(s)
self._replace_in_file('RSYNC_ENABLE=false', 'RSYNC_ENABLE=true', '/etc/default/rsync')
def _configure_account_... |
realsobek/freeipa | ipalib/install/certstore.py | Python | gpl-3.0 | 15,409 | 0.00013 | # Authors:
# Jan Cholasta <jcholast@redhat.com>
#
# Copyright (C) 2014 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 v... | ngle_value['cn'] = 'CAcert'
entry.single_value['cACertificate;binary | '] = dercert
ldap.add_entry(entry)
except errors.EmptyModlist:
pass
def clean_old_config(ldap, base_dn, dn, config_ipa, config_compat):
"""
Remove ipaCA and compatCA flags from their previous carriers.
"""
if not config_ipa and not config_compat:
return
try:
re... |
Stavitsky/python-neutronclient | neutronclient/neutron/v2_0/subnet.py | Python | apache-2.0 | 9,395 | 0 | # Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | 'dns_nameservers': _format_dns_nameservers,
'host_routes': _format_host_routes, }
list_columns = ['id', 'name', 'cidr', 'allocation_pools']
pagination_support = True
sorting_support = True
class ShowSubnet(neutronV20.ShowCommand):
"""Show information of a given subnet."""
... | ts(self, parser):
add_updatable_arguments(parser)
parser.add_argument(
'--ip-version',
type=int,
default=4, choices=[4, 6],
help=_('IP version to use, default is 4.'))
parser.add_argument(
'--ip_version',
type=int,
... |
NickRuiz/mt-serverland | dashboard/api/authentication.py | Python | bsd-3-clause | 1,948 | 0.002567 | '''
Authentication by token for the serverland dashboard Web API.
Project: MT Server Land prototype code
Author: Will Roberts <William.Roberts@dfki.de>
'''
from piston.utils import rc, translate_mime, MimerDataException
from serverland.dashboard.api.models import AuthToken
from django.core.exceptions import Multiple... | a 4-byte hexadecimal access token; by
passing this value with the key "token" to an API method, the user
will be authenticated.
'''
def is_authenticated(self, request):
'''Determines whether a given HTTP request is authenticated or
not, and sets the requests user field if it is.'''
... |
if request.GET and 'token' in request.GET:
token = request.GET['token']
# get a token if this is a POST
if request.POST and 'token' in request.POST:
token = request.POST['token']
# translate mime-types in the request if this is a mime
# message
tr... |
wearpants/osf.io | website/mails/mails.py | Python | apache-2.0 | 9,943 | 0.002715 | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_pre... | SMTPAPI. Used for email analytics.
See https://sendgrid.com/docs/User_Guide/Statistics/categories | .html
"""
def __init__(self, tpl_prefix, subject, categories=None):
self.tpl_prefix = tpl_prefix
self._subject = subject
self.categories = categories
def html(self, **context):
"""Render the HTML email message."""
tpl_name = self.tpl_prefix + HTML_EXT
return... |
sdpython/ensae_teaching_cs | src/ensae_teaching_cs/special/image/image_synthese_facette_image.py | Python | mit | 2,656 | 0 | # -*- coding: utf-8 -*-
"""
@file
@brief image et synthèse
"""
from .image_synthese_facette import Rectangle
from .image_synthese_base import Rayon, Couleur
from .image_synthese_sphere import Sphere
class RectangleImage(Rectangle):
"""définit un rectangle contenant un portrait"""
def __init__(self, a, b, c,... | e image,
si invertx == True, inverse l'image selon l'axe des x"""
Rectangle.__init__(self, a, b, c, d, Couleur(0, 0, 0))
self.image = pygame.image.load(nom_image)
self.nom_image = nom_image
self.invert | x = invertx
def __str__(self):
"""affichage"""
s = "rectangle image --- a : " + str(self.a)
s += " b : " + str(self.b)
s += " c : " + str(self.c)
s += " d : " + str(self.d)
s += " image : " + self.nom_image
return s
def couleur_point(self, p):
""... |
uber/vertica-python | vertica_python/vertica/messages/backend_messages/parameter_status.py | Python | apache-2.0 | 3,051 | 0.000983 | # Copyright (c) 2018-2021 Micro Focus or one of its affiliates.
# Copyright (c) 2018 Uber Technologies, 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/licen... | sage
A ParameterStatus message will be generated whenever the backend believes the
frontend should know about a setting parameter value. For example, when you do
SET SESSION AUTOCOMMIT ON | OFF, you get back a parameter status telling you the
new value of autocommit.
At present Vertica supports a handful of parameter... | future. Accordingly, a frontend should
simply ignore ParameterStatus for parameters that it does not understand or care
about.
"""
from __future__ import print_function, division, absolute_import
from struct import unpack
from ..message import BackendMessage
class ParameterStatus(BackendMessage):
message_id = ... |
exic/spade2 | xmppd/modules/oob.py | Python | lgpl-2.1 | 818 | 0.031785 | # -*- coding: UTF-8 -*-
from xmpp import *
class OOB(PlugIn):
NS = "jabber:iq:oob" |
def plugin(self,server):
server.Dispatcher.RegisterHandler('iq',self.OOBIqHandler,typ='set',ns="jabber:iq:oob",xmlns=NS_CLIENT)
server.Dispatcher.RegisterHandler('iq',self.OOBIqHandler,typ='result',ns="jabber:iq:oob",xmlns=NS_CLIENT)
server.Dispatcher.Regi | sterHandler('iq',self.OOBIqHandler,typ='error',ns="jabber:iq:oob",xmlns=NS_CLIENT)
def OOBIqHandler(self, session, stanza):
self.DEBUG("OOB Iq handler called","info")
s = self._owner.getsession(str(stanza['to']))
if s:
# Relay stanza
s.enqueue(stanza)
... |
vsoch/singularity-python | singularity/analysis/reproduce/utils.py | Python | agpl-3.0 | 6,015 | 0.002161 | '''
Copyright (C) 2016-2019 Vanessa Sochat.
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
option) any later version.
This program is distribute... | results = dict()
digest = dict()
allfiles = []
if tag_root:
roots = dict()
if include_sizes:
sizes = dict()
# Option 1: We are given a sandbox
if os.path.isdir(image_path):
sandbox = image_path
# Option 2: it's not a sandbox, and we need to export.
elif '... | ar, extract
if os.path.isfile(sandbox) and sandbox.endswith('tar'):
with tarfile.open(sandbox) as tar:
sandbox = os.path.join(os.path.dirname(sandbox), 'sandbox')
tar.extractall(path=sandbox)
# Recursively walk through sandbox
for root, dirnames, filenames in os.walk(sandbo... |
fxia22/ASM_xf | PythonD/site_python/twisted/test/test_http.py | Python | gpl-2.0 | 11,674 | 0.002227 |
# Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in th... | raise RuntimeError, | "didn't got all callbacks %s" % [self.gotStatus, self.gotResponse, self.gotEndHeaders]
del self.gotEndHeaders
del self.gotResponse
del self.gotStatus
del self.numHeaders
class PRequest:
"""Dummy request for persistence tests."""
def __init__(self, **headers):
self.rec... |
hipnusleo/laserjet | resource/pypi/cryptography-1.7.1/src/cryptography/hazmat/primitives/asymmetric/utils.py | Python | apache-2.0 | 2,460 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import warnings
from pyasn1.codec.der import decoder, encoder
f... | raise | ValueError("Invalid signature data. Unable to decode ASN.1")
if remaining:
raise ValueError(
"The signature contains bytes after the end of the ASN.1 sequence."
)
r = int(data.getComponentByName('r'))
s = int(data.getComponentByName('s'))
return (r, s)
def enc... |
Bootz/multicore-opimization | llvm/tools/clang/utils/analyzer/SATestAdd.py | Python | gpl-3.0 | 2,950 | 0.008136 | #!/usr/bin/env python
"""
Static Analyzer qualification infrastructure: adding a new project to
the Repository Directory.
Add a new project for testing: build it and add to the Project Map file.
Assumes it's being run from the Repository Directory.
The project directory should be added inside the Repository D... | tBuild
import os
import csv
import sys
def isExistingProject(PMapFile, projectID) :
PMapReader = csv.reader(PMapFile)
for I in PMapReader:
if projectID == I[0]:
return True
return False
# Add a new project for testing: build it and add to the Project Map file.
# Params:
# Dir is... | IsScanBuild) :
CurDir = os.path.abspath(os.curdir)
Dir = SATestBuild.getProjectDir(ID)
if not os.path.exists(Dir):
print "Error: Project directory is missing: %s" % Dir
sys.exit(-1)
# Build the project.
SATestBuild.testProject(ID, True, IsScanBuild, Dir)
# Add the proje... |
quantumlib/Cirq | cirq-google/cirq_google/ops/physical_z_tag_test.py | Python | apache-2.0 | 1,084 | 0.000923 | # Copyright 2020 The Cirq Developers
#
# 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 ... | 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 language governing permissions and
# limitations under the License.
import cirq
import cirq_google
def test_equality():
assert cirq_google.PhysicalZTag() == cirq_google.PhysicalZTag()
assert hash(ci... |
jorisvandenbossche/DS-python-data-analysis | notebooks/_solutions/case2_biodiversity_processing11.py | Python | bsd-3-clause | 133 | 0.015038 | sur | vey_data_decoupled.groupby(survey_data_decoupled["eve | ntDate"].dt.year).size().plot(kind='barh', color="#00007f", figsize=(10, 10)) |
Havate/havate-openstack | proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/dashboards/admin/info/views.py | Python | apache-2.0 | 1,045 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | se at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either expre | ss or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from horizon import tabs
from openstack_dashboard.dashboards.admin.info import tabs as project_tabs
class IndexView(tabs.TabbedTableView):
tab_group_class = project_tabs.SystemInfoTabs
... |
alihalabyah/grab | test/spider_mysql_cache.py | Python | mit | 346 | 0 | from unittest import TestCase
from .mixin.spider_cache import SpiderCacheMixin
class BasicSpiderTestCase(TestCase, SpiderCacheMixin):
def setUp(self):
SpiderCac | heMixin.setUp(self)
def setup_cache(self, bot):
bot.setup_cache(backend='mysql', database='spider_test',
user='web', passwd= | 'web-**')
|
astooke/synkhronos | tests/get_set_value_lengths.py | Python | mit | 578 | 0 |
import synkhronos as synk
import numpy as np
import theano
synk.fork()
s = theano.shared(np.ones([5, 5], dtype='float32'), name="shared_var")
s2 = theano.shared(np.ones([4, 4], dtype='float32'), name="shared_var_2")
f = synk.function([], [s.dot(s), s2.dot(s2)])
synk.distribute()
# print(f())
# | print(synk.get_value(1, s))
# d = 2 * np.ones([5, 5], dtype='float32')
# synk.set_value(1, s, d)
d55 = np.array(list(range(5 * 5)), dtype='float32').reshape(5, 5)
d64 = np.array(list(range(6 * 4)), dtype='float32').reshape(6, 4)
# (run interactive in iPython for se | tup)
|
to266/hyperspy | examples/hyperspy_as_library/minimal_example.py | Python | gpl-3.0 | 280 | 0.003571 | """ Loads hyperspy as a regular python library, creates a spectrum with random numbers and | plots it to a file"""
import hyperspy.api as hs
import numpy as np
import matplotlib.pyplot as plt
s = hs.signals.Spectrum(np.random.rand(1024))
s.plot()
plt.savefig("testS | pectrum.png")
|
Lothiraldan/ZeroServices | zeroservices/exceptions.py | Python | mit | 434 | 0.009217 | class ServiceUnavailable(Exception):
pass
class UnknownNode(Exception):
pass
class UnknownService(Exception):
pass
class ResourceException(Exception):
def __init__(self, error_message):
self.error_message = error | _message
def __str__(self):
return self.__repr__()
def __repr__(self):
return "ResourceException(%s)" % self.error_message
class ResourceNotFound(Exception):
| pass
|
ibayer/fastFM-fork | fastFM/bpr.py | Python | bsd-3-clause | 2,859 | 0 | # Author: Immanuel Bayer
# License: BSD 3 clause
import ffm
import numpy as np
from .base import FactorizationMachine
from sklearn.utils.testing import assert_array_equal
from .validation import check_array, assert_all_finite
class FMRecommender(FactorizationMachine):
""" Factorization Machine Recommender with ... | high value then the second
| FM(X[i,0]) > FM(X[i, 1]).
"""
X = X.T
X = check_array(X, accept_sparse="csc", dtype=np.float64)
assert_all_finite(pairs)
pairs = pairs.astype(np.float64)
# check that pairs contain no real values
assert_array_equal(pairs, pairs.astype(np.int32))
asser... |
saschpe/gnome_picross | gnomepicross/game.py | Python | gpl-2.0 | 5,836 | 0.035127 | #!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later ... | f.__level:
if row[col] == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
retu | rn hint
def getField(self,col,row):
return self.__level[row][col]
def isGameWon(self):
return self.__fieldsOpened == self.__fieldsToOpen
#
# Game manipulation methods
#
def restart(self):
"""Reinitializes the current game
"""
for i, row in enumerate(self.__level):
for j, field in enumerate(row)... |
valentin-krasontovitsch/ansible | lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_template.py | Python | gpl-3.0 | 10,716 | 0.001027 | #!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... | ask_tags:
description:
- Prompt user for job tags on launch.
type: bool
default: 'no'
ask_skip_tags:
description:
- Prompt user for job tags to skip on launch.
| version_added: 2.7
type: bool
default: 'no'
ask_job_type:
description:
- Prompt user for job type on launch.
type: bool
default: 'no'
ask_verbosity:
description:
- Prompt user to choose a verbosity level on launch.
version_added: 2.7
type: bool
... |
tgquintela/Mscthesis | script_computation.py | Python | mit | 836 | 0.008373 |
from FirmsLocations.Computers.precomputers import PrecomputerCollection
from FirmsLocations.Computers.computers import Directmodel, LocationOnlyModel,\
LocationGeneralModel
## Pathpameters
# Set path parameters |
execfile('set_pathparameters.py')
# Set precomputation parameters
execfile('set_precomputationparameters.py')
# Set computation paramters
execfile('set_computationparameters.py')
### Data precomputation
precomps = PrecomputerCollection(logfile, pathfolder, old_computed=True)
### Models
#dirmodel = Directmodel(logfil... | pathfolder, precomps, num_cores=1)
locmodel.compute(pars_loconly_model)
#
#locgeneralmodel = LocationGeneralModel(logfile, pathfolder, precomps)
#locgeneralmodel.compute(pars_loc_model)
|
bowen0701/algorithms_data_structures | lc0695_max_area_of_island.py | Python | bsd-2-clause | 4,625 | 0.045622 | """Leetcode 695. Max Area of Island
Medium
URL: https://leetcode.com/problems/max-area-of-island/
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's
(representing land) connected 4-directionally (horizontal or vertical.)
You may assume all four edges of the grid are surrounded by water.
Find... | [0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
print SolutionDFSIterUpd | ate().maxAreaOfIsland(grid)
# Output: 0.
grid = [[0,0,0,0,0,0,0,0]]
print SolutionDFSRecurUpdate().maxAreaOfIsland(grid)
grid = [[0,0,0,0,0,0,0,0]]
print SolutionDFSIterUpdate().maxAreaOfIsland(grid)
if __name__ == '__main__':
main()
|
abrt/faf | src/pyfaf/actions/addcompathashes.py | Python | gpl-3.0 | 5,960 | 0.001174 | # Copyright (C) 2014 ABRT Team
# Copyright (C) 2014 Red Hat, Inc.
#
# This file is part of faf.
#
# faf 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) ... | emtype:
ptypes = list(problemtypes.keys())
else:
ptypes = []
for ptype in cmdline.problemtype:
if ptype not in problemtypes:
self.log_warn("Problem type '{0}' is not supported"
| .format(ptype))
continue
ptypes.append(ptype)
if not ptypes:
self.log_info("Nothing to do")
return 1
for i, ptype in enumerate(ptypes, start=1):
problemtype = problemtypes[ptype]
self.log... |
jeremyphilemon/uniqna | api/tests/test_models.py | Python | bsd-3-clause | 459 | 0.021786 | from django.test import TestCase
from api.models import UsernameSnippet
class TestUsernameSnippet(TestCas | e):
@classmethod
def setUpTestData(cls):
UsernameSnippet.objects.create(available=True)
def test_existence(self):
u = UsernameSnippet.ob | jects.first()
self.assertIsInstance(u, UsernameSnippet)
self.assertEqual(u.available, True)
def test_field_types(self):
u = UsernameSnippet.objects.first()
self.assertIsInstance(u.available, bool)
|
clolsonus/madesigner | madesigner/madlib/contour.py | Python | gpl-3.0 | 28,367 | 0.007791 | #!python
__author__ = "Curtis L. Olson < curtolson {at} flightgear {dot} org >"
__url__ = "http://gallinazo.flightgear.org"
__version__ = "1.0"
__license__ = "GPL v2"
import fileinput
import math
import string
from . import spline
import Polygon
import Polygon.Shapes
import Polygon.Utils
class Cutpos:
def __in... | + str(pt[1]))
for pt in self.bottom:
print(str(pt[0]) + " " + str(pt[1]))
# rotate a point about (0, 0)
def rotate_point( self, pt, angle ):
rad = math.radians(angle)
newx = pt[0] * math.cos(rad) - pt[1] * math.sin(rad)
newy = pt[1] * math.cos(rad) + pt[0] * math.sin... | e(self, angle):
newtop = []
for pt in self.top:
newtop.append( self.rotate_point(pt, angle) )
self.top = list(newtop)
newbottom = []
for pt in self.bottom:
newbottom.append( self.rotate_point(pt, angle) )
self.bottom = list(newbottom)
new... |
Tony-Tsoi/proj-euler-ans | problems/prob044.py | Python | mit | 1,103 | 0.012762 | """
Problem 44
Pentagonal numbers are generated by the formula, Pn = n*(3n−1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and ... | """
for x in range(i, j):
Pn = int( x*(3*x-1)/2 )
S.append(Pn)
def fitsRule(Pj, Pk, S):
return isPent(Pj + Pk, S) and isPent(Pj - Pk, S)
T = []
setSet(1, 100, T)
diff = | 99999999
for i in range(1, 5000):
for j in range(1, i):
if fitsRule(T[i], T[j], T) and (T[i] - T[j]) < diff:
diff = T[i] - T[j]
print('end.', diff) |
wisechengyi/pants | src/python/pants/engine/build_files.py | Python | apache-2.0 | 12,398 | 0.003388 | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os.path
from collections.abc import Mapping
from typing import Dict
from pants.base.exceptions import ResolveError
from pants.base.project_tree import Dir
from pants.base.specs imp... | '"{}" was not found in namespace "{}". '
"Did you mean one of:\n {}".format(name, address_family.namespace, possibilities)
)
if source:
raise resolve_error from source
raise resolve_error
@rule
async def find_build_file(address: Address) -> BuildFileAddress:
address_family = await ... | sables:
_raise_did_you_mean(address_family=address_family, name=address.target_name)
return next(
build_file_address
for build_file_address in address_family.addressables.keys()
if build_file_address == address
)
@rule
async def find_build_files(addresses: Addresses) -> BuildFi... |
rogerhu/django | django/contrib/gis/geos/prepared.py | Python | bsd-3-clause | 1,034 | 0 | from django.contrib.gis.geos.base import GEOSBase
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.contrib.gis.geos.prototypes import prepared as capi
class PreparedGeometry(GEOSBase):
"""
A geometry that is prepared for performing certain operations.
At the moment this includes the c... | def contains_properly(self, other):
return capi.prepared_contains_properly(self.ptr, other.ptr)
def covers(self, other):
return capi.prepared_covers(self.ptr, other.ptr)
def intersects(self, other):
return capi.prepared_intersects(self.ptr, other.pt | r)
|
nzsquirrell/p2pool-myriad | oldstuff/SOAPpy/version.py | Python | gpl-3.0 | 22 | 0.090909 | _ | _version__="0.12.5 | "
|
BirkbeckCTP/janeway | src/utils/management/commands/backup.py | Python | agpl-3.0 | 5,466 | 0.002012 | import os
import shutil
import boto
from boto.s3.key import Key
import subprocess
from io import StringIO
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.conf import settings
from django.utils import timezone
from django.core.mail import send_mail
from c... | e folder for copying
:param dest_path: The destination these files/folders should be copied to
:return: None
"""
if not os.path.exists(src_path):
os.makedirs(src_path)
files = os.listdir(src_path)
for file_name in files:
if not file_name == 'temp':
full_file_name = ... | )
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, dest_path)
else:
dir_dest = os.path.join(dest_path, file_name)
if os.path.exists(dir_dest):
shutil.rmtree(os.path.join(dir_dest))
shutil.copytree(f... |
plumJ/catsup | config.py | Python | mit | 1,211 | 0.012386 | # -*- coding:utf-8 -*-
import os
site_title = 'plum.J'
site_description = '\'s blog'
site_url = 'http://plumj.com'
static_url = 'static'
theme_name = 'sealscript'
google_analytics = ''
catsup_path = os.path.dirname(__file__)
posts_path = os.path.join(catsup_path, '_posts')
theme_path = os.path.join(catsup_path, 'the... | with('/'):
site_url = site_url[:-1]
if static_url.endswith('/'):
static_url = static_url[:-1]
settings = dict(static_path=os.path.join(theme_path, 'static'),
template_path=os.path.join(theme_path, 'template'),
gzip=True,
site_title=site_title,
site_description=site_description,
site_url=sit... | post_per_page=post_per_page,
disqus_shortname=disqus_shortname,
links=links,
static_url=static_url,
google_analytics=google_analytics,
)
|
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/application_gateway_ssl_predefined_policy.py | Python | mit | 1,826 | 0.000548 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | tocol_version: str or
~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslProtocol
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'},
'min_protocol_... | it__(**kwargs)
self.name = kwargs.get('name', None)
self.cipher_suites = kwargs.get('cipher_suites', None)
self.min_protocol_version = kwargs.get('min_protocol_version', None)
|
wbsavage/shinken | shinken/misc/datamanagerhostd.py | Python | agpl-3.0 | 5,441 | 0.000919 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redis... | SERVICE THAT MA5TCH", s.get('service_description', '')
| services.append(s)
res.append((tpl, services))
return res
datamgr = DataManagerHostd()
|
brownnrl/moneyguru | support/genchangelog.py | Python | gpl-3.0 | 2,089 | 0.005744 | #!/usr/bin/env python3
import sys
import datetime
import re
CHANGELOG_FORMAT = """
{version} ({date})
----------------------
{description}
"""
TIXURL = "https://github.com/hsoft/moneyguru/issues/{}"
def tixgen(tixurl):
"""This is a filter *generator*. tixurl is a url pattern for the tix with a {0} placeholder
... | date': date, 'date_str': date_str, 'version': version, 'description': description.strip()}
result.append(d)
return result
def changelog_to_rst(changelogpath):
changelog = read_ | changelog_file(changelogpath)
tix = tixgen(TIXURL)
for log in changelog:
description = tix(log['description'])
# The format of the changelog descriptions is in markdown, but since we only use bulled list
# and links, it's not worth depending on the markdown package. A simple regexp suffi... |
Juniper/neutron | neutron/db/migration/cli.py | Python | apache-2.0 | 4,441 | 0.000225 | # Copyright 2012 New Dream Network, LLC (DreamHost)
#
# 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 a... | mbic_config.Config(
os.path.join(os.path.dirname(__file__), | 'alembic.ini')
)
config.set_main_option('script_location',
'neutron.db.migration:alembic_migrations')
# attach the Neutron conf to the Alembic conf
config.neutron_config = CONF
CONF()
#TODO(gongysh) enable logging
legacy.modernize_quantum_config(CONF)
CONF.co... |
quantumlib/ReCirq | recirq/quantum_chess/bit_utils.py | Python | apache-2.0 | 2,765 | 0 | # Copyright 2020 Google
#
# 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, soft... | t(sq: str) -> int:
"""Transform algebraic square notation into a bitboard bit number."""
return move.y_of(sq) * 8 + move.x_of(sq)
def bit_to_square(bit: int) -> str:
"""Transform a bitboard bit number into algebraic square notation."""
| return move.to_square(bit % 8, bit // 8)
def squares_to_bitboard(squares: List[str]) -> int:
"""Transform a list of algebraic squares into a 64-bit board bitstring."""
bitboard = 0
for sq in squares:
bitboard += 1 << square_to_bit(sq)
return bitboard
def bitboard_to_squares(bitboard: int... |
bigfootproject/OSMEF | data_processing/overview.py | Python | apache-2.0 | 3,112 | 0.010604 | #!/usr/bin/python
import json
import os
import sys
if not os.access("data.json", os.F_OK):
print("Please run aggregate.py first")
sys.exit(1)
data = json.load(open("data.json", "r"))
print("Results for 1 connection")
print("{:<20s} {:>8s} | {:>7s} | {:>5s} | {:>5s} | {:>5s} | {:>5s}".format("name",
... | "std"))
for name | in sorted(data):
print("{:<20s} {:>8.2f} | {:>8.2f} | {:>7.2f} | {:>5.2f} | {:>5.2f} | {:>5.2f} | {:>5.2f}".format(name,
data[name]["c=30"]["btc"]["rx"]["rate_KBps"]["sum"],
data[name]["c=30"]["btc"]["rx"]["rate_KBps"]["avg"],
... |
piksels-and-lines-orchestra/inkscape | share/extensions/fig2dev-ext.py | Python | gpl-2.0 | 1,025 | 0.001951 | #!/usr/bin/env python
"""
fig2dev-ext.py
Python script for running fig2dev in Inkscape extensions
Copyright (C) 2008 Stephen Silver
This program is free software; you can redistribute it and/or modify
it under the t | erms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PA... | cense for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
import sys
from run_command import run
run('fig2dev -L svg "%s" "%%s"' % sys.argv[1]... |
cypherai/PySyft | syft/__init__.py | Python | apache-2.0 | 42 | 0 | from | .tensor import *
from .math | import *
|
wangg12/caffe | scripts/download_model_binary.py | Python | bsd-2-clause | 2,496 | 0.000401 | #!/usr/bin/env python
import os
import sys
import time
import yaml
import urllib
import hashlib
import argparse
required_keys = ['caffemodel', 'caffemodel_url', 'sha1']
def reporthook(count, block_size, total_size):
"""
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
"""
glob... | frontmatter = args.dirname[1]
model_filename = os.path.join(dirname, frontmatter['caffemodel'])
# Closure-d function for checking SHA1.
def model_checks_out(filename=model_filename, sha1=frontmatter['sha1']):
with open(filename, 'r') as f:
return hashlib.sha1(f.r | ead()).hexdigest() == sha1
# Check if model exists.
if os.path.exists(model_filename) and model_checks_out():
print("Model already exists.")
sys.exit(0)
# Download and verify model.
urllib.urlretrieve(
frontmatter['caffemodel_url'], model_filename, reporthook)
if not model_... |
robertding/vo | vo/dl/__init__.py | Python | mit | 242 | 0.004132 | #!/usr/bin/ | env python
# -*- coding:utf-8 -*-
#
# Author : RobertDing
# E-mail : robertdingx@gmail.com
# Date : 15/08/29 02:24:28
# Desc : fetch video
#
from __future__ import absolute_import, divisi | on, with_statement
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.