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 |
|---|---|---|---|---|---|---|---|---|
SebastienPittet/cavelink | setup.py | Python | mit | 1,270 | 0 | # coding: utf-8
"""
A simple module to fetch Cavelink values by parsing the HTML page of sensors.
"""
from setuptools import find_packages, setup
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='cavelink',
version='1.1.1',
author='Sébastien Pittet',
author_email='sebast... | of sensors.',
long_description=long_description,
url='https://github.com/SebastienPittet/cavelink',
keywords='speleo cave sensor',
packages=find_packages(),
license='MIT',
platforms='any',
install_requires=['p | ython-dateutil', 'requests'],
classifiers=[
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.4',
'Programming Language... |
fxstein/ISYlib-python | bin/isy_net_wol.py | Python | bsd-2-clause | 1,132 | 0.013251 | #!/usr/local/bin/python3.4
"""
Simple example to send a WoL to a registared system on the ISY
if this script is call without any arg
we print a list of registared WoL systems
if we have any args we treat them as registared WoL Id's
and attempt to send a WoL packet
"""
__author__ = "Peter Shipley"
imp | ort sys
import ISY
from ISY.IsyExceptionClass import IsyResponseError, IsyValueError
def main(isy):
if len(sys.argv[1:]) > 0:
for a in sys.argv[1:] :
try :
isy.n | et_wol(a)
except (IsyValueError, IsyResponseError) as errormsg :
print("problem sending WOL to {!s} : {!s}".format(a, errormsg))
continue
else :
print("WOL sent to {!s}".format(a))
else :
pfmt = "{:<5}{:<16} {:<20}"
print(pfmt.f... |
mdlawson/autojump | install.py | Python | gpl-3.0 | 5,781 | 0.000346 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import platform
import shutil
import sys
sys.path.append('bin')
from autojump_argparse import ArgumentParser
SUPP | ORTED_SHELLS = ('bash', 'zsh', 'fish')
def cp(src, dest, dryrun=False):
print("copying file: %s -> %s" % (src, dest))
if not dryrun:
shutil.copy(src, dest)
def get_shell():
return os.path.b | asename(os.getenv('SHELL', ''))
def mkdir(path, dryrun=False):
print("creating directory:", path)
if not dryrun and not os.path.exists(path):
os.makedirs(path)
def modify_autojump_sh(etc_dir, dryrun=False):
"""Append custom installation path to autojump.sh"""
custom_install = "\
\n# ... |
EternityForest/KaithemAutomation | kaithem/data/modules/Beholder/main.py | Python | gpl-3.0 | 787 | 0.01906 | ## Code outside the data string, and the setup and action blocks is ignored
## If manually editing, you m | ust reload the code. Delete the resource timestamp so kaithem knows it's new
__data__="""
{continual: false, enable: true, once: true, priority: interactive, rate-limit: 0.0,
resource-timestamp: 1645141613510257, resource-type: event}
"""
__trigger__='False'
if __name__=='__setup__':
#This code runs once when ... | t loads. It also runs when you save the event during the test compile
#and may run multiple times when kaithem boots due to dependancy resolution
__doc__=''
def nbr():
return(50, '<a href="/pages/Beholder/ui"><i class="icofont-castle"></i>Beholder</a>')
kaithem.web.navBarPlugins['Beholder']... |
clebergnu/autotest | client/common_lib/hosts/__init__.py | Python | gpl-2.0 | 435 | 0 | # | Copyright 2009 Google Inc. Released under the GPL v2
"""This is a convenience module to import all available types of hosts.
Implementation details:
You should 'import hosts' instead of importing every available host module.
"""
from autotest_lib.client.common_lib import utils
import base_classes
Host = utils.impor... | .Host)
|
zstackorg/zstack-woodpecker | integrationtest/vm/multihosts/volumes/test_snapshot_resize_vm.py | Python | apache-2.0 | 1,782 | 0.002806 | '''
New Integration Test for resizing root volume.
@author: czhou25
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.ope... | after)
snapshots.delete()
test_obj_dict.rm_volume_snapshot(snapshots)
test_lib.lib_error_cleanup(test_obj_dict)
test_util.test_pass('Resize VM Snapshot Test Success')
#Will be called only if exception happens in test().
def error_cleanup():
test_lib.lib_error_clea | nup(test_obj_dict)
|
mPowering/django-orb | orb/fixtures/__init__.py | Python | gpl-3.0 | 2,306 | 0.000869 | # -*- coding: utf-8 -*-
"""
pytest fixtures
"""
import pytest
from django.contrib.auth.models import User
from orb.models import Category, Tag, UserProfile
from orb.peers.models import Peer
from orb.resources.tests.factory import resource_factory
pytestmark = pytest.mark.django_db
@pytest.fixture
def testing_user... | ,
"create_user": testing_user,
"update_user": testing_user,
})
assert Tag.tags.roles()
yield tag
@pytest.fixture
def test_resource(testing_user):
yield resource_factory(
user=testing_user,
title=u" | Básica salud del recién nacido",
description=u"Básica salud del recién nacido",
)
@pytest.fixture(scope="session")
def test_peer():
peer = Peer.peers.create(name="Distant ORB", host="http://www.orb.org/")
yield peer
@pytest.fixture(scope="session")
def remote_resource(import_user, test_peer):
... |
agrajaghh/duplicati | guiTests/guiTest.py | Python | lgpl-2.1 | 8,072 | 0.002602 | import os
import sys
import shutil
import errno
import time
import hashlib
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
if "TRAVIS_BUILD_NUMBER" in os.environ:
if "SAUCE_... | /dd/p/span[contains(text(),'Run now')]") if n.is_displayed()][0].click()
wait_for_text(60, "//div[@class='task ng-scope']/dl[2]/dd[1]", "(took ")
# Restore
if len([n for n in driver.find_elemen | ts_by_xpath("//span[contains(text(),'Restore files ...')]") if n.is_displayed()]) == 0:
driver.find_element_by_link_text(BACKUP_NAME).click()
[n for n in driver.find_elements_by_xpath("//span[contains(text(),'Restore files ...')]") if n.is_displayed()][0].click()
driver.find_element_by_xpath("//span[contains(text(... |
graphql-python/graphene | examples/starwars_relay/data.py | Python | mit | 1,593 | 0.001255 | data = {}
def setup():
global data
from .schema import Ship, Faction
xwing = Ship(id="1", name="X-Wing")
ywing = Ship(id="2", name="Y-Wing")
awing = Ship(id="3", name="A-Wing")
# Yeah, technically it's Corellian. But it flew in the service of the rebels,
# so for the purposes of this ... | s():
return | get_faction("1")
def get_empire():
return get_faction("2")
|
jordanjoz1/flickr-views-counter | count_views.py | Python | mit | 4,590 | 0 | import flickrapi
import csv
import sys
import datetime
import argparse
import os
# environment variable keys
ENV_KEY = 'FLICKR_API_KEY'
ENV_SECRET = 'FLICKR_API_SECRET'
MAX_PHOTOS_PER_PAGE = 500
# column headers for output file
columns = ['Title', 'Upload date', 'photo_id', 'url', 'Description',
'View cou... | s.search(
user_id=userId, per_page=str(MAX_PHO | TOS_PER_PAGE), page=page))
# get view count for each photo
data = []
for photo_page in photo_pages:
for photo in photo_page[0]:
data.append(get_photo_data(photo.get('id')))
# write counts to output
if (fname is not None):
rows = create_rows_from_data(data)
write... |
ygol/odoo | addons/mrp_subcontracting/models/stock_move_line.py | Python | agpl-3.0 | 1,039 | 0.002887 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class StockMoveLine(models.Model):
_inherit = 'stock.move.line'
@api.model_create_multi
def create(self, vals_list):
records = super(StockMoveLine, self).create(vals_li... | eservation and self.move_id.is_subcontract:
re | turn True
return should_bypass_reservation
|
Blackclaws/client | src/downloadManager/__init__.py | Python | gpl-3.0 | 3,779 | 0.00688 | from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest
from PyQt4 import QtGui, QtCore
import urllib2
import logging
import os
import util
import warnings
logger= logging.getLogger(__name__)
VAULT_PREVIEW_ROOT = "http://content.faforever.com/faf/vault/map_previews/small/"
class downloadManager(QtCore.QOb... | ing()] = []
request = QNetworkRequest(url)
self.nam.get(request)
self.mapRequests[url.toString()].append(requester)
else :
self.mapRequests[url.toString()].append(requester)
if item:
self.mapRequestsItem.append(requester)
def downloadModPr... | rl = QtCore.QUrl(strurl)
if not url.toString() in self.modRequests:
logger.debug("Searching mod preview for: " + os.path.basename(strurl).rsplit('.',1)[0])
self.modRequests[url.toString()] = []
request = QNetworkRequest(url)
self.nam.get(request)
self.modR... |
oubiwann/txjsonrpc | examples/ssl/client.py | Python | mit | 1,418 | 0.009168 | from __future__ import print_function
import logging
from twisted.internet import reactor, ssl
from txjsonrpc.web.jsonrpc import Proxy
from OpenSSL import SSL
from twisted.python import log
def printValue(value):
print("Result: %s" % str(value))
def printError(error):
print('error', error)
def shutDown(dat... | def verifyCallback(connection, x509, errnum, | errdepth, ok):
log.msg(connection.__str__())
if not ok:
log.msg('invalid server cert: %s' % x509.get_subject(), logLevel=logging.ERROR)
return False
else:
log.msg('good server cert: %s' % x509.get_subject(), logLevel=logging.INFO)
return True
class AltCtxFactory(ssl.ClientCo... |
MungoRae/home-assistant | homeassistant/components/scene/lifx_cloud.py | Python | apache-2.0 | 2,931 | 0 | """
Support for LIFX Cloud scenes.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/scene.lifx_cloud/
"""
import asyncio
import logging
import voluptuous as vol
im | port aiohttp
import async_timeout
from homeassistant.components.scene import Scene
from homeassistant.const import (CONF_PLATFORM, CONF_TOKEN, CONF_TIMEOUT)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.aiohttp_client import (async_get_clien | tsession)
_LOGGER = logging.getLogger(__name__)
LIFX_API_URL = 'https://api.lifx.com/v1/{0}'
DEFAULT_TIMEOUT = 10
PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): 'lifx_cloud',
vol.Required(CONF_TOKEN): cv.string,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
})
# pyl... |
sidnarayanan/IntelROCCS | Detox/python/siteProperties.py | Python | mit | 12,964 | 0.011571 | #====================================================================================================
# C L A S S E S concerning the site description
#====================================================================================================
#----------------------------------------------------------------... | nt datasetName
#addedExtra = addedExtra + 1
continue
if "/REC | O" in datasetName:
delta = (self.epochTime - self.dsetUpdTime[datasetName])/(60*60*24)
#if dataPropers[datasetName].daysSinceUsed() > 180 and delta>180:
if delta > 180:
space = space + self.datasetSizes[datasetName]
self.wishList.append(datasetName)
dataPropers... |
TimurNurlygayanov/mistral | mistral/api/controllers/v1/workbook_definition.py | Python | apache-2.0 | 1,511 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | ort expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services | import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
@expose()
def get(self, workbook_name):
LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_nam... |
Arno-Nymous/pyload | module/lib/beaker/crypto/__init__.py | Python | gpl-3.0 | 1,233 | 0 | from warnings import warn
from beaker.crypto.pbkdf2 import PBKDF2, strxor
from beaker.crypto.util import hmac, sha1, hmac_sha1, md5
from beaker import util
keyLength = None
if util.jython:
try:
from beaker.crypto.jcecrypto import getKeyLength, aesEncrypt
keyLength = getKeyLength()
except Impo... | nerated session cookies may b | e incompatible with other '
'environments' % (keyLength * 8))
def generateCryptoKeys(master_key, salt, iterations):
# NB: We XOR parts of the keystream into the randomly-generated parts, just
# in case os.urandom() isn't as random as it should be. Note that if
# os.urandom() returns truly random... |
The-Tasty-Jaffa/Tasty-Jaffa-cogs | say/say.py | Python | gpl-3.0 | 6,218 | 0.008363 | import discord, os, logging
from discord.ext import commands
from .utils import checks
from .utils.dataIO import dataIO
from .utils.chat_formatting import pagify, box
#The Tasty Jaffa
#Requested by Freud
def get_role(ctx, role_id):
roles = set(ctx.message.server.roles)
for role in roles:
if role.id ==... | rver.id]["ROLE"]
self.settings[server.id]["USERS"]
except:
self.settings[server.id] = {}
self.settings[server.id]["ROLE"] = None
self.settings[server.id]["USERS"] = []
@commands.group(name="setsay", pass_context | =True, no_pm=True, invoke_without_command=True)
async def sayset(self, ctx):
"""The 'Say' command set
add - Adds a user to have the abillity to use the speak command
list - list users allowed and permited role
remove - Removes a user to have the abillity to use the speak command
role - Adds a permited role... |
guilhermef/aws | tc_aws/loaders/s3_loader.py | Python | mit | 2,000 | 0.0025 | # coding: utf-8
from boto.s3.bucket import Bucket
from thumbor.utils import logger
from tornado.concurrent import return_future
import urllib2
import thumbor.loaders.http_loader as http_loader
from tc_aws.aws.connection import get_connection
def _get_bucket(url, root_path=None):
"""
Returns a tuple contain... | t('S3_ALLOWED_BUCKETS', default=None)
return not allowed_buckets or bucket in allowed_buckets
@return_future
def load(context, url, callback | ):
enable_http_loader = context.config.get('AWS_ENABLE_HTTP_LOADER', default=False)
if enable_http_loader and url.startswith('http'):
return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url)
url = urllib2.unquote(url)
bucket = context.config.get('S3_LOADER_BUCKE... |
dawran6/zulip | zerver/tests/test_push_notifications.py | Python | apache-2.0 | 17,956 | 0.001337 | import mock
from mock import call
import time
from typing import Any, Dict, Union, SupportsInt, Text
import gcm
from django.test import TestCase
from django.conf import settings
from zerver.models import PushDeviceToken, UserProfile, Message
from zerver.models import get_user_profile_by_email, receives_online_notifi... |
err_rsp = self.get_error_response(identifier=100, status=8)
b64_token = apn.hex_to_b64('aaaa')
self.assertEqual(PushDeviceToken.objects. | filter(
user=self.user_profile, token=b64_token).count(), 1)
apn.response_listener(err_rsp)
self.assertEqual(mock_warn.call_count, 2)
self.assertEqual(PushDeviceToken.objects.filter(
user=self.user_profile, token=b64_token).count(), 0)
class TestPushApi(ZulipTestCase):
... |
RussellRiesJr/CoupleComeStatWithMe | ccswm/statApi/serializers.py | Python | mit | 1,581 | 0.001898 | from ccswm.statApi.models import *
from rest_fram | ework import serializers
class EpisodeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Episode
fields = ('id', 'url', 'season', 'episodeNumber', 'location')
class StarterSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Starter
fie... | ):
class Meta:
model = Entree
fields = ('id', 'url', 'protein', 'proteinStyle', 'side', 'sideStyle')
class DessertSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Dessert
fields = ('id', 'url', 'main', 'secondary')
class EntertainmentSerializer(serializ... |
tiangolo/fastapi | docs_src/extra_models/tutorial002.py | Python | mit | 824 | 0 | from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class UserBase(BaseModel):
username: str
email: EmailStr
ful | l_name: Optional[str] = None
class UserIn(UserBase):
password: str
|
class UserOut(UserBase):
pass
class UserInDB(UserBase):
hashed_password: str
def fake_password_hasher(raw_password: str):
return "supersecret" + raw_password
def fake_save_user(user_in: UserIn):
hashed_password = fake_password_hasher(user_in.password)
user_in_db = UserInDB(**user_in.dict(), h... |
Psycojoker/geholparser | src/gehol/__init__.py | Python | mit | 76 | 0 | __version__ = '0.1'
from geholproxy import *
from geholexceptio | ns impor | t *
|
tempbottle/restcommander | play-1.2.4/python/Lib/_abcoll.py | Python | apache-2.0 | 13,666 | 0.000951 | # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrappin... | rom_iterable(cls, it):
'''Construct an ins | tance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
'''
return cls(it)
def __and__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
retu... |
encukou/freeipa | ipaclient/plugins/user.py | Python | gpl-3.0 | 2,966 | 0 | # Authors:
# Jason Gerard DeRose <[email protected]>
# Pavel Zuna <[email protected]>
#
# Copyright (C) 2008 Red H | at
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This prog... | d warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ipaclient.frontend import MethodOverride
from i... |
davelab6/pyfontaine | fontaine/charsets/noto_chars/notosansolditalic_regular.py | Python | gpl-3.0 | 2,939 | 0.015652 | # -*- coding: utf-8 -*-
class Charset(object):
common_name = 'NotoSansOldItalic-Regular'
native_name = ''
def glyphs(self):
chars = []
chars.append(0x0000) #uniFEFF ????
chars.append(0x0020) #uni00A0 SPACE
chars.append(0x00A0) #uni00A0 NO-BREAK SPACE
chars.appen... | 0x10303) #glyph00007 OLD ITALIC LETTER DE
chars.append(0x10304) #glyph00008 OLD ITALIC LETTER E
chars.append(0x10305) #glyph00009 OLD ITALIC LETTER VE
ch | ars.append(0x10306) #glyph00010 OLD ITALIC LETTER ZE
chars.append(0x10307) #glyph00011 OLD ITALIC LETTER HE
chars.append(0x10308) #glyph00012 OLD ITALIC LETTER THE
chars.append(0x10309) #glyph00013 OLD ITALIC LETTER I
chars.append(0x1030A) #glyph00014 OLD ITALIC LETTER KA
ch... |
maniteja123/numpy | numpy/distutils/fcompiler/gnu.py | Python | bsd-3-clause | 14,957 | 0.001872 | from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_uti... | f d is not None:
g2c = self.g2c + '-pic'
f = self.static_lib_format % (g2c, self.static_lib_extension)
if not os.path.isfile(os.path.join(d, f)):
g2c = self.g2c
else:
g2c = self.g2c
if g2c is not None:
opt.app | end(g2c)
c_compiler = self.c_compiler
if sys.platform == 'win32' and c_compiler and \
c_compiler.compiler_type == 'msvc':
# the following code is not needed (read: breaks) when using MinGW
# in case want to link F77 compiled code with MSVC
opt.append('g... |
ge0rgi/cinder | cinder/tests/unit/api/v3/test_volume_manage.py | Python | apache-2.0 | 8,439 | 0 | # Copyright (c) 2016 Stratoscale, Ltd.
#
# 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 ... | ' + version
req.environ['cinder.context'] = self._admin_ctxt
req. | body = jsonutils.dump_as_bytes(body)
res = req.get_response(app())
return res
@mock.patch('cinder.volume.api.API.manage_existing',
wraps=test_contrib.api_manage)
@mock.patch(
'cinder.api.openstack.wsgi.Controller.validate_name_and_description')
def test_manage_volume... |
TheMOOCAgency/edx-platform | openedx/core/djangoapps/programs/tasks/v1/tests/test_tasks.py | Python | agpl-3.0 | 14,729 | 0.00224 | """
Tests for programs celery tasks.
"""
import json
import unittest
from celery.exceptions import MaxRetriesExceededError
import ddt
from django.conf import settings
from django.core.cache import cache
from django.test import override_settings, TestCase
from edx_rest_api_client.client import EdxRestApiClient
from edx... | ef _assert_num_requests(self, count):
"""DRY helper for verifying request counts."""
self.assertEqual(len(httpretty.httpretty.latest_requests), count)
@mock.patch(UTILS_MODULE + '.get_completed_courses')
def test_get_ | completed_programs(self, mock_get_completed_courses):
"""
Verify that completed programs are found, using the cache when possible.
"""
course_id = 'org/course/run'
data = [
factories.Program(
organizations=[factories.Organization()],
co... |
kumar303/rockit | vendor-local/boto/s3/bucket.py | Python | bsd-3-clause | 62,883 | 0.001749 | # Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# All rights reserved.
#
# 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 res... | license, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be inc | luded
# 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 PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ... |
rossant/galry | examples/modern_art.py | Python | bsd-3-clause | 365 | 0.00274 | """Modern art."""
from galry import *
import num | py.random as rdn
figure(constrain_ratio=True, antialiasing=True)
# random positions
positions = .25 * rdn.randn(1000, 2)
# random colors
colors = rdn.rand(len(positions),4)
# TRIANGLES: three consecutive points = o | ne triangle, no overlap
plot(primitive_type='TRIANGLES', position=positions, color=colors)
show()
|
volnt/22board | app/config.py | Python | mit | 240 | 0 | from os import environ
AWS_ACCE | SS_KEY_ID = environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY = environ["AWS_SECRET_ACCESS_KEY"]
BUCKET_NAME = "22board-captchas"
AWS_ROOT_URL = "https: | //s3-eu-west-1.amazonaws.com/{}/".format(BUCKET_NAME)
|
cubiks/rpi_thermo_py | test/test_logging.py | Python | mit | 147 | 0 | import | logging.config
logging.config.fileConfig("config/logging.conf")
logger = logging.getLogger("temp")
logger.info("Using temperature | logger")
|
danielhers/ucca | scripts/set_external_id_offline.py | Python | gpl-3.0 | 1,091 | 0.003666 | #!/usr/bin/env python3
import argparse
import os
import sys
from ucca.ioutil import get_passages_with_progress_bar, write_passage
desc = """Rename passages by a given mapping of IDs"""
def main(filename, input_filenames, outdir):
os.makedirs(outdir, ex | ist_ok=True)
with open(filename, encoding="utf-8") as f:
pairs = [line.strip().split() for line in f]
old_to_new_id = {old_id: new_id for new_id, old_id in pairs}
for passage in get_passages_with_progress_bar(input_filenames, desc="Renaming"):
passage._ID = old_to_new_id[passage.ID]
... | ge(passage, outdir=outdir, verbose=False)
if __name__ == "__main__":
argument_parser = argparse.ArgumentParser(description=desc)
argument_parser.add_argument("filename", help="file with lines of the form <NEW ID> <OLD ID>")
argument_parser.add_argument("input_filenames", help="filename pattern or director... |
fniephaus/alfred-homebrew | src/brew.py | Python | mit | 12,427 | 0.000644 | # encoding: utf-8
import os
import subprocess
import sys
from workflow import Workflow3 as Workflow, MATCH_SUBSTRING
from workflow.background import run_in_background
import brew_actions
import helpers
GITHUB_SLUG = 'fniephaus/alfred-homebrew'
def execute(wf, cmd_list):
brew_arch = helpers.get_brew_arch(wf)
... | la,
valid=True,
icon=helpers.get_icon(wf, 'package'))
elif query and query.startswith('services'):
query_filter = query.split()
if len(query_filter) == 2 and query.endswith(' '):
| service_name = query_filter[1]
add_service_actions(wf, service_name)
else:
services = filter_all_services(wf, query)
for service in services:
wf.add_item(service['name'], 'Select for action. Status: %s' % service['status'],
... |
pythonchelle/opencomparison | apps/pypi/slurper.py | Python | mit | 2,191 | 0.010041 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PyPI interface (see http://wiki.python.org/moin/PyPiXmlRpc)
"""
from datetime import datetime
import itertools
import re
import xmlrpclib
from django.template.defaultfilters import slugify
from package.models import Category, Package, Version
from pypi.versioning im... | title='Python', slug='python')
self.dumb_category.save()
def get_latest_version_number(self, package_name, versions=None):
""" Returns the latest version number for a package """
if versions:
return highest_version(versions)
else:
... | PYPI.release_data(package_name, version)
pypi_url = base_url + package_name
package, created = Package.objects.get_or_create(
title = data['name'],
slug = slugify(package_name),
category = self.dumb_category,
pypi_url = ... |
kfcpaladin/sze-the-game | renpy/gl/glblacklist.py | Python | mit | 1,846 | 0 | # Copyright 2004-2017 Tom Rothamel <[email protected]>
#
# 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, m... | LIST = [
# Crashes for Mugenjohncel.
("S3 Graphics DeltaChrome", "1.4 20.00", False, False),
# A bug in Mesa 7.9 and 7.10 (before 7 | .10.3) causes the system to
# fail to initialize the GLSL compiler.
# https://bugs.freedesktop.org/show_bug.cgi?id=35603
("Mesa", "Mesa 7.9", False, True),
("Mesa", "Mesa 7.10.3", True, True),
("Mesa", "Mesa 7.10", False, True),
# Default to allowing everything.
("", "", True, True),
]
|
rizzatti/luigi | examples/elasticsearch_index.py | Python | apache-2.0 | 3,410 | 0.00176 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | oIndex.run`.
After running this task you can run:
.. code-block:: console
$ curl "localhost:9200/example_index/_search?pretty"
to see the indexed documents.
To see the update log, run
.. code-block:: console
$ curl "localhost:9200/update_log/_search?q=target_index:example_inde... | DELETE "localhost:9200/update_log/_query?q=target_index:example_index"
"""
#: date task parameter (default = today)
date = luigi.DateParameter(default=datetime.date.today())
#: the name of the index in ElasticSearch to be updated.
index = 'example_index'
#: the name of the document type.
d... |
TalatCikikci/heritago | heritago/heritago/urls.py | Python | mit | 1,796 | 0.000557 | """ heritago URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... | ogout/$', views.logout, name='logout'),
# url(r'^invalid/$', views.invalid_login, name='invalid_login'),
# url(r'^r | egister/$', views.register_user, name='register_user'),
# url(r'^profile/$', views.user_profile, name='user_profile'),
# url(r'^change_password/$', views.change_password , name='password-change'),
]
urlpatterns += router.urls
|
Jumpers/MysoftAutoTest | Step1-PythonBasic/Practices/yuxq/1-5/ex5.py | Python | apache-2.0 | 570 | 0.033333 | my_name='Zed A. Shaw'
my_age=35 #notalie
my_height=74 #inches
my_weight=180 #lbs
my_eyes='Blue'
my_teeth='White'
my_hair='Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %... | es,my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
#this line is tricky,try to get it exactly r | ight
print "If I add %d,%d,and %d I get %d." % (
my_age,my_height,my_weight,my_age+my_height+my_weight) |
blurstudio/cross3d | cross3d/classes/__init__.py | Python | mit | 434 | 0.016129 | ##
# \namespace cross3d.classes
#
| # \remarks [desc::commented]
#
# \author Mikeh
# \author Blur Studio
# \date 06/08/11
#
from fcurve import FCurve
from exceptions import Exceptions
from dispatch import Dispatch
from clipboard import Clipboard
from valuerange import ValueRange
from framerange import FrameRange
from filesequence import... | Book
|
exleym/IWBT | alembic/versions/97cd7f996752_first_commit.py | Python | apache-2.0 | 552 | 0 | """first commit
Revision ID: 97cd7f996752
Revises: 084658cb0aab
Create Date: 2017-05-20 06:49 | :09.431920
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '97cd7f996752'
down_revision = '084658cb0aab'
branch_labels = None
depends_on = None
def upgrade():
# ### c | ommands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
|
netsuileo/sfu-cluster-dashboard | dashboard/app/modules/monitoring_nodes/urls.py | Python | lgpl-3.0 | 780 | 0.007692 | # -*- coding: utf8 -*-
from __future__ import absolute_import
from django.conf.urls import url, include
from .views import MonitoringView
urlpatterns = [
url(r'^$', MonitoringView.as_view(), name="index"),
url(r'^info/', include('app.modules.monitoring_nodes.info.urls', namespace='info')),
url(r'^plugins/'... | ude('app.modules.monitoring_nodes.nodes.urls', namespace="nodes")),
url(r'^groups/', include('app.modules.monitoring_nodes.groups.urls', namespace="groups")),
url(r'^graphs/', include('app.modules.monitoring_nodes.graphs.urls', namespace="graphs")),
url(r'^co | nfigs/', include('app.modules.monitoring_nodes.configs.urls', namespace="configs")),
]
|
selectnull/serverscope-benchmark | serverscope_benchmark/utils.py | Python | mit | 2,357 | 0.001273 | # -*- coding: utf-8 -*-
import sys
import subprocess
import signal
imp | ort locale
from six import print_
from six.moves import urllib
import requests
class Color:
PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
ORANGE = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
c = Color
# from http://hg.python.org/c... | nal(getattr(signal, sig), signal.SIG_DFL)
def run_and_print(command, cwd=None):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=-1,
cwd=cwd,
preexec_... |
MiltosD/CEF-ELRC | misc/tools/statserver/urls.py | Python | bsd-3-clause | 427 | 0.032787 | from django.conf.urls.defaults import patterns
| from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
( r'^$', 'statserver.stats.views.browse' ),
( r'^stats/addnode$', 'statserver.stats.views.addnode' ),
( r'^media | /(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
|
louisLouL/pair_trading | capstone_env/lib/python3.6/site-packages/kafka/protocol/produce.py | Python | mit | 3,232 | 0.001238 | from __future__ import absolute_import
from .api import Request, Response
from .message import MessageSet
from .types import Int16, Int32, Int64, String, Array, Schema
class ProduceResponse_v0(Response):
API_KEY = 0
API_VERSION = 0
SCHEMA = Schema(
('topics', Array(
('topic', String('... | ('timestamp', Int64))))),
('throttle_time_ms', Int32)
)
class ProduceResponse_v3(Response):
API_KEY = 0
API_VERSION = 3
SCHEMA = ProduceResponse_v2.SCHEMA
class ProduceRequest_v0(Request):
API_KEY = 0
API_VERSION = 0
RESPONSE_TYPE = ProduceResponse_v0
SCHEMA = Schema(
... | 'utf-8')),
('partitions', Array(
('partition', Int32),
('messages', MessageSet)))))
)
def expect_response(self):
if self.required_acks == 0: # pylint: disable=no-member
return False
return True
class ProduceRequest_v1(Request):
API_K... |
nerzhul/Z-Eye | service/WebApp/Z_Eye/engine/Switches/API/__init__.py | Python | gpl-2.0 | 3,146 | 0.020979 | # -*- coding: utf-8 -*-
"""
* Copyright (C) 2010-2014 Loic BLOT <http://www.unix-experience.fr/>
*
* 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 op... | ndor"] == "cisco":
SwitchObj = Cisco.CiscoSwitch()
mib = request.GET["mib"]
if SwitchObj.setDevice(request.GET["device"]) and mib in Cisco.Mibs:
if "pid" in request.GET and SwitchObj.setPortId(request.GET["pid"]):
# We don't call methods here, it's faster to use the dictionnary
return HttpRes... | b],request.GET["value"]))
else:
# Invalid the port ID
SwitchObj.setPortId("")
return HttpResponse(SwitchObj.snmpset(Cisco.Mibs[mib],request.GET["value"]))
return HttpResponse(_('Err-Wrong-Request'))
def saveDeviceConfig(request):
if request.method == "GET" and "vendor" in request.GET and "de... |
nycholas/ask-undrgz | src/ask-undrgz/ask_undrgz/settings.py | Python | bsd-3-clause | 5,653 | 0.002653 | # -*- coding: utf-8 -*-
#
# ask-undrgz system of questions uses data from underguiz.
# Copyright (c) 2010, Nycholas de Oliveira e Oliveira <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditio... | AND CONTRIBUTORS "AS IS"
# AND ANY E | XPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDI... |
de-vri-es/qtile | setup.py | Python | mit | 5,466 | 0.000732 | #!/usr/bin/env python
# Copyright (c) 2008 Aldo Cortesi
# Copyright (c) 2011 Mounier Florian
# Copyright (c) 2012 dmpayton
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 roger
# Copyright (c) 2014 Pedro Algarvio
# Copyright (c) 2014-2015 Tycho Andersen
#
# Permission is hereby granted, free of charge, to any perso... | se :: OSI Approved :: MIT License",
"Development Status :: 3 - Alpha",
"Programming Language :: Python",
"Programming Language :: | Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Operatin... |
yoms/sentinel-banner-generator | banner_generator.py | Python | apache-2.0 | 6,246 | 0.013289 | from osgeo import gdal, osr, ogr
import numpy as np
import scipy.misc
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("banner-generator")
def create_raster_from_band( red, green, blue, output_file):
logger.debug("Create big raster in output_file : %s"%output_file)
red_ds = gd... | lip_array(2, green_clip)
logger.debug("Prepare blue color, clip raw value at %s, %s"%blue_clip)
blue_array = clip_array(3, blue_clip)
rgb = np.zeros((len(red_array), len(red_array[0]), 3), dtype=np.uint8)
rgb[..., 0] = red_array
rgb[..., 1] = green_array
rgb[..., 2] = blue_array
logger.... | on, lat):
logger.debug("Compute x and y from lon lat")
logger.debug("Longitude : %s"%lon)
logger.debug("Latitude : %s"%lat)
sref = osr.SpatialReference()
sref.ImportFromEPSG(4326)
# create a geometry from coordinates
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat)
ra... |
T-R0D/JustForFun | aoc2018/day02/test/test_solution.py | Python | gpl-2.0 | 1,946 | 0.001542 | import unittest
import day02.solution as solution
class TestDay02(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_part_one(self):
test_input = [
'abcdef',
'bababc',
'abbcde',
'abcccd',
'aabcdd'... | self.assertTrue(solution.has_n_letters('bababc', 2))
self.assertTrue(solution.has_n_letters('abbcde', 2))
self.assertFalse(solution.has_n_letters('abcccd', 2))
self.assertTrue(solution.has_n_letters('aabcdd', 2))
self.assertTrue(solution.has_n_letters('abcdee', 2))
| self.assertFalse(solution.has_n_letters('ababab', 2))
self.assertFalse(solution.has_n_letters('abcdef', 3))
self.assertTrue(solution.has_n_letters('bababc', 3))
self.assertFalse(solution.has_n_letters('abbcde', 3))
self.assertTrue(solution.has_n_letters('abcccd', 3))
self.asse... |
Gjum/agarnet | setup.py | Python | gpl-3.0 | 1,095 | 0.001826 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='agarnet',
packages=['agarnet'],
py_modules=['agarnet'],
version='0.2.4',
description='agar.io client and connection toolkit',
install_requires=['websocket-client>=0.32.0'],
aut... | classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Natural Language :: English',
... | 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Education',
'Topic :: Games/Entertainment',
],
)
|
bderembl/mitgcm_configs | test_pg_hr/input/mygendata.py | Python | mit | 8,360 | 0.035167 | #!/usr/bin/env python
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import scipy.io.netcdf as netcdf
import spoisson
import def_radius
from scipy import interpolate
from scipy.interpolate import interp1d
import glob
#plt.ion()
binprec = '>f4'
flag_conf = 2 # 0: samelson, 1: gr... | polate.interp2d(xx, yy,eta, kind='cubic')
eta_n = fint(xn,yn)
#np.savetxt('upg.dat',uvel_n[0,:,:])
#np.savetxt('sstpg.dat',theta_n[0,:,:])
uvel_n.astype(binprec).tofile('uinit.box')
vvel_n.astype(binprec).tofile('vinit.box')
theta_n.astype(binprec).tofile('tinit.box')
eta_n.astype(binprec).tofile('einit.box')
#----... | .ones((si_z,si_y,si_x))
tmask.astype(binprec).tofile('tmask.box')
# relax to initial conditions
theta_n.astype(binprec).tofile('trelax.box')
# compute relaxation length scale
N2 = -gg*alphaT*np.diff(theta_n,axis=0)/dz2
N2_min = 1e-7
N2 = np.where(N2<N2_min, N2_min, N2)
gp = N2*dz2
lmax = 500e3
filt_len = np.zeros(... |
IllusionRom-deprecated/android_platform_tools_idea | python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams_after.py | Python | apache-2.0 | 148 | 0.040541 | __author__ = 'ktisha'
def foo(x):
return x
class A():
@staticmethod
@accepts(i | nt, int)
def my_<caret>method():
print "Smth" | |
aelkikhia/pyduel_engine | pyduel_gui/widgets/game_status_widget.py | Python | apache-2.0 | 560 | 0.003571 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import QLabel
class StatusBar(QLabel):
def __init__(self, status, parent=None):
super(StatusBar, self).__init__(parent)
self.setToolTip("game status bar")
self.setText(status)
def setStatus(self, status):
self.setText(... | __':
import sys
from PyQt4.QtGui import QApplication
app = QApplication(sys.argv)
widget = Stat | usBar("R: {} T: {}\tPhase: {}".format(1, 2, 'Move'))
widget.show()
sys.exit(app.exec_())
|
bigswitch/tempest | tempest/scenario/test_security_groups_basic_ops.py | Python | apache-2.0 | 26,295 | 0 | # Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | nt_allow:
* test that cross- | tenant traffic is enabled once an appropriate
rule has been created on destination tenant.
* test that reverse traffic is still blocked
* test than reverse traffic is enabled once an appropriate rule has
been created on source tenant
7._test_port_update_new_securi... |
leiforion/t1-python | terminalone/utils/credentials.py | Python | bsd-3-clause | 1,971 | 0.000507 | # -*- coding: utf-8 -*-
"""Get credentials from file or environment variables"""
from functools import reduce
def dpath(dict_, path):
"""Dig into dictionary by string path. e.g.
dpath({'a': {'b': {'c': 'd'}}}, 'a.b') -> {'c': 'd'}
"""
from operator import getitem
paths = path.split('.')
retu... | PI_KEY
:param filename: str filename of JSON file containing credentials.
:param root: str path to get to credentials object. For instance, in object:
{
"credentials | ": {
"api": {
"username": "myusername",
"password": "supersecret",
"api_key": "myapikey"
}
}
}
"root" is "credentials.api"
:return: dict[str]str
:raise: TypeError: no JSON file or envvars
... |
nilsonmorales/Badass | Packages_POU/pre-paquetes/20140430/20140430.pet/usr/share/local/apps/VideoThumbnail/extopts.py | Python | gpl-3.0 | 1,009 | 0.038652 | """Grab the tips from Options.xml
$Id: extopts.py,v 1.1 2007/01/14 14:07:31 stephen Exp $
Originally ROX-Filer/src/po/tips.py by Thomas Leonard.
"""
from xml.sax import *
from xml.sax.handler import ContentHandler
import os, sys
class Handler(ContentHandler):
data = ""
def startElement(self, tag, attrs):
for x i... | , 'unit']:
if attrs.has_key(x):
self.trans(attrs[x])
self.data = ""
def characters(self, data):
self.data = self.data + data
def endElement(self, tag):
data = self.data.strip()
if data:
self.trans(data)
self.data = ""
def trans(self, da | ta):
data = '\\n'.join(data.split('\n'))
if data:
out.write('_("%s")\n' % data.replace('"', '\\"'))
ifname='Options.xml'
ofname='Options_strings'
if len(sys.argv)>2:
ifname=sys.argv[1]
ofname=sys.argv[2]
elif len(sys.argv)==2:
ifname=sys.argv[1]
print "Extracting translatable bits from %s..." % os.path.ba... |
SanPen/GridCal | src/research/power_flow/helm/old/helm_z_pq.py | Python | lgpl-3.0 | 6,030 | 0.002819 | import numpy as np
np.set_printoptions(precision=6, suppress=True, linewidth=320)
from numpy import where, zeros, ones, mod, conj, array, dot, angle, complex128 #, complex256
from numpy.linalg import solve
# Set the complex precision to use
complex_type = complex128
def calc_W(n, npqpv, C, W):
"""
Calculatio... | -= 1
L = nn
M = nn
an = np.ndarray.flatten(an)
rhs = an[L + 1:L + M + 1]
C = zeros((L, M), dtype=complex_type)
for i in range(L):
k = i + 1
C[i, :] = an[L - M + k:L + k]
try:
b = solve(C, -rhs) # bn to b1
except:
return 0, zeros(L + 1, dtype=complex_... | eros(L + 1, dtype=complex_type)
a[0] = an[0]
for i in range(L):
val = complex_type(0)
k = i + 1
for j in range(k + 1):
val += an[k - j] * b[j]
a[i + 1] = val
p = complex_type(0)
q = complex_type(0)
for i in range(L + 1):
p += a[i] * s ** i
... |
schreiberx/sweet | mule/platforms/50_himmuc/JobPlatform.py | Python | mit | 4,801 | 0.016038 | import platform
import socket
import sys
import os
from mule_local.JobGeneration import *
from mule.JobPlatformResources import *
from . import JobPlatformAutodetect
# Underscore defines symbols to be private
_job_id = None
def get_platform_autodetect():
"""
Returns
-------
bool
True if curren... | if not p.mpiexec_disabled:
mpiexec = "mpiexec -n "+str(p.num_ranks)
content = """
# mpiexec ... would be here without a line break
EXEC=\""""+jg.compile.getProgramPath()+"""\"
PARAMS=\""""+jg.runtime.getRuntimeOptions()+"""\"
echo \"${EXEC} ${PARAMS}\"
"""+mpiexec+""" $EXEC $PARAMS || exit 1
"""
ret... | ng
multiline text for scripts
"""
content = ""
content += jg.runtime.get_jobscript_plan_exec_suffix(jg.compile, jg.runtime)
return content
def jobscript_get_footer(jg : JobGeneration):
"""
Footer at very end of job script
Returns
-------
string
multiline text for scrip... |
fnp/pylucene | samples/LuceneInAction/lia/analysis/keyword/KeywordAnalyzerTest.py | Python | apache-2.0 | 2,858 | 0.00035 | # ====================================================================
# 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 re... | tCase
from lucene import \
IndexWriter, Term, SimpleAnalyzer, PerFieldAnalyzerWrapper, \
RAMDirectory, Document, Field, Ind | exSearcher, TermQuery, \
QueryParser, Analyzer, StringReader, Token, JavaError, \
Version
from lia.analysis.keyword.KeywordAnalyzer import KeywordAnalyzer
from lia.analysis.keyword.SimpleKeywordAnalyzer import SimpleKeywordAnalyzer
class KeywordAnalyzerTest(TestCase):
def setUp(self):
self.di... |
Soya93/Extract-Refactoring | python/helpers/pydev/tests_pydevd_python/test_pydev_monkey.py | Python | apache-2.0 | 5,544 | 0.00487 | import sys
import os
import unittest
try:
from _pydev_bundle import pydev_monkey
except:
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from _pydev_bundle import pydev_monkey
from pydevd import SetupHolder
from _pydev_bundle.pydev_monkey import pydev_src_dir
class TestCase(unittest.TestCase)... | ,
pydev_monkey.patch_arg_str_win(check)
)
finally:
SetupHolder.setup = original
def test_str_to_args_windows(self):
self.assertEqual(['a', 'b'], pydev_monkey.str_to_args_windows('a "b"'))
def test_monkey_patch_args_indc(self):
original = Se | tupHolder.setup
try:
SetupHolder.setup = {'client':'127.0.0.1', 'port': '0'}
check=['C:\\bin\\python.exe', '-u', '-c', 'connect(\\"127.0.0.1\\")']
sys.original_argv = []
self.assertEqual(pydev_monkey.patch_args(check), [
'C:\\bin\\python.exe',
... |
mardiros/apium | apium/__init__.py | Python | bsd-3-clause | 122 | 0 | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
__version__ = '0.1'
| from .proxy import | Proxy
|
wegamekinglc/Finance-Python | PyFin/Analysis/TechnicalAnalysis/__init__.py | Python | mit | 6,089 | 0.007226 | # -*- coding: utf-8 -*-
u"""
Created on 2015-8-8
@author: cheng.li
"""
from PyFin.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecuritySignValueHolder
from PyFin.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAverageValueHolder
from PyFin.Analysis.TechnicalAnalysis.StatelessTec... | yMovingSum
from PyFin.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingVariance
from PyFin.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingStandardDeviation
from PyFin.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovi | ngCountedPositive
from PyFin.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingPositiveAverage
from PyFin.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingCountedNegative
from PyFin.Analysis.TechnicalAnalysis.StatefulTechnicalAnalysers import SecurityMovingNegativeAver... |
bswartz/manila | manila/api/middleware/fault.py | Python | apache-2.0 | 3,089 | 0 | # 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 except in compliance with the License. You may obtain
# a ... | icense for the specific language governing permissions and limitations
# under the Lice | nse.
from oslo_log import log
import six
import webob.dec
import webob.exc
from manila.api.openstack import wsgi
from manila.i18n import _
from manila import utils
from manila.wsgi import common as base_wsgi
LOG = log.getLogger(__name__)
class FaultWrapper(base_wsgi.Middleware):
"""Calls down the middleware st... |
aguinane/qld-tariffs | qldtariffs/monthanalysis.py | Python | mit | 2,897 | 0.000345 | from statistics import mean
from datetime import datetime, timedelta
import calendar
from typing import NamedTuple
from typing import Iterable, Tuple, Dict
from energy_shaper import group_into_profiled_intervals
from .dayanalysis import Usage, get_daily_charges
class MonthUsage(NamedTuple):
""" Represen... | (daily_summary, key=lambda tup: (tup[0], tup[1]), reverse=True)
):
if i < 4:
if day.peak:
demand = day.peak
else:
demand = day.shoulder
avg_peak_d | emand = average_daily_peak_demand(demand)
top_four_days.append(avg_peak_demand)
if top_four_days:
return mean(top_four_days)
else:
return 0
|
sileht/deb-openstack-quantum | quantum/plugins/ryu/nova/linux_net.py | Python | apache-2.0 | 2,786 | 0.000359 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# <yamahata at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... | default='127.0.0.1:8080',
help='Openflow Ryu REST API host:port')
FLAGS = flags.FLAGS
F | LAGS.register_opt(ryu_linux_net_opt)
def _get_datapath_id(bridge_name):
out, _err = utils.execute('ovs-vsctl', 'get', 'Bridge',
bridge_name, 'datapath_id', run_as_root=True)
return out.strip().strip('"')
def _get_port_no(dev):
out, _err = utils.execute('ovs-vsctl', 'get', '... |
dedichan/ChemDB | setup_win.py | Python | gpl-3.0 | 1,223 | 0.035159 | from distutils.core import setup
import py2exe
import os, sys
from glob import glob
import PyQt | 5
data_files=[('',['C:/Python34/DLLs/sqlite3.dll','C:/Python34/Lib/site-packages/PyQt5/icuuc53.dll','C:/Python34/Lib/site-packages/PyQt5/icudt53.dll','C:/Python34/Lib/site-packages/PyQt5/icuin53.dll','C:/Python34/Lib/site-pack | ages/PyQt5/Qt5Gui.dll','C:/Python34/Lib/site-packages/PyQt5/Qt5Core.dll','C:/Python34/Lib/site-packages/PyQt5/Qt5Widgets.dll']),
('data',['data/configure','data/model.sqlite','data/loading.jpg']),
('platforms',['C:/Python34/Lib/site-packages/PyQt5/plugins/platforms/qminimal.dll','C:/Python34/Lib/site-packages/PyQt5/plu... |
QiJune/Paddle | python/paddle/fluid/op.py | Python | apache-2.0 | 10,014 | 0 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE- | 2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHO | UT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import numpy as np
import six
import paddle.fluid.core as core
import paddle.fluid.proto.framework_pb2 as fr... |
ic-hep/DIRAC | src/DIRAC/Core/Utilities/MemStat.py | Python | gpl-3.0 | 1,174 | 0.000852 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
__RCSID__ = | "$Id$"
def VmB(vmKey):
__memScale = {"kB": 1024.0, "mB": 1024.0 * 1024.0, "KB": 1024.0, "MB": 1024.0 * 1024.0}
__vmKeys = [
"VmPeak:",
"VmSize:",
"VmLck:",
"VmHWM:",
"VmRSS:",
"VmData:",
"VmStk:",
"VmExe:",
| "VmLib:",
"VmPTE:",
"VmPeak",
"VmSize",
"VmLck",
"VmHWM",
"VmRSS",
"VmData",
"VmStk",
"VmExe",
"VmLib",
"VmPTE",
]
if vmKey not in __vmKeys:
return 0
procFile = "/proc/%d/status" % os.getpid()
# get pseudo fi... |
laloxxx20/TiendaVirtual | setup.py | Python | apache-2.0 | 293 | 0 | #!/usr/bin/env python
from setuptools import setup
set | up(
name='YourAppName',
version='1.0',
description='OpenShift App',
author='Your Name',
author_email='[email protected]',
url='http://www.python.org/ | sigs/distutils-sig/',
install_requires=['Django<=1.4'],
)
|
claytantor/grailo | feeds/models.py | Python | lgpl-3.0 | 6,456 | 0.006506 | from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.utils.translation import ugettext_lazy as _
# relational databases are a terrible way to do
# multicast messages (just ask Twitter) but here you have it :-)
import re
reply_re = re.compile("^@(\w+)")
cl... | ):
# recipients.add(follower)
#
# # add sender
# recipients.add(user)
#
# # if starts with @user send it to them too even if not following
# match = reply_re.match(instance.text)
| # if match:
# try:
# reply_recipient = User.objects.get(username=match.group(1))
# recipients.add(reply_recipient)
# except User.DoesNotExist:
# pass # oh well
# else:
# if notification:
# notification.send([reply_recipient], "message_re... |
saydulk/sogo | Tests/Integration/test-carddav.py | Python | gpl-2.0 | 6,859 | 0.004228 | #!/usr/bin/python
from config import hostname, port, username, password
import carddav
import sogotests
import unittest
import webdavlib
import time
class JsonDavEventTests(unittest.TestCase):
def setUp(self):
self._connect_as_user()
def _connect_as_user(self, newuser=username, newpassword=passwor... | except ValueError:
#print "Can't find", phone
pass
self._save_card()
def _connect_as_user(se | lf, newuser=username, newpassword=password):
self.dv = carddav.Carddav(newuser, newpassword)
def _create_new_card(self, path):
gid = self.dv.newguid(path)
card = {'c_categories': None,
'c_cn': 'John Doe',
'c_component': 'vcard',
'c_givenname':... |
orlandov/parpg-game | local_loaders/xmlmap.py | Python | gpl-3.0 | 13,207 | 0.007496 | #!/usr/bin/python
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in th... | if dir:
dir = reverse_root_subf | ile(self.source, dir)
# Don't parse duplicate imports
if (dir,file) in parsedImports:
print "Duplicate import:" ,(dir,file)
continue
parsedImports[(dir,file)] = 1
if file and dir:
loaders.loadImportFile('/'.join(d... |
rbuffat/pyidf | tests/test_glazeddoorinterzone.py | Python | apache-2.0 | 2,670 | 0.003745 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.thermal_zones_and_surfaces import GlazedDoorInterzone
log = logging.getLogger(__name__)
class TestGlazedDoorInterzone(unittest.TestCase):
def setUp(self):
self.fd, ... | for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertEqual(idf2.glazeddoorinterzones[0].name, var_name)
self.assertEqual(idf2.glazeddoorinterzones[0].construction_name, var_construction_name)
| self.assertEqual(idf2.glazeddoorinterzones[0].building_surface_name, var_building_surface_name)
self.assertEqual(idf2.glazeddoorinterzones[0].outside_boundary_condition_object, var_outside_boundary_condition_object)
self.assertAlmostEqual(idf2.glazeddoorinterzones[0].multiplier, var_multiplier)
... |
Aluriak/neural_world | neural_world/prompt.py | Python | gpl-2.0 | 4,845 | 0.009701 | """
Definition of the Prompt class, designed for editing Configuration
with a terminal prompt.
"""
from functools import partial
from prompt_toolkit import prompt
from prompt_toolkit.contrib.regular_languages.compiler import compile as pt_compile
from prompt_toolkit.contrib.completers import Word... | values | = match.variables()
subcmd = values.get('subcmd')
args = values.get('args')
cmd = next( # get root name, not an alias
cmd_name
for cmd_name, aliases in COMMAND_NAMES.items()
if values.get('cmd') in aliases
)
# ... |
jbuchbinder/youtube-dl | youtube_dl/__init__.py | Python | unlicense | 18,757 | 0.001546 | #!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
__license__ = 'Public Domain'
import codecs
import io
import os
import random
import sys
from .options import (
parseOpts,
)
from .compat import (
compat_expanduser,
compat_getpass,
compat_shlex_split,
workaround_optp... | ('Type account password and press [Return]: ')
if opts.ap_username is not None and opts.ap_password is None:
opts.ap_password = compat_getpass('Type TV provider account password and press [Ret | urn]: ')
if opts.ratelimit is not None:
numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
if numeric_limit is None:
parser.error('invalid rate limit specified')
opts.ratelimit = numeric_limit
if opts.min_filesize is not None:
numeric_limit = FileDownloader.pa... |
juliend88/os_image_factory | test-tools/pytesting_os/openstackutils.py | Python | gpl-3.0 | 8,608 | 0.015335 | #!/usr/bin/env python
#-*- coding: utf-8 -
import keystoneclient.v2_0.client as keystone
from keystoneauth1.identity import v2
from keystoneauth1 import session
import novaclient.client as nova
import cinderclient.client as cinder
from glanceclient.v1 import client as glance
import neutronclient.v2_0.client as neutron
... | .wait_server_available(server)
return self.nova_client.servers.g | et(server.id).rescue()
def unrescue(self,server):
self.wait_server_available(server)
return self.nova_client.servers.get(server.id).unrescue()
def attach_volume_to_server(self,server,volume):
#self.nova_client.volumes.create_server_volume(server_id=server.id,volume_id=env['NOSE_VOLUME... |
dana-i2cat/felix | msjp/module/common/__init__.py | Python | apache-2.0 | 108 | 0.027778 | import os, glob
__all__ = [os.path.bas | ename(f)[:-3] for f in glob.glob(os.path.dirname(__file__) + | "/*.py")] |
daineseh/kodi-plugin.video.ted-talks-chinese | youtube_dl/extractor/xvideos.py | Python | gpl-2.0 | 2,444 | 0.001227 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote
from ..utils import (
clean_html,
ExtractorError,
determine_ext,
)
class XVideosIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?xvideos\.com/video(?P<id>[0-9]+)(?... | h(r'<h1 class="inlineError">(.+?)</h1>', webpage)
if mobj:
raise ExtractorError('%s said: %s' % (self.IE_NAME, clean_html(mobj.group(1))), expected=True)
video_title = self._html_search_regex(
r'<title>(.*?)\s+-\s+XVID', webpage, 'title')
video_thumbnail = self._search_r... | r'url_bigthumb=(.+?)&', webpage, 'thumbnail', fatal=False)
formats = []
video_url = compat_urllib_parse_unquote(self._search_regex(
r'flv_url=(.+?)&', webpage, 'video URL', default=''))
if video_url:
formats.append({'url': video_url})
player_args = self... |
kohnle-lernmodule/exe201based | exe/export/pages.py | Python | gpl-2.0 | 8,659 | 0.004735 | # ===========================================================================
# eXe
# Copyright 2004-2005, University of Auckland
# Copyright 2004-2008 eXe Project, http://eXeLearning.org/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as ... | mons.org/licenses/by-nc-nd/4.0/",
"free software license GPL": "http://www.gnu.org/copyleft/gpl.html"
}
licenses_names = {"license GFDL": c_("GNU Free Documentation License"),
"creative commons: attribution 2.5": c_("Creative Commons Attribution L... | "creative commons: attribution - non derived work 2.5": c_("Creative Commons Attribution No Derivatives License 2.5"),
"creative commons: attribution - non commercial 2.5": c_("Creative Commons Attribution Non-commercial License 2.5"),
"creative ... |
gaolichuang/py-essential | tests/testmods/fbar_foo_opt.py | Python | apache-2.0 | 719 | 0 | # Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at |
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific la... | ONF.register_opt(opt, group='fbar')
|
nlaanait/pyxrim | examples/hdf5_export.py | Python | mit | 1,439 | 0.014593 | """
Created on 4/18/17
@author: Numan Laanait -- [email protected]
"""
#MIT License
#Copyright (c) 2017 Numan Laanait
#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, i... | r = os.path.join | (datadir,'images')
# load ioHDF5
io = px.ioHDF5('test.h5')
io.scans_export(specfile,imagedir)
io.close()
|
googleapis/python-assured-workloads | samples/generated_samples/assuredworkloads_v1_generated_assured_workloads_service_create_workload_async.py | Python | apache-2.0 | 1,877 | 0.001598 | # -*- coding: utf-8 -*-
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | async]
from google.cloud import assuredworkloads_v1
async def sample_create_workload():
# Create a client
client = assuredworkloads_v1.AssuredWorkloadsServiceAsyncClient()
# Initialize request argument(s)
workload = assuredworkloads_v1.Workload()
workload.display_name = "display_name_value"
w... | alue"
request = assuredworkloads_v1.CreateWorkloadRequest(
parent="parent_value",
workload=workload,
)
# Make the request
operation = client.create_workload(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the re... |
jni/python-redshirt | redshirt/read.py | Python | mit | 2,123 | 0.000471 | import numpy as np
from skimage import io
def read_image(fn, normalize=True):
"""Read a CCD/CMOS image in .da format (Redshirt). [1_]
Parameters
----------
fn : string
The input filename.
Returns
-------
images : array, shape (nrow, ncol, nframes)
The images (normalized b... | der[388] / 1000
acquisition_ratio = header[391]
if frame_interval >= 10:
frame_interval *= header[390] # dividing factor
image_size = nrows * ncols * nframes
bnc_start = header_size + image_size
images = np.reshape(np.arr | ay(data[header_size:bnc_start]),
(nrows, ncols, nframes))
bnc_end = bnc_start + 8 * acquisition_ratio * nframes
bnc = np.reshape(np.array(data[bnc_start:bnc_end]), (8, nframes * acquisition_ratio))
dark_frame = np.reshape(np.array(data[bnc_end:-8]), (nrows, ncols))
if normalize:
... |
yaroslavprogrammer/django-modeltranslation | modeltranslation/__init__.py | Python | bsd-3-clause | 2,020 | 0 | # -*- coding: utf-8 -*-
"""
Version code adopted from Django development version.
https://github.com/django/django
"""
VERSION = (0, 7, 2, 'final', 0)
def get_version(version=None):
"""
Returns a PEP 386-compliant version number from VERSION.
"""
if version is None:
from modeltranslation impor... | rr=subprocess.PIPE, shell=True, | cwd=repo_dir,
universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
|
NervanaSystems/neon | examples/video-c3d/network.py | Python | apache-2.0 | 2,289 | 0.002184 | # ******************************************************************************
# Copyright 2014-2018 Intel Corporation
#
# 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.apa... | t(1)
# model initialization
padding = {'pad_d': 1, 'pad_h': 1, 'pad_w': 1}
strides = {'str_d': 2, 'str_h': 2, 'st | r_w': 2}
layers = [
Conv((3, 3, 3, 64), padding=padding, init=g1, bias=c0, activation=Rectlin()),
Pooling((1, 2, 2), strides={'str_d': 1, 'str_h': 2, 'str_w': 2}),
Conv((3, 3, 3, 128), padding=padding, init=g1, bias=c1, activation=Rectlin()),
Pooling((2, 2, 2), strides=strides),
... |
hkernbach/arangodb | 3rdParty/V8/v5.7.492.77/tools/gyp/pylib/gyp/generator/msvs.py | Python | apache-2.0 | 133,929 | 0.009796 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import ntpath
import os
import posixpath
import re
import subprocess
import sys
import gyp.common
import gyp.easy_xml as easy_xml
import gyp.generator... | = MSVSProject.Filter('_excluded_files',
contents=excluded_resul | t)
result.append(excluded_folder)
if msvs_version and msvs_version.UsesVcxproj():
return result
# Populate all the folders.
for f in folders:
contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f],
excluded=excluded,
... |
rgardler/acs-logging-test | src/runSimulation.py | Python | apache-2.0 | 269 | 0.003717 | """
Generate simulated logs, placing new items into the queue.
Process the | Queue, generating summary data and
appending entries to the log store
"""
| import analyzer
import simulatedLogs
# simulate_logs
simulatedLogs.simulate()
# process queue
analyzer.complete()
|
belangeo/pyo | pyo/examples/09-callbacks/03-delayed-calls.py | Python | lgpl-3.0 | 2,090 | 0.000478 | """
03-delayed-calls.py - Calling a function once, after a given delay.
If you want to setup a callback once in the future, the CallAfter
object is very easy to use. You just give it the function name, the
time to wait before making the call and an optional argument.
"""
from pyo import *
s = Server().boot()
# A fo... | ator's frequencies and start the envelope.
def set_osc_freqs(notes):
print(notes)
osc.set(attr="freq", value=midiToHz(list(notes)), port=0.005)
amp.play()
# Initial ch | ord.
set_osc_freqs([60, 64, 67, 72])
# We must be sure that our CallAfter object stays alive as long as
# it waits to call its function. If we don't keep a reference to it,
# it will be garbage-collected before doing its job.
call = None
def new_notes(notes):
global call # Use a global variable.
amp.stop() ... |
dmanev/ArchExtractor | ArchExtractor/umlgen/Specific/STK/StkParser/StkCFileCriteria/StkCHeaderProvDATControlCriteria.py | Python | gpl-3.0 | 1,064 | 0.007519 |
import StkPortInterfaces.StkDATControlIf
import PortInterface.ProvidedPort
import re
import StkParser.StkPortCriteria
import Components.IComponent
import Parser.IPortCriteria
class StkCHeaderProvDATControlCriteria(StkParser.StkPortCriteria.StkPortCriteria):
"""STK C Header file provided DATControl criteria"""
... | inpTextContent):
pif = self.getPortInterfaceFactory()
dtf = self.getDataTypeFactory()
clSrvIntIf = pif.getS | tkDATControlIf(datControl, dtf)
provPort = PortInterface.ProvidedPort.ProvidedPort(clSrvIntIf)
provPort.setName(datControl)
provPort.setInterface(clSrvIntIf)
inoutIComponent.addPort(provPort)
## Bouml preserved body end 000389EF
def __i... |
kubeflow/pipelines | sdk/python/kfp/compiler_cli_tests/test_data/two_step_pipeline.py | Python | apache-2.0 | 2,004 | 0 | # Copyright 2020 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
@dsl.pipeline(name='simple-two-step-pipeline', pipeline_root='dummy_root')
def my_pipeline(text: str = 'Hello world!'):
component_1 = component_op_1(text=text).set_display_name('Producer | ')
component_2 = component_op_2(
input_gcs_path=component_1.outputs['output_gcs_path'])
component_2.set_display_name('Consumer')
if __name__ == '__main__':
compiler.Compiler().compile(
pipeline_func=my_pipeline,
pipeline_parameters={'text': 'Hello KFP!'},
package_path=__fil... |
it-projects-llc/pos-addons | wechat/__init__.py | Python | mit | 100 | 0 | # License MI | T (https://opensource.org/licenses/MIT).
from . import models
from . import c | ontrollers
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/lib/caching.py | Python | bsd-3-clause | 17,413 | 0.003963 | """
CherryPy implements a simple caching system as a pluggable Tool. This tool tries
to be an (in-process) HTTP/1.1-compliant cache. It's not quite there yet, but
it's probably good enough for most sites.
In general, GET responses are cached (along with selecting headers) and, if
another request arrives for the same r... | e."""
raise NotImplemented
def delete(self):
"""Remove ALL cached variants of the current resource."""
raise NotImplemented
def clear(self):
"""Reset the cache to its initial, empty state."""
raise NotImplemented
# ------------------------------- Memory Cache... | Cache(dict):
"""A storage system for cached items which reduces stampede collisions."""
def wait(self, key, timeout=5, debug=False):
"""Return the cached value for the given key, or None.
If timeout is not None, and the value is already
being calculated by another thread, w... |
google-research/sloe-logistic | setup.py | Python | apache-2.0 | 1,690 | 0.001183 | # Copyright 2021 The SLOE Logistic Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | ext_modules=ext_modules,
cmdclass={
"build_ext": build_ext,
"build_clib": build_clib.build_clib,
| },
zip_safe=False,
)
|
ramusus/django-vkontakte-video | vkontakte_video/admin.py | Python | bsd-3-clause | 1,566 | 0.002581 | # -*- coding: utf-8 -*-
from django.contrib import admin
from django.core.urlresolvers import reverse
from vkontakte_api.admin import VkontakteModel | Admin
from .models import Album, Video
class VideoInline(admin.TabularInline):
def imag | e(self, instance):
return '<img src="%s" />' % (instance.photo_130,)
image.short_description = 'video'
image.allow_tags = True
model = Video
fields = ('title', 'image', 'owner', 'comments_count', 'views_count')
readonly_fields = fields
extra = False
can_delete = False
class AlbumA... |
fishstamp82/loprop | test/h2o_data.py | Python | gpl-3.0 | 11,431 | 0.017234 | from ..daltools.util.full import init
Z = [8., 1., 1.]
Rc = init([0.00000000, 0.00000000, 0.48860959])
Dtot = [0, 0, -0.76539388]
Daa = init([
[ 0.00000000, 0.00000000, -0.28357300],
[ 0.15342658, 0.00000000, 0.12734703],
[-0.15342658, 0.00000000, 0.12734703],
])
QUc = init([-7.31176220, 0., 0., -5.432... |
[
[ 0.00000000, 0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, 0.43066796, 0.04316104, 0.00000000, 0.36285790],
[ 0.00150789, 0.10111974, 0.00000000, 0.11541803, 0.53753360, 0.00000000, 0.43120945, 0.04333774, 0.00000000, 0.36314215],
[-0.00150230, | 0.09934695, 0.00000000, 0.11398581, 0.53667861, 0.00000000, 0.43012612, 0.04298361, 0.00000000, 0.36257249],
[ 0.00000331, 0.10023328, 0.00125017, 0.11470067, 0.53710812, -0.00006107, 0.43066944, 0.04316020, 0.00015952, 0.36285848],
[ 0.00000100, 0.10023249, -0.00125247, 0.11470042, 0.53710716... |
mick-d/nipype | nipype/algorithms/tests/test_auto_MeshWarpMaths.py | Python | bsd-3-clause | 1,014 | 0.013807 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..mesh import MeshWarpMaths
def test_MeshWarpMaths_inputs():
input_map = | dict(float_trait=dict(),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_surf=dict(mandatory=True,
),
operation=dict(usedefault=True,
),
operator=dict(mandatory=True,
),
out_file=dict(usedefault=True,
| ),
out_warp=dict(usedefault=True,
),
)
inputs = MeshWarpMaths.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_MeshWarpMaths_outputs():
output_map = d... |
shire210/Shire-HA | custom_components/hue_custom/device_tracker.py | Python | mit | 3,939 | 0.000508 | """
Sensor for checking the status of Hue sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.hue/
"""
import asyncio
import async_timeout
from datetime import timedelta
import logging
import homeassistant.util.dt as dt_util
from homeassistan... | zone_home.attributes[ATTR_LATITUDE],
zone_home.attributes[ATTR_LONGITUDE],
]
kwargs[ATTR_GPS_ACCURACY] = 0
else:
| kwargs["location_name"] = STATE_NOT_HOME
_LOGGER.debug(
"Hue Geofence %s: %s (%s)",
sensor.name,
kwargs["location_name"],
kwargs["attributes"],
)
result = await self.async_see(**kwargs)
return result
async def async_update_... |
gelab/mainr | tests/test_pooling.py | Python | gpl-2.0 | 14,346 | 0.00007 | # MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptio... | pool = pooling.MySQLConnectionPool(pool_size=1, pool_name='test',
pool_reset_session=False)
self.assertFalse(cnxpool._reset_session)
def test_pool_name(self):
"""Test MySQLConnectionPool.pool_name property"""
pool_name = 'ham'
cnxpool = ... | ):
"""Test MySQLConnectionPool.reset_session property"""
cnxpool = pooling.MySQLConnectionPool(pool_name='test',
pool_reset_session=False)
self.assertFalse(cnxpool.reset_session)
cnxpool._reset_session = True
self.assertTrue(cnxpool.r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.