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 |
|---|---|---|---|---|---|---|---|---|
mbareta/edx-platform-ft | openedx/core/djangoapps/user_api/legacy_urls.py | Python | agpl-3.0 | 1,618 | 0.00309 | """
Defines the URL routes for this app.
"""
from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework import routers
from . import views as user_api_views
from .models import UserPreference
USER_API_ROUTER = routers.DefaultRouter()
USER_API_RO | UTER.register(r'users', user_api_views.UserViewSet)
USER_API_ROUTER.register(r'user_prefs', user_api_views.UserPreferenceViewSet)
urlpatterns = patterns(
'',
url(r'^v1/', include(USER_API_ROUTER.urls)),
url(
r'^v1/preferences/(? | P<pref_key>{})/users/$'.format(UserPreference.KEY_REGEX),
user_api_views.PreferenceUsersListView.as_view()
),
url(
r'^v1/forum_roles/(?P<name>[a-zA-Z]+)/users/$',
user_api_views.ForumRoleUsersListView.as_view()
),
url(
r'^v1/preferences/email_opt_in/$',
user_api_... |
ryanorz/code-camp | starscream/starscream/items.py | Python | apache-2.0 | 289 | 0 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/ | latest/topics/items.html
import scrapy
class StarscreamItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
| |
cyncyncyn/evette | lookupmethods.py | Python | gpl-2.0 | 6,071 | 0.049415 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#Copyright (C) 2007 Adam Spencer - Free Veterinary Management Suite
#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 ... |
self.lookup | = lookup
topsizer = wx.BoxSizer(wx.VERTICAL)
self.listbox = wx.ListBox(self)
self.listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.EditLookup)
self.listbox.Bind(wx.EVT_RIGHT_DOWN, self.Popup)
topsizer.Add(self.listbox, 1, wx.EXPAND)
self.SetSizer(topsizer)
self.RefreshLookups()
def Popup(self, I... |
execunix/vinos | xsrc/external/mit/MesaLib/dist/scons/gallium.py | Python | apache-2.0 | 22,345 | 0.005684 | """gallium
Frontend-tool for Gallium3D architecture.
"""
#
# Copyright 2008 VMware, 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 restriction, inclu... | use instead'
print
print ' scons build=release'
print
env['build'] = 'release'
if env['profile']:
print 'scons: warning: profile option is deprecated and will be removed eventually; use instead'
print
print ' scons build=profile... |
print
env['build'] = 'profile'
if False:
# Enforce SConscripts to use the new build variable
env.popitem('debug')
env.popitem('profile')
else:
# Backwar |
catapult-project/catapult | telemetry/telemetry/internal/testing/dependency_test_dir/other_animals/cat/cat/cat_object.py | Python | bsd-3-clause | 255 | 0.007843 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style | license that can be
# found in the LICENSE file.
from __future__ import print_function
class Cat(object):
def Run(self):
print('Meow | ')
|
gdesmott/politube | politube/urls.py | Python | agpl-3.0 | 710 | 0.002817 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import politube.views
urlpatterns = patterns('',
url(r'^$', politube.views.home, name='home'),
url(r'^about/', politube.views.about, name='about'),
... | (r'^plenary/', include('plenary.urls')),
url(r'^deputy/', include('deputy.urls')),
url(r'^videos_tools/', include('videos_tools.urls')),
# Uncomment the admin/doc line below to enable admin documentat | ion:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
|
gis4dis/poster | apps/processing/ala/migrations/0010_update_aggregation_procedures.py | Python | bsd-3-clause | 751 | 0.002663 | # Generated by Django 2.0.3 on 2018-06-27 08:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ala', '0009_samplingfeature_geometry'),
]
operations = [
migrations.RunSQL("UPDATE ala_observation "
"SET | procedure_id = ("
"SELECT id "
"FROM public.common_process "
"WHERE name_id = 'apps.common.aggregate.arithmetic_mean') "
"WHERE procedure_id = ("
"SELECT id "
... | name_id = 'avg_hour')"
)
]
|
karthik-sethuraman/ONFOpenTransport | RI/flask_server/tapi_server/models/tapi_odu_deg_thr.py | Python | apache-2.0 | 3,907 | 0.000512 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_odu_deg_thr_type import TapiOduDegThrType # noqa: F401,E501
from tapi_server.models.tapi_... | self._percentage_granularity = percentage_granularity
@property
def deg_thr_type(self):
"""Gets the deg_thr_type of this TapiOduDegThr.
:return: The deg_thr_type of this TapiOduDegThr.
:rtype: TapiOduDegThrType
"""
return sel | f._deg_thr_type
@deg_thr_type.setter
def deg_thr_type(self, deg_thr_type):
"""Sets the deg_thr_type of this TapiOduDegThr.
:param deg_thr_type: The deg_thr_type of this TapiOduDegThr.
:type deg_thr_type: TapiOduDegThrType
"""
self._deg_thr_type = deg_thr_type
|
vriera/micropython | docs/conf.py | Python | mit | 9,675 | 0.005581 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# MicroPython documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 21 11:42:03 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... | htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%d %b %Y'
# If true, Sma | rtyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pa... |
OpenTechFund/WebApp | opentech/apply/review/admin_helpers.py | Python | gpl-2.0 | 906 | 0.002208 | from wagtail.contrib.modeladmin.helpers import PageButtonHelper
class | ButtonsWithClone(PageButtonHelper):
def clone_button(self, obj, classnames_add, classnames_exclude):
classnames = self.copy_button_classnames + classnames_add
cn = self.finalise_classname(classnames, classnames_exclude)
return {
'url': self.url_helper.get_action_url('clone', ins... | label': 'Clone',
'classname': cn,
'title': 'Clone this %s' % self.verbose_name,
}
def get_buttons_for_obj(self, obj, exclude=list(), classnames_add=list(),
classnames_exclude=list()):
btns = super().get_buttons_for_obj(obj, exclude, classnames_add... |
jwilder/nginx-proxy | test/test_multiple-networks.py | Python | mit | 545 | 0.011009 | import pytest
def test_unknown_virtual_host(docker_compose, nginxproxy):
r = nginxproxy.get("http://nginx-proxy/")
assert r.status_code == 503
def test_forwards_to_web1(docker_compose, nginxpr | oxy):
r = nginxproxy.get("http://web1.nginx-proxy.local/port")
assert r.status_code == 200
assert r.text == "answer from port 81\n"
def test_forwards_to_web2(docker_compose, nginxproxy):
r = nginxpro | xy.get("http://web2.nginx-proxy.local/port")
assert r.status_code == 200
assert r.text == "answer from port 82\n" |
luboslenco/lowpolyfactory | editor.py | Python | gpl-2.0 | 6,413 | 0 | import bpy
from bpy.props import *
from add_mesh_LowPolyFactory.materials import *
from add_mesh_LowPolyFactory.populate import *
def get_prefs(context):
return context.user_preferences.addons[__package__].preferences
class LPF_Panel(bpy.types.Panel):
bl_label = "LowPoly Factory"
bl_space_type = "PROPER... | des['Emission'].inputs[1].default_value = 0.5
world_inp0.default_value = [0.334, 0.274, 0.402, 1]
world_inp1.default_value = 2.0
elif prefs.lp_Light_Type == 'lp_Light_Dawn':
| lamp_nodes['Emission'].inputs[1].default_value = 1.0
world_inp0.default_value = [0.869, 0.570, 0.371, 1]
world_inp1.default_value = 2.0
lamp_object.select = True
c.scene.objects.active = lamp_object
return {'FINISHED'}
class LPF_PopulateButton(bpy.types.Oper... |
TheShellLand/pies | v3/Libraries/sys/Open file.py | Python | mit | 102 | 0.009804 | #!/usr/bin/env python
import sys
with open(sys.argv[1], 'r') | as my_fi | le:
print(my_file.read())
|
kergoth/git-origin | git-python/lib/git/tag.py | Python | mit | 2,251 | 0.002665 | # tag.py
# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
#
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
from commit import Commit
class Tag(object):
def __init__(self, name, commit):
"""
... | s, will be passed
to git-for-each-ref
Returns
``git.Tag[]``
List is sorted by committerdate
"""
options = {'sort': "committerdate",
'format': "%(refname)%00%(objectname)"}
options.update(**kwargs)
output = repo... | ns)
return cls.list_from_string(repo, output)
@classmethod
def list_from_string(cls, repo, text):
"""
Parse out tag information into an array of Tag objects
``repo``
is the Repo
``text``
is the text output from the git-for-each command
... |
markuskont/kirka | examples/ml/main.py | Python | gpl-3.0 | 117 | 0.017094 | #!/usr/b | in/env python
import kNN
group,labels = kNN.createDataSet()
print kNN.classify0([0,0.1], group, label | s, 3)
|
tvtsoft/odoo8 | openerp/service/server.py | Python | agpl-3.0 | 35,763 | 0.002628 | #-----------------------------------------------------------
# Threaded, Gevent and Prefork Servers
#-----------------------------------------------------------
import datetime
import errno
import logging
import os
import os.path
import platform
import random
import select
import signal
import socket
import subprocess
... | hutdown.\n")
os._exit(0)
elif sig == signal.SIGHUP:
| # restart on kill -HUP
openerp.phoenix = True
self.quit_signals_received += 1
def cron_thread(self, number):
while True:
time.sleep(SLEEP_INTERVAL + number) # Steve Reich timing style
registries = openerp.modules.registry.RegistryManager.registries
... |
openai/gym3 | gym3/env.py | Python | mit | 3,105 | 0.003543 | from typing import Any, Dict, List, Sequence, Tuple
from gym3.types import ValType
class Env:
"""
An interface for reinforcement learning environments.
:param ob_space: ValType representing the valid observations generated by the environment
:param ac_space: ValType representing the valid actions th... | ef observe(self) -> Tuple[Any, Any, Any]:
"""
Structured data that's accessible to the agent
Can be called zero or more times per act() call; it is idempotent and does
| not affect the environment. Returns the observation after the last act()
call has affected the environment or the initial state if no act()
call has been made.
The following snippet shows what the start of a rollout looks like, and
the usual convention for indexing the values:
... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractNovelexpressWordpressCom.py | Python | bsd-3-clause | 620 | 0.030645 | def extractNovelexpressWordpressCom(item):
'''
Parser for 'novelexpress.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not | (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('RGG', 'Rebirth Of The General\'s Granddaughter', 'translated'),
('MBH', 'My Beastly Husband', 'translated'),
]
for tagname, name, tl_type | in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
Biles430/FPF_PIV | piv_inner.py | Python | mit | 5,688 | 0.033579 | import pandas as pd
from pandas import DataFrame
import numpy as np
import PIV
import h5py
import matplotlib.pyplot as plt
import hotwire as hw
### PIV INNER PLOTS AND ANALYSIS ########
#########################################
def piv_inner(date, num_tests, utau, legend1):
##########################################... | -xb', '-ob','-sb | ']
legend2 = [r'$Re_\tau=$1450', r'$Re_\tau=$2180', r'$Re_\tau=$2280', r'$Re_\tau=$3270', r'$Re_\tau=$5680', r'$Re_\tau=$6430', r'$Re_\tau=$10770', r'$Re_\tau=$15480', r'$Re_\tau=$15740'] + legend1
marker_V = ['-xr', '-xg', '-xb', '-xm', '-xk', '-xc', '-sr', '-sg', '-sb']
plt.figure()
##Uplus Yplus
#plot vincenti... |
radiac/sermin | examples/webhost/my.example.com.py | Python | bsd-3-clause | 156 | 0 | " | ""
Host definition for my.example.com
"""
from .nginx import NginxSite
from .web import * # NOQA
NginxSite('my.example.com', '/var/www/my | .example.com')
|
sileht/deb-openstack-nova | nova/tests/api/openstack/compute/contrib/test_snapshots.py | Python | apache-2.0 | 10,216 | 0.00137 | # Copyright 2011 Denali Systems, 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 requ... | distributed under the License is distributed on an " | AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
import json
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import volum... |
OpenData-NC/open-data-nc | opendata/settings/local.example.py | Python | mit | 61 | 0.016393 | from opendata.settings.dev impo | rt *
| # Override settings here |
paddycarey/stretch | tests/stretch/test_config.py | Python | mit | 1,338 | 0 | # stdlib imports
import logging
# local imports
from stretch import config
def test_get_local_debug(monkeypatch):
monkeypatch.setenv('LOCAL_DEBUG', 'true')
assert config.get_local_debug()
def test_get_local_debug_not_set():
assert not config.get_local_debug()
def test_get_log_level(monkeypatch):
... | _get_log_level_not_set():
assert config.get_log_level() == logging.INFO
def test_get_log_leve | l_invalid(monkeypatch):
monkeypatch.setenv('LOG_LEVEL', 'log all the things')
assert config.get_log_level() == logging.INFO
def test_get_marathon_url(monkeypatch):
expected = 'http://marathon.example.com'
monkeypatch.setenv('MARATHON_URL', expected)
assert config.get_marathon_url() == expected
d... |
willprice/arduino-sphere-project | scripts/example_direction_finder/temboo/Library/eBay/Trading/GetCategories.py | Python | gpl-2.0 | 5,654 | 0.004952 | # -*- coding: utf-8 -*-
###############################################################################
#
# GetCategories
# Returns the latest category hierarchy for the eBay site.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# yo... | als, must be supplied.
"""
super(GetCategories, self).__init__(temboo_session, '/Library/eBay/Trading/GetCategories')
def new_input_set(self):
return GetCategoriesInputSet()
| def _make_result_set(self, result, path):
return GetCategoriesResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return GetCategoriesChoreographyExecution(session, exec_id, path)
class GetCategoriesInputSet(InputSet):
"""
An InputSet with methods appropriate for... |
pythonfoo/pythonfooLite | Level_03/listen.py | Python | gpl-3.0 | 2,306 | 0.003935 | #!/usr/bin/env python3
# Listentypen:
# 1. Die Liste:
# Eine Liste ist eine beliebig lange Folge von beliebigen Objekten
# Eine Liste wird mit Hilfe von eckigen Klammern definiert.
liste = [0, "foo"] # type: list
print(liste)
# Mit list() lässt sich bspw. ein String in einen Liste verwandeln:
String = "ABCDEFGHIJ... | nt(liste)
# Die pop()-Methode löscht das Objekt an dem Index in der Liste.
# Ist kein Index angegeben lösht pop() das letzte Element
liste.pop()
print(liste)
# alternativ per Index löschen
del liste[1]
# Ein Element kann aber nicht nur über den Index gelöscht werden, sondern
# auch über das Objekt, es wird allerdi | ngs nur das erste Auftreten des
# Objektes gelöscht. Dabei wird ein Fehler geworfen, falls das Objekt
# nicht in der Liste vorhanden ist.
liste.remove('bar') # type: None
print(liste)
# Element über den Wert finden
liste.index('foo')
# Um festzustellen, wie oft ein Wert in einer Liste vorhanden ist kann
# die count... |
xpclove/autofp | diffpy/pyfullprof/baseclass.py | Python | gpl-3.0 | 17,485 | 0.008407 | #!/usr/bin/env python
##############################################################################
#
# diffpy.pyfullprof by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2010 Trustees of the Columbia University
# in the City of New York. All rights reserve... | s address
"""
# In the case a None or an empty string is passed in
if not path:
return self
| # If the name has hierarchy, keep breaking it to the end
if path.count('.') > 0:
try:
objpath,paramname = path.rsplit('.',1)
except ValueError:
raise RietError('Invalid format for a parameter name: ' + path)
# The code below check if the ret... |
pacoqueen/ginn | ginn/formularios/consulta_partidas_por_producto.py | Python | gpl-2.0 | 12,338 | 0.015498 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) 2005-2008 Francisco José Rodríguez Bogado, #
# Diego Muñoz Escalante. #
# (pacoqueen@users.sourceforge.ne... | ublic License as published by #
# the Free Software Foundation; either version | 2 of the License, or #
# (at your option) any later version. #
# #
# GeotexInn is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the im... |
noroutine/ansible | lib/ansible/plugins/action/vyos.py | Python | gpl-3.0 | 3,640 | 0.002473 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is d... | vider(vyos_provider_spec, self._task.args)
pc = copy.deepcopy(self._play_context)
pc.connection = 'network_cli'
pc.network_os = 'vyos'
pc.remote_addr = provider['host'] or self._play_context.remote_addr
pc.port = int(provider['port'] or self._play_context.port... | 2)
pc.remote_user = provider['username'] or self._play_context.connection_user
pc.password = provider['password'] or self._play_context.password
pc.private_key_file = provider['ssh_keyfile'] or self._play_context.private_key_file
pc.timeout = int(provider['timeout'] or C.... |
chrisxue815/leetcode_python | problems/test_0144_recursive.py | Python | unlicense | 835 | 0 | import unittest
from typing import List
import utils
from tree import TreeNode
# O(n) time. O(log(n)) space. Recursive pre-order DFS.
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
resul | t = []
def dfs(curr):
if not curr:
return
resu | lt.append(curr.val)
dfs(curr.left)
dfs(curr.right)
dfs(root)
return result
class Test(unittest.TestCase):
def test(self):
cases = utils.load_test_json(__file__).test_cases
for case in cases:
args = str(case.args)
root = TreeNode.fr... |
citrix-openstack-build/swift | test/unit/common/ring/test_builder.py | Python | apache-2.0 | 41,584 | 0.000144 | # Copyright (c) 2010-2012 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | = rb.get_ring()
self.assert_(isinstance(r, ring.RingData))
r2 = rb.get_ring()
self.assert_(r is r2)
rb.rebalance()
r3 = rb.get_ring()
self.assert_(r3 is not r2)
r4 = rb.get_ring()
self.assert_(r3 is r4)
def test_rebalance_with_seed(self):
devs... | rb = ring.RingBuilder(8, 3, 1)
for idx, (zone, port) in enumerate(devs):
rb.add_dev({'id': idx, 'region': 0, 'zone': zone, 'weight': 1,
'ip': '127.0.0.1', 'port': port, 'device': 'sda1'})
ring_builders.append(rb)
rb0 = ring_builders[0]
... |
hypebeast/docker-alpine-python | examples/simple-mount-app/app.py | Python | mit | 146 | 0.013699 | #!/usr/bin/env python
import click
@click.comm | and()
def | hello():
click.echo('Hello alpine-python!')
if __name__ == '__main__':
hello()
|
romansalin/testrail-reporting | testrail_reporting/auth/views.py | Python | apache-2.0 | 1,344 | 0 | import logging
from flask impor | t abort
from flask import Bluepri | nt
from flask import current_app
from flask import flash
from flask import redirect
from flask import session
from flask import url_for
from testrail_reporting.auth.models import AuthUser
from testrail_reporting.auth.oauth import get_google
log = logging.getLogger(__name__)
auth = Blueprint('auth', __name__)
@auth.... |
reillyeon/webpixels | webpixels/__init__.py | Python | mit | 3,802 | 0.030773 | from abc import ABCMeta, abstractmethod
from math import copysign
import re
MAX_STEP_SIZE = 10
class Channel(object):
def __init__(self, name, controller, value=0):
self.name = name
self.controller = controller
self.value = value
self.target_value = value
def set(self, new_value):
... | t()
self.red = red_chan
self.controllers.add(red_chan.get_controller())
self.green = green_chan
self.controllers.add(green_chan.get_controller())
self.blue = blue_chan
self.controllers.add(blue_chan.get_controller())
def set(self, red, green, blue):
self.red.set(red)
... | green, blue):
self.red.set_target(red)
self.green.set_target(green)
self.blue.set_target(blue)
def step(self):
results = (self.red.step(), self.green.step(), self.blue.step())
return any(results)
def get(self):
return self.red.get(), self.green.get(), self.blue.get()
def ... |
nomuna/codility | Lesson_07/nesting.py | Python | mit | 673 | 0.031204 | #correctness 100%, performance 0%
import re
stack = []
def solution(line):
global stack
if re.findall('\w+', line): return 0
try:
if not line and not stack: return 1
if line[0] == '(': stack.append('(')
elif line[0] == ')': stack.pop()
| print "stack:", stack
line = line[1:]
print "line: %s" % (line,)
return solution(line)
except IndexError as e:
print e
return 0
if __name__ == '__main__':
testdata = [ "", None, "(())" , "(awdasdwa)", "()(()()(((()())(()()))" ]
#testdata = [ "()(()()(( | (()())(()()))" ]
for data in testdata:
print "Input: %s" % data
print "result for %s is %d" % (data, solution(str(data)))
|
purduesigbots/pros-cli | pros/config/cli_config.py | Python | mpl-2.0 | 2,836 | 0.002116 | import json.decoder
import os.path
from datetime import datetime, timedelta
from typing import *
import click
import pros.common
# import pros.conductor.providers.github_releases as githubreleases
from pros.config.config import Config
if TYPE_CHECKING:
from pros.upgrade.manifests.upgrade_manifest_v1 import Upgra... | tch: datetime) -> bool:
return datetime.now() - last_fetch > self.update_frequency
@property
def use_build_compile_commands(self):
if self.overri | de_use_build_compile_commands is not None:
return self.override_use_build_compile_commands
paths = [os.path.join('~', '.pros-atom'), os.path.join('~', '.pros-editor')]
return any([os.path.exists(os.path.expanduser(p)) for p in paths])
def get_upgrade_manifest(self, force: bool = False) ... |
wangyarui/deep-learning | Q-Learning/RLtest.py | Python | unlicense | 4,294 | 0.032371 | import tensorflow as tf
import numpy as np
import gym
import random
from collections import deque
EPISDOE = 10000
STEP = 10000
ENV_NAME = 'MountainCar-v0'
BATCH_SIZE = 32
INIT_EPSILON = 1.0
FINAL_EPSILON = 0.1
REPLAY_SIZE = 50000
TRAIN_START_SIZE = 200
GAMMA = 0.9
def get_weights(shape):
weights = tf.truncated_nor... | self.y_input = tf.placeholder( tf.float32, [None] )
w1 = ge | t_weights( [self.state_dim, self.neuron_num] )
b1 = get_bias([self.neuron_num])
hidden_layer = tf.nn.relu( tf.matmul( self.input_layer, w1 ) + b1 )
w2 = get_weights( [ self.neuron_num, self.action_dim ] )
b2 = get_bias( [ self.action_dim ] )
self.Q_value = tf.matmul( hidden_l... |
xlqian/navitia | source/jormungandr/jormungandr/street_network/tests/here_test.py | Python | agpl-3.0 | 9,105 | 0.001869 | # coding=utf-8
# Copyright (c) 2001-2017, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility an... | n = make_pt_object(type_pb2.ADDRESS, 2.439938, 48.572841)
destination = make_pt_object(type_pb2.ADDRESS, 2.440548, 48.57307)
with requests_mock.Mocker() as req:
req.get(requests_mock.ANY, json=valid_here_matrix, status_code=200)
response = here.get_street_network_ | routing_matrix(
instance,
[origin],
[destination, destination, destination],
mode='walking',
max_duration=42,
request={'datetime': str_to_time_stamp('20170621T174600')},
request_id=None,
)
assert response.rows[0].routing... |
MercenariesEngineering/openexrid | build_tools/installer.py | Python | mit | 2,364 | 0.030034 | import tempfile, shutil, os, re, platform, zipfile
def get_version ():
file = open("openexrid/Version.h", "r")
for line in file:
version = re.search("Version\s*=\s*\"([^\"]+)", line)
if version:
return version.group(1)
def strip (path):
if platform.system() == "Linux":
print ("strip " + path)
os.system ... | shutil.copy (cwd + "/LICENSE", "openexrid/")
for nuke in nuke_versions:
| if os.path.exists(cwd + "/build/release/lib/" + nuke + "/DeepOpenEXRId" + so_ext):
os.mkdir ("openexrid/"+nuke)
shutil.copy (cwd + "/build/release/lib/" + nuke + "/DeepOpenEXRId" + so_ext, "openexrid/"+nuke)
strip ("openexrid/"+nuke + "/DeepOpenEXRId" + so_ext)
shutil.copy (cwd + "/nuke/menu.py", "openexr... |
apdjustino/DRCOG_Urbansim | src/opus_gui/data_manager/run/tools/esri_feature_to_point.py | Python | agpl-3.0 | 1,487 | 0.011432 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
import os, sys
import imp
def opusRun(progressCB,logCB,params):
f, filename, description = imp.find_module('arcgisscripting', ['c:/Python25/Lib/site-p... | 'The input and output parameters will accept paths to shapefiles (c:\\test.shp), ' \
'personal or file geodatabase feature classes (c:\\test.gdb\\test_fc or c:\\test.mdb\\test_fc), ' \
'or SDE feature classes (Database Connections\\Your Database Connection.sde\\your feature class).\n' \
... | \
'output_shapefile: path to the output shapefile or feature class\n' \
'buffer_size: buffer size in the units that the shapefile or feature class is in\n'
return help
|
Aratz/pyurdme | test/test_adfsp.py | Python | gpl-3.0 | 806 | 0.006203 | #!/usr/bin/env python
from pyurdme.adfsp_solver import ADFSPSolver
from examples.cylinder_demo.cylinder_demo3D import cylinderDemo3D
import matplotlib.pyplot as plt
import numpy
import pyurdme
import time
model = cylinderDemo3D()
sol = ADFSPSolver(model, report_level=1, error_tolarance=0.0 | 5)
print "Attempting to compile"
sol.compile()
print "Beginning simulation"
t1 = time.time()
result = sol.run()
print "Simulation complete in {0}s".format(time.time()-t1)
print "Plotting solution"
# Plot of the time-average spatial concentration.
x_vals = model.mesh.coordinates()[:, 0]
A_vals = numpy.mean(result.get_sp... | als,A_vals,'.r',x_vals,B_vals,'.b')
plt.legend(['A', 'B'])
plt.show()
|
hellious/TradeViz | data_pre/collect_2.py | Python | mit | 4,253 | 0.01881 |
import threading
import urllib2
import time, json
import requests
import os.path
#"284330,150810,09,1109,52,071040,17,28432,7406"
countrylist = ["brazil","canada","china","france","japan","india","mexico","russia","uk","us"]
yrs = ["2011","2012","2013","2014","2015"]
dataTable ={"284330":"gold","150810":"crude","09... | ata = {}
for k in range(0,len(countrylist)):
with open(file_list[k],"r") as json_data:
data_json = json.load(json_data)
for j in range(0,len(data_json)):
if data_json[j]['yr'] == 2011:
a = (countrylist[k],"2011")
elif data_json[j]['yr'] == 2012:
... | 12")
elif data_json[j]['yr'] == 2013:
a = (countrylist[k],"2013")
elif data_json[j]['yr'] == 2014:
a = (countrylist[k],"2014")
elif data_json[j]['yr'] == 2015:
a = (countrylist[k],"2015")
# insrt the key
a = "".j... |
jindaxia/xbmc-addons-chinese | service.subtitles.subhd/service.py | Python | gpl-2.0 | 9,754 | 0.016343 | # -*- coding: utf-8 -*-
import re
import os
import sys
import xbmc
import urllib
import urllib2
import xbmcvfs
import xbmcaddon
import xbmcgui,xbmcplugin
from bs4 import BeautifulSoup
__addon__ = xbmcaddon.Addon()
__author__ = __addon__.getAddonInfo('author')
__scriptid__ = __addon__.getAddonInfo('id')
__scrip... | se:
req = urllib2.Request(url)
req.add_header('User-Agent', UserAgent)
try:
response = urllib2.urlopen(req)
httpdata = r | esponse.read()
response.close()
except:
log(__name__, "%s (%d) [%s]" % (
sys.exc_info()[2].tb_frame.f_code.co_name,
sys.exc_info()[2].tb_lineno,
sys.exc_info()[1]
))
return ''
return httpdata
def Search( item ):
subtitles_l... |
terhorst/psmcpp | util/smc2psmc.py | Python | gpl-3.0 | 1,221 | 0.000819 | #!/usr/bin/env python3
import numpy as np
import argparse
from smcpp.estimation_tools import load_data
if __name__ == "__main__":
parser = argparse.ArgumentPars | er(
description='Convert SMC++-formatted data set into PSMCfa-style data.')
parser.add_argument("--contig", help="name of outputted contig")
parser.add_argument("input", metavar="file.smc[.gz]")
args = parser.parse_args()
args.contig = args.contig or args.input
contig = load | _data([args.input])[0]
L = contig.data[:, 0].sum()
L += 100 - (L % 100)
fa = np.full(L, -1)
last = 0
for span, a, b, nb in contig.data:
fa[last:last + span] = a
last += span
fa.shape = (L // 100, -1)
code = fa.max(axis=1).astype('|S1')
code[code == b'0'] = b'T'
code[c... |
diefenbach/django-lfs | lfs/manage/product/variants.py | Python | bsd-3-clause | 31,374 | 0.002359 | import json
from copy import deepcopy
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import EmptyPage
from django.db import IntegrityError
from django.fo... | choices.append(cv)
for variant in Product.objects.filter(parent=product | ):
choices.append([variant.id, "%s (%s)" % (variant.get_name(), variant.variant_position)])
self.fields["category_variant"].widget = Select(choices=choices)
class Meta:
model = Product
fields = ("category_variant", )
class DisplayTypeForm(ModelForm):
"""Form to add/edit p... |
Semprini/cbe-retail | retail/customer_bill/apps.py | Python | apache-2.0 | 1,070 | 0.01215 | from django.apps import AppConfig
from django.db.models.signals import post_save, post_delete
from django.conf import settings
| class CustomerBillConfig(AppConfig):
name = 'retail.customer_bill'
def __init__(self, app_name, app_m | odule):
super(self.__class__, self).__init__(app_name, app_module)
def ready(self):
import drf_nest.signals
from retail.customer_bill.models import CustomerBill
from retail.customer_bill.serializers import CustomerBillSerializer
exchange_prefix = settings.MQ_FRAMEWORK['... |
bikash/kaggleCompetition | microsoft malware/Malware_Say_No_To_Overfitting/kaggle_Microsoft_malware_small/gen_code_img.py | Python | apache-2.0 | 592 | 0.030405 | import subprocess
asm_code_path='asm_code_'
data_path='.'
cmd='mkdir '+' '.join([asm_code_path+'train',asm_code_path+'test'])
subprocess.call(cmd,shell=True)
cmd='pypy writeasm.py xid_train.p '+' '.join([data_path+'/train',asm_code_path+'train'])
subprocess.call(cmd,shell=True)
cmd='pypy writeasm.py xid_test.p '+' '.... | =True)
cmd='python rebuild_code.py xid_train.p '+asm_code_path+'train'
subprocess.call(cmd,shell=True)
cmd='python rebuild_co | de.py xid_test.p '+asm_code_path+'test'
subprocess.call(cmd,shell=True)
|
NetApp/manila | manila/share/drivers/windows/windows_smb_helper.py | Python | apache-2.0 | 11,283 | 0.000089 | # Copyright (c) 2015 Cloudbase Solutions SRL
# 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
#
# Unle... | fo(_LI("Granted %(access_level)s access to '%(access_to)s' "
"on share %(share_name)s"),
{'access_level': access_level,
'access_to': access_to,
| 'share_name': share_name})
def _refresh_acl(self, server, share_name):
cmd = ['Set-SmbPathAcl', '-ShareName', share_name]
self._remote_exec(server, cmd)
def _revoke_share_access(self, server, share_name, access_to):
cmd = ['Revoke-SmbShareAccess', '-Name', share_name,
... |
fabthefabulousfab/script_plantuml | extract_tshark.py | Python | apache-2.0 | 1,810 | 0.028177 | ##################################################
#
# IMpot
#
#################################################
import subprocess
import shlex
import packet
##################################################
#
# Constants
#
#################################################
# Genrals imports
HEADER = "tshark -r"
PR... | -e ip.dst """ #4
FILTRE = FILTRE + """ -e sip.Method """ #5
FILTRE = FILTRE + """ -e sip.Status-Code""" #6
FILTRE = FILTRE + """ -e msrp.method """ #7
FILTRE = FILTRE + """ -e msrp.data """ #8
FILTRE = FILTRE + """ -e msrp.status.code""" #9
FILTRE = F | ILTRE + """ -e diameter.cmd.code """ #10
array_color_http=['blue','orange']
array_color_msrp=['blue','orange']
array_color_diameter=['blue','orange']
array_color_sip=['blue','orange']
all_packets = []
##################################################
#
# Functions
#
##############################################... |
maxiee/LearnPythonTheHardWayExercises | ex20.py | Python | gpl-2.0 | 601 | 0.008319 | from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(li | ne_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
curr... | 1
print_a_line(current_line, current_file)
|
twolfson/suplemon | suplemon/linelight/json.py | Python | mit | 442 | 0 | from suplemo | n import helpers
from suplemon.linelight.color_map import color_map
class Syntax:
def get_comment(self, line):
return ("", "")
def get_color(self, raw_line):
color = color_map["white"]
line = raw_line.strip()
if helpers.starts(line, ["{", "}"]):
color = color_map["... | en"]
return color
|
otron/zenodo | zenodo/base/format_elements/bfe_openaire_license.py | Python | gpl-3.0 | 1,437 | 0.010438 | # -*- coding: utf-8 -*-
#
## This file is part of Zenodo.
## Copyright (C) 2012, 2013 CERN.
##
## Zenodo 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... | d have received a copy of the GNU General Public License
## along with Zenodo. If not, see <http://www.gnu.org/licenses/>.
##
## In applying this licence, CERN does not waive the privileges and immunities
## granted to it by virtue of its status as an Intergovernmental Organization
## or submit itself to any jurisdicti... | )
license_url = bfo.field('540__u')
access_right = bfo.field('542__l')
if access_right in ["open", "embargoed"]:
if license_url:
return """<a href="%s">%s</a>""" % (license_url, license)
else:
return license
return ""
def escape_values(bfo):
"""
Called ... |
tcalmant/ipopo | pelix/remote/xml_rpc.py | Python | apache-2.0 | 8,341 | 0 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Pelix remote services: XML-RPC implementation
Based on standard package xmlrpclib
:author: Thomas Calmant
:copyright: Copyright 2020, Thomas Calmant
:license: Apache License 2.0
:version: 1.0.1
..
Copyright 2020 Thomas Calmant
Licensed under the Apa... | # pylint: disable=R0903
"""
Service call proxy
"""
def __init__(self, name, url):
"""
Sets up the call proxy
:param name: End point name
:param url: End point URL
| """
self.__name = name
self.__url = url
def __getattr__(self, name):
"""
Prefixes the requested attribute name by the endpoint name
"""
# Make a proxy for this call
# This is an ugly trick to handle multithreaded calls, as the
# underlying proxy re-... |
inventree/InvenTree | InvenTree/label/models.py | Python | mit | 10,528 | 0.00038 | """
Label printing models
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import os
import logging
import datetime
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.core.validators import FileExtensionValidator, MinValueValidator
... | import Template, Context
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from InvenTree.helpers import validateFilterString, normalize
import common.models
import stock.models
import part.models
try:
from django_weasyprint import WeasyTemplateResponse... | alled.")
sys.exit(1)
logger = logging.getLogger("inventree")
def rename_label(instance, filename):
""" Place the label file into the correct subdirectory """
filename = os.path.basename(filename)
return os.path.join('label', 'template', instance.SUBDIR, filename)
def validate_stock_item_filters(... |
imarin/Odoo-Mexico-localization | l10n_mx_invoice_currency_chgdft/__init__.py | Python | agpl-3.0 | 1,332 | 0 | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Vauxoo - http://www.vauxoo.com
# All Rights Reserved.
# info@vauxoo.com
###################################################... |
# Coded by: isaac (isaac@vauxoo.com)
# Coded by: rodo (rodo@vauxoo.com)
############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by th... | version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GN... |
chaosking121/best-of-nosleep | script.py | Python | mit | 1,416 | 0.011299 | def get_data():
import pickle
with open('data.p', 'rb') as f:
return pickle.load(f)
if __name__ == '__main__':
import praw
import os, os.path
from datetime import datetime, timedelta
# Change the working directory to the script directory
os.chdir(os.path.dirname(os.pat... | posts.insert(0,
dict(
title = '[{}, +{}] "{}" by /u/{}'.format(
post_date,
submission.score,
submission.title,
submission.author)[ | 0:300],
url = submission.url.replace('www', 'np', 1),
send_replies = False))
for post in posts:
bons.submit(**post) |
thelabnyc/django-oscar-api-checkout | src/oscarapicheckout/__init__.py | Python | isc | 52 | 0 | default_app_config = "o | scarapicheckout.apps | .Config"
|
nerith/scribe | scribe/parser.py | Python | mit | 4,538 | 0.006611 | import re
class Parser:
''' The Parser class represents a parser that parses text using specified
markup. Once the parser parses the text, HTML is generated as output.
'''
def __init__(self):
self.written_text = ''
self.remaining_text = ''
self.markup = { 'h1': '^[#]{1}(\s*)',
... | n_text = text[:start] + inner_text
| else:
self.written_text = inner_text
self.remaining_text = text[match.end(len(match.groups())):]
elif key == 'li':
if not self.lists:
self.lists = True
some_text = "<ul>"
... |
sneron7/DupliCut | deleted_file_recovery.py | Python | apache-2.0 | 890 | 0.004494 | import exception_utils
import os
| import shutil
deleted_file_path = '/home/ron/Desktop/duplicut_tester/1/11/11.txt.duplicutted' # the XXX.duplicutted file
if __name__ == '__main__':
try:
deleted_file_path_splitted = deleted_file_path.split('/')[0:-1]
file_name = deleted_file_path.split('/')[-1]
file_name = file_name.repla... | ne = False
with open(deleted_file_path, "r") as fh:
for line in fh: # it supposed to be only one line
recovery_file_path = line
shutil.copy(r'' + recovery_file_path, dest_path + file_name)
is_done = True
if is_done:
os.remove(r'' ... |
onaio/rapidpro | temba/public/migrations/0004_auto_20170228_0837.py | Python | agpl-3.0 | 1,341 | 0.002983 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-28 08:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('public', '0003_reset_1'),
]
operations = [
mig... | migrations.AlterField(
model_name='lead',
name='modified_on',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=Fal | se, help_text='When this item was last modified'),
),
migrations.AlterField(
model_name='video',
name='created_on',
field=models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False, help_text='When this item was originally created'),
),... |
FireBladeNooT/Medusa_1_6 | medusa/history.py | Python | gpl-3.0 | 4,645 | 0.001292 | # coding=utf-8
# Author: Nic Wolfe <nic@wolfeden.ca>
#
# This file is part of Medusa.
#
# Medusa 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 late... | :param searchResult: search result object
"""
for curEpObj in searchResult.episodes:
showid = int(curEpObj.show.indexerid)
season = int(curEpObj.season)
episode = int(curEpObj.e | pisode)
quality = searchResult.quality
version = searchResult.version
proper_tags = '|'.join(searchResult.proper_tags)
manually_searched = searchResult.manually_searched
providerClass = searchResult.provider
if providerClass is not None:
provider = providerCl... |
splatspace/esprelay | esprelay.py | Python | apache-2.0 | 4,441 | 0 | #!/usr/bin/env python
#
# Simple TCP line-based text chat server. Clients connect and send a
# conversation ID (any string) as the first line, then they are connected
# to other clients who sent the same conversation ID.
#
# Uses a thread pair per connection, so not highly scalable.
from Queue import Queue, Empty
fro... | th conversations_lock:
for handler in conversations[self._conversation_id]:
if handler is not self:
handler._messages.put(line)
def _write_handler(self):
while not self.rfile.closed and not self.wfile.closed:
try:
# Get | the next message we should write from the queue.
# A short timeout lets us detect a closed socket (otherwise
# the thread would only discover it on the next attempt
# to write a message).
message = self._messages.get(block=True, timeout=1)
... |
kantel/python-schulung | sources/hallowelt/hallomatplotlib01.py | Python | mit | 117 | 0.008547 | i | mport numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show | () |
anryko/ansible | contrib/inventory/rax.py | Python | gpl-3.0 | 16,904 | 0.000237 | #!/usr/bin/env python
# (c) 2013, Jesse Keating <jesse.keating@rackspace.com,
# Paul Durivage <paul.durivage@rackspace.com>,
# Matt Martz <matt@sivel.net>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | ent variable to narrow inventory search
scope. If used, needs a value like ORD, DFW, SY | D (a Rackspace
datacenter) and optionally accepts a comma-separated list.
environment:
Environment Variable: RAX_ENV
A configuration that will use an environment as configured in
~/.pyrax.cfg, see
https://github.com/rackspace/pyrax/blob/master/docs/getting_started.md
m... |
specdb/specdb | setup.py | Python | gpl-3.0 | 2,862 | 0.00594 | #!/usr/bin/env python
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function
#
# Standard imports
#
import glob, os
from distutils.extension import Extension
#
# setuptools' sdist command ignores MANIFEST.in
#
#from distutils.command.sdist import... | ilsSdist}
#etup_keywords['test_suite']='{name}.tests.{name}_test_suite.{name}_test_suite'.format(**setup_keywords)
setup_keywords['setup_requires']=['pytest-runner']
setup_keywords['tests_require']=['pytest']
# Autogenerate command-line scripts.
#
# setup_keywords['entry_points'] = {'console_scripts':['desiInstall = d... | gh the data directory, adding all files
data_generator = os.walk('specdb/data')
for path, directories, files in data_generator:
for f in files:
data_path = '/'.join(path.split('/')[1:])
data_files.append(data_path + '/' + f)
setup_keywords['package_data'] = {'specdb': data_files,
... |
aruizramon/alec_erpnext | erpnext/stock/doctype/quote_item/quote_item.py | Python | agpl-3.0 | 271 | 0.01107 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contribut | ors | and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class QuoteItem(Document):
pass
|
rcarmo/yaki-gae | appengine_config.py | Python | mit | 283 | 0.031802 | import os, sys
sys.path.insert(0,os.path.join(os.path.dirname(os.path.abspath(__file__) | ),'lib'))
appstats_CALC_RPC_COSTS = True
def webapp_add_wsgi_middleware(app): |
from google.appengine.ext.appstats import recording
#app = recording.appstats_wsgi_middleware(app)
return app
|
apdjustino/DRCOG_Urbansim | src/opus_core/tests/utils/variable_tester.py | Python | agpl-3.0 | 9,384 | 0.006181 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from numpy import ma, alltrue, allclose
import os.path
from opus_core.datasets.dataset_pool import DatasetPool
from opus_core.storage_fa | ctory import StorageFactory
from opus_core.datasets.dataset_factory import DatasetFactory
from opus_core.datasets.dataset import Dataset
from opus_core.misc import opus_path_for_variable_from_module_path
from opus_core.variables.variable_family_name_translator import VariableFamilyNameTranslator
class VariableTester(... | ests of Opus variables."""
def __init__(self, file_path, package_order, test_data):
"""
file_path is the directory path to the module defining the variable
to be tested. The name of the variable to be tested is extracted
from this path. As a special case, if the file_path ... |
lmazuel/azure-sdk-for-python | azure-mgmt-datafactory/azure/mgmt/datafactory/models/operation_metric_availability.py | Python | mit | 1,181 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | r storage account, per
hour.
:type blob_duration: str
"""
_attribute_map = {
'time_grain': {'key': 'timeGrain', 'type': 'str'},
'blob_duration': {'key': 'blobDuration', 'type': 'str'},
}
def __init__(self, time_grain=None, blob_duration=None):
s | uper(OperationMetricAvailability, self).__init__()
self.time_grain = time_grain
self.blob_duration = blob_duration
|
detlefm/cmd_colors_convert | converters/minrc2reg.py | Python | unlicense | 2,961 | 0.023978 |
# coding: utf-8
import sys
import os
prgname = 'minrc2reg'
colornames ={
"Black": "ColorTable08",
"BoldBlack": "ColorTable00",
"Red": "ColorTable12",
"BoldRed": "ColorTable04",
"Green": "ColorTable10",
"BoldGreen": "ColorTable02",
"Yellow": "ColorTable15",
"BoldYellow": "ColorTable06",
"Blue": "ColorTable09",
"Bo... | 'w') as outfile:
print('Windows Registry Editor Version 5.00',file =outfile);
print('; generated from '+ prgname,file = outfile)
for l in license:
print('; '+l,file=outfile)
with open(fromfile) as f:
for line in f:
regline = convert_line(li... |
def file_filter(pathname):
specialnames = ['LICENSE','downloadfrom.txt']
if os.path.isfile(pathname) and os.path.getsize(pathname)<1000:
head, tail = os.path.split(pathname)
if tail in specialnames or tail.lower().endswith('.reg'):
return False
return True
retu... |
SpoonBoy/python-aws-foundation | test/test_four.py | Python | mit | 1,580 | 0.007595 | #!/usr/bin/env python2
# -*- coding : utf8 -*-
import unittest
import re
from section.four import *
class TestSectionFour(unittest.TestCase):
def setUp(self):
"""this is run before each test, we need to create a SectionFour object"""
self.testee=SectionFour()
def test_init(self):
se... | "testing that the function list_all_sg returns the right format 1/3"""
#[{u'GroupName': 'toto42', u'GroupId': 'sg-xxxxx'}]
for sgname, sgid in self.testee.list_all_sg():
self.assertTrue('GroupName' in sgname)
def test_sg_groupid_present(self):
"""testing that the function list | _all_sg returns the right format 2/3"""
for sgname, sgid in self.testee.list_all_sg():
self.assertTrue('GroupId' in sgid)
def test_sg_id_format(self):
"""testing that the function list_all_sg returns the right format 3/3"""
if self.testee.list_all_sg():
# matching sg... |
Spacecraft-Code/SPELL | src/spell/spell/lang/helpers/tchelper.py | Python | lgpl-3.0 | 37,359 | 0.013544 | ############ | ####################################################################
"""
DESCRIPTION: Helpers for telecommand wrapper functions.
PACKAGE: spell.lang.helpers.tchelper
PROJECT: SPELL
Copyright (C) 2008, 2015 SES ENGINEERING, Luxembourg S.a.r.l.
This file is part of SPELL.
This library is free software: you c... | tion, either
version 3 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more deta... |
dmonroy/emergency | emergency/web.py | Python | mit | 917 | 0 | import os
import asyncio
import aiopg
from chilero import | web
from emergency import ui, api
from emergency.db import parse_pgurl
from emergency. | settings import get_settings
settings = get_settings()
def get_routes():
return [
[os.path.join('/api', item[0]), item[1]] for item in api.routes
] + [
[os.path.join('/ui', item[0]), item[1]] for item in ui.routes
]
class Application(web.Application):
@asyncio.coroutine
def get... |
drvink/pyc-fmtstr-parser | pyc_fmtstr_parser/printf_parse.py | Python | lgpl-2.1 | 13,012 | 0.001844 | # ported from gnulib rev be7d73709d2b3bceb987f1be00a049bb7021bf87
#
# Copyright (C) 2014, Mark Laws.
# Copyright (C) 1999, 2002-2003, 2005-2007, 2009-2014 Free Software
# Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Lice... | gs):
# If 'long long' exists and is larger than 'long':
if flags >= 16 or flags & 4:
return c, Arg_type.TYPE_LONGLONGINT
else:
# If 'long long' exists and is the same as 'long', we parse "lld" into
# TYPE_LONGINT.
if flags >= 8:
type = Arg_type.TYPE_LONGINT
... | type = Arg_type.TYPE_SCHAR
elif flags & 1:
type = Arg_type.TYPE_SHORT
else:
type = Arg_type.TYPE_INT
return c, type
def conv_unsigned(c, flags):
# If 'long long' exists and is larger than 'long':
if flags >= 16 or flags & 4:
return c, Arg_type.TY... |
WellerQu/LearnPython | lesson6/main.py | Python | mit | 344 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from web import a
import sys
a.sayHello()
print 'main', __name__
print sys.argv
print '--------'
# print a.__builtins__
print '__doc__: | %s' % a.__doc__
print '__file__:%s' % a.__file__
print '__name__:%s' % a.__name__
p | rint '__package__:%s' % a.__package__
print '__author__:%s' % a.__author__
|
akretion/roulier | roulier/carriers/geodis/__init__.py | Python | agpl-3.0 | 463 | 0 | from . import geodis
from . import geodis_common_ws
from . import geodis_api_ws
from . import geodis_api_find_localite_ws
from . import geodis_api_edi
from . import geodis_api_rest_ws
from . import geodis_encoder_ws
from . import geodis_encoder_edi
from . import geodis_encoder_rest_ws
from . import geodis_decoder_ws
fr... | . import geodis_transport_ws
from . import geodis_transport_edi
from . import geodis_transport_rest_w | s
|
rednerrus/fiveLessons | manage.py | Python | mit | 254 | 0 | #!/usr/bin/env p | ython
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fiveLessons.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| |
MichaelKohler/bedrock | tests/functional/firefox/new/test_download.py | Python | mpl-2.0 | 1,331 | 0.003005 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.new.download import DownloadPage
@pytest.mark.smoke
@pytest.mark.sanity
@pytest.mark... | yed
# Firefox and Internet Explorer don't cope | well with file prompts whilst using Selenium.
@pytest.mark.skip_if_firefox(reason='http://saucelabs.com/jobs/5a8a62a7620f489d92d6193fa67cf66b')
@pytest.mark.skip_if_internet_explorer(reason='https://github.com/SeleniumHQ/selenium/issues/448')
@pytest.mark.nondestructive
def test_click_download_button(base_url, seleniu... |
Phyks/Flatisfy | flatisfy/data.py | Python | mit | 3,457 | 0.001157 | # coding: utf-8
"""
This module contains all the code related to building necessary data files from
the source opendata files.
"""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import flatisfy.exceptions
from flatisfy import database
from flatisfy import data_files
from flat... | .
:param config: A config dictionary.
:returns: A list of loaded SQLAlchemy objects from the db
"""
get_session = database.init_db(config["database"], config["search_index"])
results = []
with get_session() as session:
areas = []
# Get areas to fetch from, using postal codes
... | les.french_postal_codes_to_quarter(postal_code))
# Load data for each area
areas = list(set(areas))
for area in areas:
results.extend(session.query(model).filter(model.area == area).all())
# Expunge loaded data from the session to be able to use them
# afterwards
... |
openstack/storlets | storlets/agent/daemon/files.py | Python | apache-2.0 | 6,334 | 0 | # Copyright (c) 2015-2016 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | file.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def _emit_log(self, level, msg):
msg = '%s %s: %s' % (self.storlet_name, level, msg)
self.log_file.write(msg.en | code('utf-8'))
def debug(self, msg):
self._emit_log('DEBUG', msg)
def info(self, msg):
self._emit_log('INFO', msg)
def warn(self, msg):
self._emit_log('WARN', msg)
warning = warn
def error(self, msg):
self._emit_log('ERROR', msg)
def exception(self, msg):
... |
dhaitz/CalibFW | cfg/artus/mc_noc.py | Python | gpl-2.0 | 508 | 0.007874 | import ArtusConfig | Base as base
import mc
def config():
conf = mc.config()
l = []
for pipeline in conf['Pipelines']:
if not pipeline.startswith('all'):
l.append(pipeline)
elif 'CHS' not in pipeline:
l.append(pipeline)
for pipeline in l:
del conf['Pipelines'][pipeline]
... | ]
return conf
|
deepmind/bsuite | bsuite/experiments/discounting_chain/analysis.py | Python | apache-2.0 | 4,042 | 0.009401 | # python3
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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... | ize=1.75)
return p
def plot_seeds(df_in: pd.DataFrame,
sweep_vars: Optional[Sequence[str]] = None) -> gg.ggplot:
"""Plot the returns through time individually by run."""
df = dc_preprocess(df_in)
df['average_return'] = 1.1 - (df.total_regret.diff() / df.episode.diff())
p = plotting.plot_indiv... | _in=df,
max_episode=NUM_EPISODES,
return_column='average_return',
colour_var='optimal_horizon',
yintercept=1.1,
sweep_vars=sweep_vars,
)
return p + gg.ylab('average episodic return')
|
ahmadshahwan/cohorte-herald | python/run_xmpp.py | Python | apache-2.0 | 5,512 | 0.000363 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Runs an Herald XMPP framework
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.4
:status: Alpha
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
... | nts
parser = argparse.ArgumentParser(description="Pelix Herald demo")
# XMPP server
group = parser.add_argument_group("XMPP Configuration",
"Configuration of the XMPP transport")
| group.add_argument("-s", "--server", action="store", default="localhost",
dest="xmpp_server", help="Host of the XMPP server")
group.add_argument("-p", "--port", action="store", type=int, default=5222,
dest="xmpp_port", help="Port of the XMPP server")
# XMPP logi... |
UniMOOC/AAClassroom | modules/um_assessments/exceptions.py | Python | apache-2.0 | 816 | 0 | # Copyright 2015 UniMOOC. 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,
# WITHOUT WARRANTIES OR | CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class NoAttemptsLeft(Exception):
pass
class NoDatesAvailable(Exception):
pass
class InvalidStudent(Exception):
pass
class InvalidAssessment(Excep... |
RRCKI/panda-jedi | pandajedi/jediddm/GenDDMClient.py | Python | apache-2.0 | 411 | 0.007299 | from pandajedi.jedicore.MsgWrapper import MsgWrapper
from DDMClientBase import DDMClientBase
# logger
from pandacommon.pandalogger.PandaLogger import PandaLogger
logger = PandaLogger().getLogger(__name__.split('.')[-1])
# class to access to general DDM
class Ge | nDDMClient(DDMClientBase):
# constructor
def __init__(self,con):
# initialize base class
DDMClientBase.__init | __(self,con)
|
rmcgibbo/msmbuilder | msmbuilder/featurizer/__init__.py | Python | lgpl-2.1 | 139 | 0 | from __future__ import absolut | e_import
from .featurizer import *
from .subset_featurizer import *
from .feature_union import Featu | reUnion
|
egbertbouman/tribler-g | Tribler/Core/DecentralizedTracking/pymdht/core/test_const.py | Python | lgpl-2.1 | 3,096 | 0.006137 | # Copyright (C) 2009-2010 Raul Jimenez
# Released under GNU LGPL 2.1
# See LICENSE.txt for more information
#from nose.tools import eq_, ok_
'''
import logging, logging_conf
logs_path = 'test_logs'
logs_level = logging.DEBUG
logging_conf.setup(logs_path, logs_level)
'''
import identifier
from identifier import Id, | ID_SIZE_BITS, BITS_PER_BYTE
import node
TASK | _INTERVAL = .01
TIMEOUT_DELAY = .4
CLIENT_ID = identifier.Id('\x41' * identifier.ID_SIZE_BYTES)
CLIENT_ADDR = ('127.0.0.1', 6000)
CLIENT_NODE = node.Node(CLIENT_ADDR, CLIENT_ID)
BT_PORT = 7777
SERVER_ID = identifier.Id('\x01' * identifier.ID_SIZE_BYTES)
SERVER_ADDR = ('127.0.0.1', 6001)
SERVER_NODE = node.Node(SERVER... |
aaren/pywt | pywt/_wavelet_packets.py | Python | mit | 24,077 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2012 Filip Wasilewski <http://en.ig.ma/>
# See COPYING for license details.
"""1D and 2D Wavelet packet transform module."""
from __future__ import division, print_function, absolute_import
__all__ = ["BaseNode", "Node", "WaveletPacket", "Node2D", "WaveletPacket2D"]
imp... | self._maxlevel = self._evaluate_maxlevel(evaluate_from='subnodes')
return self._maxlevel
@property
def node_name(self):
return self.path[-self.PART_LEN:]
def decompose(self):
"""
Decompose node data creating DWT coefficients subnodes.
Performs Discrete W... | `~BaseNode.data` and
returns transform coefficients.
Note
----
Descends to subnodes and recursively
calls `~BaseNode.reconstruct` on them.
"""
if self.level < self.maxlevel:
return self._decompose()
else:
raise ValueError("Maximu... |
gabrielgaliaso/pyitaushopline | itaushopline/itaushopline.py | Python | mit | 6,081 | 0.012032 | # coding: utf-8
import requests
from random import randint
class ItauShopline(object):
urls = {}
KEYS_MAP = {
'pedido': 8,
'valor': 10,
'observacao': 40,
'nome': 30,
'codigo_inscricao': 2,
'numero_inscricao': 14,
'endereco': 40,
'bairro': 15,
... | chave):
self.indices = []
self.asc_codes = []
self.inicializa(chave)
l = 0
data_chave = []
for j in range(1, len(token)+1):
k = j % 256
l = (l + self.indices[k]) % 256
i = self.indices[k]
self.indices[k] = ... | en[(j-1):j]) ^ int(self.indices[(self.indices[k] + self.indices[l]) % 256]))
data_chave.append(chr(caracter))
return ''.join(data_chave)
@classmethod
def inicializa(self, chave):
for j in range(0, 256):
self.indices.append('')
self.asc_codes.append('')
... |
drgarcia1986/simple-settings | simple_settings/dynamic_settings/s3_reader.py | Python | mit | 1,740 | 0 | from .base import BaseReader
try:
from boto3 import resource
from botocore.exceptions import ClientError
except ImportError: # pragma: no cover
raise ImportError(
'To use "s3" dynamic settings reader\n'
'you need to install simple-settings with s3 dependency:\n'
'pip install simple... | self.s3.Object(
self.conf['bucket_name'],
key
| ).get()
except ClientError:
return None
return response['Body'].read().decode()
def _set(self, key, value):
bytes_value = bytes(value, 'utf-8')
self.s3.Object(
bucket_name=self.conf['bucket_name'],
key=key
).put(
Body=bytes... |
TouK/vumi | vumi/transports/netcore/tests/test_netcore.py | Python | bsd-3-clause | 4,145 | 0 | from urllib import urlencode
from twisted.internet.defer import inlineCallbacks
from twisted.web import http
from vumi.tests.helpers import VumiTestCase
from vumi.transports.netcore import NetcoreTransport
from vumi.transports.tests.helpers import TransportHelper
from vumi.utils import http_request_full
def request... | h_path
resp | = yield request(transport, 'GET', path=health_path)
self.assertEqual(resp.delivered_body, 'OK')
self.assertEqual(resp.code, http.OK)
|
BenaroyaResearch/bripipetools | bripipetools/postprocessing/stitching.py | Python | mit | 10,439 | 0.001341 | """
Combine parsed data from a set of batch processing output files and write to a
single CSV file.
"""
import logging
import os
import re
import csv
import pandas as pd
from .. import io
from .. import parsing
from .. import util
logger = logging.getLogger(__name__)
class OutputStitcher(object):
"""
Given... | + float(metrics['read_pairs_examined']))
/ float(metrics['fastq_total_reads']))
data[idx + 1].append(mapped_reads)
data[0].append('mapped_reads_w_dups')
except KeyError:
logger.warning("required fields missing; ... | ups")
return data
def _build_combined_filename(self):
"""
Parse input path to create filename for combined CSV file.
"""
path_parts = re.sub('.*Illumina/|.*ICAC/', '', self.path).split('/')
logger.debug("building combined filename from path parts {}"
... |
BT-fgarbely/website | website_blog_facebook_comment/__openerp__.py | Python | agpl-3.0 | 1,587 | 0 | # -*- coding: utf-8 -*-
# Python source code encoding : https://www.python.org/dev/peps/pep-0263/
##############################################################################
#
# Copyright (c) 2015 Antiun Ingeniería S.L. (http://www.antiun.com)
# Endika Iglesias <endikaig@antiun.com>
#
# T... | shed
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE | SS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################... |
poppogbr/genropy | packages/test15/webpages/components/thermo.py | Python | lgpl-2.1 | 6,614 | 0.003629 | # -*- coding: UTF-8 -*-
# thermo.py
# Created by Francesco Porcari on 2010-09-03.
# Copyright (c) 2010 Softwell. All rights reserved.
#
#
import os
from gnr.core.gnrbag import Bag
import random
import time
cli_max = 12
invoice_max = 20
row_max = 100
sleep_time = 0.05
class GnrCustomWebPage(object):
dojo_versio... | voices):
rows = int(random.random() * row_max)
for row in self.row_provider(rows):
time.sl | eep(sleep_time)
except self.btc.exception_stopped:
self.btc.batch_aborted()
except Exception, e:
self.btc.batch_error(error=str(e))
self.btc.batch_complete(result='Execution completed', result_attr=dict(url='http://www.apple.com'))
def client_provider(self, clients):... |
swiftstack/container-crawler | test/unit/__init__.py | Python | apache-2.0 | 85 | 0 | # Copyright (c) 2016-2021, NVIDIA CORPORATION.
# SPDX-License-Identifier: Apach | e-2.0
| |
levilucio/SyVOLT | ExFamToPerson/contracts/unit/HUnitDaughter2Woman_ConnectedLHS.py | Python | mit | 2,107 | 0.03085 | from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitDaughter2Woman_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_... | class Child(Child) node
self.add_node()
self.vs[1]["MT_pre__attr1"] = """return True"""
self.vs[1]["MT_label__"] = """2"""
self.vs[1]["mm__"] = """MT_pre__Child"""
self.vs[1]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child')
# match association null--daughters-->nullnode
self.add_node()
self.vs[2]["M... | uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child')
# Add the edges
self.add_edges([
(0,2), # match class null(Fam) -> association daughters
(2,1), # association null -> match class null(Child)
])
# define evaluation methods for each match class.
def eval_attr11(self, attr_value, this):
return True
de... |
zerolab/wagtail | wagtail/contrib/forms/tests/test_models.py | Python | bsd-3-clause | 28,754 | 0.002687 | # -*- coding: utf-8 -*-
import json
import unittest
from django import VERSION as DJANGO_VERSION
from django.core import mail
from django.core.checks import Info
from django.test import TestCase, override_settings
from wagtail.contrib.forms.models import FormSubmission
from wagtail.contrib.forms.tests.utils import (
... | bmission[0].form_data)
# Check that the all the multiple checkbox values are serialised in the
# email correctly
self.assertEqual(len(mail.outbox), 1)
self.assertIn("bar", mail.outbox[0].body)
self.assertIn("foo", mail.outbox[0].body)
self.assertIn("baz", mail.outbox[0].... | .post('/contact-us/', {
'your_email': 'bob@example.com',
'your_message': 'hello world',
'your_choices': {},
})
# Check response
self.assertContains(response, "Thank you for your feedback.")
self.assertTemplateNotUsed(response, 'tests/form_page.html')
... |
tinloaf/home-assistant | homeassistant/components/switch/android_ip_webcam.py | Python | apache-2.0 | 2,983 | 0 | """
Support for IP Webcam settings.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.android_ip_webcam/
"""
from homeassistant.components.switch import SwitchDevice
from homeassistant.components.android_ip_webcam import (
KEY_MAP, ICON_MAP, DAT... | elif self._setting == 'focus':
await self._ipcam.focus(activate=True)
elif self._setting == 'video_recording':
await self._ipcam.record(record=True)
else:
await self._ipcam.change_setting(self._setting, True)
self._state = True
self.async_schedul... | f._setting == 'torch':
await self._ipcam.torch(activate=False)
elif self._setting == 'focus':
await self._ipcam.focus(activate=False)
elif self._setting == 'video_recording':
await self._ipcam.record(record=False)
else:
await self._ipcam.change_set... |
TejasM/wisely | wisely_project/pledges/urls.py | Python | mit | 1,256 | 0.008758 | __author__ = 'Cheng'
from django.con | f.urls import patterns, url
import views
urlpatterns = patterns('',
# /pledges/
url(r'^$', views.index, name='index'),
url(r'^reward/list/$', views.list_rewards, name='list_rewards'),
url(r'^reward/collect/$', views.col | lect_reward, name='collect_reward'),
# /pledges/23
url(r'^(?P<pledge_id>\d+)/$', views.detail, name='detail'),
url(r'^follow/(?P<pledge_id>\d+)/$', views.follow, name='follow'),
url(r'^finish/(?P<pledge_id>\d+)/$', views.finish,... |
cloudbase/maas | src/maasserver/middleware.py | Python | agpl-3.0 | 8,467 | 0.001653 | # Copyright 2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
"""Access middleware."""
str = None
__metaclass__ = type
__all__ = [
"AccessMid... | nabledFor(self.log_level):
header = " Response dump ".center(79, "#")
content = getattr(response, "content", "{no content}")
try:
decoded_content = content | .decode('utf-8')
except UnicodeDecodeError:
logger.log(
|
JelleAalbers/blueice | tests/test_source.py | Python | bsd-3-clause | 494 | 0.004049 | from blueice.test_helpers import *
from blue | ice.model import Model
def test_mcsource():
conf = test_conf(mc=True)
m = Model(conf)
s = m.sources[0]
bins = conf['analysis_space'][0][1]
assert s.events_per_day == 1000
assert s.fraction_in_range > 0.9999 # Ten sigma events happen sometimes..
assert abs(s.pdf([0]) - stats.norm.pdf(0))... | bins[0] + bins[1])/2])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.