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 |
|---|---|---|---|---|---|---|---|---|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sure/six.py | Python | agpl-3.0 | 12,755 | 0.001803 | """Utilities for writing code that runs on Python 2 and 3"""
# Copyright (c) 2010-2013 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including with... | module, returning the | module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result)
# This is a bit ugly, but it avoids runni... |
SyntaxBlitz/syntaxblitz.github.io | portfolio/pdf-scripts/do-page-generate.py | Python | mit | 3,014 | 0.023557 | import subprocess
from music21 import *
from pyPdf import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from reportlab.lib import pagesizes
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# some important constants
MUSIC_XML_... | etrics.registerFont(TTFont("Cambria", PATH_TO_CAMBRIA))
pageNumberPdfCanvas.setFont("Cambria", 12)
if pageNum != -1: # tit | le page is -1, and we don't want a page number there.
if pageNum % 2 == 0: # even pages are on left, so put text on right
widthOfText = pageNumberPdfCanvas.stringWidth(hexPageNumber, "Cambria", 12)
pageNumberPdfCanvas.drawString(inch * 8.5 - inch * .5 - widthOfText, inch * 11 - inch * .5, hexPageNumber)
else:... |
soasme/axe | axe/default_exts.py | Python | mit | 680 | 0.011765 | # -*- coding: utf | -8 -*-
import json
from axe.http_exceptions import BadJSON
def get_request(request):
return request
def get_query(request):
return request.args
def get_form(request):
return reque | st.form
def get_body(request):
return request.data
def get_headers(request):
return request.headers
def get_cookies(request):
return request.cookies
def get_method(request):
return request.method
def get_json(headers, body):
content_type = headers.get('Content-Type')
if content_type != 'app... |
Bionetbook/bionetbook | bnbapp/protocols/forms/verbs/discard.py | Python | mit | 870 | 0.018391 | from protocols.forms import forms
from core.utils import TIME_UNITS
class Disca | rdForm(forms.VerbForm):
name = "Discard"
slug = "discard"
has_manual = True
layers = ['item_to_act','item_to_retain','conditional_statement','settif | y']
item_to_act = forms.CharField(required=False, label='item to discard')
item_to_retain = forms.CharField()
conditional_statement = forms.CharField(required = False, help_text ='if X happens, do Y')
min_time = forms.FloatField(required=False, help_text='this is the minimal time this should take', wid... |
BenceJanosSzabo/titan.core | etc/scripts/tpd_graph_xml2dot.py | Python | epl-1.0 | 978 | 0.005112 | ##############################################################################
# Copyright (c) 2000-2016 Ericsson Telecom AB
# All rights reserved. This program | and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distributio | n, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Balasko, Jeno
# Delic, Adam
#
##############################################################################
import xml.etree.ElementTree as ET
tree = ET.parse('project_hierarchy_graph.xml')
root = tree.getroot()
f = open('projec... |
openstack/mistral | mistral/scheduler/scheduler_server.py | Python | apache-2.0 | 2,019 | 0 | # Copyright 2018 - Nokia Networks.
#
# 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 agre... | lf._rpc_server = rpc.get_rpc_server_driver()(cfg.CONF.engine)
self._rpc_server.register_endpoint(self)
self._rpc_server.run()
self._notify_started('Scheduler server started.')
def stop(self, graceful=False):
super(SchedulerServer, self).stop()
if self._rpc_server:
... | op(graceful)
def schedule(self, rpc_ctx, job):
"""Receives requests over RPC to schedule delayed calls.
:param rpc_ctx: RPC request context.
:param job: Scheduler job.
"""
LOG.info("Received RPC request 'schedule'[job=%s]", job)
return self.scheduler.schedule(job, ... |
aptana/Pydev | tests/com.python.pydev.refactoring.tests/src/pysrcrefactoring/reflib/renameparameter/methoddef2.py | Python | epl-1.0 | 145 | 0.006897 | class Foo(object):
def mm(self, barparam):
| '''
@param barparam: this is barparam
'''
f | = Foo()
f.mm(barparam=10)
|
andychase/codebook | topics/migrations/0015_auto_20151218_1823.py | Python | mit | 1,259 | 0.002383 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.datetime_safe
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('topics'... | id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
('text', models.TextField()),
('slug', models.TextField(unique=True)),
('pub_date', models.DateTimeField(default=django.utils.datetime_safe.datetime.now, verbose_name='date pu... | o=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),
],
),
migrations.RemoveField(
model_name='tags',
name='user',
),
migrations.AlterField(
model_name='link',
name='tags',
field=models.ManyToManyField(to='topics.... |
fergalmoran/dss | dss/settings.py | Python | bsd-2-clause | 6,629 | 0.000905 | # e Django settings for dss project.
import os
import mimetypes
from django.core.urlresolvers import reverse_lazy
import djcelery
from django.conf import global_settings
from dss import logsettings
from utils import here
from localsettings import *
from pipelinesettings import *
from storagesettings impor... | 'avatar',
'spa',
'spa.signals',
'core',
'dirtyfields',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter | ',
'allauth.socialaccount.providers.google',
'debug_toolbar',
'django_jenkins',
'dbbackup',
'schedule',
'djrill',
'paypal.standard.ipn',
'django_user_agents',
'storages',
'rest_framework',
)
# where to redirect users to after logging in
LOGIN_REDIRECT_URL = reverse... |
fbennett/legal-resource-registry | attic/WALK-FILES.py | Python | bsd-2-clause | 1,115 | 0.011659 | #!/usr/bin/python
import os,sys,json,re
for dirpath,dirnames,filenames in os.walk("data/courts/us"):
indexPath = os.path.join(dirpath,"index.txt")
if not os.path.exists(indexPath):
print "Oops: %s" % indexPath
sys.exit()
fh = open(indexPath)
lines = []
template = None
firstCon... | nd(':court-id:') > -1: continue
line = line.rstrip()
if not firstContent:
if not line: continue
firstContent = True
if line.startswith('.. category:: '):
template = ' :category-id: %s'
elif line.startswith('.. court:: '):
template = ' :... | sys.exit()
id = ';'.join(dirpath.split("/")[2:])
lines = lines[0:1] + [template % id] + lines[1:]
txt = "\n".join(lines) + "\n"
print txt
#open(indexPath, "w+").write(txt)
|
mppmu/secdec | examples/elliptic2L_physical/generate_elliptic2L_physical.py | Python | gpl-3.0 | 1,518 | 0.049407 | #! /usr/bin/env python
from pySecDec.loop_integral import loop_package
import pySecDec as psd
li = psd.loop_integral.LoopIntegralFromPropagators(
propagators = ['k1**2-msq','(k1+p1+p2)**2-msq','k2**2-msq','(k2+p1+p2)**2-msq','(k1+p1)**2-msq','(k1-k2)**2','(k2-p3)**2-msq','(k2+p1)**2',' | (k1-p3)**2'],
powerlist = [1,1,0,1,1,1,1,0,0],
loop_momenta = ['k1','k2'],
replacement_rules = [
('p1*p1',0),
('p2*p2',0),
('p3*p3',0),
('p1*p2','s/2'),
('p2*p3','pp4/2-s/2-t/2'),
... | ,'t/2')
]
)
Mandelstam_symbols = ['s','t','pp4']
mass_symbols = ['msq']
loop_package(
name = 'elliptic2L_physical',
loop_integral = li,
real_parameters = Mandelstam_symbols + mass_symbols,
#additional_prefactor = '(s/msq)**(3/2)',
# the highest order of the final epsilon expansion --> chang... |
Navisite/flasgger | flasgger/simple_test.py | Python | mit | 916 | 0.001092 | """
# create a virtualenv
mkvirtualenv test_api
# install dependencies
pip install flask
pip install flasgger
# run the following script
python simple_test.py
"""
from flask impo | rt Flask, jsonify, request
from flasgger import Swagger
app = Flask(__name__)
Swagger(app)
@app.route("/recs", methods=['GET'])
def recs():
"""
A simple test API
This ednpoint does nothing
Only returs "test"
---
tags:
- testapi
parameters:
- name: size
in: query
... | schema:
id: return_test
properties:
result:
type: string
description: The test
default: 'test'
"""
size = int(request.args.get('size', 1))
return jsonify({"result": "test" * size})
app.run(debug=True)
|
mpi4py/mpi4py | demo/futures/run_julia.py | Python | bsd-2-clause | 1,252 | 0.00639 | import sys
import time
from mpi4py.futures import MPICommExecutor
x0 = -2.0
x1 = +2.0
y0 = | -1.5
y1 = +1.5
w = 1600
h = 1200
dx = (x1 - x0) / w
dy = (y1 - y0) / h
def julia(x, y):
c = complex(0, 0.65)
z = complex(x, y)
n = 255
while abs(z) < 3 and n > 1:
z = z**2 + c
n -= 1
return n
def julia_line(k):
line = bytearray(w)
y = y1 - k * dy
for j in range(w):
... | rom matplotlib import pyplot as plt
except ImportError:
return
plt.figure()
plt.imshow(image, aspect='equal', cmap='cubehelix')
plt.axis('off')
try:
plt.draw()
plt.pause(2)
except:
pass
def test_julia():
with MPICommExecutor() as executor:
if executor... |
praekelt/txtalert | txtalert/core/tests/test_clinic_admin.py | Python | gpl-3.0 | 5,959 | 0 | from uuid import uuid4
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User, Group
from django.test import RequestFactory
from txtalert.core.clinic_admin import VisitAdmin, PatientAdmin
from txtalert.core.models import Visit, Clinic, Patient
from txtalert.core.tests.base import... | ='clinic1')
self.clinic1_user.groups = [self.clinic1_group]
self.clinic1_user.save()
self.clinic1 = Clinic.objects.create(
name='Clinic 1', user=self.clinic1 | _user, te_id=uuid4().hex)
self.clinic2_group = Group.objects.create(name='clinic group 2')
self.clinic2_user = User.objects.create_user(
'clinic2', 'clinic2@clinic2.com', password='clinic2')
self.clinic2_user.groups = [self.clinic2_group]
self.clinic2_user.save()
se... |
ToiDenGaAli/odoo | setup.py | Python | gpl-3.0 | 5,678 | 0.001585 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
execfile(join(dirname(__file__), 'openerp', 'release.py')) # Load release variables
lib_name = 'openerp'
def py2exe_datafiles():
data_files = {}... | le__)
for root, _, filenames in os.walk(join(tzdir, 'zoneinfo')):
base = join('pytz', root[len(tzdir) + 1:])
data_files[base] = [join(root, f) for f in filenames]
import docutils
import passlib
import requests
data_mapping = ((docutils, 'docutils'),
(passlib, 'pa... | basedir = dirname(mod.__file__)
for root, _, filenames in os.walk(basedir):
base = join(datadir, root[len(basedir) + 1:])
data_files[base] = [join(root, f)
for f in filenames
if not f.endswith(('.py', '.pyc', '.pyo'))]
... |
hgqislub/hybird-orchard | code/cloudmanager/install/hws/hws_cloud_info_persist.py | Python | apache-2.0 | 3,963 | 0.005804 | from heat.engine.resources.cloudmanager.util.conf_util import *
class HwsCloudInfoPersist:
def __init__(self, _access_cloud_install_info_file, cloud_id):
self.info_handler = CloudInfoHandler(_access_cloud_install_info_file, cloud_id)
def write_vpc_info(self, vpc_id, vpc_name, vpc_cidr, security_group... | def write_vpn(self, server_id, public_ip, external_api_ip, tunnel_bearing_ip):
vpn_info = {"server_id": | server_id,
"public_ip": public_ip,
"external_api_ip": external_api_ip,
"tunnel_bearing_ip": tunnel_bearing_ip}
self.info_handler.write_unit_info("vpn", vpn_info)
def write_proxy(self, proxy_info):
self.info_handler.write_unit_info("proxy_info", proxy... |
zerovm/zerovm-cli | zpmlib/zpm.py | Python | apache-2.0 | 26,716 | 0 | # Copyright 2014 Rackspace, 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... | UT WARRANTIES OR | CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import fnmatch
import glob
import gzip
import json
import os
import shlex
import sys
import tarfile
try:
import urlparse
except ImportError:
import urllib.... |
SukkoPera/audiotrans | AudioTrans/Process.py | Python | gpl-3.0 | 2,826 | 0.023355 | #!/usr/bin/env python
###########################################################################
# Copyright (C) 2008-2016 by SukkoPera #
# software@sukkology.net #
# ... | re 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; witho... | E. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the ... |
MatthewGWilliams/Staff-Transport | emergencyTransport/RouteFinder/GoogleDistances.py | Python | mit | 1,984 | 0.043851 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib
import time
import datetime
#From PatMap by Jason Young, available | on GitHub at github.com/JasYoung314/PatMap
#Function to get distance between 2 points from google maps. By default route is by car, distance is given in miles and time in minutes.
def CalculateDistance(Origin = False,Destination = False, Method = "driving",TimeUnits = "Minutes",DistUnits = "Miles"):
#this is the sta... | de('utf-8') %(Origin)
urldestination = "destinations=%s&".encode('utf-8') %(Destination)
urlmethod = "mode=%s&" %(Method)
if DistUnits == "Kilometers" or DistUnits == "Meters":
urlunits = "units=metric&"
else:
urlunits = "units=imperial&"
#constructs the completed url
url = base.decode('utf-8') + urlorigin.de... |
succhiello/ansible-playbook-wrapper | ansible_playbook_wrapper/__init__.py | Python | mit | 556 | 0 | # -*- coding: utf-8 -*-
from argparse import ArgumentParser
from ansible_playbook_wrapper.command.play import PlayCommand
def main():
parser = ArgumentParser()
sub_parsers = parser.add_subparsers(help='commands')
play_parser = sub_parsers.add_parser('play', help='play playbook')
for arg_info in P... | Command)
p | arsed_args = parser.parse_args()
parsed_args.command_class(parsed_args).run()
|
srenner/photerva | mainsite/migrations/0006_auto_20150916_0219.py | Python | apache-2.0 | 2,722 | 0.001102 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('mainsite', '0005_auto_20150909_0246'),
... | to=settings.AUTH_USER_MODEL | ),
preserve_default=False,
),
migrations.AddField(
model_name='link',
name='owner',
field=models.ForeignKey(default=1, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
migrations.AddField(
model_name='phone',... |
greenlion/mysql-server | storage/ndb/mcc/request_handler.py | Python | gpl-2.0 | 23,716 | 0.009529 | # Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain s... | name': ch.hostInfo.uname,
'installdir': ch.installdir,
'datadir': ch.hostInfo.pm.join( | ch.homedir, 'MySQL_Cluster') }})
def start_proc(proc, body):
"""Start individual process as specified in startClusterReq command.
proc - the process object in the message
body - the whole message
"""
f = proc['file']
(user, pwd) = get_cred(body)
with produce_ABClusterHost(f['hostName'], ... |
lambdamusic/testproject | konproj/libs/PyRTF/examples/examples2.py | Python | gpl-2.0 | 1,338 | 0.076233 | import os
import sys
sys.path.append( '../' )
from PyRTF import *
def MakeExample1() :
doc = Document()
ss = doc.StyleSheet
section = Section()
doc.Sections.append( section )
# text can be added directly to the section
# a paragraph object is create as needed
section.append( 'Image Example 1' )
sec... | lose()
import image_tmp
section.append( Paragraph( image_tmp.TEST_IMAGE ) )
section.append( 'Have a look in image_tmp.py for the converted RawCode.' )
section.append( 'here are some png files' )
for f in [ 'img1.png',
'img2.png',
'img3.png',
'img4.png' ] :
section.append( Paragraph( Image( f ... | def OpenFile( name ) :
return file( '%s.rtf' % name, 'w' )
if __name__ == '__main__' :
DR = Renderer()
doc1 = MakeExample1()
DR.Write( doc1, OpenFile( 'Image1' ) )
print "Finished"
|
sjdv1982/seamless | seamless/graphs/multi_module/mytestpackage/mod4.py | Python | mit | 10 | 0 | bl | ah = 33
| |
epaglier/Project-JARVIS | mycroft-core/test/unittests/stt/test_stt.py | Python | gpl-3.0 | 5,110 | 0 | import mock
import unittest
import mycroft.stt
from mycroft.configuration import ConfigurationManager
class TestSTT(unittest.TestCase):
@mock.patch.object(ConfigurationManager, 'get')
def test_factory(self, mock_get):
mycroft.stt.STTApi = mock.MagicMock()
config = {'stt': {
'... | # Check that it works with two letters
config['lang'] = 'sv'
stt = TestSTT()
self.assertEqual(stt.lang, 'sv')
@mock.patch.object(ConfigurationManager, 'get')
def test_mycroft_stt(self, mock_get):
mycroft.stt.STT | Api = mock.MagicMock()
config = {'stt': {
'module': 'mycroft',
'mycroft': {'uri': 'https://test.com'}
},
'lang': 'en-US'
}
mock_get.return_value = config
stt = mycroft.stt.MycroftSTT()
audio = mock.MagicMock()
stt... |
shams-sam/logic-lab | DfsShortestPath/dfs_solution.py | Python | mit | 2,348 | 0.008518 | import sys
n, m = map(int, raw_input().strip().split())
v1, v2 = map(int, raw_input().strip().split())
x, y = map(int, raw_input().strip().split())
route_map = {}
distance_map = {}
def get_edge_name(x, y):
if x > y:
x, y = y, x
return str(x) + '_' + str(y)
def get_edge_distance(x,y):
edge_name = get... | d_nodes:
dist.append(get_min_cycle_time(elem, y, dist_acc + get_edge_distance(x, elem), visited_nodes))
else:
continue
return (min(dist) if len(dist) else sys.maxsize)
cycle = get_min_cycle_time(x,y)
bike = get_min_bike_time(x,y)
cycle_time = cycle/float(v1)
bike_ti... | /float(v2)
print '------------------'
print bike, cycle
print bike_time, cycle_time
|
hstau/manifold-cryo | S2tessellation.py | Python | gpl-2.0 | 1,976 | 0.039474 | import distribute3Sphere
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import logging, sys
from sklearn.neighbors import NearestNeighbors
#from scipy.spatial import Delaunay
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.DEBUG)
def get_S2(q):
try:
assert(q.shape[0] > 3)
excep... | n (IND,NC)
def op(q,shAngWidth,PDsizeTh,visual,*fig):
nG = np.floor(4*np.pi / (shAngWidth**2)).astype(int)
# reference angles
S20,it = distribute3Sphere.op(nG)
#pri | nt S20.shape
S20 = S20.T
#nS = q.shape[1]
# projection angles
S2 = get_S2(q)
IND, NC = classS2(S20.T, S2.T)
NIND = (NC > PDsizeTh).nonzero()[0]
#sys.exit()
S20_th = S20[:,NIND]
CG = []
for i in xrange(len(NIND)):
a = (IND == NIND[i]).nonzero()[0]
CG.append(a)
if visual:
... |
splotz90/urh | tests/HackRFTests.py | Python | gpl-3.0 | 4,709 | 0.004247 | import time
import unittest
import os
import tempfile
import numpy as np
from urh.util import util
util.set_windows_lib_path()
from urh.dev.native.lib import hackrf
from urh.dev.native.HackRF import HackRF
class TestHackRF(unittest.TestCase):
def callback_fun(self, buffer):
print(buffer)
for i... | t("init", hackrf.init())
print("open", hackrf.open())
print("start_tx", hackrf.start_tx_mode(callback))
time.sleep(1)
| print("stop_tx", hackrf.stop_tx_mode())
print("close", hackrf.close())
print("exit", hackrf.exit())
if __name__ == "__main__":
unittest.main()
|
yspanchal/bitbucketcli | bitbucket/wiki.py | Python | apache-2.0 | 4,056 | 0.000247 | # Copyright (c) 2013 Yogesh Panchal, yspanchal@gmail.com
# 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 ... | r' Invalid argument supp | lied.\n")
sys.exit(1)
class Wikipost(Command):
"""
* Post new wiki page for repositorys
"""
log = logging.getLogger(__name__ + '.Wikipost')
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)
def get_parser(self, prog_name):
parser = su... |
jefftc/changlab | genomicode/primer3.py | Python | mit | 5,865 | 0.004774 | """
Functions:
primer3
primer3_core
parse
"""
import sys
def primer3(sequence, **params):
# See primer3_core for more options.
# Return list of (left_primer, right_primer, product_size)
from StringIO import StringIO
handle = StringIO()
primer3_core(sequence, outhandle=handle, **params)
... | ss.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=Tru | e)
w, r = p.stdin, p.stdout
w.write("SEQUENCE_ID=test\n")
#w.write("SEQUENCE=%s\n" % sequence) # obsolete
w.write("SEQUENCE_TEMPLATE=%s\n" % sequence)
if target is not None:
assert len(target) == 2
base, length = target
assert base-1+length <= len(sequence)
w.write("... |
jordanemedlock/psychtruths | temboo/core/Library/Nexmo/Voice/__init__.py | Python | apache-2.0 | 565 | 0.00531 | from temboo.Library.Nexmo.Voice.CaptureTextToSpeechPrompt import CaptureTextToSpeechPrompt, CaptureTextToSpeechPromptInputSet, CaptureTextToSpeechPromptResultSet, CaptureTextToSpeechPromptChoreographyExecution
from temboo.Library.Nexmo.Voice.ConfirmTextToSpeechPrompt import ConfirmTextToSpeechPrompt, ConfirmTextToSpe | echPromptInputSet, ConfirmTextToSpeechPromptResultSet, ConfirmTextToSpeechPromptChoreographyExecution
from temboo.Library.Nexmo. | Voice.TextToSpeech import TextToSpeech, TextToSpeechInputSet, TextToSpeechResultSet, TextToSpeechChoreographyExecution
|
chipx86/reviewboard | reviewboard/reviews/search_indexes.py | Python | mit | 5,009 | 0 | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Index... | for user in review_request.target_people.all()
] or [0]
def prepare_author(self, review_request):
"""Prepare the author field.
Args:
review_request (reviewboard.reviews.models.review_request.
ReviewRequest):
The review request... | |
rtbn/TER_Project | poodle-PoC/poodle.py | Python | gpl-2.0 | 12,158 | 0.005511 | #!/usr/bin/env python
# - | *- coding: utf-8 -*-
'''
Poodle implementation with a client <--> proxy <--> server
'''
import argparse
import random
import re
import select
import socket
import SocketServer
import ssl
import string
import sys
import struct
import threading
import time
from utils.color import draw
from pprint import pprint
from... | ndle(self):
self.request = ssl.wrap_socket(self.request, keyfile="cert/localhost.pem", certfile="cert/localhost.pem", server_side=True, ssl_version=ssl.PROTOCOL_SSLv3)
#loop to avoid broken pipe
while True:
try:
data = self.request.recv(1024)
if data == '':
br... |
yeyanchao/calibre | src/calibre/gui2/wizard/library_ui.py | Python | gpl-3.0 | 3,115 | 0.002889 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/yc/code/calibre/calibre/src/calibre/gui2/wizard/library.ui'
#
# Created: Thu Oct 25 16:54:55 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
... | ocation"))
self.gridLayout.addWidget(self.location, 3, 0, 1, 2)
self.button_change = QtGui.QPushButton(WizardPage)
self.button_change.setText(_("&Change"))
self.button_change.setObjectName(_fromUtf8("button_change"))
self.gridLayout.addWidget(self.button_change, 3, 2, 1, 1)
... | bel2.setText(_("If you have an existing calibre library, it will be copied to the new location. If a calibre library already exists at the new location, calibre will switch to using it."))
self.libloc_label2.setWordWrap(True)
self.libloc_label2.setObjectName(_fromUtf8("libloc_label2"))
self.grid... |
tommy-u/enable | integrationtests/kiva/agg/test_arc.py | Python | bsd-3-clause | 3,344 | 0.006878 | import os
import unittest
from math import pi
import numpy
from kiva import agg
def save_path(filename):
return filename
def draw_arcs(gc, x2, y2, radiusstep=25.0):
gc.set_stroke_color((0.2,0.2,0.2)) # lightgray
gc.move_to(0, 0)
gc.line_to(100, 0)
gc.line_to(x2, y2)
gc.stroke_path()
gc... |
whole_shebang.rotate_ctm(-agg.pi/2)
| whole_shebang.add_path(arc)
whole_shebang.rotate_ctm(agg.pi/2)
whole_shebang.translate_ctm(50.5, -50.5)
whole_shebang.rotate_ctm(-agg.pi)
whole_shebang.add_path(arc)
whole_shebang.rotate_ctm(agg.pi)
whole_shebang.translate_ctm(-50.5, -50.5)
whole_shebang.rotate_... |
nravic/py-amber_alert | aalert/views.py | Python | mit | 2,721 | 0.005513 | from flask import request, flash, render_template, url_for, redirect, abort, Blueprint, g
from aalert import app, db
from flask_login import login_required, logout_user, login_user, current_user
from aalert.forms import *
from aalert.models import *
from sqlalchemy_searchable import search
from flask_admin import Admin... | (u'Logged in Successfully.', 'success')
return redirect(url_for('index'))
else:
flash(u'Incorrect username/password combination.', 'error')
return redirect(url_for('index'))
return render_template('login.html', form=form)
@app.route('/', methods=['GET'])
def index():
... | tries = db.session.query(Info.id, Info.firstname, Info.lastname, Info.age,
Info.height,Info.last_loc, Info.missing_since)
return render_template('disp.html', entries=entries)
@app.route('/search', methods=['GET', 'POST'])
def search():
if not g.search_form.validate_on_submit():
... |
plotly/python-api | packages/python/plotly/plotly/validators/contour/colorbar/_tickformatstops.py | Python | mit | 2,290 | 0.000873 | import _plotly_utils.basevalidators
class TickformatstopsValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(
self, plotly_name="tickformatstops", parent_name="contour.colorbar", **kwargs
):
super(TickformatstopsValidator, self).__init__(
plotly_name=plotly... | dtickrange
range [*min*, *max*], where "min", "max" -
dtick values which describe some zoom level, it
is possible to omit "min" or "max" value by
passing "null"
enabled
Determines whether or not this stop is used. If
... | created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications ... |
olavvatne/agac | abstractnode.py | Python | mit | 2,220 | 0.009459 | from abc import ABCMeta, abstractmethod
#Node object, important for traversing the search graph. Abstract class
#that contain abstract methods that has to be implemented by subclasses.
#These abstract methods, is what constitute the specialization of the A*
#for this problem domain.
class Node(object):
__metaclass... | states from itself.
@abstractmethod
def generate_successors(self):
pass
#A getter for the heuristic. The heuristic is the estimate of the nearness to
#the goal the specific node is. In case of a distance A to B problem,
#the H is the admissable (no overes | timates) distance from the goal from the nodes position.
@abstractmethod
def calc_H(self):
pass
#The actual distance from start to the node. The path cost.
def get_G(self):
return self.g
def set_G(self, cost):
self.g = cost
#Each node has to have to generate a id, to a... |
Krastanov/cutiepy | cutiepy/operators.py | Python | bsd-3-clause | 1,593 | 0.032116 | import numpy as np
from scipy.sparse import csr_matrix
from .symbolic import Operator
SPARSITY_N_CUTOFF = 600 # TODO lower after fixing sparse matrices
def sparsify(mat):
assert SPARSITY_N_CUTOFF > 5, 'The SPARSITY_N_CUTOFF is set to a very low number.'
if min(mat.shape) > SPARSITY_N_CUTOFF:
return cs... | )**0.5,k=1)))
def create(N): #TODO name prints ugly
return Operator('{a^\dagger}_{%d}'%N,
N,
sparsify(np.diag(np.arange(1,N,dtype=complex)**0.5,k=-1)))
def num(N):
return Operator('{n}_{%d}'%N,
N,
sparsify(np.diag(np.arange(0,N,dt... | ]) + 1j*np.random.random([N,N])
m = (m + np.conj(m.T))/2
return Operator.anon(N, sparsify(m))
s_m = np.array([[0, 0 ],[1 , 0]],dtype=complex)
s_p = np.array([[0, 1 ],[0 , 0]],dtype=complex)
s_x = np.array([[0, 1 ],[1 , 0]],dtype=complex)
s_y = np.array([[0,-1j],[1j, 0]],dtype=complex)
s_z = np.array([[1, 0 ],[... |
neolynx/aptly | system/t09_repo/edit.py | Python | mit | 2,278 | 0.000878 | import os
import inspect
from lib import BaseTest
def changesRemove(_, s):
return s.replace(os.path.join(os.path.dirname(inspect.getsourcefile(BaseTest)), "changes"), "")
class EditRepo1Test(BaseTest):
"""
edit repo: change comment
"""
fixtureCmds = [
"aptly repo create repo1",
]
... | broken uploaders.json
"""
fixtureCmds = [
"aptly repo create repo5",
]
runCmd = "aptly repo edit - | uploaders-file=${changes}/uploaders3.json repo5"
expectedCode = 1
class EditRepo6Test(BaseTest):
"""
edit local repo: with missing uploaders.json
"""
fixtureCmds = [
"aptly repo create repo6",
]
runCmd = "aptly repo edit -uploaders-file=${changes}/uploaders-not-found.json repo6"
... |
gmittal/aar-nlp-research-2016 | src/pygame-pygame-6625feb3fc7f/test/_vlcmovietest.py | Python | mit | 4,005 | 0.009488 | #################################### IMPORTS ###################################
from __future__ import generators
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests... | e.display.init()
pygame.mixer.quit()
movie_file = trunk_relative_path('examples/data/blue.mpg')
movie = gmovie.Movie(movie_file)
self.assertEqual(movie.playing, False)
movie.play(-1)
self.assertEqual(movie.playing, True)
self.assertEqual(movie.paused, Fal... | qual(movie.playing, False)
self.assertEqual(movie.paused, False)
del movie
def test_rewind(self):
pygame.display.init()
pygame.mixer.quit()
movie_file = trunk_relative_path('examples/data/blue.mpg')
movie = gmovie.Movie(movie_file)
m... |
lawzou/shoop | shoop/admin/modules/methods/views/edit.py | Python | agpl-3.0 | 4,422 | 0.002488 | # This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from copy import deepcopy
from django import forms
from dj... |
extra_css_class="btn-info",
disable_reason=disable_reason
))
class _BaseMethodEditView(CreateOrUpdateView):
model = None # Overridden below
action_url_name_prefix = None
template_name = "shoop/admin/methods/edit.jinja"
form_class = forms.Form
context_object_name =... | elf.model._meta.verbose_name}
def get_breadcrumb_parents(self):
return [
MenuEntry(
text=force_text(self.model._meta.verbose_name_plural).title(),
url="shoop_admin:%s.list" % self.action_url_name_prefix
)
]
def get_form(self, form_class=N... |
TiVo/wombat | correctness/kafka_to_mysql.py | Python | apache-2.0 | 5,895 | 0.008142 | #!/usr/bin/python
######################################################################
#
# File: kafka_to_mysql.py
#
# Copyright 2015 TiVo Inc. All Rights Reserved.
#
######################################################################
"""
Usage: kafka_to_mysql.py <kafka_topic> <kafka_broker> <mysql-ip> <mysql-port... | is None:
continue
if val == -62170156800000:
# this is hacky and a sign that i'm doing something wrong, I think.
val = "0000-00-00 00:00:00"
else:
val = val/1000
import datetime;
... | values = [ v for (k, v) in sorted(data.items()) ]
keys_wo_primary = [ k for (k, v) in sorted(data.items()) ]
for p in sorted_primary_key_names:
keys_wo_primary.remove(p)
# e.g.
# insert into dbname.tablename (col1, col2) values (%s, %s) on duplicate ke... |
psigcat/padrohabitants | plugin/ui/padrohabitants_dialog.py | Python | gpl-2.0 | 844 | 0.007109 | # -*- coding: utf-8 -*-
from PyQt4 import QtGui, uic
import os
#from qgis.utils import iface
FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'padrohabitants_dialog.ui'))
class PadroHabitantsDialog(QtGui.QDialog, FORM_CLASS):
def __init__(self, parent=N | one):
"""Constructor."""
super(PadroHabitantsDialog, self).__init__(parent)
# Set up the user interface from Designer.
# After setupUI you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4... | Button.setIcon(iface.actionPanToSelected().icon()) |
verolero86/ooh-py | base_machine.py | Python | mit | 7,770 | 0.007336 | #!/usr/bin/env python
#
# Author: Veronica G. Vergara L.
#
#
from .scheduler_factory import SchedulerFactory
from .jobLauncher_factory import JobLauncherFactory
from abc import abstractmethod, ABCMeta
import os
import shutil
class BaseMachine(metaclass=ABCMeta):
""" BaseMachine represents a compute resourc... | ir_head1, dir_tail1) = os.path.split(currentdir)
self.__rgt_results_dir = os.path.join(dir_head | 1,"Run_Archive",self.get_rgt_harness_id())
return
def get_rgt_results_dir(self):
""" Return the string corresponding to the path to the Run_Archive directory."""
return self.__rgt_results_dir
def get_rgt_scripts_dir(self):
return self.__rgt_scripts_dir
def get_rgt_workdir(... |
Kvoti/ditto | ditto/tickets/api/serializers.py | Python | bsd-3-clause | 900 | 0.004444 | from django.core.urlresolvers import reverse
from rest_framework import serializers
from casenotes.api import CaseNoteSerializer
from .. import models
class ViewTicketSerializer(serializers | .ModelSerializer):
case_note = CaseNoteSerializer()
claim_url = serializers.SerializerMethodField()
resolve_url = serializers.SerializerMethodField()
assigned_to = serializers.SlugRelatedField(slug_field='username', read_only=True)
def get_claim_url(self, obj):
| return reverse('ditto:ticket_claim', args=(obj.pk,))
def get_resolve_url(self, obj):
return reverse('ditto:ticket_resolve', args=(obj.pk,))
class Meta:
model = models.Ticket
fields = (
'id',
'claim_url',
'resolve_url',
'created_... |
beeftornado/sentry | tests/sentry/web/frontend/test_auth_saml2.py | Python | bsd-3-clause | 6,945 | 0.001728 | from __future__ import absolute_import
import six
import pytest
import base64
from sentry.utils.compat import mock
from exam import fixture
from six.moves.urllib.parse import urlencode, urlparse, parse_qs
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from ... | ping": {
Attributes.IDENTIFIER: "user_id",
Attributes.USER_EMAIL: "email",
Attributes.FIRST_NAME: "first_name",
Attributes.LAST_NAME: "last_name",
},
| }
class DummySAML2Provider(SAML2Provider):
def get_saml_setup_pipeline(self):
return []
def build_config(self, state):
return dummy_provider_config
@pytest.mark.skipif(not HAS_SAML2, reason="SAML2 library is not installed")
class AuthSAML2Test(AuthProviderTestCase):
provider = DummySAML... |
joergdietrich/reduced_shear_correction | reduced_shear_correction.py | Python | mit | 3,647 | 0.001097 | #!/usr/bin/env python
from __future__ import print_function, division
i | mport numpy as np
import astropy.cosmology
from astropy import units as u
from astropy import constants as const
def compute_sigma_crit(zl, zs, weights=None, cosmology=None):
"""Compute the critical su | rface mass density.
Parameters:
===========
zl: float, redshift of the lens
zs: array_like, redshift of the source
cosmology: astropy.cosmology.cosmology, optional, default None will load
astropy default
Returns:
========
sigma_crit: astropy.Quantity, critical surface mass densit... |
zhichao-li/BigDL | dl/src/main/python/util/common.py | Python | apache-2.0 | 7,567 | 0.000529 | #
# Licensed to Intel Corporation under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# Intel Corporation licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this fi... | ons import ListConverter, JavaArray, JavaList
from pyspark import RDD, SparkContext
from pyspark.serializers import PickleSerializer, AutoBatchedSerializer
from pyspark.sql import DataFrame, SQLContext |
from pyspark.mllib.common import callJavaFunc
from pyspark import SparkConf
if sys.version >= '3':
long = int
unicode = str
class JavaValue(object):
def jvm_class_constructor(self):
name = "create" + self.__class__.__name__
print("creating: " + name)
return name
def __init__... |
alexzoo/python | selenium_tests/test/test_del_group.py | Python | apache-2.0 | 156 | 0.00641 |
de | f test_delete_first_group(app):
app.session.login(username="admin", password="secret")
app.group.delete_first_group()
app.session.log | out()
|
obi-two/Rebelion | data/scripts/templates/object/static/structure/dantooine/shared_dant_small_mudhut.py | Python | mit | 457 | 0.04814 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### | MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
res | ult.template = "object/static/structure/dantooine/shared_dant_small_mudhut.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
ainich/politraf | _test.py | Python | mit | 375 | 0.005333 | import pytest
import socket as s
@pytest.fixture
def socket(request):
_socket = s.socket(s.AF_INET, s.SOCK | _STREAM)
def socket_teardown():
_socket.close()
request.addfinalizer(socket_teardown)
return _socket
def test_server_connect(socket):
socket.connect(('127.0.0.1',8123))
assert socket
if not socket:
| raise AssertionError()
|
cercisanat/cercisanat.com | cerci_admin/templatetags/issue_submit.py | Python | gpl-3.0 | 1,033 | 0.00484 | from django import template
register = template.Library()
@register.inclusion_tag('admin/cerci_issue/issue/submit_line.html', takes_context=True)
def submit_issue_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context['opts']
change = context['change']
is_popup =... | context['has_add_permission'] and
| not is_popup and (not save_as or context['add']),
'show_save_and_continue': not is_popup and context['has_change_permission'],
'is_popup': is_popup,
'show_save': True
}
if context.get('original') is not None:
ctx['original'] = context['original']
return ctx
|
a-kirin/Dockerfiles | sample01/web/sample01/memos/apps.py | Python | mit | 85 | 0 | from django.app | s import AppConfig
class MemosConfig(AppConfig):
| name = 'memos'
|
madmatah/lapurge | lapurge/purge.py | Python | mit | 3,000 | 0.000333 | # Copyright (c) 2013 Matthieu Huguet
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, dist... | l be included in | all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE L... |
stscieisenhamer/ginga | ginga/util/plots.py | Python | bsd-3-clause | 17,329 | 0.002193 | #
# plots.py -- Utility functions for plotting.
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy
import matplotlib as mpl
from matplotlib.figure import Figure
# fix issue of negative numbers rendering incorrectly with default font
mpl.rcParams[... | ## if self.cbar is not None:
## | self.cbar.remove()
self.ax.cla()
self.ax.set_axis_bgcolor('#303030')
try:
im = self.ax.imshow(data, interpolation=self.interpolation,
origin='lower', cmap=self.cmap)
# Create a contour plot
self.xdata = numpy.arange(x1, x2, ... |
smrmkt/sample_mecab_word2vec | corpus.py | Python | bsd-3-clause | 1,144 | 0.004401 | #!/usr/bin/env python
#-*- coding: utf-8 -*
import argparse
from lib.Parser import Parser
from lib.Vectorizer import Vectorizer
# 引数設定
parser = argparse.ArgumentParser()
parser.add_argument('menu')
parser.add_argument('in_path')
parser.add_argument('out_path', nargs='?')
def get_input():
pos = []
neg = []
... | nu == 'parse':
p = Parser('-Owakati')
p.parse_file(in_path, out_path)
elif menu == 'vectorize':
v = Vectorizer(min_count=10)
v.build_from_file(in_path)
v.store(out_path)
elif menu == 'calc':
v = Vectorizer()
v.load(in_path)
| while True:
pos, neg = get_input()
if pos[0] == 'END':
break;
else:
v.calc(pos, neg)
|
inspirehep/inspire-next | inspirehep/modules/records/serializers/schemas/json/authors/common/position.py | Python | gpl-3.0 | 1,690 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014-2018 CERN.
#
# INSPIRE 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 ... | t absolute_import, division, print_function
from marshmallow import Schema, fields, missing
class PositionSchemaV1(Schema):
current = fields.Raw()
institution = fields.Raw()
rank = fields.Raw()
display_date = fields.Method('get_display_date', default=missing)
def get_display_date(self, data):
... | art_date = data.get('start_date')
end_date = data.get('end_date')
suffixed_start_date = '{}-'.format(start_date) if start_date else ''
if current:
return '{}present'.format(suffixed_start_date)
if end_date:
return '{}{}'.format(suffixed_start_date, end_date)
... |
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2018_06_01/aio/_configuration.py | Python | mit | 2,950 | 0.004407 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | ,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kw... | .get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy... |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/docutils/parsers/rst/languages/gl.py | Python | gpl-2.0 | 3,711 | 0.001886 | # -* | - coding: utf-8 -*-
# Author: David Goodger
# Contact: goodger@users.sourceforge.net
# Revision: $Revision: 4229 $
# Date: $Date: 2005-12-23 00:46:16 +0100 (Fri, 23 Dec 2005) $
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# ... | n-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
u'atenci\u00f3n': 'attention',
u'advertencia': 'caution',
u'code (translation required)': 'code',
u'perigo': 'danger',
u'erro'... |
Beeblio/django | django/contrib/flatpages/views.py | Python | bsd-3-clause | 2,846 | 0.000703 | from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import get_current_site
from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.template import loader, RequestContext
fr... | rl
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage,
url__exact=url, sites__id__exact=site_id)
except Http404:
| if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage,
url__exact=url, sites__id__exact=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(reques... |
zstackorg/zstack-woodpecker | integrationtest/vm/simulator/dhcp_server_ip/test_dhcp_for_vpcrouter_cidr.py | Python | apache-2.0 | 2,037 | 0.018164 | '''
1.create private vpc router network with cidr
2.check dhcp ip address
@author Antony WeiJiang
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zs... | Version[0])
private_vpcnetwork.create_l3uuid(l3_name)
test_util.test_logger("anton | y @@@debug : %s" %(private_vpcnetwork.get_l3uuid()))
private_vpcnetwork.add_service_to_l3_vpcnetwork()
test_util.test_logger("add ip v4 range to l3 network")
private_vpcnetwork.add_ip_by_networkcidr(ip_range_name, networkcidr, dhcp_system_tags)
if private_vpcnetwork.check_dhcp_ipaddress().find(dhcp_ip_for_private_... |
robertpeteuil/multi-cloud-control | mcc/uimode.py | Python | gpl-3.0 | 12,295 | 0.000081 | """Process User Interface and execute commands.
License:
MCC - Command-Line Instance Control for AWS, Azure, GCP and AliCloud.
Copyright (C) 2017-2018 Robert Peteuil
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published... | valid:
val = input_by_key()
cmd_name, cmd_valid = key_lu.get(val.lower(), ["invalid", False])
if not cmd_valid:
ui_print(" - {0}Invalid Entry{1}".format(C_ERR, C_NORM))
sleep(0.5)
| ui_cmd_bar()
return cmd_name
def node_cmd(cmd_name, node_dict):
"""Process commands that target specific nodes."""
sc = {"run": cmd_startstop, "stop": cmd_startstop,
"connect": cmd_connect, "details": cmd_details}
node_num = node_selection(cmd_name, len(node_dict))
refresh_main = None
... |
mtlchun/edx | lms/djangoapps/django_comment_client/tests/test_utils.py | Python | agpl-3.0 | 33,221 | 0.001355 | # -*- coding: utf-8 -*-
from datetime import datetime
import json
from pytz import UTC
from django.core.urlresolvers import reverse
from django.test import TestCase
from edxmako import add_lookup
import mock
from django_comment_client.tests.factories import RoleFactory
from django_comment_client.tests.unicode import ... | d=self.course_id)
self.student1 = UserFactory(username='student', email='student@edx.org')
self.student1_enrollment = CourseEnrollmentF | actory(user=self.student1)
self.student_role.users.add(self.student1)
self.student2 = UserFactory(username='student2', email='student2@edx.org')
self.student2_enrollment = CourseEnrollmentFactory(user=self.student2)
self.moderator = UserFactory(username='moderator', email='staff@edx.org'... |
SwordGO/SwordGO_app | example/kivy-gmaps/main.py | Python | gpl-3.0 | 2,807 | 0.00285 | __version__ = '1.3'
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty
from gmaps import GMap, run_on_ui_thread
gmap_kv = '''
<Toolbar@BoxLayout>:
size_hint_y: None
height: '48dp'
padding: '4dp'
spacing: '4dp'
canvas:
Color:
rgb... | pos: self.pos
size: self.size
FloatLayout:
GMap:
id: map_widget
# top toolbar
Toolbar:
pos_hint: {'top': 1}
Button:
text: 'Move to Lille, France'
| on_release: app.move_to_lille()
Button:
text: 'Move to Sydney, Autralia'
on_release: app.move_to_sydney()
# bottom toolbar
Toolbar:
Label:
text: 'Longitude: {} - Latitude: {}'.format(app.longitude, app.latitude)
'''
class GMapTestApp(App):
latitude = N... |
pablohoffman/scrapy | scrapy/commands/version.py | Python | bsd-3-clause | 1,277 | 0.003132 | import sys
import platform
import twisted
import scrapy
from scrapy.command import ScrapyCommand
class Command(ScrapyCommand):
def syntax(self):
return "[-v]"
def short_desc(self):
return "Print Scrapy version"
def add_options(self, parser):
ScrapyCommand.add_options(self, pars... | atform info (useful for bug reports)")
def run(self, args, opts):
if opts.verbose:
try:
import lxml.etree
except ImportError:
lxml_version = libxml2_version = "(lxml not available)"
else:
lxml_version = ".".join(map(str, lx... | crapy : %s" % scrapy.__version__
print "lxml : %s" % lxml_version
print "libxml2 : %s" % libxml2_version
print "Twisted : %s" % twisted.version.short()
print "Python : %s" % sys.version.replace("\n", "- ")
print "Platform: %s" % platform.platform()
... |
pombredanne/pykram | src/main/py/pyelyts.py | Python | gpl-3.0 | 1,729 | 0.019665 | #!/usr/bin/env python
# pykram
#
# Created by nicerobot on 2012-02-03.
# Copyright (c) 2012 Nice Robot | Corporation. All rights reserved.
#
# This file is part of pykram.
#
# pykram is free software: you can redistribute i | t 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.
#
# pykram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warra... |
reyoung/Paddle | benchmark/fluid/models/se_resnext.py | Python | apache-2.0 | 10,123 | 0.000296 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | groups=1,
act=None):
conv = fluid.layers.conv2d(
input=input,
num_filter | s=num_filters,
filter_size=filter_size,
stride=stride,
padding=(filter_size - 1) / 2,
groups=groups,
act=None,
bias_attr=False)
return fluid.layers.batch_norm(
input=conv, act=act, is_test=not self.is_train)
def squeeze_exc... |
perfsonar/pscheduler | python-pscheduler/pscheduler/tests/limitprocessor_identifier_hint_test.py | Python | apache-2.0 | 1,127 | 0.002662 | #!/usr/bin/env python3
"""
Test for Hintidentifier
"""
import datetime
import un | ittest
from base_test import PschedTestBase
from pscheduler.limitprocessor.identifier.hint import *
DATA = {
"hint": "value",
"match": {
"style": "exact",
"match": "testing",
"case-insensitive": False
}
}
HINTS_HIT = { |
"value": "testing"
}
HINTS_MISS = {
"value": "not-testing"
}
class TestLimitprocessorIdentifierAlways(PschedTestBase):
"""
Test the Identifier
"""
def test_data_is_valid(self):
"""Limit Processor / Identifier Hint / Data Validation"""
self.assertEqual(data_is_valid(DATA), (... |
OpenSpaceProgram/pyOSP | library/components/Condition.py | Python | mit | 917 | 0.001091 | # -*- coding: utf-8 -*-
class Condition(object):
operator = ''
def __init__(self, operator):
super(Condition, self).__init__()
self.operator = operator
def equal(self, value1, value2):
return (str(value1) == str(value2))
def nequal(self, value1, value2):
return (str(... | or == 'nequal'):
return self.nequal(value1, value2)
elif(self.operator == 'gthan'):
return self.gthan(value1, value2)
elif(self.operator == 'lthan'):
return self.lthan(value1, value2)
retur | n False |
alex-petrenko/hierarchical-rl | microtbs_rl/utils/tests/test_utils.py | Python | mit | 1,981 | 0.000505 | """
Utils module tests.
"""
import shutil
from unittest import TestCase
from microtbs_rl import envs
from microtbs_rl.utils.exploration import LinearDecay
from microtbs_rl.utils.record_policy_execution import record
from microtbs_rl.utils.common_utils import get_test_logger, experiment_dir
from microtbs_rl.algori... | schedule.at(0.9), 0.05)
class RenderGifTests(TestCase):
def test_render_gif(self):
experiment_name = 'gif_test'
test_env = envs.COLLECT_WITH_TERRAIN_LATEST
a2c_params = a2c.AgentA2C.Params(experiment_name)
a2c_params.train_for_steps = 10
a2c_params.save_every = a2c_params.t... | _for_steps - 1
self.assertEqual(a2c.train_a2c.train(a2c_params, test_env), 0)
self.assertEqual(record(experiment_name, test_env, save_as_gif=True, num_episodes=1), 0)
shutil.rmtree(experiment_dir(experiment_name))
|
fesh0r/romdump | ichdesc.py | Python | mit | 3,000 | 0.001 | """
ICH flash descriptor
"""
import struct
from raw import RAW
from fd import FD
_SIG = '5AA5F00F'.decode('hex')
_SIG_OFFSET = 0x10
_SIG_SIZE = 0x4
_S_HEADER = struct.Struct('< 16s 4s BBBB BBBB BBBB')
_S_REGION = struct.Struct('< H H')
_REGIONS = [('ich', RAW), ('bios', FD), ('me', RAW), ('gbe', RAW), ('plat', RA... | self.frba = frba << 4
self.nr = nr + 1
self.fmba = fmba << 4
self.nm = nm + 1
self.fpsba = fpsba << 4
self.isl = isl
self.fmsba = fmsba << 4
self.psl = psl
self.blocks = []
self.regions = []
offset = self.frba
region_size = 0
... | base = base << 12
limit = (limit << 12) | 0xfff
region_size += limit - base + 1
cur_prefix = '%s%s_' % (prefix, name)
self.blocks.append(class_(data[base:limit + 1], start + base, cur_prefix))
else:
base = None
... |
bikalabs/bika.wine | bika/wine/permissions.py | Python | agpl-3.0 | 669 | 0 | """All permissions are defined here.
They are also defined in permissions.zcml.
The two files must be kept in sync.
"""
# Add Permissions:
A | ddCountry = 'BIKA: Add Country'
AddRegion = 'BIKA: Add Region'
AddCultivar = 'BIKA: Add Cultivar'
AddWineType = 'BIKA: Add Wine type'
AddTransportCondition = 'BIKA: Add Transport condition'
AddStorageCondition = 'BIKA: Add Storage condition'
# Add Permissions for specific types, if required
ADD_CONTENT_PERMISSIONS = {... | 'Country': AddCountry,
'Region': AddRegion,
'Cultivar': AddCultivar,
'WineType': AddWineType,
'TransportCondition': AddTransportCondition,
'StorageCondition': AddStorageCondition,
}
|
mephizzle/wagtail | wagtail/wagtailadmin/views/page_privacy.py | Python | bsd-3-clause | 3,072 | 0.001302 | from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from wagtail.wagtailcore.models import Page, PageViewRestriction
from wagtail.wagtailadmin.forms import PageViewRestrictionForm
from wagtail.wagtailadmin.modal_workflow import render_modal_workflow
def set_privacy(requ... | al={
'restriction_type': 'password', 'password': restriction.password
})
else:
# no current view restrictions on this page
form = PageViewRestrictionForm(initial={
| 'restriction_type': 'none'
})
if restriction_exists_on_ancestor:
# display a message indicating that there is a restriction at ancestor level -
# do not provide the form for setting up new restrictions
return render_modal_workflow(
request, 'wagtailadmin/page_... |
HPPTECH/hpp_IOSTressTest | Refer/IOST_OLD_SRC/IOST_0.10/IOST_WMain_CTRL.py | Python | mit | 2,475 | 0.006061 | #!/usr/bin/python
#======================================================================
#
# Project : hpp_IOStressTest
# File : IOST_WMain_CTRL.py
# Date : Oct 20, 2016
# Author : HuuHoang Nguyen
# Contact : hhnguyen@apm.com
# : hoangnh.hpp@gmail.com
# License : MIT License
# Copyright : 2016
#... | Cancel Button
# --------------------
def on_IOST_Wmain_Config_CTRL_Cancel_B_clicked(self, object, data=None):
"Control to Cancel button"
#----------------------------------------------- | -----------------------
def on_IOST_Wmain_Config_CTRL_Run_B_clicked(self, object, data=None):
"Control to Run button"
IOST_WRun.__init__(self, self.IOST_WMain_GladeFile,
self.ConfigObjs["IOST_WRun"]["WRun_Name"],
None)
self.ConfigObjs["... |
klen/muffin-rest | muffin_rest/peewee/__init__.py | Python | mit | 5,302 | 0.000943 | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
i | mport typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JSONType
from peewee_aio import Manager, Model
from muffin_rest.errors import APIError
from muffin_rest.ha... | STOptions
from muffin_rest.peewee.filters import PWFilters
from muffin_rest.peewee.openapi import PeeweeOpenAPIMixin
from muffin_rest.peewee.sorting import PWSorting
# XXX: Patch apispec.MarshmallowPlugin to support ForeignKeyField
MarshmallowPlugin.Converter.field_mapping[ForeignKey] = ("integer", None)
class PWRES... |
tgquintela/ChaosFunctions | ChaosFunctions/chaotic_series.py | Python | mit | 1,312 | 0 |
"""
Chaotic series
"""
from plotting import plot_iteration
from generic_iteration import generic_iteration
class Iterator:
"""Iterator object to compute iterative processes or magnitudes.
"""
def __init(self, iter_f, stop_f):
"""Instantiation of the iteration.
Parameters
-----... | nce):
"""Plot a 1d sequence.
Parameters
----------
sequence: np.ndarray
the sequence information.
Returns
-------
fig: matplotlib.pyplot.figure
the figure object wh | ich contains the plot.
"""
fig = plot_iteration(sequence)
return fig
|
NicoVarg99/daf-recipes | ckan/ckan/ckan/ckanext/stats/__init__.py | Python | gpl-3.0 | 75 | 0 | # encoding: utf-8
__imp | ort__('pkg_resources').declare_namespace(__nam | e__)
|
flavour/eden | modules/templates/historic/WACOP/menus.py | Python | mit | 8,445 | 0.003671 | # -*- coding: utf-8 -*-
from gluon import *
from s3 import *
from s | 3layouts import *
try:
from .layouts import *
except ImportError:
pass
import s3menus as default
# =============================================================================
class S3MainMenu(default.S3MainMenu):
"""
Custom Main Menu
"""
# ------------------------------------------------... | les(),
# Service menus, align-right
# Note: always define right-hand items in reverse order!
cls.menu_lang(right=True),
#cls.menu_gis(right=True),
cls.menu_auth(right=True),
cls.menu_admin(right=True),
cls.menu_help(right=True),
... |
kartvep/Combaine | plugins/datagrid/mysqldg.py | Python | lgpl-3.0 | 5,281 | 0.00303 | #!/usr/bin/env python
import os
import random
import types
import uuid
import msgpack
import MySQLdb
#from MySQLdb.cursors import DictCursor
#from MySQLdb.cursors import Cursor
from warnings import filterwarnings
from cocaine.worker import Worker
from cocaine.logging import Logger
#Suppressing warnings
filterwarnin... | ger.error('Unsupported field types. Look at preparePlace()')
return False
self.cursor.execute('DROP TABLE IF EXISTS %s' % tablename)
query = | "CREATE TABLE IF NOT EXISTS %(tablename)s %(struct)s ENGINE = MEMORY DATA DIRECTORY='/dev/shm/'" % {'tablename': tablename,
'struct': self.place}
self.cursor.execute(query)
... |
WZQ1397/automatic-repo | python/checkWeixinApi.py | Python | lgpl-3.0 | 1,022 | 0.002075 | #!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
from gevent import monkey
monkey.patch_all()
hosts = [
'https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info', # 公众平台接口通用域名
'https://qyapi.weixin.qq.com/cgi-bin/menu/get', # 企业号域名
'https://login.weixin.qq.com/', # 微信网页版
'https://wx2... | 04.106 Safari/537.36",
'cache-control': "no-cache",
}
response = requests.request("GET", url, headers=headers)
print len(response.text), "retrieved from %s " % url
gevent.sleep(0.5)
print response.headers, "from %s " % url
if __name__ == '__main__':
| import gevent
gevent.joinall([gevent.spawn(request_http, host) for host in hosts])
|
ryanolson/cookiecutter-webapp | {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/api/v1/__init__.py | Python | mit | 946 | 0.001058 | # -*- coding: utf-8 -*-
"""
{{ cookiecutter.app_name }}.api.v1
{{ "~" * (cookiecutter.app_name ~ ".api.v1")|count }}
:author: {{ cookiecutter.author }}
:copyright: © {{ cookiecutter.copyright }}
:license: {{ cookiecutter.li | cense }}, see LICENSE for more details.
templated from https://github.com/ryanolson/cookiecutter-webapp
"""
from .todos import TodosAPI, TodosResource, TodoResource
d | ef create_blueprint(name=None, url_prefix=None, subdomain=None):
"""Register API endpoints on a Flask :class:`Blueprint`."""
from flask import Blueprint
# Determine blueprint name
name = name or __name__.split('.')[-1]
url_prefix = url_prefix or "/{0}".format(name)
if subdomain:
name =... |
Andy-hpliu/AirtestX | atx/cmds/webide.py | Python | apache-2.0 | 7,985 | 0.002385 | # coding: utf-8
import os
import sys
import logging
import webbrowser
import socket
import time
import json
import traceback
import cv2
import tornad | o.ioloop
import tornado.web
import tornado.websocket
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor # `pip install futures` for python2
import atx
from atx import logutils
from atx import imutils
from atx import base
__dir__ = os.path.dirname(os.path.abspath(__file... | =logging.DEBUG)
log.setLevel(logging.DEBUG)
IMAGE_PATH = ['.', 'imgs', 'images']
workdir = '.'
device = None
atx_settings = {}
def read_file(filename, default=''):
if not os.path.isfile(filename):
return default
with open(filename, 'rb') as f:
return f.read()
def write_file(filename, conten... |
epicsdeb/cothread | examples/simple.py | Python | gpl-2.0 | 216 | 0 | #! | /bin/env dls-python2.6
'''Channel Access Example'''
from __future__ import print_function
# load correct version of catools
import require
from cothread.catools import *
print(caget('SR21C-DI-DCCT-01 | :SIGNAL'))
|
uclouvain/osis | education_group/tasks/__init__.py | Python | agpl-3.0 | 391 | 0.002558 | from . import check_academic_calendar
from celery.schedules import crontab
from backoffice.celery import app as celery_app
celery_app.conf.beat_schedule.update({
'|Education group| Check academic calendar': {
'ta | sk': 'education_group.tasks.check_academic_calendar.run',
'schedule': crontab(minute=0, hour=0, day_of_month='*', month_of_year='*', day_of_week=0)
| },
})
|
20n/act | reachables/src/main/python/DeepLearningLcmsPeak/netcdf/netcdf_parser.py | Python | gpl-3.0 | 2,813 | 0.000711 | """
" "
" This file is part of the 20n/act project. "
" 20n/act enables DNA predict | ion for synthetic biology/bioengineering. "
" Copyright (C) 2017 20n Labs, Inc. "
" | "
" Please direct all queries to act@20n.com. "
" "
" This program is free software: you can redistribute it and/or modify "
" it under the terms of the GNU General Public License a... |
yuzhichang/pdf_shuffer | pdf_shuffer.py | Python | gpl-3.0 | 34,766 | 0.006041 | #!/usr/bin/env python3
# encoding: utf-8
'''
Other good PDF utils available on Debian/Ubuntu Linux:
pdfshuffler a gui of PyPDF.
pdfgrep search pdf files for a regular expression. For example, "pdfgrep -n scare *.pdf" search a word among pdf files under current directory.
cups-pdf PDF printer for CUPS. It does what Sm... | _paper = '^a[1-6]paper$'
encoding = locale.getdefaultlocale()[1]
if(not encoding):
# None means the portable 'C' locale. However str.decode(encoding) doesn't accept None.
encoding = 'ASCII'
def getstatusoutput(cmdline, keepStdErr=True, raiseException=True):
logging.info(str(cmdline))
| if(keepStdErr):
err = subprocess.STDOUT
else:
err = None
stdout = subprocess.PIPE
pro |
wheelcms/wheelcms_axle | wheelcms_axle/tests/models.py | Python | bsd-2-clause | 2,181 | 0.006419 | from wheelcms_axle.content import Content, FileContent, ImageContent
from wheelcms_axle.spoke import Spoke, action, FileSpoke
from wheelcms_axle.content import type_registry
from django.db import models
class Type1(Content):
t1field = models.TextField(null=True, blank=True)
class Type1Type(Spoke):
model = T... | mage(ImageContent):
storage = models.ImageField(upload_to="images", blank=False)
class TestImageType(FileSpoke):
model = TestImage
children = ()
class OtherTestImage(ImageContent):
storage = models.ImageField(upload_to="images", blank=False)
class OtherTestImageType(FileSpoke):
model = OtherTes... | els.TextField(unique=True)
class TypeUniqueType(Spoke):
model = TypeUnique
type_registry.register(Type1Type)
type_registry.register(Type2Type)
type_registry.register(TestFileType)
type_registry.register(TestImageType)
type_registry.register(OtherTestFileType)
type_registry.register(OtherTestImageType)
type_regist... |
mhugo/QGIS | python/plugins/processing/algs/qgis/ExtractSpecificVertices.py | Python | gpl-2.0 | 6,483 | 0.002314 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExtractSpecificVertices.py
--------------------
Date : October 2016
Copyright : (C) 2016 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
******... | ut_geometry.distanceToVertex( | vertex_index)
angle = math.degrees(input_geometry.angleAtVertex(vertex_index))
output_feature = QgsFeature()
attrs = f.attributes()
attrs.append(vertex)
attrs.append(vertex_index)
attrs.append(vertex... |
JamesLinEngineer/RKMC | addons/plugin.video.phstreams/resources/lib/sources/phdmovies_mv_tv.py | Python | gpl-2.0 | 6,645 | 0.017306 | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your opti... | code('utf-8')
host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0]
if not host in hostDict: raise Exception()
| host = client.replaceHTMLCodes(host)
host = host.encode('utf-8')
sources.append({'source': host, 'quality': quality, 'provider': 'Phdmovies', 'url': url, 'info': info, 'direct': False, 'debridonly': True})
except:
pass
... |
beagles/neutron_hacking | neutron/tests/unit/ml2/test_rpcapi.py | Python | apache-2.0 | 5,110 | 0 | # Copyright (c) 2013 OpenStack Foundation
# 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 ... | ork='fake_physical_network')
def test_tunnel_update(self):
rpcapi = plugin_r | pc.AgentNotifierApi(topics.AGENT)
self._test_rpc_api(rpcapi,
topics.get_topic_name(topics.AGENT,
type_tunnel.TUNNEL,
topics.UPDATE),
'tunnel_update', rpc_method... |
aminotti/converter | lib/scrapper/__init__.py | Python | gpl-3.0 | 54 | 0 | from | .thetvdb import TheTVDB
from .tmdb import TheMD | B
|
DMOJ/site | judge/jinja2/timedelta.py | Python | agpl-3.0 | 584 | 0 | import datetime
from judge.utils.timedelta import nice_repr
from . | import registry
@registry.filter
def timedelta(value, display='long'):
if value is None:
return value
return nice_repr(value, display)
@registry.filter
def timestampdelta(value, display='long'):
value = datetime.timedelta(seconds=value)
return timedelta(value, display)
@registry.filter
def... | ')
def as_countdown(timedelta):
return {'countdown': timedelta}
|
donowsolutions/deanslist | setup.py | Python | mit | 1,127 | 0 | from setuptools import setup, find_packages
__name__ = 'deanslist'
__version__ = '0.6'
setup(
name=__name__,
version=__version__,
| url='https://github.com/donowsolutions/%s' % __name__,
author='Jonathan Elliott Blum',
author_email='jon@donowsolutions.com',
description='DeansList API w | rapper',
license='MIT',
packages=['deanslist'],
install_requires=[
'requests >=2.10.0, <3',
],
keywords=['deanslist', 'api', 'wrapper'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'... |
wcmitchell/insights-core | insights/parsers/fstab.py | Python | apache-2.0 | 6,335 | 0.00221 | """
fstab - file ``/etc/fstab``
===========================
Parse the ``/etc/fstab`` file into a list of lines. Each line is a dictionary
of fields, named according to their definitions in ``man fstab``:
* ``fs_spec`` - the device to mount
* ``fs_file`` - the mount point
* ``fs_vfstype`` - the type of file system
* ... | fs_file fs_vfstype raw_fs_mntops fs_freq fs_passno"
type_info = namedtuple('type_info', field_names=['type', 'default'])
@parser(fstab)
class FSTab(Parser):
"""
Parse the content of ``/etc/fstab` | `.
This object provides the '__len__' and '__iter__' methods to allow it to
be used as a list to iterate over the ``data`` data, e.g.::
>>> if len(fstab) > 0:
>>> for fs in fstab:
>>> print fs.fs_file
>>> print fs.raw
Attributes:
data (list): a ... |
catapult-project/catapult | devil/devil/base_error.py | Python | bsd-3-clause | 747 | 0.008032 | # Copyright 2015 The Chromium Authors. All rights r | eserved.
# Use of this source code is governed by a BS | D-style license that can be
# found in the LICENSE file.
class BaseError(Exception):
"""Base error for all test runner errors."""
def __init__(self, message, is_infra_error=False):
super(BaseError, self).__init__(message)
self._is_infra_error = is_infra_error
self.message = message
def __eq__(self... |
kartikgupta0909/gittest | configs/b2g_bumper/master.py | Python | mpl-2.0 | 3,963 | 0.003028 | #!/usr/bin/env python
config = {
"exes": {
# Get around the https warnings
"hg": ['/usr/local/bin/hg', "--config", "web.cacerts=/etc/pki/tls/certs/ca-bundle.crt"],
"hgtool.py": ["/usr/local/bin/hgtool.py"],
"gittool.py": ["/usr/local/bin/gittool.py"],
},
'gecko_pull_url': 'ht... | git.mozilla.org/external/sprd-aosp',
'git://github.com/apitrace/': 'https://git.mozilla.org/external/apitrace',
'git://github.com/t2m-foxfone/': 'https://git.mozilla.org/external/t2m-foxfone',
# Some mappings to ourself, we want to leave these as-is!
'https://git.mozilla.org/external/aos... | rg/b2g': 'https://git.mozilla.org/b2g',
'https://git.mozilla.org/external/apitrace': 'https://git.mozilla.org/external/apitrace',
'https://git.mozilla.org/external/t2m-foxfone': 'https://git.mozilla.org/external/t2m-foxfone',
},
}
|
mozilla/pymake | tests/datatests.py | Python | mit | 6,946 | 0.001152 | import pymake.data, pymake.functions, pymake.util
import unittest
import re
def multitest(cls):
for name in cls.testdata.keys():
def m(self, name=name):
return self.runSingle(*self.testdata[name])
setattr(cls, 'test_%s' % name, m)
return cls
class SplitWordsTest(unittest.TestCase... | :
s1 = pymake.data.StringExpansion('FOO', None)
self.assertTrue(s1.is_static_string)
funcs = list(s1.functions())
self.assertEqual(len(funcs), 0)
funcs = list(s1.functions(True))
self.assertEqual(len(funcs), 0)
refs = list(s1.variable_references())
sel... | _is_static_string(self):
e1 = pymake.data.Expansion()
e1.appendstr('foo')
self.assertTrue(e1.is_static_string)
e1.appendstr('bar')
self.assertTrue(e1.is_static_string)
vname = pymake.data.StringExpansion('FOO', None)
func = pymake.functions.VariableRef(None, vn... |
drunknbass/srs | trunk/research/code-statistic/cs.py | Python | mit | 3,920 | 0.006633 | #!/usr/bin/python
'''
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the r... | comments:
if "*/" in line:
verbose("[block][end] %s"%line)
is_block_comments = False
is_line_comments = False
else:
verbose("[block][cont] %s"%line)
stat_block_comment | s += 1
continue
if line.startswith("/*"):
verbose("[block][start] %s"%line)
is_block_comments = True
is_line_comments = False
stat_block_comments += 1
# inline block comments
if is_block_comments:
if "*/" in line... |
Flowdalic/bitcoin | test/functional/p2p_sendheaders.py | Python | mit | 26,404 | 0.002197 | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test behavior of headers messages to announce blocks.
Setup:
- Two nodes:
- node0 is the node-und... | elf.block_announced = False
self.last_message.pop("headers", None)
self.recent_headers_announced = []
def check_last | _inv_announcement(self, inv):
"""Test whether the last announcement received had the right inv.
inv should be a list of block hashes."""
test_function = lambda: self.block_announced
wait_until(test_function, timeout=60, lock=mininode_lock)
with mininode_lock:
compar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.