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 |
|---|---|---|---|---|---|---|---|---|
RPGOne/Skynet | imbalanced-learn-master/examples/over-sampling/plot_smote_svm.py | Python | bsd-3-clause | 1,830 | 0.002732 | """
=========
SMOTE SVM
=========
An illustration of the random SMOTE SVM method.
"""
print(__doc__)
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# Define some color for the plotting
almost_black = '#262626'
palette = sns.color_palette()
from sklearn.datasets import make_classification
from skl... | lmost_black, facecolor=palette[2], linewidth=0.15)
ax1.set_title('Original set')
ax2.scatter(X_res_vis[y_resampled == 0, 0], X_res_vis[y_resampled == 0, 1],
label="Class #0", alpha=.5, edgecolor=almost_black,
facecolor=palette[0], linewidth=0.15)
ax2.scatter(X_res_vis[y_resampled == 1, 0], X_re... | black,
facecolor=palette[2], linewidth=0.15)
ax2.set_title('SMOTE svm')
plt.show()
|
sit0x/farmasoft | interaccion_usuario.py | Python | gpl-3.0 | 2,473 | 0.001227 | #!/usr/bin/env python
# coding: utf-8
#encoding: latin1
def ingresar_numero(numero_minimo, numero_maximo):
''' Muestra un cursor de ingreso al usuario para que ingrese un número
tal que numero_mínimo <= ingreso <= numero_máximo. Ante un ingreso
inválido muestra un mensaje descriptivo de error y repregunta.... | pción de
acuerdo a la numeración mostrada, generada por la función. Se valida el
ingreso repreguntando tantas veces como sea necesario.
opciones es una lista de cadena con las opciones a mostrar.
opcion_por_defecto es una opción adicional, obligatoria, no incluida en
la lista de opciones. Se mos... | so se orienta a una
opción de tipo "cancelar".
Se devuelve un número entero según la elección del usuario. Si
selecciona un elemento de la lista de opciones, devuelve su índice. Si
selecciona la opción por defecto, devuelve -1.
'''
print("Seleccione una opción:")
for numero_opcion in ran... |
amwelch/a10sdk-python | a10sdk/core/acos/acos_scaleout_cluster_config_device_groups_device_group.py | Python | apache-2.0 | 1,370 | 0.010949 | from a10sdk.common.A10BaseClass import A10BaseClass
class DeviceGroup(A10BaseClass):
"""Class Description::
configure scaleout device groups.
Class device-group supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param devi... | -groups/device-group/{device_group}"
self.DeviceProxy = ""
self.device_group = ""
self.device_id_start = ""
self.device_id_end = ""
for keys, | value in kwargs.items():
setattr(self,keys, value)
|
eicher31/compassion-switzerland | partner_communication_switzerland/models/partner_communication_config.py | Python | agpl-3.0 | 4,913 | 0.000204 | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... | ner
Outputs the texts in a file
:param partner:
:return: True
"""
self.ensure_one()
comm_obj = self.env["partner.communication.job"].with_context(
must_skip_send_to_printer=True)
res = []
object_ids | = self._get_test_objects(partner)
object_ids = ",".join([str(id) for id in object_ids])
temp_comm = comm_obj.create({
"partner_id": partner.id,
"config_id": self.id,
"object_ids": object_ids,
"auto_send": False,
"send_mode": send_mode,
... |
adoublebarrel/geo-tweet-exercise | server/assesment_site/geo_tweets/apps.py | Python | mit | 94 | 0 | from django.apps import AppConfi | g
class GeoTweetsConfig(AppConfig | ):
name = 'geo_tweets'
|
jgmanzanas/CMNT_004_15 | project-addons/stock_deposit/stock_deposit.py | Python | agpl-3.0 | 10,814 | 0.001017 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Santi Argüeso
# Copyright 2014 Pexego Sistemas Informáticos S.L.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | string='Date of Transfer',
store=True,
readonly=True)
state = fields.Selection([('draft', 'D | raft'), ('sale', 'Sale'),
('returned', 'Returned'),
('invoiced', 'Invoiced'),
('loss', 'Loss')], 'State',
readonly=True, required=True)
sale_move_id = fields.Many2one('stock.move', 'Sale Move', req... |
MeerkatLabs/sleekpromises | test/promises/test_2_3_4.py | Python | bsd-3-clause | 7,323 | 0.006691 | """
2.3.4: If `x` is not an object or function, fulfill `promise` with `x`
https://github.com/promises-aplus/promises-tests/blob/2.1.1/lib/tests/2.3.4.js
"""
from test.promises.helpers import generate_fulfilled_test_case, generate_rejected_test_case
dummy = {'dummy': 'dummy'}
sentinel = {'sentinel': 'sentinel'}
def ... | ef return_primitive(value):
return primitive_value
def retr | ieve_primitive(value):
test_case.assertEqual(value, primitive_value)
done()
promise.then(None, return_primitive).then(retrieve_primitive)
return test_method
None_FulfilledTestCase = generate_fulfilled_test_case(primitive_fulfilled_wrapper(None), dummy,
... |
Teekuningas/mne-python | examples/datasets/plot_limo_data.py | Python | bsd-3-clause | 13,302 | 0 | """
.. _ex-limo-data:
=============================================================
Single trial linear regression analysis with the LIMO dataset
=============================================================
Here we explore the structure of the data contained in the
`LIMO dataset`_.
This example replicates and extend... | provides more or less the same
# information as the ``print(limo_epochs)`` command we ran before. T | here are
# 1055 faces (i.e., epochs), subdivided in 2 conditions (i.e., Face A and
# Face B) and, for this particular subject, there are more epochs for the
# condition Face B.
#
# In addition, we can see in the second column that the values for the
# phase-coherence variable range from -1.619 to 1.642. This is because... |
IronLanguages/ironpython3 | Tests/test_surrogatepass.py | Python | apache-2.0 | 4,002 | 0.010245 | # Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
##
## Test surrogatepass encoding error handler
##
import unittest
import codecs
from iptest import run_test
... | ), b"abc")
self.assertEqual(b"abc".decode("ascii", errors="sur | rogatepass"), "abc")
def test_utf_7(self):
self.assertEqual("abc\ud810xyz".encode("utf_7", errors="surrogatepass"), b"abc+2BA-xyz")
self.assertEqual(b"abc+2BA-xyz".decode("utf_7", errors="surrogatepass"), "abc\ud810xyz")
def test_utf_8(self):
self.assertEqual("abc\ud810xyz".encode("utf... |
indigo-dc/im | test/unit/connectors/OpenNebula.py | Python | gpl-3.0 | 17,429 | 0.003844 | #! /usr/bin/env python
#
# IM - Infrastructure Manager
# Copyright (C) 2011 - GRyCAP - Universitat Politecnica de Valencia
#
# 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 t... | ("files/sgs.xml"), 0)
one_server.one.secgroup.allocate.return_value = (True, 1, 0)
server_proxy.return_value = one_server
inf = InfrastructureInfo()
inf.auth = auth
res = one_cloud.launch(inf, radl, radl, 1, auth)
success, _ = res[0]
self.assertTrue(success, msg=... | E = inbound, RANGE = 22:22 ]\n'
'RULE = [ PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 8080:8080 ]\n'
'RULE = [ PROTOCOL = TCP, RULE_TYPE = inbound, RANGE = 9000:9100 ]\n')
self.assertEqual(one_server.one.secgroup.allocate.call_args_list, [call('user:pass', sg_templ... |
uw-it-aca/spacescout_web | spacescout_web/views/share.py | Python | apache-2.0 | 8,038 | 0.000498 | """ Copyright 2012, 2013 UW Information Technology, University of Washington
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 r... | ort validate_back_link
import oauth2
import socket
import simplejson as json
import logging
logger = logging.getLogger(__name__)
@login_required(login_url='/login')
def share(request, spot_id=None):
if request.method == 'POST':
f | orm = ShareForm(request.POST)
try:
back = request.POST['back']
validate_back_link(back)
except:
back = '/'
if form.is_valid():
spot_id = form.cleaned_data['spot_id']
back = form.cleaned_data['back']
sender = form.cleaned_d... |
MCGallaspy/kolibri | kolibri/core/webpack/utils.py | Python | mit | 1,718 | 0.004075 | """
This module manages the interface between webpack and Django.
It loads webpack bundle tracker stats files, and catalogues the different files |
that need to be served in order to inject that frontend code into a Django template.
Originally, it was a monkeypatch of django-webpack-loader - but as our needs are somewhat
different, much of the code has simply been rewritten, and will continue to be done so to better much our use case.
"""
from __future__ import a | bsolute_import, print_function, unicode_literals
from django.conf import settings
from django.utils.safestring import mark_safe
def render_as_url(chunk):
"""
This function returns the URL for a particular chunk (JS or CSS file), by
appending the url or public path for the file to the current STATIC_URL s... |
UdK-VPT/Open_eQuarter | crow_archive/crow_django/ates/models.py | Python | gpl-2.0 | 33,811 | 0.00627 | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free ... | l2area = models.FloatField(db_column='wall2Area', blank=True, null=True) # Field name made lowercase.
wall2azimuth = models.FloatField(db_column='wall2Azimuth', blank=True, null=True) # Field name made lowercase | .
wall3area = models.FloatField(db_column='wall3Area', blank=True, null=True) # Field name made lowercase.
wall3azimuth = models.FloatField(db_column='wall3Azimuth', blank=True, null=True) # Field name made lowercase.
wall4area = models.FloatField(db_column='wall4Area', blank=True, null=True) # Field nam... |
guohongze/adminset | elfinder/utils/archivers.py | Python | gpl-2.0 | 1,102 | 0.006352 | from zipfile import ZipFile
class ZipFileArchiver(object):
"""
An archiver used to generate .zip files.
This wraps Python's built in :class:`zipfile.ZipFile`
methods to operate exactly like :class:`tarfile.TarFile` does.
"""
def __init__(self, *args, **kwargs):
"""
Create ... | and store it to the ``zipfile`` member.
"""
self.zipfile = ZipFile(*args, **kwargs)
@classmethod
def open(self, *args, **kwargs):
"""
Open the archive. This must be a classmethod.
"""
return ZipFileArchiver(*args,**kwargs)
|
def add(self, *args, **kwargs):
"""
Add file to the archive.
"""
self.zipfile.write(*args, **kwargs)
def extractall(self, *args, **kwargs):
"""
Extract all files from the archive.
"""
self.zipfile.extractall(*args, **kwargs)
def close(... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationradiuspolicy_authenticationvserver_binding.py | Python | apache-2.0 | 5,569 | 0.035374 | #
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | ess or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix. | netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util
class authenticationradiu... |
ivandgreat/netmiko | tests/test_utils.py | Python | mit | 567 | 0.001764 | #!/usr/bin/env python
"""
Implement common functions for tests
"""
from __future__ import print_function
from __future__ import unicode_literals
import io
import sys
def parse_yaml(yaml_file):
"""
Parses a yaml file, returning its contents as a dict.
"""
try:
import yaml
except ImportErro... | o.open( | yaml_file, encoding='utf-8') as fname:
return yaml.load(fname)
except IOError:
sys.exit("Unable to open YAML file: {0}".format(yaml_file))
|
Ophiuchus1312/enigma2-master | lib/python/Screens/ParentalControlSetup.py | Python | gpl-2.0 | 14,944 | 0.02844 | from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen
from Components.ActionMap import NumberActionMap
from Components.config import config, getConfigListEntry, ConfigNothing, NoSave, ConfigPIN
from Components.ParentalControlList import ParentalControlEntryComponent, ParentalControlList
... | green"] = StaticText(_("OK"))
self.onLayoutFinish.append(sel | f.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup_title)
def isProtected(self):
return config.ParentalControl.setuppinactive.getValue() and config.ParentalControl.configured.getValue()
def createSetup(self):
self.editListEntry = None
self.changePin = None
self.changeSetupPin = None
... |
FNST-OpenStack/cloudkitty-dashboard | cloudkittydashboard/dashboards/project/billing_overview/views.py | Python | apache-2.0 | 14,849 | 0.027079 | # coding=utf-8
import json
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponse
import django.views
from django.template import defaultfilters as template_filters
from horizon import tables
from horizon import exceptions
from cloudkittydashboard.api import cloudkitty as api
f... | ango.views.generic.TemplateView):
def get(self,request,*args,**kwargs):
tenant_id = get_tenant_id( | self.request)
billing_month = get_month(self.request)
tenants = get_tenant_list(self.request)
for tenant in tenants:
if tenant.id == tenant_id:
tenant_name = tenant.name
break
reports = api.cloudkittyclient(self.request).billings.list_month_report(tenant_id,... |
fomars/yandex-tank | setup.py | Python | lgpl-2.1 | 3,327 | 0.000902 | from setuptools import setup, find_packages
setup(
name='yandextank',
version='1.12.7',
description='a performance measurement tool',
longer_description='''
Yandex.Tank is a performance measurement and load testing automatization tool.
It uses other load generators such as JMeter, ab or phantom inside ... | oftware Development :: Testing',
'Topic :: Software Development :: Testing :: Traffic Generation',
'Programming Language :: Python :: 2',
],
entry_points={
'console_scripts': [
'yandex-tank = yandextank | .core.cli:main',
'yandex-tank-check-ssh = yandextank.common.util:check_ssh_connection',
'tank-postloader = yandextank.plugins.DataUploader.cli:post_loader',
'tank-docs-gen = yandextank.validator.docs_gen:main'
],
},
package_data={
'yandextank.api': ['config/*'... |
Crowdlink/lever | lever/tests/unit_tests.py | Python | bsd-2-clause | 14,490 | 0.000897 | import unittest
import types
import datetime
from flask import Flask
from pprint import pprint
from sqlalchemy import (Column, create_engine, DateTime, Date, Float,
ForeignKey, Integer, Boolean, Unicode, create_engine)
from lever import API, preprocess, postprocess, ModelBasedACL, ImpersonateM... | pass
@postprocess(method='post')
def preprocess_that(self):
pass
self.assertEqual(
APIAwesome._post_method['post'][0].__name__, 'preprocess_those')
def test_none(self):
class APIAwesome(API):
pass
assert APIAwesome._pre_m... | |
thefab/tornadis | tests/test_pubsub.py | Python | mit | 3,713 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tornado.testing
import tornado.ioloop
import tornado.gen
from tornadis.pubsub import PubSubClient
from tornadis.client import Client
from support import test_redis_or_raise_skiptest, mock
class PubSubClientTestCase(tornado.testing.AsyncTestCase):
def setUp(s... | yield c.connect()
res = yield c.pubsub_subscribe()
self.assertFalse(res)
c.disconnect()
@tornado.testing.gen_test
def test_subscribe_no_redis(self):
c = PubSubClient()
with mock.patch.object(c, "is_connected", return_value=False):
| res = yield c.pubsub_subscribe("foo")
self.assertFalse(res)
self.assertFalse(c.subscribed)
@tornado.testing.gen_test
def test_unsubscribe_no_redis(self):
c = PubSubClient()
yield c.pubsub_subscribe("foo")
with mock.patch.object(c, "is_connected", return_value... |
oblique-labs/pyVM | rpython/translator/goal/targetsegfault.py | Python | mit | 291 | 0.013746 | def getitem(list, ind | ex):
return list[index]
def entry_point(i):
return getitem([i, 2, 3, 4], 2) + getitem(None, i)
def target(*args):
return entry_point, [int]
def get_llinterp_args():
return [1]
# ____ | _ Run translated _____
def run(c_entry_point):
c_entry_point(0)
|
buguelos/odoo | yowsup/Interfaces/DBus/__init__.py | Python | agpl-3.0 | 22 | 0.045455 | #import DBusInterface | ||
telefonicaid/fiware-IoTAgent-Cplusplus | third_party/mosquitto-1.4.4/test/broker/04-retain-qos1-qos0.py | Python | agpl-3.0 | 1,749 | 0.005718 | #!/usr/bin/env python
# Test whether a retained PUBLISH to a topic with QoS 1 is retained.
# Subscription is made with QoS 0 so the retained message should also have QoS
# 0.
import subprocess
import socket
import time
import inspect, os, sys
# From http://stackoverflow.com/questions/279237/python-import-a-module-fr... | wait()
if rc:
(stdo, stde) = broker.communicate()
print(std | e)
exit(rc)
|
pyhmsa/pyhmsa | pyhmsa/fileformat/exporter/raw.py | Python | mit | 3,504 | 0.001427 | """
Export to RAW/RPL file format
Based on:
http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm
"""
# Standard library modules.
import os
# Third party modules.
# Local modules.
from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread
from pyhmsa.spec.datum.analysislist import A... | um.imageraster import ImageRaster2D, ImageRaster2DSpectral
# Globals and constants variables.
class _ExporterRAWThread(_ExporterThread):
def _run | (self, datafile, dirpath, *args, **kwargs):
basefilename = datafile.header.title or 'Untitled'
keys = set(datafile.data.findkeys(AnalysisList2D)) | \
set(datafile.data.findkeys(ImageRaster2D)) | \
set(datafile.data.findkeys(ImageRaster2DSpectral))
length = len(keys)
... |
att-comdev/deckhand | deckhand/tests/unit/db/test_revision_diffing.py | Python | apache-2.0 | 14,036 | 0 | # Copyright 2017 AT&T Intellectual Property. All other 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... | # Between revision_ids[0] and [2], bucket_name is modified (by 2) and
# alt_bucket_name is created (by 1).
self._verify_buckets_status(
revision_ids[0], revision_ids[2],
{bucket_name: 'modified', alt_bucket_name: 'created'})
# Between revision_ids[0] and [3], bucket_n... | lt_bucket_name is created (by [1]) (as well as modified by [3]).
self._verify_buckets_status(
revision_ids[0], revision_ids[3],
{bucket_name: 'modified', alt_bucket_name: 'created'})
# Between revision_ids[1] and [2], bucket_name is modified but
# alt_bucket_name remains... |
megasan/210-CT | coursework 6.py | Python | mit | 903 | 0.006645 | """ Write the pseudocode and code for a function that reverses the words in a sentence. Input: "This is awesome" Output: "awesome is This". Give the Big O notation. """
def reverse(sentence):
""" split original sentence into a list, then append elements of the old list to the new list starting from last to first.... | n join the list back toghether. """
original = sentence.split()
reverse = []
count = len(original) - 1
while count >= 0:
reverse.append(original[count])
count = count - 1
result = " ".join(reverse)
return result
""" sentence <- input sentence
result <- e... | ]
index <- index - 1
end while
return result
O(N)
"""
|
michaelkirk/QGIS | python/plugins/processing/algs/lidar/fusion/FirstLastReturn.py | Python | gpl-2.0 | 2,653 | 0.001131 | # -*- coding: utf-8 -*-
"""
***************************************************************************
FirstLastReturn.py
---------------------
Date : May 2014
Copyright : (C) 2014 by Niccolo' Marchi
Email : sciurusurbanus at hotmail dot it
***************... | FusionPath(), 'FirstLastReturn.exe')]
commands.append('/verbose')
if self.getPa | rameterValue(self.SWITCH):
commands.append('/uselas')
self.addAdvancedModifiersToCommand(commands)
outFile = self.getOutputValue(self.OUTPUT)
commands.append(outFile)
files = self.getParameterValue(self.INPUT).split(';')
if len(files) == 1:
commands.append... |
jejung/godot | doc/tools/doc_status.py | Python | mit | 15,221 | 0.003679 | #!/usr/bin/env python3
import os
import sys
import re
import math
import platform
import xml.etree.ElementTree as ET
################################################################################
# Config #
#######################################... | _problem', s)
else:
s = color('part_big_problem', s)
pad_size = max(len(str(self.described)), len(str(self.total)))
pad_described = ''.ljust(pad_size - len(str(self.described)))
pad_percent = ''.ljust(3 - len(str(percent)))
pad_total = ''.ljust(pad_size - len(str(self... | def __init__(self, name=''):
self.name = name
self.has_brief_description = True
self.has_description = True
self.progresses = {
'methods': ClassStatusProgress(),
'constants': ClassStatusProgress(),
'members': ClassStatusProgress(),
'signal... |
vDial-up/client | libs/vDialing.py | Python | gpl-3.0 | 5,879 | 0.004252 | # vDial-up client
# Copyright (C) 2015 - 2017 Nathaniel Olsen
# 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 pr... | " + "\n", "utf-8"))
if main.listen_for_data(sock) == "PONG":
| break
else:
print("Disconnected: Connection timeout.")
def vdialing(vNumber_to_connect, vNumber_IP):
if core.config['use_ipv6_when_possible']:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET... |
PLyczkowski/Sticky-Keymap | 2.74/scripts/addons_contrib/cursor_control/history.py | Python | gpl-2.0 | 9,295 | 0.006885 | # -*- coding: utf-8 -*-
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# ... | 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.
#
# ##### END GPL LICENSE BLOCK #####
"""
TODO:
IDEAS:
LATER:
ISSUES:
Bugs:
Seg-faults when unregistering addon...
Mites:
... |
bvancsics/TCMC | maximum_matching.py | Python | gpl-3.0 | 35,707 | 0.002745 | """Weighted maximum matching in general graphs.
The algorithm is taken from "Efficient Algorithms for Finding Maximum
Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
It is based on the "blossom" method for finding augmenting paths and
the "primal-dual" method for finding a matching of maximum weight, bo... | ]
# If v is a vertex, |
# neighbend[v] is the list of remote endpoints of the edges attached to v.
# Not modified by the algorithm.
neighbend = [ [ ] for i in range(nvertex) ]
for k in range(len(edges)):
(i, j, w) = edges[k]
neighbend[i].append(2*k+1)
neighbend[j].append(2*k)
# If v is a vertex,
... |
quittle/bazel_toolbox | actions/scripts/jinja_helper.py | Python | apache-2.0 | 2,197 | 0.005007 | # Copyright (c) 2016 Dustin Doloff
# Licensed under Apache License v2.0
import jinja2
import os
MESSAGE_FILL = '`'
AUTO_GEN_MESSAGE = """
``````````````````````````````````````````````````````
``````````````````````````````````````````````````````
````````______________________________________ ``````
```````/ ... | trip()
if open:
message = message.replace(MESSAGE_FILL * len(open), open, 1)
if close:
message = reverse(reverse(message).replace(MESSAGE_FILL * len(close), close[::-1], 1))
if | fill:
message = message.replace(MESSAGE_FILL * len(fill), fill)
return message
def generate(template, config, out_file, pretty=False):
path, ext = os.path.splitext(out_file.name)
ext = ext[1:]
if pretty:
if ext == 'py':
out_file.write(auto_gen_message('#', '#', ''))
... |
cityscapesc/specobs | main/tools/USRP_N200_UBX40_Filter_Testing/GRC/FFTshift.py | Python | apache-2.0 | 837 | 0.04779 | #!/usr/bin/env python
from gnuradio import gr
from gnuradio import blocks
from gnuradio import digital
import numpy
#applies fftshift to a vecter.
#
class FFTshift(gr.basic_block):
#constructor
def __init__(self,size,drop_when_overloaded):
gr.basic_block.__init__(self, name="FFT_Shift",
in_sig=[(numpy.float32,s... | nput_items, output_items):
in0 = input_items[0]
out = output_items[0]
| if len(out) >= len(in0):
ps_len = len(in0)
consume_len = ps_len
elif self.drop_true:
ps_len = len(out)
consume_len = len(in0)
else:
ps_len = len(out)
consume_len = ps_len
for cnt in range(0,ps_len):
out[cnt] = numpy.fft.fftshift(in0[cnt])
self.consume_each(consume_len)
return ... |
bartoldeman/easybuild-easyblocks | easybuild/easyblocks/r/rosetta.py | Python | gpl-2.0 | 12,847 | 0.003269 | ##
# Copyright 2009-2018 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://www.vscentrum.be),
# Flemish Research Foundation (F... | elf.toolchain.comp_family() in [toolchain.GCC]: #@UndefinedVariable
cxx_ver = '.'.join(get_software_version('GCC').split('.')[:2])
elif self.toolchain.comp_family() in [toolchain.INTELCOMP]: #@UndefinedVariable
cxx_ver = '.'.join(get_icc_version().split('.')[:2])
else:
... | r))
if self.toolchain.options.get('usempi', None):
self.cfg.update('buildopts', 'extras=mpi')
defines.extend(['USEMPI', 'MPICH_IGNORE_CXX_SEEK'])
# make sure important environment variables are passed down
# e.g., compiler env vars for MPI wrappers
env_vars = {}... |
lemonad/jaikuengine | common/tests.py | Python | apache-2.0 | 2,923 | 0.008211 | # Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (None, 'stream/something/else'),
('duuom+aasdd@gmail.com', 'crazy/duuom+aasdd@gmail.com/dddfff$$%%///'),
('asdad@asdasd@asdasd', 'multi/asdad@asdasd@asdasd/cllad/asdff' | )]
for t in topics:
self.assertEqual(util.get_user_from_topic(t[1]), t[0], t[1])
# We're going to import the rest of the test cases into the local
# namespace so that we can run them as
# python manage.py test common.WhateverTest
from common.test.api import *
from common.test.clean import *
from common.tes... |
rkibria/yapyg | yapyg_widgets/screen_widget.py | Python | mit | 18,072 | 0.012561 | # Copyright (c) 2015 Raihan Kibria
#
# 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, distr... | ound_normal=background_file,
background_down=background_down_file,
| size_hint=(button_width, button_height),
pos_hint = {"x" : joystick_x, "y" : joystick_y},
)
else:
... |
frankosan/pypers | pypers/steps/picard/reordersam.py | Python | gpl-3.0 | 1,863 | 0.011809 | import os
from pypers.core.step import CmdLineStep
class ReorderSam(CmdLineStep):
spec = {
"version": "0.0.1",
"descr": [
"Runs ReorderSam to reorder chromosomes into GATK order"
],
"args":
{
"inputs": [
{
"name" ... | ={{input_bam}} O={{output_bam}} CREATE_INDEX=True R={{reference}}"
],
"requirem | ents": {
"memory": '8'
}
}
def preprocess(self):
"""
Set output bam name
"""
file_name = os.path.basename(self.input_bam)
self.output_bam = file_name.replace('.bam','.reord.bam')
super(ReorderSam, self).preprocess()
|
cpennington/edx-platform | pavelib/paver_tests/test_servers.py | Python | agpl-3.0 | 13,743 | 0.002401 | """Unit tests for the Paver server tasks."""
import ddt
from paver.easy import call_task
from ..utils.envs import Env
from .utils import PaverTestCase
EXPECTED_SASS_COMMAND = (
u"libsass {sass_directory}"
)
EXPECTED_COMMON_SASS_DIRECTORIES = [
u"common/static/sass",
]
EXPECTED_LMS_SASS_DIRECTORIES = [
u... | COOKIE_NAME={user_info_cookie_name} "
u"$(npm bin)/webpack --config={webpack_config_path}" |
)
@ddt.ddt
class TestPaverServerTasks(PaverTestCase):
"""
Test the Paver server tasks.
"""
@ddt.data(
[{}],
[{"settings": "aws"}],
[{"asset-settings": "test_static_optimized"}],
[{"settings": "devstack_optimized", "asset-settings": "test_static_optimized"}],
[{... |
imvu/bluesteel | app/logic/gitrepo/models/GitParentModel.py | Python | mit | 713 | 0.007013 | """ | Git Parent model """
from django.db import models
class GitParentEntry(models.Model):
""" Git Parent """
project = models.ForeignKey('gitrepo.GitProjectEntry', related_name='git_parent_project')
parent = models.ForeignKey('gitrepo.GitCommitEntry', related | _name='git_parent_commit')
son = models.ForeignKey('gitrepo.GitCommitEntry', related_name='git_son_commit')
order = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
def __unicode__(se... |
mikemoorester/ESM | nadirSiteSolution.py | Python | mit | 7,907 | 0.020362 | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
#import calendar
#import datetime as dt
#import pprint
#import pickle
import sys
def plotFontSize(ax,fontsize=8):
for item in ([ax.title, ax.xaxis.l... | vmax=15, lw=0)
cbar = plt.colorbar(polar,shrink=0.75,pad=.10)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('ESM (mm)',size=8)
ax = plotFontSize(ax,8)
plt.tight_layout()
fig = plt.figur | e()
#fig.canvas.set_window_title("All SVNs")
ax = fig.add_subplot(111,polar='true')
ax.set_theta_direction(-1)
ax.set_theta_offset(np.radians(90.))
ax.set_ylim([0,1])
ax.set_rgrids((0.00001, np.radians(20.)/np.pi*2, np.radians(40.)/np.pi*2,np.radians(60.)/np.pi*2,np.radians(80.)/np.pi*2),labels=... |
OCA/account-financial-reporting | account_financial_report/tests/test_trial_balance.py | Python | agpl-3.0 | 33,159 | 0.000513 | # Author: Julien Coux
# Copyright 2016 Camptocamp SA
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestTrialBalanceReport(common.TransactionCase):
def setUp(self):
super(TestTrialBalance... | "credit": receivable_debit,
"partner_id": partner.id,
"account_id": self.account301.id,
},
),
],
}
move = self.env["account.move"].create(move_vals)
move.post()
def _get_report_li... |
self, with_partners=False, account_ids=False, hierarchy_on="computed"
):
company = self.env.ref("base.main_company")
trial_balance = self.env["trial.balance.report.wizard"].create(
{
"date_from": self.date_start,
"date_to": self.date_end,
... |
JALusk/SuperBoL | tests/test_mag2flux.py | Python | mit | 2,006 | 0.011964 | import unittest
import numpy as np
from astropy import constants as const
from astropy import units as u
from .context import superbol
from superbol.mag2flux import *
from yaml import load
class TestMag2Flux(unittest.TestC | ase):
def setUp(self):
self.filter_band = "V"
self.magnitude = 8.8
self.uncertainty = 0.02
self.effective_wl = 5450.0 * u.AA
self.flux_at_zero_mag = 3.631E-9 * (u.erg / (u.s * u.cm**2 * u.AA))
def test_mag2flux_converts_mag_to_correct_flux(self):
expected ... | ude)
result_flux, result_uncertainty = mag2flux(self.magnitude,
self.uncertainty,
self.effective_wl,
self.flux_at_zero_mag)
... |
kingvuplus/gui_test4 | upgrade.py | Python | gpl-2.0 | 3,532 | 0.003681 | #Embedded file name: /usr/lib/enigma2/python/upgrade.py
import os
from subprocess import Popen, PIPE
opkgDestinations = ['/']
opkgStatusPath = ''
overwriteSettingsFiles = False
overwriteDriversFiles = True
overwriteEmusFiles = True
overwritePiconsFiles = True
overwriteBootlogoFiles = True
overwriteSpinnerFiles = True
... | pkg/status'
if os.path.exists(os.path.join(mount, opkgStatusPath)):
opkgAddDestination(mount)
def getValue(line):
dummy = line.split('=')
if len(dummy) != 2:
print 'Error: Wr | ong formatted settings file'
exit
if dummy[1] == 'false':
return False
elif dummy[1] == 'true':
return True
else:
return False
p = Popen('opkg list-upgradable', stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stderr != '':
print 'Error occured:... |
eicher31/compassion-switzerland | report_compassion/models/contract_group.py | Python | agpl-3.0 | 5,996 | 0.001167 | ##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... | rint,
returns the list of months grouped by the frequency payment
of the contract group and only containing unpaid sponsorships.
:param months: list of dates (date, datetime or string)
:param sponsorships: recordset of included sponsorships
:return: list of dates grouped in strin... | d
# Take first open invoice or next_invoice_date
open_invoice = min([i for i in sponsorships.mapped("first_open_invoice") if i])
if open_invoice:
first_invoice_date = open_invoice.replace(day=1)
else:
raise UserError(_("No open invoice found !"))
for i, m... |
Deepomatic/DIGITS | digits/model/images/forms.py | Python | bsd-3-clause | 3,851 | 0.001298 | # Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from wtforms import validators
from ..forms import ModelForm
from digits import utils
class ImageModelForm(ModelForm):
"""
Defines the form used to create a new ImageModelJob
"""
crop_size = ... | ),
],
default='none',
tooltip="Randomly flips each image during batch preprocessing."
)
aug_quad_rot = utils.forms.SelectField(
'Quadrilateral Rotation',
choices=[
('none', 'None'),
('rot90', '0, 90 or 270 degrees'),
('rot180', '0 or 1... | degree steps) each image during batch preprocessing."
)
aug_rot = utils.forms.IntegerField(
'Rotation (+- deg)',
default=0,
validators=[
validators.NumberRange(min=0, max=180)
],
tooltip="The uniform-random rotation angle that will be performed during batch ... |
laborautonomo/Mailpile | mailpile/plugins/setup_magic.py | Python | apache-2.0 | 40,094 | 0.000499 | import os
import random
import sys
from datetime import date
from urllib import urlencode
import mailpile.auth
from mailpile.defaults import CONFIG_RULES
from mailpile.i18n import ListTranslations, ActivateTranslation, gettext
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpil... | : _('Blank'),
},
'Drafts': {
'type': 'drafts',
'flag_editable': True,
'display': 'priority',
'display_order': 1,
'icon': 'icon-compose',
'label_color': '03-gray-dark',
'name': _('Drafts'),
},
'Outbox': {
... | ': _('Outbox'),
},
'Sent': {
'type': 'sent',
'display': 'priority',
'display_order': 4,
'icon': 'icon-sent',
'label_color': '03-gray-dark',
'name': _('Sent'),
},
'Spam': {
'type': 'spam',
'fla... |
thunderhoser/GewitterGefahr | gewittergefahr/deep_learning/input_examples.py | Python | mit | 103,640 | 0.000251 | """Deals with input examples for deep learning.
One "input example" is one storm object.
--- NOTATION ---
The following letters will be used throughout this module.
E = number of examples (storm objects)
M = number of rows in each radar image
N = number of columns in each radar image
H_r = number of radar heights
F... | _TIMES_KEY, TARGET_MATRIX_KEY
]
METADATA | _KEYS = [
TARGET_NAMES_KEY, ROTATED_GRIDS_KEY, ROTATED_GRID_SPACING_KEY,
RADAR_FIELDS_KEY, RADAR_HEIGHTS_KEY, SOUNDING_FIELDS_KEY,
SOUNDING_HEIGHTS_KEY
]
TARGET_NAME_KEY = 'target_name'
TARGET_VALUES_KEY = 'target_values'
EXAMPLE_DIMENSION_KEY = 'storm_object'
ROW_DIMENSION_KEY = 'grid_row'
COLUMN_DIMENSI... |
codewarrior0/pytest | _pytest/python.py | Python | mit | 84,482 | 0.002 | """ Python test discovery, setup and run of test functions. """
import re
import fnmatch
import functools
import py
import inspect
import sys
import pytest
from _pytest.mark import MarkDecorator, MarkerError
from py._code.code import TerminalRepr
try:
import enum
except ImportError: # pragma: no cover
# Only ... | e, yieldctx=True)(scope)
else:
return FixtureFunctionMarker(scope, params, auto | use,
yieldctx=True, ids=ids)
defaultfuncargprefixmarker = fixture()
def pyobj_property(name):
def get(self):
node = self.getparent(getattr(pytest, name))
if node is not None:
return node.obj
doc = "python %s object this node was collected from (... |
aptuz/mezzanine_onepage_theme | one_page/customapp/templatetags/testtag.py | Python | mit | 1,240 | 0.004032 | from __future__ import unicode_literals
from future.builtins import int
from collections import defaultdict
from django.core.urlresolvers import reverse
from django.template.defaultfilters import linebreaksbr, urlize
from mezzanine import template
from mezzanine.conf import settings
from mezzanine.generic.forms impo... | status', 'title', 'titles', 'updated']
output = []
# import pdb;pdb.set_trace()
AllPa | ges = RichTextPage.objects.all()
for item in AllPages:
temp = {}
for fld in page_fields:
temp[fld] = getattr(item, fld)
output.append(temp)
return {
'pages': output
}
@register.filter()
def remove_slash(value):
return '#' + value[1:-1]
@register.filter()
de... |
EPiCS/soundgates | hardware/tools/to_samples.py | Python | mit | 505 | 0.017822 | #!/usr/bin/env python
# coding: utf8
import sys;
import struct;
def do_convert(filename):
fid_in = open(filename, 'rb')
fid_out = open('s | ound_conv.out','w')
data = fid_in.read(4) # read 4 bytes = 32 Bit Sample
while data:
ser = str(struct.unpack('<i', data)[0]) + '\n'
fid_out.write(ser)
data = fid_in.read(4)
fid_in.close()
fid_out.close()
if __name__ == "__main__":
pri | nt "Converting..."
do_convert(sys.argv[1])
print "done"
|
IsmaelRLG/UserBot | mods/translate/__init__.py | Python | mit | 817 | 0.015912 | # -*- coding: utf-8 -*-
"""
UserBot module
Copyright 2015, Ismael R. Lugo G.
"""
import translate
reload(translate)
from sysb import commands
from translate import lang
from translate impor | t _
commands.addHandler('translate', '(tr|translate)2 (?P<in>[^ ]+) (?P<out>[^ ]+) '
'(?P<text>.*)', {'sintax': 'tr2 <input> <output> <text>',
'example': 'tr2 en es Hello!',
'alias': ('traslate2',),
'desc': _('Traduce un texto de un idioma a otro', lang)},
anyuser=True)(tra | nslate.translate2_1)
commands.addHandler('translate', '(tr|translate) (?P<in>[^ ]+) (?P<out>[^ ]+) ('
'?P<text>.*)', {'sintax': 'tr <input> <output> <text>',
'example': 'tr en es Hello!',
'alias': ('traslate',),
'desc': _('Traduce un texto de un idioma a otro', lang)},
anyuser=True)(translate.tran... |
tokyo-jesus/university | src/python/koans/python3/runner/path_to_enlightenment.py | Python | unlicense | 4,893 | 0.000204 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The path to enlightenment starts with the following:
import unittest
from koans.about_asserts import AboutAsserts
from koans.about_strings import AboutStrings
from koans.about_none import AboutNone
from koans.about_lists import AboutLists
from koans.about_list_assignme... | suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithFunctions))
suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithCla | sses))
suite.addTests(loader.loadTestsFromTestCase(AboutInheritance))
suite.addTests(loader.loadTestsFromTestCase(AboutMultipleInheritance))
suite.addTests(loader.loadTestsFromTestCase(AboutScope))
suite.addTests(loader.loadTestsFromTestCase(AboutModules))
suite.addTests(loader.loadTestsFromTestCase... |
TheTrueH4cks0r/YeagerBomb | FiLe_AD.py | Python | gpl-3.0 | 315 | 0.060317 | from dateti | me import datetime
path= str(datetime.now().date())
per= datetime.now()
per_h= str(per.hour)
per_m= str(per.minute)
timeit= str("%s:%s"%(per_h,per_m))
def Final(file_name):
NPfile= str("%s-%s"%(file_name,timeit))
A_Dump= "airodump-ng wlan0 -w "
ADFN= A_Dump+NPfile
return AD | FN
|
hekra01/mercurial | contrib/import-checker.py | Python | gpl-2.0 | 8,337 | 0.001679 | import ast
import os
import sys
# Import a minimal set of stdlib modules needed for list_stdlib_modules()
# to work when run from a virtualenv. The modules were chosen empirically
# so that the return value matches the return value without virtualenv.
import BaseHTTPServer
import zlib
def dotted_name_of_path(path, t... | dirname.startswith(prefix):
# Then this directory is redundant.
break
else:
stdlib_prefixes.add(dirname)
for libpath in sys.path:
# We want to walk everything in sys.path that starts with
# something in stdlib_prefixes. check-code suppressed becaus... | # the ast module used by this script implies the availability
# of any().
if not any(libpath.startswith(p) for p in stdlib_prefixes): # no-py24
continue
if 'site-packages' in libpath:
continue
for top, dirs, files in os.walk(libpath):
for name in... |
antoinecarme/pyaf | tests/artificial/transf_RelativeDifference/trend_ConstantTrend/cycle_0/ar_12/test_artificial_1024_RelativeDifference_ConstantTrend_0_12_20.py | Python | bsd-3-clause | 279 | 0.082437 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 0, transform | = "RelativeDifference", sigma = 0.0, exog_co | unt = 20, ar_order = 12); |
Jimdo/thrift | test/features/string_limit.py | Python | apache-2.0 | 1,665 | 0.001201 | #!/usr/bin/env python
import argparse
import sys
from util import add_common_args, init_protocol
from local_thrift import thrift
from thrift.Thrift import TMessageType, TType
# TODO: generate from ThriftTest.thrift
def test_string(proto, value):
method_name = 'testString'
ttype = TType.STRING
proto.writ... | , type=int)
args = p.parse_args()
proto = init_protocol(args)
test_string(proto, 'a' * (args.limit - 1))
test_string(proto, 'a' * (args.limit - 1))
print('[OK]: limit - 1')
test_str | ing(proto, 'a' * args.limit)
test_string(proto, 'a' * args.limit)
print('[OK]: just limit')
try:
test_string(proto, 'a' * (args.limit + 1))
except:
print('[OK]: limit + 1')
else:
print('[ERROR]: limit + 1')
assert False
if __name__ == '__main__':
main(sys.argv[1:... |
pyocd/pyOCD | pyocd/target/builtin/target_lpc4088qsb.py | Python | apache-2.0 | 5,692 | 0.01669 | # pyOCD debugger
# Copyright (c) 2006-2016 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | 0xf44f0f01, 0xbf145000, 0x619061d0,
0x5f20f1b5, 0x46 | 22d305, 0x5020f1a5, 0x41f0e8bd, 0xf5b5e6bd, 0xd3052f00, 0xf5a54622, 0xe8bd2000,
0xe6b441f0, 0xe9d4b975, 0x44080100, 0x1202e9d4, 0x44084411, 0x44086921, 0x44086961, 0x440869a1,
0x61e04240, 0x28100b28, 0x210ebf24, 0x00d0eb01, 0x4e1e2132, 0x8078f8df, 0xe9c6444e, 0x60b01000,
0x0114f106, 0x47c04630, 0xb9886970, ... |
mattjmorrison/ReportLab | src/reportlab/pdfbase/pdfdoc.py | Python | bsd-3-clause | 83,521 | 0.009279 | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfbase/pdfdoc.py
__version__=''' $Id: pdfdoc.py 3795 2010-09-30 15:52:16Z rgbecker $ '''
__doc__="""
The module pdfdoc.py handles the 'outer structure... | r(cat)) # initialize with timestamp digest
# mapping of internal identifier ("Page001") to PDF objectnum | ber and generation number (34, 0)
self.idToObjectNumberAndVersion = {}
# mapping of internal identifier ("Page001") to PDF object (PDFPage instance)
self.idToObject = {}
# internal id to file location
self.idToOffset = {}
# number to id
self.numberToId = {}
... |
danielvdende/incubator-airflow | airflow/contrib/hooks/wasb_hook.py | Python | apache-2.0 | 5,899 | 0 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | =conn.password, **service_options)
def check_for_blob(self, container_name, blob_name, **kwargs):
"""
Check if a blob exists on Azure Bl | ob Storage.
:param container_name: Name of the container.
:type container_name: str
:param blob_name: Name of the blob.
:type blob_name: str
:param kwargs: Optional keyword arguments that
`BlockBlobService.exists()` takes.
:type kwargs: object
:return... |
kyouko-taiga/mushi | mushi/apps/webui/views.py | Python | apache-2.0 | 1,256 | 0.001592 | # Copyright 2015 Dimitri Racordon
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | .
from flask import Blueprint, current_app, redirect, render_template, url_for
from mushi.core.auth import parse_auth_token, require_auth_token, validate_auth_token
from mushi.core.exc import AuthenticationError
bp = Blueprint('views', __name__)
@bp.route('/')
@require_auth_token
def index(auth_token):
return ... | n = parse_auth_token()
validate_auth_token(auth_token)
return redirect(url_for('views.index'))
except AuthenticationError:
return render_template('login.html', api_root=current_app.config['API_ROOT'])
|
atlefren/beercalc | db_repository/versions/006_migration.py | Python | mit | 884 | 0.001131 | from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
user = Table('u | ser', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
| Column('username', String(length=64)),
Column('email', String(length=120)),
Column('role', SmallInteger, default=ColumnDefault(0)),
Column('name', String(length=120)),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadat... |
kbrebanov/ansible-modules-extras | monitoring/logentries.py | Python | gpl-3.0 | 4,638 | 0.00539 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Ivan Vanderbyl <ivan@app.io>
#
# This module 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 la... | (' '.join(cmd))
if not query_log_status(module, le_path, log):
module.fail_json(msg="failed to follow '%s': %s" % (log, err.strip()))
followed_count += 1
if followed_count > 0:
module.exit_json(changed=True, msg="followed %d log(s)" % (followed_count,))
module.exit_json(c... | loop incase of error, we can report the package that failed
for log in logs:
# Query the log first, to see if we even need to remove.
if not query_log_status(module, le_path, log):
continue
if module.check_mode:
module.exit_json(changed=True)
rc, out, err = m... |
kern3020/opportunity | opportunity/settings/prod.py | Python | mit | 575 | 0.006957 | import dj_database_url
import os
from .base import *
# Parse database configurati | on from $DATABASE_URL
DATABASES = { 'default': {} }
DATABASES['default'] = dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static asset configuration
BASE_DIR = | os.path.join(os.path.dirname(os.path.abspath(__file__)),'..')
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
|
fpeder/mscr | bin/db_ext_split.py | Python | bsd-2-clause | 1,070 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Usage: db_ext_split.py <src> <dst> <prob>
Options:
-h --help
"""
import os
import cv2
from glob import glob
from docopt import docopt
from mscr.split import Split, RandomSplitPredicate
from mscr.util import Crop
from mscr.data import MyProgressBar
PAD = 8
if ... | ['<src>']
dst = args['<dst>']
prob = float(args['<prob>'])
split = Split(RandomSplitPredicate(p=prob))
crop = Crop()
count = 0
if os.path.exists(src) and os.path.exists(dst):
filz = glob(os.path.join(src, '*.jpg'))
pbar = MyProgressBar(len(filz), 'extending db:')
for im ... | for bl in split.run(img):
out = os.path.join(dst, str(count).zfill(PAD) + '.jpg')
cv2.imwrite(out, bl.img)
count += 1
pbar.update()
pbar.finish()
else:
print 'err: dimstat.py: path doesn\'t exists'
|
jetskijoe/SickGear | sickbeard/db.py | Python | gpl-3.0 | 19,942 | 0.002507 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear 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,... | . If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os.path
import re
import sqlite3
import time
import threading
import sickbeard
from sickbeard import encodingKludge as ek
from sickbeard import logger
from sickbeard.exceptions import ex
import helpers
db_lock = threading.L... | will be made to be sickbeard.db
@param suffix: The suffix to append to the filename. A '.' will be added
automatically, i.e. suffix='v0' will make dbfile.db.v0
@return: the correct location of the database file.
"""
if suffix:
filename = '%s.%s' % (filename, suffix)
... |
chartmogul/chartmogul-python | chartmogul/api/plan.py | Python | mit | 727 | 0 | from marshmallow import Schema, fields, post_load, EXCLUDE
from ..resource import Resource
from collec | tions import namedtuple |
class Plan(Resource):
"""
https://dev.chartmogul.com/v1.0/reference#plans
"""
_path = "/plans{/uuid}"
_root_key = 'plans'
_many = namedtuple('Plans', [_root_key, "current_page", "total_pages"])
class _Schema(Schema):
uuid = fields.String()
data_source_uuid = fields.String... |
limodou/parm | parm/utils.py | Python | bsd-2-clause | 10,640 | 0.004229 | from __future__ import print_function
from ._compat import string_types
import os
import re
import logging
import inspect
import datetime
import decimal
log = logging
def safe_import(path):
module = path.split('.')
g = __import__(module[0], fromlist=['*'])
s = [module[0]]
for i in module[1:]:
... | os.path.join(dst, r), verbose, exclude, exclude_ext, recursion, replace)
else:
ext = os.path.splitext(fpath)[1]
if ext in exclude_ext or ext in default_exclude_ext:
| continue
extract_file(mod, fpath, dst, verbose, replace)
def match(f, patterns):
from fnmatch import fnmatch
flag = False
for x in patterns:
if fnmatch(f, x):
return True
def walk_dirs(path, include=None, include_ext=None, exclude=None,
... |
dave-shawley/ietfparse | tests/test_datastructure.py | Python | bsd-3-clause | 3,585 | 0 | import unittest
from ietfparse.datastructures import ContentType
class ContentTypeCreationTests(unittest.TestCase):
def test_that_primary_type_is_normalized(self):
self.assertEqual('contenttype',
ContentType('COntentType', 'b').content_type)
def test_that_subtype_is_normaliz... | rs={
'KEY': 'Value'
| }).parameters)
class ContentTypeStringificationTests(unittest.TestCase):
def test_that_simple_case_works(self):
self.assertEqual('primary/subtype',
str(ContentType('primary', 'subtype')))
def test_that_parameters_are_sorted_by_name(self):
ct = ContentTyp... |
DavisNT/mopidy-playbackdefaults | tests/test_frontend.py | Python | apache-2.0 | 5,145 | 0.000972 | import unittest
import mock
from mopidy_playbackdefaults import PlaybackDefaultsFrontend
class PlaybackDefaultsFrontendTest(unittest.TestCase):
def test_no_settings(self):
config = {'playbackdefaults': {'default_random': '', 'default_repeat': '', 'default_consume': '', 'default_single': ''}}
co... | self.assertEqual(core.tracklist.set_repeat.call_count, 0)
self.assertEqual(core.tracklist.set_consume.call_count, 0)
self.assertEqual(core.tracklist.set_single.call_count, 0)
PlaybackDefaultsFrontend(config, core)
self.assertEqual(core.tracklist.set_random.call_count, 0)
... | l_count, 0)
def test_random(self):
config = {'playbackdefaults': {'default_random': '', 'default_repeat': '', 'default_consume': '', 'default_single': ''}}
core = mock.Mock()
self.assertEqual(core.tracklist.set_random.call_count, 0)
self.assertEqual(core.tracklist.set_repeat.call_co... |
rtapadar/pscan | pscan/tests/test_scan.py | Python | apache-2.0 | 5,489 | 0.00419 | # Copyright 2016 Rudrajit Tapadar
#
# 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... | alue().strip(), output)
@mock.patch('socket.socket.connect')
def test_udp_port_open(self, mock_connect):
hosts = "127.0.0.1"
ports = "53"
mock_connect.return_value = None
scanner = self.get_scanner_obj(hosts, ports)
scanner.udp()
#h = self.get_host_obj(hosts, [22... | 0].status = "Open"
#self.assertPortsEqual(scanner.hosts[0].ports,
# h[0].ports)
|
khs26/pele | examples/frozen_degrees_of_freedom/frozen_lj.py | Python | gpl-3.0 | 1,133 | 0.002648 | """
this example shows how to freeze degrees of freedom using the Lennard Jones potential as
an example
"""
import numpy as np
| from pele.potentials import LJ, FrozenPotentialWrapper
from pele.optimize import mylbfgs
def main():
natoms = 4
pot = LJ()
reference_coords = np.random.uniform(-1, 1, [3 * natoms])
print reference_coords
# freeze the firs | t two atoms (6 degrees of freedom)
frozen_dof = range(6)
fpot = FrozenPotentialWrapper(pot, reference_coords, frozen_dof)
reduced_coords = fpot.get_reduced_coords(reference_coords)
print "the energy in the full representation:"
print pot.getEnergy(reference_coords)
print "is the same as the e... |
jimmysitu/jBenchmark | micro-benchmark/MixBurnIn/MixBurnIn.py | Python | gpl-2.0 | 4,944 | 0.002629 | #!/usr/bin/env python3
from optparse import OptionParser
from datetime import datetime
from datetime import timedelta
import pyopencl as cl
import numpy as np
import time
MIN_ELAPSED = 0.25
KEY_LENGTH = 64
BUF_MAX_SIZE= 1024 * 1024
class BurnInTarget():
def __init__(self, platform, kernel):
self.name = ... | ed.total_seconds())
t.minXSize = xsize
t.minYSize = ysize
print("Final min size: %d, %d" % (t.minXSize, t.minYSize))
# Burn in one by one
time.sleep(20)
for t in target | s:
print("Burning platform: %s" % t.name)
startTime = datetime.utcnow()
events =[]
# Make sure this is longer than Tu of PL2
for i in range(16):
events.append(t.burn((8*t.minXSize, 2*t.minYSize)))
for e in events:
e.wait()
endTime = date... |
SamR1/OpenCityLab-dataviz | functions.py | Python | gpl-3.0 | 4,740 | 0.005274 | #
# #/usr/bin/env python3
# -*- coding:utf-8 -*-
from database import Measure
import json
import requests
import time
import yaml
with open("param.yml", 'r') as stream:
try:
param = yaml.load(stream)
except yaml.YAMLError as e:
print(e)
def getkwatthours(url, data, headers, sensorId, t0, t1)... | ta():
items = param['listItems'] # items must be defined in param.yml
lastData = []
for item in items:
query = Measure.query.filter_by(item=item).order_by(Measure.timestamp.desc()).first()
print(query)
itemData = {}
itemData["id"] = item
itemData["name"] = p | aram[item]['name']
itemData["type"] = param[item]['type']
itemData["lat"] = param[item]['lat']
itemData["lon"] = param[item]['lon']
if query is None:
itemData["value"] = 0
else:
itemData["value"] = query.value
lastData.append(itemData.copy())
... |
JoshuaOndieki/buckylist | bucky/helpers.py | Python | mit | 710 | 0.002817 | """
Module contains helper functions
"""
def get_user(username, db):
"""
Usage: queries through and database and returns user
object with passed username argument
:return: User object or None if no such user
"""
for user in db:
if user.username.lower() | == username.lower():
return user
return None
def get_bucket(title, db, current_user):
"""
Usage: queries through and database and returns bucket
object with passed title argument
:return: Bucket object or None if no such Bucket
"""
for bucket in db:
... | e.lower():
return bucket
return None
|
qedsoftware/commcare-hq | corehq/doctypemigrations/migrations/0004_auto_20151001_1809.py | Python | bsd-3-clause | 527 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from corehq.doctypemigra | tions.djangomigrations import assert_initial_complete
from corehq.doctypemigrations.migrator_instances import users_migration
from corehq.sql_db.operations import HqRunPython
class Migration(migrations.Migration):
dependencies = [
| ('doctypemigrations', '0003_doctypemigration_cleanup_complete'),
]
operations = [
HqRunPython(assert_initial_complete(users_migration))
]
|
kpreid/shinysdr | shinysdr/interfaces.py | Python | gpl-3.0 | 11,304 | 0.007432 | # -*- coding: utf-8 -*-
# Copyright 2013, 2014, 2015, 2016, 2017, 2018 Kevin Reid and the ShinySDR contributors
#
# This file is part of ShinySDR.
#
# ShinySDR 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,... | """
Return whether this demodulator can reconfigure itself to demodulate the specified mode.
If it returns False, it will typically be replaced with a newly created demodulator.
"""
def set_mode(mode):
"""
Per can_set_mode.
"""
__all__.append('ID... | # TODO: BandShape doesn't really belong here but it is related to IDemodulator. Find better location.
# All frequencies are relative to the demodulator's input signal (i.e. baseband)
_BandShape = namedtuple('BandShape', [
'stop_low', # float; lower edge of stopband
'pass_low', # float; lower edge of passband... |
tboyce021/home-assistant | homeassistant/components/hue/light.py | Python | apache-2.0 | 14,995 | 0.001067 | """Support for the Philips Hue lights."""
from datetime import timedelta
from functools import partial
import logging
import random
import aiohue
import async_timeout
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_FLASH,
ATTR_HS_COLOR,
ATTR_TRA... | etting gamut to None."
| _LOGGER.warning(err, self.name, str(self.gamut))
self.gamut_typ = GAMUT_TYPE_UNAVAILABLE
self.gamut = None
@property
def unique_id(self):
"""Return the unique ID of this Hue light."""
return self.light.uniqueid
@property
def device_i... |
snowfarthing/nibbles_3d | vertex.py | Python | mit | 6,509 | 0.020126 | # vertex.py
# This module contains all the things for creating
# and using vertices...starting with vector, and
# going on to edge and face.
# Observe two things, though:
# First, I tried to keep small numbers as "zeros"
# by rounding divisions (see __div__ and norm) to
# five significant digits. So if a number i... | if v1 < v2:
self.v1 = v1
self.v2 = v2
else:
self.v1 = v2
self.v2 = v1
self.color = color
def __eq__(self, e):
"""Returns true if both vertex indices are equal."""
return (self.v1 == e.v1) and (self.v2 == e.v2)
def __ne__(self, e):
"""Returns ... | eturn "[ %s, %s ] %s" % (self.v1, self.v2, self.color)
class face(object):
def __init__(self, vertices, edges, color='none'):
"""Initializes a face for a wireframe.
In addition to vertices and color, this class also
keeps track of edges, center, normal and norm*Vertex
of the face.
No... |
ltiao/basketball-intelligence | bball_intel/bball_intel/wsgi.py | Python | mit | 437 | 0.004577 | """
WSGI config for bball_intel project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
i | mport o | s
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bball_intel.settings.base")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
|
skoczen/qi-toolkit | qi_toolkit/boltbase.py | Python | bsd-3-clause | 27,252 | 0.007339 | # A base file for use in fabfiles.
# This file is geared toward a particular directory structure on webfaction and in dev
# Some of it may be useful to other folks, but no guarantees.
# Local Structure
# /
# /db (sqllite for dev and dumps)
# /media
# /appname
# /source (psds and the like)
# Remote Structure (webfact... | .system_u | ser,'h':h} for h in env.staging_hosts]
env.production_db_hosts = ["%(system_user)s@%(h)s" % {'system_user':env.system_user,'h':h} for h in env.production_db_hosts]
env.staging_db_hosts = ["%(system_user)s@%(h)s" % {'system_user':env.system_user,'h':h} for h in env.staging_db_hosts]
if env.system_user == "r... |
cniswander/clipocr | clipocr1.py | Python | bsd-3-clause | 6,229 | 0.013004 |
"""
clipocr1.py
Demonstrates a technique that often improves ocr quality on screen captures.
Reads an image from the system clipboard,
and writes to stdout various versions of the text recognized in the image.
Uses tesseract OCR.
The technique is based on judicious rescaling of image dimensions.
... | s,
based on resizing the image to different size image files,
and prints multiple OCR attempts' text.
"""
def params_textname(params):
"""Given /params/, a resize method specification from resize_methods,
constructs a text string that can be used in a filename
for a resized/r | escaled image.
"""
params = params[0][0], params[0][1], params[1]
return '_'.join([str(x).strip() for x in params])
# do ocr on original, non-rescaled image.
print 'ORIGINAL IMAGE:'
print do_ocr_to_imagefile(fname)
im1 = Image.open(fname)
# List of image resizing methods to try.
# Each met... |
msmbuilder/msmbuilder-legacy | Extras/parallel_assign/scripts/AssignParallel.py | Python | gpl-2.0 | 7,120 | 0.007022 | #!/usr/bin/env python
import sys, os
import numpy as np
import logging
import IPython as ip
from IPython import parallel
from IPython.parallel.error import RemoteError
from msmbuilder import arglib
from msmbuilder import metrics
from msmbuilder import Project
from parallel_assign import remote, local
def setup_logge... | cept RemoteError as e:
print 'Remote Error:'
e.print_traceback()
raise
vtraj_id = local.save(f_assignments, f_distances, assignments, distances, chunk)
log_status(logger, len(pending), n_jobs, vtraj_id, async)
... | async_result):
"""After a job has completed, log the status of the map to the console
Parameters
----------
logger : logging.Logger
logger to print to
n_pending : int
number of jobs still remaining
n_jobs : int
total number of jobs in map
job_id : int
t... |
Yelp/paasta | tests/api/test_client.py | Python | apache-2.0 | 1,486 | 0.000673 | # Copyright 2015-2016 Yelp 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 writin | g, 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 mock
from paasta_tools.api.client import get_paasta_oapi_client
from paasta_tools.api.client import renew_issue_cert
def test_get_paasta_oapi_client(system_paasta_config):
with mock.patch(
"paasta_tool... |
luci/luci-py | appengine/components/test_support/test_case.py | Python | apache-2.0 | 11,348 | 0.009076 | # Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import base64
import contextlib
import datetime
import json
import logging
import time
import webtest
from google.appengine.datastore import dat... |
from depot_tools import auto_stub
# W0212: Access to a protected member XXX of a client class
# pylint: disable=W0212
def mock_now(test, now, seconds):
"""Mocks utcnow() and ndb properties.
In particular handles when auto_now and auto_now_add are used.
"""
now = now + datetime.timedelta(seconds=seconds)
... | stub.TestCase):
"""Support class to enable more unit testing in GAE.
Adds support for:
- google.appengine.api.mail.send_mail_to_admins().
- Running task queues.
"""
# See APP_DIR to the root directory containing index.yaml and queue.yaml. It
# will be used to assert the indexes and task queues are pr... |
wbsavage/shinken | shinken/modules/syslog_broker.py | Python | agpl-3.0 | 1,841 | 0.001086 | #!/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... | he License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have r... | tp://www.gnu.org/licenses/>.
# This Class is a plugin for the Shinken Broker. It is in charge
# to brok log into the syslog
import syslog
from shinken.basemodule import BaseModule
from shinken.log import logger
properties = {
'daemons': ['broker'],
'type': 'syslog',
'external': False,
'phases': ['r... |
mbi/django-simple-captcha | setup.py | Python | mit | 2,125 | 0.000471 | import sys
from captcha import get_version as get_captcha_version
from setuptools import find_packages, setup
from setuptools.command.test import test as test_command
class Tox(test_command):
user_options = [("tox-args=", "a", "Arguments to pass to tox")]
def initialize_options(self):
test_command.i... | nse",
"Operating System :: OS Independent",
" | Programming Language :: Python",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Security",
"Topic :: Internet :: WWW/HTTP",
"Framework :: Django",
],
include_package_data=True,
... |
bninja/rump | rump/request.py | Python | isc | 10,243 | 0.000293 | import base64
import copy
import inspect
import logging
import re
import urlparse
import pilo
from . import Expression, exp, types
logger = logging.getLogger(__name__)
__all__ = [
'PathMixin',
'String',
'Boolean',
'Integer',
'IPAddress',
'IPNetwork',
'NamedTuple'
'StringHash',
'A... | munge(self, value):
return dict(
| (match.group(0).lower(), value)
for _, match, value in super(HeaderHash, self)._munge(value)
)
def __getattr__(self, name):
return StringSubField(self, name)
def contains(self, item):
return exp.FieldContains(self, item)
class BasicAuthorization(types.NamedTuple)... |
Microvellum/Fluid-Designer | win64-vc/2.78/scripts/templates_py/operator_node.py | Python | gpl-3.0 | 1,429 | 0 | import bpy
def main(operator, context):
space = context.space_data
node_tree = space.node_tree
node_active = context.active_node
node_selected = context.selected_nodes
# now we have the context, pe | rform a simple operation
if node_active in node_selected:
node_selected.remove(node_active)
if len(node_selected) | != 1:
operator.report({'ERROR'}, "2 nodes must be selected")
return
node_other, = node_selected
# now we have 2 nodes to operate on
if not node_active.inputs:
operator.report({'ERROR'}, "Active node has no inputs")
return
if not node_other.outputs:
operator.rep... |
acesonl/remotecare | remotecare/apps/questionnaire/rheumatism/__init__.py | Python | gpl-3.0 | 114 | 0 | # -*- coding: utf-8 -*-
"" | "
This package contains all the forms and models
for the rheumatism questionnaires.
"" | "
|
Tilo15/PhotoFiddle2 | PF2/Tools/HueEqualiser.py | Python | gpl-3.0 | 5,526 | 0.005972 | import cv2
import numpy
import Tool
class HueEqualiser(Tool.Tool):
def on_init(self):
self.id = "hueequaliser"
self.name = "Hue Equaliser"
self.icon_path = "ui/PF2_Icons/HueEqualiser.png"
self.properties = [
Tool.Property("header", "Hue Equaliser", "Header", None, has_t... | "Slider", 0.25, max=2.0, min=0.0),
# Red
Tool.Property("header_red", "Red", "Header", None, has_toggle=False, has_button=False),
| Tool.Property("red_value", "Value", "Slider", 0, max=50, min=-50),
Tool.Property("red_saturation", "Saturation", "Slider", 0, max=50, min=-50),
# Yellow
Tool.Property("header_yellow", "Yellow", "Header", None, has_toggle=False, has_button=False),
Tool.Property("yell... |
HERA-Team/hera_mc | scripts/mc_listen_to_corr_logger.py | Python | bsd-2-clause | 3,281 | 0.000914 | #! /usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2018 the HERA Collaboration
# Licensed under the 2-clause BSD license.
"""Gather correlator log outputs and log them into M&C."""
import sys
import json
import redis
import socket
import logging
from astropy.time import Time
from hera_mc impor... | message_dict["subsystem"],
| message_dict["severity"],
message_dict["message"],
)
session.add_daemon_status(
"mc_listen_to_corr_logger", hostname, Time.now(), "good"
)
session.commit()
except KeyboardInte... |
shivam1111/python-fedex | fedex/services/rate_service.py | Python | bsd-3-clause | 5,261 | 0.004752 | """
Rate Service Module
===================
This package contains classes to request pre-ship rating information and to
determine estimated or courtesy billing quotes. Time in Transit can be
returned with the rates if it is specified in the request.
"""
from datetime import datetime
from .. base_service import FedexBa... | ""
# Default behavior is to not request transit information
self.ReturnTransitAndCommit = False
# This is the primary data structure for processShipment requests.
self.RequestedShipment = self.client.factory.create('RequestedShipment')
self.RequestedShipment.ShipTimestamp = dat... | ')
# Start at nothing.
TotalWeight.Value = 0.0
# Default to pounds.
TotalWeight.Units = 'LB'
# This is the total weight of the entire shipment. Shipments may
# contain more than one package.
self.RequestedShipment.TotalWeight = TotalWeight
# T... |
p5py/p5 | p5/pmath/tests/test_utils.py | Python | gpl-3.0 | 874 | 0 | import unittest
from p5.pmath.utils import (
constrain,
lerp,
remap,
normalize,
magnitude,
distance,
sq)
class TestUtils(unittest.TestCase):
def test_constrain(self):
self.assertEqual(constrain(5, 0, 10), 5)
self.assertEqual(constrain(-10, 0, 10), 0)
self.asse... | 5)
def test_magnitude(self):
self.assertEqual(magnitude(3, 4), 5)
def test_distance(self):
self.assertEqual(distance((0, 0, 0), (2, 3, 6)), 7)
def test_sq(self):
| self.assertEqual(sq(4), 16)
if __name__ == "__main__":
unittest.main()
|
BGCECSE2015/CADO | PYTHON/NURBSReconstruction/DooSabin/DualCont_toABC_simple.py | Python | bsd-3-clause | 4,309 | 0.02019 | __author__ = 'erik'
import numpy as np
from PetersScheme.Edge import Edge
from PetersScheme.Quad import Quad
from PetersScheme.Vertex import Vertex
def getABsC_ind(quadIndex, indVertex, indOtherVertex, regularPoints):
'''
:param _quad:
:param indVertex:
:param indOtherVertex:
:param regularPoints... | suming 16 vertices per row of regularPoints
# listed l | ike
'''
4-------------------2
| 12 13 14 15 |
| 8 9 10 11 |
| 4 5 6 7 |
| 0 1 2 3 |
0-------------------1
'''
# points in order A, B1, B2, C
# B1 is the one closest to the edge
clockwiseQuadrantIndices = np.array([[5,4,1,0],\
... |
jordanemedlock/psychtruths | temboo/core/Library/Google/ComputeEngine/Zones/ListZones.py | Python | apache-2.0 | 5,734 | 0.005232 | # -*- coding: utf-8 -*-
###############################################################################
#
# ListZones
# Retrieves the list of Zone resources for the specified project.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#... | et of Temboo credentials, must be supplied.
"""
super(ListZones, self).__init__(temboo_session | , '/Library/Google/ComputeEngine/Zones/ListZones')
def new_input_set(self):
return ListZonesInputSet()
def _make_result_set(self, result, path):
return ListZonesResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return ListZonesChoreographyExecution(sessio... |
hank5925/automatic-subtitle-transcriptor | subgen/subtitle_parsing.py | Python | mit | 1,283 | 0.018706 | import math
import datetime
#from subgen.subtitle import Subtitle
#def time_parse(s):
#hour, minute, second_decimal = [t for t in s.split(':')]
#second, microsec = second_decimal.split('.')
#microsec = microsec.ljust(6, '0')
#return [int(hour), int(minute), int(second), int(microsec)]
def subtitle_par... | e
ss = f.readlines()
for s in ss:
if inEvents == True:
sl = s.strip().split(',')
if sl[1] != ' Start':
#rs = time_parse(sl[1])
#re = time_parse(sl[2])
rs = sl[1]
re = sl[2]
... | if s.strip() == "[Events]":
inEvents = True
res_offset += len(s)
return res_start, res_end, res_offset
#if __name__ == "__main__":
#import sys
#import os
#if os.path.exists(sys.argv[1]) == True:
#subtitle_parser(sys.argv[1])
#else:
#raise FileNotFo... |
houseurmusic/my-swift | test/unit/container/test_updater.py | Python | apache-2.0 | 8,262 | 0.000484 | # Copyright (c) 2010-2011 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | raise err
info = cb.get_info()
self.assertEquals(info['object_count'], 1)
self.assertEquals(info['bytes_used'], 3)
self.asser | tEquals(info['reported_object_count'], 1)
self.assertEquals(info['reported_bytes_used'], 3)
def test_unicode(self):
cu = container_updater.ContainerUpdater({
'devices': self.devices_dir,
'mount_check': 'false',
'swift_dir': self.testdir,
'interval': '... |
Patreon/cartographer | cartographer/exceptions/request_exceptions.py | Python | apache-2.0 | 2,455 | 0.001222 | AUTHENTICATION_REQUIRED_401 = 401
NOT_AUTHORIZED_403 = 403
INVALID_REQUEST_400 = 400
REQUEST_ENTITY_TOO_LARGE_413 = 413
NOT_FOUND_404 = 404
INTERNAL_SERVER_ERROR_500 = 500
RESOURCE_CONFLICT_409 = 409
PAYMENT_REQUIRED_402 = 402
HEADER_PRECONDITIONS_FAILED = 412
LOCKED_423 = 423
TOO_MANY_REQUESTS_429 = 429
class JSONAP... | is missing.".format(parameter_name or self.parameter_name)
class ParameterInvalid(JSONAPIException):
status_code = INVALID_REQUEST_400
def __init__(self, parameter_name, parameter_value | ):
self.error_title = \
"Invalid value for parameter '{}'.".format(parameter_name)
self.error_description = \
"Invalid parameter for '{0}': {1}.".format(parameter_name, parameter_value)
class BadPageCountParameter(ParameterInvalid):
def __init__(self, parameter_value):
... |
shapiromatron/tblBuilder | src/private/scripts/ftpScraper.py | Python | mit | 3,966 | 0.000756 | from io import BytesIO
import json
import os
import urllib.parse
import six
import sys
from ftptool import FTPHost
import xlsxwriter
# from https://docs.djangoproject.com/en/1.10/_modules/django/utils/encoding/
def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"):
"""
Returns a text objec... | parser = urllib.parse.quote
# write data rows
row = 0
for path, files in data:
for fn in files:
row += 1
path_url = parser(
os.path.join(path | .decode("utf8"), fn.decode("utf8")).encode("utf8")
)
url = root_url + path_url
ws.write(row, 0, smart_text(path))
ws.write(row, 1, smart_text(fn))
ws.write(row, 2, smart_text(url))
# setup header and autofilter
bold = wb.add_format({"bold": True})
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.