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 |
|---|---|---|---|---|---|---|---|---|
pskeshu/microscoper | microscoper/io.py | Python | mit | 6,962 | 0.000144 | """Microscoper is a wrapper around bioformats using a forked
python-bioformats to extract the raw images from Olympus IX83
CellSense .vsi format, into a more commonly used TIFF format.
Images are bundled together according to their channels.
This code is used internally in SCB Lab, TCIS, TIFR-H.
You're free to modify... | channel_name = str(channel)
images.append(image)
save_images(np.asarray(images), channel_name, save_directory, big,
save_separate)
return metadata
def save_images(images, cha | nnel, save_directory, big=False,
save_separate=False):
"""Saves the images as TIFs with channel name as the filename.
Channel names are saved as numbers when names are not available."""
# Make the output directory, if it doesn't alredy exist.
if not os.path.exists(save_directory):
... |
tefino/kanycast-cinc-combined | examples/swig-samples/python/streaming/recv_and_pub.py | Python | gpl-2.0 | 3,579 | 0.005868 | #!/usr/bin/env python
#-
# Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# Alternatively, this software may be distributed und... | break
except error, select_error:
# select() may raise an error if fds are closed.
print "select:", select_error
print "recv_and_pub stopped"
while True:
| ev = Event()
ba.getEvent(ev)
print ev
if not ev:
continue
print ev.type, "when", publishing
if ev.type == START_PUBLISH and not publishing:
print "Start publish"
sock = socket.socket(socket.AF_INET, sock... |
shobhitmishra/CodingProblems | epi_judge_python/max_trapped_water.py | Python | mit | 394 | 0 | from typing import List
from | test_framework import generic_test
def ge | t_max_trapped_water(heights: List[int]) -> int:
# TODO - you fill in here.
return 0
if __name__ == '__main__':
exit(
generic_test.generic_test_main('max_trapped_water.py',
'max_trapped_water.tsv',
get_max_trapped_water))... |
watchdogpolska/watchdog-id | watchdog_id/main/views.py | Python | mit | 41 | 0 | # coding=utf-8
# Create your views | here.
| |
comses/catalog | catalog/core/management/commands/populate_visualization_cache.py | Python | gpl-3.0 | 359 | 0.002786 | import logging
from django.core.management.base import BaseCommand
from catalog.core.vis | ualization.data_access import visualization_cache
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''Build pandas dataframe cache of primary data'''
def handle( | self, *args, **options):
visualization_cache.get_or_create_many() |
amenonsen/ansible | lib/ansible/modules/network/fortios/fortios_wanopt_profile.py | Python | gpl-3.0 | 32,337 | 0.002505 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | description:
- Enable/disable securing the WAN Opt tunnel using SSL. Secure and non-secure tunnels use the same TCP port (7810).
type: str
choices:
- enable
- disable
| status:
description:
- Enable/disable HTTP WAN Optimization.
type: str
choices:
- enable
- disable
tunnel_sharing:
... |
maberyick/RPi-EPOC | EpocArmVisual/__init__.py | Python | gpl-3.0 | 315 | 0.003175 | # -*- coding: utf-8 -*-
"""
EE | GRobotic - EEG emovit with robotic Arm
~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Moreno-Barrera
"""
__title__ = "EEGRobotic"
__version__ = "1.0"
__build__ = 0x000001
__author__ = "Cristian Barrera - Joseph Moreno"
__license__ = "???"
__copyright__ = "Copyright | 2015 Moreno-Barrera"
|
RDFLib/rdflib | rdflib/paths.py | Python | bsd-3-clause | 16,568 | 0.000302 | __doc__ = r"""
This module implements the SPARQL 1.1 Property path operators, as
defined in:
http://www.w3.org/TR/sparql11-query/#propertypaths
In SPARQL the syntax is as follows:
+--------------------+-------------------------------------------------+
|Syntax | Matches ... | -----------------------+
|!^iri or | Negated property set where the excluded matches |
|!(^iri\ :sub:`1`\ \|| are based on reversed path. That is, not one of | |
|...\|^iri\ :sub:`n`)| iri\ :sub:`1`...iri\ :sub:`n` as reverse paths. |
| | !^iri is short for !(^iri). |
+--------------------+-------------------------------------------------+
|!(iri\ :sub:`1`\ \| | A combination of forward and reverse |
|...\|iri\ :sub:`j`\ | prop... |
martaenciso/calc | calc.py | Python | bsd-3-clause | 529 | 0.003781 | """calc.py: A simple Python calculator."""
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys | .argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(nums))
elif command == 'min':
print(min(nums))
else:
usage = "calc.py [add|multipl | y|min] NUM1 [NUM2 [NUM3 [...]]]"
print(usage)
|
Azure/azure-sdk-for-python | sdk/servicelinker/azure-mgmt-servicelinker/azure/mgmt/servicelinker/aio/__init__.py | Python | mit | 797 | 0.003764 | # 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 cause in | correct behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._microsoft_service_linker import MicrosoftServiceLinker
__all__ = ['MicrosoftServiceLinker']
# `._patch.py` is used for handwritten extensions to the generated code
# Exampl... |
fpsw/Servo | servo/urls/rules.py | Python | bsd-2-clause | 429 | 0 | # -*- coding | : utf-8 -*-
from django.conf.urls import include, url
from servo.views.rules import *
urlpatterns = [
url(r'^$', list_rules, name='rules-list_rules'),
url(r'^add/$', edit_rule, name='rules-create'),
url(r'^(?P<pk>\d+)$', view_rule, name='rules-view_rule'),
url(r'^(?P<pk>\d+)/edit/$', edit_rule, name... | )/delete/$', delete_rule, name='rules-delete_rule'),
]
|
jamespcole/home-assistant | homeassistant/components/google_assistant/smart_home.py | Python | apache-2.0 | 12,254 | 0 | """Support for Google Assistant Smart Home API."""
from asyncio import gather
from collections.abc import Mapping
from itertools import product
import logging
from homeassistant.util.decorator import Registry
from homeassistant.core import callback
from homeassistant.const import (
CLOUD_NEVER_EXPOSED_ENTITIES, C... | TYPE_BLINDS,
fan.DOMAIN: TYPE_FAN,
group.DOMAIN: TYPE_SWITCH,
input_boolean.DOMAIN: TYPE_SWITCH,
light.DOMAIN: TYPE_LIGHT,
lock.DOMAIN: TYPE_LOCK,
media_player.DOMA | IN: TYPE_SWITCH,
scene.DOMAIN: TYPE_SCENE,
script.DOMAIN: TYPE_SCENE,
switch.DOMAIN: TYPE_SWITCH,
vacuum.DOMAIN: TYPE_VACUUM,
}
def deep_update(target, source):
"""Update a nested dictionary with another nested dictionary."""
for key, value in source.items():
if isinstance(value, Mappi... |
Azure-Samples/hdinsight-python-storm-wordcount | multilang/resources/countbolt.py | Python | mit | 806 | 0.003722 | import storm
# Counter is a nice way to count things,
# but it | is a Python 2.7 thing
from collections import Counter
class CountBolt(storm.BasicBolt):
# Initialize this instance
def initialize(self, conf, context):
self._conf = conf
self._context = context
# Create a new counter for this instance
self._counter = Counter()
storm.log... | instance starting...")
def process(self, tup):
# Get the word from the inbound tuple
word = tup.values[0]
# Increment the counter
self._counter[word] +=1
count = self._counter[word]
storm.logInfo("Emitting %s:%s" % (word, count))
# Emit the word and count
... |
xutian/avocado-vt | virttest/cartesian_config.py | Python | gpl-2.0 | 78,677 | 0.000292 | #!/usr/bin/python
"""
Cartesian configuration format file parser.
Filter syntax:
* ``,`` means ``OR``
* ``..`` means ``AND``
* ``.`` means ``IMMEDIATELY-FOLLOWED-BY``
* ``(xx=yy)`` where ``xx=VARIANT_NAME`` and ``yy=VARIANT_VALUE``
Example:
::
qcow2..(guest_os=Fedora).14, RHEL.6..raw..boot, smp2..qcow2..migr... | e = line
self.filename = filename
self.linenum = linenum
def __str__(self):
return ("%r (%s:%s): file does not exist or it's not a reg | ular "
"file" % (self.line, self.filename, self.linenum))
if sys.version_info[0] == 2 and sys.version_info[1] < 6:
def enum(iterator, start_pos=0):
for i in iterator:
yield start_pos, i
start_pos += 1
else:
enum = enumerate
def _match_adjacent(block, ctx, ctx_... |
jeremyprice/RU_Python_II | examples/example_function_obj.py | Python | gpl-2.0 | 269 | 0 | #!/usr/bin/env python3
import dis
def myFunc():
x | = 1
y = 2
z = 'abc' # noqa
return x + y
print(myFunc.__name__)
print(myFunc.__code__.co_varnames)
print(myFunc.__code__.co_consts)
print(myFunc.__code__.co_code)
dis.disassem | ble(myFunc.__code__)
|
vxvinh1511/django-social-auth | social_auth/backends/contrib/bitbucket.py | Python | bsd-3-clause | 73 | 0 | from social.backends.bitbucket import BitbucketOAu | th as BitbucketBa | ckend
|
ahmadiga/min_edx | common/djangoapps/third_party_auth/api/tests/test_views.py | Python | agpl-3.0 | 12,482 | 0.003365 | # pylint: disable=no-member
"""
Tests for the Third Party Auth REST API
"""
import unittest
import ddt
from django.core.urlresolvers import reverse
from django.http import QueryDict
from mock import patch
from provider.constants import CONFIDENTIAL
from provider.oauth2.models import Client, AccessToken
from openedx.co... | )
@ddt.unpack
def test_list_connected_providers(self, request_user, target_user, expect_result):
self.client.login(username=request_user, password=PASSWORD)
url = reverse('third_party_auth_users_api', kwargs={'username': targ | et_user})
response = self.client.get(url)
self.assertEqual(response.status_code, expect_result)
if expect_result == 200:
self.assertIn("active", response.data)
self.assertItemsEqual(response.data["active"], self.expected_active(target_user))
@ddt.data(
# A s... |
dfurtado/generator-djangospa | generators/app/templates/root/appfiles/urls.py | Python | mit | 1,320 | 0.046212 | <% if (djangoVersion != '2.0') { %>
from django.conf.urls import url, include
<% } else { %>
from django.urls import path, include
<% } %>
from django.contrib import admin
from <%= appName %> import views
<% if (includeLoginPage == true) { %>
from <%= appName %>.forms import AuthenticationForm
from django.contr | ib.auth.views import login, logout
<% } %>
<% if (djangoVersion != '2.0') { %>
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^', include('<%= appName %>.urls')),
url(r'^admin/', include(admin.site.urls)),
]
<% if (includeLoginPage == true) { %>
urlpatterns += [
url(r'^accounts/login/$',... | ': '/'
}, name='logout'),
]
<% } %>
<% } else { %>
urlpatterns = [
path(r'', views.index, name="index"),
path(r'', include('<%= appName %>.urls')),
path(r'admin/', admin.site.urls),
]
<% if (includeLoginPage == true) { %>
urlpatterns += [
path(r'accounts/login', login, {
'template_name': 'lo... |
logdna/python | logdna/logdna.py | Python | mit | 10,185 | 0 | import logging
import requests
import socket
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from .configs import defaults
from .utils import sanitize_meta, get_ip, normalize_list_option
class LogDNAHandler(logging.Handler):
def __init__(self, key, options={}):
... | end(self.se | condary)
self.secondary = []
data = {'e': 'ls', 'ls': self.buf}
retries = 0
while retries < self.max_retry_attempts:
retries += 1
if self.send_request(data):
self.clean_after_success()
break
sleep_time = self.retry_inte... |
Vauxoo/e-commerce | website_sale_product_detail_attribute_image/controllers/main.py | Python | agpl-3.0 | 661 | 0 | # Copyright 2019 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.addons.website_sale.controllers.main imp | ort WebsiteSale
from odoo import http
class WebsiteSaleProductDetailAttributeImage(WebsiteSale):
@http.route()
def product(self, product, category='', search='', **kwargs):
res = super().product(
product, category=category, search=search, **kwargs)
attributes_detail = product.attr... | es_detail
return res
|
heyglen/sublime-network | lib/iana/ripe/objects/rpsl.py | Python | gpl-3.0 | 2,010 | 0.001493 | """
Copyright 2019 Glen Harmon
RPSL Common Attributes
https://www.ripe.net/manage-ips-and-asns/db/support/documentation/ripe-database-documentation/rpsl-object-types/4-1-description-of-attributes-common-to-all-objects
"""
class Rpsl:
def __init__(self):
self.organisation = list()
self.admin_con... | if not value:
continue
if isinstance(value, (list, set)):
if label:
text += """<p>
<div>{}: </div>
""".format(label)
for entry in value:
text += '<div>{}</div>\n'.format(en... | <span>{}: </span><span>{}</span>
</p>
""".format(label, value)
else:
text += """<p>
<span>{}</span>
</p>
""".format(value)
return text |
Sbalbp/DIRAC | FrameworkSystem/Client/SecurityLogClient.py | Python | gpl-3.0 | 2,116 | 0.033554 |
import syslog
from DIRAC import gLogger, gConfig
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.Core.Utilities import Time
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
class SecurityLogClient:
__securityLogStore = []
def __init__( self ):
self.__messagesList = []
self._... | Time()
msg = ( timestamp, success, sourceIP, sourcePort, sourceIdentity,
destinationIP, destinationPort, destinationService, action )
if gConfig.getValue( "/Registry | /EnableSysLog", False ):
strMsg = "Time=%s Accept=%s Source=%s:%s SourceID=%s Destination=%s:%s Service=%s Action=%s"
syslog.syslog( strMsg % msg )
while len( self.__messagesList ) > self.__maxMessagesWaiting:
self.__messagesList.pop( 0 )
if not self.__securityLogStore:
self.__messagesLi... |
nevillegrech/stdl | src/STDL/Program.py | Python | epl-1.0 | 4,723 | 0.016303 | from __future__ import absolute_import
import sys, types
#sys.path=['Coders'] + sys.path
from BaseClasses import *
from InitParams import *
from Test import *
from Coders.ICoder import *
# The following 3 functions are taken from the python cookbook
def _get_mod(modulePath):
try:
aMod = sys.modu... | e=name
self.inheritedSubPartitions={}
self.tests=[]
self.initParams=initParams
ParsedElement.__init__(self,tokens)
def getCode(self):
if not self.isPopulated:
return None
params=self.initParams.params
coder=params['language']
... | loading %s Coder object/language not supported"%coder)
valid=params['valid_cs'] if 'valid_cs' in params else 2
invalid=params['invalid_cs'] if 'valid_cs' in params else 'bc'
suites=[]
coderObject.setInitparams(params)
try:
for test in self.tests:
... |
bianchimro/django-cms-fragments | cms_fragments/demo/fragmentsdemo/manage.py | Python | bsd-3-clause | 256 | 0 | #!/usr/bin/env python
import os
import sys
if __ | name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_M | ODULE", "fragmentsdemo.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
openprocurement/openprocurement.auctions.dgf | openprocurement/auctions/dgf/includeme.py | Python | apache-2.0 | 3,915 | 0.001277 | import logging
from pyramid.interfaces import IRequest
from openprocurement.auctions.dgf.models import (
IDgfOtherAssetsAuction,
IDgfFinancialAssetsAuction,
DGFOtherAssets,
DGFFinancialAssets
)
from openprocurement.auctions.dgf.adapters import (
AuctionDGFOtherAssetsConfigurator,
AuctionDGFFina... | W_LOCATIONS:
config.scan(view_location)
# Register Adapters
config.registry.registerAdapter(
AuctionDGFFinancialAssetsConfigurator,
(IDgfFinancialAssetsAuction, IRequest),
IContentConfigurator
)
config.registry.registerAdapter(
AwardingNextCheckV3,
(IDgfF... | tCheck
)
config.registry.registerAdapter(
AuctionDGFFinancialAssetsManagerAdapter,
(IDgfFinancialAssetsAuction, ),
IAuctionManager
)
LOGGER.info("Included openprocurement.auctions.dgf.other plugin",
extra={'MESSAGE_ID': 'included_plugin'})
# add accreditation... |
KirovVerst/qproject | qproject/__init__.py | Python | mit | 130 | 0 | from _ | _future__ import absolute_import, unicode_literals
from qproject.celery import app as celery_app
__all__ = ['celery | _app']
|
TracyWebTech/cnab240 | tests/data.py | Python | mit | 4,584 | 0.003054 |
import os
import codecs
from decimal import Decimal
from cnab240.bancos import itau
from cnab240.tipos import Lote, Evento
TESTS_DIRPATH = os.path.abspath(os.path.dirname(__file__))
ARQS_DIRPATH = os.path.join(TESTS_DIRPATH, 'arquivos')
def get_itau_data_from_file():
itau_data = dict()
arquivo_remessa = code... | data['seg_q2'] = itau.registros.SegmentoQ()
itau_data['seg_q2_str'] = arquivo_remessa.readline().strip('\r\n')
itau_data['seg_q2'].carregar(itau_data['seg_q2_str'])
itau_data['trailer_lote'] = itau.registros.TrailerLoteCobranca()
it | au_data['trailer_lote_str'] = arquivo_remessa.readline().strip('\r\n')
itau_data['trailer_lote'].carregar(itau_data['trailer_lote_str'])
itau_data['trailer_arquivo'] = itau.registros.TrailerArquivo()
itau_data['trailer_arquivo_str'] = arquivo_remessa.readline().strip('\r\n')
itau_data['trailer_arquivo'... |
dbtucker/universe | docs/tutorial/helloworld.py | Python | apache-2.0 | 1,005 | 0.00597 | import time
import http.server
import os
HOST_NAME = '0.0.0.0' # Host name of the http server
# Gets the port number from $PORT0 environment variable
PORT_NUMBER = int(os.environ['PORT0'])
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(s | ):
"""Respond to a GET request."""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><head><title>Time Server</title></head>")
s.wfile.write("<body><p>The current time is {}</p>".f | ormat(time.asctime()))
s.wfile.write("</body></html>")
if __name__ == '__main__':
server_class = http.server.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print(time.asctime(), "Server Starts - {}:{}".format(HOST_NAME, PORT_NUMBER))
try:
httpd.serve_forever()
... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/nbformat/v2/__init__.py | Python | bsd-2-clause | 2,577 | 0.002716 | """The main API for the v2 notebook format.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distribute... | ------------------------------------------------------------------------
import os
from .nbbase import (
NotebookNode,
new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
new_metadata, new_author
)
from .nbjson import reads as reads_json, writes as writes_json
from .nbjson im | port reads as read_json, writes as write_json
from .nbjson import to_notebook as to_notebook_json
from .nbxml import reads as reads_xml
from .nbxml import reads as read_xml
from .nbxml import to_notebook as to_notebook_xml
from .nbpy import reads as reads_py, writes as writes_py
from .nbpy import reads as read_py, wr... |
oscarvarto/oscarvarto.github.io | fabfile.py | Python | apache-2.0 | 2,437 | 0.004103 | from fabric.api import *
import fabric.contrib.project as project
import os
import shutil
import sys
import SocketServer
from pelican.server import ComplexHTTPRequestHandler
# Local path configuration (can be absolute or relative to fabfile)
env.deploy_path = 'output'
DEPLOY_PATH = env.deploy_path
# Remote server co... | ""Publish to production via rsync"""
local('pelican -s publishconf.py')
project.rsync_project(
remote_dir=dest_path,
exclude=".DS_Store",
local_dir=DEPLOY_PATH.rstrip('/') + '/',
delete=True,
extra_opts='-c',
)
def gh_pages():
"""Publish to GitHub Pages"""
re... | )
local("ghp-import -b {github_pages_branch} {deploy_path} -p".format(**env))
|
jiadaizhao/LeetCode | 0101-0200/0110-Balanced Binary Tree/0110-Balanced Binary Tree.py | Python | mit | 493 | 0.002028 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.lef | t = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(root):
if root is None:
return (True, 0)
lb, lh = dfs(root.left)
rb, rh = dfs(root.right)
h = max(lh, rh) + 1
return (lb and r... | s(root)[0]
|
neslihanturan/artge | app/context_processors.py | Python | gpl-3.0 | 556 | 0.005396 | from .models import MenuItem, ContactInformation
#custom context processor | to pass menu items to base.html
def list_menu(request):
menu_items = MenuItem.objects.all()
phone = ContactInformation.objects.all()[0].phone
fax = ContactInformation.objects.all()[0].fax
email = ContactInform | ation.objects.all()[0].email
address = ContactInformation.objects.all()[0].address
print(phone)
return {'menu_items': menu_items,
'phone': phone,
'fax': fax,
'email': email,
'address': address,}
|
j5shi/Thruster | pylibs/idlelib/PathBrowser.py | Python | gpl-2.0 | 3,069 | 0.001303 | import os
import sys
import imp
from idlelib.TreeWidget import TreeItem
from idlelib.ClassBrowser import ClassBrowser, ModuleBrowserTreeItem
from idlelib.PyShell import PyShellFileList
class PathBrowser(ClassBrowser):
def __init__(self, flist, _htest=False):
"""
_htest - bool, chang... | file = | os.path.join(self.dir, name)
if self.ispackagedir(file):
nn = os.path.normcase(name)
packages.append((nn, name, file))
packages.sort()
sublist = []
for nn, name, file in packages:
item = DirBrowserTreeItem(file, self.packages + [name... |
ubyssey/dispatch | dispatch/migrations/0018_podcasts.py | Python | gpl-2.0 | 2,099 | 0.003335 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-21 18:59
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migr | ations.Migration):
dependencies = [
('dispatch', '0017_subsections'),
]
operations = [
migrations.CreateModel(
name='Podcast',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('slug', models.S... | ('author', models.CharField(max_length=255)),
('owner_name', models.CharField(max_length=255)),
('owner_email', models.EmailField(max_length=255)),
('category', models.CharField(max_length=255)),
('image', models.ForeignKey(null=True, on_delete=dj... |
AIMS-Ghana/cams | disorganized/dostuff.py | Python | cc0-1.0 | 1,634 | 0.003672 | __author__ = 'carlpearson'
import csv
def seeds():
res = []
with open("rdat.csv", newline="") as csvfile:
lines_reader = csv.reader(csvfile)
lines_reader.__next__()
for x in range(0, 5):
dat = lines_reader.__next__()
res.append(int(dat[1].strip()))
return re... | __next__()
res.append(dat[1].strip())
return res
import random
if __name__ == "__main__":
colors = color_list()
shapes = shape_list()
tot_res = {}
for s in seeds():
random.seed(s)
print("seed", s, sep=" ")
with open("cuts"+str(s | )+".out", mode="w") as tarfile:
writer = csv.writer(tarfile)
res = {}
for x in range(0, 40):
c = random.choice(colors)
s = random.choice(shapes)
writer.writerow([c, s])
m = res.get(c, {})
m[s] = m.get(s, ... |
pytroll/pyspectral | pyspectral/tests/data.py | Python | gpl-3.0 | 17,220 | 0.006678 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, 2019 Pytroll developers
#
# Author(s):
#
# Adam.Dybbroe <a000680@c20671.ad.smhi.se>
#
# 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 ... | [0.09136979, 0.12638275, 0.14449048, 0.16090511, 0.17467757,
0.18867479],
[0.09136979, 0.12903725, 0.14820713, 0.16542192, 0.17977735,
0.19430672]],
[[0.09770... | 0.17253682],
[0.09770439, 0.12222815, 0.1385407, 0.15448725, 0.16840136,
0.18287206],
[0.09770439, 0.12838849, 0.14689755, 0.16441305, 0.17942691,
0.19487251],... |
jrconlin/campaign_manager | campaign/decorators.py | Python | mpl-2.0 | 4,802 | 0.000208 | import json
import pyramid.httpexceptions as http
import random
import utils
from campaign import logger, LOG
from campaign.auth.default import DefaultAuth
from dateutil import parser
from pyramid.request import Request
from pyramid.testing import DummyRequest
from time import time
class checkService(object):
"""... | = request.registry.get('storage')
if utils.strToBool(settings.get("db.checkAccount", True)):
return storage.is_user(email)
else:
return True
except TypeError:
pass
except Exception:
if utils.strToBool(settings. | get('dbg.traceback', False)):
import traceback
traceback.print_exc()
if utils.strToBool(settings.get('dbg.break_unknown_exception',
False)):
import pdb
pdb.set_trace()
pass
return ... |
nwjs/chromium.src | third_party/wpt_tools/wpt/tools/manifest/update.py | Python | bsd-3-clause | 3,459 | 0.000867 | #!/usr/bin/env python
import argparse
import os
from . import manifest
from . import vcs
from .log import get_logger, enable_debug_logging
from .download import download_from_github
here = os.path.dirname(__file__)
wpt_root = os.path.abspath(os.path.join(here, os.pardir, os.pardir))
logger = get_logger()
MYPY = Fa... | "--url-base", action="store", default="/",
help="Base url to use as the mount point for tests in this manifest.")
parser.add_argument(
"--no-download", dest="download", action="store_false", default=True,
help="Never attempt to download the manifest.")
parser.add_argument(
"-... | ath in which to store any caches (default <tests_root>/.wptcache/)")
parser.add_argument(
"--no-parallel", dest="parallel", action="store_false", default=True,
help="Do not parallelize building the manifest")
return parser
def run(*args, **kwargs):
# type: (*Any, **Any) -> None
if kwar... |
showerst/openstates | openstates/ne/committees.py | Python | gpl-3.0 | 4,104 | 0.000487 | import re
import lxml.html
from billy.scrape import NoDataForPeriod
from billy.scrape.committees import CommitteeScraper, Committee
from openstates.utils import LXMLMixin
class NECommitteeScraper(CommitteeScraper, LXMLMixin):
jurisdiction = 'ne'
latest_only = True
def _scrape_standing_committees(self):
... | raska state legislature."""
main_url = 'http://www.nebraskalegislature.gov/committees/select-committees.php'
page = self.lxmlize(main_url) |
committee_nodes = self.get_nodes(
page,
'//div[@class="main-content"]/div[@class="panel panel-leg"]')
for committee_node in committee_nodes:
committee_name = self.get_node(
committee_node,
'.//h2[@class="panel-title"]/text()[normaliz... |
commtrack/temp-aquatest | apps/xformmanager/tests/data_versioning.py | Python | bsd-3-clause | 8,448 | 0.006037 | import unittest
from decimal import Decimal
from datetime import *
from django.db import connection
from hq.dbutil import get_column_names
from xformmanager.tests.util import *
from xformmanager.xformdef import FormDef
from xformmanager.models import FormDataGroup, FormDataColumn
class DataVersioningTestC... | ginal_formdef, duplicate_formdef]
dom = Domain.objects.all()[0]
group = FormDataGroup.from_forms(forms, dom)
self.assertEqual(2, len(group.forms.all()))
for form in group.f | orms.all():
self.assertTrue(form in forms)
columns = self.original_formdef.get_data_column_names()
self.assertEqual(len(columns), len(group.columns.all()))
for column in columns:
column_def = group.columns.get(name=column)
self.assertEqual(2, l... |
pcn/graphite-web | misc/generate-apache-config.py | Python | apache-2.0 | 1,339 | 0.014937 | #!/usr/bin/env python
import sys, os
from optparse import OptionParser
option_parser = OptionParser()
option_parser.add_option('--install-root',default='/opt/graphite/',
help="The base directory of the graphite installation")
option_parser.add_option('--libs',default=None,
help="The directory where the graphite p... | ot install_root.endswith('/'):
install_root += '/'
if not os.path.isdir(install_root):
print "Graphite does not appear to be installed at %s, do you need to specify a different --install-root?" % install_root
sys.exit(1)
python_path = [ os.path.join(install_root,'webapp') ]
if options.libs:
python_path.append... | e('@INSTALL_ROOT@', install_root)
vhost = vhost.replace('@PYTHON_PATH@', str(python_path))
vhost = vhost.replace('@DJANGO_ROOT@', django_root)
fh = open('graphite-vhost.conf','w')
fh.write(vhost)
fh.close()
print "Generated graphite-vhost.conf"
print "Put this file in your apache installation's vhost include director... |
valhallasw/pywikibot-core | pywikibot/daemonize.py | Python | mit | 1,961 | 0 | # -*- coding: utf-8 -*-
"""Module to daemonize the current process on Unix."""
#
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
#
import os
import sys
import codecs
is_daemon = False
def daemonize(close_fd=True, chdir=True, write_pid=False, redirect_std=N... | compatible operating systems.
The process will fork to the background and return control to terminal.
@param close_fd: Close the standard streams and replace them by /dev/null
@type close_fd: bool
@param chdir: Change the current working directory to /
@type chdir: bool
@param write_pid: Write ... | name to redirect stdout and stdin to
@type redirect_std: str
"""
# Fork away
if not os.fork():
# Become session leader
os.setsid()
# Fork again to prevent the process from acquiring a
# controlling terminal
pid = os.fork()
if not pid:
global is... |
seecr/meresco-lucene | meresco/__init__.py | Python | gpl-2.0 | 1,123 | 0.002671 | ## begin license ##
#
# "Meresco Lucene" is a set of components and tools to integrate Lucene (based on PyLucene) into Meresco
#
# Copyright (C) 2013 Seecr (Seek You Too B.V.) http://seecr.nl
# Copyright (C) 2013 Stichting Bibliotheek.nl (BNL) http://www.bibliotheek.nl
#
# This file is part of "Meresco Lucene"
#
# "Mer... | cene" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# | (at your option) any later version.
#
# "Meresco Lucene" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy... |
trivoldus28/pulsarch-verilog | tools/local/bas-release/bas,3.9/lib/python/lib/python2.3/test/test_cookie.py | Python | gpl-2.0 | 1,516 | 0.005277 | # Simple test suite for Cookie.py
from test.test_support import verify, verbose, run_doctest
import Cookie
import warnings
warnings.filterwarnings("ignore",
".* class is insecure.*",
DeprecationWarning)
# Currently this only tests SimpleCookie
cases = [
('chips=ah... | 'path'])
print C.js_output()
print C.js_output(['path'])
# Try cookie with quoted meta-data
C = Cookie.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
verify(C['Customer'].value == 'WILE_E_COYOTE')
verify(C['Customer']['version'] == '1')
verify(C['Customer']['path'] == '/acme')
print "If ... | ws up after this line, it's from Cookie's doctest."
run_doctest(Cookie)
|
jabbalaci/PrimCom | data/python/infinity.py | Python | gpl-2.0 | 118 | 0 | my_i | nf = float('Inf')
print 99999999 > my_inf
# False
my_neg_inf = float('-Inf')
print my_n | eg_inf < -99999999
# True
|
SVilgelm/CloudFerry | cloudferry/actions/helper/fake_action.py | Python | apache-2.0 | 777 | 0 | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you ma | y 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 O... | nse for the specific language governing permissions and#
# limitations under the License.
from cloudferry.lib.base.action import action
class FakeAction(action.Action):
def __init__(self, init):
super(FakeAction, self).__init__(init)
def run(self, **kwargs):
pass
|
enthought/distarray | distarray/localapi/format.py | Python | bsd-3-clause | 11,157 | 0 | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... | ['buffer'])
def read_localarray_header(fp, version):
"""
Read an array header from a filelike object using the 1.0 file format
version.
This will leave the file object located just after the header.
Parameters
----------
fp : filelike object
A file object or something with a `.re... | --
__version__ : str
Version of the Distributed Array Protocol used.
dim_data : tuple
A tuple containing a dictionary for each dimension of the underlying
array, as described in the Distributed Array Protocol.
Raises
------
ValueError
If the data is invalid.
"""... |
malor/oslo.db | tests/sqlalchemy/test_migrations.py | Python | apache-2.0 | 6,274 | 0 | # Copyright 2010-2011 OpenStack Foundation
# Copyright 2012-2013 IBM Corp.
# 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/li... | k_141.assert_called_with(self.engine, test_value)
def test_migrate_down(self):
self.migration_api.db_version.return_value = 42
self.a | ssertTrue(self._migrate_down(self.engine, 42))
self.migration_api.db_version.assert_called_with(
self.engine, self.REPOSITORY)
def test_migrate_down_not_implemented(self):
self.migration_api.downgrade.side_effect = NotImplementedError
self.assertFalse(self._migrate_down(self.eng... |
jamieadkins95/Roach-backend | scripts/gogapi.py | Python | apache-2.0 | 10,416 | 0.003072 | #!/usr/bin/env python3
import http.cookiejar
import json
import re
import requests
import urllib.parse
import http.server
import webbrowser
from datetime import datetime, timezone, timedelta
import os.path
from pprint import pprint
PARSE_JSON = True
# Taken from Gwent Client logs. These are the Gwent client client i... | }?_data_version=" + DATA_VERSION,
"gwent.versions": | "decks:/data_versions",
"gwent.version": "decks:/data_versions/{}",
"gwent.config": "config:/game/" + GAME + "_" + SECRET + "/config.json",
"gwent.game": "config:/game/" + GAME + "_" + SECRET + "/data/" + DATA_VERSION + "_" + HASH + "/data_definitions.zip",
"gwent.profile": "profile:/users/{}"
}
gog_s... |
imiolek-ireneusz/pysiogame | game_boards/game013.py | Python | gpl-3.0 | 6,163 | 0.001298 | # -*- coding: utf-8 -*-
import random
import sys
import pygame
import classes.board
import classes.extras as ex
import classes.game_driver as gd
import classes.level_controller as lc
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self,... | for i in range(self.data[0])]
if self.board.grid[2] == self.solution_grid:
for i in range(len(self.board.ships)):
if self.board.ships[i].grid_y == 2:
result[self.board.ships[i].grid_x] = self.board.ships[i].value
result_s = ''.join(result).strip()
... | y_again()
else:
self.level.try_again()
|
siongui/userpages | content/code/python-jinja2-vs-go-html-template/jinja2-example-3.py | Python | unlicense | 485 | 0.006186 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from jinja2 import Template
import sys
tmpl = """
{% for link in links %}
{{ l | oop.index0 }}: <a href="{{link.href}}">{{link.name}}</a>
{{ loop.index }}: <a href="{{link.href}}">{{link.name}}</a>
{% endfor %}
"""
if __name__ == '__main__':
links = [
{'name | ': 'Google', 'href': 'https://www.google.com'},
{'name': 'Facebook', 'href': 'https://www.facebook.com'}
]
t = Template(tmpl)
sys.stdout.write(t.render(links=links))
|
ChenglongChen/Kaggle_HomeDepot | Code/Chenglong/model_param_space.py | Python | mit | 14,040 | 0.005413 | # -*- coding: utf-8 -*-
"""
@author: Chenglong Chen <c.chenglong@gmail.com>
@brief: model parameter space
"""
import numpy as np
from hyperopt import hp
import config
## xgboost
xgb_random_seed = config.RANDOM_SEED
xgb_nthread = config.NUM_CORES
xgb_n_estimators_min = 100
xgb_n_estimators_max = 1000
xgb_n_estimato... | single model)
param_space_reg_xgb_tree_best_single_model = {
"booster": "gbtree",
"objective": "reg:linear",
"base_score": config.BASE_SCORE,
"n_estimators" : 880,
"learning_rate" | : 0.014,
"gamma": 0.0007375692431738125,
"reg_alpha" : 0.0024595063900801238,
"reg_lambda" : 0.0031003919409140915,
"min_child_weight": 96.14430369781684,
"max_depth": 7,
"subsample": 0.8500000000000001,
"colsample_bytree": 1,
"colsample_bylevel": 0.15000000000000002,
"nthread": xgb_... |
iMurfyD/supremm | supremm/subsample.py | Python | lgpl-3.0 | 3,772 | 0.002121 | #!/usr/bin/env python
""" Timeseries subsampling module """
import numpy
class TimeseriesAccumulator(object):
""" Stores a subset of time-value pairs for a dataseries """
MAX_DATAPOINTS = 100
LEAD_IN_DATAPOINTS = 10
def __init__(self, nhosts, totaltime):
self._totaltime = totaltime
se... | += delta
| else:
self._accumulator = numpy.zeros(value.shape)
self._last = value
return self._accumulator
def get(self):
""" get current stored value """
return self._accumulator
|
Beauhurst/django | tests/gis_tests/distapp/tests.py | Python | bsd-3-clause | 24,141 | 0.002361 | from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform,
)
from django.contrib.gis.geos import GEOSGeometry, LineString, Point
from django.contrib.gis.measure import D # alias for Distance
from django.db import connection
from django.db.models import F, Q
from django.test ... | , SouthTexasCityFt.objects.count())
self.assertEqual(11, AustraliaCity.objects.count())
self.assertEqual(4, SouthTexasZipcode.objects.count())
self.assertEqual(4, CensusZipcode.objects.count())
self.assertEqual(1, Interstate.objects.count())
| self.assertEqual(1, SouthTexasInterstate.objects.count())
@skipUnlessDBFeature("supports_dwithin_lookup")
def test_dwithin(self):
"""
Test the `dwithin` lookup type.
"""
# Distances -- all should be equal (except for the
# degree/meter pair in au_cities, that's s... |
jashworth-isb/cmonkey-python | cmonkey/microarray.py | Python | lgpl-3.0 | 7,657 | 0.001175 | # vi: sw=4 ts=4 et:
"""microarray.py - cMonkey microarray related processing
This module captures the microarray-specific scoring component
of cMonkey.
This file is part of cMonkey Python. Please see README and LICENSE for
more information and licensing details.
"""
import numpy as np
import logging
import datamatrix ... | return row_scores_for_cluster
else:
return None
def __compute_row_scores_for_submatrix(matrix, submatrix):
"""For a given matrix, compute the row scores. The second submatrix is
used to calculate the column means on and should be derived from
datamatrix filtered by the row names and column nam... | ld be filtered by the columns of a specific cluster in
order for the column means to be applied properly.
The result is a DataMatrix with one row containing all the row scores"""
return np.log(
util.row_means(np.square(matrix.values - submatrix.column_means())) + 1e-99)
"""
def __quantile_normaliz... |
gandrewstone/yadog | d2html.py | Python | gpl-3.0 | 3,641 | 0.029388 | """?? This file is the engine that converts the xml to html
"""
import pdb
import os
from common import *
import microdom
#? <section name="Helper Functions">
def genTagDict(xml):
"""?? Converts a <ref>microdom</ref> tree into a dictionary of key: tag names, value: list of objects
"""
tags = {}
for node in ... | rating %s using module %s" % (k,v)
importAndRun(v,[("%s.generate(obj,cfg,td)" % v,{"obj":xml,"cfg":cfg,"td":tagDict})])
# Generate the lowest level pages
for sect in cfg["sections"]:
if tagDict.has_key(sect):
# Look | up the page implementation for this section
pi = htmlcfg["pageimplementers"].get(sect,None)
if pi:
importAndRun(pi,[("%s.generate(obj,cfg)" % pi,{"obj":obj,"cfg":cfg}) for obj in tagDict[sect]])
pi = htmlcfg["indeximplementers"].get(sect,None)
if pi:
importAndRun(pi,[("%s.gener... |
vyrus/wubi | src/wubi/backends/win32/virtualdisk.py | Python | gpl-2.0 | 5,753 | 0.004519 | #
# Copyright (c) 2007, 2008 Agostino Russo
# Python port of wubi/disckimage/main.c by Hampus Wessman
#
# Written by Agostino Russo <agostino.russo@gmail.com>
#
# win32.ui 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 So... |
log.debug("grant_privileges: AdjustTokenPrivileges() failed.")
else:
log.debug("grant_privileges: LookupPrivilegeValue() failed.")
defs.CloseHandle(handle)
else:
log.debug("grant_privileges: OpenProcessToken() failed.")
def call_SetFileValidData(file_hand... | sys.getwindowsversion()
major, minor, build, platform, txt = full_version
if platform < 2:
log.debug("Skipping SetFileValidData, because Windows 95/98/ME was detected")
return
try:
SetFileValidData = ctypes.windll.kernel32.SetFileValidData
except:
log.debug("Coul... |
qPCR4vir/orange | docs/tutorial/rst/code/data-instances4.py | Python | gpl-3.0 | 130 | 0 | import Orange
fro | m collect | ions import Counter
data = Orange.data.Table("lenses")
print Counter(str(d.get_class()) for d in data)
|
maltouzes/pixel-fighters-2D | load_character.py | Python | gpl-3.0 | 844 | 0 | """ This file is a part of pixel-fighters-2D made by Maltouzes """
def load_character(self, character, character_source):
import os
print character
""" Load all img when the game start """
for file in os.listdir(self.path + character + '/5x/'):
if file.endswith(".gif"):
if "player"... | self.img_monster.source = (self.path + self.path_monster
+ "/5x/" + file)
elif "2" in character_source:
self.img_monster2.source = (self.path + self.path_monster2
+ "/5x/" + file)
# ... | int self.img.source
|
CheckPoint-APIs-Team/LocalToGlobal | local_object_to_global.py | Python | apache-2.0 | 5,523 | 0.002897 | """
This class is used as a dispatcher, calls the relevant function according to the type object
"""
import sys
from args_container import ArgsContainer
from local_address_range_to_global import LocalAddressRangeToGlobal
from local_group_to_global import LocalGroupToGlobal
from local_group_to_global import L... | gs_container):
"""
This function gets the type of a given objects and sends it to relevant
:param object_info:
:param args_container:
:return:
"""
if object_info["type"] is None:
if object_info["uid"]:
type_obj = sel | f.get_obj_type(object_info["uid"], args_container)
if type_obj is None:
return None
args_container.obj_uid = object_info["uid"]
else:
args_container.log("Couldn't get Object, object won't be cloned")
return None
... |
zeziba/PiMotionCamera | src/GUI/img_loader/loader.py | Python | gpl-3.0 | 1,624 | 0.003695 | from os.path import join, split
from os import listdir, getcwd
from PIL import Image, ImageTk
class Loader:
def __init__(self, save_location: str=getcwd()):
self._path = save_location if save_location else None
self._files = list()
self.cache = dict()
self.__current_index = 0
... | return True
except FileNotFoundError as error:
print(error)
return False
def _load_files(self):
"""
Function Works as required
:return:
"""
self._files = [join(self._path, file) for file in listdir(self._path)
if ".png" | in split(file)[1]]
def change_index(self, move_by):
self.__current_index += move_by
if self.__current_index < 0:
self.__current_index += len(self._files)
if self.__current_index > len(self._files) - 1:
self.__current_index -= len(self._files)
def __call__(self,... |
MichaelPHStumpf/Peitho | peitho/errors_and_parsers/abc_sysbio/abcsysbio/generateTemplate.py | Python | mit | 13,980 | 0.013019 |
def getSpeciesValue(species):
"""
Return the initial amount of a species.
If species. | isSetInitialAmount() == True, return the initial amount.
Otherwise, return the initial concentration.
***** args *****
species: a libsbml.Species object
"""
if species.isSetInitialAmount():
return species.getInitialAmount()
else:
return species.getInitialConcentrat... | enerate a model summary file (model_summary.txt) and a template file (filename) from one or more SBML source files.
***** args *****
source: a list of strings.
Each entry describes a SBML file.
***** kwargs *****
filename: a string.
The name of th... |
vlegoff/cocomud | src/ui/dialogs/trigger.py | Python | bsd-3-clause | 10,388 | 0.001637 | # Copyright (c) 2016, LE GOFF Vincent
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and th... | og):
"""Trigger dialog."""
def __init__(self, engine, world):
super(TriggerDialog, self).__init__(Non | e, title=t("common.trigger", 2))
self.engine = engine
self.world = world
self.InitUI()
self.Center()
def InitUI(self):
sizer = wx.BoxSizer(wx.VERTICAL)
top = wx.BoxSizer(wx.HORIZONTAL)
edit = wx.BoxSizer(wx.VERTICAL)
buttons = wx.BoxSizer(wx.HORIZONT... |
Butakus/Roberto | rpi/src/roberto_driver/src/roberto_driver/parser_test.py | Python | gpl-3.0 | 1,927 | 0 | """ Test the serialize functions from the parser module """
from parser import *
from driver_comm import *
from time import sleep
def test_callback(command, payload):
print "------------------------------------------------"
print "Command received: {}".format(command)
print "Payload: {}".format(payload)
... | a - 3.14159265))
if __name__ == '__main__':
comm = ArdPiComm(test_callback, port="/dev/ttyACM0")
comm.start()
print "Press Enter to exit..."
sleep(2)
raw_input()
comm | .stop()
|
digideskio/lets-encrypt-preview | letsencrypt/constants.py | Python | apache-2.0 | 2,420 | 0 | """Let's Encrypt constants."""
import logging
from acme import challenges
SETUPTOOLS_PLUGINS_ENTRY_POINT = "letsencrypt.plugins"
"""Setuptools e | ntry point group name for plugins."""
CLI_DEFAULTS = dict(
config_files=["/etc/letsencrypt/cli.ini"],
verbose_count=-(logging.WARNING / 10),
server="https://www.letsencrypt-demo.org/acme/new-reg",
rsa_key_size=2048,
rollback_checkpoints=0,
config_dir="/etc/letsencrypt",
work_dir="/var/lib/... | backups",
key_dir="/etc/letsencrypt/keys",
certs_dir="/etc/letsencrypt/certs",
cert_path="/etc/letsencrypt/certs/cert-letsencrypt.pem",
chain_path="/etc/letsencrypt/certs/chain-letsencrypt.pem",
renewer_config_file="/etc/letsencrypt/renewer.conf",
no_verify_ssl=False,
dvsni_port=challenges.D... |
nbari/my-sandbox | python/exercices/k_points/NN.py | Python | bsd-3-clause | 1,144 | 0.000874 | """
http://en.wikipedia.org/wiki/K-d_tree#Nearest_neighbour_search
"""
from collections import | namedtuple
from operator import itemgetter
from pprint import pformat
class Node(namedtuple('Node', 'location left_child right_child')):
def __repr__(self):
return pformat(tuple(self))
def kdtree(point_list, depth=0):
try:
k = len(point_list[0]) # assumes all points have the same dimensio... |
axis = depth % k
# Sort point list and choose median as pivot element
point_list.sort(key=itemgetter(axis))
median = len(point_list) // 2 # choose median
# Create node and construct subtrees
return Node(
location=point_list[median],
left_child=kdtree(point_list[:median], dept... |
hradec/cortex | test/IECore/MeshAlgoTest.py | Python | bsd-3-clause | 14,716 | 0.058983 | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | of source code must retain the above copyright
# notice, this list of co | nditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of Image Engine Design no... |
mat128/python-ubersmith-remote-module-server | ubersmith_remote_module_server/api.py | Python | apache-2.0 | 1,954 | 0.003071 | # Copyright 2016 Internap
#
# 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, sof... | uter.list_implemented_methods(module)
return json_response({'implemented_methods': methods}, 200)
def handle_remote_invocation(self, module):
data = request.get_json()
output = self.router.invoke_method(module=module, **data)
| return json_response(output, 200)
def json_response(data, code):
json_data = json.dumps(data, indent=None)
response = current_app.response_class(json_data, mimetype='application/json; charset=UTF-8')
response.status_code = code
return response
|
huertatipografica/HTLetterspacer | Examples/ExampleFont-Glyphs3_autospace.py | Python | gpl-3.0 | 826 | 0.159806 |
# Reference
# Script, Category, Subcategory, case, value, referenceGlyph, filter
# Letters
*,Letter,*,upper,1.25,H,*,
*,Letter,*,smallCaps,1.1,h.sc,*,
*,Letter,*,lower,1,x,*,
*,Letter,*,minor,0.7,m.sups,.sups,
# Numbers
*,Number,Decimal Digit,*,1.2,one,*,
*,Number,Decimal Digit,*,1.2,zero.osf,.osf,
*,Number,Fraction... | Currency,*,1.6,*,*,
*,Symbol,*,*,1.5,*,*,
*,Mark,*,*,1,*,*,
# Devanagari
devanagari,Letter,Other,*,1,devaHeight,*,
devanagari,Letter,Ligature,*, | 1,devaHeight,*,
|
pcampese/codewars | sudoku_solver_level_3_1.py | Python | gpl-3.0 | 6,456 | 0.032063 | # https://www.codewars.com/kata/sudoku-solver/train/python
def sudoku(puzzle):
import collections
print('=== in sudoku ===')
# Print arguments
print_board(puzzle)
# Count the numbers that are currently populated on the sudoku board
number_count = collections.Counter(number for row in puzzle for number in row)... | ts
for row in puzzle: # Go | through each row in the board
single_row = [row[s_index:s_index+3] for s_index in xrange(0, len(row), 3)]
# Break it down:
# single_row = [] #
# for s_index in xrange(0, len(row), 3): # s_index to define where to split the row (every 3 numbers)
# split_row = row[s_index:s_index+3] # Get the s... |
pinkpegasus/omaha_vs2010 | enterprise/generate_group_policy_template.py | Python | apache-2.0 | 16,322 | 0.004166 | #!/usr/bin/python2.4
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | RIC
VALUENAME AutoUpdateCheckPeriodMinutes
DEFAULT 1400 ; 23 hours 20 minutes.
MIN 60
MAX 43200 ; 30 days.
SPIN 60 ; Increment in hour chunks.
END PART
PART !!Part_DisableAllAutoUpdateChecks CHECKBOX
VALUENAME... | runs last.
VALUENAME AutoUpdateCheckPeriodMinutes VALUE NUMERIC 0
END ACTIONLISTON
ACTIONLISTOFF
; Do nothing. Let Part_AutoUpdateCheckPeriod take effect.
END ACTIONLISTOFF
VALUEOFF NUMERIC 0
VALUEON NUMERIC 1
E... |
openstack/barbican | barbican/common/policies/secrets.py | Python | apache-2.0 | 4,101 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | 'not rule:secret_private_read) or ' +
f"({_PROJECT_MEMBER} and ({_SECRET_CREATOR} or " +
f"{_SECRET_IS_NOT_PRIVATE})) or {_PROJECT_ADMIN}",
scope_types=['project'],
description='Delete a secret by uuid.',
operations=[
{
'path': '/... | name='secrets:post',
check_str=f'rule:admin_or_creator or {_MEMBER}',
scope_types=['project'],
description='Creates a Secret entity.',
operations=[
{
'path': '/v1/secrets',
'method': 'POST'
}
]
),
policy.Document... |
ruler501/modserver | modserver/settings.py | Python | lgpl-3.0 | 3,033 | 0 | """
Django settings for modserver project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... | ddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
| 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'modserver.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'... |
gbook/nidb | src/gdcm/Examples/Python/AddPrivateAttribute.py | Python | gpl-3.0 | 1,122 | 0.019608 | ############################################################################
#
# Program: GDCM (Grassroots DICOM). A DICOM library
#
# Copyright (c) 2006-2011 Mathieu Malaterre
# All rights reserved.
# See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
#
# This software is distributed ... |
# PURPOSE. See the above copyright notice for more information.
#
############################################################################
"""
Usage:
python AddPrivateAttribute.py input.dcm output.dcm
"""
import sys
import gdcm
if __name__ == "__main__":
file1 = sy | s.argv[1]
file2 = sys.argv[2]
r = gdcm.Reader()
r.SetFileName( file1 )
if not r.Read():
sys.exit(1)
f = r.GetFile()
ds = f.GetDataSet()
# Create a dataelement
de = gdcm.DataElement(gdcm.Tag(0x0051, 0x1011))
de.SetByteStringValue("p2")
de.SetVR(gdcm.VR(gdcm.VR.SH))
ds.Insert(de)
w = gdcm... |
mdbenito/ModelSelection | src/LocalTests.py | Python | gpl-3.0 | 2,638 | 0.001895 | from Hypotheses import *
from ModelSelection import LinearRegression
from Test import *
sigma = 5 # observation noise sigma
##############################################################################
# Synthetic tests
##############################################################################
from Test import ... | ####################################################################
# Interactive tests
##############################################################################
"""
from Test import select_points_and_fit
hc = HypothesisCollection()
hc.append(PolynomialHypothesis(M=2, variance=3, | noiseVariance=sigma**2))
hc.append(PolynomialHypothesis(M=3, variance=3, noiseVariance=sigma**2))
hc.append(TrigonometricHypothesis(halfM=4, variance=2, noiseVariance=sigma**2))
lr = LinearRegression(hc, sigma)
select_points_and_fit(lr, num=10)
"""
####################################################################... |
harshilasu/GraphicMelon | y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/route53/healthcheck.py | Python | gpl-3.0 | 5,825 | 0.00206 | # Copyright (c) 2014 Tellybug, Matt Millar
#
# 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, publis... | t
# 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 included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, ... | UTHOR 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 SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
From http://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHealthCheck.html
POST... |
prikevs/KevBlog | config.py | Python | mit | 437 | 0.011442 | #coding:utf8
DEBUG = True
try:
import sae
DBNAME = sae.const.MYSQL_DB
USER = sae.const.MYSQL_USER
PASSWD = sae.const.MYSQL_PASS
HOST = s | ae.const.MYSQL_HOST
PORT = sae.const.MYSQL_PORT
SQLALCHEMY_DATABASE_URI = "mysql://%s:%s@%s:%s/%s" %(USER, PASSWD, HOST, PORT, DBNAME)
except:
SQLALCHEMY_DATABASE_URI = "sqlite:////tmp/test.db"
TOKEN = "123456"
AUTHOR = "Kevince"
TI | ME_FORMAT = '%Y-%m-%d %H:%M:%S'
|
nerdvegas/rez | src/rez/status.py | Python | apache-2.0 | 12,472 | 0.000962 | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
from __future__ import print_function
import sys
import os
import os.path
from fnmatch import fnmatch
from rez import __version__
from rez.utils.data_utils import cached_property
from rez.resolved_context import ResolvedContext
from re... | @cached_property
def context(self):
"""Get the current context.
Returns:
`ResolvedContext` or None if not in a context.
"""
path = self.context_file
return ResolvedContext.load(path) if path else None
@cached_property
def suites(self):
"""Get cu... | ATH.
Returns:
List of `Suite` objects.
"""
return Suite.load_visible_suites()
@cached_property
def parent_suite(self):
"""Get the current parent suite.
A parent suite exists when a context within a suite is active. That is,
during execution of a too... |
ehealthafrica-ci/kivy | kivy/uix/video.py | Python | mit | 7,503 | 0.000267 | '''
Video
=====
The :class:`Video` widget is used to display video files and streams.
Depending on your Video core provider, platform, and plugins, you will
be able to play different formats. For example, the pygame video
provider only supports MPEG1 on Linux and OSX. GStreamer is more
versatile, and can read many vid... | op'
return self.on_state(instance, value)
def on_state(self, instance, value):
if not self._video:
return
if value == 'play':
if self.eos:
self._video.stop()
self._video.position = 0.
self._video.eos = False
... | self._video.position = 0
self._video.eos = False
def _on_video_frame(self, *largs):
self.duration = self._video.duration
self.position = self._video.position
self.texture = self._video.texture
self.canvas.ask_update()
def _on_eos(self, *largs):
if self._... |
tjcsl/ion | intranet/apps/templatetags/dates.py | Python | gpl-2.0 | 2,302 | 0.000434 | import logging
from datetime import datetime
from django import template
from django.utils import timezone
register = template.Library()
logger = logging.getLogger(__name__)
@register.filter(expects_localtime=True)
def fuzzy_time(time):
"""Formats a `datetime.time` object relative to the current time."""
dt... | me` object relative to the current time."""
if date.tzinfo is None:
date = timezone.make_aware(date)
now = timezone.localtime()
if date <= now:
diff = now - date
seconds = diff.total_seco | nds()
minutes = seconds // 60
hours = minutes // 60
if minutes <= 1:
return "moments ago"
elif minutes < 60:
return "{} minutes ago".format(int(seconds // 60))
elif hours < 24:
hrs = int(diff.seconds // (60 * 60))
return "{} hour{}... |
Micronaet/micronaet-product | inventory_status_assign_wizard/assign_wizard.py | Python | agpl-3.0 | 9,908 | 0.005249 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###############################################################################
#
# ODOO (ex OpenERP)
# Open Source Management Solution
# Copyright (C) 2001-2015 Micronaet S.r.l. (<https://micronaet.com>)
# Developer: Nicola Riolini @thebrush (<https://it.linkedin.com/in/thebr... | dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID
from openerp import tools
from op | enerp.tools.translate import _
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
DEFAULT_SERVER_DATETIME_FORMAT,
DATETIME_FORMATS_MAP,
float_compare)
_logger = logging.getLogger(__name__)
class SaleOrderLine(orm.Model):
""" Model name: SaleOrderLine
"""
_inherit = 'sale.order.li... |
cgthayer/test | django-userlinks/userlinks/migrations/0004_auto_20170307_1838.py | Python | gpl-3.0 | 562 | 0.001779 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2017-03-08 02:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userlinks', '0003_auto_20170203_1130'),
]
operations = [
migrations.AlterFie... | ,
field=models.CharField(blank=True, choices=[(('likes',), 'Likes'), ('saved', 'Bookmarked'), ('been_to', 'Visited')] | , max_length=32, null=True),
),
]
|
nuagenetworks/vspk-python | vspk/v6/nuvnfthresholdpolicy.py | Python | bsd-3-clause | 16,674 | 0.008996 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyrigh... | F Threshold Policy represents thresholds for resources consumed by VNF instance running on NS Gateway and action to be taken when resource utilization crosses configured thresholds.
"""
__rest_name__ = "vnfthresholdpolicy"
__resource_name__ = "vnfthresholdpolicies"
## Constants
CONST_ENT... | OPE_GLOBAL = "GLOBAL"
CONST_ACTION_SHUTOFF = "SHUTOFF"
CONST_ACTION_NONE = "NONE"
CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE"
def __init__(self, **kwargs):
""" Initializes a VNFThresholdPolicy instance
Notes:
You can specify all parameters ... |
ngageoint/six-library | six/modules/python/six/tests/runUnitTests.py | Python | lgpl-3.0 | 1,737 | 0.001727 | #!/usr/bin/env python
#
# =========================================================================
# This file is part of six.sicd-python
# =========================================================================
#
# (C) Copyright 2004 - 2016, MDA Information Systems LLC
#
# six.sicd-python is free software; you can... | print(os.path.join(unitTestDir, childDir, test))
testPathname = os.path.join(unitTestDir, childDir, test)
if test.endswith('.py'):
command = ['python', testPathname]
else:
command = [utils.executableName(testPathname)]
if call(command) !=... | print('{} failed'.format(testPathname))
return False
return True
if __name__ == '__main__':
utils.setPaths()
run()
|
pior/moto | tests/test_ec2/test_key_pairs.py | Python | apache-2.0 | 2,532 | 0 | from __future__ import unicode_literals
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises
from nose.tools import assert_raises
import boto
import six
import sure # noqa
from boto.exception import EC2ResponseError
from moto import mock_ec2
@mock_ec2
def test_key_pai... | r('foo')
kp = conn.create_key_pair('bar')
assert kp.material.startswith('---- BEGIN RSA PRIVATE KEY ----')
kps = conn.get_all_key_pairs()
assert len(kps) == 2
# on Python 3, these are reversed for some reason
if six.PY3:
return
assert kps[0].name == 'foo'
assert kps[1].name == 'b... | assert len(kps) == 1
assert kps[0].name == 'foo'
@mock_ec2
def test_key_pairs_create_exist():
conn = boto.connect_ec2('the_key', 'the_secret')
kp = conn.create_key_pair('foo')
assert kp.material.startswith('---- BEGIN RSA PRIVATE KEY ----')
assert len(conn.get_all_key_pairs()) == 1
with as... |
51reboot/actual_13_homework | 06/peter/zhuangshiqi.py | Python | mit | 472 | 0.006356 | #!/usr/bin | /env python
# coding: utf-8
import time
import sys
print sys.argv
def test(func):
def wapper(*args, **kwargs):
print args, kwargs
if kwargs["username"] == "asdf":
print "ok"
else:
print "error"
print time.time()
func(*args, **kwargs)
print ti... | print "test"
test2(username="asdf", password=None)
|
wesleybowman/UTide | utide/astronomy.py | Python | mit | 4,983 | 0 | import numpy as np
# (comments based on t_tide)
# Coefficients of the formulas in the Explan. Suppl.
_sc = np.array([270.434164, 13.1763965268, -0.0000850, 0.000000039])
_hc = np.array([279.696678, 0.9856473354, 0.00002267, 0.000000000])
_pc = np.array([334.329556, 0.1114040803, -0.0007739, -0.00000026])
_npc = np.ar... | = np.atleast_1d(jd).flatten()
# Shift epoch to 1899-12-31 at noon:
# daten = 693961.500000000 Matlab datenum version
daten = 693595.5 # Python epoch is 366 days later than Matlab's
d = jd - daten
D = d / 10000
args = np.vstack((np.ones(jd.shape), d, D * D, D ** 3))
astro | = np.fmod((np.dot(_coefs, args) / 360), 1)
# lunar time: fractional part of solar day
# plus hour angle to longitude of sun
# minus longitude of moon
tau = jd % 1 + astro[1, :] - astro[0, :]
astro = np.vstack((tau, astro))
# derivatives (polynomial)
dargs = np.vsta... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_text/string_template_defaultpattern.py | Python | apache-2.0 | 69 | 0.014493 | import string
t = s | tring.Template('$var')
| print(t.pattern.pattern)
|
kpounot/nPDyn | nPDyn/lmfit/lmfit_builtins.py | Python | gpl-3.0 | 6,538 | 0 | """This module provides several built-in models for incoherent
neutron scattering data fitting.
These functions generate a `Model` class instance from
the **lmfit** package [#]_.
References
----------
.. [#] https://lmfit.github.io/lmfit-py/
"""
import operator
import numpy as np
try:
from lmfit import Comp... | s to pass to :func:`build_2D_model`
"""
def __init__(self, q, nLor=2, **kwargs):
prefix = ""
if "prefix" in kwargs.keys():
prefix = kwargs.pop("prefix")
left = delta(q, prefix="%sdelta_" % prefix, **kwargs)
right = lorentzian(q, prefix="%sl0_" % prefix, **kwargs)
... | right,
lorentzian(q, prefix="%sl%i_" % (prefix, i), **kwargs),
operator.add,
)
super().__init__(left, right, operator.add)
def guess(self, data, x=None, q=None, **kwargs):
"""Estimate initial model parameter values from data."""
pars = self.make_... |
hackersql/sq1map | lib/takeover/web.py | Python | gpl-3.0 | 16,870 | 0.003299 | #!/usr/bin/env python
#coding=utf-8
"""
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import os
import posixpath
import re
import StringIO
import tempfile
import urlparse
from extra.cloak.cloak import decloak
from lib.core.agent import agent
from ... | ath = None
self.webDirectory = None
def webBackdoorRunCmd(self, cmd):
if self.webBackdoorUrl is None:
return
output = None
| if not cmd:
cmd = conf.osCmd
cmdUrl = "%s?cmd=%s" % (self.webBackdoorUrl, cmd)
page, _, _ = Request.getPage(url=cmdUrl, direct=True, silent=True, timeout=BACKDOOR_RUN_CMD_TIMEOUT)
if page is not None:
output = re.search("<pre>(.+?)</pre>", page, re.I | re.S)
... |
fnl/libfnl | src/fnl/nlp/analysis.py | Python | agpl-3.0 | 10,878 | 0.003218 | import logging
from unicodedata import category
from unidecode import unidecode
from fnl.nlp.dictionary import Dictionary
from fnl.nlp.strtok import Category
from fnl.text.symbols import LATIN
from fnl.text.token import Token
class TextAnalytics:
"""
A toolset to annotate text with multiple entity taggers and... | :par | am use_greek_letters: do not expand/regularize Greek letters to their Latin words
"""
self.tag_all_nouns = tag_all_nouns
self.use_greek_letters = use_greek_letters
self._ner_dictionaries = []
self._ner_taggers = []
self._pos_tagger = pos_tagger
self._tokenizer = t... |
jaesivsm/pyAggr3g470r | jarr/controllers/icon.py | Python | agpl-3.0 | 1,276 | 0.001567 | import base64
from jarr.bootstrap import conf, session
from jarr.models import Icon
from jarr.utils import jarr_get
from .abstract import AbstractController
class IconController(AbstractController):
_db_cls = Icon
_user_id_key = None # type: str
@staticmethod
def _build_from_url(a | ttrs):
if 'url' in attrs and 'content' not in attrs:
try:
resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout,
user_agent=conf.crawler.user_agent)
except Exception:
| return attrs
attrs.update({'url': resp.url,
'mimetype': resp.headers.get('content-type', None),
'content': base64.b64encode(resp.content).decode('utf8')})
return attrs
def create(self, **attrs):
return super().create(**self._build_from_url(... |
Gleamo/gleamo-device | scheduler/scheduler.py | Python | bsd-2-clause | 2,501 | 0.001999 | from time import time
from networks.inetwork import INetwork
from dispatcher.dispatcher import Dispatcher
from commands.command import Command
from state.state import State
from colors.color import Color
from buzzer.buzzer_pattern import BuzzerPattern
DefaultCommand = Command(
duration=1,
color=Color.no_change... | mmand = DefaultCommand
| self.current_command.set_start_values(now, self.state.color)
return self.current_command
# determine which commands should get run
def run_commands(self, now):
current_command = self.get_current_command(now)
if current_command != None:
next_state = self.dispatcher_... |
andrewyoung1991/scons | test/Configure/Streamer1.py | Python | mit | 2,529 | 0.001186 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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,
... | This is because
io.StringIO (used by SCons.SConf.Streamer) accepts only unicode strings.
Non-unicode input causes it to raise an exception.
"""
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """
# SConstruct
#
# The CheckHello should return 'yes' if everything works fine. Otherwise it
# retu... | eaks the script
with open(env.subst('$TARGET', target = target),'w') as f:
f.write('yes')
except:
# write to file, as stdout/stderr is broken
traceback.print_exc(file=open('traceback','w'))
return 0
def CheckHello(context):
import sys
context.Display('Checking whether hello works... ')
stat... |
richard-fisher/repository | desktop/gnome/core/gconf/comar/packageHandler.py | Python | gpl-2.0 | 816 | 0.018382 | #!/usr/bin/python
import piksemel
import os
def updateGConf (filepath, remove=False):
parse = piksemel.parse (filepath)
schemaList = list()
for xmlfile in parse.tags ("File"):
path = xmlfile.getTagData ("Path")
# Only interested in /etc/gconf/schemas
if "etc/gconf/schemas" in pat... | ist.append ("/%s" % path)
if len(schemaList) > 0:
os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults'
operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule"
cmd = "/usr/bin/gconftool-2 %s %s" % (operation, | " ".join(schemaList))
os.system (cmd)
def setupPackage (metapath, filepath):
updateGConf (filepath)
def postCleanupPackage (metapath, filepath):
updateGConf (filepath)
|
npuichigo/ttsflow | third_party/tensorflow/tensorflow/python/kernel_tests/softplus_op_test.py | Python | apache-2.0 | 4,807 | 0.006657 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ps, -log_eps - one, -log_eps + one,
-log_eps - ten, -log_eps + ten
],
use_gpu=True)
def testGradient(self):
with self.test_session():
x = constant_op.constant(
[-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],
shape=[2, 5],
| name="x")
y = nn_ops.softplus(x, name="softplus")
x_init = np.asarray(
[[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],
dtype=np.float32,
order="F")
err = gradient_checker.compute_gradient_error(
x, [2, 5], y, [2, 5], x_init_value=x_init)
pr... |
esemin83/python_training | fixture/db.py | Python | apache-2.0 | 1,837 | 0.005444 | import pymysql.cursors
from model.group import Group
from model.group_address import Address_data
import re
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysq... | dress,
home_phone=home, mobile_phone=mobile, work_phone=work, email_1=email,
email_2=email2))
finally | :
cursor.close()
return contact_list
def destroy(self):
self.connection.close()
|
danuzclaudes/robottelo | tests/foreman/performance/test_standard_prep.py | Python | gpl-3.0 | 7,716 | 0 | """Test class for Environment Preparation after a fresh installation"""
from robottelo import ssh
from robottelo.cli.base import CLIReturnCodeError
from robottelo.cli.org import Org
from robottelo.cli.product import Product
from robottelo.cli.repository import Repository
from robottelo.cli.repository_set import Reposit... | name
cls.savepoint = settings.performance.fresh_install_savepoint,
# parameters for uploading manifests
cls.manifest_file = settings.fake_manifest.url
cls.org_id = ''
# parameters for changing cdn address
cls.target_url = setti | ngs.performance.cdn_address
# parameters for enabling repositories
cls.sub_id = ''
cls.sub_name = ''
cls.pid = ''
# [repo-id,$basearch,$releasever]
cls.repository_list = [
[168, 'x86_64', '6Server'],
[2456, 'x86_64', '7Server'],
[1952... |
fsufitch/eve-shipspinning | models/utils.py | Python | mit | 7,220 | 0.010111 | eveapi = local_import('eveapi')
def is_igb():
return 'http_eve_charid' in request.env
def auto_vivify(charid):
if db(db.char.charid==charid).count():
return # character id already exists in db
api = eveapi.EVEAPIConnection()
try:
el = api.eve.CharacterName(ids=str(charid))
... | cter id:', charid)
char = q.select().first()
return char
def get_name_from_id(charid):
return get_char_row_from_id(charid).charna | me
def get_id_from_name(charname):
q = db(db.char.charname==charname)
if not q.count():
return None
charid = q.select()[0].charid
return charid
TYPENAME = 'evedb.typename'
PACKCOUNT = 'prizepack.count'
PACKIMG = 'prizepack.image_url'
PACKDATA_CACHE = {} # md5 : extracted pack
def extract_pack(... |
Freso/listenbrainz-server | listenbrainz/db/user_timeline_event.py | Python | gpl-2.0 | 5,585 | 0.001791 | # listenbrainz-server - Server for the ListenBrainz project.
#
# Copyright (C) 2021 Param Singh <me@param.codes>
#
# 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... |
def get_user_notification_events(user_id: int, count: int = 50) -> List[UserTimelineEvent]:
""" Gets notification posted on the user's timeline.
The optional `count` parameter can be used to control the number of events being returned.
"""
return get_user_timeline_events(
user_ | id=user_id,
event_type=UserTimelineEventType.NOTIFICATION,
count=count
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.