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 |
|---|---|---|---|---|---|---|---|---|
robertsj/poropy | pyqtgraph/examples/ViewBox.py | Python | mit | 2,670 | 0.010861 | #!/usr/bin/python
# -*- coding: utf-8 -*-
## Add path | to lib | rary (just for examples; you do not need this)
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
## This example uses a ViewBox to create a PlotWidget-like interface
#from scipy import random
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
app = Q... |
zerocoordinate/deployer | deployer/tasks/databases/postgis.py | Python | bsd-3-clause | 1,222 | 0.006547 | import os
from fabric.api import *
from fabric.context_managers import cd
from .postgresql import remove_db, remove_db_user, create_db_user, backup_db
from .postgresql import configure_db as configure_postgresql
def install_db():
packages = (
'postgresql',
'binutils',
'gdal-bin',
'... | gresql()
create_spatialdb_template()
def create_spatialdb_template():
''' Runs the PostGIS spatial DB template script. '''
put(os.path.join(env.deploy_dir, 'create_template_postgis-debian.sh | '),
'/tmp/', mirror_local_mode=True)
try:
sudo('/tmp/create_template_postgis-debian.sh', user='postgres')
except Exception, exc:
print "There was an error creating the spatialdb template: %s" % exc
finally:
run('rm -f /tmp/create_template_postgis-debian.sh')
def create_db(db_user, ... |
pschmitt/home-assistant | homeassistant/components/zha/device_trigger.py | Python | apache-2.0 | 2,852 | 0.000701 | """Provides device automations for ZHA devices that emit events."""
import voluptuous as vol
import homeassistant.components.automation.event as event
from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA
from homeassistant.components.device_automation.exceptions import (
InvalidDeviceAutomati... | fig
return config
async def async_attach_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
trigger = (config[CONF_TYPE], config[CONF_SUBTYPE])
try:
| zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID])
except (KeyError, AttributeError):
return None
if trigger not in zha_device.device_automation_triggers:
return None
trigger = zha_device.device_automation_triggers[trigger]
event_config = {
event.CONF_PL... |
paopao74cn/noworkflow | tests/t1.py | Python | mit | 66 | 0.030303 | def a | ():
def b():
print ' | b'
print 'a'
print a.b() |
CruiseDevice/coala | coalib/parsing/DefaultArgParser.py | Python | agpl-3.0 | 9,780 | 0 | import argparse
from coalib.misc import Constants
from coalib.collecting.Collectors import get_all_bears_names
from coalib.parsing.filters import available_filters
class CustomFormatter(argparse.RawDescriptionHelpFormatter):
"""
A Custom Formatter that will keep the metavars in the usage but remove them
... | description,
# Use our own help so that we can put it in the | group we want
add_help=False)
arg_parser.add_argument('TARGETS',
nargs='*',
help='sections to be executed exclusively')
info_group = arg_parser.add_argument_group('Info')
info_group.add_argument('-h',
'--help',
... |
lituan/tools | blosum.py | Python | cc0-1.0 | 11,063 | 0.004429 | BLOSUM45 = {
'A': {'A': 1, 'R': -2, 'N': -1, 'D': -2, 'C': -1, 'Q': -1, 'E': -1, 'G': 0, 'H': -2, 'I': -1, 'L': -1, 'K': -1, 'M': -1, 'F': -2, 'P': -1, 'S': 0, 'T': 0, 'W': -2, 'Y': -2, 'V': 0, 'B': -1, 'J': -1, 'Z': -1, 'X': -1, '*': -5},
'R': {'A': -2, 'R': 8, 'N': 0, 'D': -2, 'C': -3, 'Q': 1, 'E': -2, 'G': -... | 'Q': -4, 'E': -3, 'G': -3, 'H': -2, 'I': 0, 'L': 1, 'K': -3, 'M': 0, 'F': 8, 'P': -3, 'S': -2, 'T': -1, 'W': 1, 'Y': 3, 'V': 0, 'B': -3, 'J': 1, 'Z': -3, 'X': -1, '*': -5},
'P': {'A': -1, 'R': -2, 'N': -2, 'D': -1, 'C': -4, 'Q': -1, 'E': 0, 'G': -2, 'H': -2, 'I': -2, 'L': -3, 'K': -1, 'M': -2, 'F': -3, 'P': 2, 'S':... | : -3, 'V': -3, 'B': -2, 'J': -3, 'Z': -1, 'X': -1, '*': -5},
'S': {'A': 0, 'R': -1, 'N': 1, 'D': 0, 'C': -1, 'Q': 0, 'E': 0, 'G': 0, 'H': -1, 'I': -2, 'L': -3, 'K': -1, 'M': -2, 'F': -2, 'P': -1, 'S': 4, 'T': 2, 'W': -4, 'Y': -2, 'V': -1, 'B': 0, 'J': -2, 'Z': 0, 'X': -1, '*': -5},
'T': {'A': 0, 'R': -1, 'N': 0... |
jboy/nim-pymod | tests/01-numpy_arrays/002-data_attr/test_data_attr.py | Python | mit | 10,370 | 0.005689 | import array_utils
import numpy
import pytest
def test_0_compile_pymod_test_mod(pmgen_py_compile):
pmgen_py_compile(__name__)
def _get_array_data_address(arr):
# It took me a long time to find out how to access the `arr.data` address
# (ie, obtain the actual `arr.data` pointer as an integer) in Pyth... | DataPtrAsInt_1d2(pymod_test_mod, random_1d_array_size):
arg = array_utils.get_random_1d_array_of_size_and_type(random_1d_array_size, | numpy.bool_)
res = pymod_test_mod.returnBoolDataPtrAsInt(arg)
data_addr = _get_array_data_address(arg)
assert res == data_addr
def test_returnInt8DataPtrAsInt_1d(pymod_test_mod, random_1d_array_size):
arg = array_utils.get_random_1d_array_of_size_and_type(random_1d_array_size, numpy.int8)
res = pym... |
Elemnir/presentations | utk_prog_team_2015_04_09/flask2/flask2.py | Python | bsd-2-clause | 233 | 0.008584 | from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/")
def hello():
return re | nder_template('test.html', r=request)
if __name__ == "__main__":
app.run(host='0.0.0.0', | port=8001, debug=True)
|
taikoa/wevolver-server | wevolve/users/migrations/0005_auto__del_field_profile_modified_user__del_field_profile_data.py | Python | agpl-3.0 | 7,905 | 0.007337 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Profile.modified_user'
db.delete_column(u'user_profile', 'modified_user_id')
# De... | Field', [], {'unique': 'True', 'max_length': '150'})
},
'users.profile': {
'Meta': {'object | _name': 'Profile', 'db_table': "u'user_profile'"},
'bio': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'country': ('django.db.models.fields.rela... |
SocialNPHS/SocialNPHS | tests/sources.py | Python | mit | 5,885 | 0 | """
Unit tests for the portion of this project which collects text from social
media sources
"""
import unittest
from unittest.mock import MagicMock
from unittest.mock import patch
import tweepy
# Magically manipulate sys.path
from testassets import pathmagic
from SocialNPHS.sources.twitter import discover
from Soc... | 'postal_code': '12561'
}
| )
)],
'l': [MagicMock(
place=MagicMock(
contained_within=[{'name': 'New Paltz'}]
)
)],
'm': [MagicMock(
place=MagicMock(
contained_within=[{... |
0xced/youtube-dl | test/test_download.py | Python | unlicense | 4,976 | 0.004421 | #!/usr/bin/env python
import errno
import hashlib
import io
import os
import json
import unittest
import sys
import hashlib
import socket
# Allow direct execution
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import youtube_dl.FileDownloader
import youtube_dl.InfoExtractors
from youtub... | finished_hook_called.add(status['filename'])
fd.add_progress_hook(_hook)
test_cases = test_case.get('playlist', [test_case])
for tc in test_cases:
_try_rm(tc['file'])
_try_rm(tc['file'] + '.p | art')
_try_rm(tc['file'] + '.info.json')
try:
for retry in range(1, RETRIES + 1):
try:
fd.download([test_case['url']])
except (DownloadError, ExtractorError) as err:
if retry == RETRIES: raise
# ... |
maartenbreddels/vaex | packages/vaex-ui/vaex/ui/rthook_pyqt4.py | Python | mit | 298 | 0 | __author__ = 'breddels'
# from https://github.com/pyinst | aller/pyinstaller/wiki/Recipe-PyQt4-API-Version
import sip
sip.setapi(u'QDate', 2)
sip.setapi(u'QDateTime', 2)
sip.setapi(u'QString', 2)
sip.setapi(u'QTextStream', 2)
si | p.setapi(u'QTime', 2)
sip.setapi(u'QUrl', 2)
sip.setapi(u'QVariant', 2)
|
kaneawk/shadowsocksr | shadowsocks/udprelay.py | Python | apache-2.0 | 25,937 | 0.002275 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 clowwindy
#
# 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
# dist | ributed 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.
# SOCKS5 UDP Request
# +----+------+------+----------+----------+----------+
# ... |
kamyu104/LeetCode | Python/valid-palindrome.py | Python | mit | 994 | 0.004024 | from __future__ import print_function
# Time: O(n)
# Space: O(1)
#
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
# For example,
# "A man, a plan, a canal: Panama" is a palindrome.
# "race a car" is not a palindrome.
#
# Note:
# Have you consider that ... | nterview.
#
# For the purpose of this problem, we define empty string as valid palindrome.
#
class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1
... | if s[i].lower() != s[j].lower():
return False
i, j = i + 1, j - 1
return True
if __name__ == "__main__":
print(Solution().isPalindrome("A man, a plan, a canal: Panama"))
|
aonotas/chainer | tests/chainer_tests/links_tests/theano_tests/test_theano_function.py | Python | mit | 5,778 | 0 | import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import gradient_check
from chainer import links
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
@testing.with_requires('theano')
class TheanoFunctionTestBase(object):
fo... | nsor as T
x = T.TensorType(self.inputs[0]['type'],
(False,) * len(self.inputs[0]['shape']))('x')
i = T.TensorType(self.inputs[1]['type'],
(False,) * len(self.inputs[1]['shape']))('y')
z = x[i]
return links.TheanoFunction([x, i], z)
d... | self.input_data
return x[i],
testing.run_module(__name__, __file__)
|
unomena/unobase | unobase/blog/templatetags/blog_widgets.py | Python | bsd-3-clause | 407 | 0.007371 | __author__ = 'michael'
from django import template
from unobase import models as | unobase_models
register = template.Library()
| @register.inclusion_tag('blog/widgets/tag_cloud.html')
def tag_cloud(blog_slug):
tags = unobase_models.TagModel.get_distinct_tags('blogentry')
#set(unobase_models.TagModel.get_tags('blogentry'))
return {
'blog_slug': blog_slug,
'tags': tags
}
|
dbbhattacharya/kitsune | vendor/packages/pyparsing/examples/greetingInGreek.py | Python | bsd-3-clause | 440 | 0.021077 | # vim:fileencoding=utf-8
#
# greetingInGreek.py
#
# Demonstration of t | he parsing module, on the prototypical "Hello, World!" example
#
from pyparsing import Word
# define grammar
alphas = u''.join(unichr(x) for x in xrange(0x386, 0x3ce))
greet = Word(alphas) + u',' + Word(alphas) + u'!'
# input string
hello = "Καλημέρα, κόσμε!".decode('utf-8')
# parse input string
prin... | greet.parseString( hello )
|
mike820324/microProxy | microproxy/interceptor/plugin_manager.py | Python | mit | 3,707 | 0.00027 | import os
import sys
from copy import copy
from watchdog.events import RegexMatchingEventHandler
if sys.platform == "darwin":
from watchdog.observers.polling import PollingObserver as Observer
else:
from watchdog.observers import Observer
from microproxy.log import ProxyLogger
logger = ProxyLogger.get_logger(... | )
self._load_plugin()
def __getattr__(self, attr):
if attr not in self.PLUGIN_METHODS:
raise AttributeErr | or
try:
return self.namespace[attr]
except KeyError:
raise AttributeError
class PluginManager(object):
def __init__(self, config):
self.plugins = []
self.load_plugins(config["plugins"])
def load_plugins(self, plugin_paths):
for plugin_path in pl... |
tehranian/django-url-shortener | shortener/tests.py | Python | mit | 9,097 | 0.00011 | import random
import string
import sys
from django.core.urlresolvers import reverse
from django.template import Context, RequestContext, Template
from django.test import TestCase
from django.test.client import Client, RequestFactory
from shortener.baseconv import base62, DecodingError, EncodingError
from shortener.f... | """
the short_url templateta | g works with custom links
"""
custom = 'python'
link = Link.objects.create(
url='http://www.python.org/', id=base62.to_decimal(custom))
request = self.factory.get(reverse('index'))
out = Template(
"{% load shortener_helpers %}"
"{% short_url li... |
shiminasai/ciat_plataforma | monitoreo/indicador11/migrations/0001_initial.py | Python | mit | 14,973 | 0.007547 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CultivosVariedad'
db.create_table(u'indicador11_cultivosv... | ngth': '40'})
},
u'lugar.departamento': {
'Meta': {'ordering': "['nombre']", 'object_name': 'Departamento'},
'extension': ('django.db.models.fields.DecimalField', [], {'null' | : 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fi |
tecnologiaenegocios/tn.plonebehavior.template | src/tn/plonebehavior/template/tests/test_template.py | Python | bsd-3-clause | 14,717 | 0 | from plone.app.dexterity.behaviors.metadata import ICategorization
from plone.behavior.interfaces import IBehavior
from stubydoo import double
from stubydoo import stub
from tn.plonebehavior.template import AssociatedTemplateCompilation
from tn.plonebehavior.template import interfaces
from tn.plonebehavior.template imp... | onent.provideAdapter(Configuration)
def tearDown(self):
placelesssetup.tearDown()
def test_delegates_to_adapters(self):
context = double()
content = double(body=u'body')
zope.interface.alsoProvides(context, IAttributeAnnotatable)
template = Template(context)
s... | e.compile(content), u'html(body)')
@stubydoo.assert_expectations
class TestAssociatedTemplateCompilationAdapter(unittest.TestCase):
def setUp(self):
placelesssetup.setUp(self)
self.context = double()
s |
guyinatuxedo/escape | fmt_str/f5_64/exploit.py | Python | gpl-3.0 | 448 | 0.015625 | #First import pwn tools
from pwn import *
#Declare the binary, and run it
elf = ELF("./f5_64")
context(binary=elf)
target = process("./f5_64")
#Grab the buf0 address
buf0_address = p64(elf | .symbols["buf0"])
#Unpack sh and store as a string
sh = str(u64("sh\0\0\0\0\0\0"))
#Finish crafting the exploit and send it
target.sendline("%" + sh + "x%8$n00000" | + str(buf0_address))
#Drop to an interactive prompt to use the shell
target.interactive()
|
ISP-Tetsuro-Kitajima/xchainer | xchainer/manager.py | Python | mit | 6,615 | 0.000966 | # -*- coding: utf_8 -*-
import numpy as np
from sklearn.base import BaseEstimator
from chainer import Variable, cuda
import chainer.functions as F
class NNmanager (BaseEstimator):
def __init__(self, model, optimizer, lossFunction, gpu=True, **params):
# CUDAデバイスの設定
self.gpu = gpu
# 学習器の初期... | oss: %f, mean a | ccuracy: %f, testing loss: %f, testing accuracy: %f"
# テストデータの設定
self.x_test = None
self.y_test = None
self.showTestingMode = None
def fit(self, x_train, y_train):
if self.showTestingMode:
if self.x_test is None or self.y_test is None:
raise Runti... |
goldmedal/spark | sql/gen-sql-api-docs.py | Python | apache-2.0 | 5,943 | 0.001851 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | ut:
**Examples:**
```
> SELECT ...;
...
> SELECT ...;
...
```
"""
if examples.startswith("\n Examples:"):
examples = "\n".join(map(lambda u: u[6:], examples.strip().split("\n")[1:]) | )
return "**Examples:**\n\n```\n%s\n```\n\n" % examples
def _make_pretty_note(note):
"""
Makes the note description pretty and returns a formatted string if `note` is not
an empty string. Otherwise, returns None.
Expected input:
...
Expected output:
**Note:**
...
"... |
20tab/django-political-map | politicalplaces/migrations/0009_politicalplace_postal_code.py | Python | mit | 483 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-18 23:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('politicalplaces', '0008_auto_20170317_1636'),
]
operations = [
m | igrations.AddField(
model_name='politicalplace',
name='postal_code',
field=models.CharField(blank=True, max_length=255),
),
]
|
camielv/wildlife-monitoring | src/modules/datastructures/__init__.py | Python | lgpl-2.1 | 47 | 0 | __all__ = ["annot | ation", "detection", "t | rack"]
|
chasetb/sal | server/migrations/0004_auto_20150623_1623.py | Python | apache-2.0 | 1,504 | 0.00266 | # -*- coding: utf-8 -*-
from _ | _future__ import unicode_literals
from django.db import models, migrat | ions
class Migration(migrations.Migration):
dependencies = [
('server', '0003_auto_20150612_1123'),
]
operations = [
migrations.RemoveField(
model_name='apikey',
name='read_only',
),
migrations.AlterField(
model_name='condition',
... |
GustJc/PyPhysics | projects/03-Game/main.py | Python | gpl-3.0 | 1,567 | 0.02425 | import pygame
import src.sprite as game
pygame.init()
screen = pygame.display.set_mode((400,300))
done = False
GameUpdateList = []
GameRenderList = []
catapult = game.Sprite("data/img/catapult.png", 5)
boulder = None
catapultAnim = game.Animation(catapult, 96, 96, 5, 100)
GameUpdateList.append(catapultAnim)
GameR... | boulder = None
catapultAnim.forceFrame(0)
catapultAnim.pause = False
# Testes --------------------------------------
last_time = pygame.time.get_ticks()
while not done:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Atualiza temp | o
dt = pygame.time.get_ticks() - last_time
last_time = pygame.time.get_ticks()
# Atualiza timer da catapulta em ms
for obj in GameUpdateList:
obj.update(dt)
#catapultAnim.update(dt)
shotBoulder(dt)
for obj in GameRenderList:
obj.render(screen)
#catapultAnim.render(screen)
# Mostra ... |
FirmlyReality/docklet | src/master/settings.py | Python | bsd-3-clause | 1,940 | 0.007732 | #!/usr/bin/python3
from utils import env
import json, os
from functools import wraps
from utils.log import logger
class settingsClass:
setting = {}
def __init__(self):
settingPath = env.getenv('FS_PREFIX') + '/local/settings.conf'
if not os.path.exists(settingPath):
settingFile = ... | 0].setting}
def update(*args, **kwargs):
try:
if ( ('user_group' in kwargs) == False):
return {"success":'false', "reason":"Cannot get user_group"}
user_group = kwargs['user_group']
if (not ((user_group == 'admin') or (user_group == 'root'))):
... | ng']
settingPath = env.getenv('FS_PREFIX') + '/local/settings.conf';
settingText = json.dumps(newSetting)
settingFile = open(settingPath,'w')
settingFile.write(settingText)
settingFile.close()
args[0].setting = newSetting
return {'succe... |
GemHQ/round-py | round/users.py | Python | mit | 6,392 | 0.001095 | # -*- coding: utf-8 -*-
# users.py
#
# Copyright 2014-2015 BitVault, Inc. dba Gem
from __future__ import unicode_literals
from .config import *
from .wrappers import *
from .errors import *
from .subscriptions import Subscriptions
from .devices import Devices
from .wallets import generate, Wallet
class Users(DictW... | have sole access to their backup key, and will need to
communicate directly with Gem to provide MFA credentials for protected
actions | (updating their User object, publishing transactions, approving
devices, etc).
For a custodial model where a Wallet is intended to hold assets of multiple
individuals or an organization, read the Gem docs regarding Application
wallets.
Attributes:
first_name (str)
last_name (str)
... |
luken/pcitweak | examples/printbin.py | Python | mit | 166 | 0 | #!/usr/bin/python
from pcitweak.bitstring import BitString
for n in range(0x10):
b = BitString(uint=n, length=4)
print " % 3d 0x%02x | %s" % ( | n, n, b.bin)
|
NickolayStorm/usatu-learning | ComputerGraphic/Lab2/complexview.py | Python | mit | 6,080 | 0.00289 | from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from cairodrawing import CairoDrawing, PointType
from structures import Point, HomogeneousPoint
class ComplexView(QWidget):
def __init__(self, parent=None, indent=20):
super(ComplexView, self).__init__(parent)
width = self.width()
h... | ain)
CairoDrawi | ng.draw_point(painter, self.CX, "CX", PointType.observer_subsidiary)
CairoDrawing.draw_point(painter, self.C2, "C2", PointType.observer_main)
CairoDrawing.draw_point(painter, self.CZ, "CZ", PointType.observer_subsidiary)
CairoDrawing.draw_point(painter, self.C3, "C3", PointType.observer_main)
... |
hansonrobotics/chatbot | src/chatbot/aiml/Kernel.py | Python | mit | 50,732 | 0.001183 | # -*- coding: utf-8 -*-
"""
Copyright 2003-2010 Cort Stratton. All rights reserved.
Copyright 2015, 2016 Hanson Robotics
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the abov... | }
self._addSession(self._globalSessionID)
# Set up the bot predicates
self._botPredicates = {}
self.setBotPredicate("name", "Nameless")
# set | up the word substitutors (subbers):
self._subbers = {}
self._subbers['gender'] = WordSub(DefaultSubs.defaultGender)
self._subbers['person'] = WordSub(DefaultSubs.defaultPerson)
self._subbers['person2'] = WordSub(DefaultSubs.defaultPerson2)
self._subbers['normal'] = WordSub(Defau... |
pchaigno/grreat | lib/aff4_objects/stats_store_test.py | Python | apache-2.0 | 40,610 | 0.001231 | #!/usr/bin/env python
"""Tests for the stats_store classes."""
import math
import pandas
# pylint: disable=unused-import,g-bad-import-order
from grr.lib import server_plugins
# pylint: enable=unused-import,g-bad-import-order
from grr.lib import aff4
from grr.lib import data_store
from grr.lib import flags
from gr... | ] == "af | f4:stats_store/counter"]
self.assertEqual(len(values), 2)
http_field_value = rdfvalue.StatsStoreFieldValue(
field_type=rdfvalue.MetricFieldDefinition.FieldType.STR,
str_value="http")
rpc_field_value = rdfvalue.StatsStoreFieldValue(
field_type=rdfvalue.MetricFieldDefinition.FieldType... |
pjuu/pjuu | pjuu/posts/backend.py | Python | agpl-3.0 | 24,772 | 0 | # -*- coding: utf-8 -*-
"""Simple functions for dealing with posts, replies, votes and subscriptions
within Redis and MongoDB
:license: AGPL v3, see LICENSE for more details
:copyright: 2014-2021 Joe Doherty
"""
# 3rd party imports
from flask import current_app as app, url_for
from jinja2.filters import do_capital... | .posts.find_one({'_id': self.post_id},
{'username': True, '_id': False})
# Return the username or None
return url_for('posts.view_post', username=author.get('username'),
post_id=self.post_id)
def | verify(self):
"""Overwrites the verify() of BaseAlert to check the post exists
"""
return m.db.users.find_one({'_id': self.user_id}, {}) and \
m.db.posts.find_one({'_id': self.post_id}, {})
class TaggingAlert(PostingAlert):
"""Form of all tagging alert messages
"""
... |
juliusf/Neurogenesis | neurogenesis/__init__.py | Python | bsd-3-clause | 22 | 0 | nam | e = "neurogenesi | s"
|
pakit/test_recipes | providesb.py | Python | bsd-3-clause | 413 | 0 | """ Formula that requires no other recip | e. """
from p | akit import Dummy, Recipe
class Providesb(Recipe):
"""
Dummy recipe does nothing special but have dependency.
"""
def __init__(self):
super(Providesb, self).__init__()
self.homepage = 'dummy'
self.repos = {
'stable': Dummy()
}
def build(self):
p... |
jsirois/pex | pex/vendor/_vendored/packaging/packaging/markers.py | Python | apache-2.0 | 9,913 | 0.001211 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import operator
import os
import platform
import sys
if "__PEX_UNVENDORED... | Dict[str, str]
if hasattr(sys, "implementation"):
# Ignoring the `sys.implementation` reference for type checking due to
# mypy not liking that the attribute doesn't exist in Python 2.7 when
# run with the `--py27` flag.
iver = format_full_version(sys.implementation.version) # type... | mentation_name = sys.implementation.name # type: ignore
else:
iver = "0"
implementation_name = ""
return {
"implementation_name" |
thaim/ansible | lib/ansible/modules/windows/win_netbios.py | Python | mit | 2,309 | 0.002599 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Thomas Moore (@tmmruk)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
from __future__ import (absolute_import, ... | no
author:
- Thomas Moore (@tmmruk)
notes:
- Changing NetBIOS settings does not usually require a reboot and will take effect immediately.
- | UDP port 137/138/139 will no longer be listening once NetBIOS is disabled.
'''
EXAMPLES = r'''
- name: Disable NetBIOS system wide
win_netbios:
state: disabled
- name: Disable NetBIOS on Ethernet2
win_netbios:
state: disabled
adapter_names:
- Ethernet2
- name: Enable NetBIOS on Public and Backu... |
rrude/twilio_quest | app.py | Python | mit | 3,440 | 0.006105 | import os
from flask import Flask
from flask import Response
from flask import request
from flask import render_template
from twilio import twiml
from twilio.rest import TwilioRestClient
# Pull in configuration from system environment variables
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOK... | re | sponse = twiml.Response();
response.say('I just responded to a phone call. Huzzah!', voice='woman')
# Gather digits.
with response.gather(numDigits=1, action="/handle-key", method="POST") as g:
g.say('Press 1 for more options, or press 0 to speak to Jona.')
return str(response)
@app.route("/h... |
bluephlavio/latest | test/test_config.py | Python | mit | 438 | 0.002283 | try:
import configparser
except:
import ConfigParser as configparser
def test_config(config):
assert config.templates_dir == '~/.latest/templates/'
assert con | fig.pyexpr_entry == r'\{\$'
assert config.pyexpr_exit == r'\$\}'
assert config.env_entry == r'<<<' |
assert config.env_exit == r'>>>'
def test_non_existing_config(non_existing_config):
assert non_existing_config.env_entry == r'\\begin\{latest\}'
|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol/ubuntuone/storageprotocol/delta.py | Python | gpl-3.0 | 94 | 0.021277 | ../../../../../../share/pyshared/ubuntuone-st | orage-protocol/ubuntu | one/storageprotocol/delta.py |
knodir/son-emu | scenarios/experiments/bench.py | Python | apache-2.0 | 4,445 | 0.003825 | import time
import os
import glog
from daisy import executeCmds
def start_benchmark(algo, num_of_chains, mbps, chain_index=None, isIperf=False):
""" Allocate E2 style chains. """
# list of commands to execute one-by-one
cmds = []
if isIperf:
glog.info('Launching iperf instead of tcpreplay...'... | /traces/output.pcap mn.chain%d-source:/' % chain_index)
else:
cmds.append('sudo docker cp ../traces/output.pcap mn.chain%d-source:/' % chain_index)
executeCmds(cmds)
cmds[:] = []
# # copy the traces into the containers for tcpreplay, this might take a while
glog.info('Runnin... | t --net --time -N intf2 --bits --output /tmp/dstat.csv' % chain_index)
if isIperf:
cmds.append('sudo docker exec mn.chain%d-sink iperf3 -s' % chain_index)
else:
cmds.append('sudo docker exec -d mn.chain%d-sink dstat --net --time -N intf2 --bits --output /tmp/dstat.csv' % chain_in... |
cloudnull/tribble-api | tribble/api/views/zones_rest.py | Python | gpl-3.0 | 12,756 | 0 | # =============================================================================
# Copyright [2013] [Kevin Carter]
# License Information :
# This software has no warranty, it is provided 'as is'. It is your
# responsibility to validate the behavior of the routines and its accuracy
# using the code provided. Consult the ... | ematics/<sid>/zones/<zid>', methods=['PUT'])
def zone_put(sid=None, zid=None):
"""Up | date a Zone.
Method is accessible with PUT /v1/schematics/<sid>/zones/<zid>
:param sid: ``str`` # schematic ID
:param zid: ``str`` # Zone ID
:return json, status: ``tuple``
"""
parsed_data = utils.zone_data_handler(sid=sid)
if parsed_data[0] is False:
return utils.return_msg(msg=pa... |
aabilio/PyDownTV | Servers/riasbaixas.py | Python | gpl-3.0 | 2,956 | 0.00782 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of PyDownTV.
#
# PyDownTV 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) a... | self._URL_recibida = url
def getURL(self):
return self._URL_recibida
def setURL(self, url):
self._URL_recibida = url
url = property(getURL, setURL)
# Funciones p | rivadas que ayuden a procesarDescarga(self):
def __descHTML(self, url2down):
''' Método que utiliza la clase descargar para descargar el HTML '''
D = Descargar(url2down)
return D.descargar()
def procesarDescarga(self):
'''
Procesa lo necesario para obtener la url fin... |
monuszko/django-polls | polls/migrations/0004_auto_20160201_1000.py | Python | gpl-2.0 | 926 | 0.00216 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-01 09:00
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migrat | ion):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
| ('polls', '0003_auto_20160131_1905'),
]
operations = [
migrations.AddField(
model_name='poll',
name='created_by',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
preserve_default=False,
... |
caktus/django-timepiece | timepiece/reports/urls.py | Python | mit | 655 | 0 | from django.conf.urls import url
from timepiece.reports import views
urlpatterns = [
url(r'^r | eports/hourly/$',
views.HourlyReport.as_view(),
name='report_hourly'),
url(r'^reports/payroll/$',
views.report_payroll_summary,
| name='report_payroll_summary'),
url(r'^reports/billable_hours/$',
views.BillableHours.as_view(),
name='report_billable_hours'),
url(r'^reports/productivity/$',
views.report_productivity,
name='report_productivity'),
url(r'^reports/estimation_accuracy/$',
vi... |
spark8103/ops17 | app/user/__init__.py | Python | mit | 101 | 0.009901 | # coding: utf- | 8
from flask import | Blueprint
user = Blueprint('user', __name__)
from . import views
|
MKDTeam/SSH-Client | connection.py | Python | mit | 8,807 | 0.033413 | import paramiko, os, hashlib, random, struct
from Crypto.Cipher import AES
from Crypto import Random
from ui_class.ui_Connection import Ui_dialog_connection
from ui_class.ui_LoadSettings import Ui_qDialog_load
from ui_class.ui_SaveSettings import Ui_qDialog_save
from Exceptions import SSHConnectionError, HostError, Por... |
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
def __str__(self):
output = ''
for | line in self.data.keys():
output += line + ' = ' + self.data[line] + '\n'
return output
def __getitem__(self, key):
if key in self.data:
return self.data[key]
class ConnectionManager(QObject):
"""Создание SSH тунеля и отображение окна настроек соеденения"""
signal_onConnect = pyqtSignal() #Сигнал отправ... |
s-m-i-t-a/sales_menu | tests/factories.py | Python | bsd-3-clause | 318 | 0 | # -*- coding: utf-8 -*-
import factory
from sales_menu.models import Menu
class MenuFactory(factory.DjangoModelFactory):
FACTORY_FOR = | Menu
text = factory.Sequence(lambda n: u'Menu %d' % n)
parent = None
url = factory.Sequence(lambda n: u'/menu-%d' % n)
weight = factory. | Sequence(lambda n: n)
|
flask-restful/flask-restful | tests/test_inputs.py | Python | bsd-3-clause | 12,433 | 0.001046 | from datetime import datetime, timedelta, tzinfo
import unittest
import pytz
import re
#noinspection PyUnresolvedReferences
from nose.tools import assert_equal, assert_raises # you need it for tests in form of continuations
import six
from flask_restful import inputs
def test_reverse_rfc822_datetime():
dates =... | for value in values:
yield check_bad_url_raises, value
def test_bad_url_error_message():
values = [
'google.com',
'domain.google.com',
'kevin:[email protected]/path?query',
u'google.com/path?\u2713',
]
for value in values:
yield check_url_error_message, v... | assert False, u"inputs.url({0}) should raise an exception".format(value)
except ValueError as e:
assert_equal(six.text_type(e),
(u"{0} is not a valid URL. Did you mean: http://{0}".format(value)))
def test_regex_bad_input():
cases = (
'abc',
'123abc',
'abc... |
mheap/ansible | lib/ansible/plugins/action/eos.py | Python | gpl-3.0 | 5,886 | 0.003058 | #
# (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... | the right cli context which should be
# enable mode and not config module
if socket_path is None:
socket_path = self._connection.socket_path
conn = Connection(socket_path)
out = conn.get_prompt()
while '(config' in to_text | (out, errors='surrogate_then_replace').strip():
display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr)
conn.send_command('abort')
out = conn.get_prompt()
result = super(ActionModule, self).run(task_vars=task_vars)
return res... |
wayneww/Scrabble | game_run.py | Python | gpl-3.0 | 13,893 | 0.041748 | # wayne warren 2015
import scrabble # for my shuffling etc. PRESSING ENTER WILL SCORE WORD.
import pygame
import pygame.locals
import time
import random
from pygame import mixer
from os import getcwd
top_dir = getcwd()
print top_dir
mixer.init()
# for bleep when window pops up
bad_word_alert=mixer.Sound(top_dir+'/soun... |
# board is 40 to 600 x and y
board = []
for i in ran | ge(40,680,40):
for j in range(40,680,40):
board.append([i,j])
# tile float
tile_float = False
float_letter = ""
# pass flags lol
player_pass = False # for deadlock at end when we both pass consecutively
computer_pass = False
comp_pass_count = 0
#print board
# -------- Main Program Loop -----------
while done == F... |
ioanpocol/superdesk-core | apps/archive_broadcast/broadcast.py | Python | agpl-3.0 | 14,350 | 0.002927 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | t broadcast_genre:
raise SuperdeskApiError.badRequestError(message="Cannot find the {} genre.".format(BRO | ADCAST_GENRE))
doc['broadcast'] = {
'status': '',
'master_id': item_id,
'rewrite_id': item.get('rewritten_by')
}
doc['genre'] = broadcast_genre
doc['family_id'] = item.get('family_id')
for key in FIELDS_TO_COPY:
doc[key] = item.g... |
n3011/deeprl | dataset/replay_v2.py | Python | mit | 4,664 | 0 | import random
import numpy as np
class ReplayBuffer(object):
def __init__(self, max_size):
self.max_size = max_size
self.cur_size = 0
self.buffer = {}
self.init_length = 0
def __len__(self):
return self.cur_size
def seed_buffer(self, episodes):
self.init_... | s
def remove_n(se | lf, n):
"""Get n items for removal."""
assert self.init_length + n <= self.cur_size
if self.eviction_strategy == 'rand':
# random removal
idxs = random.sample(xrange(self.init_length, self.cur_size), n)
elif self.eviction_strategy == 'fifo':
# overwri... |
OldhamMade/beanstalkctl | specs/base_spec.py | Python | mit | 3,511 | 0.001994 | import os
import signal
import subprocess
import beanstalkc
import time
import pexpect
try:
import unittest2 as unittest
except ImportError:
import unittest
from beanstalkctl.util import BeanstalkdMixin
class BaseSpec(unittest.TestCase, BeanstalkdMixin):
beanstalkd_instance = None
beanstalkd_host =... | raise Exception(error)
return result
| def clean(self, text):
for chunk in ('\r', r'\\x1b[K'):
text = text.replace(chunk, '')
return text.strip()
def skipped(func):
from nose.plugins.skip import SkipTest
def wrapper(*args, **kwargs):
raise SkipTest("Test %s is skipped" % func.__name__)
wrapper.__name__ = fun... |
thomasyu888/synapsePythonClient | tests/unit/synapseclient/core/unit_test_download.py | Python | apache-2.0 | 24,938 | 0.004571 | import hashlib
import json
import os
import shutil
import tempfile
import unittest
from unittest.mock import MagicMock, patch, mock_open, call
import pytest
import requests
import synapseclient.core.constants.concrete_types as concrete_types
import synapseclient.core.multithread_download as multithread_download
from... | tempdir()
fileHandleId = "42"
objectId = "syn789"
objectType = "FileEntity"
# make bogus content
contents = "\n".join(str(i) for i in range(1000))
# compute MD5 of contents
m = hashlib.md5()
m.update(contents.encode('utf-8'))
contents_md5 = m.hexdigest()
url = "https://repo-p... | stream", contents=contents, buffer_size=1024)
])
# patch requests.get and also the method that generates signed
# headers (to avoid having to be logged in to Synapse)
with patch.object(syn._requests_session, 'get', side_effect=mock_requests_get), \
patch.object(Synapse, '_generate_headers', si... |
ros2/launch | launch/launch/actions/conftest.py | Python | apache-2.0 | 1,143 | 0 | # Copyright 2021 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | ort launch
import launch.actions
import launch.conditions
import launch.substitutions
import pytest
@pytest.fixture(autouse=True)
def add_imports_to_doctest_namespace(doctest_namespace):
doctest_namespace['launch'] = launch
doctest_namespace['LaunchDescription'] = launch.LaunchDescription
for subpackage ... | getattr(subpackage, x)
|
qisanstudio/qstudio-launch | src/studio/launch/commands/config.py | Python | mit | 69 | 0.014493 | # -*- c | oding: utf-8 -*-
from __future__ im | port unicode_literals
|
IDSIA/sacred | examples/06_randomness.py | Python | mit | 2,287 | 0 | #!/usr/bin/env python
# coding=utf-8
"""
This example showcases the randomness features of Sacred.
Sacred generates a random global seed for every expe | riment, that you can
find in the configuration. It will be different every time you run the
experiment.
Based on this global seed it will generate the special parameters ``_seed`` and
``_rnd`` for each captured function. Every time you call such a function the
``_seed`` will be different and ``_rnd`` will be different... | d try:
- run the experiment a couple of times and notice how the results are
different every time
- run the experiment a couple of times with a fixed seed.
Notice that the results are the same::
:$ ./06_randomness.py with seed=12345 -l WARNING
[57]
[28]
695891797
[82]
- r... |
pennetti/voicebox | server/src/voicebox/ngram.py | Python | mit | 878 | 0 | from __future__ import absolute_import
class Ngram(object):
def __ | init__(self, token):
self.token | = token
self.count = 1
self.after = []
def __str__(self):
return str({
'after': self.after,
'count': self.count
})
def __repr__(self):
return str({
'after': self.after,
'count': self.count
})
def __len__(self... |
avalcarce/gym-learn | utils.py | Python | mit | 2,550 | 0.002353 | import os
import numpy as np
def get_last_folder_id(folder_path):
t = 0
for fn in os.listdir(folder_path):
t = max(t, int(fn))
return t
def movingaverage(values, window):
weights = np.repeat(1.0, window)/window
sma = np.convolve(values, weights, 'valid')
return sma
... | th the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by in | troducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
x: the input signal
window_len: the dimension of the smoothing window; should be an odd integer
window:... |
PavanGupta01/aerospike-admin | lib/controller.py | Python | apache-2.0 | 27,343 | 0.00534 | # Copyright 2013-2014 Aerospike, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | , either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from lib.controllerlib import *
from lib import util
import time, os, sys, platform, shutil, urllib2, socket
def flip_keys(orig_data):
new_data = {}
for key1, data1 in orig_data.... | :
if isinstance(data1, Exception):
continue
for key2, data2 in data1.iteritems():
if key2 not in new_data:
new_data[key2] = {}
new_data[key2][key1] = data2
return new_data
@CommandHelp('Aerospike Admin')
class RootController(BaseController):
... |
johnbeard/kicad-git | pcbnew/scripting/examples/listPcbLibrary.py | Python | gpl-2.0 | 331 | 0.036254 | #!/usr/bin/env python
from pcbnew import *
lst = FootprintEnumerate("/usr/share/kicad/modules/so | ckets.mod")
for name in lst:
m = FootprintLoad("/usr/share/kicad/modules/sockets.mod",name)
print name,"->",m.GetLibRef(), m.Ge | tReference()
for p in m.Pads():
print "\t",p.GetPadName(),p.GetPosition(),p.GetPos0(), p.GetOffset()
|
cnr-isti-vclab/meshlab | src/external/openkinect/wrappers/python/demo_cv_async.py | Python | gpl-3.0 | 988 | 0.002024 | #!/usr/bin/env python
import freenect
import cv
import numpy as np
cv.NamedWindow('Depth')
cv.NamedWindow('RGB')
def display_depth(dev, data, timestamp):
data -= np.min(data.ravel())
data *= 65536 / np.max(data.ravel())
image = cv.CreateImageHeader((data.shape[1], data.shape[0]),
... | cv.IPL_DEPTH_8U,
3)
# Note: We swap from RGB to BGR here
cv.SetData(image, data[:, :, ::-1].tostring(),
data.dtype.itemsize * 3 * data.shape[1])
cv.ShowImage('RGB', image)
cv.WaitKey(5)
freenect.runloop(depth=display_depth,
... | |
evernym/zeno | plenum/test/node_catchup/test_incorrect_catchup_request.py | Python | apache-2.0 | 3,607 | 0.002218 | import pytest
from plenum.common.messages.node_messages import CatchupReq
from stp_core.common.log import getlogger
from plenum.test.helper import sdk_send_random_and_check
logger = getlogger()
ledger_id = 1
def test_receive_incorrect_catchup_request_with_end_greater_catchuptill(looper,
... | sdk_wallet_client,
4)
ledger_manager = txnPoolNodeSet[0].ledgerManager
ledger_manager.processCatchupReq(req, | "frm")
ledger_size = ledger_manager.ledgerRegistry[ledger_id].ledger.size
_check_call_discard(ledger_manager, "not able to service since "
"catchupTill = {} greater than "
"ledger size = {}"
.format(catchup_... |
feer56/Kitsune2 | kitsune/wiki/models.py | Python | bsd-3-clause | 51,285 | 0.000195 | import hashlib
import itertools
import logging
import time
from datetime import datetime, timedelta
from urlparse import urlparse
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from ... | approved revisions). (Remove "+" to
# enable reverse link.)
current_revision = models.ForeignKey('Revision', null=True,
related_name='current_for+')
# Latest revision which both is_approved and is_ready_for_lo | calization,
# This may remain non-NULL even if is_localizable is changed to false.
latest_localizable_revision = models.ForeignKey(
'Revision', null=True, related_name='localizable_for+')
# The Document I was translated from. NULL iff this doc is in the default
# locale or it is nonlocalizable.... |
dadavidson/Python_Lab | Python-w3resource/Python_Basic/ex03.py | Python | mit | 269 | 0.003717 | # https://www.w3r | esource.com/python-exercises/
# 3. Write a Python program to display the current date and time.
# Sample Output :
# Current date and time :
# 2014-07-05 14:34:14
import datetime
now = datetime.datetime.now()
print n | ow.strftime("%Y-%m-%d %H:%M:%S")
|
gisce/sippers | sippers/parsers/endesa.py | Python | gpl-3.0 | 2,937 | 0.001021 | from __future__ import absolute_import
from sippers import logger
from sippers.utils import build_dict
from sippers.adapters.endesa import EndesaSipsAdapter, EndesaMeasuresAdapter
from sippers.models.endesa import EndesaSipsSchema, EndesaMeasuresSchema
from sippers.parsers.parser import Parser, register
class Endesa... | ter = ';'
def __init__(self, strict=False):
self.adapter = EndesaSipsAdapter(strict=strict)
self.schema = EndesaSipsSchema(strict=strict)
self.fields_ps = []
self.headers_ps = []
for f in sorted(self.schema.fields,
key=lambda f: self.schema.fields[f].metadata... | 'position']):
field = self.schema.fields[f]
self.fields_ps.append((f, field.metadata))
self.headers_ps.append(f)
self.fields = self.fields_ps
def parse_line(self, line):
slinia = tuple(unicode(line.decode(self.encoding)).split(self.delimiter))
slinia = m... |
iluxa-com/mercurial-crew-tonfa | tests/filtertmp.py | Python | gpl-2.0 | 351 | 0.002849 | #!/usr/bin/env python
#
# This used to be a simple sed call like:
#
# $ sed "s:$HGTMP:*HGTMP*:"
#
# But $HGTMP has ':' under Windows which breaks the sed call.
#
import sys, os
input = sys.stdin.read()
input = in | put.replace(os.sep, '/')
hgtmp = os.environ['HGTMP'].repl | ace(os.sep, '/')
input = input.replace(hgtmp, '$HGTMP')
sys.stdout.write(input)
|
masschallenge/django-accelerator | accelerator/tests/factories/criterion_option_spec_factory.py | Python | mit | 636 | 0 | from __future__ import unicode_literals
import | swapper
from factory import (
Sequence,
SubFactory,
)
from factory.django import DjangoModelFactory
from accelerator.tests.factories.criterion_factory import (
CriterionFactory
)
CriterionOptionSpec = swapper.load_model('accelerator', 'CriterionOptionSpec')
class CriterionOptionSpecFactory(DjangoModelFac... | ):
class Meta:
model = CriterionOptionSpec
option = Sequence(lambda n: "CriterionOptionSpec {0}".format(n))
count = CriterionOptionSpec.DEFAULT_COUNT
weight = CriterionOptionSpec.DEFAULT_WEIGHT
criterion = SubFactory(CriterionFactory)
|
sjsj0101/backtestengine | utils/storage.py | Python | apache-2.0 | 4,040 | 0.003085 | # -*- coding: utf-8 -*-
'''
author: Jimmy
contact: [email protected]
file: storage.py
time: 2017/9/4 下午3:18
description:
'''
__author__ = 'Jimmy'
import pymongo
from ctp.ctp_struct import *
from bson import json_util as jsonb
from utils.tools import *
def _getDataBase():
client = p... | trategy_id'] = '未知'
return dict
# 获取最大报单编号
def getMaxOrderRef():
db = _getDataBase()
result = list(db.send_order.find({}).sort([('order_ref', -1)]).limit(1))
if len(result) > 0:
result = result[0]
return int(result['order_ref'])
else:
return 0
def getMaxOrderActionRef():
... | return int(result['order_action_ref'])
else:
return 0
if __name__ == '__main__':
def updateAccount(event):
db = _getDataBase()
if db.account.find().count() > 0:
db.account.update({'AccountID': event.dict['AccountID']},
{"$set": event.dict})
... |
nicko96/Chrome-Infra | appengine/chromium_rietveld/codereview/decorators_chromium.py | Python | bsd-3-clause | 2,669 | 0.007119 | # Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | that insists that you are using a specific key."""
@deco.require_methods('POST')
def key_wrapper(request, *args, **kwds):
key = request.POST.get('password')
if request.user or not key:
return HttpResponseForbidden('You must be admin in for this function')
value = memcache.get('key_required')
... | _chromium.Key(hash='invalid hash')
obj.put()
value = obj.hash
memcache.add('key_required', value, 60)
if sha.new(key).hexdigest() != value:
return HttpResponseForbidden('You must be admin in for this function')
return func(request, *args, **kwds)
return key_wrapper
|
mhbu50/erpnext | erpnext/stock/doctype/customs_tariff_number/customs_tariff_number.py | Python | gpl-3.0 | 209 | 0.004785 | # Copyright (c) 2017, Frappe Technologies Pvt. L | td. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
|
class CustomsTariffNumber(Document):
pass
|
BurningMan44/SprintCoin | qa/rpc-tests/listtransactions.py | Python | mit | 10,132 | 0.016088 | #!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the listtransactions API
from test_framework.test_framework import BitcoinTestFramework
from ... | self.sync_all()
assert_array_ | result(self.nodes[1].listtransactions(),
{"category":"send","amount":Decimal("-0.11")},
{"txid":txid} )
assert_array_result(self.nodes[0].listtransactions(),
{"category":"receive","amount":Decimal("0.11")},
... |
gramps-project/addons-source | DynamicWeb/run_dynamicweb.py | Python | gpl-2.0 | 7,642 | 0.005104 | # -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2014 Pierre Bélissent
#
# 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, o... | mple/gramps/example.gramps,
And with various options.
The script is to be launched from its directory
Arguments = [-i] [report numbers]
Usage examples:
- Import example database
python run_dynamicweb.py -i
- Run reports 0 and 2
python run_dynam | icweb.py 0 2
- Run all reports
python run_dynamicweb.py
"""
from __future__ import print_function
import copy, re, os, os.path, subprocess, sys, traceback, locale, shutil, time, glob
# os.environ["LANGUAGE"] = "en_US"
# os.environ["LANG"] = "en_US.UTF-8"
# user_path = os.environ["GRAMPSHOME"]
# if (not os.path.e... |
mattoufoutu/scoopy | scoopy/oauth.py | Python | gpl-3.0 | 6,386 | 0.000783 | # -*- coding: utf-8 -*-
#
# This file is part of scoopy.
#
# Scoopy 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.
#
# ... |
"""
request_params = {
'oauth_version': '1.0',
'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': int(time()),
'oauth_token': self.token.key,
'oauth_consumer_key': self.consumer.key,
}
fo... | arams)
def request(self, url, params, method='GET'):
request_params = ''
if method.lower() == 'get':
if params:
url += ('?' + urlencode(params))
elif method.lower() == 'post':
request_params = self.generate_request_params(params)
else:
... |
amanzi/ats-dev | tools/visit_ats/visit_ats/visit_rcParams.py | Python | bsd-3-clause | 5,950 | 0.008403 | import datetime
rcParams = {'font.family':'Times',
'axes.2D.tickson':True,
'axes.2D.title.fontscale':2.0,
'axes.2D.label.fontscale':2.0,
'axes.2D.x.title':"x-coordinate [m]",
'axes.2D.y.title':"z-coordinate [m]",
'axes.3D.tickson':False,
... | ag = 0
# 3D
annot.axes3D.triadFlag = 0
annot.axes3D.bboxFlag = 0
# clobber the names
if rcParams['axes.3D.x.title'] is not None:
annot.axes3D.xAxis.title.userTitle = 1
annot.axes3D.xAxis.title.title = rcParams['axes.3D.x.title']
else:
annot.axes3D.xAxis.title.visible = ... | annot.axes3D.yAxis.title.userTitle = 1
annot.axes3D.yAxis.title.title = rcParams['axes.3D.y.title']
else:
annot.axes3D.yAxis.title.visible = 0
if rcParams['axes.3D.z.title'] is not None:
annot.axes3D.zAxis.title.userTitle = 1
annot.axes3D.zAxis.title.title = rcParams['axes.3D.z.... |
ttreeagency/PootleTypo3Org | pootle/apps/pootle_misc/browser.py | Python | gpl-2.0 | 4,675 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2013 Zuza Software Foundation
#
# This file is part of Pootle.
#
# 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... | License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from django.utils.translation import ugettext_lazy as _, ungettext
from pootle_misc import dispatch
from pootle_misc.stats import get_raw_stats, stats_descriptions
HEADING_CHOICES = [
{
'id': 'name',
'class': 'stats',... | ass': 'stats',
'display_name': _("Language"),
},
{
'id': 'progress',
'class': 'stats',
# Translators: noun. The graphical representation of translation status
'display_name': _("Progress"),
},
{
'id': 'total',
'class': 'stats-number sorttable_numer... |
janusnic/21v-python | unit_20/matplotlib/pyplot_index_formatter.py | Python | mit | 556 | 0.005396 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticke | r as ticker
r = mlab.csv2rec('data/imdb.csv')
r.sort()
r = r[-30:] # get t | he last 30 days
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return r.date[thisind].strftime('%Y-%m-%d')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.Func... |
vvw/gensim | gensim/test/test_corpora.py | Python | gpl-3.0 | 9,040 | 0.000996 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Radim Rehurek <[email protected]>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking corpus I/O formats (the corpora package).
"""
import logging
import os.path
import unittest
import tem... | module_path, 'test_data', fname)
def testfile():
# temporary data will be stored to this file
return os.path.join(tempfile.gettempdir(), 'gensim_corpus.tst')
class CorpusTestCase(unittest.TestCase):
TEST_CORPU | S = [[(1, 1.0)], [], [(0, 0.5), (2, 1.0)], []]
def run(self, result=None):
if type(self) is not CorpusTestCase:
super(CorpusTestCase, self).run(result)
def tearDown(self):
# remove all temporary test files
fname = testfile()
extensions = ['', '', '.bz2', '.gz', '.in... |
danithaca/berrypicking | django/autocomplete/demo/views.py | Python | gpl-2.0 | 569 | 0.003515 | from django.contrib.auth.models import User
from django.db.models import Q
from django.shortcuts import render
def demo(request):
retur | n render(request, 'demo/demo.html')
def demo_autocomplete(request | , template_name='demo/autocomplete.html'):
q = request.GET.get('q', '')
context = {'q': q}
queries = {
'users': User.objects.filter(Q(username__icontains=q) | Q(first_name__icontains=q) | Q(last_name__icontains=q) | Q(email__icontains=q)).distinct()[:3]
}
context.update(queries)
retur... |
tmkdev/cwd | cwd_helpers.py | Python | gpl-2.0 | 1,076 | 0.001859 | from configuration import *
from models.cwdlogs import *
from models.dataaccess import *
from utils.alarmsender import *
from logging import *
from sqlalchemy.orm.exc import *
def delcurrent(db, name):
db.query(CurrentJobs).filter(CurrentJobs.name == name).delete()
db.commit()
def clearalarm(db,name):
t... | =raisedevent)
db.add(alarm)
db.commit()
def checkauth(username, password):
if username == ADMINUSER and p | assword == ADMINPASS:
return True
return False
|
asmodehn/filefinder2 | tests/test_filefinder2/pkg/submodule.py | Python | mit | 143 | 0.006993 | #!/usr/bin/python
# -*- codin | g: utf-8 -*-
# Just Dummy class for testing
class TestClassInSubModu | le:
"""Test Class from source"""
pass |
motmot/flymovieformat | scripts/fmf_subtract_frame.py | Python | bsd-3-clause | 2,939 | 0.001021 | import pkg_resources
import motmot.FlyMovieFormat.FlyMovieFormat as FMF
import motmot.imops.imops as imops
import sys, os
from pylab import prctile
import numpy as np
import collections
from optparse import OptionParser
def doit(
input_fname, subtract_frame, start=None, stop=None, gain=1.0, offset=0.0,
):
out... | input_is_color:
frame = imops | .to_rgb8(input_format, frame)
new_frame = frame - subtract_frame
else:
frame = np.atleast_3d(frame)
new_frame = frame - subtract_frame
new_frame = np.clip(new_frame * gain + offset, 0, 255)
new_frame = new_frame.astype(np.uint8)
... |
fyabc/MiniGames | HearthStone2/MyHearthStone/network/lan_client.py | Python | mit | 2,327 | 0.00043 | #! /usr/bin/python
# -*- coding: utf-8 -*-
import socket
import threading
from . import utils2 as utils
from ..utils.message import info, error
__author__ = 'fyabc'
class LanClient:
def __init__(self, user):
self.user = user
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... |
self.wfile = self.socket.makefile('wb', 0)
self.input_thread = None
self.start()
s | elf.run()
def start(self):
# 1. Send user data to server.
self.send('user_data', nickname=self.user.nickname, deck_code=self.user.deck_code)
self.input_thread = self.InputThread(self.wfile)
t = threading.Thread(target=self.input_thread.run)
t.setDaemon(True)
t.start... |
ststaynov/fishGame | manage.py | Python | bsd-3-clause | 245 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault( | "DJANGO_SETTINGS_MODULE", "chat.settings")
from django.core.management import execute_from_command_line
execute_from_command_lin | e(sys.argv)
|
cgstudiomap/cgstudiomap | main/eggs/passlib-1.6.5-py2.7.egg/passlib/tests/test_utils.py | Python | agpl-3.0 | 35,168 | 0.006881 | """tests for passlib.util"""
#=============================================================================
# imports
#=============================================================================
from __future__ import with_statement
# core
from binascii import hexlify, unhexlify
import sys
import random
import warnin... | from passlib.utils import getrandstr, rng
def f(*a,**k):
return getrandstr(rng, * | a, **k)
# count 0
self.assertEqual(f('abc',0), '')
# count <0
self.assertRaises(ValueError, f, 'abc', -1)
# letters 0
self.assertRaises(ValueError, f, '', 0)
# letters 1
self.assertEqual(f('a',5), 'aaaaa')
# letters
x = f(u('abc'), 16)... |
GetmeUK/MongoFrames | tests/fixtures.py | Python | mit | 3,565 | 0.001122 | from datetime import datetime
from pymongo import MongoClient
import pytest
from mongoframes import *
__all__ = [
# Frames
'Dragon',
'Inventory',
'Lair',
'ComplexDragon',
'MonitoredDragon',
# Fixtures
'mongo_client',
'example_dataset_one',
'example_dataset_many'
]
|
# Classes
class Dragon(Frame):
"""
A dragon.
"""
_fields = { |
'name',
'breed'
}
_private_fields = {'breed'}
def _get_dummy_prop(self):
return self._dummy_prop
def _set_dummy_prop(self, value):
self._dummy_prop = True
dummy_prop = property(_get_dummy_prop, _set_dummy_prop)
class Inventory(SubFrame):
"""
An inven... |
CanalTP/kirin | kirin/__init__.py | Python | agpl-3.0 | 3,892 | 0.004882 | # coding=utf-8
# Copyright (c) 2001, 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 and ope... | f 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 FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should... | the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# [matrix] channel #navitia:matrix.org (https://app.element.io/#/room/#navitia:matrix.org)
# https://groups.google.com/d/forum/navitia
# www.navitia.io
import os
import ... |
fabiobatalha/analytics | analytics/views_ajax.py | Python | bsd-2-clause | 17,098 | 0.004971 | # coding: utf-8
from pyramid.view import view_config
from dogpile.cache import make_region
from analytics.control_manager import base_data_manager
from citedby.custom_query import journal_titles
cache_region = make_region(name='views_ajax_cache')
@view_config(route_name='bibliometrics_document_received_citations'... | lication.general('article', 'citations' | , data['selected_code'], data['selected_collection_code'], py_range=data['py_range'], sa_scope=data['sa_scope'], la_scope=data['la_scope'], size=40, sort_term='asc')
return request.chartsconfig.publication_article_references(chart_data)
@view_config(route_name='publication_article_authors', request_method='GET',... |
pviotti/osm-viz | map_points.py | Python | gpl-3.0 | 1,183 | 0.01268 | #!/usr/bin/env python
# Script for processing with map reduce the Open Street Map datasets.
# Counts the num | ber of GPS hits in a discretized and scaled coordinates space. |
# Example of input row: -778591613,1666898345 [as described here: http://blog.osmfoundation.org/2012/04/01/bulk-gps-point-data/ ]
# Example of output row: 1000-2579 282 [<latitude>-<longitude> \t <density value>]
import sys
SCALING = 10 # scaling factor, to decrease map resolution
MAX_LAT =... |
sidhart/antlr4 | runtime/Python2/src/antlr4/error/ErrorListener.py | Python | bsd-3-clause | 4,146 | 0.003618 | #
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... | NTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTI... | ER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Provides an empty default implementation of {@link ANTLRErrorListener}. The
# default implementation of each method does nothing, ... |
akbertram/appengine-pipeline | src/pipeline/pipeline.py | Python | apache-2.0 | 112,693 | 0.007001 | #!/usr/bin/python2.5
#
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | tial or guessable (Python's uuid1
# method generates roughly sequential IDs).
# - Ability to list all root pipelines that are live on simple page.
# Potentia | l TODOs:
# - Add support for ANY N barriers.
# - Add a global 'flags' value passed in to start() that all pipelines have
# access to; makes it easy to pass along Channel API IDs and such.
# - Allow Pipelines to declare they are "short" and optimize the evaluate()
# function to run as many of them in quick successio... |
incuna/incuna-groups | groups/migrations/0016_attachedfile.py | Python | bsd-2-clause | 997 | 0.004012 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('groups', '00... | le', models.FileField(upload_to='groups/attachments')),
('attached_to', models.ForeignKey(to='groups.BaseComment', null=True, blank=True, related_name='attachments')),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, re | lated_name='attachments')),
],
),
]
|
jjhelmus/artview | artview/components/__init__.py | Python | bsd-3-clause | 1,065 | 0.000939 | """
===========================================
Main Components (:mod:`artview.components`)
==================== | =======================
.. currentmodule:: artview.components
ARTview offers some basic Components for visualization
of weather radar data using Py-ART and
ARTview functions.
.. autosummary::
:toctree: generated/
RadarDisplay
GridDisplay
Menu
LevelButtonWindow
FieldButtonWindow
LinkPlugi... | Display
if parse_version(pyart.__version__) >= parse_version('1.6.0'):
from .plot_grid import GridDisplay
else:
from .plot_grid_legacy import GridDisplay
from .plot_points import PointsDisplay
from .menu import Menu
from .level import LevelButtonWindow
from .field import FieldButtonWindow
from .component_contro... |
vholer/zenpacklib | tests/data/zenpacks/ZenPacks.zenoss.ZPLTest1/ZenPacks/zenoss/ZPLTest1/__init__.py | Python | gpl-2.0 | 540 | 0 | ##############################################################################
#
# Copyright | (C) Zenoss, Inc. 2015, all rights reserved.
#
# This content is made available according to terms specified in
# License.zenoss under the directory where your Zenoss product is installed.
#
######################################################## | ######################
from . import zenpacklib
import os
if 'ZPL_YAML_FILENAME' in os.environ:
CFG = zenpacklib.load_yaml(os.environ['ZPL_YAML_FILENAME'])
else:
CFG = zenpacklib.load_yaml()
|
8v060htwyc/api-kickstart | examples/python/http_calls.py | Python | apache-2.0 | 5,289 | 0.017395 | # Python edgegrid module
""" Copyright 2015 Akamai Technologies, 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
Unl... | sg += "ERROR: Please ensure that the .edgerc file is formatted correctly.\n"
error_msg += "ERROR: If you still have issues, please use gen_ed | gerc.py to generate the credentials\n"
error_msg += "ERROR: Problem details: %s\n" % result["detail"]
exit(error_msg)
if status_code in [404]:
error_msg = "ERROR: Call to %s failed with a %s result\n" % (endpoint, status_code)
erro... |
AppEnlight/demo-application | src/appenlight_demo/__init__.py | Python | bsd-3-clause | 939 | 0.001065 | import redis
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
authorization_policy = ACLAuthorizati... | onfig.include('pyramid_jinja2')
config.include('.models')
config.include('.routes')
config.registry.redis_conn = redis.StrictRedis.from_url(
settings['redis.url'])
| config.scan()
return config.make_wsgi_app()
|
ahmedaljazzar/edx-platform | openedx/core/djangoapps/credit/urls.py | Python | agpl-3.0 | 908 | 0.004405 | """
URLs for the credit app.
"""
from django.conf.urls import include, url
from openedx.core.djangoapps.credit import models, routers, views
PROVIDER_ID_PATTERN = r'(? | P<provider_id>{})'.format(models.CREDIT_PROVIDER_ID_REGEX)
PROVIDER_URLS = [
url(r'^request/$', views.CreditProviderRequestCreateView.as_view(), name='create_request'),
url(r'^callback/?$', views.CreditProviderCallbackView.as_view(), name='provider_callback'),
]
V1_URLS = [
url(r'^providers/{}/'.format(PR... | yView.as_view(), name='eligibility_details'),
]
router = routers.SimpleRouter() # pylint: disable=invalid-name
router.register(r'courses', views.CreditCourseViewSet)
router.register(r'providers', views.CreditProviderViewSet)
V1_URLS += router.urls
app_name = 'credit'
urlpatterns = [
url(r'^v1/', include(V1_URLS)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.