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 |
|---|---|---|---|---|---|---|---|---|
SUSE/azure-sdk-for-python | azure-mgmt-cdn/azure/mgmt/cdn/models/sso_uri.py | Python | mit | 893 | 0 | # 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 ... | l):
"""SSO URI required to login to the supplemental portal.
:param sso_uri_value: The URI us | ed to login to the supplemental portal.
:type sso_uri_value: str
"""
_attribute_map = {
'sso_uri_value': {'key': 'ssoUriValue', 'type': 'str'},
}
def __init__(self, sso_uri_value=None):
self.sso_uri_value = sso_uri_value
|
RDCEP/hybrid-dile-server | lib/utils/geolocation.py | Python | apache-2.0 | 5,668 | 0.010233 | import math
class GeoLocation:
'''
Class representing a coordinate on a sphere, most likely Earth.
This class is based from the code smaple in this paper:
http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates
The owner of that website, Jan Philip Matuschek, is the full ow... | ad_lon - other.rad_lon)
)
if unit.lower() == "kilometers":
return distance
elif unit.lower() == "miles":
return distance/GeoLocation.CONV_FACTORS
else:
raise Exception("Illegal arguments")
def bounding_locations(self, dist, u... | nates of all points on the surface
of a sphere that has a great circle distance to the point represented
by this GeoLocation instance that is less or equal to the distance argument.
Param:
distance - the distance from the point represented by this GeoLocation
... |
Crompulence/cpl-library | test/valgrind/test_valgrind.py | Python | gpl-3.0 | 3,969 | 0.006551 | import pytest
from cplpy import run_test, prepare_config
import subprocess as sp
import os
import glob
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os... | "olap_xlo": 1, "olap_xhi": 24,
# "olap_ylo": 1, "olap_yhi": 4,
# "olap_zlo": 1, "olap_zhi": 24,
# "cnst_xlo": 1, "cnst_xhi": 1,
# "cnst_ylo": 1, "cnst_yhi": 1,
# "cnst_zlo": 1, "cnst_zhi": 1,
# ... | |
mozilla/build-relengapi | relengapi/blueprints/tooltool/__init__.py | Python | mpl-2.0 | 14,685 | 0.000885 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
import datetime
import random
import re
import sqlalchemy as sa
import structlo... | oltool files, including deleting and changing visibility levels") |
# This value should be fairly short (and its value is included in the
# `upload_batch` docstring). Uploads cannot be validated until this
# time has elapsed, otherwise a malicious uploader could alter a file
# after it had been verified.
UPLOAD_EXPIRES_IN = 60
GET_EXPIRES_IN = 60
logger = structlog.get_logger()
d... |
kyrus/PyMyo | modules/b64decode/command.py | Python | bsd-3-clause | 886 | 0.021445 |
###############################################################################
## File : b64deco | de.py
## Description: Base64 decode a supplied list of strings
## :
## Created_On : Wed Sep 26 12:33:16 2012
## Created_By : Rich Smith (rich@kyr.us)
## Mod | ified_On: Tue Jan 29 16:42:41 2013
## Modified_By: Rich Smith (rich@kyr.us)
## License : BSD-3
##
##
###############################################################################
import base64
__author__ = "rich@kyr.us"
__version__ = 1.0
__updated__ = "26/09/2012"
__help__ = "Module for decoding a string f... |
sebcourtois/pypeline-tool-devkit | pytaya/core/rendering.py | Python | gpl-3.0 | 12,494 | 0.006163 |
import maya.cmds;mc = maya.cmds
import pymel.core;pm = pymel.core
from pytaya.core.general import listForNone
from pytd.util.logutils import logMsg
from pytd.util.sysutils import grouper
def fileNodesFromObjects(oObjList):
return fileNodesFromShaders(shadersFromObjects(oObjList))
def fileNodesFromShaders(oMatL... | 'Cancel'],
defaultButton='Cancel',
cancelButton='Cancel',
dismissString='Cancel')
if result == 'Cancel':
return
else :
for oSourceXfm, oTargetXfm in transferList:
oSourceShape = oSource... | lse
oTargetCurrentShape = oTargetXfm.getShape(ni=True)
if len(oShapeList) > 1:
for oShape in oShapeList:
if oShape.getAttr("intermediateObject") and oShape.attr("worldMesh").outputs():
bShapeOrig = True
oShape.... |
Collisionc/sickbeard_mp4_automator | post_process/sample.py | Python | mit | 214 | 0.028037 | #!/usr/bin/python
import os
i | mport json
def main():
print("Sample Post Script")
files = json.loads(os.environ.get('MH_FILES'))
for filename in files:
print(filename)
if __name__ == "__main__":
| main()
|
pudo/kompromatron | kompromatron/web.py | Python | mit | 177 | 0.00565 | from kompromatron.core import app
from k | ompromatron.views.base import base
# app.register_blueprint(entities)
# app.r | egister_blueprint(relations)
#app.register_blueprint(base)
|
HoboSci/OBIS-Capelin | 1Loop_on_date_python_script.py | Python | mit | 18,420 | 0.014327 | import os
import platform
import subprocess
import datetime as dt
import time
import calendar
import sys
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# General Parameters - Tools - Proxy Network - Output Directory
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Path declaratio... | ads/motu-client-python-1.5.00-20180223190259664-bin.tar/motu-client-python/motu-client.py'
# File to log unsuccessful data extraction request(s)
logfile = 'logfile.txt'
# Copernicus Marine API Key - Login Credentials
username_cmems = 'XXX'
password_cmems = 'XXX | '
# Proxy Configuration
# Please replace "False" by "True" if you use a proxy to connect to internet and fill in the below variables.
proxy_flag = False
proxy_server_url = "http://your_proxy_address"
proxy_server_port = "8080"
proxy_user_login = "your_proxy_login"
proxy_user_password = "your_proxy_password"
# Output ... |
chrigu6/vocabulary | vocabulary/trainer/forms.py | Python | gpl-3.0 | 1,356 | 0.0059 | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from trainer.models import Language
class AddWordForm(forms.Form):
language = forms.ModelChoiceField(queryset=Language.objects.all())
word = forms.CharField(required=True)
class Create... | class Meta:
model = User
fields = ("username", "email", "first_name", "last_name", "password1", "password2")
def save(self, commit=True):
user = super(UserCreateForm,self).save(commit=False)
user.email = self.cleaned_data["email"]
user.name = self.cleaned_da... | ser.prename = self.cleaned_data["last_name"]
if commit:
user.save()
return user
class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(widget=forms.PasswordInput())
class UploadFileForm(forms.Form):
language = forms.Mode... |
sillygod/my-travel-in-learning-python | proxy.py | Python | gpl-2.0 | 1,022 | 0.004892 | import logging
from flask import (
Flask,
request,
Response
)
import requests
app = Flask(__name__)
@app.route('/<path:url>', methods=['GET', 'POST', 'PUT', 'PATCH'])
def proxy(url):
# extract the request info and change its destination
# how to deal with socketio
if url == "socket.io/":
... | od=request.method, url=target, headers=request.header | s, data=data, cookies=request.cookies)
resp = requests.Session().send(truely_request.prepare())
logging.debug(resp.content)
response = app.make_response((resp.content, resp.status_code, resp.headers.items()))
for k, v in resp.cookies:
response.set_cookie(k, v)
return response
if __nam... |
chenzeyuczy/keba | src/SysuLesson/wsgi.py | Python | gpl-2.0 | 397 | 0 | """
WSGI co | nfig for SysuLesson 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_w | sgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SysuLesson.settings")
application = get_wsgi_application()
|
anirudhagar13/PES-Portal | pes_portal/club/admin.py | Python | apache-2.0 | 548 | 0.010949 | from django.contrib import admin
'''from tester.models import Club,Mem | ber,Signup,Event
class admin_club(admin.ModelAdmin):
list_display=["club_name"]
class admin_event(admin.ModelAdmin):
list_display=["event_name"]
class admin_student(admin.ModelAdmin):
list_display=["usn","name"]
class admin_member(admin.ModelAdmin):
list_display=["club_id","usn"]
admin.site.regis... | ber,admin_member)
admin.site.register(Signup,admin_student)
admin.site.register(Event,admin_event)
'''
|
syl20bnr/nupic | nupic/research/TP.py | Python | gpl-3.0 | 132,910 | 0.00793 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ndom = Random(seed)
else:
self._random = Random(numpy.random.randint(256))
# Store creation parameters
## @todo document
self.numberOfCols = numberOfCols
## @todo document
self.cellsPerColumn = cellsPerColumn
self._numberOfCells = numberOfCols * cellsPerColumn
## @todo document
... | hold
## @todo document
self.newSynapseCount = newSynapseCount
## @todo document
self.permanenceInc = numpy.float32(permanenceInc)
## @todo document
self.permanenceDec = numpy.float32(permanenceDec)
## @ |
CiscoSystems/avos | openstack_dashboard/dashboards/identity/users/tests.py | Python | apache-2.0 | 26,197 | 0 | # 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
# not use this file except in compliance with the... | tubs({api.keystone: ('user_create',
'get_default_domain',
'add_tenant_user_role',
'tenant_list',
'get_default_role',
'roles_f... | ")
domain = self._get_default_domain()
domain_id = domain.id
role = self.roles.first()
api.keystone.get_default_domain(IgnoreArg()) \
.MultipleTimes().AndReturn(domain)
api.keystone.tenant_list(IgnoreArg(),
domain=domain_id,
... |
maateen/TextSuggestBangla | textsuggest/processors/command.py | Python | gpl-3.0 | 219 | 0.031963 | import subprocess as sp
def matches(text):
return text.startswith('#')
def process(text):
text = text[1:]
result = sp.check_output(text, shell=True).decode('utf-8').rstrip().repla | ce( | '\\n', '\n')
return result
|
Moguri/prototype-nitrogen | game/main.py | Python | apache-2.0 | 1,902 | 0.001577 | import os
import sys
from direct.showbase.ShowBase import ShowBase
import panda3d.core as p3d
import blenderpanda
import inputmapper
from nitrogen import gamestates
if hasattr(sys, 'frozen'):
APP_ROOT_DIR = os.path.dirname(sys.executable)
else:
APP_ROOT_DIR = os.path.dirname(__file__)
if not APP_ROOT_DIR:
... | (CONFIG_ROOT_DIR, 'user.prc'),
]
for config_file in CONFIG_FILES:
if os.path.exists(config_file):
print("Loading config file:", config_file)
config_file = p3d.Filename.from_os_specific(config_file)
p3d.load_prc_file(config_file)
else:
print("Could not find config file", config_... | blenderpanda.init(self)
self.input_mapper = inputmapper.InputMapper(os.path.join(CONFIG_ROOT_DIR, 'input.conf'))
self.accept('quit', sys.exit)
self.disableMouse()
winprops = self.win.get_properties()
self.win.move_pointer(0, winprops.get_x_size() // 2, winprops.get_y_size()... |
DavidHHShao/slack | tests/unit/http_client/test_raise_error.py | Python | mit | 3,437 | 0.005237 | # Copyright (c) 2014 Katsuya Noguchi
#
# Permission i | s 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, dis-
# tribute, sublicense, and/or sell copies of the So... | ons:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR... |
miguelarauj1o/8-Queens | eightqueens/__main__.py | Python | mit | 6,082 | 0.010209 | from __future__ import division
import state
import time
import csv
import random
import sys
POPULATION_SIZE = 100
MAX_COLLISION = 28
VALID_ARGS = "emg"
class FitnessListener():
def __init__(self, qtd=0):
self._qtd = qtd
def log(self):
self._qtd += 1
def retrive_qtd(self):
ret... | t = True
else:
sys.exit("argument " + argstr + " is invalid")
elif arg[:1] == "-":
argstr = arg[1:]
err = False
for c in argstr:
if c not in VALID_ARGS:
print "Unknown command-line argument",... | elitist = True
if 'm' in argstr:
if 'm' not in argstr[:-1] and len(arguments) > index+1:
methodstr = arguments[index+1]
method = choose_method(methodstr)
next_is_literal_argument = True
... |
kvchen/keffbot-py | plugins/event.py | Python | mit | 87 | 0.011494 | """!ev | ent [num]: Displays the next upcoming H | @B event."""
__match__ = r"!event( .*)"
|
kyelewisstgc/EventMaster-Python | tests/test_unit.py | Python | mit | 1,220 | 0.007377 | # This doesn't work- not updated with eventmaster.py updates
# TODO: Fix This :)
# Import Libraries
import eventmaster
import time
import random
import sys
import unittest
import sys
class InputsTestCase(unittest.TestCase):
def setUp(self):
self.s3 = E2S3.E2S3S | witcher()
self.s3.set_verbose(0)
self.s3.set_CommsXML_IP("127.0.0.1")
self.s3.set_CommsXML_Port(9876)
if not self.s3.connect(): return -1
while self.s3.is_ready() != 1: time.sleep(1)
def test_set_valid_name_on_invalid_input(self):
test_str = "PYTEST-{0 | !s}".format(random.randint(1,10))
self.assertRaises(ValueError, lambda: self.s3.get_input(99).set_Name(test_str))
def test_set_valid_name_on_valid_input(self):
test_str = "PYTEST-{0!s}".format(random.randint(1,10))
while(self.s3.has_been_processed(self.s3.get_input(0).set_Name(test_str))==0... |
lepklin/twitter-db-ui | removeDouble.py | Python | mit | 1,784 | 0.019619 | #!/usr/bin/python
import psycopg2
import sys
import pprint
import ge | ocoder
def printProgress(iteration, total, prefix='', suffix='', | decimals=2, barLength=100):
filledLength = int(round(barLength * iteration / float(total)))
percents = round(100.00 * (iteration / float(total)), decimals)
bar = '#' * filledLength + '-' * (barLength - filledLength)
sys.stdout.write('%s [%s] %s%s %s\r' % (prefix, bar, percents, '%', suffix)),
sys.st... |
saraghav/blue-box | TensorFlow/input_data.py | Python | apache-2.0 | 5,847 | 0.015735 | """Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import urllib
import numpy
from six.moves import xrange # pylint: disable=redefined-builtin
SOURCE_URL = 'http://yann.lecun.com/exdb... | ream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
def dense_to_one_hot(labels_dense, num_classes=10):
"""Convert class labels from scalars to one-hot vectors.""... | um_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
def extract_labels(filename, one_hot=False):
"""Extract the labels into a 1D uint8 numpy array [index]."""
print('Extracting', filename)
with gz... |
j0gurt/ggrc-core | src/ggrc/converters/query_helper.py | Python | apache-2.0 | 33,268 | 0.006523 | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""This module contains a class for handling request queries."""
# flake8: noqa
import collections
import datetime
import functools
import operator
import flask
import sqlalchemy as sa
from sqlalchemy.orm... | self._macro_expand_object_query(object_query)
return query
def _clean_filters(self, expression):
"""Prepare the filter expression for building the query."""
if not expression or not isinstance(expression, dict):
return
slugs = expression.get("slugs")
if slugs:
ids = expression.get("id... | on.get("ids", [])]
except ValueError as error:
# catch missing relevant filter (undefined id)
if expression.get("op", {}).get("name", "") == "relevant":
raise BadQueryException(u"Invalid relevant filter for {}".format(
expression.get("object_name", "")))
rai... |
BaReinhard/Hacktoberfest-Data-Structure-and-Algorithms | data_structures/binary_tree/python/binary_tree.py | Python | gpl-3.0 | 694 | 0.048991 | class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None | :
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.r | ightChild
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key
|
umd-mith/bagcat | setup.py | Python | mit | 647 | 0.027821 | from sys import version, exit
from setuptools import setup
requirements = open("requirements.txt").re | ad().split()
with open("README.md") as f:
long_description = f.read()
setup(
name = 'bagcat',
version = '0.0.6',
url = 'https://github.com/umd-mith/bagcat/',
author = 'Ed Summers',
author_email = 'ehs@pobox.com',
py_modules = ['bagcat',],
install_requires = requirements,
descriptio... | description=long_description,
long_description_content_type="text/markdown",
entry_points={"console_scripts": ["bagcat=bagcat:main"]},
)
|
Nzaga/home-assistant | tests/components/automation/test_init.py | Python | mit | 2,584 | 0 | """
tests.test_component_demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests demo component.
"""
import unittest
import homeassistant.core as ha
import homeassistant.components.automation as automation
import homeassistant.components.automation.event as event
from homeassistant.const import CONF_PLATFORM, ATTR_ENTITY_ID
class T... | data', self.calls[0].data['some'])
def test_service_specify_entity_id(self):
automation.setup(self.hass, {
automation.DOMAIN: {
CONF_PLATFORM: 'event',
event.CONF_E | VENT_TYPE: 'test_event',
automation.CONF_SERVICE: 'test.automation',
automation.CONF_SERVICE_ENTITY_ID: 'hello.world'
}
})
self.hass.bus.fire('test_event')
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
self.asse... |
AustinTSchaffer/DailyProgrammer | LeetCode/FindMinimumInRotatedSortedArray2/app.py | Python | mit | 277 | 0.00361 | from t | yping import List
class Solution:
def findMin(self, nums: List[int]) -> int:
first = nums[0]
# Iterate until the next number is less than current.
for num in nums:
if num < first:
return num
return first | |
Francis-Liu/animated-broccoli | nova/db/sqlalchemy/api.py | Python | apache-2.0 | 240,590 | 0.001176 | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file... | ite_synchronous',
default=True,
help='If True, SQLite uses synchronous mode.'),
cfg.StrOpt('slave_connection',
secret=True,
help='The SQLAlchemy connection string to use to connect to the'
' slave database.'),
cfg.StrOpt('mysql_sq... | ides any '
'server-set SQL mode. To use whatever SQL mode '
'is set by the server configuration, '
'set this to no value. Example: mysql_sql_mode='),
cfg.IntOpt('idle_timeout',
default=3600,
help='Timeout before idle SQL conne... |
SysTheron/adhocracy | src/adhocracy/tests/test_pep8.py | Python | agpl-3.0 | 2,111 | 0 | #!/usr/bin/env python
import os.path
import unittest
import pep8
SRC_PATH = os.path.dirname(os.path.dirname(__file__))
EXCLUDE = ['.svn', 'CVS', '.bzr', '.hg', '.git',
'Paste-1.7.5.1-py2.6.egg', 'PasteDeploy-1.5.0-py2.6.egg', 'data']
class AdhocracyStyleGuide(pep8.StyleGuide):
def ignore_code(self, ... | should be 'if cond is None:'
'E712', # comparison to True shou | ld be 'if cond is True:' or
# 'if cond:'
'W291', # trailing whitespace
'W292', # no newline at end of file
'W293', # blank line contains whitespace
'W391', # blank line at end of file
]
return code in IGNORED
class TestPep8(unitt... |
dvklopfenstein/PrincetonAlgorithms | py/AlgsSedgewickWayne/WeightedQuickUnionUF.py | Python | gpl-2.0 | 16,078 | 0.003483 | """Weighted Quick Union Algorithm takes steps to avoid tall trees."""
from AlgsSedgewickWayne.BaseComp import BaseComp
class WeightedQuickUnionUF(BaseComp):
""" UNION FIND: Weighted Quick-union [lazy approach] to avoid tall trees."""
def __init__(self, N): # $ = N
"""Initialize union-find data structure ... | ###############################
# Lecture Week 1 Quick-Union Improvements (13:02)
###########################################################################
#
# 00:22 IMPROVEMENT 1: WEIGHTING
#
# WEIGHTED QUICK-UNION.
# * Modify quick-union to avoid tall trees.
# * Keep track of size of each tree (number of objects).
... | N DEMO
# ------------------------------
# i 0 1 2 3 4 5 6 7 8 9
# INI: id[] 0 1 2 3 4 5 6 7 8 9
#
# 0 1 2 3 4 5 6 7 8 9
#
# 03:21 -- union(4, 3) --------
# WAS: id[] 0 1 2 3 4 5 6 7 8 9
# NOW: id[] 0 1 2 4 4 5 6 7 8 9
# . . . X . . . . . .
#
# 0 1 2 4 5 6 7 8 9
# |
# ... |
btrent/knave | pychess/Utils/Rating.py | Python | gpl-3.0 | 2,135 | 0.007026 | from pychess.Utils.const import *
class Rating ():
def __init__(self, ratingtype, elo, deviation=DEVIATION_NONE, wins=0,
losses=0, draws=0, bestElo=0, bestTime=0):
self.type = ratingtype
for v in (elo, deviation, wins, losses, draws, bestElo, bestTime):
assert v == None... | viation=self.deviation,
wins=self.wins, losses=self.losses, draws=self.draws,
bestElo=self.bestElo, bestTime=se | lf.bestTime)
def update (self, rating):
if self.type != rating.type:
raise TypeError
elif self.elo != rating.elo:
self.elo = rating.elo
elif self.deviation != rating.deviation:
self.deviation = rating.deviation
elif self.wins != rating.wins:
... |
jtovar2/demo_app | backend/resources/org_api.py | Python | mit | 2,570 | 0.003113 | from flask import Flask, request, abort
import json
import ndb_util
import model
from google.appengine.api import users
from google.appengine.ext import ndb
from flask_restful import Resource
#TODO auth stuff
class OrganizationApi(Resource):
def get(self, id=None):
id = str(id)
if id is None:
... | org_key = ndb.Key('Organization', body['id'])
if org_key.get() != None:
abort(401)
org = model.Organization()
| org = org.entity_from_dict(body)
print org
if org is False:
abort()
else:
org.put()
return org.to_json()
def delete(self,id=None):
id = str(id)
client_id = users.get_current_user().user_id()
if id is None or client_id != id:
... |
oaubert/advene | lib/advene/gui/edit/transcribe.py | Python | gpl-2.0 | 51,178 | 0.007386 | #
# Advene: Annotate Digital Videos, Exchange on the NEt
# Copyright (C) 2008-2017 Olivier Aubert <contact@olivieraubert.net>
#
# Advene 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 ... |
def update_font_size(self, size=None):
if size is None:
size=self.options['font-size']
if size == 0:
# Get the default value from a temporary textview
t=Gtk.TextView()
size=int(t.get_pang | o_context().get_font_description().get_size() / Pango.SCALE)
del t
f=self.textview.get_pango_context().get_font_description()
f.set_size(size * Pango.SCALE)
self.textview.modify_font(f)
def show_searchbox(self, *p):
self.searchbox.show()
self.searchbox.entry.grab... |
MauricioAlmeida/maoaberta | maoaberta/organizations/models.py | Python | gpl-2.0 | 2,083 | 0.00096 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from projects.models import Project
class Necessity(models.Model):
"""
Item or service that an organization regularly needs
"""
name = models.CharField(verbose_name=_('Name'), max_length=20)
satisfied = models.Bo... | RLField(
verbose_name=_('Facebook URL'), blank=True,
help_text=_('Organization faceboo | k link')
)
twitter_url = models.URLField(
verbose_name=_('Twitter URL'), blank=True,
help_text=_('Organization twitter link')
)
def __repr__(self):
return '<Organization({})>'.format(self.name)
def __str__(self):
return self.name
|
osborne6/luminotes | view/Updates_rss.py | Python | gpl-3.0 | 1,836 | 0.03976 | import cgi
from urllib import urlencode
from Rss_channel import Rss_channel
from Rss_item import Rss_item
class Updates_rss( Rss_channel ):
def __init__(
self,
recent_notes,
notebook_id,
notebook_name,
https_url,
):
if notebook_name == u"Luminotes":
notebook_path = u"/"
elif note... | sion, https_url ),
) for ( note_id, revision ) in recent_notes ] or [ Rss_item(
title = u"Unknown notebook",
link = None,
description = cgi.escape( u'Sorry, that notebook is unknown.' ),
date = | None,
guid = None,
) ],
)
@staticmethod
def note_link( notebook_id, notebook_name, note_id, revision, https_url ):
query = urlencode( [
( u"notebook_id", notebook_id ),
( u"notebook_name", notebook_name.encode( "utf8" ) ),
( u"note_id", note_id ),
( u"revision", unico... |
Asurada2015/TFAPI_translation | math_ops_basicoperation/tf_pow.py | Python | apache-2.0 | 416 | 0.002747 | import tensorflow as tf
"""tf.pow(x,y,name=None)
功能:计算x各元素的y次方。
输入:x,y为张量,可以为`float3 | 2`, `float64`, `int32`, `int64`,`complex64`,`complex128`类型。"""
x = tf.constant([[2, 3, 5], [2, 3, 5]], tf.float64)
y = tf.constant([[2, 3, 4]], tf.float64)
z = tf.pow(x, y)
sess = tf.Session()
print(sess.run(z))
sess.close()
"""[[ 4. 27. 625.] |
[ 4. 27. 625.]]"""
|
erudit/zenon | docs/conf.py | Python | gpl-3.0 | 9,700 | 0.005984 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Érudit.org documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 14 17:16:39 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
#... | todoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sy | s.path.insert(0, os.path.abspath('../eruditorg'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings.base')
import django
django.setup()
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
... |
mikitex70/pelican-plugins | readtime/__init__.py | Python | agpl-3.0 | 24 | 0 | from .readtime impor | t *
| |
davidt/reviewboard | reviewboard/hostingsvcs/tests/test_redmine.py | Python | mit | 899 | 0 | from __future__ import unicode_literals
from reviewboard.hostingsvcs.tests.testcases import ServiceTests
class RedmineTests(ServiceTests):
"""Unit tests for the Redmine hosting service."""
service_name = 'redmine'
fixtures = ['test_scmtools']
def test_service_support(self): |
"""Testing the Redmine service support capabi | lities"""
self.assertTrue(self.service_class.supports_bug_trackers)
self.assertFalse(self.service_class.supports_repositories)
def test_bug_tracker_field(self):
"""Testing the Redmine bug tracker field value"""
self.assertFalse(
self.service_class.get_bug_tracker_require... |
izrik/tudor | tests/logic_t/layer/LogicLayer/test_search.py | Python | gpl-2.0 | 2,413 | 0 | #!/usr/bin/env python
import unittest
from tests.logic_t.layer.LogicLayer.util import generate_ll
class SearchTest(unittest.TestCase):
def setUp(self):
self.ll = generate_ll()
self.pl = self.ll.pl
self.admin = self.pl.create_user('name@example.org', None, True)
self.pl.add(self.a... | rtEqual([task], results2)
def test_no_matching_summary_yields_nothing(self):
# given
task = self.pl.create_task('one two three')
self.pl.add(task)
self.pl.commit()
# when
results = self.ll.search('four', self.admin)
# then
self.assertIsNotNone(results... | ser('user1@example.org', None, False)
self.pl.add(user1)
task = self.pl.create_task('one two three')
task.users.append(user1)
self.pl.add(task)
self.pl.commit()
# when
results = self.ll.search('two', user1)
# then
self.assertIsNotNone(results)
... |
mmikitka/usdanutrient | usdanutrient/importservice.py | Python | gpl-3.0 | 15,884 | 0.003463 | import inspect
import os
import re
import sys
import csv
import sqlalchemy.orm.exc
from sqlalchemy.orm.session import make_transient
from sqlalchemy import and_, Boolean, Date, func, Integer, Numeric
from datetime import date
from decimal import Decimal
import model
def db_import_file(engine, table_class, fname, col_o... | t
def process_row_local_food(row_in, args):
session = args['session']
result = None
foods = session.\
query(model.Food).\
filter(model.Food.long_desc == row_in[0])
for food in foods:
session.delete(food)
session.commit()
food_group = session.\
query(mod... | name == row_in[3]).\
one()
result = {
'long_desc': row_in[0],
'short_desc': row_in[1],
'manufacturer': row_in[2],
'group_id': food_group.id,
'refuse_pct': row_in[4]
}
return result
def process_row_local_food_weight(row_in, args):
session = args['session'... |
secnot/rectpack | rectpack/packer.py | Python | apache-2.0 | 17,585 | 0.006028 | from .maxrects import MaxRectsBssf
import operator
import itertools
import collections
import decimal
# Float to Decimal helper
def float2dec(ft, decimal_digits):
"""
Convert float (or int) to Decimal (rounding up) with the
requested number of decimal digits.
Arguments:
ft (float, int): Numb... | ]/r[1]) # Sort by side ratio
SORT | _NONE = lambda rectlist: list(rectlist) # Unsorted
class BinFactory(object):
def __init__(self, width, height, count, pack_algo, *args, **kwargs):
self._width = width
self._height = height
self._count = count
self._pack_algo = pack_algo
self._algo_kwargs = kwargs... |
pgleeson/TestArea | models/Cerebellum/pythonScripts/Test_SingleGranule.py | Python | gpl-2.0 | 2,965 | 0.018887 | #
#
# File to test behaviour of the Golgi Cell.
#
# To execute this type of file, type '..\..\..\nC.bat -python XXX.py' (Windows)
# or '../../../nC.sh -python XXX.py' (Linux/Mac). Note: you may have to update the
# NC_HOME and NC_MAX_MEMORY variables in nC.bat/nC.sh
#
# Author: Padraig Gleeson
#
# ... | http://www.neuroconstruct.org/docs/python.html for more details"
quit()
sys.path.append(os.environ["NC_HOME"]+"/pythonNeuroML/nCUtils")
import ncutils as nc
projFile = File("../Cerebellum.ncx")
############## Main settings ##################
simConfigs = []
#simConfigs.append("Default Simulatio... | ["NEURON", "GENESIS_PHYS", "GENESIS_SI"] # Note: nernst object isn't implemented in MOOSE yet
varTimestepNeuron = True
varTimestepTolerance = 0.00001
plotSims = True
plotVoltageOnly = True
runInBackground = True
analyseSims = True
verbose = False
... |
lightning-round/salud-api | app/mod_profiles/common/parsers/user.py | Python | gpl-2.0 | 615 | 0 | # -*- coding: utf-8 -*-
from flask_restful import reqparse
from app.mod_profiles.validators.generic_validators import is_valid_id
# Parser general
parser = reqparse.RequestParser()
parser.add_argument('username', type=str, required=True)
parser.add_argument('email', type=str, required=True)
parser.add_arg | ument('password', type=str, required=True)
parser.add_argument('profile_id', type=is_valid_id, required=True)
# Parser para recurso POST
parser_post = parser.copy()
# Parser para | recurso PUT
parser_put = parser.copy()
parser_put.remove_argument('password')
parser_put.add_argument('password', type=str)
|
kyvinh/home-assistant | tests/components/recorder/models_original.py | Python | apache-2.0 | 5,545 | 0 | """Models for SQLAlchemy.
This file contains the original models definitions before schema tracking was
implemented. It is used to test the schema migration logic.
"""
import json
from datetime import datetime
import logging
from sqlalchemy import (Boolean, Column, DateTime, ForeignKey, Index, Integer,
... | = query.filter(States.last_updated < self.end)
return [row[0] for row in query]
def to_native(self):
"""Return self, native format is this model."""
return self
def _process_timestamp(ts):
"""Process a timestamp into datetime object."""
if ts is None:
return None
eli... | turn dt_util.as_utc(ts)
|
airbnb/airflow | tests/utils/test_python_virtualenv.py | Python | apache-2.0 | 2,580 | 0.003101 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | hon_bin = prepare_virtualenv(
venv_directory="/VENV",
python_bin="pythonVER",
system_site_packages=False,
requirements=['apache-beam[gcp]'],
)
self.assertEqual("/VENV/bin/python", python_bin)
mock_ex | ecute_in_subprocess.assert_any_call(['virtualenv', '/VENV', '--python=pythonVER'])
mock_execute_in_subprocess.assert_called_with(['/VENV/bin/pip', 'install', 'apache-beam[gcp]'])
|
MostlyOpen/odoo_addons | myo_person_mng/models/person_mng.py | Python | agpl-3.0 | 3,872 | 0.00155 | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# 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
#... | (string='Person Code', required=False)
notes = fields.Text(string='Notes')
date_inclusion = fields.Datetime("Inclusion Date", required=False, readonly=False,
| default=lambda *a: datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
batch_name = fields.Char('Batch Name', required=False)
country_id_2 = fields.Many2one('res.country', 'Nationality')
birthday = fields.Date("Date of Birth")
age = fields.Char(
string='Age',
compute='_compute_age',
... |
GiantSpaceRobot/FindFungi | FindFungi-v0.23/CSV-to-Tree.py | Python | mit | 2,781 | 0.024811 | #!/usr/bin/env python
"""
This script accepts .csv pipeline output and gives a .ps file with a basic tree structure
"""
__author__ = "Paul Donovan"
__maintainer__ = "Paul Donovan"
__email__ = "pauldonovandonegal@gmail.com"
import sys
import argparse
from ete3 import NCBITaxa
#Display help and usage
parser = argpar... |
else:
ResultTaxid = line[1]
ResultTaxids.append(ResultTaxid)
lineage = ncbi.get_lineage(ResultTa | xid)
for index, taxid in enumerate(lineage):
name = ncbi.get_taxid_translator([str(taxid)])
name = name[taxid]
for char in name:
if char in BadChars:
name = name.replace(str(char),"_") #Replace ugly strings
NextIndex = int(index) + 1
if NextIndex == len(lineage):
pass
else:
NextTaxi... |
rspavel/spack | var/spack/repos/builtin/packages/vtk/package.py | Python | lgpl-2.1 | 12,385 | 0.000888 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import sys
from spack import *
class Vtk(CMakePackage):
"""The Visualization Toolkit (VTK) is an open-sou... | ', default=False, description='Enable OSMesa support')
variant('python', default=False, description='Enable Python support')
variant('qt', default=False, description='Build with support for Qt')
variant('xdmf', default=False, description='Build XDMF file support')
variant('ffmpeg', default=False, descri... | ort')
variant('mpi', default=True, description='Enable MPI support')
patch('gcc.patch', when='@6.1.0')
# At the moment, we cannot build with both osmesa and qt, but as of
# VTK 8.1, that should change
conflicts('+osmesa', when='+qt')
extends('python', when='+python')
# Acceptable python ... |
voytekresearch/neurodsp | neurodsp/plts/utils.py | Python | apache-2.0 | 1,740 | 0.002299 | """Utility functions for plots."""
from functools import wraps
from os.path import join as pjoin
import matplotlib.pyplot as plt
###################################################################################################
########################################################################################... | rab file name and path arguments, if they are in kwargs
file_name = kwargs.pop('file_name', None)
file_path = kwargs.pop('file_path', None)
# Check for an explicit argument for whether to save figure or not
# Defaults to saving when file name given (since bool(str)->True; boo | l(None)->False)
save_fig = kwargs.pop('save_fig', bool(file_name))
# Check any collect any other plot keywords
save_kwargs = kwargs.pop('save_kwargs', {})
save_kwargs.setdefault('bbox_inches', 'tight')
# Check and collect whether to close the plot
close = kwargs.pop('cl... |
ec429/quIRC | gen_numerics.py | Python | gpl-3.0 | 1,245 | 0.011245 | #!/usr/bin/python
# gen_numerics.py: generate numerics.h
import numerics
print """/*
quIRC - simple terminal-based IRC client
Copyright (C) 2010-13 Edward Cree
See quirc.c for license information
numeric: IRC numeric replies
*/
/***
This file is generated by gen_numerics.py from masters in numerics.py.
Do not... | gn with usage elsewhere.
*/
/* Error replies */"""
errs = [n for n in numerics.nums.values() if isinstance(n, numerics.NumericError)]
for e in errs:
print str(e)
print """
/* Command responses */"""
rpls = [n for n in numerics.nums.values() if isinstance(n, numerics.NumericReply)]
for r in | rpls:
print str(r)
|
mozilla/normandy | normandy/base/api/filters.py | Python | mpl-2.0 | 1,421 | 0 | import django_filters
from rest_framework import filters
class CaseInsensitiveBooleanFilter(django_filters.Filter):
# The default django_filters boolean filter *only* accepts True and False
# which is problematic when dealing with non-Python clients. This allows
# the lower case variants, as well as 0 and... | lid_fields
def get_ordering(self, *args, **kwargs):
ordering = super().get_ordering(*args, **kwargs)
if ordering is not None:
return list(map(self.replace_alias, ordering))
return ordering
def replace_alias(self, term):
field = term.lstrip("-")
if field in ... | "-" if term.startswith("-") else ""
return modifier + self.aliases[field][0]
return term
|
evewspace/eve-wspace | evewspace/wsgi.py | Python | apache-2.0 | 397 | 0.002519 | "" | "
WSGI config for mysite 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.8/howto/deployment/wsgi/
"""
import os, sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... | ()
|
temugen/pipil | pipil.py | Python | mit | 10,540 | 0.017268 | # Copyright (C) 2011 Brad Misik
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
| # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substanti | al portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAM... |
GrahamDigital/django-scheduler | tests/test_utils.py | Python | bsd-3-clause | 2,204 | 0.003176 | import datetime
from django.test import TestCase
from django.utils import timezone
from schedule.models import Event, Rule, Calendar
from schedule.utils import EventListManager
class TestEventListManager(TestCase):
def setUp(self):
weekly = Rule.objects.create(frequency="WEEKLY")
daily = Rule.ob... | t2)
self.assertEqual(next(occurrences).event, self.event2)
self.assertEqual(next(occurrences).event, self.event2)
self.assert | Equal(next(occurrences).event, self.event1)
occurrences = eml.occurrences_after()
self.assertEqual(list(occurrences), [])
|
khughitt/ete | ete_dev/tools/utils.py | Python | gpl-3.0 | 6,239 | 0.010258 | import re
import time
import readline
import os
# CONVERT shell colors to the same curses palette
SHELL_COLORS = {
"wr": '\033[1;37;41m', # white on red
"wo": '\033[1;37;43m', # white on orange
"wm": '\033[1;37;45m', # white on magenta
"wb": '\033[1;37;46m', # white on blue
"bw": '\033[1;37;40m', #... | can be found at
https://gist.github.com/jhcepas/5884168
# print_table([[3,2, {"whatever":1, "bla":[1,2]}], [5,"this is a test\n of wrapping text\n with the new function",777], [1,1,1]],
# header=[ "This is column number 1", "Column number 2", "col3"],
# wrap=True, m... | lumn | Column number 2 | col3
# number 1 | |
# =============== | =============== | ===============
# 3 | 2 | {'bla': [1, 2],
# | | 'whatever': 1}
# --------------- | --------------- | ----... |
Zlash65/erpnext | erpnext/patches/v11_0/add_market_segments.py | Python | gpl-3.0 | 317 | 0.018927 | from __future__ import unicod | e_literals
import frappe
from frappe import _
from erpnext.setup.setup_wizard.operations.install_fixtures import add_market_segments
def execute():
| frappe.reload_doc('crm', 'doctype', 'market_segment')
frappe.local.lang = frappe.db.get_default("lang") or 'en'
add_market_segments() |
DeflatedPickle/pkinter | pkinter_test.py | Python | mit | 6,451 | 0.00093 | import tkinter as tk
from tkinter import ttk
import pkinter as pk
root = tk.Tk()
menu = tk.Menu(root, type="menubar")
filemenu = tk.Menu(menu)
filemenu.add_command(label="New")
filemenu.add_command(label="Save")
menu.add_cascade(label="File", menu=filemenu)
helpmenu = tk.Menu(menu)
helpmenu.add_checkbutton(label="Abo... | )
frame2 = ttk.Frame(pv.frame)
ttk.Checkbutton(frame2, text="Checkbutton").pack()
frame3 = ttk.Frame(pv.frame)
ttk.Label(frame3, text="Frame 3").pack(side="bottom")
pv.add(child=frame1)
pv.add(child=frame2)
pv.add(child=frame3)
##################################################
def func():
print("Function")
bb... | .grid(row=3, column=1)
##################################################
ve = pk.ValidEntry(frame, valid_list=["validentry", "validEntry", "Validentry", "ValidEntry"])
ve.grid(row=3, column=2)
##################################################
cb = pk.ChoiceBook(frame)
cb.grid(row=4, column=0)
frame1 = ttk.Frame(... |
misko/neon | neon/data/video.py | Python | apache-2.0 | 865 | 0 | # ----------------------------------------------------------------------------
# Copyright 2014 Nervana 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Licens... | verning permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
"""
Defines video dataset handling.
"""
class Video(object):
def __init__(self):
raise NotImplementedError()
|
TechWritingWhiz/indy-node | indy_client/test/cli/conftest.py | Python | apache-2.0 | 46,041 | 0.000673 | import json
import os
import re
import tempfile
from typing import List
import pytest
from plenum.common.signer_did import DidSigner
from indy_client.test.agent.acme import ACME_ID, ACME_SEED
from indy_client.test.agent.acme import ACME_VERKEY
from indy_client.test.agent.faber import FABER_ID, FABER_VERKEY, FABER_SEED... | createNym, buildStewardClient
from indy_common.constants import ENDPOINT, TRUST_ANCHOR
from indy_common.roles import Roles
from indy_common.test.conftest import poolTxnTrusteeNames
from indy_common.test.conftest import domainTxnOrderedFields
from indy_node.test.helper import TestNode
from plenum.common.keygen_utils imp... | .test.cli.helper import newKeyPair, doByCtx
from indy_client.test.cli.helper import ensureNodesCreated, get_connection_request, \
getPoolTxnData, newCLI, getCliBuilder, P, prompt_is, addAgent, doSendNodeCmd, addNym
from indy_client.test.agent.conftest import faberIsRunning as runningFaber, \
acmeIsRunning as r... |
Lorquas/subscription-manager | src/rhsmlib/dbus/util.py | Python | gpl-2.0 | 2,488 | 0.001608 | from __future__ import print_function, division, absolute_import
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNES... | severity = "warning"
if hasattr(err, 'severity'):
severity = err.severity
# Raise exception string as JSON string. Thus it can be parsed and printed properly.
error_msg = json.dumps(
{
"exception": type(er | r).__name__,
"severity": severity,
"message": err_msg
}
)
six.reraise(exceptions.RHSM1DBusException, exceptions.RHSM1DBusException(error_msg), trace)
def dbus_service_method(*args, **kwargs):
# Tell python-dbus that "sender" will be the keyword to use fo... |
DistributedSystemsGroup/zoe | zoe_master/metrics/kairosdb.py | Python | apache-2.0 | 4,088 | 0.001223 | # Copyright (c) 2016, Daniele Venzano
#
# 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 w... | NY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Retrieves metrics about services from KairosDB."""
| from datetime import datetime, timedelta
import logging
import requests
from zoe_lib.config import get_conf
log = logging.getLogger(__name__)
class KairosDBInMetrics:
"""KairosDB metrics."""
def __init__(self):
self.base_url = get_conf().kairosdb_url
self.tags_url = self.base_url + '/api/v... |
lyoniionly/django-cobra | src/cobra/apps/summary/admin.py | Python | apache-2.0 | 76 | 0.013158 | from d | jango.contrib import admin
from cobra.core.loading import get_model
| |
mablae/weblate | weblate/trans/tests/test_suggestions.py | Python | gpl-3.0 | 7,857 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | anslated
self.assertEqual(len(unit.checks()), 0)
self.assertTrue(unit.translated)
self.assertFalse(unit.fuzzy)
self.assertEqual(unit.target, 'Ahoj svete!\n')
self.assertBackend(1)
self.assertEqual(len(self.get_unit().suggestions()), 1)
def test_accept_anonymous(self)... | ggestion_1()
self.client.login(username='testuser', password='testpassword')
# Get ids of created suggestion
suggestions = list(self.get_unit().suggestions())
self.assertEqual(len(suggestions), 1)
self.assertIsNone(suggestions[0].user)
# Accept one of suggestions
... |
srgblnch/LinacGUI | ctli/widgets/actionform.py | Python | gpl-3.0 | 2,316 | 0.000864 | # ##### 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 3
# of the License, or (at your option) any later version.
#
# This program is distrib... | oup'] = 'Taurus Linac Widge | ts'
ret['container'] = ':/designer/dialogbuttonbox.png'
ret['container'] = False
return ret
def main():
app = Qt.QApplication(sys.argv)
w = ActionForm()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
|
Conan-Kudo/bodhi | bodhi/tests/server/views/__init__.py | Python | gpl-2.0 | 817 | 0.001225 | # Copyright © 2018 Red Hat, Inc.
#
# This file is part of Bodhi.
#
# This program is free software; you can redistribut | e it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied war... | 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Test the bod... |
zxsted/Passage | passage/inits.py | Python | mit | 701 | 0.007133 | import numpy as np
import theano
import theano.tensor as T
from theano_utils import sharedX, floatX, intX
def uniform(shape, scale=0.05):
return sharedX(np.random.uniform(low=-scale, high=scale, size=shape))
def normal | (shape, scale=0.05):
return sharedX(np.random.randn(*shape) * scale)
def o | rthogonal(shape, scale=1.1):
""" benanne lasagne ortho init (faster than qr approach)"""
flat_shape = (shape[0], np.prod(shape[1:]))
a = np.random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
q = u if u.shape == flat_shape else v # pick the one with the correct shape
... |
mrozo/PyNas | PyNAS.py | Python | bsd-3-clause | 839 | 0.001192 | try:
from DevelopmentConfig import NasConf
print("Loaded DevelopementConf file")
except ImportError:
from Config import NasConf
print("Loaded Conf file")
from ConfigParser import config_parser_class_tests, ConfigParser
from Partition import partition_class_tests
from Disk import disk_class_tests
__aut... | _ = 'm'
# todo .gitignore
# todo learn a proper unit tests
def py_nas_tests():
try:
config = ConfigParser(NasConf)
except Exception as E:
assert False, 'Failed to parse NasConfig\n' + str(E)
assert partition_class_tests(), 'Partition class tests have failed.'
assert disk_class_tests()... | |
bigmassa/django_mail_save | mail_save/urls.py | Python | mit | 238 | 0.004202 | fr | om django.conf.urls import patterns, url
from .views import EmailAlternativeView
urlpatterns = patterns(
'',
url(r'^email_alternative/(?P<pk>\d+)/$',
EmailAlternativeView.as_v | iew(),
name='email_alternative'),
) |
numericube/twistranet | twistranet/twistapp/lib/slugify.py | Python | agpl-3.0 | 1,520 | 0.006579 | import re
import unicodedata
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
# List o | f words you're not allowed to use as a slu | g
RESERVED_KEYWORDS = [
"account",
"add_to_network",
"cache",
"configuration",
"content",
"comment",
"create",
"delete",
"download",
"id",
"invitations",
"join",
"media",
"media_resource",
"menu_builder",
"new",
"resource",
"remove_from_network",
... |
google-research/augmix | imagenet.py | Python | apache-2.0 | 15,187 | 0.008692 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | h < 2 * k:
m = 0.1
else:
m = 0.01
lr = args.learning_rate * m * b
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k.""" |
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.appen... |
asvetlov/europython2015 | timerfd.py | Python | apache-2.0 | 2,878 | 0.001042 | import asyncio
import ctypes
import os
import time
import unittest
import sys
clib = ctypes.CDLL('libc.so.6', use_errno=True)
class timespec(ctypes.Structure):
_fields_ = [('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)]
class itimerspec(ctypes.Structure):
_fields_ = [('it_interval',... | timerfd_settime = clib.timerfd_settime
timerfd_settime.argtypes = [ctypes.c_int, ctypes.c_int,
ctypes.POINTER(itimerspec),
ctypes.POINTER(itimerspec)]
TFD_NON | BLOCK = os.O_NONBLOCK
CLOCK_MONOTONIC = time.CLOCK_MONOTONIC
class Timer:
def __init__(self, *, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._fileno = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK)
self._loop = loop
loop.add_reader(self._fileno, self... |
chunfengh/seq2seq | bin/tools/generate_toy_data.py | Python | apache-2.0 | 5,150 | 0.00913 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 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 req... | st([str(x) for x in range(ARGS.vocab_size - 1)])
# VOCABULARY += ["笑"]
def get_target_token(source_tokens):
num_odd = 0
num_even = 0
for token in source_tokens:
if int(token) % 2 == 0:
num_even += 1
else:
num_odd += 1
if num_even == num_odd:
return "EQUAL"
elif num_even > num_ | odd:
return "EVEN"
else:
return "ODD"
def make_copy(num_examples, min_len, max_len):
"""
Generates a dataset where the target is equal to the source.
Sequence lengths are chosen randomly from [min_len, max_len].
Args:
num_examples: Number of examples to generate
min_len: Minimum sequence len... |
ezotrank/wheezy.template | src/wheezy/template/tests/test_engine.py | Python | mit | 1,081 | 0 |
""" Unit tests for ``wheezy.templates.engine.Engine``.
"""
import unittest
class EngineTestCase(unittest.TestCase):
""" Test the ``Engine``.
"""
def setUp(self):
from wheezy.template.engine import Engine
from wheezy.template.loader import DictLoader
self.engine = Engine(
... | def test_template_not_found(self):
""" Raises IOError.
"""
self.assertRaises(IOError, lambda: self.engine.get_template('x'))
def tes | t_import_not_found(self):
""" Raises IOError.
"""
self.assertRaises(IOError, lambda: self.engine.import_name('x'))
def test_remove_unknown_name(self):
""" Invalidate name that is not known to engine.
"""
self.engine.remove('x')
def test_remove_name(self):
... |
pinard/TweeTabs | TweeTabs/Tab.py | Python | gpl-2.0 | 14,849 | 0.001617 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2009 Progiciels Bourbeau-Pinard inc.
# François Pinard <pinard@iro.umontreal.ca>, 2009.
# 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 Foundatio... | ; without 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 co | py 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. */
"""\
A Twitter reader and personal manager - Tab structures.
"""
__metaclass__ = type
import atexit, gtk, re, sys
import Common, Sched... |
tomer8007/kik-bot-api-unofficial | kik_unofficial/protobuf/messagepath/v1/visibility_rules_pb2.py | Python | mit | 5,997 | 0.00617 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: messagepath/v1/visibility_rules.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... | ning_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='drop_if_initiator_not_friend', full_name='common.messagepath.v1.VisibilityRu | lesAttachment.drop_if_initiator_not_friend', index=2,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
... |
Azure/azure-sdk-for-python | sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2021_01_15/models/_web_site_management_client_enums.py | Python | mit | 26,652 | 0.005516 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | EnumMeta, str, Enum)):
"""Certificate product type.
"""
STANDARD_DOMAIN_VALIDATED_SSL = "StandardDomainValidatedSsl"
STANDARD_DOMAIN_VALIDATED_WILD_CARD_SSL = "StandardDo | mainValidatedWildCardSsl"
class Channels(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
"""List of channels that this recommendation can apply.
"""
NOTIFICATION = "Notification"
API = "Api"
EMAIL = "Email"
WEBHOOK = "Webhook"
ALL = "All"
class CheckNameResourceTypes(with_metaclass(C... |
jakeret/tf_unet | scripts/ultrasound_launcher.py | Python | gpl-3.0 | 3,744 | 0.005342 | # tf_unet 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.
#
# tf_unet is distributed in the hope that it will be useful,
# but WITHOUT... | ataProvider(ImageDataProvider):
"""
Extends the default ImageDataProvider to randomly select the next
image and ensures that only | data sets are used where the mask is not empty.
The data then gets mean and std adjusted
"""
def __init__(self, mean, std, *args, **kwargs):
super(DataProvider, self).__init__(*args, **kwargs)
self.mean = mean
self.std = std
def _next_data(self):
data, mask = super(Dat... |
flavour/eden | controllers/msg.py | Python | mit | 87,816 | 0.011604 | # -*- coding: utf-8 -*-
"""
Messaging Module - Controllers
"""
if not settings.has_module(c):
raise HTTP(404, body="Module disabled: %s" % c)
# -----------------------------------------------------------------------------
def index():
""" Module's Home Page """
module_name = settings.modules[c].get(... | ========================================================================
def outbox():
""" View the contents of the Outbox """
if not auth.s3_logged_in():
session.error = T("Requires Login!")
redirect(URL(c="default", f="user",
args = "login",
))
f... | table = s3db[tablename]
table.message_id.label = T("Message")
table.message_id.writable = False
table.message_id.readable = True
table.pe_id.readable = True
table.pe_id.label = T("Recipient")
table.message_id.represent = s3db.msg_message_represent
table.pe_id.represent = pr_PersonEntityR... |
Pica4x6/megaradrp | megaradrp/recipes/calibration/weights.py | Python | gpl-3.0 | 15,527 | 0.002061 | from __future__ import division
import copy
import new
import math
import multiprocessing as mp
import time
import timeit
import shutil
import json as ujson
from tempfile import mkdtemp
import copy_reg
import numpy as np
import os
import os.path
from megaradrp.core.recipe import MegaraBaseRecipe
from numina.core im... | filename = '%s/%s.npz' % (path, col)
loader = np.load(filename)
return csr_matrix(
(loader['data'], loader['indices'], loader['indptr']),
shape=loader['shape'])
def load_files_from_directory(self, path, tar_file=None):
'''
:param path: <str> path to load ... | e: <str> if it is given, *.fits files are extracted
:return: list of csr_matrix
'''
if tar_file:
path = self.decompress()
pool = mp.Pool(processes=self.procesos)
results = [pool.apply_async(self._load_files_paralell,
args=(ite, pa... |
rmyers/clouddb-rpc | dashboard/stashboard/content/databases/views.py | Python | apache-2.0 | 19,542 | 0 | # Copyright 2013 Rackspace Hosting
#
# 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 ... | ions import OrderedDict
import logging
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ug | ettext_lazy as _
import six
from horizon import exceptions
from horizon import forms as horizon_forms
from horizon import tables as horizon_tables
from horizon import tabs as horizon_tabs
from horizon.utils import memoized
from horizon import workflows as horizon_workflows
from openstack_dashboard.dashboards.project.... |
pombredanne/metamorphosys-desktop | metamorphosys/META/src/CADAssembler/ExtractACM-XMLfromCreoModels/testExtractACM.py | Python | mit | 4,969 | 0.00322 | # Copyright (C) 2013-2015 MetaMorph Software, Inc
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this data, including any software or models in source or binary
# form, as well as any drawings, specifications, and documentation
# (collectively "the Data"), to deal in the Data ... | ice and this permission notice shall be included
# in all copies or substantial portions of the Data.
# THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EV... | S, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
# =======================
# This version of the META to... |
pczhaoyun/wolf | wolf/spiders/wolves/henbt.py | Python | apache-2.0 | 1,085 | 0.004608 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urlparse
from scrapy import log
from scrapy.http import Request
from base.base_wolf import Base_Wolf
class Wolf(Base_Wolf):
def __init__(self, *args, **kwargs):
super(Wolf, self).__init__(*args, **kwargs)
| self.name = 'henbt'
self.seed_urls = [
'http://henbt.com/',
]
self.base_url = 'http://henbt.com/'
self.rule['follow'] = re.compile(r'show-')
self.anchor['desc'] = "//*[@class='intro']"
def get_resource(self, item, response, tree):
item = super(Wolf, self)... | , tree)
resource = tree.xpath("//*[@class='original download']//a/@href")
downloads = [urlparse.urljoin(self.base_url, r) for r in resource if re.match(r'down.php', r)]
if len(downloads):
return self.download_bt(item, [Request(d, cookies=self.cookiejar._cookies,) for d in downloads... |
momomoxiaoxi/security | Scripts/Check.py | Python | apache-2.0 | 574 | 0.019164 | #!/usr/bin/env python
#!-*- coding:utf-8 -*-
def read(filename):
dic=[]
with open(filename,'r') as fp:
w | hile True:
lines = fp.readlines(10000)
if not lines :
break
for line in lines:
#line = line.strip('\n')
dic.append(line)
return dic
def Write(file,dic):
with open(file,'w') as fp:
for i in dic:
fp.write(i)
... | t.txt',set(test))
|
superdesk/superdesk-core | content_api/packages/__init__.py | Python | agpl-3.0 | 721 | 0 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and co | ntributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import superdesk
from .service import PackagesService
from .resource import PackagesResource
def init_app(app) -> None:
... | "
service = PackagesService(endpoint_name, backend=superdesk.get_backend())
PackagesResource(endpoint_name, app=app, service=service)
|
pixelrebel/st2 | st2actions/tests/unit/test_paramiko_remote_script_runner.py | Python | apache-2.0 | 5,199 | 0.0025 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | timeout=None)
@patch('st2common.runners.parallel_ssh.ParallelSSHClient', Mock)
@patch.object(ParallelSSHClient, 'run', MagicMock(return_value={}))
@patch.object(ParallelSSHClient, 'connect', MagicMock(return_value={}))
def test_username_only_ssh(self):
... | }
self.assertRaises(InvalidCredentialsException, paramiko_runner.pre_run)
def test_username_invalid_private_key(self):
paramiko_runner = ParamikoRemoteScriptRunner('runner_1')
paramiko_runner.runner_parameters = {
'username': 'test_user',
'hosts': '127.0.0.1',
... |
jck/myhdl | myhdl/_instance.py | Python | lgpl-2.1 | 3,952 | 0.000253 | # This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by t... | not have arguments"
_error.ArgType = "decorated object should be a generator function"
class _CallInfo(object):
def __init__(self, name, modctxt, symdict):
self.name = name
self.modctxt = modctxt
self.symdict = symdict
def _getCallInfo():
"""Get info on the caller of an Instantiato... | his function gets the required info about the caller.
It uses the frame stack:
0: this function
1: the instantiator decorator
2: the block function that defines instances
3: the caller of the block function, e.g. the BlockInstance.
"""
from myhdl import _block
funcrec = inspect.stack()[2... |
whoi-acomms/pyacomms | bin/console_logger.py | Python | lgpl-3.0 | 941 | 0.014878 | #!/usr/bin/env python |
#__author__ = 'Andrew'
from acomms import micromodem, unifiedlog
import logging
from time import sleep
import argparse
if __name__ == '__main__':
ap = argparse.ArgumentParser(description ='Connect to a MM for testing purposes')
ap.add_argument("logpath", help="Location of Log File", default... | OM Port to connect', default="/dev/ttyO1")
ap.add_argument("-BR","--Baudrate", help="COM Port Baud Rate", default=19200)
args = ap.parse_args()
unified_log = unifiedlog.UnifiedLog(log_path=args.logpath, console_log_level=logging.INFO)
um1 = micromodem.Micromodem(name=... |
CptLemming/django-json-patch | docs/conf.py | Python | bsd-3-clause | 8,191 | 0.007447 | # -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... | served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-json-patchdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# ... | ze ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [... |
ktbyers/pynet-ons-mar17 | threads_procs/threads_show_ver.py | Python | apache-2.0 | 1,188 | 0.003367 | #!/usr/bin/env python
'''
Use threads and Netmiko to connect to each of the devices. Execute
'show version' on each device. Record the amount of time required to do this.
'''
import threading
from datetime import datetime
from netmiko import ConnectHandler
from my_devices import device_list as devices
def show_version... | 0
print remote_conn.send_command_expect("show version")
print '#' * 80
print
def main():
'''
Use threads and Netmiko to connect to each of the devices. Execute
'show version' on e | ach device. Record the amount of time required to do this.
'''
start_time = datetime.now()
for a_device in devices:
my_thread = threading.Thread(target=show_version, args=(a_device,))
my_thread.start()
main_thread = threading.currentThread()
for some_thread in threading.enumerate()... |
faunalia/rt_geosisma_offline | Utils.py | Python | gpl-3.0 | 8,122 | 0.034105 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Omero RT
Description : Omero plugin
Date : August 15, 2010
copyright : (C) 2010 by Giuseppe Sucameli (Faunalia)
email : sucameli@faunalia.i... | = layer.getFeatur | es(QgsFeatureRequest().setFilterFid( featureId ))
ret = f.next()
else:
IDs = [f.id() for f in layer.getFeatures(QgsFeatureRequest(rect))]
if onlyIds:
ret = IDs
else:
ret = []
for featureId in IDs:
f = layer.getFeatures(QgsFeatureRequest().setFilterFid( featureId ))
ret.append( f )... |
epitron/youtube-dl | youtube_dl/extractor/huajiao.py | Python | unlicense | 1,850 | 0 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from | ..utils import (
parse_duration,
parse_iso8601,
)
class HuajiaoIE(InfoExtractor):
IE_DESC = '花椒直播'
_VALID_URL = r'https?://(?:www\.)?huajiao\.com/l/(?P<id>[0-9]+)'
_TEST = {
| 'url': 'http://www.huajiao.com/l/38941232',
'md5': 'd08bf9ac98787d24d1e4c0283f2d372d',
'info_dict': {
'id': '38941232',
'ext': 'mp4',
'title': '#新人求关注#',
'description': 're:.*',
'duration': 2424.0,
'thumbnail': r're:^https?://.*... |
plotly/plotly.py | packages/python/plotly/plotly/validators/carpet/_a0.py | Python | mit | 380 | 0 | import _plotly_utils.basevalidators
class A0Validator(_plotl | y_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="a0", parent_name="carpet", **kwargs):
super(A0Validator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
| )
|
danhuss/faker | faker/providers/ssn/en_PH/__init__.py | Python | mit | 2,596 | 0.005008 | from ... import BaseProvider
class Provider(BaseProvider):
"""
Provider for Philippine IDs that are related to social security
There is no unified social security program in the Philippines. Instead, the Philippines has a messy collection of
social programs and IDs that, when put together, serves as ... | om_element(self.umid_formats))
def ssn(self):
# Use UMID as SSN in the interim till its deprecatio | n
return self.umid()
|
jorisroovers/gitlint | gitlint-core/gitlint/tests/samples/user_rules/parent_package/__init__.py | Python | mit | 336 | 0.002985 | # -*- coding: utf-8 -*-
# This file is | meant to test that we can also load rules from __init__.py files, this was an issue with pypy before.
from gitlint.rules import CommitRule
class InitFileRule(CommitRule):
name = "my-init-cömmit-rule"
id = "UC1"
options_spec = []
def validate(s | elf, _commit):
return []
|
thinkernel/buck | src/com/facebook/buck/command/intellij.py | Python | apache-2.0 | 15,347 | 0.008927 | import errno
import fnmatch
import json
import os
import re
import subprocess
import sys
MODULE_XML_START = """<?xml version="1.0" encoding="UTF-8"?>
<module type="%(type)s" version="4">"""
MODULE_XML_END = """
</module>
"""
ANDROID_FACET = """
<component name="FacetManager">
<facet type="android" name="Andro... | telliJPlugin']:
module_type = 'PLUGIN_MODULE'
xml = MODULE_XML_START % {
'type': module_type,
}
# Android facet, if appropriate.
if module.get('hasAndroidFacet') == True:
if 'keystorePath' in module:
keystore = 'file://$MODULE_DIR$/%s' % module['keystorePath']
else:
... | android_manifest = module['androidManifest']
else:
android_manifest = '/AndroidManifest.xml'
is_library_project = module['isAndroidLibraryProject']
android_params = {
'android_manifest': android_manifest,
'res': '/res',
'is_android_library_project': str(is_libr... |
largetalk/tenbagger | capital/reactor/cc/migrations/0004_auto_20180313_1052.py | Python | mit | 386 | 0 | # Generated by Django 2.0.2 on 2018-03-13 02:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cc', ' | 0003_auto_20180228_1145'),
]
operations = [
migrations.AlterF | ield(
model_name='creditcard',
name='tail_no',
field=models.CharField(max_length=10),
),
]
|
cc-archive/jtoolkit | jToolkit/localize.py | Python | gpl-2.0 | 6,307 | 0.015538 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""extends the standard Python gettext classes
allows multiple simultaneous domains... (makes multiple sessions with different languages easier too)"""
# Copyright 2002, 2003 St James Software
#
# This file is part of jToolkit.
#
# jToolkit is free software; you can redi... | =None):
"""same as gettext.find, but handles many domains, returns many mofiles (not just one)"""
mofiles = []
if languages is None:
languages = getin | stalledlanguages(localedir)
for domain in domains:
mofile = gettext.find(domain, localedir, languages)
mofiles.append(mofile)
return mofiles
def translation(domains, localedir=None, languages=None, class_=None):
"""same as gettext.translation, but handles many domains, returns a ManyTranslations object""... |
capital-boss/plate-recognition | msp.py | Python | apache-2.0 | 1,393 | 0.002872 | import sys
import cv2
import helper as hp
class MSP():
name = "MSP"
def __init__(self):
self.__patterns_num = []
self.__patterns_sym = []
self.__labels_num = []
self.__labels_sym = []
msp_num, msp_sym = "msp/num", "msp/sym"
self.__load_num_patterns(msp_num)
... | self.__patterns | _num
elif mode == "sym":
return self.__labels_sym, self.__patterns_sym
def rec(self, img, mode):
tmp_max, tmp, rec = sys.maxint, 0, 0
labels, patterns = self.__get_mode(mode)
for pattern, label in zip(patterns, labels):
tmp = cv2.countNonZero(pattern - img)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.